1 /* Postprocess module symbol versions
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
8 * This software may be used and distributed according to the terms
9 * of the GNU General Public License, incorporated herein by reference.
11 * Usage: modpost vmlinux module1.o module2.o ...
24 #include "../../include/linux/license.h"
26 /* Are we using CONFIG_MODVERSIONS? */
27 static bool modversions;
28 /* Is CONFIG_MODULE_SRCVERSION_ALL set? */
29 static bool all_versions;
30 /* If we are modposting external module set to 1 */
31 static bool external_module;
32 /* Only warn about unresolved symbols */
33 static bool warn_unresolved;
35 static int sec_mismatch_count;
36 static bool sec_mismatch_warn_only = true;
37 /* ignore missing files */
38 static bool ignore_missing_files;
39 /* If set to 1, only warn (instead of error) about missing ns imports */
40 static bool allow_missing_ns_imports;
42 static bool error_occurred;
44 static bool extra_warn;
47 * Cut off the warnings when there are too many. This typically occurs when
48 * vmlinux is missing. ('make modules' without building vmlinux.)
50 #define MAX_UNRESOLVED_REPORTS 10
51 static unsigned int nr_unresolved;
53 /* In kernel, this size is defined in linux/module.h;
54 * here we use Elf_Addr instead of long for covering cross-compile
57 #define MODULE_NAME_LEN (64 - sizeof(Elf_Addr))
59 void __attribute__((format(printf, 2, 3)))
60 modpost_log(enum loglevel loglevel, const char *fmt, ...)
66 fprintf(stderr, "WARNING: ");
69 fprintf(stderr, "ERROR: ");
72 fprintf(stderr, "FATAL: ");
74 default: /* invalid loglevel, ignore */
78 fprintf(stderr, "modpost: ");
80 va_start(arglist, fmt);
81 vfprintf(stderr, fmt, arglist);
84 if (loglevel == LOG_FATAL)
86 if (loglevel == LOG_ERROR)
87 error_occurred = true;
90 static inline bool strends(const char *str, const char *postfix)
92 if (strlen(str) < strlen(postfix))
95 return strcmp(str + strlen(str) - strlen(postfix), postfix) == 0;
98 void *do_nofail(void *ptr, const char *expr)
101 fatal("Memory allocation failure: %s.\n", expr);
106 char *read_text_file(const char *filename)
113 fd = open(filename, O_RDONLY);
119 if (fstat(fd, &st) < 0) {
124 buf = NOFAIL(malloc(st.st_size + 1));
131 bytes_read = read(fd, buf, nbytes);
132 if (bytes_read < 0) {
137 nbytes -= bytes_read;
139 buf[st.st_size] = '\0';
146 char *get_line(char **stringp)
148 char *orig = *stringp, *next;
150 /* do not return the unwanted extra line at EOF */
151 if (!orig || *orig == '\0')
154 /* don't use strsep here, it is not available everywhere */
155 next = strchr(orig, '\n');
164 /* A list of all modules we processed */
167 static struct module *find_module(const char *modname)
171 list_for_each_entry(mod, &modules, list) {
172 if (strcmp(mod->name, modname) == 0)
178 static struct module *new_module(const char *name, size_t namelen)
182 mod = NOFAIL(malloc(sizeof(*mod) + namelen + 1));
183 memset(mod, 0, sizeof(*mod));
185 INIT_LIST_HEAD(&mod->exported_symbols);
186 INIT_LIST_HEAD(&mod->unresolved_symbols);
187 INIT_LIST_HEAD(&mod->missing_namespaces);
188 INIT_LIST_HEAD(&mod->imported_namespaces);
190 memcpy(mod->name, name, namelen);
191 mod->name[namelen] = '\0';
192 mod->is_vmlinux = (strcmp(mod->name, "vmlinux") == 0);
195 * Set mod->is_gpl_compatible to true by default. If MODULE_LICENSE()
196 * is missing, do not check the use for EXPORT_SYMBOL_GPL() becasue
197 * modpost will exit wiht error anyway.
199 mod->is_gpl_compatible = true;
201 list_add_tail(&mod->list, &modules);
206 /* A hash of all exported symbols,
207 * struct symbol is also used for lists of unresolved symbols */
209 #define SYMBOL_HASH_SIZE 1024
213 struct list_head list; /* link to module::exported_symbols or module::unresolved_symbols */
214 struct module *module;
219 bool is_gpl_only; /* exported by EXPORT_SYMBOL_GPL */
223 static struct symbol *symbolhash[SYMBOL_HASH_SIZE];
225 /* This is based on the hash algorithm from gdbm, via tdb */
226 static inline unsigned int tdb_hash(const char *name)
228 unsigned value; /* Used to compute the hash value. */
229 unsigned i; /* Used to cycle through random values. */
231 /* Set the initial value from the key size. */
232 for (value = 0x238F13AF * strlen(name), i = 0; name[i]; i++)
233 value = (value + (((unsigned char *)name)[i] << (i*5 % 24)));
235 return (1103515243 * value + 12345);
239 * Allocate a new symbols for use in the hash of exported symbols or
240 * the list of unresolved symbols per module
242 static struct symbol *alloc_symbol(const char *name)
244 struct symbol *s = NOFAIL(malloc(sizeof(*s) + strlen(name) + 1));
246 memset(s, 0, sizeof(*s));
247 strcpy(s->name, name);
252 /* For the hash of exported symbols */
253 static void hash_add_symbol(struct symbol *sym)
257 hash = tdb_hash(sym->name) % SYMBOL_HASH_SIZE;
258 sym->next = symbolhash[hash];
259 symbolhash[hash] = sym;
262 static void sym_add_unresolved(const char *name, struct module *mod, bool weak)
266 sym = alloc_symbol(name);
269 list_add_tail(&sym->list, &mod->unresolved_symbols);
272 static struct symbol *sym_find_with_module(const char *name, struct module *mod)
276 /* For our purposes, .foo matches foo. PPC64 needs this. */
280 for (s = symbolhash[tdb_hash(name) % SYMBOL_HASH_SIZE]; s; s = s->next) {
281 if (strcmp(s->name, name) == 0 && (!mod || s->module == mod))
287 static struct symbol *find_symbol(const char *name)
289 return sym_find_with_module(name, NULL);
292 struct namespace_list {
293 struct list_head list;
297 static bool contains_namespace(struct list_head *head, const char *namespace)
299 struct namespace_list *list;
301 list_for_each_entry(list, head, list) {
302 if (!strcmp(list->namespace, namespace))
309 static void add_namespace(struct list_head *head, const char *namespace)
311 struct namespace_list *ns_entry;
313 if (!contains_namespace(head, namespace)) {
314 ns_entry = NOFAIL(malloc(sizeof(*ns_entry) +
315 strlen(namespace) + 1));
316 strcpy(ns_entry->namespace, namespace);
317 list_add_tail(&ns_entry->list, head);
321 static void *sym_get_data_by_offset(const struct elf_info *info,
322 unsigned int secindex, unsigned long offset)
324 Elf_Shdr *sechdr = &info->sechdrs[secindex];
326 return (void *)info->hdr + sechdr->sh_offset + offset;
329 void *sym_get_data(const struct elf_info *info, const Elf_Sym *sym)
331 return sym_get_data_by_offset(info, get_secindex(info, sym),
335 static const char *sech_name(const struct elf_info *info, Elf_Shdr *sechdr)
337 return sym_get_data_by_offset(info, info->secindex_strings,
341 static const char *sec_name(const struct elf_info *info, unsigned int secindex)
344 * If sym->st_shndx is a special section index, there is no
345 * corresponding section header.
346 * Return "" if the index is out of range of info->sechdrs[] array.
348 if (secindex >= info->num_sections)
351 return sech_name(info, &info->sechdrs[secindex]);
354 #define strstarts(str, prefix) (strncmp(str, prefix, strlen(prefix)) == 0)
356 static void sym_update_namespace(const char *symname, const char *namespace)
358 struct symbol *s = find_symbol(symname);
361 * That symbol should have been created earlier and thus this is
362 * actually an assertion.
365 error("Could not update namespace(%s) for symbol %s\n",
371 s->namespace = namespace[0] ? NOFAIL(strdup(namespace)) : NULL;
374 static struct symbol *sym_add_exported(const char *name, struct module *mod,
377 struct symbol *s = find_symbol(name);
379 if (s && (!external_module || s->module->is_vmlinux || s->module == mod)) {
380 error("%s: '%s' exported twice. Previous export was in %s%s\n",
381 mod->name, name, s->module->name,
382 s->module->is_vmlinux ? "" : ".ko");
385 s = alloc_symbol(name);
387 s->is_gpl_only = gpl_only;
388 list_add_tail(&s->list, &mod->exported_symbols);
394 static void sym_set_crc(struct symbol *sym, unsigned int crc)
397 sym->crc_valid = true;
400 static void *grab_file(const char *filename, size_t *size)
403 void *map = MAP_FAILED;
406 fd = open(filename, O_RDONLY);
413 map = mmap(NULL, *size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
417 if (map == MAP_FAILED)
422 static void release_file(void *file, size_t size)
427 static int parse_elf(struct elf_info *info, const char *filename)
433 const char *secstrings;
434 unsigned int symtab_idx = ~0U, symtab_shndx_idx = ~0U;
436 hdr = grab_file(filename, &info->size);
438 if (ignore_missing_files) {
439 fprintf(stderr, "%s: %s (ignored)\n", filename,
447 if (info->size < sizeof(*hdr)) {
448 /* file too small, assume this is an empty .o file */
451 /* Is this a valid ELF file? */
452 if ((hdr->e_ident[EI_MAG0] != ELFMAG0) ||
453 (hdr->e_ident[EI_MAG1] != ELFMAG1) ||
454 (hdr->e_ident[EI_MAG2] != ELFMAG2) ||
455 (hdr->e_ident[EI_MAG3] != ELFMAG3)) {
456 /* Not an ELF file - silently ignore it */
459 /* Fix endianness in ELF header */
460 hdr->e_type = TO_NATIVE(hdr->e_type);
461 hdr->e_machine = TO_NATIVE(hdr->e_machine);
462 hdr->e_version = TO_NATIVE(hdr->e_version);
463 hdr->e_entry = TO_NATIVE(hdr->e_entry);
464 hdr->e_phoff = TO_NATIVE(hdr->e_phoff);
465 hdr->e_shoff = TO_NATIVE(hdr->e_shoff);
466 hdr->e_flags = TO_NATIVE(hdr->e_flags);
467 hdr->e_ehsize = TO_NATIVE(hdr->e_ehsize);
468 hdr->e_phentsize = TO_NATIVE(hdr->e_phentsize);
469 hdr->e_phnum = TO_NATIVE(hdr->e_phnum);
470 hdr->e_shentsize = TO_NATIVE(hdr->e_shentsize);
471 hdr->e_shnum = TO_NATIVE(hdr->e_shnum);
472 hdr->e_shstrndx = TO_NATIVE(hdr->e_shstrndx);
473 sechdrs = (void *)hdr + hdr->e_shoff;
474 info->sechdrs = sechdrs;
476 /* modpost only works for relocatable objects */
477 if (hdr->e_type != ET_REL)
478 fatal("%s: not relocatable object.", filename);
480 /* Check if file offset is correct */
481 if (hdr->e_shoff > info->size) {
482 fatal("section header offset=%lu in file '%s' is bigger than filesize=%zu\n",
483 (unsigned long)hdr->e_shoff, filename, info->size);
487 if (hdr->e_shnum == SHN_UNDEF) {
489 * There are more than 64k sections,
490 * read count from .sh_size.
492 info->num_sections = TO_NATIVE(sechdrs[0].sh_size);
495 info->num_sections = hdr->e_shnum;
497 if (hdr->e_shstrndx == SHN_XINDEX) {
498 info->secindex_strings = TO_NATIVE(sechdrs[0].sh_link);
501 info->secindex_strings = hdr->e_shstrndx;
504 /* Fix endianness in section headers */
505 for (i = 0; i < info->num_sections; i++) {
506 sechdrs[i].sh_name = TO_NATIVE(sechdrs[i].sh_name);
507 sechdrs[i].sh_type = TO_NATIVE(sechdrs[i].sh_type);
508 sechdrs[i].sh_flags = TO_NATIVE(sechdrs[i].sh_flags);
509 sechdrs[i].sh_addr = TO_NATIVE(sechdrs[i].sh_addr);
510 sechdrs[i].sh_offset = TO_NATIVE(sechdrs[i].sh_offset);
511 sechdrs[i].sh_size = TO_NATIVE(sechdrs[i].sh_size);
512 sechdrs[i].sh_link = TO_NATIVE(sechdrs[i].sh_link);
513 sechdrs[i].sh_info = TO_NATIVE(sechdrs[i].sh_info);
514 sechdrs[i].sh_addralign = TO_NATIVE(sechdrs[i].sh_addralign);
515 sechdrs[i].sh_entsize = TO_NATIVE(sechdrs[i].sh_entsize);
517 /* Find symbol table. */
518 secstrings = (void *)hdr + sechdrs[info->secindex_strings].sh_offset;
519 for (i = 1; i < info->num_sections; i++) {
521 int nobits = sechdrs[i].sh_type == SHT_NOBITS;
523 if (!nobits && sechdrs[i].sh_offset > info->size) {
524 fatal("%s is truncated. sechdrs[i].sh_offset=%lu > "
525 "sizeof(*hrd)=%zu\n", filename,
526 (unsigned long)sechdrs[i].sh_offset,
530 secname = secstrings + sechdrs[i].sh_name;
531 if (strcmp(secname, ".modinfo") == 0) {
533 fatal("%s has NOBITS .modinfo\n", filename);
534 info->modinfo = (void *)hdr + sechdrs[i].sh_offset;
535 info->modinfo_len = sechdrs[i].sh_size;
538 if (sechdrs[i].sh_type == SHT_SYMTAB) {
539 unsigned int sh_link_idx;
541 info->symtab_start = (void *)hdr +
542 sechdrs[i].sh_offset;
543 info->symtab_stop = (void *)hdr +
544 sechdrs[i].sh_offset + sechdrs[i].sh_size;
545 sh_link_idx = sechdrs[i].sh_link;
546 info->strtab = (void *)hdr +
547 sechdrs[sh_link_idx].sh_offset;
550 /* 32bit section no. table? ("more than 64k sections") */
551 if (sechdrs[i].sh_type == SHT_SYMTAB_SHNDX) {
552 symtab_shndx_idx = i;
553 info->symtab_shndx_start = (void *)hdr +
554 sechdrs[i].sh_offset;
555 info->symtab_shndx_stop = (void *)hdr +
556 sechdrs[i].sh_offset + sechdrs[i].sh_size;
559 if (!info->symtab_start)
560 fatal("%s has no symtab?\n", filename);
562 /* Fix endianness in symbols */
563 for (sym = info->symtab_start; sym < info->symtab_stop; sym++) {
564 sym->st_shndx = TO_NATIVE(sym->st_shndx);
565 sym->st_name = TO_NATIVE(sym->st_name);
566 sym->st_value = TO_NATIVE(sym->st_value);
567 sym->st_size = TO_NATIVE(sym->st_size);
570 if (symtab_shndx_idx != ~0U) {
572 if (symtab_idx != sechdrs[symtab_shndx_idx].sh_link)
573 fatal("%s: SYMTAB_SHNDX has bad sh_link: %u!=%u\n",
574 filename, sechdrs[symtab_shndx_idx].sh_link,
577 for (p = info->symtab_shndx_start; p < info->symtab_shndx_stop;
585 static void parse_elf_finish(struct elf_info *info)
587 release_file(info->hdr, info->size);
590 static int ignore_undef_symbol(struct elf_info *info, const char *symname)
592 /* ignore __this_module, it will be resolved shortly */
593 if (strcmp(symname, "__this_module") == 0)
595 /* ignore global offset table */
596 if (strcmp(symname, "_GLOBAL_OFFSET_TABLE_") == 0)
598 if (info->hdr->e_machine == EM_PPC)
599 /* Special register function linked on all modules during final link of .ko */
600 if (strstarts(symname, "_restgpr_") ||
601 strstarts(symname, "_savegpr_") ||
602 strstarts(symname, "_rest32gpr_") ||
603 strstarts(symname, "_save32gpr_") ||
604 strstarts(symname, "_restvr_") ||
605 strstarts(symname, "_savevr_"))
607 if (info->hdr->e_machine == EM_PPC64)
608 /* Special register function linked on all modules during final link of .ko */
609 if (strstarts(symname, "_restgpr0_") ||
610 strstarts(symname, "_savegpr0_") ||
611 strstarts(symname, "_restvr_") ||
612 strstarts(symname, "_savevr_") ||
613 strcmp(symname, ".TOC.") == 0)
616 if (info->hdr->e_machine == EM_S390)
617 /* Expoline thunks are linked on all kernel modules during final link of .ko */
618 if (strstarts(symname, "__s390_indirect_jump_r"))
620 /* Do not ignore this symbol */
624 static void handle_symbol(struct module *mod, struct elf_info *info,
625 const Elf_Sym *sym, const char *symname)
627 switch (sym->st_shndx) {
629 if (strstarts(symname, "__gnu_lto_")) {
630 /* Should warn here, but modpost runs before the linker */
632 warn("\"%s\" [%s] is COMMON symbol\n", symname, mod->name);
635 /* undefined symbol */
636 if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL &&
637 ELF_ST_BIND(sym->st_info) != STB_WEAK)
639 if (ignore_undef_symbol(info, symname))
641 if (info->hdr->e_machine == EM_SPARC ||
642 info->hdr->e_machine == EM_SPARCV9) {
643 /* Ignore register directives. */
644 if (ELF_ST_TYPE(sym->st_info) == STT_SPARC_REGISTER)
646 if (symname[0] == '.') {
647 char *munged = NOFAIL(strdup(symname));
649 munged[1] = toupper(munged[1]);
654 sym_add_unresolved(symname, mod,
655 ELF_ST_BIND(sym->st_info) == STB_WEAK);
658 /* All exported symbols */
659 if (strstarts(symname, "__ksymtab_")) {
660 const char *name, *secname;
662 name = symname + strlen("__ksymtab_");
663 secname = sec_name(info, get_secindex(info, sym));
665 if (strstarts(secname, "___ksymtab_gpl+"))
666 sym_add_exported(name, mod, true);
667 else if (strstarts(secname, "___ksymtab+"))
668 sym_add_exported(name, mod, false);
670 if (strcmp(symname, "init_module") == 0)
671 mod->has_init = true;
672 if (strcmp(symname, "cleanup_module") == 0)
673 mod->has_cleanup = true;
679 * Parse tag=value strings from .modinfo section
681 static char *next_string(char *string, unsigned long *secsize)
683 /* Skip non-zero chars */
686 if ((*secsize)-- <= 1)
690 /* Skip any zero padding. */
693 if ((*secsize)-- <= 1)
699 static char *get_next_modinfo(struct elf_info *info, const char *tag,
703 unsigned int taglen = strlen(tag);
704 char *modinfo = info->modinfo;
705 unsigned long size = info->modinfo_len;
708 size -= prev - modinfo;
709 modinfo = next_string(prev, &size);
712 for (p = modinfo; p; p = next_string(p, &size)) {
713 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
714 return p + taglen + 1;
719 static char *get_modinfo(struct elf_info *info, const char *tag)
722 return get_next_modinfo(info, tag, NULL);
725 static const char *sym_name(struct elf_info *elf, Elf_Sym *sym)
728 return elf->strtab + sym->st_name;
734 * Check whether the 'string' argument matches one of the 'patterns',
735 * an array of shell wildcard patterns (glob).
737 * Return true is there is a match.
739 static bool match(const char *string, const char *const patterns[])
743 while ((pattern = *patterns++)) {
744 if (!fnmatch(pattern, string, 0))
751 /* useful to pass patterns to match() directly */
752 #define PATTERNS(...) \
754 static const char *const patterns[] = {__VA_ARGS__, NULL}; \
758 /* sections that we do not want to do full section mismatch check on */
759 static const char *const section_white_list[] =
763 ".zdebug*", /* Compressed debug sections. */
764 ".GCC.command.line", /* record-gcc-switches */
765 ".mdebug*", /* alpha, score, mips etc. */
766 ".pdr", /* alpha, score, mips etc. */
771 ".xt.prop", /* xtensa */
772 ".xt.lit", /* xtensa */
773 ".arcextmap*", /* arc */
774 ".gnu.linkonce.arcext*", /* arc : modules */
775 ".cmem*", /* EZchip */
776 ".fmt_slot*", /* EZchip */
783 * This is used to find sections missing the SHF_ALLOC flag.
784 * The cause of this is often a section specified in assembler
785 * without "ax" / "aw".
787 static void check_section(const char *modname, struct elf_info *elf,
790 const char *sec = sech_name(elf, sechdr);
792 if (sechdr->sh_type == SHT_PROGBITS &&
793 !(sechdr->sh_flags & SHF_ALLOC) &&
794 !match(sec, section_white_list)) {
795 warn("%s (%s): unexpected non-allocatable section.\n"
796 "Did you forget to use \"ax\"/\"aw\" in a .S file?\n"
797 "Note that for example <linux/init.h> contains\n"
798 "section definitions for use in .S files.\n\n",
805 #define ALL_INIT_DATA_SECTIONS \
806 ".init.setup", ".init.rodata", ".meminit.rodata", \
807 ".init.data", ".meminit.data"
808 #define ALL_EXIT_DATA_SECTIONS \
809 ".exit.data", ".memexit.data"
811 #define ALL_INIT_TEXT_SECTIONS \
812 ".init.text", ".meminit.text"
813 #define ALL_EXIT_TEXT_SECTIONS \
816 #define ALL_PCI_INIT_SECTIONS \
817 ".pci_fixup_early", ".pci_fixup_header", ".pci_fixup_final", \
818 ".pci_fixup_enable", ".pci_fixup_resume", \
819 ".pci_fixup_resume_early", ".pci_fixup_suspend"
821 #define ALL_XXXINIT_SECTIONS MEM_INIT_SECTIONS
823 #define ALL_INIT_SECTIONS INIT_SECTIONS, ALL_XXXINIT_SECTIONS
824 #define ALL_EXIT_SECTIONS EXIT_SECTIONS
826 #define DATA_SECTIONS ".data", ".data.rel"
827 #define TEXT_SECTIONS ".text", ".text.*", ".sched.text", \
828 ".kprobes.text", ".cpuidle.text", ".noinstr.text", \
830 #define OTHER_TEXT_SECTIONS ".ref.text", ".head.text", ".spinlock.text", \
831 ".fixup", ".entry.text", ".exception.text", \
832 ".coldtext", ".softirqentry.text"
834 #define INIT_SECTIONS ".init.*"
835 #define MEM_INIT_SECTIONS ".meminit.*"
837 #define EXIT_SECTIONS ".exit.*"
839 #define ALL_TEXT_SECTIONS ALL_INIT_TEXT_SECTIONS, ALL_EXIT_TEXT_SECTIONS, \
840 TEXT_SECTIONS, OTHER_TEXT_SECTIONS
842 /* init data sections */
843 static const char *const init_data_sections[] =
844 { ALL_INIT_DATA_SECTIONS, NULL };
846 /* all init sections */
847 static const char *const init_sections[] = { ALL_INIT_SECTIONS, NULL };
849 /* all text sections */
850 static const char *const text_sections[] = { ALL_TEXT_SECTIONS, NULL };
853 static const char *const data_sections[] = { DATA_SECTIONS, NULL };
855 static const char *const head_sections[] = { ".head.text*", NULL };
856 static const char *const linker_symbols[] =
857 { "__init_begin", "_sinittext", "_einittext", NULL };
858 static const char *const optim_symbols[] = { "*.constprop.*", NULL };
865 XXXINIT_TO_SOME_INIT,
866 ANY_INIT_TO_ANY_EXIT,
867 ANY_EXIT_TO_ANY_INIT,
873 * Describe how to match sections on different criteria:
875 * @fromsec: Array of sections to be matched.
877 * @bad_tosec: Relocations applied to a section in @fromsec to a section in
878 * this array is forbidden (black-list). Can be empty.
880 * @good_tosec: Relocations applied to a section in @fromsec must be
881 * targeting sections in this array (white-list). Can be empty.
883 * @mismatch: Type of mismatch.
885 * @handler: Specific handler to call when a match is found. If NULL,
886 * default_mismatch_handler() will be called.
889 struct sectioncheck {
890 const char *fromsec[20];
891 const char *bad_tosec[20];
892 const char *good_tosec[20];
893 enum mismatch mismatch;
894 void (*handler)(const char *modname, struct elf_info *elf,
895 const struct sectioncheck* const mismatch,
896 Elf_Rela *r, Elf_Sym *sym, const char *fromsec);
900 static void extable_mismatch_handler(const char *modname, struct elf_info *elf,
901 const struct sectioncheck* const mismatch,
902 Elf_Rela *r, Elf_Sym *sym,
903 const char *fromsec);
905 static const struct sectioncheck sectioncheck[] = {
906 /* Do not reference init/exit code/data from
907 * normal code and data
910 .fromsec = { TEXT_SECTIONS, NULL },
911 .bad_tosec = { ALL_INIT_SECTIONS, NULL },
912 .mismatch = TEXT_TO_ANY_INIT,
915 .fromsec = { DATA_SECTIONS, NULL },
916 .bad_tosec = { ALL_XXXINIT_SECTIONS, NULL },
917 .mismatch = DATA_TO_ANY_INIT,
920 .fromsec = { DATA_SECTIONS, NULL },
921 .bad_tosec = { INIT_SECTIONS, NULL },
922 .mismatch = DATA_TO_ANY_INIT,
925 .fromsec = { TEXT_SECTIONS, NULL },
926 .bad_tosec = { ALL_EXIT_SECTIONS, NULL },
927 .mismatch = TEXT_TO_ANY_EXIT,
930 .fromsec = { DATA_SECTIONS, NULL },
931 .bad_tosec = { ALL_EXIT_SECTIONS, NULL },
932 .mismatch = DATA_TO_ANY_EXIT,
934 /* Do not reference init code/data from meminit code/data */
936 .fromsec = { ALL_XXXINIT_SECTIONS, NULL },
937 .bad_tosec = { INIT_SECTIONS, NULL },
938 .mismatch = XXXINIT_TO_SOME_INIT,
940 /* Do not use exit code/data from init code */
942 .fromsec = { ALL_INIT_SECTIONS, NULL },
943 .bad_tosec = { ALL_EXIT_SECTIONS, NULL },
944 .mismatch = ANY_INIT_TO_ANY_EXIT,
946 /* Do not use init code/data from exit code */
948 .fromsec = { ALL_EXIT_SECTIONS, NULL },
949 .bad_tosec = { ALL_INIT_SECTIONS, NULL },
950 .mismatch = ANY_EXIT_TO_ANY_INIT,
953 .fromsec = { ALL_PCI_INIT_SECTIONS, NULL },
954 .bad_tosec = { INIT_SECTIONS, NULL },
955 .mismatch = ANY_INIT_TO_ANY_EXIT,
957 /* Do not export init/exit functions or data */
959 .fromsec = { "___ksymtab*", NULL },
960 .bad_tosec = { INIT_SECTIONS, EXIT_SECTIONS, NULL },
961 .mismatch = EXPORT_TO_INIT_EXIT,
964 .fromsec = { "__ex_table", NULL },
965 /* If you're adding any new black-listed sections in here, consider
966 * adding a special 'printer' for them in scripts/check_extable.
968 .bad_tosec = { ".altinstr_replacement", NULL },
969 .good_tosec = {ALL_TEXT_SECTIONS , NULL},
970 .mismatch = EXTABLE_TO_NON_TEXT,
971 .handler = extable_mismatch_handler,
975 static const struct sectioncheck *section_mismatch(
976 const char *fromsec, const char *tosec)
981 * The target section could be the SHT_NUL section when we're
982 * handling relocations to un-resolved symbols, trying to match it
983 * doesn't make much sense and causes build failures on parisc
989 for (i = 0; i < ARRAY_SIZE(sectioncheck); i++) {
990 const struct sectioncheck *check = §ioncheck[i];
992 if (match(fromsec, check->fromsec)) {
993 if (check->bad_tosec[0] && match(tosec, check->bad_tosec))
995 if (check->good_tosec[0] && !match(tosec, check->good_tosec))
1003 * Whitelist to allow certain references to pass with no warning.
1006 * If a module parameter is declared __initdata and permissions=0
1007 * then this is legal despite the warning generated.
1008 * We cannot see value of permissions here, so just ignore
1010 * The pattern is identified by:
1011 * tosec = .init.data
1016 * module_param_call() ops can refer to __init set function if permissions=0
1017 * The pattern is identified by:
1018 * tosec = .init.text
1020 * atsym = __param_ops_*
1023 * Whitelist all references from .head.text to any init section
1026 * Some symbols belong to init section but still it is ok to reference
1027 * these from non-init sections as these symbols don't have any memory
1028 * allocated for them and symbol address and value are same. So even
1029 * if init section is freed, its ok to reference those symbols.
1030 * For ex. symbols marking the init section boundaries.
1031 * This pattern is identified by
1032 * refsymname = __init_begin, _sinittext, _einittext
1035 * GCC may optimize static inlines when fed constant arg(s) resulting
1036 * in functions like cpumask_empty() -- generating an associated symbol
1037 * cpumask_empty.constprop.3 that appears in the audit. If the const that
1038 * is passed in comes from __init, like say nmi_ipi_mask, we get a
1039 * meaningless section warning. May need to add isra symbols too...
1040 * This pattern is identified by
1041 * tosec = init section
1042 * fromsec = text section
1043 * refsymname = *.constprop.*
1046 * Hide section mismatch warnings for ELF local symbols. The goal
1047 * is to eliminate false positive modpost warnings caused by
1048 * compiler-generated ELF local symbol names such as ".LANCHOR1".
1049 * Autogenerated symbol names bypass modpost's "Pattern 2"
1050 * whitelisting, which relies on pattern-matching against symbol
1051 * names to work. (One situation where gcc can autogenerate ELF
1052 * local symbols is when "-fsection-anchors" is used.)
1054 static int secref_whitelist(const struct sectioncheck *mismatch,
1055 const char *fromsec, const char *fromsym,
1056 const char *tosec, const char *tosym)
1058 /* Check for pattern 1 */
1059 if (match(tosec, init_data_sections) &&
1060 match(fromsec, data_sections) &&
1061 strstarts(fromsym, "__param"))
1064 /* Check for pattern 1a */
1065 if (strcmp(tosec, ".init.text") == 0 &&
1066 match(fromsec, data_sections) &&
1067 strstarts(fromsym, "__param_ops_"))
1070 /* symbols in data sections that may refer to any init/exit sections */
1071 if (match(fromsec, PATTERNS(DATA_SECTIONS)) &&
1072 match(tosec, PATTERNS(ALL_INIT_SECTIONS, ALL_EXIT_SECTIONS)) &&
1073 match(fromsym, PATTERNS("*_template", // scsi uses *_template a lot
1074 "*_timer", // arm uses ops structures named _timer a lot
1075 "*_sht", // scsi also used *_sht to some extent
1082 /* symbols in data sections that may refer to meminit sections */
1083 if (match(fromsec, PATTERNS(DATA_SECTIONS)) &&
1084 match(tosec, PATTERNS(ALL_XXXINIT_SECTIONS)) &&
1085 match(fromsym, PATTERNS("*driver")))
1089 * symbols in data sections must not refer to .exit.*, but there are
1090 * quite a few offenders, so hide these unless for W=1 builds until
1094 match(fromsec, PATTERNS(DATA_SECTIONS)) &&
1095 match(tosec, PATTERNS(EXIT_SECTIONS)) &&
1096 match(fromsym, PATTERNS("*driver")))
1099 /* Check for pattern 3 */
1100 if (match(fromsec, head_sections) &&
1101 match(tosec, init_sections))
1104 /* Check for pattern 4 */
1105 if (match(tosym, linker_symbols))
1108 /* Check for pattern 5 */
1109 if (match(fromsec, text_sections) &&
1110 match(tosec, init_sections) &&
1111 match(fromsym, optim_symbols))
1114 /* Check for pattern 6 */
1115 if (strstarts(fromsym, ".L"))
1121 static inline int is_arm_mapping_symbol(const char *str)
1123 return str[0] == '$' &&
1124 (str[1] == 'a' || str[1] == 'd' || str[1] == 't' || str[1] == 'x')
1125 && (str[2] == '\0' || str[2] == '.');
1129 * If there's no name there, ignore it; likewise, ignore it if it's
1130 * one of the magic symbols emitted used by current ARM tools.
1132 * Otherwise if find_symbols_between() returns those symbols, they'll
1133 * fail the whitelist tests and cause lots of false alarms ... fixable
1134 * only by merging __exit and __init sections into __text, bloating
1135 * the kernel (which is especially evil on embedded platforms).
1137 static inline int is_valid_name(struct elf_info *elf, Elf_Sym *sym)
1139 const char *name = elf->strtab + sym->st_name;
1141 if (!name || !strlen(name))
1143 return !is_arm_mapping_symbol(name);
1147 * Find symbol based on relocation record info.
1148 * In some cases the symbol supplied is a valid symbol so
1149 * return refsym. If st_name != 0 we assume this is a valid symbol.
1150 * In other cases the symbol needs to be looked up in the symbol table
1151 * based on section and address.
1153 static Elf_Sym *find_elf_symbol(struct elf_info *elf, Elf64_Sword addr,
1157 Elf_Sym *near = NULL;
1158 Elf64_Sword distance = 20;
1160 unsigned int relsym_secindex;
1162 if (relsym->st_name != 0)
1166 * Strive to find a better symbol name, but the resulting name may not
1167 * match the symbol referenced in the original code.
1169 relsym_secindex = get_secindex(elf, relsym);
1170 for (sym = elf->symtab_start; sym < elf->symtab_stop; sym++) {
1171 if (get_secindex(elf, sym) != relsym_secindex)
1173 if (ELF_ST_TYPE(sym->st_info) == STT_SECTION)
1175 if (!is_valid_name(elf, sym))
1177 if (sym->st_value == addr)
1179 /* Find a symbol nearby - addr are maybe negative */
1180 d = sym->st_value - addr;
1182 d = addr - sym->st_value;
1188 /* We need a close match */
1196 * Find symbols before or equal addr and after addr - in the section sec.
1197 * If we find two symbols with equal offset prefer one with a valid name.
1198 * The ELF format may have a better way to detect what type of symbol
1199 * it is, but this works for now.
1201 static Elf_Sym *find_elf_symbol2(struct elf_info *elf, Elf_Addr addr,
1205 Elf_Sym *near = NULL;
1206 Elf_Addr distance = ~0;
1208 for (sym = elf->symtab_start; sym < elf->symtab_stop; sym++) {
1211 if (is_shndx_special(sym->st_shndx))
1213 symsec = sec_name(elf, get_secindex(elf, sym));
1214 if (strcmp(symsec, sec) != 0)
1216 if (!is_valid_name(elf, sym))
1218 if (sym->st_value <= addr && addr - sym->st_value <= distance) {
1219 distance = addr - sym->st_value;
1226 static int is_function(Elf_Sym *sym)
1229 return ELF_ST_TYPE(sym->st_info) == STT_FUNC;
1234 static inline void get_pretty_name(int is_func, const char** name, const char** name_p)
1237 case 0: *name = "variable"; *name_p = ""; break;
1238 case 1: *name = "function"; *name_p = "()"; break;
1239 default: *name = "(unknown reference)"; *name_p = ""; break;
1244 * Print a warning about a section mismatch.
1245 * Try to find symbols near it so user can find it.
1246 * Check whitelist before warning - it may be a false positive.
1248 static void report_sec_mismatch(const char *modname,
1249 const struct sectioncheck *mismatch,
1250 const char *fromsec,
1251 const char *fromsym,
1252 const char *tosec, const char *tosym)
1254 sec_mismatch_count++;
1256 switch (mismatch->mismatch) {
1257 case TEXT_TO_ANY_INIT:
1258 case DATA_TO_ANY_INIT:
1259 case TEXT_TO_ANY_EXIT:
1260 case DATA_TO_ANY_EXIT:
1261 case XXXINIT_TO_SOME_INIT:
1262 case ANY_INIT_TO_ANY_EXIT:
1263 case ANY_EXIT_TO_ANY_INIT:
1264 warn("%s: section mismatch in reference: %s (section: %s) -> %s (section: %s)\n",
1265 modname, fromsym, fromsec, tosym, tosec);
1267 case EXPORT_TO_INIT_EXIT:
1268 warn("%s: EXPORT_SYMBOL used for init/exit symbol: %s (section: %s)\n",
1269 modname, tosym, tosec);
1271 case EXTABLE_TO_NON_TEXT:
1272 fatal("There's a special handler for this mismatch type, we should never get here.\n");
1277 static void default_mismatch_handler(const char *modname, struct elf_info *elf,
1278 const struct sectioncheck* const mismatch,
1279 Elf_Rela *r, Elf_Sym *sym, const char *fromsec)
1285 const char *fromsym;
1287 from = find_elf_symbol2(elf, r->r_offset, fromsec);
1288 fromsym = sym_name(elf, from);
1290 tosec = sec_name(elf, get_secindex(elf, sym));
1291 to = find_elf_symbol(elf, r->r_addend, sym);
1292 tosym = sym_name(elf, to);
1294 /* check whitelist - we may ignore it */
1295 if (secref_whitelist(mismatch,
1296 fromsec, fromsym, tosec, tosym)) {
1297 report_sec_mismatch(modname, mismatch,
1298 fromsec, fromsym, tosec, tosym);
1302 static int is_executable_section(struct elf_info* elf, unsigned int section_index)
1304 if (section_index >= elf->num_sections)
1305 fatal("section_index is outside elf->num_sections!\n");
1307 return ((elf->sechdrs[section_index].sh_flags & SHF_EXECINSTR) == SHF_EXECINSTR);
1310 static void report_extable_warnings(const char* modname, struct elf_info* elf,
1311 const struct sectioncheck* const mismatch,
1312 Elf_Rela* r, Elf_Sym* sym,
1313 const char* fromsec, const char* tosec)
1315 Elf_Sym* fromsym = find_elf_symbol2(elf, r->r_offset, fromsec);
1316 const char* fromsym_name = sym_name(elf, fromsym);
1317 Elf_Sym* tosym = find_elf_symbol(elf, r->r_addend, sym);
1318 const char* tosym_name = sym_name(elf, tosym);
1319 const char* from_pretty_name;
1320 const char* from_pretty_name_p;
1321 const char* to_pretty_name;
1322 const char* to_pretty_name_p;
1324 get_pretty_name(is_function(fromsym),
1325 &from_pretty_name, &from_pretty_name_p);
1326 get_pretty_name(is_function(tosym),
1327 &to_pretty_name, &to_pretty_name_p);
1329 warn("%s(%s+0x%lx): Section mismatch in reference"
1330 " from the %s %s%s to the %s %s:%s%s\n",
1331 modname, fromsec, (long)r->r_offset, from_pretty_name,
1332 fromsym_name, from_pretty_name_p,
1333 to_pretty_name, tosec, tosym_name, to_pretty_name_p);
1335 if (!match(tosec, mismatch->bad_tosec) &&
1336 is_executable_section(elf, get_secindex(elf, sym)))
1338 "The relocation at %s+0x%lx references\n"
1339 "section \"%s\" which is not in the list of\n"
1340 "authorized sections. If you're adding a new section\n"
1341 "and/or if this reference is valid, add \"%s\" to the\n"
1342 "list of authorized sections to jump to on fault.\n"
1343 "This can be achieved by adding \"%s\" to \n"
1344 "OTHER_TEXT_SECTIONS in scripts/mod/modpost.c.\n",
1345 fromsec, (long)r->r_offset, tosec, tosec, tosec);
1348 static void extable_mismatch_handler(const char* modname, struct elf_info *elf,
1349 const struct sectioncheck* const mismatch,
1350 Elf_Rela* r, Elf_Sym* sym,
1351 const char *fromsec)
1353 const char* tosec = sec_name(elf, get_secindex(elf, sym));
1355 sec_mismatch_count++;
1357 report_extable_warnings(modname, elf, mismatch, r, sym, fromsec, tosec);
1359 if (match(tosec, mismatch->bad_tosec))
1360 fatal("The relocation at %s+0x%lx references\n"
1361 "section \"%s\" which is black-listed.\n"
1362 "Something is seriously wrong and should be fixed.\n"
1363 "You might get more information about where this is\n"
1364 "coming from by using scripts/check_extable.sh %s\n",
1365 fromsec, (long)r->r_offset, tosec, modname);
1366 else if (!is_executable_section(elf, get_secindex(elf, sym)))
1367 error("%s+0x%lx references non-executable section '%s'\n",
1368 fromsec, (long)r->r_offset, tosec);
1371 static void check_section_mismatch(const char *modname, struct elf_info *elf,
1372 Elf_Rela *r, Elf_Sym *sym, const char *fromsec)
1374 const char *tosec = sec_name(elf, get_secindex(elf, sym));
1375 const struct sectioncheck *mismatch = section_mismatch(fromsec, tosec);
1378 if (mismatch->handler)
1379 mismatch->handler(modname, elf, mismatch,
1382 default_mismatch_handler(modname, elf, mismatch,
1387 static unsigned int *reloc_location(struct elf_info *elf,
1388 Elf_Shdr *sechdr, Elf_Rela *r)
1390 return sym_get_data_by_offset(elf, sechdr->sh_info, r->r_offset);
1393 static int addend_386_rel(struct elf_info *elf, Elf_Shdr *sechdr, Elf_Rela *r)
1395 unsigned int r_typ = ELF_R_TYPE(r->r_info);
1396 unsigned int *location = reloc_location(elf, sechdr, r);
1400 r->r_addend = TO_NATIVE(*location);
1403 r->r_addend = TO_NATIVE(*location) + 4;
1410 #define R_ARM_CALL 28
1412 #ifndef R_ARM_JUMP24
1413 #define R_ARM_JUMP24 29
1416 #ifndef R_ARM_THM_CALL
1417 #define R_ARM_THM_CALL 10
1419 #ifndef R_ARM_THM_JUMP24
1420 #define R_ARM_THM_JUMP24 30
1422 #ifndef R_ARM_THM_JUMP19
1423 #define R_ARM_THM_JUMP19 51
1426 static int32_t sign_extend32(int32_t value, int index)
1428 uint8_t shift = 31 - index;
1430 return (int32_t)(value << shift) >> shift;
1433 static int addend_arm_rel(struct elf_info *elf, Elf_Shdr *sechdr, Elf_Rela *r)
1435 unsigned int r_typ = ELF_R_TYPE(r->r_info);
1436 Elf_Sym *sym = elf->symtab_start + ELF_R_SYM(r->r_info);
1437 void *loc = reloc_location(elf, sechdr, r);
1443 inst = TO_NATIVE(*(uint32_t *)loc);
1444 r->r_addend = inst + sym->st_value;
1449 inst = TO_NATIVE(*(uint32_t *)loc);
1450 offset = sign_extend32((inst & 0x00ffffff) << 2, 25);
1451 r->r_addend = offset + sym->st_value + 8;
1453 case R_ARM_THM_CALL:
1454 case R_ARM_THM_JUMP24:
1455 case R_ARM_THM_JUMP19:
1456 /* From ARM ABI: ((S + A) | T) - P */
1457 r->r_addend = (int)(long)(elf->hdr +
1459 (r->r_offset - sechdr->sh_addr));
1467 static int addend_mips_rel(struct elf_info *elf, Elf_Shdr *sechdr, Elf_Rela *r)
1469 unsigned int r_typ = ELF_R_TYPE(r->r_info);
1470 unsigned int *location = reloc_location(elf, sechdr, r);
1473 if (r_typ == R_MIPS_HI16)
1474 return 1; /* skip this */
1475 inst = TO_NATIVE(*location);
1478 r->r_addend = inst & 0xffff;
1481 r->r_addend = (inst & 0x03ffffff) << 2;
1491 #define EM_RISCV 243
1494 #ifndef R_RISCV_SUB32
1495 #define R_RISCV_SUB32 39
1498 static void section_rela(const char *modname, struct elf_info *elf,
1505 const char *fromsec;
1507 Elf_Rela *start = (void *)elf->hdr + sechdr->sh_offset;
1508 Elf_Rela *stop = (void *)start + sechdr->sh_size;
1510 fromsec = sec_name(elf, sechdr->sh_info);
1511 /* if from section (name) is know good then skip it */
1512 if (match(fromsec, section_white_list))
1515 for (rela = start; rela < stop; rela++) {
1516 r.r_offset = TO_NATIVE(rela->r_offset);
1517 #if KERNEL_ELFCLASS == ELFCLASS64
1518 if (elf->hdr->e_machine == EM_MIPS) {
1520 r_sym = ELF64_MIPS_R_SYM(rela->r_info);
1521 r_sym = TO_NATIVE(r_sym);
1522 r_typ = ELF64_MIPS_R_TYPE(rela->r_info);
1523 r.r_info = ELF64_R_INFO(r_sym, r_typ);
1525 r.r_info = TO_NATIVE(rela->r_info);
1526 r_sym = ELF_R_SYM(r.r_info);
1529 r.r_info = TO_NATIVE(rela->r_info);
1530 r_sym = ELF_R_SYM(r.r_info);
1532 r.r_addend = TO_NATIVE(rela->r_addend);
1533 switch (elf->hdr->e_machine) {
1535 if (!strcmp("__ex_table", fromsec) &&
1536 ELF_R_TYPE(r.r_info) == R_RISCV_SUB32)
1540 sym = elf->symtab_start + r_sym;
1541 /* Skip special sections */
1542 if (is_shndx_special(sym->st_shndx))
1544 check_section_mismatch(modname, elf, &r, sym, fromsec);
1548 static void section_rel(const char *modname, struct elf_info *elf,
1555 const char *fromsec;
1557 Elf_Rel *start = (void *)elf->hdr + sechdr->sh_offset;
1558 Elf_Rel *stop = (void *)start + sechdr->sh_size;
1560 fromsec = sec_name(elf, sechdr->sh_info);
1561 /* if from section (name) is know good then skip it */
1562 if (match(fromsec, section_white_list))
1565 for (rel = start; rel < stop; rel++) {
1566 r.r_offset = TO_NATIVE(rel->r_offset);
1567 #if KERNEL_ELFCLASS == ELFCLASS64
1568 if (elf->hdr->e_machine == EM_MIPS) {
1570 r_sym = ELF64_MIPS_R_SYM(rel->r_info);
1571 r_sym = TO_NATIVE(r_sym);
1572 r_typ = ELF64_MIPS_R_TYPE(rel->r_info);
1573 r.r_info = ELF64_R_INFO(r_sym, r_typ);
1575 r.r_info = TO_NATIVE(rel->r_info);
1576 r_sym = ELF_R_SYM(r.r_info);
1579 r.r_info = TO_NATIVE(rel->r_info);
1580 r_sym = ELF_R_SYM(r.r_info);
1583 switch (elf->hdr->e_machine) {
1585 if (addend_386_rel(elf, sechdr, &r))
1589 if (addend_arm_rel(elf, sechdr, &r))
1593 if (addend_mips_rel(elf, sechdr, &r))
1597 sym = elf->symtab_start + r_sym;
1598 /* Skip special sections */
1599 if (is_shndx_special(sym->st_shndx))
1601 check_section_mismatch(modname, elf, &r, sym, fromsec);
1606 * A module includes a number of sections that are discarded
1607 * either when loaded or when used as built-in.
1608 * For loaded modules all functions marked __init and all data
1609 * marked __initdata will be discarded when the module has been initialized.
1610 * Likewise for modules used built-in the sections marked __exit
1611 * are discarded because __exit marked function are supposed to be called
1612 * only when a module is unloaded which never happens for built-in modules.
1613 * The check_sec_ref() function traverses all relocation records
1614 * to find all references to a section that reference a section that will
1615 * be discarded and warns about it.
1617 static void check_sec_ref(const char *modname, struct elf_info *elf)
1620 Elf_Shdr *sechdrs = elf->sechdrs;
1622 /* Walk through all sections */
1623 for (i = 0; i < elf->num_sections; i++) {
1624 check_section(modname, elf, &elf->sechdrs[i]);
1625 /* We want to process only relocation sections and not .init */
1626 if (sechdrs[i].sh_type == SHT_RELA)
1627 section_rela(modname, elf, &elf->sechdrs[i]);
1628 else if (sechdrs[i].sh_type == SHT_REL)
1629 section_rel(modname, elf, &elf->sechdrs[i]);
1633 static char *remove_dot(char *s)
1635 size_t n = strcspn(s, ".");
1638 size_t m = strspn(s + n + 1, "0123456789");
1639 if (m && (s[n + m + 1] == '.' || s[n + m + 1] == 0))
1646 * The CRCs are recorded in .*.cmd files in the form of:
1647 * #SYMVER <name> <crc>
1649 static void extract_crcs_for_object(const char *object, struct module *mod)
1651 char cmd_file[PATH_MAX];
1656 base = strrchr(object, '/');
1659 dirlen = base - object;
1665 ret = snprintf(cmd_file, sizeof(cmd_file), "%.*s.%s.cmd",
1666 dirlen, object, base);
1667 if (ret >= sizeof(cmd_file)) {
1668 error("%s: too long path was truncated\n", cmd_file);
1672 buf = read_text_file(cmd_file);
1675 while ((p = strstr(p, "\n#SYMVER "))) {
1681 name = p + strlen("\n#SYMVER ");
1683 p = strchr(name, ' ');
1691 continue; /* skip this line */
1693 crc = strtoul(p, &p, 0);
1695 continue; /* skip this line */
1697 name[namelen] = '\0';
1700 * sym_find_with_module() may return NULL here.
1701 * It typically occurs when CONFIG_TRIM_UNUSED_KSYMS=y.
1702 * Since commit e1327a127703, genksyms calculates CRCs of all
1703 * symbols, including trimmed ones. Ignore orphan CRCs.
1705 sym = sym_find_with_module(name, mod);
1707 sym_set_crc(sym, crc);
1714 * The symbol versions (CRC) are recorded in the .*.cmd files.
1715 * Parse them to retrieve CRCs for the current module.
1717 static void mod_set_crcs(struct module *mod)
1719 char objlist[PATH_MAX];
1720 char *buf, *p, *obj;
1723 if (mod->is_vmlinux) {
1724 strcpy(objlist, ".vmlinux.objs");
1726 /* objects for a module are listed in the *.mod file. */
1727 ret = snprintf(objlist, sizeof(objlist), "%s.mod", mod->name);
1728 if (ret >= sizeof(objlist)) {
1729 error("%s: too long path was truncated\n", objlist);
1734 buf = read_text_file(objlist);
1737 while ((obj = strsep(&p, "\n")) && obj[0])
1738 extract_crcs_for_object(obj, mod);
1743 static void read_symbols(const char *modname)
1745 const char *symname;
1750 struct elf_info info = { };
1753 if (!parse_elf(&info, modname))
1756 if (!strends(modname, ".o")) {
1757 error("%s: filename must be suffixed with .o\n", modname);
1761 /* strip trailing .o */
1762 mod = new_module(modname, strlen(modname) - strlen(".o"));
1764 if (!mod->is_vmlinux) {
1765 license = get_modinfo(&info, "license");
1767 error("missing MODULE_LICENSE() in %s\n", modname);
1769 if (!license_is_gpl_compatible(license)) {
1770 mod->is_gpl_compatible = false;
1773 license = get_next_modinfo(&info, "license", license);
1776 namespace = get_modinfo(&info, "import_ns");
1778 add_namespace(&mod->imported_namespaces, namespace);
1779 namespace = get_next_modinfo(&info, "import_ns",
1784 for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
1785 symname = remove_dot(info.strtab + sym->st_name);
1787 handle_symbol(mod, &info, sym, symname);
1788 handle_moddevtable(mod, &info, sym, symname);
1791 for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
1792 symname = remove_dot(info.strtab + sym->st_name);
1794 /* Apply symbol namespaces from __kstrtabns_<symbol> entries. */
1795 if (strstarts(symname, "__kstrtabns_"))
1796 sym_update_namespace(symname + strlen("__kstrtabns_"),
1797 sym_get_data(&info, sym));
1800 check_sec_ref(modname, &info);
1802 if (!mod->is_vmlinux) {
1803 version = get_modinfo(&info, "version");
1804 if (version || all_versions)
1805 get_src_version(mod->name, mod->srcversion,
1806 sizeof(mod->srcversion) - 1);
1809 parse_elf_finish(&info);
1813 * Our trick to get versioning for module struct etc. - it's
1814 * never passed as an argument to an exported function, so
1815 * the automatic versioning doesn't pick it up, but it's really
1818 sym_add_unresolved("module_layout", mod, false);
1824 static void read_symbols_from_files(const char *filename)
1827 char fname[PATH_MAX];
1829 if (strcmp(filename, "-") != 0) {
1830 in = fopen(filename, "r");
1832 fatal("Can't open filenames file %s: %m", filename);
1835 while (fgets(fname, PATH_MAX, in) != NULL) {
1836 if (strends(fname, "\n"))
1837 fname[strlen(fname)-1] = '\0';
1838 read_symbols(fname);
1847 /* We first write the generated file into memory using the
1848 * following helper, then compare to the file on disk and
1849 * only update the later if anything changed */
1851 void __attribute__((format(printf, 2, 3))) buf_printf(struct buffer *buf,
1852 const char *fmt, ...)
1859 len = vsnprintf(tmp, SZ, fmt, ap);
1860 buf_write(buf, tmp, len);
1864 void buf_write(struct buffer *buf, const char *s, int len)
1866 if (buf->size - buf->pos < len) {
1867 buf->size += len + SZ;
1868 buf->p = NOFAIL(realloc(buf->p, buf->size));
1870 strncpy(buf->p + buf->pos, s, len);
1874 static void check_exports(struct module *mod)
1876 struct symbol *s, *exp;
1878 list_for_each_entry(s, &mod->unresolved_symbols, list) {
1879 const char *basename;
1880 exp = find_symbol(s->name);
1882 if (!s->weak && nr_unresolved++ < MAX_UNRESOLVED_REPORTS)
1883 modpost_log(warn_unresolved ? LOG_WARN : LOG_ERROR,
1884 "\"%s\" [%s.ko] undefined!\n",
1885 s->name, mod->name);
1888 if (exp->module == mod) {
1889 error("\"%s\" [%s.ko] was exported without definition\n",
1890 s->name, mod->name);
1894 s->module = exp->module;
1895 s->crc_valid = exp->crc_valid;
1898 basename = strrchr(mod->name, '/');
1902 basename = mod->name;
1904 if (exp->namespace &&
1905 !contains_namespace(&mod->imported_namespaces, exp->namespace)) {
1906 modpost_log(allow_missing_ns_imports ? LOG_WARN : LOG_ERROR,
1907 "module %s uses symbol %s from namespace %s, but does not import it.\n",
1908 basename, exp->name, exp->namespace);
1909 add_namespace(&mod->missing_namespaces, exp->namespace);
1912 if (!mod->is_gpl_compatible && exp->is_gpl_only)
1913 error("GPL-incompatible module %s.ko uses GPL-only symbol '%s'\n",
1914 basename, exp->name);
1918 static void check_modname_len(struct module *mod)
1920 const char *mod_name;
1922 mod_name = strrchr(mod->name, '/');
1923 if (mod_name == NULL)
1924 mod_name = mod->name;
1927 if (strlen(mod_name) >= MODULE_NAME_LEN)
1928 error("module name is too long [%s.ko]\n", mod->name);
1932 * Header for the generated file
1934 static void add_header(struct buffer *b, struct module *mod)
1936 buf_printf(b, "#include <linux/module.h>\n");
1938 * Include build-salt.h after module.h in order to
1939 * inherit the definitions.
1941 buf_printf(b, "#define INCLUDE_VERMAGIC\n");
1942 buf_printf(b, "#include <linux/build-salt.h>\n");
1943 buf_printf(b, "#include <linux/elfnote-lto.h>\n");
1944 buf_printf(b, "#include <linux/export-internal.h>\n");
1945 buf_printf(b, "#include <linux/vermagic.h>\n");
1946 buf_printf(b, "#include <linux/compiler.h>\n");
1947 buf_printf(b, "\n");
1948 buf_printf(b, "BUILD_SALT;\n");
1949 buf_printf(b, "BUILD_LTO_INFO;\n");
1950 buf_printf(b, "\n");
1951 buf_printf(b, "MODULE_INFO(vermagic, VERMAGIC_STRING);\n");
1952 buf_printf(b, "MODULE_INFO(name, KBUILD_MODNAME);\n");
1953 buf_printf(b, "\n");
1954 buf_printf(b, "__visible struct module __this_module\n");
1955 buf_printf(b, "__section(\".gnu.linkonce.this_module\") = {\n");
1956 buf_printf(b, "\t.name = KBUILD_MODNAME,\n");
1958 buf_printf(b, "\t.init = init_module,\n");
1959 if (mod->has_cleanup)
1960 buf_printf(b, "#ifdef CONFIG_MODULE_UNLOAD\n"
1961 "\t.exit = cleanup_module,\n"
1963 buf_printf(b, "\t.arch = MODULE_ARCH_INIT,\n");
1964 buf_printf(b, "};\n");
1966 if (!external_module)
1967 buf_printf(b, "\nMODULE_INFO(intree, \"Y\");\n");
1971 "#ifdef CONFIG_RETPOLINE\n"
1972 "MODULE_INFO(retpoline, \"Y\");\n"
1975 if (strstarts(mod->name, "drivers/staging"))
1976 buf_printf(b, "\nMODULE_INFO(staging, \"Y\");\n");
1978 if (strstarts(mod->name, "tools/testing"))
1979 buf_printf(b, "\nMODULE_INFO(test, \"Y\");\n");
1982 static void add_exported_symbols(struct buffer *buf, struct module *mod)
1989 /* record CRCs for exported symbols */
1990 buf_printf(buf, "\n");
1991 list_for_each_entry(sym, &mod->exported_symbols, list) {
1992 if (!sym->crc_valid)
1993 warn("EXPORT symbol \"%s\" [%s%s] version generation failed, symbol will not be versioned.\n"
1994 "Is \"%s\" prototyped in <asm/asm-prototypes.h>?\n",
1995 sym->name, mod->name, mod->is_vmlinux ? "" : ".ko",
1998 buf_printf(buf, "SYMBOL_CRC(%s, 0x%08x, \"%s\");\n",
1999 sym->name, sym->crc, sym->is_gpl_only ? "_gpl" : "");
2004 * Record CRCs for unresolved symbols
2006 static void add_versions(struct buffer *b, struct module *mod)
2013 buf_printf(b, "\n");
2014 buf_printf(b, "static const struct modversion_info ____versions[]\n");
2015 buf_printf(b, "__used __section(\"__versions\") = {\n");
2017 list_for_each_entry(s, &mod->unresolved_symbols, list) {
2020 if (!s->crc_valid) {
2021 warn("\"%s\" [%s.ko] has no CRC!\n",
2022 s->name, mod->name);
2025 if (strlen(s->name) >= MODULE_NAME_LEN) {
2026 error("too long symbol \"%s\" [%s.ko]\n",
2027 s->name, mod->name);
2030 buf_printf(b, "\t{ %#8x, \"%s\" },\n",
2034 buf_printf(b, "};\n");
2037 static void add_depends(struct buffer *b, struct module *mod)
2042 /* Clear ->seen flag of modules that own symbols needed by this. */
2043 list_for_each_entry(s, &mod->unresolved_symbols, list) {
2045 s->module->seen = s->module->is_vmlinux;
2048 buf_printf(b, "\n");
2049 buf_printf(b, "MODULE_INFO(depends, \"");
2050 list_for_each_entry(s, &mod->unresolved_symbols, list) {
2055 if (s->module->seen)
2058 s->module->seen = true;
2059 p = strrchr(s->module->name, '/');
2063 p = s->module->name;
2064 buf_printf(b, "%s%s", first ? "" : ",", p);
2067 buf_printf(b, "\");\n");
2070 static void add_srcversion(struct buffer *b, struct module *mod)
2072 if (mod->srcversion[0]) {
2073 buf_printf(b, "\n");
2074 buf_printf(b, "MODULE_INFO(srcversion, \"%s\");\n",
2079 static void write_buf(struct buffer *b, const char *fname)
2086 file = fopen(fname, "w");
2091 if (fwrite(b->p, 1, b->pos, file) != b->pos) {
2095 if (fclose(file) != 0) {
2101 static void write_if_changed(struct buffer *b, const char *fname)
2107 file = fopen(fname, "r");
2111 if (fstat(fileno(file), &st) < 0)
2114 if (st.st_size != b->pos)
2117 tmp = NOFAIL(malloc(b->pos));
2118 if (fread(tmp, 1, b->pos, file) != b->pos)
2121 if (memcmp(tmp, b->p, b->pos) != 0)
2133 write_buf(b, fname);
2136 static void write_vmlinux_export_c_file(struct module *mod)
2138 struct buffer buf = { };
2141 "#include <linux/export-internal.h>\n");
2143 add_exported_symbols(&buf, mod);
2144 write_if_changed(&buf, ".vmlinux.export.c");
2148 /* do sanity checks, and generate *.mod.c file */
2149 static void write_mod_c_file(struct module *mod)
2151 struct buffer buf = { };
2152 char fname[PATH_MAX];
2155 check_modname_len(mod);
2158 add_header(&buf, mod);
2159 add_exported_symbols(&buf, mod);
2160 add_versions(&buf, mod);
2161 add_depends(&buf, mod);
2162 add_moddevtable(&buf, mod);
2163 add_srcversion(&buf, mod);
2165 ret = snprintf(fname, sizeof(fname), "%s.mod.c", mod->name);
2166 if (ret >= sizeof(fname)) {
2167 error("%s: too long path was truncated\n", fname);
2171 write_if_changed(&buf, fname);
2177 /* parse Module.symvers file. line format:
2178 * 0x12345678<tab>symbol<tab>module<tab>export<tab>namespace
2180 static void read_dump(const char *fname)
2182 char *buf, *pos, *line;
2184 buf = read_text_file(fname);
2186 /* No symbol versions, silently ignore */
2191 while ((line = get_line(&pos))) {
2192 char *symname, *namespace, *modname, *d, *export;
2198 if (!(symname = strchr(line, '\t')))
2201 if (!(modname = strchr(symname, '\t')))
2204 if (!(export = strchr(modname, '\t')))
2207 if (!(namespace = strchr(export, '\t')))
2209 *namespace++ = '\0';
2211 crc = strtoul(line, &d, 16);
2212 if (*symname == '\0' || *modname == '\0' || *d != '\0')
2215 if (!strcmp(export, "EXPORT_SYMBOL_GPL")) {
2217 } else if (!strcmp(export, "EXPORT_SYMBOL")) {
2220 error("%s: unknown license %s. skip", symname, export);
2224 mod = find_module(modname);
2226 mod = new_module(modname, strlen(modname));
2227 mod->from_dump = true;
2229 s = sym_add_exported(symname, mod, gpl_only);
2230 sym_set_crc(s, crc);
2231 sym_update_namespace(symname, namespace);
2237 fatal("parse error in symbol dump file\n");
2240 static void write_dump(const char *fname)
2242 struct buffer buf = { };
2246 list_for_each_entry(mod, &modules, list) {
2249 list_for_each_entry(sym, &mod->exported_symbols, list) {
2250 buf_printf(&buf, "0x%08x\t%s\t%s\tEXPORT_SYMBOL%s\t%s\n",
2251 sym->crc, sym->name, mod->name,
2252 sym->is_gpl_only ? "_GPL" : "",
2253 sym->namespace ?: "");
2256 write_buf(&buf, fname);
2260 static void write_namespace_deps_files(const char *fname)
2263 struct namespace_list *ns;
2264 struct buffer ns_deps_buf = {};
2266 list_for_each_entry(mod, &modules, list) {
2268 if (mod->from_dump || list_empty(&mod->missing_namespaces))
2271 buf_printf(&ns_deps_buf, "%s.ko:", mod->name);
2273 list_for_each_entry(ns, &mod->missing_namespaces, list)
2274 buf_printf(&ns_deps_buf, " %s", ns->namespace);
2276 buf_printf(&ns_deps_buf, "\n");
2279 write_if_changed(&ns_deps_buf, fname);
2280 free(ns_deps_buf.p);
2284 struct list_head list;
2288 int main(int argc, char **argv)
2291 char *missing_namespace_deps = NULL;
2292 char *dump_write = NULL, *files_source = NULL;
2294 LIST_HEAD(dump_lists);
2295 struct dump_list *dl, *dl2;
2297 while ((opt = getopt(argc, argv, "ei:mnT:o:aWwENd:")) != -1) {
2300 external_module = true;
2303 dl = NOFAIL(malloc(sizeof(*dl)));
2305 list_add_tail(&dl->list, &dump_lists);
2311 ignore_missing_files = true;
2314 dump_write = optarg;
2317 all_versions = true;
2320 files_source = optarg;
2326 warn_unresolved = true;
2329 sec_mismatch_warn_only = false;
2332 allow_missing_ns_imports = true;
2335 missing_namespace_deps = optarg;
2342 list_for_each_entry_safe(dl, dl2, &dump_lists, list) {
2343 read_dump(dl->file);
2344 list_del(&dl->list);
2348 while (optind < argc)
2349 read_symbols(argv[optind++]);
2352 read_symbols_from_files(files_source);
2354 list_for_each_entry(mod, &modules, list) {
2358 if (mod->is_vmlinux)
2359 write_vmlinux_export_c_file(mod);
2361 write_mod_c_file(mod);
2364 if (missing_namespace_deps)
2365 write_namespace_deps_files(missing_namespace_deps);
2368 write_dump(dump_write);
2369 if (sec_mismatch_count && !sec_mismatch_warn_only)
2370 error("Section mismatches detected.\n"
2371 "Set CONFIG_SECTION_MISMATCH_WARN_ONLY=y to allow them.\n");
2373 if (nr_unresolved > MAX_UNRESOLVED_REPORTS)
2374 warn("suppressed %u unresolved symbol warnings because there were too many)\n",
2375 nr_unresolved - MAX_UNRESOLVED_REPORTS);
2377 return error_occurred ? 1 : 0;