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;
45 * Cut off the warnings when there are too many. This typically occurs when
46 * vmlinux is missing. ('make modules' without building vmlinux.)
48 #define MAX_UNRESOLVED_REPORTS 10
49 static unsigned int nr_unresolved;
51 /* In kernel, this size is defined in linux/module.h;
52 * here we use Elf_Addr instead of long for covering cross-compile
55 #define MODULE_NAME_LEN (64 - sizeof(Elf_Addr))
57 void __attribute__((format(printf, 2, 3)))
58 modpost_log(enum loglevel loglevel, const char *fmt, ...)
64 fprintf(stderr, "WARNING: ");
67 fprintf(stderr, "ERROR: ");
70 fprintf(stderr, "FATAL: ");
72 default: /* invalid loglevel, ignore */
76 fprintf(stderr, "modpost: ");
78 va_start(arglist, fmt);
79 vfprintf(stderr, fmt, arglist);
82 if (loglevel == LOG_FATAL)
84 if (loglevel == LOG_ERROR)
85 error_occurred = true;
88 static inline bool strends(const char *str, const char *postfix)
90 if (strlen(str) < strlen(postfix))
93 return strcmp(str + strlen(str) - strlen(postfix), postfix) == 0;
96 void *do_nofail(void *ptr, const char *expr)
99 fatal("Memory allocation failure: %s.\n", expr);
104 char *read_text_file(const char *filename)
111 fd = open(filename, O_RDONLY);
117 if (fstat(fd, &st) < 0) {
122 buf = NOFAIL(malloc(st.st_size + 1));
129 bytes_read = read(fd, buf, nbytes);
130 if (bytes_read < 0) {
135 nbytes -= bytes_read;
137 buf[st.st_size] = '\0';
144 char *get_line(char **stringp)
146 char *orig = *stringp, *next;
148 /* do not return the unwanted extra line at EOF */
149 if (!orig || *orig == '\0')
152 /* don't use strsep here, it is not available everywhere */
153 next = strchr(orig, '\n');
162 /* A list of all modules we processed */
165 static struct module *find_module(const char *modname)
169 list_for_each_entry(mod, &modules, list) {
170 if (strcmp(mod->name, modname) == 0)
176 static struct module *new_module(const char *name, size_t namelen)
180 mod = NOFAIL(malloc(sizeof(*mod) + namelen + 1));
181 memset(mod, 0, sizeof(*mod));
183 INIT_LIST_HEAD(&mod->exported_symbols);
184 INIT_LIST_HEAD(&mod->unresolved_symbols);
185 INIT_LIST_HEAD(&mod->missing_namespaces);
186 INIT_LIST_HEAD(&mod->imported_namespaces);
188 memcpy(mod->name, name, namelen);
189 mod->name[namelen] = '\0';
190 mod->is_vmlinux = (strcmp(mod->name, "vmlinux") == 0);
193 * Set mod->is_gpl_compatible to true by default. If MODULE_LICENSE()
194 * is missing, do not check the use for EXPORT_SYMBOL_GPL() becasue
195 * modpost will exit wiht error anyway.
197 mod->is_gpl_compatible = true;
199 list_add_tail(&mod->list, &modules);
204 /* A hash of all exported symbols,
205 * struct symbol is also used for lists of unresolved symbols */
207 #define SYMBOL_HASH_SIZE 1024
211 struct list_head list; /* link to module::exported_symbols or module::unresolved_symbols */
212 struct module *module;
217 bool is_gpl_only; /* exported by EXPORT_SYMBOL_GPL */
221 static struct symbol *symbolhash[SYMBOL_HASH_SIZE];
223 /* This is based on the hash algorithm from gdbm, via tdb */
224 static inline unsigned int tdb_hash(const char *name)
226 unsigned value; /* Used to compute the hash value. */
227 unsigned i; /* Used to cycle through random values. */
229 /* Set the initial value from the key size. */
230 for (value = 0x238F13AF * strlen(name), i = 0; name[i]; i++)
231 value = (value + (((unsigned char *)name)[i] << (i*5 % 24)));
233 return (1103515243 * value + 12345);
237 * Allocate a new symbols for use in the hash of exported symbols or
238 * the list of unresolved symbols per module
240 static struct symbol *alloc_symbol(const char *name)
242 struct symbol *s = NOFAIL(malloc(sizeof(*s) + strlen(name) + 1));
244 memset(s, 0, sizeof(*s));
245 strcpy(s->name, name);
250 /* For the hash of exported symbols */
251 static void hash_add_symbol(struct symbol *sym)
255 hash = tdb_hash(sym->name) % SYMBOL_HASH_SIZE;
256 sym->next = symbolhash[hash];
257 symbolhash[hash] = sym;
260 static void sym_add_unresolved(const char *name, struct module *mod, bool weak)
264 sym = alloc_symbol(name);
267 list_add_tail(&sym->list, &mod->unresolved_symbols);
270 static struct symbol *sym_find_with_module(const char *name, struct module *mod)
274 /* For our purposes, .foo matches foo. PPC64 needs this. */
278 for (s = symbolhash[tdb_hash(name) % SYMBOL_HASH_SIZE]; s; s = s->next) {
279 if (strcmp(s->name, name) == 0 && (!mod || s->module == mod))
285 static struct symbol *find_symbol(const char *name)
287 return sym_find_with_module(name, NULL);
290 struct namespace_list {
291 struct list_head list;
295 static bool contains_namespace(struct list_head *head, const char *namespace)
297 struct namespace_list *list;
299 list_for_each_entry(list, head, list) {
300 if (!strcmp(list->namespace, namespace))
307 static void add_namespace(struct list_head *head, const char *namespace)
309 struct namespace_list *ns_entry;
311 if (!contains_namespace(head, namespace)) {
312 ns_entry = NOFAIL(malloc(sizeof(*ns_entry) +
313 strlen(namespace) + 1));
314 strcpy(ns_entry->namespace, namespace);
315 list_add_tail(&ns_entry->list, head);
319 static void *sym_get_data_by_offset(const struct elf_info *info,
320 unsigned int secindex, unsigned long offset)
322 Elf_Shdr *sechdr = &info->sechdrs[secindex];
324 return (void *)info->hdr + sechdr->sh_offset + offset;
327 void *sym_get_data(const struct elf_info *info, const Elf_Sym *sym)
329 return sym_get_data_by_offset(info, get_secindex(info, sym),
333 static const char *sech_name(const struct elf_info *info, Elf_Shdr *sechdr)
335 return sym_get_data_by_offset(info, info->secindex_strings,
339 static const char *sec_name(const struct elf_info *info, unsigned int secindex)
342 * If sym->st_shndx is a special section index, there is no
343 * corresponding section header.
344 * Return "" if the index is out of range of info->sechdrs[] array.
346 if (secindex >= info->num_sections)
349 return sech_name(info, &info->sechdrs[secindex]);
352 #define strstarts(str, prefix) (strncmp(str, prefix, strlen(prefix)) == 0)
354 static void sym_update_namespace(const char *symname, const char *namespace)
356 struct symbol *s = find_symbol(symname);
359 * That symbol should have been created earlier and thus this is
360 * actually an assertion.
363 error("Could not update namespace(%s) for symbol %s\n",
369 s->namespace = namespace[0] ? NOFAIL(strdup(namespace)) : NULL;
372 static struct symbol *sym_add_exported(const char *name, struct module *mod,
375 struct symbol *s = find_symbol(name);
377 if (s && (!external_module || s->module->is_vmlinux || s->module == mod)) {
378 error("%s: '%s' exported twice. Previous export was in %s%s\n",
379 mod->name, name, s->module->name,
380 s->module->is_vmlinux ? "" : ".ko");
383 s = alloc_symbol(name);
385 s->is_gpl_only = gpl_only;
386 list_add_tail(&s->list, &mod->exported_symbols);
392 static void sym_set_crc(struct symbol *sym, unsigned int crc)
395 sym->crc_valid = true;
398 static void *grab_file(const char *filename, size_t *size)
401 void *map = MAP_FAILED;
404 fd = open(filename, O_RDONLY);
411 map = mmap(NULL, *size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
415 if (map == MAP_FAILED)
420 static void release_file(void *file, size_t size)
425 static int parse_elf(struct elf_info *info, const char *filename)
431 const char *secstrings;
432 unsigned int symtab_idx = ~0U, symtab_shndx_idx = ~0U;
434 hdr = grab_file(filename, &info->size);
436 if (ignore_missing_files) {
437 fprintf(stderr, "%s: %s (ignored)\n", filename,
445 if (info->size < sizeof(*hdr)) {
446 /* file too small, assume this is an empty .o file */
449 /* Is this a valid ELF file? */
450 if ((hdr->e_ident[EI_MAG0] != ELFMAG0) ||
451 (hdr->e_ident[EI_MAG1] != ELFMAG1) ||
452 (hdr->e_ident[EI_MAG2] != ELFMAG2) ||
453 (hdr->e_ident[EI_MAG3] != ELFMAG3)) {
454 /* Not an ELF file - silently ignore it */
457 /* Fix endianness in ELF header */
458 hdr->e_type = TO_NATIVE(hdr->e_type);
459 hdr->e_machine = TO_NATIVE(hdr->e_machine);
460 hdr->e_version = TO_NATIVE(hdr->e_version);
461 hdr->e_entry = TO_NATIVE(hdr->e_entry);
462 hdr->e_phoff = TO_NATIVE(hdr->e_phoff);
463 hdr->e_shoff = TO_NATIVE(hdr->e_shoff);
464 hdr->e_flags = TO_NATIVE(hdr->e_flags);
465 hdr->e_ehsize = TO_NATIVE(hdr->e_ehsize);
466 hdr->e_phentsize = TO_NATIVE(hdr->e_phentsize);
467 hdr->e_phnum = TO_NATIVE(hdr->e_phnum);
468 hdr->e_shentsize = TO_NATIVE(hdr->e_shentsize);
469 hdr->e_shnum = TO_NATIVE(hdr->e_shnum);
470 hdr->e_shstrndx = TO_NATIVE(hdr->e_shstrndx);
471 sechdrs = (void *)hdr + hdr->e_shoff;
472 info->sechdrs = sechdrs;
474 /* modpost only works for relocatable objects */
475 if (hdr->e_type != ET_REL)
476 fatal("%s: not relocatable object.", filename);
478 /* Check if file offset is correct */
479 if (hdr->e_shoff > info->size) {
480 fatal("section header offset=%lu in file '%s' is bigger than filesize=%zu\n",
481 (unsigned long)hdr->e_shoff, filename, info->size);
485 if (hdr->e_shnum == SHN_UNDEF) {
487 * There are more than 64k sections,
488 * read count from .sh_size.
490 info->num_sections = TO_NATIVE(sechdrs[0].sh_size);
493 info->num_sections = hdr->e_shnum;
495 if (hdr->e_shstrndx == SHN_XINDEX) {
496 info->secindex_strings = TO_NATIVE(sechdrs[0].sh_link);
499 info->secindex_strings = hdr->e_shstrndx;
502 /* Fix endianness in section headers */
503 for (i = 0; i < info->num_sections; i++) {
504 sechdrs[i].sh_name = TO_NATIVE(sechdrs[i].sh_name);
505 sechdrs[i].sh_type = TO_NATIVE(sechdrs[i].sh_type);
506 sechdrs[i].sh_flags = TO_NATIVE(sechdrs[i].sh_flags);
507 sechdrs[i].sh_addr = TO_NATIVE(sechdrs[i].sh_addr);
508 sechdrs[i].sh_offset = TO_NATIVE(sechdrs[i].sh_offset);
509 sechdrs[i].sh_size = TO_NATIVE(sechdrs[i].sh_size);
510 sechdrs[i].sh_link = TO_NATIVE(sechdrs[i].sh_link);
511 sechdrs[i].sh_info = TO_NATIVE(sechdrs[i].sh_info);
512 sechdrs[i].sh_addralign = TO_NATIVE(sechdrs[i].sh_addralign);
513 sechdrs[i].sh_entsize = TO_NATIVE(sechdrs[i].sh_entsize);
515 /* Find symbol table. */
516 secstrings = (void *)hdr + sechdrs[info->secindex_strings].sh_offset;
517 for (i = 1; i < info->num_sections; i++) {
519 int nobits = sechdrs[i].sh_type == SHT_NOBITS;
521 if (!nobits && sechdrs[i].sh_offset > info->size) {
522 fatal("%s is truncated. sechdrs[i].sh_offset=%lu > "
523 "sizeof(*hrd)=%zu\n", filename,
524 (unsigned long)sechdrs[i].sh_offset,
528 secname = secstrings + sechdrs[i].sh_name;
529 if (strcmp(secname, ".modinfo") == 0) {
531 fatal("%s has NOBITS .modinfo\n", filename);
532 info->modinfo = (void *)hdr + sechdrs[i].sh_offset;
533 info->modinfo_len = sechdrs[i].sh_size;
536 if (sechdrs[i].sh_type == SHT_SYMTAB) {
537 unsigned int sh_link_idx;
539 info->symtab_start = (void *)hdr +
540 sechdrs[i].sh_offset;
541 info->symtab_stop = (void *)hdr +
542 sechdrs[i].sh_offset + sechdrs[i].sh_size;
543 sh_link_idx = sechdrs[i].sh_link;
544 info->strtab = (void *)hdr +
545 sechdrs[sh_link_idx].sh_offset;
548 /* 32bit section no. table? ("more than 64k sections") */
549 if (sechdrs[i].sh_type == SHT_SYMTAB_SHNDX) {
550 symtab_shndx_idx = i;
551 info->symtab_shndx_start = (void *)hdr +
552 sechdrs[i].sh_offset;
553 info->symtab_shndx_stop = (void *)hdr +
554 sechdrs[i].sh_offset + sechdrs[i].sh_size;
557 if (!info->symtab_start)
558 fatal("%s has no symtab?\n", filename);
560 /* Fix endianness in symbols */
561 for (sym = info->symtab_start; sym < info->symtab_stop; sym++) {
562 sym->st_shndx = TO_NATIVE(sym->st_shndx);
563 sym->st_name = TO_NATIVE(sym->st_name);
564 sym->st_value = TO_NATIVE(sym->st_value);
565 sym->st_size = TO_NATIVE(sym->st_size);
568 if (symtab_shndx_idx != ~0U) {
570 if (symtab_idx != sechdrs[symtab_shndx_idx].sh_link)
571 fatal("%s: SYMTAB_SHNDX has bad sh_link: %u!=%u\n",
572 filename, sechdrs[symtab_shndx_idx].sh_link,
575 for (p = info->symtab_shndx_start; p < info->symtab_shndx_stop;
583 static void parse_elf_finish(struct elf_info *info)
585 release_file(info->hdr, info->size);
588 static int ignore_undef_symbol(struct elf_info *info, const char *symname)
590 /* ignore __this_module, it will be resolved shortly */
591 if (strcmp(symname, "__this_module") == 0)
593 /* ignore global offset table */
594 if (strcmp(symname, "_GLOBAL_OFFSET_TABLE_") == 0)
596 if (info->hdr->e_machine == EM_PPC)
597 /* Special register function linked on all modules during final link of .ko */
598 if (strstarts(symname, "_restgpr_") ||
599 strstarts(symname, "_savegpr_") ||
600 strstarts(symname, "_rest32gpr_") ||
601 strstarts(symname, "_save32gpr_") ||
602 strstarts(symname, "_restvr_") ||
603 strstarts(symname, "_savevr_"))
605 if (info->hdr->e_machine == EM_PPC64)
606 /* Special register function linked on all modules during final link of .ko */
607 if (strstarts(symname, "_restgpr0_") ||
608 strstarts(symname, "_savegpr0_") ||
609 strstarts(symname, "_restvr_") ||
610 strstarts(symname, "_savevr_") ||
611 strcmp(symname, ".TOC.") == 0)
614 if (info->hdr->e_machine == EM_S390)
615 /* Expoline thunks are linked on all kernel modules during final link of .ko */
616 if (strstarts(symname, "__s390_indirect_jump_r"))
618 /* Do not ignore this symbol */
622 static void handle_symbol(struct module *mod, struct elf_info *info,
623 const Elf_Sym *sym, const char *symname)
625 switch (sym->st_shndx) {
627 if (strstarts(symname, "__gnu_lto_")) {
628 /* Should warn here, but modpost runs before the linker */
630 warn("\"%s\" [%s] is COMMON symbol\n", symname, mod->name);
633 /* undefined symbol */
634 if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL &&
635 ELF_ST_BIND(sym->st_info) != STB_WEAK)
637 if (ignore_undef_symbol(info, symname))
639 if (info->hdr->e_machine == EM_SPARC ||
640 info->hdr->e_machine == EM_SPARCV9) {
641 /* Ignore register directives. */
642 if (ELF_ST_TYPE(sym->st_info) == STT_SPARC_REGISTER)
644 if (symname[0] == '.') {
645 char *munged = NOFAIL(strdup(symname));
647 munged[1] = toupper(munged[1]);
652 sym_add_unresolved(symname, mod,
653 ELF_ST_BIND(sym->st_info) == STB_WEAK);
656 /* All exported symbols */
657 if (strstarts(symname, "__ksymtab_")) {
658 const char *name, *secname;
660 name = symname + strlen("__ksymtab_");
661 secname = sec_name(info, get_secindex(info, sym));
663 if (strstarts(secname, "___ksymtab_gpl+"))
664 sym_add_exported(name, mod, true);
665 else if (strstarts(secname, "___ksymtab+"))
666 sym_add_exported(name, mod, false);
668 if (strcmp(symname, "init_module") == 0)
669 mod->has_init = true;
670 if (strcmp(symname, "cleanup_module") == 0)
671 mod->has_cleanup = true;
677 * Parse tag=value strings from .modinfo section
679 static char *next_string(char *string, unsigned long *secsize)
681 /* Skip non-zero chars */
684 if ((*secsize)-- <= 1)
688 /* Skip any zero padding. */
691 if ((*secsize)-- <= 1)
697 static char *get_next_modinfo(struct elf_info *info, const char *tag,
701 unsigned int taglen = strlen(tag);
702 char *modinfo = info->modinfo;
703 unsigned long size = info->modinfo_len;
706 size -= prev - modinfo;
707 modinfo = next_string(prev, &size);
710 for (p = modinfo; p; p = next_string(p, &size)) {
711 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
712 return p + taglen + 1;
717 static char *get_modinfo(struct elf_info *info, const char *tag)
720 return get_next_modinfo(info, tag, NULL);
723 static const char *sym_name(struct elf_info *elf, Elf_Sym *sym)
726 return elf->strtab + sym->st_name;
732 * Check whether the 'string' argument matches one of the 'patterns',
733 * an array of shell wildcard patterns (glob).
735 * Return true is there is a match.
737 static bool match(const char *string, const char *const patterns[])
741 while ((pattern = *patterns++)) {
742 if (!fnmatch(pattern, string, 0))
749 /* sections that we do not want to do full section mismatch check on */
750 static const char *const section_white_list[] =
754 ".zdebug*", /* Compressed debug sections. */
755 ".GCC.command.line", /* record-gcc-switches */
756 ".mdebug*", /* alpha, score, mips etc. */
757 ".pdr", /* alpha, score, mips etc. */
762 ".xt.prop", /* xtensa */
763 ".xt.lit", /* xtensa */
764 ".arcextmap*", /* arc */
765 ".gnu.linkonce.arcext*", /* arc : modules */
766 ".cmem*", /* EZchip */
767 ".fmt_slot*", /* EZchip */
774 * This is used to find sections missing the SHF_ALLOC flag.
775 * The cause of this is often a section specified in assembler
776 * without "ax" / "aw".
778 static void check_section(const char *modname, struct elf_info *elf,
781 const char *sec = sech_name(elf, sechdr);
783 if (sechdr->sh_type == SHT_PROGBITS &&
784 !(sechdr->sh_flags & SHF_ALLOC) &&
785 !match(sec, section_white_list)) {
786 warn("%s (%s): unexpected non-allocatable section.\n"
787 "Did you forget to use \"ax\"/\"aw\" in a .S file?\n"
788 "Note that for example <linux/init.h> contains\n"
789 "section definitions for use in .S files.\n\n",
796 #define ALL_INIT_DATA_SECTIONS \
797 ".init.setup", ".init.rodata", ".meminit.rodata", \
798 ".init.data", ".meminit.data"
799 #define ALL_EXIT_DATA_SECTIONS \
800 ".exit.data", ".memexit.data"
802 #define ALL_INIT_TEXT_SECTIONS \
803 ".init.text", ".meminit.text"
804 #define ALL_EXIT_TEXT_SECTIONS \
805 ".exit.text", ".memexit.text"
807 #define ALL_PCI_INIT_SECTIONS \
808 ".pci_fixup_early", ".pci_fixup_header", ".pci_fixup_final", \
809 ".pci_fixup_enable", ".pci_fixup_resume", \
810 ".pci_fixup_resume_early", ".pci_fixup_suspend"
812 #define ALL_XXXINIT_SECTIONS MEM_INIT_SECTIONS
813 #define ALL_XXXEXIT_SECTIONS MEM_EXIT_SECTIONS
815 #define ALL_INIT_SECTIONS INIT_SECTIONS, ALL_XXXINIT_SECTIONS
816 #define ALL_EXIT_SECTIONS EXIT_SECTIONS, ALL_XXXEXIT_SECTIONS
818 #define DATA_SECTIONS ".data", ".data.rel"
819 #define TEXT_SECTIONS ".text", ".text.unlikely", ".sched.text", \
820 ".kprobes.text", ".cpuidle.text", ".noinstr.text"
821 #define OTHER_TEXT_SECTIONS ".ref.text", ".head.text", ".spinlock.text", \
822 ".fixup", ".entry.text", ".exception.text", ".text.*", \
823 ".coldtext", ".softirqentry.text"
825 #define INIT_SECTIONS ".init.*"
826 #define MEM_INIT_SECTIONS ".meminit.*"
828 #define EXIT_SECTIONS ".exit.*"
829 #define MEM_EXIT_SECTIONS ".memexit.*"
831 #define ALL_TEXT_SECTIONS ALL_INIT_TEXT_SECTIONS, ALL_EXIT_TEXT_SECTIONS, \
832 TEXT_SECTIONS, OTHER_TEXT_SECTIONS
834 /* init data sections */
835 static const char *const init_data_sections[] =
836 { ALL_INIT_DATA_SECTIONS, NULL };
838 /* all init sections */
839 static const char *const init_sections[] = { ALL_INIT_SECTIONS, NULL };
841 /* All init and exit sections (code + data) */
842 static const char *const init_exit_sections[] =
843 {ALL_INIT_SECTIONS, ALL_EXIT_SECTIONS, NULL };
845 /* all text sections */
846 static const char *const text_sections[] = { ALL_TEXT_SECTIONS, NULL };
849 static const char *const data_sections[] = { DATA_SECTIONS, NULL };
852 /* symbols in .data that may refer to init/exit sections */
853 #define DEFAULT_SYMBOL_WHITE_LIST \
855 "*_template", /* scsi uses *_template a lot */ \
856 "*_timer", /* arm uses ops structures named _timer a lot */ \
857 "*_sht", /* scsi also used *_sht to some extent */ \
863 static const char *const head_sections[] = { ".head.text*", NULL };
864 static const char *const linker_symbols[] =
865 { "__init_begin", "_sinittext", "_einittext", NULL };
866 static const char *const optim_symbols[] = { "*.constprop.*", NULL };
873 XXXINIT_TO_SOME_INIT,
874 XXXEXIT_TO_SOME_EXIT,
875 ANY_INIT_TO_ANY_EXIT,
876 ANY_EXIT_TO_ANY_INIT,
882 * Describe how to match sections on different criteria:
884 * @fromsec: Array of sections to be matched.
886 * @bad_tosec: Relocations applied to a section in @fromsec to a section in
887 * this array is forbidden (black-list). Can be empty.
889 * @good_tosec: Relocations applied to a section in @fromsec must be
890 * targeting sections in this array (white-list). Can be empty.
892 * @mismatch: Type of mismatch.
894 * @symbol_white_list: Do not match a relocation to a symbol in this list
895 * even if it is targeting a section in @bad_to_sec.
897 * @handler: Specific handler to call when a match is found. If NULL,
898 * default_mismatch_handler() will be called.
901 struct sectioncheck {
902 const char *fromsec[20];
903 const char *bad_tosec[20];
904 const char *good_tosec[20];
905 enum mismatch mismatch;
906 const char *symbol_white_list[20];
907 void (*handler)(const char *modname, struct elf_info *elf,
908 const struct sectioncheck* const mismatch,
909 Elf_Rela *r, Elf_Sym *sym, const char *fromsec);
913 static void extable_mismatch_handler(const char *modname, struct elf_info *elf,
914 const struct sectioncheck* const mismatch,
915 Elf_Rela *r, Elf_Sym *sym,
916 const char *fromsec);
918 static const struct sectioncheck sectioncheck[] = {
919 /* Do not reference init/exit code/data from
920 * normal code and data
923 .fromsec = { TEXT_SECTIONS, NULL },
924 .bad_tosec = { ALL_INIT_SECTIONS, NULL },
925 .mismatch = TEXT_TO_ANY_INIT,
926 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
929 .fromsec = { DATA_SECTIONS, NULL },
930 .bad_tosec = { ALL_XXXINIT_SECTIONS, NULL },
931 .mismatch = DATA_TO_ANY_INIT,
932 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
935 .fromsec = { DATA_SECTIONS, NULL },
936 .bad_tosec = { INIT_SECTIONS, NULL },
937 .mismatch = DATA_TO_ANY_INIT,
938 .symbol_white_list = {
939 "*_template", "*_timer", "*_sht", "*_ops",
940 "*_probe", "*_probe_one", "*_console", NULL
944 .fromsec = { TEXT_SECTIONS, NULL },
945 .bad_tosec = { ALL_EXIT_SECTIONS, NULL },
946 .mismatch = TEXT_TO_ANY_EXIT,
947 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
950 .fromsec = { DATA_SECTIONS, NULL },
951 .bad_tosec = { ALL_EXIT_SECTIONS, NULL },
952 .mismatch = DATA_TO_ANY_EXIT,
953 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
955 /* Do not reference init code/data from meminit code/data */
957 .fromsec = { ALL_XXXINIT_SECTIONS, NULL },
958 .bad_tosec = { INIT_SECTIONS, NULL },
959 .mismatch = XXXINIT_TO_SOME_INIT,
960 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
962 /* Do not reference exit code/data from memexit code/data */
964 .fromsec = { ALL_XXXEXIT_SECTIONS, NULL },
965 .bad_tosec = { EXIT_SECTIONS, NULL },
966 .mismatch = XXXEXIT_TO_SOME_EXIT,
967 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
969 /* Do not use exit code/data from init code */
971 .fromsec = { ALL_INIT_SECTIONS, NULL },
972 .bad_tosec = { ALL_EXIT_SECTIONS, NULL },
973 .mismatch = ANY_INIT_TO_ANY_EXIT,
974 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
976 /* Do not use init code/data from exit code */
978 .fromsec = { ALL_EXIT_SECTIONS, NULL },
979 .bad_tosec = { ALL_INIT_SECTIONS, NULL },
980 .mismatch = ANY_EXIT_TO_ANY_INIT,
981 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
984 .fromsec = { ALL_PCI_INIT_SECTIONS, NULL },
985 .bad_tosec = { INIT_SECTIONS, NULL },
986 .mismatch = ANY_INIT_TO_ANY_EXIT,
987 .symbol_white_list = { NULL },
989 /* Do not export init/exit functions or data */
991 .fromsec = { "___ksymtab*", NULL },
992 .bad_tosec = { INIT_SECTIONS, EXIT_SECTIONS, NULL },
993 .mismatch = EXPORT_TO_INIT_EXIT,
994 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
997 .fromsec = { "__ex_table", NULL },
998 /* If you're adding any new black-listed sections in here, consider
999 * adding a special 'printer' for them in scripts/check_extable.
1001 .bad_tosec = { ".altinstr_replacement", NULL },
1002 .good_tosec = {ALL_TEXT_SECTIONS , NULL},
1003 .mismatch = EXTABLE_TO_NON_TEXT,
1004 .handler = extable_mismatch_handler,
1008 static const struct sectioncheck *section_mismatch(
1009 const char *fromsec, const char *tosec)
1014 * The target section could be the SHT_NUL section when we're
1015 * handling relocations to un-resolved symbols, trying to match it
1016 * doesn't make much sense and causes build failures on parisc
1022 for (i = 0; i < ARRAY_SIZE(sectioncheck); i++) {
1023 const struct sectioncheck *check = §ioncheck[i];
1025 if (match(fromsec, check->fromsec)) {
1026 if (check->bad_tosec[0] && match(tosec, check->bad_tosec))
1028 if (check->good_tosec[0] && !match(tosec, check->good_tosec))
1036 * Whitelist to allow certain references to pass with no warning.
1039 * If a module parameter is declared __initdata and permissions=0
1040 * then this is legal despite the warning generated.
1041 * We cannot see value of permissions here, so just ignore
1043 * The pattern is identified by:
1044 * tosec = .init.data
1049 * module_param_call() ops can refer to __init set function if permissions=0
1050 * The pattern is identified by:
1051 * tosec = .init.text
1053 * atsym = __param_ops_*
1056 * Many drivers utilise a *driver container with references to
1057 * add, remove, probe functions etc.
1058 * the pattern is identified by:
1059 * tosec = init or exit section
1060 * fromsec = data section
1061 * atsym = *driver, *_template, *_sht, *_ops, *_probe,
1062 * *probe_one, *_console, *_timer
1065 * Whitelist all references from .head.text to any init section
1068 * Some symbols belong to init section but still it is ok to reference
1069 * these from non-init sections as these symbols don't have any memory
1070 * allocated for them and symbol address and value are same. So even
1071 * if init section is freed, its ok to reference those symbols.
1072 * For ex. symbols marking the init section boundaries.
1073 * This pattern is identified by
1074 * refsymname = __init_begin, _sinittext, _einittext
1077 * GCC may optimize static inlines when fed constant arg(s) resulting
1078 * in functions like cpumask_empty() -- generating an associated symbol
1079 * cpumask_empty.constprop.3 that appears in the audit. If the const that
1080 * is passed in comes from __init, like say nmi_ipi_mask, we get a
1081 * meaningless section warning. May need to add isra symbols too...
1082 * This pattern is identified by
1083 * tosec = init section
1084 * fromsec = text section
1085 * refsymname = *.constprop.*
1088 * Hide section mismatch warnings for ELF local symbols. The goal
1089 * is to eliminate false positive modpost warnings caused by
1090 * compiler-generated ELF local symbol names such as ".LANCHOR1".
1091 * Autogenerated symbol names bypass modpost's "Pattern 2"
1092 * whitelisting, which relies on pattern-matching against symbol
1093 * names to work. (One situation where gcc can autogenerate ELF
1094 * local symbols is when "-fsection-anchors" is used.)
1096 static int secref_whitelist(const struct sectioncheck *mismatch,
1097 const char *fromsec, const char *fromsym,
1098 const char *tosec, const char *tosym)
1100 /* Check for pattern 1 */
1101 if (match(tosec, init_data_sections) &&
1102 match(fromsec, data_sections) &&
1103 strstarts(fromsym, "__param"))
1106 /* Check for pattern 1a */
1107 if (strcmp(tosec, ".init.text") == 0 &&
1108 match(fromsec, data_sections) &&
1109 strstarts(fromsym, "__param_ops_"))
1112 /* Check for pattern 2 */
1113 if (match(tosec, init_exit_sections) &&
1114 match(fromsec, data_sections) &&
1115 match(fromsym, mismatch->symbol_white_list))
1118 /* Check for pattern 3 */
1119 if (match(fromsec, head_sections) &&
1120 match(tosec, init_sections))
1123 /* Check for pattern 4 */
1124 if (match(tosym, linker_symbols))
1127 /* Check for pattern 5 */
1128 if (match(fromsec, text_sections) &&
1129 match(tosec, init_sections) &&
1130 match(fromsym, optim_symbols))
1133 /* Check for pattern 6 */
1134 if (strstarts(fromsym, ".L"))
1140 static inline int is_arm_mapping_symbol(const char *str)
1142 return str[0] == '$' &&
1143 (str[1] == 'a' || str[1] == 'd' || str[1] == 't' || str[1] == 'x')
1144 && (str[2] == '\0' || str[2] == '.');
1148 * If there's no name there, ignore it; likewise, ignore it if it's
1149 * one of the magic symbols emitted used by current ARM tools.
1151 * Otherwise if find_symbols_between() returns those symbols, they'll
1152 * fail the whitelist tests and cause lots of false alarms ... fixable
1153 * only by merging __exit and __init sections into __text, bloating
1154 * the kernel (which is especially evil on embedded platforms).
1156 static inline int is_valid_name(struct elf_info *elf, Elf_Sym *sym)
1158 const char *name = elf->strtab + sym->st_name;
1160 if (!name || !strlen(name))
1162 return !is_arm_mapping_symbol(name);
1166 * Find symbol based on relocation record info.
1167 * In some cases the symbol supplied is a valid symbol so
1168 * return refsym. If st_name != 0 we assume this is a valid symbol.
1169 * In other cases the symbol needs to be looked up in the symbol table
1170 * based on section and address.
1172 static Elf_Sym *find_elf_symbol(struct elf_info *elf, Elf64_Sword addr,
1176 Elf_Sym *near = NULL;
1177 Elf64_Sword distance = 20;
1179 unsigned int relsym_secindex;
1181 if (relsym->st_name != 0)
1184 relsym_secindex = get_secindex(elf, relsym);
1185 for (sym = elf->symtab_start; sym < elf->symtab_stop; sym++) {
1186 if (get_secindex(elf, sym) != relsym_secindex)
1188 if (ELF_ST_TYPE(sym->st_info) == STT_SECTION)
1190 if (!is_valid_name(elf, sym))
1192 if (sym->st_value == addr)
1194 /* Find a symbol nearby - addr are maybe negative */
1195 d = sym->st_value - addr;
1197 d = addr - sym->st_value;
1203 /* We need a close match */
1211 * Find symbols before or equal addr and after addr - in the section sec.
1212 * If we find two symbols with equal offset prefer one with a valid name.
1213 * The ELF format may have a better way to detect what type of symbol
1214 * it is, but this works for now.
1216 static Elf_Sym *find_elf_symbol2(struct elf_info *elf, Elf_Addr addr,
1220 Elf_Sym *near = NULL;
1221 Elf_Addr distance = ~0;
1223 for (sym = elf->symtab_start; sym < elf->symtab_stop; sym++) {
1226 if (is_shndx_special(sym->st_shndx))
1228 symsec = sec_name(elf, get_secindex(elf, sym));
1229 if (strcmp(symsec, sec) != 0)
1231 if (!is_valid_name(elf, sym))
1233 if (sym->st_value <= addr && addr - sym->st_value <= distance) {
1234 distance = addr - sym->st_value;
1242 * Convert a section name to the function/data attribute
1243 * .init.text => __init
1244 * .memexitconst => __memconst
1247 * The memory of returned value has been allocated on a heap. The user of this
1248 * method should free it after usage.
1250 static char *sec2annotation(const char *s)
1252 if (match(s, init_exit_sections)) {
1253 char *p = NOFAIL(malloc(20));
1260 while (*s && *s != '.')
1265 if (strstr(s, "rodata") != NULL)
1266 strcat(p, "const ");
1267 else if (strstr(s, "data") != NULL)
1273 return NOFAIL(strdup(""));
1277 static int is_function(Elf_Sym *sym)
1280 return ELF_ST_TYPE(sym->st_info) == STT_FUNC;
1285 static void print_section_list(const char * const list[20])
1287 const char *const *s = list;
1290 fprintf(stderr, "%s", *s);
1293 fprintf(stderr, ", ");
1295 fprintf(stderr, "\n");
1298 static inline void get_pretty_name(int is_func, const char** name, const char** name_p)
1301 case 0: *name = "variable"; *name_p = ""; break;
1302 case 1: *name = "function"; *name_p = "()"; break;
1303 default: *name = "(unknown reference)"; *name_p = ""; break;
1308 * Print a warning about a section mismatch.
1309 * Try to find symbols near it so user can find it.
1310 * Check whitelist before warning - it may be a false positive.
1312 static void report_sec_mismatch(const char *modname,
1313 const struct sectioncheck *mismatch,
1314 const char *fromsec,
1315 unsigned long long fromaddr,
1316 const char *fromsym,
1318 const char *tosec, const char *tosym,
1321 const char *from, *from_p;
1322 const char *to, *to_p;
1326 sec_mismatch_count++;
1328 get_pretty_name(from_is_func, &from, &from_p);
1329 get_pretty_name(to_is_func, &to, &to_p);
1331 warn("%s(%s+0x%llx): Section mismatch in reference from the %s %s%s "
1332 "to the %s %s:%s%s\n",
1333 modname, fromsec, fromaddr, from, fromsym, from_p, to, tosec,
1336 switch (mismatch->mismatch) {
1337 case TEXT_TO_ANY_INIT:
1338 prl_from = sec2annotation(fromsec);
1339 prl_to = sec2annotation(tosec);
1341 "The function %s%s() references\n"
1343 "This is often because %s lacks a %s\n"
1344 "annotation or the annotation of %s is wrong.\n",
1346 to, prl_to, tosym, to_p,
1347 fromsym, prl_to, tosym);
1351 case DATA_TO_ANY_INIT: {
1352 prl_to = sec2annotation(tosec);
1354 "The variable %s references\n"
1356 "If the reference is valid then annotate the\n"
1357 "variable with __init* or __refdata (see linux/init.h) "
1358 "or name the variable:\n",
1359 fromsym, to, prl_to, tosym, to_p);
1360 print_section_list(mismatch->symbol_white_list);
1364 case TEXT_TO_ANY_EXIT:
1365 prl_to = sec2annotation(tosec);
1367 "The function %s() references a %s in an exit section.\n"
1368 "Often the %s %s%s has valid usage outside the exit section\n"
1369 "and the fix is to remove the %sannotation of %s.\n",
1370 fromsym, to, to, tosym, to_p, prl_to, tosym);
1373 case DATA_TO_ANY_EXIT: {
1374 prl_to = sec2annotation(tosec);
1376 "The variable %s references\n"
1378 "If the reference is valid then annotate the\n"
1379 "variable with __exit* (see linux/init.h) or "
1380 "name the variable:\n",
1381 fromsym, to, prl_to, tosym, to_p);
1382 print_section_list(mismatch->symbol_white_list);
1386 case XXXINIT_TO_SOME_INIT:
1387 case XXXEXIT_TO_SOME_EXIT:
1388 prl_from = sec2annotation(fromsec);
1389 prl_to = sec2annotation(tosec);
1391 "The %s %s%s%s references\n"
1393 "If %s is only used by %s then\n"
1394 "annotate %s with a matching annotation.\n",
1395 from, prl_from, fromsym, from_p,
1396 to, prl_to, tosym, to_p,
1397 tosym, fromsym, tosym);
1401 case ANY_INIT_TO_ANY_EXIT:
1402 prl_from = sec2annotation(fromsec);
1403 prl_to = sec2annotation(tosec);
1405 "The %s %s%s%s references\n"
1407 "This is often seen when error handling "
1408 "in the init function\n"
1409 "uses functionality in the exit path.\n"
1410 "The fix is often to remove the %sannotation of\n"
1411 "%s%s so it may be used outside an exit section.\n",
1412 from, prl_from, fromsym, from_p,
1413 to, prl_to, tosym, to_p,
1414 prl_to, tosym, to_p);
1418 case ANY_EXIT_TO_ANY_INIT:
1419 prl_from = sec2annotation(fromsec);
1420 prl_to = sec2annotation(tosec);
1422 "The %s %s%s%s references\n"
1424 "This is often seen when error handling "
1425 "in the exit function\n"
1426 "uses functionality in the init path.\n"
1427 "The fix is often to remove the %sannotation of\n"
1428 "%s%s so it may be used outside an init section.\n",
1429 from, prl_from, fromsym, from_p,
1430 to, prl_to, tosym, to_p,
1431 prl_to, tosym, to_p);
1435 case EXPORT_TO_INIT_EXIT:
1436 prl_to = sec2annotation(tosec);
1438 "The symbol %s is exported and annotated %s\n"
1439 "Fix this by removing the %sannotation of %s "
1440 "or drop the export.\n",
1441 tosym, prl_to, prl_to, tosym);
1444 case EXTABLE_TO_NON_TEXT:
1445 fatal("There's a special handler for this mismatch type, "
1446 "we should never get here.");
1449 fprintf(stderr, "\n");
1452 static void default_mismatch_handler(const char *modname, struct elf_info *elf,
1453 const struct sectioncheck* const mismatch,
1454 Elf_Rela *r, Elf_Sym *sym, const char *fromsec)
1460 const char *fromsym;
1462 from = find_elf_symbol2(elf, r->r_offset, fromsec);
1463 fromsym = sym_name(elf, from);
1465 if (strstarts(fromsym, "reference___initcall"))
1468 tosec = sec_name(elf, get_secindex(elf, sym));
1469 to = find_elf_symbol(elf, r->r_addend, sym);
1470 tosym = sym_name(elf, to);
1472 /* check whitelist - we may ignore it */
1473 if (secref_whitelist(mismatch,
1474 fromsec, fromsym, tosec, tosym)) {
1475 report_sec_mismatch(modname, mismatch,
1476 fromsec, r->r_offset, fromsym,
1477 is_function(from), tosec, tosym,
1482 static int is_executable_section(struct elf_info* elf, unsigned int section_index)
1484 if (section_index > elf->num_sections)
1485 fatal("section_index is outside elf->num_sections!\n");
1487 return ((elf->sechdrs[section_index].sh_flags & SHF_EXECINSTR) == SHF_EXECINSTR);
1491 * We rely on a gross hack in section_rel[a]() calling find_extable_entry_size()
1492 * to know the sizeof(struct exception_table_entry) for the target architecture.
1494 static unsigned int extable_entry_size = 0;
1495 static void find_extable_entry_size(const char* const sec, const Elf_Rela* r)
1498 * If we're currently checking the second relocation within __ex_table,
1499 * that relocation offset tells us the offsetof(struct
1500 * exception_table_entry, fixup) which is equal to sizeof(struct
1501 * exception_table_entry) divided by two. We use that to our advantage
1502 * since there's no portable way to get that size as every architecture
1503 * seems to go with different sized types. Not pretty but better than
1504 * hard-coding the size for every architecture..
1506 if (!extable_entry_size)
1507 extable_entry_size = r->r_offset * 2;
1510 static inline bool is_extable_fault_address(Elf_Rela *r)
1513 * extable_entry_size is only discovered after we've handled the
1514 * _second_ relocation in __ex_table, so only abort when we're not
1515 * handling the first reloc and extable_entry_size is zero.
1517 if (r->r_offset && extable_entry_size == 0)
1518 fatal("extable_entry size hasn't been discovered!\n");
1520 return ((r->r_offset == 0) ||
1521 (r->r_offset % extable_entry_size == 0));
1524 #define is_second_extable_reloc(Start, Cur, Sec) \
1525 (((Cur) == (Start) + 1) && (strcmp("__ex_table", (Sec)) == 0))
1527 static void report_extable_warnings(const char* modname, struct elf_info* elf,
1528 const struct sectioncheck* const mismatch,
1529 Elf_Rela* r, Elf_Sym* sym,
1530 const char* fromsec, const char* tosec)
1532 Elf_Sym* fromsym = find_elf_symbol2(elf, r->r_offset, fromsec);
1533 const char* fromsym_name = sym_name(elf, fromsym);
1534 Elf_Sym* tosym = find_elf_symbol(elf, r->r_addend, sym);
1535 const char* tosym_name = sym_name(elf, tosym);
1536 const char* from_pretty_name;
1537 const char* from_pretty_name_p;
1538 const char* to_pretty_name;
1539 const char* to_pretty_name_p;
1541 get_pretty_name(is_function(fromsym),
1542 &from_pretty_name, &from_pretty_name_p);
1543 get_pretty_name(is_function(tosym),
1544 &to_pretty_name, &to_pretty_name_p);
1546 warn("%s(%s+0x%lx): Section mismatch in reference"
1547 " from the %s %s%s to the %s %s:%s%s\n",
1548 modname, fromsec, (long)r->r_offset, from_pretty_name,
1549 fromsym_name, from_pretty_name_p,
1550 to_pretty_name, tosec, tosym_name, to_pretty_name_p);
1552 if (!match(tosec, mismatch->bad_tosec) &&
1553 is_executable_section(elf, get_secindex(elf, sym)))
1555 "The relocation at %s+0x%lx references\n"
1556 "section \"%s\" which is not in the list of\n"
1557 "authorized sections. If you're adding a new section\n"
1558 "and/or if this reference is valid, add \"%s\" to the\n"
1559 "list of authorized sections to jump to on fault.\n"
1560 "This can be achieved by adding \"%s\" to \n"
1561 "OTHER_TEXT_SECTIONS in scripts/mod/modpost.c.\n",
1562 fromsec, (long)r->r_offset, tosec, tosec, tosec);
1565 static void extable_mismatch_handler(const char* modname, struct elf_info *elf,
1566 const struct sectioncheck* const mismatch,
1567 Elf_Rela* r, Elf_Sym* sym,
1568 const char *fromsec)
1570 const char* tosec = sec_name(elf, get_secindex(elf, sym));
1572 sec_mismatch_count++;
1574 report_extable_warnings(modname, elf, mismatch, r, sym, fromsec, tosec);
1576 if (match(tosec, mismatch->bad_tosec))
1577 fatal("The relocation at %s+0x%lx references\n"
1578 "section \"%s\" which is black-listed.\n"
1579 "Something is seriously wrong and should be fixed.\n"
1580 "You might get more information about where this is\n"
1581 "coming from by using scripts/check_extable.sh %s\n",
1582 fromsec, (long)r->r_offset, tosec, modname);
1583 else if (!is_executable_section(elf, get_secindex(elf, sym))) {
1584 if (is_extable_fault_address(r))
1585 fatal("The relocation at %s+0x%lx references\n"
1586 "section \"%s\" which is not executable, IOW\n"
1587 "it is not possible for the kernel to fault\n"
1588 "at that address. Something is seriously wrong\n"
1589 "and should be fixed.\n",
1590 fromsec, (long)r->r_offset, tosec);
1592 fatal("The relocation at %s+0x%lx references\n"
1593 "section \"%s\" which is not executable, IOW\n"
1594 "the kernel will fault if it ever tries to\n"
1595 "jump to it. Something is seriously wrong\n"
1596 "and should be fixed.\n",
1597 fromsec, (long)r->r_offset, tosec);
1601 static void check_section_mismatch(const char *modname, struct elf_info *elf,
1602 Elf_Rela *r, Elf_Sym *sym, const char *fromsec)
1604 const char *tosec = sec_name(elf, get_secindex(elf, sym));
1605 const struct sectioncheck *mismatch = section_mismatch(fromsec, tosec);
1608 if (mismatch->handler)
1609 mismatch->handler(modname, elf, mismatch,
1612 default_mismatch_handler(modname, elf, mismatch,
1617 static unsigned int *reloc_location(struct elf_info *elf,
1618 Elf_Shdr *sechdr, Elf_Rela *r)
1620 return sym_get_data_by_offset(elf, sechdr->sh_info, r->r_offset);
1623 static int addend_386_rel(struct elf_info *elf, Elf_Shdr *sechdr, Elf_Rela *r)
1625 unsigned int r_typ = ELF_R_TYPE(r->r_info);
1626 unsigned int *location = reloc_location(elf, sechdr, r);
1630 r->r_addend = TO_NATIVE(*location);
1633 r->r_addend = TO_NATIVE(*location) + 4;
1640 #define R_ARM_CALL 28
1642 #ifndef R_ARM_JUMP24
1643 #define R_ARM_JUMP24 29
1646 #ifndef R_ARM_THM_CALL
1647 #define R_ARM_THM_CALL 10
1649 #ifndef R_ARM_THM_JUMP24
1650 #define R_ARM_THM_JUMP24 30
1652 #ifndef R_ARM_THM_JUMP19
1653 #define R_ARM_THM_JUMP19 51
1656 static int addend_arm_rel(struct elf_info *elf, Elf_Shdr *sechdr, Elf_Rela *r)
1658 unsigned int r_typ = ELF_R_TYPE(r->r_info);
1662 /* From ARM ABI: (S + A) | T */
1663 r->r_addend = (int)(long)
1664 (elf->symtab_start + ELF_R_SYM(r->r_info));
1669 case R_ARM_THM_CALL:
1670 case R_ARM_THM_JUMP24:
1671 case R_ARM_THM_JUMP19:
1672 /* From ARM ABI: ((S + A) | T) - P */
1673 r->r_addend = (int)(long)(elf->hdr +
1675 (r->r_offset - sechdr->sh_addr));
1683 static int addend_mips_rel(struct elf_info *elf, Elf_Shdr *sechdr, Elf_Rela *r)
1685 unsigned int r_typ = ELF_R_TYPE(r->r_info);
1686 unsigned int *location = reloc_location(elf, sechdr, r);
1689 if (r_typ == R_MIPS_HI16)
1690 return 1; /* skip this */
1691 inst = TO_NATIVE(*location);
1694 r->r_addend = inst & 0xffff;
1697 r->r_addend = (inst & 0x03ffffff) << 2;
1707 #define EM_RISCV 243
1710 #ifndef R_RISCV_SUB32
1711 #define R_RISCV_SUB32 39
1714 static void section_rela(const char *modname, struct elf_info *elf,
1721 const char *fromsec;
1723 Elf_Rela *start = (void *)elf->hdr + sechdr->sh_offset;
1724 Elf_Rela *stop = (void *)start + sechdr->sh_size;
1726 fromsec = sech_name(elf, sechdr);
1727 fromsec += strlen(".rela");
1728 /* if from section (name) is know good then skip it */
1729 if (match(fromsec, section_white_list))
1732 for (rela = start; rela < stop; rela++) {
1733 r.r_offset = TO_NATIVE(rela->r_offset);
1734 #if KERNEL_ELFCLASS == ELFCLASS64
1735 if (elf->hdr->e_machine == EM_MIPS) {
1737 r_sym = ELF64_MIPS_R_SYM(rela->r_info);
1738 r_sym = TO_NATIVE(r_sym);
1739 r_typ = ELF64_MIPS_R_TYPE(rela->r_info);
1740 r.r_info = ELF64_R_INFO(r_sym, r_typ);
1742 r.r_info = TO_NATIVE(rela->r_info);
1743 r_sym = ELF_R_SYM(r.r_info);
1746 r.r_info = TO_NATIVE(rela->r_info);
1747 r_sym = ELF_R_SYM(r.r_info);
1749 r.r_addend = TO_NATIVE(rela->r_addend);
1750 switch (elf->hdr->e_machine) {
1752 if (!strcmp("__ex_table", fromsec) &&
1753 ELF_R_TYPE(r.r_info) == R_RISCV_SUB32)
1757 sym = elf->symtab_start + r_sym;
1758 /* Skip special sections */
1759 if (is_shndx_special(sym->st_shndx))
1761 if (is_second_extable_reloc(start, rela, fromsec))
1762 find_extable_entry_size(fromsec, &r);
1763 check_section_mismatch(modname, elf, &r, sym, fromsec);
1767 static void section_rel(const char *modname, struct elf_info *elf,
1774 const char *fromsec;
1776 Elf_Rel *start = (void *)elf->hdr + sechdr->sh_offset;
1777 Elf_Rel *stop = (void *)start + sechdr->sh_size;
1779 fromsec = sech_name(elf, sechdr);
1780 fromsec += strlen(".rel");
1781 /* if from section (name) is know good then skip it */
1782 if (match(fromsec, section_white_list))
1785 for (rel = start; rel < stop; rel++) {
1786 r.r_offset = TO_NATIVE(rel->r_offset);
1787 #if KERNEL_ELFCLASS == ELFCLASS64
1788 if (elf->hdr->e_machine == EM_MIPS) {
1790 r_sym = ELF64_MIPS_R_SYM(rel->r_info);
1791 r_sym = TO_NATIVE(r_sym);
1792 r_typ = ELF64_MIPS_R_TYPE(rel->r_info);
1793 r.r_info = ELF64_R_INFO(r_sym, r_typ);
1795 r.r_info = TO_NATIVE(rel->r_info);
1796 r_sym = ELF_R_SYM(r.r_info);
1799 r.r_info = TO_NATIVE(rel->r_info);
1800 r_sym = ELF_R_SYM(r.r_info);
1803 switch (elf->hdr->e_machine) {
1805 if (addend_386_rel(elf, sechdr, &r))
1809 if (addend_arm_rel(elf, sechdr, &r))
1813 if (addend_mips_rel(elf, sechdr, &r))
1817 sym = elf->symtab_start + r_sym;
1818 /* Skip special sections */
1819 if (is_shndx_special(sym->st_shndx))
1821 if (is_second_extable_reloc(start, rel, fromsec))
1822 find_extable_entry_size(fromsec, &r);
1823 check_section_mismatch(modname, elf, &r, sym, fromsec);
1828 * A module includes a number of sections that are discarded
1829 * either when loaded or when used as built-in.
1830 * For loaded modules all functions marked __init and all data
1831 * marked __initdata will be discarded when the module has been initialized.
1832 * Likewise for modules used built-in the sections marked __exit
1833 * are discarded because __exit marked function are supposed to be called
1834 * only when a module is unloaded which never happens for built-in modules.
1835 * The check_sec_ref() function traverses all relocation records
1836 * to find all references to a section that reference a section that will
1837 * be discarded and warns about it.
1839 static void check_sec_ref(const char *modname, struct elf_info *elf)
1842 Elf_Shdr *sechdrs = elf->sechdrs;
1844 /* Walk through all sections */
1845 for (i = 0; i < elf->num_sections; i++) {
1846 check_section(modname, elf, &elf->sechdrs[i]);
1847 /* We want to process only relocation sections and not .init */
1848 if (sechdrs[i].sh_type == SHT_RELA)
1849 section_rela(modname, elf, &elf->sechdrs[i]);
1850 else if (sechdrs[i].sh_type == SHT_REL)
1851 section_rel(modname, elf, &elf->sechdrs[i]);
1855 static char *remove_dot(char *s)
1857 size_t n = strcspn(s, ".");
1860 size_t m = strspn(s + n + 1, "0123456789");
1861 if (m && (s[n + m + 1] == '.' || s[n + m + 1] == 0))
1868 * The CRCs are recorded in .*.cmd files in the form of:
1869 * #SYMVER <name> <crc>
1871 static void extract_crcs_for_object(const char *object, struct module *mod)
1873 char cmd_file[PATH_MAX];
1878 base = strrchr(object, '/');
1881 dirlen = base - object;
1887 ret = snprintf(cmd_file, sizeof(cmd_file), "%.*s.%s.cmd",
1888 dirlen, object, base);
1889 if (ret >= sizeof(cmd_file)) {
1890 error("%s: too long path was truncated\n", cmd_file);
1894 buf = read_text_file(cmd_file);
1897 while ((p = strstr(p, "\n#SYMVER "))) {
1903 name = p + strlen("\n#SYMVER ");
1905 p = strchr(name, ' ');
1913 continue; /* skip this line */
1915 crc = strtol(p, &p, 0);
1917 continue; /* skip this line */
1919 name[namelen] = '\0';
1922 * sym_find_with_module() may return NULL here.
1923 * It typically occurs when CONFIG_TRIM_UNUSED_KSYMS=y.
1924 * Since commit e1327a127703, genksyms calculates CRCs of all
1925 * symbols, including trimmed ones. Ignore orphan CRCs.
1927 sym = sym_find_with_module(name, mod);
1929 sym_set_crc(sym, crc);
1936 * The symbol versions (CRC) are recorded in the .*.cmd files.
1937 * Parse them to retrieve CRCs for the current module.
1939 static void mod_set_crcs(struct module *mod)
1941 char objlist[PATH_MAX];
1942 char *buf, *p, *obj;
1945 if (mod->is_vmlinux) {
1946 strcpy(objlist, ".vmlinux.objs");
1948 /* objects for a module are listed in the *.mod file. */
1949 ret = snprintf(objlist, sizeof(objlist), "%s.mod", mod->name);
1950 if (ret >= sizeof(objlist)) {
1951 error("%s: too long path was truncated\n", objlist);
1956 buf = read_text_file(objlist);
1959 while ((obj = strsep(&p, "\n")) && obj[0])
1960 extract_crcs_for_object(obj, mod);
1965 static void read_symbols(const char *modname)
1967 const char *symname;
1972 struct elf_info info = { };
1975 if (!parse_elf(&info, modname))
1978 if (!strends(modname, ".o")) {
1979 error("%s: filename must be suffixed with .o\n", modname);
1983 /* strip trailing .o */
1984 mod = new_module(modname, strlen(modname) - strlen(".o"));
1986 if (!mod->is_vmlinux) {
1987 license = get_modinfo(&info, "license");
1989 error("missing MODULE_LICENSE() in %s\n", modname);
1991 if (!license_is_gpl_compatible(license)) {
1992 mod->is_gpl_compatible = false;
1995 license = get_next_modinfo(&info, "license", license);
1998 namespace = get_modinfo(&info, "import_ns");
2000 add_namespace(&mod->imported_namespaces, namespace);
2001 namespace = get_next_modinfo(&info, "import_ns",
2006 for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
2007 symname = remove_dot(info.strtab + sym->st_name);
2009 handle_symbol(mod, &info, sym, symname);
2010 handle_moddevtable(mod, &info, sym, symname);
2013 for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
2014 symname = remove_dot(info.strtab + sym->st_name);
2016 /* Apply symbol namespaces from __kstrtabns_<symbol> entries. */
2017 if (strstarts(symname, "__kstrtabns_"))
2018 sym_update_namespace(symname + strlen("__kstrtabns_"),
2019 sym_get_data(&info, sym));
2022 check_sec_ref(modname, &info);
2024 if (!mod->is_vmlinux) {
2025 version = get_modinfo(&info, "version");
2026 if (version || all_versions)
2027 get_src_version(mod->name, mod->srcversion,
2028 sizeof(mod->srcversion) - 1);
2031 parse_elf_finish(&info);
2035 * Our trick to get versioning for module struct etc. - it's
2036 * never passed as an argument to an exported function, so
2037 * the automatic versioning doesn't pick it up, but it's really
2040 sym_add_unresolved("module_layout", mod, false);
2046 static void read_symbols_from_files(const char *filename)
2049 char fname[PATH_MAX];
2051 if (strcmp(filename, "-") != 0) {
2052 in = fopen(filename, "r");
2054 fatal("Can't open filenames file %s: %m", filename);
2057 while (fgets(fname, PATH_MAX, in) != NULL) {
2058 if (strends(fname, "\n"))
2059 fname[strlen(fname)-1] = '\0';
2060 read_symbols(fname);
2069 /* We first write the generated file into memory using the
2070 * following helper, then compare to the file on disk and
2071 * only update the later if anything changed */
2073 void __attribute__((format(printf, 2, 3))) buf_printf(struct buffer *buf,
2074 const char *fmt, ...)
2081 len = vsnprintf(tmp, SZ, fmt, ap);
2082 buf_write(buf, tmp, len);
2086 void buf_write(struct buffer *buf, const char *s, int len)
2088 if (buf->size - buf->pos < len) {
2089 buf->size += len + SZ;
2090 buf->p = NOFAIL(realloc(buf->p, buf->size));
2092 strncpy(buf->p + buf->pos, s, len);
2096 static void check_exports(struct module *mod)
2098 struct symbol *s, *exp;
2100 list_for_each_entry(s, &mod->unresolved_symbols, list) {
2101 const char *basename;
2102 exp = find_symbol(s->name);
2104 if (!s->weak && nr_unresolved++ < MAX_UNRESOLVED_REPORTS)
2105 modpost_log(warn_unresolved ? LOG_WARN : LOG_ERROR,
2106 "\"%s\" [%s.ko] undefined!\n",
2107 s->name, mod->name);
2110 if (exp->module == mod) {
2111 error("\"%s\" [%s.ko] was exported without definition\n",
2112 s->name, mod->name);
2116 s->module = exp->module;
2117 s->crc_valid = exp->crc_valid;
2120 basename = strrchr(mod->name, '/');
2124 basename = mod->name;
2126 if (exp->namespace &&
2127 !contains_namespace(&mod->imported_namespaces, exp->namespace)) {
2128 modpost_log(allow_missing_ns_imports ? LOG_WARN : LOG_ERROR,
2129 "module %s uses symbol %s from namespace %s, but does not import it.\n",
2130 basename, exp->name, exp->namespace);
2131 add_namespace(&mod->missing_namespaces, exp->namespace);
2134 if (!mod->is_gpl_compatible && exp->is_gpl_only)
2135 error("GPL-incompatible module %s.ko uses GPL-only symbol '%s'\n",
2136 basename, exp->name);
2140 static void check_modname_len(struct module *mod)
2142 const char *mod_name;
2144 mod_name = strrchr(mod->name, '/');
2145 if (mod_name == NULL)
2146 mod_name = mod->name;
2149 if (strlen(mod_name) >= MODULE_NAME_LEN)
2150 error("module name is too long [%s.ko]\n", mod->name);
2154 * Header for the generated file
2156 static void add_header(struct buffer *b, struct module *mod)
2158 buf_printf(b, "#include <linux/module.h>\n");
2160 * Include build-salt.h after module.h in order to
2161 * inherit the definitions.
2163 buf_printf(b, "#define INCLUDE_VERMAGIC\n");
2164 buf_printf(b, "#include <linux/build-salt.h>\n");
2165 buf_printf(b, "#include <linux/elfnote-lto.h>\n");
2166 buf_printf(b, "#include <linux/export-internal.h>\n");
2167 buf_printf(b, "#include <linux/vermagic.h>\n");
2168 buf_printf(b, "#include <linux/compiler.h>\n");
2169 buf_printf(b, "\n");
2170 buf_printf(b, "BUILD_SALT;\n");
2171 buf_printf(b, "BUILD_LTO_INFO;\n");
2172 buf_printf(b, "\n");
2173 buf_printf(b, "MODULE_INFO(vermagic, VERMAGIC_STRING);\n");
2174 buf_printf(b, "MODULE_INFO(name, KBUILD_MODNAME);\n");
2175 buf_printf(b, "\n");
2176 buf_printf(b, "__visible struct module __this_module\n");
2177 buf_printf(b, "__section(\".gnu.linkonce.this_module\") = {\n");
2178 buf_printf(b, "\t.name = KBUILD_MODNAME,\n");
2180 buf_printf(b, "\t.init = init_module,\n");
2181 if (mod->has_cleanup)
2182 buf_printf(b, "#ifdef CONFIG_MODULE_UNLOAD\n"
2183 "\t.exit = cleanup_module,\n"
2185 buf_printf(b, "\t.arch = MODULE_ARCH_INIT,\n");
2186 buf_printf(b, "};\n");
2188 if (!external_module)
2189 buf_printf(b, "\nMODULE_INFO(intree, \"Y\");\n");
2193 "#ifdef CONFIG_RETPOLINE\n"
2194 "MODULE_INFO(retpoline, \"Y\");\n"
2197 if (strstarts(mod->name, "drivers/staging"))
2198 buf_printf(b, "\nMODULE_INFO(staging, \"Y\");\n");
2201 static void add_exported_symbols(struct buffer *buf, struct module *mod)
2208 /* record CRCs for exported symbols */
2209 buf_printf(buf, "\n");
2210 list_for_each_entry(sym, &mod->exported_symbols, list) {
2211 if (!sym->crc_valid) {
2212 warn("EXPORT symbol \"%s\" [%s%s] version generation failed, symbol will not be versioned.\n"
2213 "Is \"%s\" prototyped in <asm/asm-prototypes.h>?\n",
2214 sym->name, mod->name, mod->is_vmlinux ? "" : ".ko",
2219 buf_printf(buf, "SYMBOL_CRC(%s, 0x%08x, \"%s\");\n",
2220 sym->name, sym->crc, sym->is_gpl_only ? "_gpl" : "");
2225 * Record CRCs for unresolved symbols
2227 static void add_versions(struct buffer *b, struct module *mod)
2234 buf_printf(b, "\n");
2235 buf_printf(b, "static const struct modversion_info ____versions[]\n");
2236 buf_printf(b, "__used __section(\"__versions\") = {\n");
2238 list_for_each_entry(s, &mod->unresolved_symbols, list) {
2241 if (!s->crc_valid) {
2242 warn("\"%s\" [%s.ko] has no CRC!\n",
2243 s->name, mod->name);
2246 if (strlen(s->name) >= MODULE_NAME_LEN) {
2247 error("too long symbol \"%s\" [%s.ko]\n",
2248 s->name, mod->name);
2251 buf_printf(b, "\t{ %#8x, \"%s\" },\n",
2255 buf_printf(b, "};\n");
2258 static void add_depends(struct buffer *b, struct module *mod)
2263 /* Clear ->seen flag of modules that own symbols needed by this. */
2264 list_for_each_entry(s, &mod->unresolved_symbols, list) {
2266 s->module->seen = s->module->is_vmlinux;
2269 buf_printf(b, "\n");
2270 buf_printf(b, "MODULE_INFO(depends, \"");
2271 list_for_each_entry(s, &mod->unresolved_symbols, list) {
2276 if (s->module->seen)
2279 s->module->seen = true;
2280 p = strrchr(s->module->name, '/');
2284 p = s->module->name;
2285 buf_printf(b, "%s%s", first ? "" : ",", p);
2288 buf_printf(b, "\");\n");
2291 static void add_srcversion(struct buffer *b, struct module *mod)
2293 if (mod->srcversion[0]) {
2294 buf_printf(b, "\n");
2295 buf_printf(b, "MODULE_INFO(srcversion, \"%s\");\n",
2300 static void write_buf(struct buffer *b, const char *fname)
2307 file = fopen(fname, "w");
2312 if (fwrite(b->p, 1, b->pos, file) != b->pos) {
2316 if (fclose(file) != 0) {
2322 static void write_if_changed(struct buffer *b, const char *fname)
2328 file = fopen(fname, "r");
2332 if (fstat(fileno(file), &st) < 0)
2335 if (st.st_size != b->pos)
2338 tmp = NOFAIL(malloc(b->pos));
2339 if (fread(tmp, 1, b->pos, file) != b->pos)
2342 if (memcmp(tmp, b->p, b->pos) != 0)
2354 write_buf(b, fname);
2357 static void write_vmlinux_export_c_file(struct module *mod)
2359 struct buffer buf = { };
2362 "#include <linux/export-internal.h>\n");
2364 add_exported_symbols(&buf, mod);
2365 write_if_changed(&buf, ".vmlinux.export.c");
2369 /* do sanity checks, and generate *.mod.c file */
2370 static void write_mod_c_file(struct module *mod)
2372 struct buffer buf = { };
2373 char fname[PATH_MAX];
2376 check_modname_len(mod);
2379 add_header(&buf, mod);
2380 add_exported_symbols(&buf, mod);
2381 add_versions(&buf, mod);
2382 add_depends(&buf, mod);
2383 add_moddevtable(&buf, mod);
2384 add_srcversion(&buf, mod);
2386 ret = snprintf(fname, sizeof(fname), "%s.mod.c", mod->name);
2387 if (ret >= sizeof(fname)) {
2388 error("%s: too long path was truncated\n", fname);
2392 write_if_changed(&buf, fname);
2398 /* parse Module.symvers file. line format:
2399 * 0x12345678<tab>symbol<tab>module<tab>export<tab>namespace
2401 static void read_dump(const char *fname)
2403 char *buf, *pos, *line;
2405 buf = read_text_file(fname);
2407 /* No symbol versions, silently ignore */
2412 while ((line = get_line(&pos))) {
2413 char *symname, *namespace, *modname, *d, *export;
2419 if (!(symname = strchr(line, '\t')))
2422 if (!(modname = strchr(symname, '\t')))
2425 if (!(export = strchr(modname, '\t')))
2428 if (!(namespace = strchr(export, '\t')))
2430 *namespace++ = '\0';
2432 crc = strtoul(line, &d, 16);
2433 if (*symname == '\0' || *modname == '\0' || *d != '\0')
2436 if (!strcmp(export, "EXPORT_SYMBOL_GPL")) {
2438 } else if (!strcmp(export, "EXPORT_SYMBOL")) {
2441 error("%s: unknown license %s. skip", symname, export);
2445 mod = find_module(modname);
2447 mod = new_module(modname, strlen(modname));
2448 mod->from_dump = true;
2450 s = sym_add_exported(symname, mod, gpl_only);
2451 sym_set_crc(s, crc);
2452 sym_update_namespace(symname, namespace);
2458 fatal("parse error in symbol dump file\n");
2461 static void write_dump(const char *fname)
2463 struct buffer buf = { };
2467 list_for_each_entry(mod, &modules, list) {
2470 list_for_each_entry(sym, &mod->exported_symbols, list) {
2471 buf_printf(&buf, "0x%08x\t%s\t%s\tEXPORT_SYMBOL%s\t%s\n",
2472 sym->crc, sym->name, mod->name,
2473 sym->is_gpl_only ? "_GPL" : "",
2474 sym->namespace ?: "");
2477 write_buf(&buf, fname);
2481 static void write_namespace_deps_files(const char *fname)
2484 struct namespace_list *ns;
2485 struct buffer ns_deps_buf = {};
2487 list_for_each_entry(mod, &modules, list) {
2489 if (mod->from_dump || list_empty(&mod->missing_namespaces))
2492 buf_printf(&ns_deps_buf, "%s.ko:", mod->name);
2494 list_for_each_entry(ns, &mod->missing_namespaces, list)
2495 buf_printf(&ns_deps_buf, " %s", ns->namespace);
2497 buf_printf(&ns_deps_buf, "\n");
2500 write_if_changed(&ns_deps_buf, fname);
2501 free(ns_deps_buf.p);
2505 struct list_head list;
2509 int main(int argc, char **argv)
2512 char *missing_namespace_deps = NULL;
2513 char *dump_write = NULL, *files_source = NULL;
2515 LIST_HEAD(dump_lists);
2516 struct dump_list *dl, *dl2;
2518 while ((opt = getopt(argc, argv, "ei:mnT:o:awENd:")) != -1) {
2521 external_module = true;
2524 dl = NOFAIL(malloc(sizeof(*dl)));
2526 list_add_tail(&dl->list, &dump_lists);
2532 ignore_missing_files = true;
2535 dump_write = optarg;
2538 all_versions = true;
2541 files_source = optarg;
2544 warn_unresolved = true;
2547 sec_mismatch_warn_only = false;
2550 allow_missing_ns_imports = true;
2553 missing_namespace_deps = optarg;
2560 list_for_each_entry_safe(dl, dl2, &dump_lists, list) {
2561 read_dump(dl->file);
2562 list_del(&dl->list);
2566 while (optind < argc)
2567 read_symbols(argv[optind++]);
2570 read_symbols_from_files(files_source);
2572 list_for_each_entry(mod, &modules, list) {
2576 if (mod->is_vmlinux)
2577 write_vmlinux_export_c_file(mod);
2579 write_mod_c_file(mod);
2582 if (missing_namespace_deps)
2583 write_namespace_deps_files(missing_namespace_deps);
2586 write_dump(dump_write);
2587 if (sec_mismatch_count && !sec_mismatch_warn_only)
2588 error("Section mismatches detected.\n"
2589 "Set CONFIG_SECTION_MISMATCH_WARN_ONLY=y to allow them.\n");
2591 if (nr_unresolved > MAX_UNRESOLVED_REPORTS)
2592 warn("suppressed %u unresolved symbol warnings because there were too many)\n",
2593 nr_unresolved - MAX_UNRESOLVED_REPORTS);
2595 return error_occurred ? 1 : 0;