Linux kernel mirror (for testing)
git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel
os
linux
1/* Postprocess module symbol versions
2 *
3 * Copyright 2003 Kai Germaschewski
4 * Copyright 2002-2004 Rusty Russell, IBM Corporation
5 * Copyright 2006-2008 Sam Ravnborg
6 * Based in part on module-init-tools/depmod.c,file2alias
7 *
8 * This software may be used and distributed according to the terms
9 * of the GNU General Public License, incorporated herein by reference.
10 *
11 * Usage: modpost vmlinux module1.o module2.o ...
12 */
13
14#define _GNU_SOURCE
15#include <elf.h>
16#include <fnmatch.h>
17#include <stdio.h>
18#include <ctype.h>
19#include <string.h>
20#include <limits.h>
21#include <stdbool.h>
22#include <errno.h>
23
24#include <hash.h>
25#include <hashtable.h>
26#include <list.h>
27#include <xalloc.h>
28#include "modpost.h"
29#include "../../include/linux/license.h"
30
31#define MODULE_NS_PREFIX "module:"
32
33static bool module_enabled;
34/* Are we using CONFIG_MODVERSIONS? */
35static bool modversions;
36/* Is CONFIG_MODULE_SRCVERSION_ALL set? */
37static bool all_versions;
38/* Is CONFIG_BASIC_MODVERSIONS set? */
39static bool basic_modversions;
40/* Is CONFIG_EXTENDED_MODVERSIONS set? */
41static bool extended_modversions;
42/* If we are modposting external module set to 1 */
43static bool external_module;
44/* Only warn about unresolved symbols */
45static bool warn_unresolved;
46
47static int sec_mismatch_count;
48static bool sec_mismatch_warn_only = true;
49/* Trim EXPORT_SYMBOLs that are unused by in-tree modules */
50static bool trim_unused_exports;
51
52/* ignore missing files */
53static bool ignore_missing_files;
54/* If set to 1, only warn (instead of error) about missing ns imports */
55static bool allow_missing_ns_imports;
56
57static bool error_occurred;
58
59static bool extra_warn;
60
61bool target_is_big_endian;
62bool host_is_big_endian;
63
64/*
65 * Cut off the warnings when there are too many. This typically occurs when
66 * vmlinux is missing. ('make modules' without building vmlinux.)
67 */
68#define MAX_UNRESOLVED_REPORTS 10
69static unsigned int nr_unresolved;
70
71/* In kernel, this size is defined in linux/module.h;
72 * here we use Elf_Addr instead of long for covering cross-compile
73 */
74
75#define MODULE_NAME_LEN (64 - sizeof(Elf_Addr))
76
77void modpost_log(bool is_error, const char *fmt, ...)
78{
79 va_list arglist;
80
81 if (is_error) {
82 fprintf(stderr, "ERROR: ");
83 error_occurred = true;
84 } else {
85 fprintf(stderr, "WARNING: ");
86 }
87
88 fprintf(stderr, "modpost: ");
89
90 va_start(arglist, fmt);
91 vfprintf(stderr, fmt, arglist);
92 va_end(arglist);
93}
94
95static inline bool strends(const char *str, const char *postfix)
96{
97 if (strlen(str) < strlen(postfix))
98 return false;
99
100 return strcmp(str + strlen(str) - strlen(postfix), postfix) == 0;
101}
102
103/**
104 * get_basename - return the last part of a pathname.
105 *
106 * @path: path to extract the filename from.
107 */
108const char *get_basename(const char *path)
109{
110 const char *tail = strrchr(path, '/');
111
112 return tail ? tail + 1 : path;
113}
114
115char *read_text_file(const char *filename)
116{
117 struct stat st;
118 size_t nbytes;
119 int fd;
120 char *buf;
121
122 fd = open(filename, O_RDONLY);
123 if (fd < 0) {
124 perror(filename);
125 exit(1);
126 }
127
128 if (fstat(fd, &st) < 0) {
129 perror(filename);
130 exit(1);
131 }
132
133 buf = xmalloc(st.st_size + 1);
134
135 nbytes = st.st_size;
136
137 while (nbytes) {
138 ssize_t bytes_read;
139
140 bytes_read = read(fd, buf, nbytes);
141 if (bytes_read < 0) {
142 perror(filename);
143 exit(1);
144 }
145
146 nbytes -= bytes_read;
147 }
148 buf[st.st_size] = '\0';
149
150 close(fd);
151
152 return buf;
153}
154
155char *get_line(char **stringp)
156{
157 char *orig = *stringp, *next;
158
159 /* do not return the unwanted extra line at EOF */
160 if (!orig || *orig == '\0')
161 return NULL;
162
163 /* don't use strsep here, it is not available everywhere */
164 next = strchr(orig, '\n');
165 if (next)
166 *next++ = '\0';
167
168 *stringp = next;
169
170 return orig;
171}
172
173/* A list of all modules we processed */
174LIST_HEAD(modules);
175
176static struct module *find_module(const char *filename, const char *modname)
177{
178 struct module *mod;
179
180 list_for_each_entry(mod, &modules, list) {
181 if (!strcmp(mod->dump_file, filename) &&
182 !strcmp(mod->name, modname))
183 return mod;
184 }
185 return NULL;
186}
187
188static struct module *new_module(const char *name, size_t namelen)
189{
190 struct module *mod;
191
192 mod = xmalloc(sizeof(*mod) + namelen + 1);
193 memset(mod, 0, sizeof(*mod));
194
195 INIT_LIST_HEAD(&mod->exported_symbols);
196 INIT_LIST_HEAD(&mod->unresolved_symbols);
197 INIT_LIST_HEAD(&mod->missing_namespaces);
198 INIT_LIST_HEAD(&mod->imported_namespaces);
199 INIT_LIST_HEAD(&mod->aliases);
200
201 memcpy(mod->name, name, namelen);
202 mod->name[namelen] = '\0';
203 mod->is_vmlinux = (strcmp(mod->name, "vmlinux") == 0);
204
205 /*
206 * Set mod->is_gpl_compatible to true by default. If MODULE_LICENSE()
207 * is missing, do not check the use for EXPORT_SYMBOL_GPL() because
208 * modpost will exit with an error anyway.
209 */
210 mod->is_gpl_compatible = true;
211
212 list_add_tail(&mod->list, &modules);
213
214 return mod;
215}
216
217struct symbol {
218 struct hlist_node hnode;/* link to hash table */
219 struct list_head list; /* link to module::exported_symbols or module::unresolved_symbols */
220 struct module *module;
221 char *namespace;
222 unsigned int crc;
223 bool crc_valid;
224 bool weak;
225 bool is_func;
226 bool is_gpl_only; /* exported by EXPORT_SYMBOL_GPL */
227 bool used; /* there exists a user of this symbol */
228 char name[];
229};
230
231static HASHTABLE_DEFINE(symbol_hashtable, 1U << 10);
232
233/**
234 * Allocate a new symbols for use in the hash of exported symbols or
235 * the list of unresolved symbols per module
236 **/
237static struct symbol *alloc_symbol(const char *name)
238{
239 struct symbol *s = xmalloc(sizeof(*s) + strlen(name) + 1);
240
241 memset(s, 0, sizeof(*s));
242 strcpy(s->name, name);
243
244 return s;
245}
246
247/* For the hash of exported symbols */
248static void hash_add_symbol(struct symbol *sym)
249{
250 hash_add(symbol_hashtable, &sym->hnode, hash_str(sym->name));
251}
252
253static void sym_add_unresolved(const char *name, struct module *mod, bool weak)
254{
255 struct symbol *sym;
256
257 sym = alloc_symbol(name);
258 sym->weak = weak;
259
260 list_add_tail(&sym->list, &mod->unresolved_symbols);
261}
262
263static struct symbol *sym_find_with_module(const char *name, struct module *mod)
264{
265 struct symbol *s;
266
267 /* For our purposes, .foo matches foo. PPC64 needs this. */
268 if (name[0] == '.')
269 name++;
270
271 hash_for_each_possible(symbol_hashtable, s, hnode, hash_str(name)) {
272 if (strcmp(s->name, name) == 0 && (!mod || s->module == mod))
273 return s;
274 }
275 return NULL;
276}
277
278static struct symbol *find_symbol(const char *name)
279{
280 return sym_find_with_module(name, NULL);
281}
282
283struct namespace_list {
284 struct list_head list;
285 char namespace[];
286};
287
288static bool contains_namespace(struct list_head *head, const char *namespace)
289{
290 struct namespace_list *list;
291
292 /*
293 * The default namespace is null string "", which is always implicitly
294 * contained.
295 */
296 if (!namespace[0])
297 return true;
298
299 list_for_each_entry(list, head, list) {
300 if (!strcmp(list->namespace, namespace))
301 return true;
302 }
303
304 return false;
305}
306
307static void add_namespace(struct list_head *head, const char *namespace)
308{
309 struct namespace_list *ns_entry;
310
311 if (!contains_namespace(head, namespace)) {
312 ns_entry = xmalloc(sizeof(*ns_entry) + strlen(namespace) + 1);
313 strcpy(ns_entry->namespace, namespace);
314 list_add_tail(&ns_entry->list, head);
315 }
316}
317
318static void *sym_get_data_by_offset(const struct elf_info *info,
319 unsigned int secindex, unsigned long offset)
320{
321 Elf_Shdr *sechdr = &info->sechdrs[secindex];
322
323 return (void *)info->hdr + sechdr->sh_offset + offset;
324}
325
326void *sym_get_data(const struct elf_info *info, const Elf_Sym *sym)
327{
328 return sym_get_data_by_offset(info, get_secindex(info, sym),
329 sym->st_value);
330}
331
332static const char *sech_name(const struct elf_info *info, Elf_Shdr *sechdr)
333{
334 return sym_get_data_by_offset(info, info->secindex_strings,
335 sechdr->sh_name);
336}
337
338static const char *sec_name(const struct elf_info *info, unsigned int secindex)
339{
340 /*
341 * If sym->st_shndx is a special section index, there is no
342 * corresponding section header.
343 * Return "" if the index is out of range of info->sechdrs[] array.
344 */
345 if (secindex >= info->num_sections)
346 return "";
347
348 return sech_name(info, &info->sechdrs[secindex]);
349}
350
351static struct symbol *sym_add_exported(const char *name, struct module *mod,
352 bool gpl_only, const char *namespace)
353{
354 struct symbol *s = find_symbol(name);
355
356 if (s && (!external_module || s->module->is_vmlinux || s->module == mod)) {
357 error("%s: '%s' exported twice. Previous export was in %s%s\n",
358 mod->name, name, s->module->name,
359 s->module->is_vmlinux ? "" : ".ko");
360 }
361
362 s = alloc_symbol(name);
363 s->module = mod;
364 s->is_gpl_only = gpl_only;
365 s->namespace = xstrdup(namespace);
366 list_add_tail(&s->list, &mod->exported_symbols);
367 hash_add_symbol(s);
368
369 return s;
370}
371
372static void sym_set_crc(struct symbol *sym, unsigned int crc)
373{
374 sym->crc = crc;
375 sym->crc_valid = true;
376}
377
378static void *grab_file(const char *filename, size_t *size)
379{
380 struct stat st;
381 void *map = MAP_FAILED;
382 int fd;
383
384 fd = open(filename, O_RDONLY);
385 if (fd < 0)
386 return NULL;
387 if (fstat(fd, &st))
388 goto failed;
389
390 *size = st.st_size;
391 map = mmap(NULL, *size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
392
393failed:
394 close(fd);
395 if (map == MAP_FAILED)
396 return NULL;
397 return map;
398}
399
400static void release_file(void *file, size_t size)
401{
402 munmap(file, size);
403}
404
405static int parse_elf(struct elf_info *info, const char *filename)
406{
407 unsigned int i;
408 Elf_Ehdr *hdr;
409 Elf_Shdr *sechdrs;
410 Elf_Sym *sym;
411 const char *secstrings;
412 unsigned int symtab_idx = ~0U, symtab_shndx_idx = ~0U;
413
414 hdr = grab_file(filename, &info->size);
415 if (!hdr) {
416 if (ignore_missing_files) {
417 fprintf(stderr, "%s: %s (ignored)\n", filename,
418 strerror(errno));
419 return 0;
420 }
421 perror(filename);
422 exit(1);
423 }
424 info->hdr = hdr;
425 if (info->size < sizeof(*hdr)) {
426 /* file too small, assume this is an empty .o file */
427 return 0;
428 }
429 /* Is this a valid ELF file? */
430 if ((hdr->e_ident[EI_MAG0] != ELFMAG0) ||
431 (hdr->e_ident[EI_MAG1] != ELFMAG1) ||
432 (hdr->e_ident[EI_MAG2] != ELFMAG2) ||
433 (hdr->e_ident[EI_MAG3] != ELFMAG3)) {
434 /* Not an ELF file - silently ignore it */
435 return 0;
436 }
437
438 switch (hdr->e_ident[EI_DATA]) {
439 case ELFDATA2LSB:
440 target_is_big_endian = false;
441 break;
442 case ELFDATA2MSB:
443 target_is_big_endian = true;
444 break;
445 default:
446 fatal("target endian is unknown\n");
447 }
448
449 /* Fix endianness in ELF header */
450 hdr->e_type = TO_NATIVE(hdr->e_type);
451 hdr->e_machine = TO_NATIVE(hdr->e_machine);
452 hdr->e_version = TO_NATIVE(hdr->e_version);
453 hdr->e_entry = TO_NATIVE(hdr->e_entry);
454 hdr->e_phoff = TO_NATIVE(hdr->e_phoff);
455 hdr->e_shoff = TO_NATIVE(hdr->e_shoff);
456 hdr->e_flags = TO_NATIVE(hdr->e_flags);
457 hdr->e_ehsize = TO_NATIVE(hdr->e_ehsize);
458 hdr->e_phentsize = TO_NATIVE(hdr->e_phentsize);
459 hdr->e_phnum = TO_NATIVE(hdr->e_phnum);
460 hdr->e_shentsize = TO_NATIVE(hdr->e_shentsize);
461 hdr->e_shnum = TO_NATIVE(hdr->e_shnum);
462 hdr->e_shstrndx = TO_NATIVE(hdr->e_shstrndx);
463 sechdrs = (void *)hdr + hdr->e_shoff;
464 info->sechdrs = sechdrs;
465
466 /* modpost only works for relocatable objects */
467 if (hdr->e_type != ET_REL)
468 fatal("%s: not relocatable object.", filename);
469
470 /* Check if file offset is correct */
471 if (hdr->e_shoff > info->size)
472 fatal("section header offset=%lu in file '%s' is bigger than filesize=%zu\n",
473 (unsigned long)hdr->e_shoff, filename, info->size);
474
475 if (hdr->e_shnum == SHN_UNDEF) {
476 /*
477 * There are more than 64k sections,
478 * read count from .sh_size.
479 */
480 info->num_sections = TO_NATIVE(sechdrs[0].sh_size);
481 }
482 else {
483 info->num_sections = hdr->e_shnum;
484 }
485 if (hdr->e_shstrndx == SHN_XINDEX) {
486 info->secindex_strings = TO_NATIVE(sechdrs[0].sh_link);
487 }
488 else {
489 info->secindex_strings = hdr->e_shstrndx;
490 }
491
492 /* Fix endianness in section headers */
493 for (i = 0; i < info->num_sections; i++) {
494 sechdrs[i].sh_name = TO_NATIVE(sechdrs[i].sh_name);
495 sechdrs[i].sh_type = TO_NATIVE(sechdrs[i].sh_type);
496 sechdrs[i].sh_flags = TO_NATIVE(sechdrs[i].sh_flags);
497 sechdrs[i].sh_addr = TO_NATIVE(sechdrs[i].sh_addr);
498 sechdrs[i].sh_offset = TO_NATIVE(sechdrs[i].sh_offset);
499 sechdrs[i].sh_size = TO_NATIVE(sechdrs[i].sh_size);
500 sechdrs[i].sh_link = TO_NATIVE(sechdrs[i].sh_link);
501 sechdrs[i].sh_info = TO_NATIVE(sechdrs[i].sh_info);
502 sechdrs[i].sh_addralign = TO_NATIVE(sechdrs[i].sh_addralign);
503 sechdrs[i].sh_entsize = TO_NATIVE(sechdrs[i].sh_entsize);
504 }
505 /* Find symbol table. */
506 secstrings = (void *)hdr + sechdrs[info->secindex_strings].sh_offset;
507 for (i = 1; i < info->num_sections; i++) {
508 const char *secname;
509 int nobits = sechdrs[i].sh_type == SHT_NOBITS;
510
511 if (!nobits && sechdrs[i].sh_offset > info->size)
512 fatal("%s is truncated. sechdrs[i].sh_offset=%lu > sizeof(*hrd)=%zu\n",
513 filename, (unsigned long)sechdrs[i].sh_offset,
514 sizeof(*hdr));
515
516 secname = secstrings + sechdrs[i].sh_name;
517 if (strcmp(secname, ".modinfo") == 0) {
518 if (nobits)
519 fatal("%s has NOBITS .modinfo\n", filename);
520 info->modinfo = (void *)hdr + sechdrs[i].sh_offset;
521 info->modinfo_len = sechdrs[i].sh_size;
522 } else if (!strcmp(secname, ".export_symbol")) {
523 info->export_symbol_secndx = i;
524 } else if (!strcmp(secname, ".no_trim_symbol")) {
525 info->no_trim_symbol = (void *)hdr + sechdrs[i].sh_offset;
526 info->no_trim_symbol_len = sechdrs[i].sh_size;
527 }
528
529 if (sechdrs[i].sh_type == SHT_SYMTAB) {
530 unsigned int sh_link_idx;
531 symtab_idx = i;
532 info->symtab_start = (void *)hdr +
533 sechdrs[i].sh_offset;
534 info->symtab_stop = (void *)hdr +
535 sechdrs[i].sh_offset + sechdrs[i].sh_size;
536 sh_link_idx = sechdrs[i].sh_link;
537 info->strtab = (void *)hdr +
538 sechdrs[sh_link_idx].sh_offset;
539 }
540
541 /* 32bit section no. table? ("more than 64k sections") */
542 if (sechdrs[i].sh_type == SHT_SYMTAB_SHNDX) {
543 symtab_shndx_idx = i;
544 info->symtab_shndx_start = (void *)hdr +
545 sechdrs[i].sh_offset;
546 info->symtab_shndx_stop = (void *)hdr +
547 sechdrs[i].sh_offset + sechdrs[i].sh_size;
548 }
549 }
550 if (!info->symtab_start)
551 fatal("%s has no symtab?\n", filename);
552
553 /* Fix endianness in symbols */
554 for (sym = info->symtab_start; sym < info->symtab_stop; sym++) {
555 sym->st_shndx = TO_NATIVE(sym->st_shndx);
556 sym->st_name = TO_NATIVE(sym->st_name);
557 sym->st_value = TO_NATIVE(sym->st_value);
558 sym->st_size = TO_NATIVE(sym->st_size);
559 }
560
561 if (symtab_shndx_idx != ~0U) {
562 Elf32_Word *p;
563 if (symtab_idx != sechdrs[symtab_shndx_idx].sh_link)
564 fatal("%s: SYMTAB_SHNDX has bad sh_link: %u!=%u\n",
565 filename, sechdrs[symtab_shndx_idx].sh_link,
566 symtab_idx);
567 /* Fix endianness */
568 for (p = info->symtab_shndx_start; p < info->symtab_shndx_stop;
569 p++)
570 *p = TO_NATIVE(*p);
571 }
572
573 symsearch_init(info);
574
575 return 1;
576}
577
578static void parse_elf_finish(struct elf_info *info)
579{
580 symsearch_finish(info);
581 release_file(info->hdr, info->size);
582}
583
584static int ignore_undef_symbol(struct elf_info *info, const char *symname)
585{
586 /* ignore __this_module, it will be resolved shortly */
587 if (strcmp(symname, "__this_module") == 0)
588 return 1;
589 /* ignore global offset table */
590 if (strcmp(symname, "_GLOBAL_OFFSET_TABLE_") == 0)
591 return 1;
592 if (info->hdr->e_machine == EM_PPC)
593 /* Special register function linked on all modules during final link of .ko */
594 if (strstarts(symname, "_restgpr_") ||
595 strstarts(symname, "_savegpr_") ||
596 strstarts(symname, "_rest32gpr_") ||
597 strstarts(symname, "_save32gpr_") ||
598 strstarts(symname, "_restvr_") ||
599 strstarts(symname, "_savevr_"))
600 return 1;
601 if (info->hdr->e_machine == EM_PPC64)
602 /* Special register function linked on all modules during final link of .ko */
603 if (strstarts(symname, "_restgpr0_") ||
604 strstarts(symname, "_savegpr0_") ||
605 strstarts(symname, "_restvr_") ||
606 strstarts(symname, "_savevr_") ||
607 strcmp(symname, ".TOC.") == 0)
608 return 1;
609
610 /* ignore linker-created section bounds variables */
611 if (strstarts(symname, "__start_") || strstarts(symname, "__stop_"))
612 return 1;
613
614 /* Do not ignore this symbol */
615 return 0;
616}
617
618static void handle_symbol(struct module *mod, struct elf_info *info,
619 const Elf_Sym *sym, const char *symname)
620{
621 switch (sym->st_shndx) {
622 case SHN_COMMON:
623 if (strstarts(symname, "__gnu_lto_")) {
624 /* Should warn here, but modpost runs before the linker */
625 } else
626 warn("\"%s\" [%s] is COMMON symbol\n", symname, mod->name);
627 break;
628 case SHN_UNDEF:
629 /* undefined symbol */
630 if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL &&
631 ELF_ST_BIND(sym->st_info) != STB_WEAK)
632 break;
633 if (ignore_undef_symbol(info, symname))
634 break;
635 if (info->hdr->e_machine == EM_SPARC ||
636 info->hdr->e_machine == EM_SPARCV9) {
637 /* Ignore register directives. */
638 if (ELF_ST_TYPE(sym->st_info) == STT_SPARC_REGISTER)
639 break;
640 if (symname[0] == '.') {
641 char *munged = xstrdup(symname);
642 munged[0] = '_';
643 munged[1] = toupper(munged[1]);
644 symname = munged;
645 }
646 }
647
648 sym_add_unresolved(symname, mod,
649 ELF_ST_BIND(sym->st_info) == STB_WEAK);
650 break;
651 default:
652 if (strcmp(symname, "init_module") == 0)
653 mod->has_init = true;
654 if (strcmp(symname, "cleanup_module") == 0)
655 mod->has_cleanup = true;
656 break;
657 }
658}
659
660/**
661 * Parse tag=value strings from .modinfo section
662 **/
663static char *next_string(char *string, unsigned long *secsize)
664{
665 /* Skip non-zero chars */
666 while (string[0]) {
667 string++;
668 if ((*secsize)-- <= 1)
669 return NULL;
670 }
671
672 /* Skip any zero padding. */
673 while (!string[0]) {
674 string++;
675 if ((*secsize)-- <= 1)
676 return NULL;
677 }
678 return string;
679}
680
681static char *get_next_modinfo(struct elf_info *info, const char *tag,
682 char *prev)
683{
684 char *p;
685 unsigned int taglen = strlen(tag);
686 char *modinfo = info->modinfo;
687 unsigned long size = info->modinfo_len;
688
689 if (prev) {
690 size -= prev - modinfo;
691 modinfo = next_string(prev, &size);
692 }
693
694 for (p = modinfo; p; p = next_string(p, &size)) {
695 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
696 return p + taglen + 1;
697 }
698 return NULL;
699}
700
701static char *get_modinfo(struct elf_info *info, const char *tag)
702
703{
704 return get_next_modinfo(info, tag, NULL);
705}
706
707static const char *sym_name(struct elf_info *elf, Elf_Sym *sym)
708{
709 return sym ? elf->strtab + sym->st_name : "";
710}
711
712/*
713 * Check whether the 'string' argument matches one of the 'patterns',
714 * an array of shell wildcard patterns (glob).
715 *
716 * Return true is there is a match.
717 */
718static bool match(const char *string, const char *const patterns[])
719{
720 const char *pattern;
721
722 while ((pattern = *patterns++)) {
723 if (!fnmatch(pattern, string, 0))
724 return true;
725 }
726
727 return false;
728}
729
730/* useful to pass patterns to match() directly */
731#define PATTERNS(...) \
732 ({ \
733 static const char *const patterns[] = {__VA_ARGS__, NULL}; \
734 patterns; \
735 })
736
737/* sections that we do not want to do full section mismatch check on */
738static const char *const section_white_list[] =
739{
740 ".comment*",
741 ".debug*",
742 ".zdebug*", /* Compressed debug sections. */
743 ".GCC.command.line", /* record-gcc-switches */
744 ".mdebug*", /* alpha, score, mips etc. */
745 ".pdr", /* alpha, score, mips etc. */
746 ".stab*",
747 ".note*",
748 ".got*",
749 ".toc*",
750 ".xt.prop", /* xtensa */
751 ".xt.lit", /* xtensa */
752 ".arcextmap*", /* arc */
753 ".gnu.linkonce.arcext*", /* arc : modules */
754 ".cmem*", /* EZchip */
755 ".fmt_slot*", /* EZchip */
756 ".gnu.lto*",
757 ".discard.*",
758 ".llvm.call-graph-profile", /* call graph */
759 NULL
760};
761
762/*
763 * This is used to find sections missing the SHF_ALLOC flag.
764 * The cause of this is often a section specified in assembler
765 * without "ax" / "aw".
766 */
767static void check_section(const char *modname, struct elf_info *elf,
768 Elf_Shdr *sechdr)
769{
770 const char *sec = sech_name(elf, sechdr);
771
772 if (sechdr->sh_type == SHT_PROGBITS &&
773 !(sechdr->sh_flags & SHF_ALLOC) &&
774 !match(sec, section_white_list)) {
775 warn("%s (%s): unexpected non-allocatable section.\n"
776 "Did you forget to use \"ax\"/\"aw\" in a .S file?\n"
777 "Note that for example <linux/init.h> contains\n"
778 "section definitions for use in .S files.\n\n",
779 modname, sec);
780 }
781}
782
783
784
785#define ALL_INIT_DATA_SECTIONS \
786 ".init.setup", ".init.rodata", ".init.data"
787
788#define ALL_PCI_INIT_SECTIONS \
789 ".pci_fixup_early", ".pci_fixup_header", ".pci_fixup_final", \
790 ".pci_fixup_enable", ".pci_fixup_resume", \
791 ".pci_fixup_resume_early", ".pci_fixup_suspend"
792
793#define ALL_INIT_SECTIONS ".init.*"
794#define ALL_EXIT_SECTIONS ".exit.*"
795
796#define DATA_SECTIONS ".data", ".data.rel"
797#define TEXT_SECTIONS ".text", ".text.*", ".sched.text", \
798 ".kprobes.text", ".cpuidle.text", ".noinstr.text", \
799 ".ltext", ".ltext.*"
800#define OTHER_TEXT_SECTIONS ".ref.text", ".head.text", ".spinlock.text", \
801 ".fixup", ".entry.text", ".exception.text", \
802 ".coldtext", ".softirqentry.text", ".irqentry.text"
803
804#define ALL_TEXT_SECTIONS ".init.text", ".exit.text", \
805 TEXT_SECTIONS, OTHER_TEXT_SECTIONS
806
807enum mismatch {
808 TEXTDATA_TO_ANY_INIT_EXIT,
809 XXXINIT_TO_SOME_INIT,
810 ANY_INIT_TO_ANY_EXIT,
811 ANY_EXIT_TO_ANY_INIT,
812 EXTABLE_TO_NON_TEXT,
813};
814
815/**
816 * Describe how to match sections on different criteria:
817 *
818 * @fromsec: Array of sections to be matched.
819 *
820 * @bad_tosec: Relocations applied to a section in @fromsec to a section in
821 * this array is forbidden (black-list). Can be empty.
822 *
823 * @good_tosec: Relocations applied to a section in @fromsec must be
824 * targeting sections in this array (white-list). Can be empty.
825 *
826 * @mismatch: Type of mismatch.
827 */
828struct sectioncheck {
829 const char *fromsec[20];
830 const char *bad_tosec[20];
831 const char *good_tosec[20];
832 enum mismatch mismatch;
833};
834
835static const struct sectioncheck sectioncheck[] = {
836/* Do not reference init/exit code/data from
837 * normal code and data
838 */
839{
840 .fromsec = { TEXT_SECTIONS, DATA_SECTIONS, NULL },
841 .bad_tosec = { ALL_INIT_SECTIONS, ALL_EXIT_SECTIONS, NULL },
842 .mismatch = TEXTDATA_TO_ANY_INIT_EXIT,
843},
844/* Do not use exit code/data from init code */
845{
846 .fromsec = { ALL_INIT_SECTIONS, NULL },
847 .bad_tosec = { ALL_EXIT_SECTIONS, NULL },
848 .mismatch = ANY_INIT_TO_ANY_EXIT,
849},
850/* Do not use init code/data from exit code */
851{
852 .fromsec = { ALL_EXIT_SECTIONS, NULL },
853 .bad_tosec = { ALL_INIT_SECTIONS, NULL },
854 .mismatch = ANY_EXIT_TO_ANY_INIT,
855},
856{
857 .fromsec = { ALL_PCI_INIT_SECTIONS, NULL },
858 .bad_tosec = { ALL_INIT_SECTIONS, NULL },
859 .mismatch = ANY_INIT_TO_ANY_EXIT,
860},
861{
862 .fromsec = { "__ex_table", NULL },
863 /* If you're adding any new black-listed sections in here, consider
864 * adding a special 'printer' for them in scripts/check_extable.
865 */
866 .bad_tosec = { ".altinstr_replacement", NULL },
867 .good_tosec = {ALL_TEXT_SECTIONS , NULL},
868 .mismatch = EXTABLE_TO_NON_TEXT,
869}
870};
871
872static const struct sectioncheck *section_mismatch(
873 const char *fromsec, const char *tosec)
874{
875 int i;
876
877 /*
878 * The target section could be the SHT_NUL section when we're
879 * handling relocations to un-resolved symbols, trying to match it
880 * doesn't make much sense and causes build failures on parisc
881 * architectures.
882 */
883 if (*tosec == '\0')
884 return NULL;
885
886 for (i = 0; i < ARRAY_SIZE(sectioncheck); i++) {
887 const struct sectioncheck *check = §ioncheck[i];
888
889 if (match(fromsec, check->fromsec)) {
890 if (check->bad_tosec[0] && match(tosec, check->bad_tosec))
891 return check;
892 if (check->good_tosec[0] && !match(tosec, check->good_tosec))
893 return check;
894 }
895 }
896 return NULL;
897}
898
899/**
900 * Whitelist to allow certain references to pass with no warning.
901 *
902 * Pattern 1:
903 * If a module parameter is declared __initdata and permissions=0
904 * then this is legal despite the warning generated.
905 * We cannot see value of permissions here, so just ignore
906 * this pattern.
907 * The pattern is identified by:
908 * tosec = .init.data
909 * fromsec = .data*
910 * atsym =__param*
911 *
912 * Pattern 1a:
913 * module_param_call() ops can refer to __init set function if permissions=0
914 * The pattern is identified by:
915 * tosec = .init.text
916 * fromsec = .data*
917 * atsym = __param_ops_*
918 *
919 * Pattern 3:
920 * Whitelist all references from .head.text to any init section
921 *
922 * Pattern 4:
923 * Some symbols belong to init section but still it is ok to reference
924 * these from non-init sections as these symbols don't have any memory
925 * allocated for them and symbol address and value are same. So even
926 * if init section is freed, its ok to reference those symbols.
927 * For ex. symbols marking the init section boundaries.
928 * This pattern is identified by
929 * refsymname = __init_begin, _sinittext, _einittext
930 *
931 * Pattern 5:
932 * GCC may optimize static inlines when fed constant arg(s) resulting
933 * in functions like cpumask_empty() -- generating an associated symbol
934 * cpumask_empty.constprop.3 that appears in the audit. If the const that
935 * is passed in comes from __init, like say nmi_ipi_mask, we get a
936 * meaningless section warning. May need to add isra symbols too...
937 * This pattern is identified by
938 * tosec = init section
939 * fromsec = text section
940 * refsymname = *.constprop.*
941 *
942 **/
943static int secref_whitelist(const char *fromsec, const char *fromsym,
944 const char *tosec, const char *tosym)
945{
946 /* Check for pattern 1 */
947 if (match(tosec, PATTERNS(ALL_INIT_DATA_SECTIONS)) &&
948 match(fromsec, PATTERNS(DATA_SECTIONS)) &&
949 strstarts(fromsym, "__param"))
950 return 0;
951
952 /* Check for pattern 1a */
953 if (strcmp(tosec, ".init.text") == 0 &&
954 match(fromsec, PATTERNS(DATA_SECTIONS)) &&
955 strstarts(fromsym, "__param_ops_"))
956 return 0;
957
958 /* symbols in data sections that may refer to any init/exit sections */
959 if (match(fromsec, PATTERNS(DATA_SECTIONS)) &&
960 match(tosec, PATTERNS(ALL_INIT_SECTIONS, ALL_EXIT_SECTIONS)) &&
961 match(fromsym, PATTERNS("*_ops", "*_probe", "*_console")))
962 return 0;
963
964 /* Check for pattern 3 */
965 if (strstarts(fromsec, ".head.text") &&
966 match(tosec, PATTERNS(ALL_INIT_SECTIONS)))
967 return 0;
968
969 /* Check for pattern 4 */
970 if (match(tosym, PATTERNS("__init_begin", "_sinittext", "_einittext")))
971 return 0;
972
973 /* Check for pattern 5 */
974 if (match(fromsec, PATTERNS(ALL_TEXT_SECTIONS)) &&
975 match(tosec, PATTERNS(ALL_INIT_SECTIONS)) &&
976 match(fromsym, PATTERNS("*.constprop.*")))
977 return 0;
978
979 return 1;
980}
981
982static Elf_Sym *find_fromsym(struct elf_info *elf, Elf_Addr addr,
983 unsigned int secndx)
984{
985 return symsearch_find_nearest(elf, addr, secndx, false, ~0);
986}
987
988static Elf_Sym *find_tosym(struct elf_info *elf, Elf_Addr addr, Elf_Sym *sym)
989{
990 Elf_Sym *new_sym;
991
992 /* If the supplied symbol has a valid name, return it */
993 if (is_valid_name(elf, sym))
994 return sym;
995
996 /*
997 * Strive to find a better symbol name, but the resulting name may not
998 * match the symbol referenced in the original code.
999 */
1000 new_sym = symsearch_find_nearest(elf, addr, get_secindex(elf, sym),
1001 true, 20);
1002 return new_sym ? new_sym : sym;
1003}
1004
1005static bool is_executable_section(struct elf_info *elf, unsigned int secndx)
1006{
1007 if (secndx >= elf->num_sections)
1008 return false;
1009
1010 return (elf->sechdrs[secndx].sh_flags & SHF_EXECINSTR) != 0;
1011}
1012
1013static void default_mismatch_handler(const char *modname, struct elf_info *elf,
1014 const struct sectioncheck* const mismatch,
1015 Elf_Sym *tsym,
1016 unsigned int fsecndx, const char *fromsec, Elf_Addr faddr,
1017 const char *tosec, Elf_Addr taddr)
1018{
1019 Elf_Sym *from;
1020 const char *tosym;
1021 const char *fromsym;
1022 char taddr_str[16];
1023
1024 from = find_fromsym(elf, faddr, fsecndx);
1025 fromsym = sym_name(elf, from);
1026
1027 tsym = find_tosym(elf, taddr, tsym);
1028 tosym = sym_name(elf, tsym);
1029
1030 /* check whitelist - we may ignore it */
1031 if (!secref_whitelist(fromsec, fromsym, tosec, tosym))
1032 return;
1033
1034 sec_mismatch_count++;
1035
1036 if (!tosym[0])
1037 snprintf(taddr_str, sizeof(taddr_str), "0x%x", (unsigned int)taddr);
1038
1039 /*
1040 * The format for the reference source: <symbol_name>+<offset> or <address>
1041 * The format for the reference destination: <symbol_name> or <address>
1042 */
1043 warn("%s: section mismatch in reference: %s%s0x%x (section: %s) -> %s (section: %s)\n",
1044 modname, fromsym, fromsym[0] ? "+" : "",
1045 (unsigned int)(faddr - (fromsym[0] ? from->st_value : 0)),
1046 fromsec, tosym[0] ? tosym : taddr_str, tosec);
1047
1048 if (mismatch->mismatch == EXTABLE_TO_NON_TEXT) {
1049 if (match(tosec, mismatch->bad_tosec))
1050 fatal("The relocation at %s+0x%lx references\n"
1051 "section \"%s\" which is black-listed.\n"
1052 "Something is seriously wrong and should be fixed.\n"
1053 "You might get more information about where this is\n"
1054 "coming from by using scripts/check_extable.sh %s\n",
1055 fromsec, (long)faddr, tosec, modname);
1056 else if (is_executable_section(elf, get_secindex(elf, tsym)))
1057 warn("The relocation at %s+0x%lx references\n"
1058 "section \"%s\" which is not in the list of\n"
1059 "authorized sections. If you're adding a new section\n"
1060 "and/or if this reference is valid, add \"%s\" to the\n"
1061 "list of authorized sections to jump to on fault.\n"
1062 "This can be achieved by adding \"%s\" to\n"
1063 "OTHER_TEXT_SECTIONS in scripts/mod/modpost.c.\n",
1064 fromsec, (long)faddr, tosec, tosec, tosec);
1065 else
1066 error("%s+0x%lx references non-executable section '%s'\n",
1067 fromsec, (long)faddr, tosec);
1068 }
1069}
1070
1071static void check_export_symbol(struct module *mod, struct elf_info *elf,
1072 Elf_Addr faddr, const char *secname,
1073 Elf_Sym *sym)
1074{
1075 static const char *prefix = "__export_symbol_";
1076 const char *label_name, *name, *data;
1077 Elf_Sym *label;
1078 struct symbol *s;
1079 bool is_gpl;
1080
1081 label = find_fromsym(elf, faddr, elf->export_symbol_secndx);
1082 label_name = sym_name(elf, label);
1083
1084 if (!strstarts(label_name, prefix)) {
1085 error("%s: .export_symbol section contains strange symbol '%s'\n",
1086 mod->name, label_name);
1087 return;
1088 }
1089
1090 if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL &&
1091 ELF_ST_BIND(sym->st_info) != STB_WEAK) {
1092 error("%s: local symbol '%s' was exported\n", mod->name,
1093 label_name + strlen(prefix));
1094 return;
1095 }
1096
1097 name = sym_name(elf, sym);
1098 if (strcmp(label_name + strlen(prefix), name)) {
1099 error("%s: .export_symbol section references '%s', but it does not seem to be an export symbol\n",
1100 mod->name, name);
1101 return;
1102 }
1103
1104 data = sym_get_data(elf, label); /* license */
1105 if (!strcmp(data, "GPL")) {
1106 is_gpl = true;
1107 } else if (!strcmp(data, "")) {
1108 is_gpl = false;
1109 } else {
1110 error("%s: unknown license '%s' was specified for '%s'\n",
1111 mod->name, data, name);
1112 return;
1113 }
1114
1115 data += strlen(data) + 1; /* namespace */
1116 s = sym_add_exported(name, mod, is_gpl, data);
1117
1118 /*
1119 * We need to be aware whether we are exporting a function or
1120 * a data on some architectures.
1121 */
1122 s->is_func = (ELF_ST_TYPE(sym->st_info) == STT_FUNC);
1123
1124 /*
1125 * For parisc64, symbols prefixed $$ from the library have the symbol type
1126 * STT_LOPROC. They should be handled as functions too.
1127 */
1128 if (elf->hdr->e_ident[EI_CLASS] == ELFCLASS64 &&
1129 elf->hdr->e_machine == EM_PARISC &&
1130 ELF_ST_TYPE(sym->st_info) == STT_LOPROC)
1131 s->is_func = true;
1132
1133 if (match(secname, PATTERNS(ALL_INIT_SECTIONS)))
1134 warn("%s: %s: EXPORT_SYMBOL used for init symbol. Remove __init or EXPORT_SYMBOL.\n",
1135 mod->name, name);
1136 else if (match(secname, PATTERNS(ALL_EXIT_SECTIONS)))
1137 warn("%s: %s: EXPORT_SYMBOL used for exit symbol. Remove __exit or EXPORT_SYMBOL.\n",
1138 mod->name, name);
1139}
1140
1141static void check_section_mismatch(struct module *mod, struct elf_info *elf,
1142 Elf_Sym *sym,
1143 unsigned int fsecndx, const char *fromsec,
1144 Elf_Addr faddr, Elf_Addr taddr)
1145{
1146 const char *tosec = sec_name(elf, get_secindex(elf, sym));
1147 const struct sectioncheck *mismatch;
1148
1149 if (module_enabled && elf->export_symbol_secndx == fsecndx) {
1150 check_export_symbol(mod, elf, faddr, tosec, sym);
1151 return;
1152 }
1153
1154 mismatch = section_mismatch(fromsec, tosec);
1155 if (!mismatch)
1156 return;
1157
1158 default_mismatch_handler(mod->name, elf, mismatch, sym,
1159 fsecndx, fromsec, faddr,
1160 tosec, taddr);
1161}
1162
1163static Elf_Addr addend_386_rel(uint32_t *location, unsigned int r_type)
1164{
1165 switch (r_type) {
1166 case R_386_32:
1167 return get_unaligned_native(location);
1168 case R_386_PC32:
1169 return get_unaligned_native(location) + 4;
1170 }
1171
1172 return (Elf_Addr)(-1);
1173}
1174
1175static int32_t sign_extend32(int32_t value, int index)
1176{
1177 uint8_t shift = 31 - index;
1178
1179 return (int32_t)(value << shift) >> shift;
1180}
1181
1182static Elf_Addr addend_arm_rel(void *loc, Elf_Sym *sym, unsigned int r_type)
1183{
1184 uint32_t inst, upper, lower, sign, j1, j2;
1185 int32_t offset;
1186
1187 switch (r_type) {
1188 case R_ARM_ABS32:
1189 case R_ARM_REL32:
1190 inst = get_unaligned_native((uint32_t *)loc);
1191 return inst + sym->st_value;
1192 case R_ARM_MOVW_ABS_NC:
1193 case R_ARM_MOVT_ABS:
1194 inst = get_unaligned_native((uint32_t *)loc);
1195 offset = sign_extend32(((inst & 0xf0000) >> 4) | (inst & 0xfff),
1196 15);
1197 return offset + sym->st_value;
1198 case R_ARM_PC24:
1199 case R_ARM_CALL:
1200 case R_ARM_JUMP24:
1201 inst = get_unaligned_native((uint32_t *)loc);
1202 offset = sign_extend32((inst & 0x00ffffff) << 2, 25);
1203 return offset + sym->st_value + 8;
1204 case R_ARM_THM_MOVW_ABS_NC:
1205 case R_ARM_THM_MOVT_ABS:
1206 upper = get_unaligned_native((uint16_t *)loc);
1207 lower = get_unaligned_native((uint16_t *)loc + 1);
1208 offset = sign_extend32(((upper & 0x000f) << 12) |
1209 ((upper & 0x0400) << 1) |
1210 ((lower & 0x7000) >> 4) |
1211 (lower & 0x00ff),
1212 15);
1213 return offset + sym->st_value;
1214 case R_ARM_THM_JUMP19:
1215 /*
1216 * Encoding T3:
1217 * S = upper[10]
1218 * imm6 = upper[5:0]
1219 * J1 = lower[13]
1220 * J2 = lower[11]
1221 * imm11 = lower[10:0]
1222 * imm32 = SignExtend(S:J2:J1:imm6:imm11:'0')
1223 */
1224 upper = get_unaligned_native((uint16_t *)loc);
1225 lower = get_unaligned_native((uint16_t *)loc + 1);
1226
1227 sign = (upper >> 10) & 1;
1228 j1 = (lower >> 13) & 1;
1229 j2 = (lower >> 11) & 1;
1230 offset = sign_extend32((sign << 20) | (j2 << 19) | (j1 << 18) |
1231 ((upper & 0x03f) << 12) |
1232 ((lower & 0x07ff) << 1),
1233 20);
1234 return offset + sym->st_value + 4;
1235 case R_ARM_THM_PC22:
1236 case R_ARM_THM_JUMP24:
1237 /*
1238 * Encoding T4:
1239 * S = upper[10]
1240 * imm10 = upper[9:0]
1241 * J1 = lower[13]
1242 * J2 = lower[11]
1243 * imm11 = lower[10:0]
1244 * I1 = NOT(J1 XOR S)
1245 * I2 = NOT(J2 XOR S)
1246 * imm32 = SignExtend(S:I1:I2:imm10:imm11:'0')
1247 */
1248 upper = get_unaligned_native((uint16_t *)loc);
1249 lower = get_unaligned_native((uint16_t *)loc + 1);
1250
1251 sign = (upper >> 10) & 1;
1252 j1 = (lower >> 13) & 1;
1253 j2 = (lower >> 11) & 1;
1254 offset = sign_extend32((sign << 24) |
1255 ((~(j1 ^ sign) & 1) << 23) |
1256 ((~(j2 ^ sign) & 1) << 22) |
1257 ((upper & 0x03ff) << 12) |
1258 ((lower & 0x07ff) << 1),
1259 24);
1260 return offset + sym->st_value + 4;
1261 }
1262
1263 return (Elf_Addr)(-1);
1264}
1265
1266static Elf_Addr addend_mips_rel(uint32_t *location, unsigned int r_type)
1267{
1268 uint32_t inst;
1269
1270 inst = get_unaligned_native(location);
1271 switch (r_type) {
1272 case R_MIPS_LO16:
1273 return inst & 0xffff;
1274 case R_MIPS_26:
1275 return (inst & 0x03ffffff) << 2;
1276 case R_MIPS_32:
1277 return inst;
1278 }
1279 return (Elf_Addr)(-1);
1280}
1281
1282#ifndef EM_RISCV
1283#define EM_RISCV 243
1284#endif
1285
1286#ifndef R_RISCV_SUB32
1287#define R_RISCV_SUB32 39
1288#endif
1289
1290#ifndef EM_LOONGARCH
1291#define EM_LOONGARCH 258
1292#endif
1293
1294#ifndef R_LARCH_SUB32
1295#define R_LARCH_SUB32 55
1296#endif
1297
1298#ifndef R_LARCH_RELAX
1299#define R_LARCH_RELAX 100
1300#endif
1301
1302#ifndef R_LARCH_ALIGN
1303#define R_LARCH_ALIGN 102
1304#endif
1305
1306static void get_rel_type_and_sym(struct elf_info *elf, uint64_t r_info,
1307 unsigned int *r_type, unsigned int *r_sym)
1308{
1309 typedef struct {
1310 Elf64_Word r_sym; /* Symbol index */
1311 unsigned char r_ssym; /* Special symbol for 2nd relocation */
1312 unsigned char r_type3; /* 3rd relocation type */
1313 unsigned char r_type2; /* 2nd relocation type */
1314 unsigned char r_type; /* 1st relocation type */
1315 } Elf64_Mips_R_Info;
1316
1317 bool is_64bit = (elf->hdr->e_ident[EI_CLASS] == ELFCLASS64);
1318
1319 if (elf->hdr->e_machine == EM_MIPS && is_64bit) {
1320 Elf64_Mips_R_Info *mips64_r_info = (void *)&r_info;
1321
1322 *r_type = mips64_r_info->r_type;
1323 *r_sym = TO_NATIVE(mips64_r_info->r_sym);
1324 return;
1325 }
1326
1327 if (is_64bit)
1328 r_info = TO_NATIVE((Elf64_Xword)r_info);
1329 else
1330 r_info = TO_NATIVE((Elf32_Word)r_info);
1331
1332 *r_type = ELF_R_TYPE(r_info);
1333 *r_sym = ELF_R_SYM(r_info);
1334}
1335
1336static void section_rela(struct module *mod, struct elf_info *elf,
1337 unsigned int fsecndx, const char *fromsec,
1338 const Elf_Rela *start, const Elf_Rela *stop)
1339{
1340 const Elf_Rela *rela;
1341
1342 for (rela = start; rela < stop; rela++) {
1343 Elf_Sym *tsym;
1344 Elf_Addr taddr, r_offset;
1345 unsigned int r_type, r_sym;
1346
1347 r_offset = TO_NATIVE(rela->r_offset);
1348 get_rel_type_and_sym(elf, rela->r_info, &r_type, &r_sym);
1349
1350 tsym = elf->symtab_start + r_sym;
1351 taddr = tsym->st_value + TO_NATIVE(rela->r_addend);
1352
1353 switch (elf->hdr->e_machine) {
1354 case EM_RISCV:
1355 if (!strcmp("__ex_table", fromsec) &&
1356 r_type == R_RISCV_SUB32)
1357 continue;
1358 break;
1359 case EM_LOONGARCH:
1360 switch (r_type) {
1361 case R_LARCH_SUB32:
1362 if (!strcmp("__ex_table", fromsec))
1363 continue;
1364 break;
1365 case R_LARCH_RELAX:
1366 case R_LARCH_ALIGN:
1367 /* These relocs do not refer to symbols */
1368 continue;
1369 }
1370 break;
1371 }
1372
1373 check_section_mismatch(mod, elf, tsym,
1374 fsecndx, fromsec, r_offset, taddr);
1375 }
1376}
1377
1378static void section_rel(struct module *mod, struct elf_info *elf,
1379 unsigned int fsecndx, const char *fromsec,
1380 const Elf_Rel *start, const Elf_Rel *stop)
1381{
1382 const Elf_Rel *rel;
1383
1384 for (rel = start; rel < stop; rel++) {
1385 Elf_Sym *tsym;
1386 Elf_Addr taddr, r_offset;
1387 unsigned int r_type, r_sym;
1388 void *loc;
1389
1390 r_offset = TO_NATIVE(rel->r_offset);
1391 get_rel_type_and_sym(elf, rel->r_info, &r_type, &r_sym);
1392
1393 loc = sym_get_data_by_offset(elf, fsecndx, r_offset);
1394 tsym = elf->symtab_start + r_sym;
1395
1396 switch (elf->hdr->e_machine) {
1397 case EM_386:
1398 taddr = addend_386_rel(loc, r_type);
1399 break;
1400 case EM_ARM:
1401 taddr = addend_arm_rel(loc, tsym, r_type);
1402 break;
1403 case EM_MIPS:
1404 taddr = addend_mips_rel(loc, r_type);
1405 break;
1406 default:
1407 fatal("Please add code to calculate addend for this architecture\n");
1408 }
1409
1410 check_section_mismatch(mod, elf, tsym,
1411 fsecndx, fromsec, r_offset, taddr);
1412 }
1413}
1414
1415/**
1416 * A module includes a number of sections that are discarded
1417 * either when loaded or when used as built-in.
1418 * For loaded modules all functions marked __init and all data
1419 * marked __initdata will be discarded when the module has been initialized.
1420 * Likewise for modules used built-in the sections marked __exit
1421 * are discarded because __exit marked function are supposed to be called
1422 * only when a module is unloaded which never happens for built-in modules.
1423 * The check_sec_ref() function traverses all relocation records
1424 * to find all references to a section that reference a section that will
1425 * be discarded and warns about it.
1426 **/
1427static void check_sec_ref(struct module *mod, struct elf_info *elf)
1428{
1429 int i;
1430
1431 /* Walk through all sections */
1432 for (i = 0; i < elf->num_sections; i++) {
1433 Elf_Shdr *sechdr = &elf->sechdrs[i];
1434
1435 check_section(mod->name, elf, sechdr);
1436 /* We want to process only relocation sections and not .init */
1437 if (sechdr->sh_type == SHT_REL || sechdr->sh_type == SHT_RELA) {
1438 /* section to which the relocation applies */
1439 unsigned int secndx = sechdr->sh_info;
1440 const char *secname = sec_name(elf, secndx);
1441 const void *start, *stop;
1442
1443 /* If the section is known good, skip it */
1444 if (match(secname, section_white_list))
1445 continue;
1446
1447 start = sym_get_data_by_offset(elf, i, 0);
1448 stop = start + sechdr->sh_size;
1449
1450 if (sechdr->sh_type == SHT_RELA)
1451 section_rela(mod, elf, secndx, secname,
1452 start, stop);
1453 else
1454 section_rel(mod, elf, secndx, secname,
1455 start, stop);
1456 }
1457 }
1458}
1459
1460static char *remove_dot(char *s)
1461{
1462 size_t n = strcspn(s, ".");
1463
1464 if (n && s[n]) {
1465 size_t m = strspn(s + n + 1, "0123456789");
1466 if (m && (s[n + m + 1] == '.' || s[n + m + 1] == 0))
1467 s[n] = 0;
1468 }
1469 return s;
1470}
1471
1472/*
1473 * The CRCs are recorded in .*.cmd files in the form of:
1474 * #SYMVER <name> <crc>
1475 */
1476static void extract_crcs_for_object(const char *object, struct module *mod)
1477{
1478 char cmd_file[PATH_MAX];
1479 char *buf, *p;
1480 const char *base;
1481 int dirlen, ret;
1482
1483 base = get_basename(object);
1484 dirlen = base - object;
1485
1486 ret = snprintf(cmd_file, sizeof(cmd_file), "%.*s.%s.cmd",
1487 dirlen, object, base);
1488 if (ret >= sizeof(cmd_file)) {
1489 error("%s: too long path was truncated\n", cmd_file);
1490 return;
1491 }
1492
1493 buf = read_text_file(cmd_file);
1494 p = buf;
1495
1496 while ((p = strstr(p, "\n#SYMVER "))) {
1497 char *name;
1498 size_t namelen;
1499 unsigned int crc;
1500 struct symbol *sym;
1501
1502 name = p + strlen("\n#SYMVER ");
1503
1504 p = strchr(name, ' ');
1505 if (!p)
1506 break;
1507
1508 namelen = p - name;
1509 p++;
1510
1511 if (!isdigit(*p))
1512 continue; /* skip this line */
1513
1514 crc = strtoul(p, &p, 0);
1515 if (*p != '\n')
1516 continue; /* skip this line */
1517
1518 name[namelen] = '\0';
1519
1520 /*
1521 * sym_find_with_module() may return NULL here.
1522 * It typically occurs when CONFIG_TRIM_UNUSED_KSYMS=y.
1523 * Since commit e1327a127703, genksyms calculates CRCs of all
1524 * symbols, including trimmed ones. Ignore orphan CRCs.
1525 */
1526 sym = sym_find_with_module(name, mod);
1527 if (sym)
1528 sym_set_crc(sym, crc);
1529 }
1530
1531 free(buf);
1532}
1533
1534/*
1535 * The symbol versions (CRC) are recorded in the .*.cmd files.
1536 * Parse them to retrieve CRCs for the current module.
1537 */
1538static void mod_set_crcs(struct module *mod)
1539{
1540 char objlist[PATH_MAX];
1541 char *buf, *p, *obj;
1542 int ret;
1543
1544 if (mod->is_vmlinux) {
1545 strcpy(objlist, ".vmlinux.objs");
1546 } else {
1547 /* objects for a module are listed in the *.mod file. */
1548 ret = snprintf(objlist, sizeof(objlist), "%s.mod", mod->name);
1549 if (ret >= sizeof(objlist)) {
1550 error("%s: too long path was truncated\n", objlist);
1551 return;
1552 }
1553 }
1554
1555 buf = read_text_file(objlist);
1556 p = buf;
1557
1558 while ((obj = strsep(&p, "\n")) && obj[0])
1559 extract_crcs_for_object(obj, mod);
1560
1561 free(buf);
1562}
1563
1564static void read_symbols(const char *modname)
1565{
1566 const char *symname;
1567 char *version;
1568 char *license;
1569 char *namespace;
1570 struct module *mod;
1571 struct elf_info info = { };
1572 Elf_Sym *sym;
1573
1574 if (!parse_elf(&info, modname))
1575 return;
1576
1577 if (!strends(modname, ".o")) {
1578 error("%s: filename must be suffixed with .o\n", modname);
1579 return;
1580 }
1581
1582 /* strip trailing .o */
1583 mod = new_module(modname, strlen(modname) - strlen(".o"));
1584
1585 /* save .no_trim_symbol section for later use */
1586 if (info.no_trim_symbol_len) {
1587 mod->no_trim_symbol = xmalloc(info.no_trim_symbol_len);
1588 memcpy(mod->no_trim_symbol, info.no_trim_symbol,
1589 info.no_trim_symbol_len);
1590 mod->no_trim_symbol_len = info.no_trim_symbol_len;
1591 }
1592
1593 if (!mod->is_vmlinux) {
1594 license = get_modinfo(&info, "license");
1595 if (!license)
1596 error("missing MODULE_LICENSE() in %s\n", modname);
1597 while (license) {
1598 if (!license_is_gpl_compatible(license)) {
1599 mod->is_gpl_compatible = false;
1600 break;
1601 }
1602 license = get_next_modinfo(&info, "license", license);
1603 }
1604
1605 for (namespace = get_modinfo(&info, "import_ns");
1606 namespace;
1607 namespace = get_next_modinfo(&info, "import_ns", namespace)) {
1608 if (strstarts(namespace, MODULE_NS_PREFIX))
1609 error("%s: explicitly importing namespace \"%s\" is not allowed.\n",
1610 mod->name, namespace);
1611
1612 add_namespace(&mod->imported_namespaces, namespace);
1613 }
1614
1615 if (!get_modinfo(&info, "description"))
1616 warn("missing MODULE_DESCRIPTION() in %s\n", modname);
1617 }
1618
1619 for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
1620 symname = remove_dot(info.strtab + sym->st_name);
1621
1622 handle_symbol(mod, &info, sym, symname);
1623 handle_moddevtable(mod, &info, sym, symname);
1624 }
1625
1626 check_sec_ref(mod, &info);
1627
1628 if (!mod->is_vmlinux) {
1629 version = get_modinfo(&info, "version");
1630 if (version || all_versions)
1631 get_src_version(mod->name, mod->srcversion,
1632 sizeof(mod->srcversion) - 1);
1633 }
1634
1635 parse_elf_finish(&info);
1636
1637 if (modversions) {
1638 /*
1639 * Our trick to get versioning for module struct etc. - it's
1640 * never passed as an argument to an exported function, so
1641 * the automatic versioning doesn't pick it up, but it's really
1642 * important anyhow.
1643 */
1644 sym_add_unresolved("module_layout", mod, false);
1645
1646 mod_set_crcs(mod);
1647 }
1648}
1649
1650static void read_symbols_from_files(const char *filename)
1651{
1652 FILE *in = stdin;
1653 char fname[PATH_MAX];
1654
1655 in = fopen(filename, "r");
1656 if (!in)
1657 fatal("Can't open filenames file %s: %m", filename);
1658
1659 while (fgets(fname, PATH_MAX, in) != NULL) {
1660 if (strends(fname, "\n"))
1661 fname[strlen(fname)-1] = '\0';
1662 read_symbols(fname);
1663 }
1664
1665 fclose(in);
1666}
1667
1668#define SZ 500
1669
1670/* We first write the generated file into memory using the
1671 * following helper, then compare to the file on disk and
1672 * only update the later if anything changed */
1673
1674void __attribute__((format(printf, 2, 3))) buf_printf(struct buffer *buf,
1675 const char *fmt, ...)
1676{
1677 char tmp[SZ];
1678 int len;
1679 va_list ap;
1680
1681 va_start(ap, fmt);
1682 len = vsnprintf(tmp, SZ, fmt, ap);
1683 buf_write(buf, tmp, len);
1684 va_end(ap);
1685}
1686
1687void buf_write(struct buffer *buf, const char *s, int len)
1688{
1689 if (buf->size - buf->pos < len) {
1690 buf->size += len + SZ;
1691 buf->p = xrealloc(buf->p, buf->size);
1692 }
1693 strncpy(buf->p + buf->pos, s, len);
1694 buf->pos += len;
1695}
1696
1697/**
1698 * verify_module_namespace() - does @modname have access to this symbol's @namespace
1699 * @namespace: export symbol namespace
1700 * @modname: module name
1701 *
1702 * If @namespace is prefixed with "module:" to indicate it is a module namespace
1703 * then test if @modname matches any of the comma separated patterns.
1704 *
1705 * The patterns only support tail-glob.
1706 */
1707static bool verify_module_namespace(const char *namespace, const char *modname)
1708{
1709 size_t len, modlen = strlen(modname);
1710 const char *prefix = "module:";
1711 const char *sep;
1712 bool glob;
1713
1714 if (!strstarts(namespace, prefix))
1715 return false;
1716
1717 for (namespace += strlen(prefix); *namespace; namespace = sep) {
1718 sep = strchrnul(namespace, ',');
1719 len = sep - namespace;
1720
1721 glob = false;
1722 if (sep[-1] == '*') {
1723 len--;
1724 glob = true;
1725 }
1726
1727 if (*sep)
1728 sep++;
1729
1730 if (strncmp(namespace, modname, len) == 0 && (glob || len == modlen))
1731 return true;
1732 }
1733
1734 return false;
1735}
1736
1737static void check_exports(struct module *mod)
1738{
1739 struct symbol *s, *exp;
1740
1741 list_for_each_entry(s, &mod->unresolved_symbols, list) {
1742 const char *basename;
1743 exp = find_symbol(s->name);
1744 if (!exp) {
1745 if (!s->weak && nr_unresolved++ < MAX_UNRESOLVED_REPORTS)
1746 modpost_log(!warn_unresolved,
1747 "\"%s\" [%s.ko] undefined!\n",
1748 s->name, mod->name);
1749 continue;
1750 }
1751 if (exp->module == mod) {
1752 error("\"%s\" [%s.ko] was exported without definition\n",
1753 s->name, mod->name);
1754 continue;
1755 }
1756
1757 exp->used = true;
1758 s->module = exp->module;
1759 s->crc_valid = exp->crc_valid;
1760 s->crc = exp->crc;
1761
1762 basename = get_basename(mod->name);
1763
1764 if (!verify_module_namespace(exp->namespace, basename) &&
1765 !contains_namespace(&mod->imported_namespaces, exp->namespace)) {
1766 modpost_log(!allow_missing_ns_imports,
1767 "module %s uses symbol %s from namespace %s, but does not import it.\n",
1768 basename, exp->name, exp->namespace);
1769 add_namespace(&mod->missing_namespaces, exp->namespace);
1770 }
1771
1772 if (!mod->is_gpl_compatible && exp->is_gpl_only)
1773 error("GPL-incompatible module %s.ko uses GPL-only symbol '%s'\n",
1774 basename, exp->name);
1775 }
1776}
1777
1778static void handle_white_list_exports(const char *white_list)
1779{
1780 char *buf, *p, *name;
1781
1782 buf = read_text_file(white_list);
1783 p = buf;
1784
1785 while ((name = strsep(&p, "\n"))) {
1786 struct symbol *sym = find_symbol(name);
1787
1788 if (sym)
1789 sym->used = true;
1790 }
1791
1792 free(buf);
1793}
1794
1795/*
1796 * Keep symbols recorded in the .no_trim_symbol section. This is necessary to
1797 * prevent CONFIG_TRIM_UNUSED_KSYMS from dropping EXPORT_SYMBOL because
1798 * symbol_get() relies on the symbol being present in the ksymtab for lookups.
1799 */
1800static void keep_no_trim_symbols(struct module *mod)
1801{
1802 unsigned long size = mod->no_trim_symbol_len;
1803
1804 for (char *s = mod->no_trim_symbol; s; s = next_string(s , &size)) {
1805 struct symbol *sym;
1806
1807 /*
1808 * If find_symbol() returns NULL, this symbol is not provided
1809 * by any module, and symbol_get() will fail.
1810 */
1811 sym = find_symbol(s);
1812 if (sym)
1813 sym->used = true;
1814 }
1815}
1816
1817static void check_modname_len(struct module *mod)
1818{
1819 const char *mod_name;
1820
1821 mod_name = get_basename(mod->name);
1822
1823 if (strlen(mod_name) >= MODULE_NAME_LEN)
1824 error("module name is too long [%s.ko]\n", mod->name);
1825}
1826
1827/**
1828 * Header for the generated file
1829 **/
1830static void add_header(struct buffer *b, struct module *mod)
1831{
1832 buf_printf(b, "#include <linux/module.h>\n");
1833 buf_printf(b, "#include <linux/export-internal.h>\n");
1834 buf_printf(b, "#include <linux/compiler.h>\n");
1835 buf_printf(b, "\n");
1836 buf_printf(b, "MODULE_INFO(name, KBUILD_MODNAME);\n");
1837 buf_printf(b, "\n");
1838 buf_printf(b, "__visible struct module __this_module\n");
1839 buf_printf(b, "__section(\".gnu.linkonce.this_module\") = {\n");
1840 buf_printf(b, "\t.name = KBUILD_MODNAME,\n");
1841 if (mod->has_init)
1842 buf_printf(b, "\t.init = init_module,\n");
1843 if (mod->has_cleanup)
1844 buf_printf(b, "#ifdef CONFIG_MODULE_UNLOAD\n"
1845 "\t.exit = cleanup_module,\n"
1846 "#endif\n");
1847 buf_printf(b, "\t.arch = MODULE_ARCH_INIT,\n");
1848 buf_printf(b, "};\n");
1849
1850 if (!external_module)
1851 buf_printf(b, "\nMODULE_INFO(intree, \"Y\");\n");
1852
1853 if (strstarts(mod->name, "drivers/staging"))
1854 buf_printf(b, "\nMODULE_INFO(staging, \"Y\");\n");
1855
1856 if (strstarts(mod->name, "tools/testing"))
1857 buf_printf(b, "\nMODULE_INFO(test, \"Y\");\n");
1858}
1859
1860static void add_exported_symbols(struct buffer *buf, struct module *mod)
1861{
1862 struct symbol *sym;
1863
1864 /* generate struct for exported symbols */
1865 buf_printf(buf, "\n");
1866 list_for_each_entry(sym, &mod->exported_symbols, list) {
1867 if (trim_unused_exports && !sym->used)
1868 continue;
1869
1870 buf_printf(buf, "KSYMTAB_%s(%s, \"%s\", \"%s\");\n",
1871 sym->is_func ? "FUNC" : "DATA", sym->name,
1872 sym->is_gpl_only ? "_gpl" : "", sym->namespace);
1873 }
1874
1875 if (!modversions)
1876 return;
1877
1878 /* record CRCs for exported symbols */
1879 buf_printf(buf, "\n");
1880 list_for_each_entry(sym, &mod->exported_symbols, list) {
1881 if (trim_unused_exports && !sym->used)
1882 continue;
1883
1884 if (!sym->crc_valid)
1885 warn("EXPORT symbol \"%s\" [%s%s] version generation failed, symbol will not be versioned.\n"
1886 "Is \"%s\" prototyped in <asm/asm-prototypes.h>?\n",
1887 sym->name, mod->name, mod->is_vmlinux ? "" : ".ko",
1888 sym->name);
1889
1890 buf_printf(buf, "SYMBOL_CRC(%s, 0x%08x, \"%s\");\n",
1891 sym->name, sym->crc, sym->is_gpl_only ? "_gpl" : "");
1892 }
1893}
1894
1895/**
1896 * Record CRCs for unresolved symbols, supporting long names
1897 */
1898static void add_extended_versions(struct buffer *b, struct module *mod)
1899{
1900 struct symbol *s;
1901
1902 if (!extended_modversions)
1903 return;
1904
1905 buf_printf(b, "\n");
1906 buf_printf(b, "static const u32 ____version_ext_crcs[]\n");
1907 buf_printf(b, "__used __section(\"__version_ext_crcs\") = {\n");
1908 list_for_each_entry(s, &mod->unresolved_symbols, list) {
1909 if (!s->module)
1910 continue;
1911 if (!s->crc_valid) {
1912 warn("\"%s\" [%s.ko] has no CRC!\n",
1913 s->name, mod->name);
1914 continue;
1915 }
1916 buf_printf(b, "\t0x%08x,\n", s->crc);
1917 }
1918 buf_printf(b, "};\n");
1919
1920 buf_printf(b, "static const char ____version_ext_names[]\n");
1921 buf_printf(b, "__used __section(\"__version_ext_names\") =\n");
1922 list_for_each_entry(s, &mod->unresolved_symbols, list) {
1923 if (!s->module)
1924 continue;
1925 if (!s->crc_valid)
1926 /*
1927 * We already warned on this when producing the crc
1928 * table.
1929 * We need to skip its name too, as the indexes in
1930 * both tables need to align.
1931 */
1932 continue;
1933 buf_printf(b, "\t\"%s\\0\"\n", s->name);
1934 }
1935 buf_printf(b, ";\n");
1936}
1937
1938/**
1939 * Record CRCs for unresolved symbols
1940 **/
1941static void add_versions(struct buffer *b, struct module *mod)
1942{
1943 struct symbol *s;
1944
1945 if (!basic_modversions)
1946 return;
1947
1948 buf_printf(b, "\n");
1949 buf_printf(b, "static const struct modversion_info ____versions[]\n");
1950 buf_printf(b, "__used __section(\"__versions\") = {\n");
1951
1952 list_for_each_entry(s, &mod->unresolved_symbols, list) {
1953 if (!s->module)
1954 continue;
1955 if (!s->crc_valid) {
1956 warn("\"%s\" [%s.ko] has no CRC!\n",
1957 s->name, mod->name);
1958 continue;
1959 }
1960 if (strlen(s->name) >= MODULE_NAME_LEN) {
1961 if (extended_modversions) {
1962 /* this symbol will only be in the extended info */
1963 continue;
1964 } else {
1965 error("too long symbol \"%s\" [%s.ko]\n",
1966 s->name, mod->name);
1967 break;
1968 }
1969 }
1970 buf_printf(b, "\t{ 0x%08x, \"%s\" },\n",
1971 s->crc, s->name);
1972 }
1973
1974 buf_printf(b, "};\n");
1975}
1976
1977static void add_depends(struct buffer *b, struct module *mod)
1978{
1979 struct symbol *s;
1980 int first = 1;
1981
1982 /* Clear ->seen flag of modules that own symbols needed by this. */
1983 list_for_each_entry(s, &mod->unresolved_symbols, list) {
1984 if (s->module)
1985 s->module->seen = s->module->is_vmlinux;
1986 }
1987
1988 buf_printf(b, "\n");
1989 buf_printf(b, "MODULE_INFO(depends, \"");
1990 list_for_each_entry(s, &mod->unresolved_symbols, list) {
1991 const char *p;
1992 if (!s->module)
1993 continue;
1994
1995 if (s->module->seen)
1996 continue;
1997
1998 s->module->seen = true;
1999 p = get_basename(s->module->name);
2000 buf_printf(b, "%s%s", first ? "" : ",", p);
2001 first = 0;
2002 }
2003 buf_printf(b, "\");\n");
2004}
2005
2006static void add_srcversion(struct buffer *b, struct module *mod)
2007{
2008 if (mod->srcversion[0]) {
2009 buf_printf(b, "\n");
2010 buf_printf(b, "MODULE_INFO(srcversion, \"%s\");\n",
2011 mod->srcversion);
2012 }
2013}
2014
2015static void write_buf(struct buffer *b, const char *fname)
2016{
2017 FILE *file;
2018
2019 if (error_occurred)
2020 return;
2021
2022 file = fopen(fname, "w");
2023 if (!file) {
2024 perror(fname);
2025 exit(1);
2026 }
2027 if (fwrite(b->p, 1, b->pos, file) != b->pos) {
2028 perror(fname);
2029 exit(1);
2030 }
2031 if (fclose(file) != 0) {
2032 perror(fname);
2033 exit(1);
2034 }
2035}
2036
2037static void write_if_changed(struct buffer *b, const char *fname)
2038{
2039 char *tmp;
2040 FILE *file;
2041 struct stat st;
2042
2043 file = fopen(fname, "r");
2044 if (!file)
2045 goto write;
2046
2047 if (fstat(fileno(file), &st) < 0)
2048 goto close_write;
2049
2050 if (st.st_size != b->pos)
2051 goto close_write;
2052
2053 tmp = xmalloc(b->pos);
2054 if (fread(tmp, 1, b->pos, file) != b->pos)
2055 goto free_write;
2056
2057 if (memcmp(tmp, b->p, b->pos) != 0)
2058 goto free_write;
2059
2060 free(tmp);
2061 fclose(file);
2062 return;
2063
2064 free_write:
2065 free(tmp);
2066 close_write:
2067 fclose(file);
2068 write:
2069 write_buf(b, fname);
2070}
2071
2072static void write_vmlinux_export_c_file(struct module *mod)
2073{
2074 struct buffer buf = { };
2075 struct module_alias *alias, *next;
2076
2077 buf_printf(&buf,
2078 "#include <linux/export-internal.h>\n");
2079
2080 add_exported_symbols(&buf, mod);
2081
2082 buf_printf(&buf,
2083 "#include <linux/module.h>\n"
2084 "#undef __MODULE_INFO_PREFIX\n"
2085 "#define __MODULE_INFO_PREFIX\n");
2086
2087 list_for_each_entry_safe(alias, next, &mod->aliases, node) {
2088 buf_printf(&buf, "MODULE_INFO(%s.alias, \"%s\");\n",
2089 alias->builtin_modname, alias->str);
2090 list_del(&alias->node);
2091 free(alias->builtin_modname);
2092 free(alias);
2093 }
2094
2095 write_if_changed(&buf, ".vmlinux.export.c");
2096 free(buf.p);
2097}
2098
2099/* do sanity checks, and generate *.mod.c file */
2100static void write_mod_c_file(struct module *mod)
2101{
2102 struct buffer buf = { };
2103 struct module_alias *alias, *next;
2104 char fname[PATH_MAX];
2105 int ret;
2106
2107 add_header(&buf, mod);
2108 add_exported_symbols(&buf, mod);
2109 add_versions(&buf, mod);
2110 add_extended_versions(&buf, mod);
2111 add_depends(&buf, mod);
2112
2113 buf_printf(&buf, "\n");
2114 list_for_each_entry_safe(alias, next, &mod->aliases, node) {
2115 buf_printf(&buf, "MODULE_ALIAS(\"%s\");\n", alias->str);
2116 list_del(&alias->node);
2117 free(alias);
2118 }
2119
2120 add_srcversion(&buf, mod);
2121
2122 ret = snprintf(fname, sizeof(fname), "%s.mod.c", mod->name);
2123 if (ret >= sizeof(fname)) {
2124 error("%s: too long path was truncated\n", fname);
2125 goto free;
2126 }
2127
2128 write_if_changed(&buf, fname);
2129
2130free:
2131 free(buf.p);
2132}
2133
2134/* parse Module.symvers file. line format:
2135 * 0x12345678<tab>symbol<tab>module<tab>export<tab>namespace
2136 **/
2137static void read_dump(const char *fname)
2138{
2139 char *buf, *pos, *line;
2140
2141 buf = read_text_file(fname);
2142 if (!buf)
2143 /* No symbol versions, silently ignore */
2144 return;
2145
2146 pos = buf;
2147
2148 while ((line = get_line(&pos))) {
2149 char *symname, *namespace, *modname, *d, *export;
2150 unsigned int crc;
2151 struct module *mod;
2152 struct symbol *s;
2153 bool gpl_only;
2154
2155 if (!(symname = strchr(line, '\t')))
2156 goto fail;
2157 *symname++ = '\0';
2158 if (!(modname = strchr(symname, '\t')))
2159 goto fail;
2160 *modname++ = '\0';
2161 if (!(export = strchr(modname, '\t')))
2162 goto fail;
2163 *export++ = '\0';
2164 if (!(namespace = strchr(export, '\t')))
2165 goto fail;
2166 *namespace++ = '\0';
2167
2168 crc = strtoul(line, &d, 16);
2169 if (*symname == '\0' || *modname == '\0' || *d != '\0')
2170 goto fail;
2171
2172 if (!strcmp(export, "EXPORT_SYMBOL_GPL")) {
2173 gpl_only = true;
2174 } else if (!strcmp(export, "EXPORT_SYMBOL")) {
2175 gpl_only = false;
2176 } else {
2177 error("%s: unknown license %s. skip", symname, export);
2178 continue;
2179 }
2180
2181 mod = find_module(fname, modname);
2182 if (!mod) {
2183 mod = new_module(modname, strlen(modname));
2184 mod->dump_file = fname;
2185 }
2186 s = sym_add_exported(symname, mod, gpl_only, namespace);
2187 sym_set_crc(s, crc);
2188 }
2189 free(buf);
2190 return;
2191fail:
2192 free(buf);
2193 fatal("parse error in symbol dump file\n");
2194}
2195
2196static void write_dump(const char *fname)
2197{
2198 struct buffer buf = { };
2199 struct module *mod;
2200 struct symbol *sym;
2201
2202 list_for_each_entry(mod, &modules, list) {
2203 if (mod->dump_file)
2204 continue;
2205 list_for_each_entry(sym, &mod->exported_symbols, list) {
2206 if (trim_unused_exports && !sym->used)
2207 continue;
2208
2209 buf_printf(&buf, "0x%08x\t%s\t%s\tEXPORT_SYMBOL%s\t%s\n",
2210 sym->crc, sym->name, mod->name,
2211 sym->is_gpl_only ? "_GPL" : "",
2212 sym->namespace);
2213 }
2214 }
2215 write_buf(&buf, fname);
2216 free(buf.p);
2217}
2218
2219static void write_namespace_deps_files(const char *fname)
2220{
2221 struct module *mod;
2222 struct namespace_list *ns;
2223 struct buffer ns_deps_buf = {};
2224
2225 list_for_each_entry(mod, &modules, list) {
2226
2227 if (mod->dump_file || list_empty(&mod->missing_namespaces))
2228 continue;
2229
2230 buf_printf(&ns_deps_buf, "%s.ko:", mod->name);
2231
2232 list_for_each_entry(ns, &mod->missing_namespaces, list)
2233 buf_printf(&ns_deps_buf, " %s", ns->namespace);
2234
2235 buf_printf(&ns_deps_buf, "\n");
2236 }
2237
2238 write_if_changed(&ns_deps_buf, fname);
2239 free(ns_deps_buf.p);
2240}
2241
2242struct dump_list {
2243 struct list_head list;
2244 const char *file;
2245};
2246
2247static void check_host_endian(void)
2248{
2249 static const union {
2250 short s;
2251 char c[2];
2252 } endian_test = { .c = {0x01, 0x02} };
2253
2254 switch (endian_test.s) {
2255 case 0x0102:
2256 host_is_big_endian = true;
2257 break;
2258 case 0x0201:
2259 host_is_big_endian = false;
2260 break;
2261 default:
2262 fatal("Unknown host endian\n");
2263 }
2264}
2265
2266int main(int argc, char **argv)
2267{
2268 struct module *mod;
2269 char *missing_namespace_deps = NULL;
2270 char *unused_exports_white_list = NULL;
2271 char *dump_write = NULL, *files_source = NULL;
2272 int opt;
2273 LIST_HEAD(dump_lists);
2274 struct dump_list *dl, *dl2;
2275
2276 while ((opt = getopt(argc, argv, "ei:MmnT:to:au:WwENd:xb")) != -1) {
2277 switch (opt) {
2278 case 'e':
2279 external_module = true;
2280 break;
2281 case 'i':
2282 dl = xmalloc(sizeof(*dl));
2283 dl->file = optarg;
2284 list_add_tail(&dl->list, &dump_lists);
2285 break;
2286 case 'M':
2287 module_enabled = true;
2288 break;
2289 case 'm':
2290 modversions = true;
2291 break;
2292 case 'n':
2293 ignore_missing_files = true;
2294 break;
2295 case 'o':
2296 dump_write = optarg;
2297 break;
2298 case 'a':
2299 all_versions = true;
2300 break;
2301 case 'T':
2302 files_source = optarg;
2303 break;
2304 case 't':
2305 trim_unused_exports = true;
2306 break;
2307 case 'u':
2308 unused_exports_white_list = optarg;
2309 break;
2310 case 'W':
2311 extra_warn = true;
2312 break;
2313 case 'w':
2314 warn_unresolved = true;
2315 break;
2316 case 'E':
2317 sec_mismatch_warn_only = false;
2318 break;
2319 case 'N':
2320 allow_missing_ns_imports = true;
2321 break;
2322 case 'd':
2323 missing_namespace_deps = optarg;
2324 break;
2325 case 'b':
2326 basic_modversions = true;
2327 break;
2328 case 'x':
2329 extended_modversions = true;
2330 break;
2331 default:
2332 exit(1);
2333 }
2334 }
2335
2336 check_host_endian();
2337
2338 list_for_each_entry_safe(dl, dl2, &dump_lists, list) {
2339 read_dump(dl->file);
2340 list_del(&dl->list);
2341 free(dl);
2342 }
2343
2344 while (optind < argc)
2345 read_symbols(argv[optind++]);
2346
2347 if (files_source)
2348 read_symbols_from_files(files_source);
2349
2350 list_for_each_entry(mod, &modules, list) {
2351 keep_no_trim_symbols(mod);
2352
2353 if (mod->dump_file || mod->is_vmlinux)
2354 continue;
2355
2356 check_modname_len(mod);
2357 check_exports(mod);
2358 }
2359
2360 if (unused_exports_white_list)
2361 handle_white_list_exports(unused_exports_white_list);
2362
2363 list_for_each_entry(mod, &modules, list) {
2364 if (mod->dump_file)
2365 continue;
2366
2367 if (mod->is_vmlinux)
2368 write_vmlinux_export_c_file(mod);
2369 else
2370 write_mod_c_file(mod);
2371 }
2372
2373 if (missing_namespace_deps)
2374 write_namespace_deps_files(missing_namespace_deps);
2375
2376 if (dump_write)
2377 write_dump(dump_write);
2378 if (sec_mismatch_count && !sec_mismatch_warn_only)
2379 error("Section mismatches detected.\n"
2380 "Set CONFIG_SECTION_MISMATCH_WARN_ONLY=y to allow them.\n");
2381
2382 if (nr_unresolved > MAX_UNRESOLVED_REPORTS)
2383 warn("suppressed %u unresolved symbol warnings because there were too many)\n",
2384 nr_unresolved - MAX_UNRESOLVED_REPORTS);
2385
2386 return error_occurred ? 1 : 0;
2387}