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 ...
23 #include "../../include/linux/license.h"
25 /* Are we using CONFIG_MODVERSIONS? */
26 static int modversions;
27 /* Is CONFIG_MODULE_SRCVERSION_ALL set? */
28 static int all_versions;
29 /* If we are modposting external module set to 1 */
30 static int external_module;
31 /* Only warn about unresolved symbols */
32 static int warn_unresolved;
33 /* How a symbol is exported */
34 static int sec_mismatch_count;
35 static int sec_mismatch_warn_only = true;
36 /* ignore missing files */
37 static int ignore_missing_files;
38 /* If set to 1, only warn (instead of error) about missing ns imports */
39 static int allow_missing_ns_imports;
41 static bool error_occurred;
44 * Cut off the warnings when there are too many. This typically occurs when
45 * vmlinux is missing. ('make modules' without building vmlinux.)
47 #define MAX_UNRESOLVED_REPORTS 10
48 static unsigned int nr_unresolved;
56 /* In kernel, this size is defined in linux/module.h;
57 * here we use Elf_Addr instead of long for covering cross-compile
60 #define MODULE_NAME_LEN (64 - sizeof(Elf_Addr))
62 void __attribute__((format(printf, 2, 3)))
63 modpost_log(enum loglevel loglevel, const char *fmt, ...)
69 fprintf(stderr, "WARNING: ");
72 fprintf(stderr, "ERROR: ");
75 fprintf(stderr, "FATAL: ");
77 default: /* invalid loglevel, ignore */
81 fprintf(stderr, "modpost: ");
83 va_start(arglist, fmt);
84 vfprintf(stderr, fmt, arglist);
87 if (loglevel == LOG_FATAL)
89 if (loglevel == LOG_ERROR)
90 error_occurred = true;
93 static inline bool strends(const char *str, const char *postfix)
95 if (strlen(str) < strlen(postfix))
98 return strcmp(str + strlen(str) - strlen(postfix), postfix) == 0;
101 void *do_nofail(void *ptr, const char *expr)
104 fatal("Memory allocation failure: %s.\n", expr);
109 char *read_text_file(const char *filename)
116 fd = open(filename, O_RDONLY);
122 if (fstat(fd, &st) < 0) {
127 buf = NOFAIL(malloc(st.st_size + 1));
134 bytes_read = read(fd, buf, nbytes);
135 if (bytes_read < 0) {
140 nbytes -= bytes_read;
142 buf[st.st_size] = '\0';
149 char *get_line(char **stringp)
151 char *orig = *stringp, *next;
153 /* do not return the unwanted extra line at EOF */
154 if (!orig || *orig == '\0')
157 /* don't use strsep here, it is not available everywhere */
158 next = strchr(orig, '\n');
167 /* A list of all modules we processed */
168 static struct module *modules;
170 static struct module *find_module(const char *modname)
174 for (mod = modules; mod; mod = mod->next)
175 if (strcmp(mod->name, modname) == 0)
180 static struct module *new_module(const char *modname)
184 mod = NOFAIL(malloc(sizeof(*mod) + strlen(modname) + 1));
185 memset(mod, 0, sizeof(*mod));
188 strcpy(mod->name, modname);
189 mod->is_vmlinux = (strcmp(modname, "vmlinux") == 0);
190 mod->gpl_compatible = -1;
197 /* A hash of all exported symbols,
198 * struct symbol is also used for lists of unresolved symbols */
200 #define SYMBOL_HASH_SIZE 1024
204 struct module *module;
209 unsigned int is_static:1; /* 1 if symbol is not global */
210 enum export export; /* Type of export */
214 static struct symbol *symbolhash[SYMBOL_HASH_SIZE];
216 /* This is based on the hash algorithm from gdbm, via tdb */
217 static inline unsigned int tdb_hash(const char *name)
219 unsigned value; /* Used to compute the hash value. */
220 unsigned i; /* Used to cycle through random values. */
222 /* Set the initial value from the key size. */
223 for (value = 0x238F13AF * strlen(name), i = 0; name[i]; i++)
224 value = (value + (((unsigned char *)name)[i] << (i*5 % 24)));
226 return (1103515243 * value + 12345);
230 * Allocate a new symbols for use in the hash of exported symbols or
231 * the list of unresolved symbols per module
233 static struct symbol *alloc_symbol(const char *name, unsigned int weak,
236 struct symbol *s = NOFAIL(malloc(sizeof(*s) + strlen(name) + 1));
238 memset(s, 0, sizeof(*s));
239 strcpy(s->name, name);
246 /* For the hash of exported symbols */
247 static struct symbol *new_symbol(const char *name, struct module *module,
252 hash = tdb_hash(name) % SYMBOL_HASH_SIZE;
253 symbolhash[hash] = alloc_symbol(name, 0, symbolhash[hash]);
255 return symbolhash[hash];
258 static struct symbol *find_symbol(const char *name)
262 /* For our purposes, .foo matches foo. PPC64 needs this. */
266 for (s = symbolhash[tdb_hash(name) % SYMBOL_HASH_SIZE]; s; s = s->next) {
267 if (strcmp(s->name, name) == 0)
273 static bool contains_namespace(struct namespace_list *list,
274 const char *namespace)
276 for (; list; list = list->next)
277 if (!strcmp(list->namespace, namespace))
283 static void add_namespace(struct namespace_list **list, const char *namespace)
285 struct namespace_list *ns_entry;
287 if (!contains_namespace(*list, namespace)) {
288 ns_entry = NOFAIL(malloc(sizeof(struct namespace_list) +
289 strlen(namespace) + 1));
290 strcpy(ns_entry->namespace, namespace);
291 ns_entry->next = *list;
296 static bool module_imports_namespace(struct module *module,
297 const char *namespace)
299 return contains_namespace(module->imported_namespaces, namespace);
302 static const struct {
306 { .str = "EXPORT_SYMBOL", .export = export_plain },
307 { .str = "EXPORT_SYMBOL_GPL", .export = export_gpl },
308 { .str = "(unknown)", .export = export_unknown },
312 static const char *export_str(enum export ex)
314 return export_list[ex].str;
317 static enum export export_no(const char *s)
322 return export_unknown;
323 for (i = 0; export_list[i].export != export_unknown; i++) {
324 if (strcmp(export_list[i].str, s) == 0)
325 return export_list[i].export;
327 return export_unknown;
330 static void *sym_get_data_by_offset(const struct elf_info *info,
331 unsigned int secindex, unsigned long offset)
333 Elf_Shdr *sechdr = &info->sechdrs[secindex];
335 if (info->hdr->e_type != ET_REL)
336 offset -= sechdr->sh_addr;
338 return (void *)info->hdr + sechdr->sh_offset + offset;
341 static void *sym_get_data(const struct elf_info *info, const Elf_Sym *sym)
343 return sym_get_data_by_offset(info, get_secindex(info, sym),
347 static const char *sech_name(const struct elf_info *info, Elf_Shdr *sechdr)
349 return sym_get_data_by_offset(info, info->secindex_strings,
353 static const char *sec_name(const struct elf_info *info, int secindex)
355 return sech_name(info, &info->sechdrs[secindex]);
358 #define strstarts(str, prefix) (strncmp(str, prefix, strlen(prefix)) == 0)
360 static enum export export_from_secname(struct elf_info *elf, unsigned int sec)
362 const char *secname = sec_name(elf, sec);
364 if (strstarts(secname, "___ksymtab+"))
366 else if (strstarts(secname, "___ksymtab_gpl+"))
369 return export_unknown;
372 static void sym_update_namespace(const char *symname, const char *namespace)
374 struct symbol *s = find_symbol(symname);
377 * That symbol should have been created earlier and thus this is
378 * actually an assertion.
381 error("Could not update namespace(%s) for symbol %s\n",
387 s->namespace = namespace[0] ? NOFAIL(strdup(namespace)) : NULL;
390 static struct symbol *sym_add_exported(const char *name, struct module *mod,
393 struct symbol *s = find_symbol(name);
396 s = new_symbol(name, mod, export);
397 } else if (!external_module || s->module->is_vmlinux ||
399 warn("%s: '%s' exported twice. Previous export was in %s%s\n",
400 mod->name, name, s->module->name,
401 s->module->is_vmlinux ? "" : ".ko");
410 static void sym_set_crc(const char *name, unsigned int crc)
412 struct symbol *s = find_symbol(name);
415 * Ignore stand-alone __crc_*, which might be auto-generated symbols
416 * such as __*_veneer in ARM ELF.
425 static void *grab_file(const char *filename, size_t *size)
428 void *map = MAP_FAILED;
431 fd = open(filename, O_RDONLY);
438 map = mmap(NULL, *size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
442 if (map == MAP_FAILED)
447 static void release_file(void *file, size_t size)
452 static int parse_elf(struct elf_info *info, const char *filename)
458 const char *secstrings;
459 unsigned int symtab_idx = ~0U, symtab_shndx_idx = ~0U;
461 hdr = grab_file(filename, &info->size);
463 if (ignore_missing_files) {
464 fprintf(stderr, "%s: %s (ignored)\n", filename,
472 if (info->size < sizeof(*hdr)) {
473 /* file too small, assume this is an empty .o file */
476 /* Is this a valid ELF file? */
477 if ((hdr->e_ident[EI_MAG0] != ELFMAG0) ||
478 (hdr->e_ident[EI_MAG1] != ELFMAG1) ||
479 (hdr->e_ident[EI_MAG2] != ELFMAG2) ||
480 (hdr->e_ident[EI_MAG3] != ELFMAG3)) {
481 /* Not an ELF file - silently ignore it */
484 /* Fix endianness in ELF header */
485 hdr->e_type = TO_NATIVE(hdr->e_type);
486 hdr->e_machine = TO_NATIVE(hdr->e_machine);
487 hdr->e_version = TO_NATIVE(hdr->e_version);
488 hdr->e_entry = TO_NATIVE(hdr->e_entry);
489 hdr->e_phoff = TO_NATIVE(hdr->e_phoff);
490 hdr->e_shoff = TO_NATIVE(hdr->e_shoff);
491 hdr->e_flags = TO_NATIVE(hdr->e_flags);
492 hdr->e_ehsize = TO_NATIVE(hdr->e_ehsize);
493 hdr->e_phentsize = TO_NATIVE(hdr->e_phentsize);
494 hdr->e_phnum = TO_NATIVE(hdr->e_phnum);
495 hdr->e_shentsize = TO_NATIVE(hdr->e_shentsize);
496 hdr->e_shnum = TO_NATIVE(hdr->e_shnum);
497 hdr->e_shstrndx = TO_NATIVE(hdr->e_shstrndx);
498 sechdrs = (void *)hdr + hdr->e_shoff;
499 info->sechdrs = sechdrs;
501 /* Check if file offset is correct */
502 if (hdr->e_shoff > info->size) {
503 fatal("section header offset=%lu in file '%s' is bigger than filesize=%zu\n",
504 (unsigned long)hdr->e_shoff, filename, info->size);
508 if (hdr->e_shnum == SHN_UNDEF) {
510 * There are more than 64k sections,
511 * read count from .sh_size.
513 info->num_sections = TO_NATIVE(sechdrs[0].sh_size);
516 info->num_sections = hdr->e_shnum;
518 if (hdr->e_shstrndx == SHN_XINDEX) {
519 info->secindex_strings = TO_NATIVE(sechdrs[0].sh_link);
522 info->secindex_strings = hdr->e_shstrndx;
525 /* Fix endianness in section headers */
526 for (i = 0; i < info->num_sections; i++) {
527 sechdrs[i].sh_name = TO_NATIVE(sechdrs[i].sh_name);
528 sechdrs[i].sh_type = TO_NATIVE(sechdrs[i].sh_type);
529 sechdrs[i].sh_flags = TO_NATIVE(sechdrs[i].sh_flags);
530 sechdrs[i].sh_addr = TO_NATIVE(sechdrs[i].sh_addr);
531 sechdrs[i].sh_offset = TO_NATIVE(sechdrs[i].sh_offset);
532 sechdrs[i].sh_size = TO_NATIVE(sechdrs[i].sh_size);
533 sechdrs[i].sh_link = TO_NATIVE(sechdrs[i].sh_link);
534 sechdrs[i].sh_info = TO_NATIVE(sechdrs[i].sh_info);
535 sechdrs[i].sh_addralign = TO_NATIVE(sechdrs[i].sh_addralign);
536 sechdrs[i].sh_entsize = TO_NATIVE(sechdrs[i].sh_entsize);
538 /* Find symbol table. */
539 secstrings = (void *)hdr + sechdrs[info->secindex_strings].sh_offset;
540 for (i = 1; i < info->num_sections; i++) {
542 int nobits = sechdrs[i].sh_type == SHT_NOBITS;
544 if (!nobits && sechdrs[i].sh_offset > info->size) {
545 fatal("%s is truncated. sechdrs[i].sh_offset=%lu > "
546 "sizeof(*hrd)=%zu\n", filename,
547 (unsigned long)sechdrs[i].sh_offset,
551 secname = secstrings + sechdrs[i].sh_name;
552 if (strcmp(secname, ".modinfo") == 0) {
554 fatal("%s has NOBITS .modinfo\n", filename);
555 info->modinfo = (void *)hdr + sechdrs[i].sh_offset;
556 info->modinfo_len = sechdrs[i].sh_size;
559 if (sechdrs[i].sh_type == SHT_SYMTAB) {
560 unsigned int sh_link_idx;
562 info->symtab_start = (void *)hdr +
563 sechdrs[i].sh_offset;
564 info->symtab_stop = (void *)hdr +
565 sechdrs[i].sh_offset + sechdrs[i].sh_size;
566 sh_link_idx = sechdrs[i].sh_link;
567 info->strtab = (void *)hdr +
568 sechdrs[sh_link_idx].sh_offset;
571 /* 32bit section no. table? ("more than 64k sections") */
572 if (sechdrs[i].sh_type == SHT_SYMTAB_SHNDX) {
573 symtab_shndx_idx = i;
574 info->symtab_shndx_start = (void *)hdr +
575 sechdrs[i].sh_offset;
576 info->symtab_shndx_stop = (void *)hdr +
577 sechdrs[i].sh_offset + sechdrs[i].sh_size;
580 if (!info->symtab_start)
581 fatal("%s has no symtab?\n", filename);
583 /* Fix endianness in symbols */
584 for (sym = info->symtab_start; sym < info->symtab_stop; sym++) {
585 sym->st_shndx = TO_NATIVE(sym->st_shndx);
586 sym->st_name = TO_NATIVE(sym->st_name);
587 sym->st_value = TO_NATIVE(sym->st_value);
588 sym->st_size = TO_NATIVE(sym->st_size);
591 if (symtab_shndx_idx != ~0U) {
593 if (symtab_idx != sechdrs[symtab_shndx_idx].sh_link)
594 fatal("%s: SYMTAB_SHNDX has bad sh_link: %u!=%u\n",
595 filename, sechdrs[symtab_shndx_idx].sh_link,
598 for (p = info->symtab_shndx_start; p < info->symtab_shndx_stop;
606 static void parse_elf_finish(struct elf_info *info)
608 release_file(info->hdr, info->size);
611 static int ignore_undef_symbol(struct elf_info *info, const char *symname)
613 /* ignore __this_module, it will be resolved shortly */
614 if (strcmp(symname, "__this_module") == 0)
616 /* ignore global offset table */
617 if (strcmp(symname, "_GLOBAL_OFFSET_TABLE_") == 0)
619 if (info->hdr->e_machine == EM_PPC)
620 /* Special register function linked on all modules during final link of .ko */
621 if (strstarts(symname, "_restgpr_") ||
622 strstarts(symname, "_savegpr_") ||
623 strstarts(symname, "_rest32gpr_") ||
624 strstarts(symname, "_save32gpr_") ||
625 strstarts(symname, "_restvr_") ||
626 strstarts(symname, "_savevr_"))
628 if (info->hdr->e_machine == EM_PPC64)
629 /* Special register function linked on all modules during final link of .ko */
630 if (strstarts(symname, "_restgpr0_") ||
631 strstarts(symname, "_savegpr0_") ||
632 strstarts(symname, "_restvr_") ||
633 strstarts(symname, "_savevr_") ||
634 strcmp(symname, ".TOC.") == 0)
637 if (info->hdr->e_machine == EM_S390)
638 /* Expoline thunks are linked on all kernel modules during final link of .ko */
639 if (strstarts(symname, "__s390_indirect_jump_r"))
641 /* Do not ignore this symbol */
645 static void handle_modversion(const struct module *mod,
646 const struct elf_info *info,
647 const Elf_Sym *sym, const char *symname)
651 if (sym->st_shndx == SHN_UNDEF) {
652 warn("EXPORT symbol \"%s\" [%s%s] version generation failed, symbol will not be versioned.\n"
653 "Is \"%s\" prototyped in <asm/asm-prototypes.h>?\n",
654 symname, mod->name, mod->is_vmlinux ? "" : ".ko",
660 if (sym->st_shndx == SHN_ABS) {
665 /* symbol points to the CRC in the ELF object */
666 crcp = sym_get_data(info, sym);
667 crc = TO_NATIVE(*crcp);
669 sym_set_crc(symname, crc);
672 static void handle_symbol(struct module *mod, struct elf_info *info,
673 const Elf_Sym *sym, const char *symname)
677 switch (sym->st_shndx) {
679 if (strstarts(symname, "__gnu_lto_")) {
680 /* Should warn here, but modpost runs before the linker */
682 warn("\"%s\" [%s] is COMMON symbol\n", symname, mod->name);
685 /* undefined symbol */
686 if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL &&
687 ELF_ST_BIND(sym->st_info) != STB_WEAK)
689 if (ignore_undef_symbol(info, symname))
691 if (info->hdr->e_machine == EM_SPARC ||
692 info->hdr->e_machine == EM_SPARCV9) {
693 /* Ignore register directives. */
694 if (ELF_ST_TYPE(sym->st_info) == STT_SPARC_REGISTER)
696 if (symname[0] == '.') {
697 char *munged = NOFAIL(strdup(symname));
699 munged[1] = toupper(munged[1]);
704 mod->unres = alloc_symbol(symname,
705 ELF_ST_BIND(sym->st_info) == STB_WEAK,
709 /* All exported symbols */
710 if (strstarts(symname, "__ksymtab_")) {
713 name = symname + strlen("__ksymtab_");
714 export = export_from_secname(info,
715 get_secindex(info, sym));
716 sym_add_exported(name, mod, export);
718 if (strcmp(symname, "init_module") == 0)
720 if (strcmp(symname, "cleanup_module") == 0)
721 mod->has_cleanup = 1;
727 * Parse tag=value strings from .modinfo section
729 static char *next_string(char *string, unsigned long *secsize)
731 /* Skip non-zero chars */
734 if ((*secsize)-- <= 1)
738 /* Skip any zero padding. */
741 if ((*secsize)-- <= 1)
747 static char *get_next_modinfo(struct elf_info *info, const char *tag,
751 unsigned int taglen = strlen(tag);
752 char *modinfo = info->modinfo;
753 unsigned long size = info->modinfo_len;
756 size -= prev - modinfo;
757 modinfo = next_string(prev, &size);
760 for (p = modinfo; p; p = next_string(p, &size)) {
761 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
762 return p + taglen + 1;
767 static char *get_modinfo(struct elf_info *info, const char *tag)
770 return get_next_modinfo(info, tag, NULL);
774 * Test if string s ends in string sub
777 static int strrcmp(const char *s, const char *sub)
785 sublen = strlen(sub);
787 if ((slen == 0) || (sublen == 0))
793 return memcmp(s + slen - sublen, sub, sublen);
796 static const char *sym_name(struct elf_info *elf, Elf_Sym *sym)
799 return elf->strtab + sym->st_name;
804 /* The pattern is an array of simple patterns.
805 * "foo" will match an exact string equal to "foo"
806 * "*foo" will match a string that ends with "foo"
807 * "foo*" will match a string that begins with "foo"
808 * "*foo*" will match a string that contains "foo"
810 static int match(const char *sym, const char * const pat[])
817 endp = p + strlen(p) - 1;
820 if (*p == '*' && *endp == '*') {
821 char *bare = NOFAIL(strndup(p + 1, strlen(p) - 2));
822 char *here = strstr(sym, bare);
829 else if (*p == '*') {
830 if (strrcmp(sym, p + 1) == 0)
834 else if (*endp == '*') {
835 if (strncmp(sym, p, strlen(p) - 1) == 0)
840 if (strcmp(p, sym) == 0)
848 /* sections that we do not want to do full section mismatch check on */
849 static const char *const section_white_list[] =
853 ".cranges", /* sh64 */
854 ".zdebug*", /* Compressed debug sections. */
855 ".GCC.command.line", /* record-gcc-switches */
856 ".mdebug*", /* alpha, score, mips etc. */
857 ".pdr", /* alpha, score, mips etc. */
862 ".xt.prop", /* xtensa */
863 ".xt.lit", /* xtensa */
864 ".arcextmap*", /* arc */
865 ".gnu.linkonce.arcext*", /* arc : modules */
866 ".cmem*", /* EZchip */
867 ".fmt_slot*", /* EZchip */
874 * This is used to find sections missing the SHF_ALLOC flag.
875 * The cause of this is often a section specified in assembler
876 * without "ax" / "aw".
878 static void check_section(const char *modname, struct elf_info *elf,
881 const char *sec = sech_name(elf, sechdr);
883 if (sechdr->sh_type == SHT_PROGBITS &&
884 !(sechdr->sh_flags & SHF_ALLOC) &&
885 !match(sec, section_white_list)) {
886 warn("%s (%s): unexpected non-allocatable section.\n"
887 "Did you forget to use \"ax\"/\"aw\" in a .S file?\n"
888 "Note that for example <linux/init.h> contains\n"
889 "section definitions for use in .S files.\n\n",
896 #define ALL_INIT_DATA_SECTIONS \
897 ".init.setup", ".init.rodata", ".meminit.rodata", \
898 ".init.data", ".meminit.data"
899 #define ALL_EXIT_DATA_SECTIONS \
900 ".exit.data", ".memexit.data"
902 #define ALL_INIT_TEXT_SECTIONS \
903 ".init.text", ".meminit.text"
904 #define ALL_EXIT_TEXT_SECTIONS \
905 ".exit.text", ".memexit.text"
907 #define ALL_PCI_INIT_SECTIONS \
908 ".pci_fixup_early", ".pci_fixup_header", ".pci_fixup_final", \
909 ".pci_fixup_enable", ".pci_fixup_resume", \
910 ".pci_fixup_resume_early", ".pci_fixup_suspend"
912 #define ALL_XXXINIT_SECTIONS MEM_INIT_SECTIONS
913 #define ALL_XXXEXIT_SECTIONS MEM_EXIT_SECTIONS
915 #define ALL_INIT_SECTIONS INIT_SECTIONS, ALL_XXXINIT_SECTIONS
916 #define ALL_EXIT_SECTIONS EXIT_SECTIONS, ALL_XXXEXIT_SECTIONS
918 #define DATA_SECTIONS ".data", ".data.rel"
919 #define TEXT_SECTIONS ".text", ".text.unlikely", ".sched.text", \
920 ".kprobes.text", ".cpuidle.text", ".noinstr.text"
921 #define OTHER_TEXT_SECTIONS ".ref.text", ".head.text", ".spinlock.text", \
922 ".fixup", ".entry.text", ".exception.text", ".text.*", \
923 ".coldtext", ".softirqentry.text"
925 #define INIT_SECTIONS ".init.*"
926 #define MEM_INIT_SECTIONS ".meminit.*"
928 #define EXIT_SECTIONS ".exit.*"
929 #define MEM_EXIT_SECTIONS ".memexit.*"
931 #define ALL_TEXT_SECTIONS ALL_INIT_TEXT_SECTIONS, ALL_EXIT_TEXT_SECTIONS, \
932 TEXT_SECTIONS, OTHER_TEXT_SECTIONS
934 /* init data sections */
935 static const char *const init_data_sections[] =
936 { ALL_INIT_DATA_SECTIONS, NULL };
938 /* all init sections */
939 static const char *const init_sections[] = { ALL_INIT_SECTIONS, NULL };
941 /* All init and exit sections (code + data) */
942 static const char *const init_exit_sections[] =
943 {ALL_INIT_SECTIONS, ALL_EXIT_SECTIONS, NULL };
945 /* all text sections */
946 static const char *const text_sections[] = { ALL_TEXT_SECTIONS, NULL };
949 static const char *const data_sections[] = { DATA_SECTIONS, NULL };
952 /* symbols in .data that may refer to init/exit sections */
953 #define DEFAULT_SYMBOL_WHITE_LIST \
955 "*_template", /* scsi uses *_template a lot */ \
956 "*_timer", /* arm uses ops structures named _timer a lot */ \
957 "*_sht", /* scsi also used *_sht to some extent */ \
963 static const char *const head_sections[] = { ".head.text*", NULL };
964 static const char *const linker_symbols[] =
965 { "__init_begin", "_sinittext", "_einittext", NULL };
966 static const char *const optim_symbols[] = { "*.constprop.*", NULL };
973 XXXINIT_TO_SOME_INIT,
974 XXXEXIT_TO_SOME_EXIT,
975 ANY_INIT_TO_ANY_EXIT,
976 ANY_EXIT_TO_ANY_INIT,
982 * Describe how to match sections on different criteria:
984 * @fromsec: Array of sections to be matched.
986 * @bad_tosec: Relocations applied to a section in @fromsec to a section in
987 * this array is forbidden (black-list). Can be empty.
989 * @good_tosec: Relocations applied to a section in @fromsec must be
990 * targeting sections in this array (white-list). Can be empty.
992 * @mismatch: Type of mismatch.
994 * @symbol_white_list: Do not match a relocation to a symbol in this list
995 * even if it is targeting a section in @bad_to_sec.
997 * @handler: Specific handler to call when a match is found. If NULL,
998 * default_mismatch_handler() will be called.
1001 struct sectioncheck {
1002 const char *fromsec[20];
1003 const char *bad_tosec[20];
1004 const char *good_tosec[20];
1005 enum mismatch mismatch;
1006 const char *symbol_white_list[20];
1007 void (*handler)(const char *modname, struct elf_info *elf,
1008 const struct sectioncheck* const mismatch,
1009 Elf_Rela *r, Elf_Sym *sym, const char *fromsec);
1013 static void extable_mismatch_handler(const char *modname, struct elf_info *elf,
1014 const struct sectioncheck* const mismatch,
1015 Elf_Rela *r, Elf_Sym *sym,
1016 const char *fromsec);
1018 static const struct sectioncheck sectioncheck[] = {
1019 /* Do not reference init/exit code/data from
1020 * normal code and data
1023 .fromsec = { TEXT_SECTIONS, NULL },
1024 .bad_tosec = { ALL_INIT_SECTIONS, NULL },
1025 .mismatch = TEXT_TO_ANY_INIT,
1026 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1029 .fromsec = { DATA_SECTIONS, NULL },
1030 .bad_tosec = { ALL_XXXINIT_SECTIONS, NULL },
1031 .mismatch = DATA_TO_ANY_INIT,
1032 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1035 .fromsec = { DATA_SECTIONS, NULL },
1036 .bad_tosec = { INIT_SECTIONS, NULL },
1037 .mismatch = DATA_TO_ANY_INIT,
1038 .symbol_white_list = {
1039 "*_template", "*_timer", "*_sht", "*_ops",
1040 "*_probe", "*_probe_one", "*_console", NULL
1044 .fromsec = { TEXT_SECTIONS, NULL },
1045 .bad_tosec = { ALL_EXIT_SECTIONS, NULL },
1046 .mismatch = TEXT_TO_ANY_EXIT,
1047 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1050 .fromsec = { DATA_SECTIONS, NULL },
1051 .bad_tosec = { ALL_EXIT_SECTIONS, NULL },
1052 .mismatch = DATA_TO_ANY_EXIT,
1053 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1055 /* Do not reference init code/data from meminit code/data */
1057 .fromsec = { ALL_XXXINIT_SECTIONS, NULL },
1058 .bad_tosec = { INIT_SECTIONS, NULL },
1059 .mismatch = XXXINIT_TO_SOME_INIT,
1060 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1062 /* Do not reference exit code/data from memexit code/data */
1064 .fromsec = { ALL_XXXEXIT_SECTIONS, NULL },
1065 .bad_tosec = { EXIT_SECTIONS, NULL },
1066 .mismatch = XXXEXIT_TO_SOME_EXIT,
1067 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1069 /* Do not use exit code/data from init code */
1071 .fromsec = { ALL_INIT_SECTIONS, NULL },
1072 .bad_tosec = { ALL_EXIT_SECTIONS, NULL },
1073 .mismatch = ANY_INIT_TO_ANY_EXIT,
1074 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1076 /* Do not use init code/data from exit code */
1078 .fromsec = { ALL_EXIT_SECTIONS, NULL },
1079 .bad_tosec = { ALL_INIT_SECTIONS, NULL },
1080 .mismatch = ANY_EXIT_TO_ANY_INIT,
1081 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1084 .fromsec = { ALL_PCI_INIT_SECTIONS, NULL },
1085 .bad_tosec = { INIT_SECTIONS, NULL },
1086 .mismatch = ANY_INIT_TO_ANY_EXIT,
1087 .symbol_white_list = { NULL },
1089 /* Do not export init/exit functions or data */
1091 .fromsec = { "__ksymtab*", NULL },
1092 .bad_tosec = { INIT_SECTIONS, EXIT_SECTIONS, NULL },
1093 .mismatch = EXPORT_TO_INIT_EXIT,
1094 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1097 .fromsec = { "__ex_table", NULL },
1098 /* If you're adding any new black-listed sections in here, consider
1099 * adding a special 'printer' for them in scripts/check_extable.
1101 .bad_tosec = { ".altinstr_replacement", NULL },
1102 .good_tosec = {ALL_TEXT_SECTIONS , NULL},
1103 .mismatch = EXTABLE_TO_NON_TEXT,
1104 .handler = extable_mismatch_handler,
1108 static const struct sectioncheck *section_mismatch(
1109 const char *fromsec, const char *tosec)
1112 int elems = sizeof(sectioncheck) / sizeof(struct sectioncheck);
1113 const struct sectioncheck *check = §ioncheck[0];
1116 * The target section could be the SHT_NUL section when we're
1117 * handling relocations to un-resolved symbols, trying to match it
1118 * doesn't make much sense and causes build failures on parisc
1124 for (i = 0; i < elems; i++) {
1125 if (match(fromsec, check->fromsec)) {
1126 if (check->bad_tosec[0] && match(tosec, check->bad_tosec))
1128 if (check->good_tosec[0] && !match(tosec, check->good_tosec))
1137 * Whitelist to allow certain references to pass with no warning.
1140 * If a module parameter is declared __initdata and permissions=0
1141 * then this is legal despite the warning generated.
1142 * We cannot see value of permissions here, so just ignore
1144 * The pattern is identified by:
1145 * tosec = .init.data
1150 * module_param_call() ops can refer to __init set function if permissions=0
1151 * The pattern is identified by:
1152 * tosec = .init.text
1154 * atsym = __param_ops_*
1157 * Many drivers utilise a *driver container with references to
1158 * add, remove, probe functions etc.
1159 * the pattern is identified by:
1160 * tosec = init or exit section
1161 * fromsec = data section
1162 * atsym = *driver, *_template, *_sht, *_ops, *_probe,
1163 * *probe_one, *_console, *_timer
1166 * Whitelist all references from .head.text to any init section
1169 * Some symbols belong to init section but still it is ok to reference
1170 * these from non-init sections as these symbols don't have any memory
1171 * allocated for them and symbol address and value are same. So even
1172 * if init section is freed, its ok to reference those symbols.
1173 * For ex. symbols marking the init section boundaries.
1174 * This pattern is identified by
1175 * refsymname = __init_begin, _sinittext, _einittext
1178 * GCC may optimize static inlines when fed constant arg(s) resulting
1179 * in functions like cpumask_empty() -- generating an associated symbol
1180 * cpumask_empty.constprop.3 that appears in the audit. If the const that
1181 * is passed in comes from __init, like say nmi_ipi_mask, we get a
1182 * meaningless section warning. May need to add isra symbols too...
1183 * This pattern is identified by
1184 * tosec = init section
1185 * fromsec = text section
1186 * refsymname = *.constprop.*
1189 * Hide section mismatch warnings for ELF local symbols. The goal
1190 * is to eliminate false positive modpost warnings caused by
1191 * compiler-generated ELF local symbol names such as ".LANCHOR1".
1192 * Autogenerated symbol names bypass modpost's "Pattern 2"
1193 * whitelisting, which relies on pattern-matching against symbol
1194 * names to work. (One situation where gcc can autogenerate ELF
1195 * local symbols is when "-fsection-anchors" is used.)
1197 static int secref_whitelist(const struct sectioncheck *mismatch,
1198 const char *fromsec, const char *fromsym,
1199 const char *tosec, const char *tosym)
1201 /* Check for pattern 1 */
1202 if (match(tosec, init_data_sections) &&
1203 match(fromsec, data_sections) &&
1204 strstarts(fromsym, "__param"))
1207 /* Check for pattern 1a */
1208 if (strcmp(tosec, ".init.text") == 0 &&
1209 match(fromsec, data_sections) &&
1210 strstarts(fromsym, "__param_ops_"))
1213 /* Check for pattern 2 */
1214 if (match(tosec, init_exit_sections) &&
1215 match(fromsec, data_sections) &&
1216 match(fromsym, mismatch->symbol_white_list))
1219 /* Check for pattern 3 */
1220 if (match(fromsec, head_sections) &&
1221 match(tosec, init_sections))
1224 /* Check for pattern 4 */
1225 if (match(tosym, linker_symbols))
1228 /* Check for pattern 5 */
1229 if (match(fromsec, text_sections) &&
1230 match(tosec, init_sections) &&
1231 match(fromsym, optim_symbols))
1234 /* Check for pattern 6 */
1235 if (strstarts(fromsym, ".L"))
1241 static inline int is_arm_mapping_symbol(const char *str)
1243 return str[0] == '$' && strchr("axtd", str[1])
1244 && (str[2] == '\0' || str[2] == '.');
1248 * If there's no name there, ignore it; likewise, ignore it if it's
1249 * one of the magic symbols emitted used by current ARM tools.
1251 * Otherwise if find_symbols_between() returns those symbols, they'll
1252 * fail the whitelist tests and cause lots of false alarms ... fixable
1253 * only by merging __exit and __init sections into __text, bloating
1254 * the kernel (which is especially evil on embedded platforms).
1256 static inline int is_valid_name(struct elf_info *elf, Elf_Sym *sym)
1258 const char *name = elf->strtab + sym->st_name;
1260 if (!name || !strlen(name))
1262 return !is_arm_mapping_symbol(name);
1266 * Find symbol based on relocation record info.
1267 * In some cases the symbol supplied is a valid symbol so
1268 * return refsym. If st_name != 0 we assume this is a valid symbol.
1269 * In other cases the symbol needs to be looked up in the symbol table
1270 * based on section and address.
1272 static Elf_Sym *find_elf_symbol(struct elf_info *elf, Elf64_Sword addr,
1276 Elf_Sym *near = NULL;
1277 Elf64_Sword distance = 20;
1279 unsigned int relsym_secindex;
1281 if (relsym->st_name != 0)
1284 relsym_secindex = get_secindex(elf, relsym);
1285 for (sym = elf->symtab_start; sym < elf->symtab_stop; sym++) {
1286 if (get_secindex(elf, sym) != relsym_secindex)
1288 if (ELF_ST_TYPE(sym->st_info) == STT_SECTION)
1290 if (!is_valid_name(elf, sym))
1292 if (sym->st_value == addr)
1294 /* Find a symbol nearby - addr are maybe negative */
1295 d = sym->st_value - addr;
1297 d = addr - sym->st_value;
1303 /* We need a close match */
1311 * Find symbols before or equal addr and after addr - in the section sec.
1312 * If we find two symbols with equal offset prefer one with a valid name.
1313 * The ELF format may have a better way to detect what type of symbol
1314 * it is, but this works for now.
1316 static Elf_Sym *find_elf_symbol2(struct elf_info *elf, Elf_Addr addr,
1320 Elf_Sym *near = NULL;
1321 Elf_Addr distance = ~0;
1323 for (sym = elf->symtab_start; sym < elf->symtab_stop; sym++) {
1326 if (is_shndx_special(sym->st_shndx))
1328 symsec = sec_name(elf, get_secindex(elf, sym));
1329 if (strcmp(symsec, sec) != 0)
1331 if (!is_valid_name(elf, sym))
1333 if (sym->st_value <= addr) {
1334 if ((addr - sym->st_value) < distance) {
1335 distance = addr - sym->st_value;
1337 } else if ((addr - sym->st_value) == distance) {
1346 * Convert a section name to the function/data attribute
1347 * .init.text => __init
1348 * .memexitconst => __memconst
1351 * The memory of returned value has been allocated on a heap. The user of this
1352 * method should free it after usage.
1354 static char *sec2annotation(const char *s)
1356 if (match(s, init_exit_sections)) {
1357 char *p = NOFAIL(malloc(20));
1364 while (*s && *s != '.')
1369 if (strstr(s, "rodata") != NULL)
1370 strcat(p, "const ");
1371 else if (strstr(s, "data") != NULL)
1377 return NOFAIL(strdup(""));
1381 static int is_function(Elf_Sym *sym)
1384 return ELF_ST_TYPE(sym->st_info) == STT_FUNC;
1389 static void print_section_list(const char * const list[20])
1391 const char *const *s = list;
1394 fprintf(stderr, "%s", *s);
1397 fprintf(stderr, ", ");
1399 fprintf(stderr, "\n");
1402 static inline void get_pretty_name(int is_func, const char** name, const char** name_p)
1405 case 0: *name = "variable"; *name_p = ""; break;
1406 case 1: *name = "function"; *name_p = "()"; break;
1407 default: *name = "(unknown reference)"; *name_p = ""; break;
1412 * Print a warning about a section mismatch.
1413 * Try to find symbols near it so user can find it.
1414 * Check whitelist before warning - it may be a false positive.
1416 static void report_sec_mismatch(const char *modname,
1417 const struct sectioncheck *mismatch,
1418 const char *fromsec,
1419 unsigned long long fromaddr,
1420 const char *fromsym,
1422 const char *tosec, const char *tosym,
1425 const char *from, *from_p;
1426 const char *to, *to_p;
1430 sec_mismatch_count++;
1432 get_pretty_name(from_is_func, &from, &from_p);
1433 get_pretty_name(to_is_func, &to, &to_p);
1435 warn("%s(%s+0x%llx): Section mismatch in reference from the %s %s%s "
1436 "to the %s %s:%s%s\n",
1437 modname, fromsec, fromaddr, from, fromsym, from_p, to, tosec,
1440 switch (mismatch->mismatch) {
1441 case TEXT_TO_ANY_INIT:
1442 prl_from = sec2annotation(fromsec);
1443 prl_to = sec2annotation(tosec);
1445 "The function %s%s() references\n"
1447 "This is often because %s lacks a %s\n"
1448 "annotation or the annotation of %s is wrong.\n",
1450 to, prl_to, tosym, to_p,
1451 fromsym, prl_to, tosym);
1455 case DATA_TO_ANY_INIT: {
1456 prl_to = sec2annotation(tosec);
1458 "The variable %s references\n"
1460 "If the reference is valid then annotate the\n"
1461 "variable with __init* or __refdata (see linux/init.h) "
1462 "or name the variable:\n",
1463 fromsym, to, prl_to, tosym, to_p);
1464 print_section_list(mismatch->symbol_white_list);
1468 case TEXT_TO_ANY_EXIT:
1469 prl_to = sec2annotation(tosec);
1471 "The function %s() references a %s in an exit section.\n"
1472 "Often the %s %s%s has valid usage outside the exit section\n"
1473 "and the fix is to remove the %sannotation of %s.\n",
1474 fromsym, to, to, tosym, to_p, prl_to, tosym);
1477 case DATA_TO_ANY_EXIT: {
1478 prl_to = sec2annotation(tosec);
1480 "The variable %s references\n"
1482 "If the reference is valid then annotate the\n"
1483 "variable with __exit* (see linux/init.h) or "
1484 "name the variable:\n",
1485 fromsym, to, prl_to, tosym, to_p);
1486 print_section_list(mismatch->symbol_white_list);
1490 case XXXINIT_TO_SOME_INIT:
1491 case XXXEXIT_TO_SOME_EXIT:
1492 prl_from = sec2annotation(fromsec);
1493 prl_to = sec2annotation(tosec);
1495 "The %s %s%s%s references\n"
1497 "If %s is only used by %s then\n"
1498 "annotate %s with a matching annotation.\n",
1499 from, prl_from, fromsym, from_p,
1500 to, prl_to, tosym, to_p,
1501 tosym, fromsym, tosym);
1505 case ANY_INIT_TO_ANY_EXIT:
1506 prl_from = sec2annotation(fromsec);
1507 prl_to = sec2annotation(tosec);
1509 "The %s %s%s%s references\n"
1511 "This is often seen when error handling "
1512 "in the init function\n"
1513 "uses functionality in the exit path.\n"
1514 "The fix is often to remove the %sannotation of\n"
1515 "%s%s so it may be used outside an exit section.\n",
1516 from, prl_from, fromsym, from_p,
1517 to, prl_to, tosym, to_p,
1518 prl_to, tosym, to_p);
1522 case ANY_EXIT_TO_ANY_INIT:
1523 prl_from = sec2annotation(fromsec);
1524 prl_to = sec2annotation(tosec);
1526 "The %s %s%s%s references\n"
1528 "This is often seen when error handling "
1529 "in the exit function\n"
1530 "uses functionality in the init path.\n"
1531 "The fix is often to remove the %sannotation of\n"
1532 "%s%s so it may be used outside an init section.\n",
1533 from, prl_from, fromsym, from_p,
1534 to, prl_to, tosym, to_p,
1535 prl_to, tosym, to_p);
1539 case EXPORT_TO_INIT_EXIT:
1540 prl_to = sec2annotation(tosec);
1542 "The symbol %s is exported and annotated %s\n"
1543 "Fix this by removing the %sannotation of %s "
1544 "or drop the export.\n",
1545 tosym, prl_to, prl_to, tosym);
1548 case EXTABLE_TO_NON_TEXT:
1549 fatal("There's a special handler for this mismatch type, "
1550 "we should never get here.");
1553 fprintf(stderr, "\n");
1556 static void default_mismatch_handler(const char *modname, struct elf_info *elf,
1557 const struct sectioncheck* const mismatch,
1558 Elf_Rela *r, Elf_Sym *sym, const char *fromsec)
1564 const char *fromsym;
1566 from = find_elf_symbol2(elf, r->r_offset, fromsec);
1567 fromsym = sym_name(elf, from);
1569 if (strstarts(fromsym, "reference___initcall"))
1572 tosec = sec_name(elf, get_secindex(elf, sym));
1573 to = find_elf_symbol(elf, r->r_addend, sym);
1574 tosym = sym_name(elf, to);
1576 /* check whitelist - we may ignore it */
1577 if (secref_whitelist(mismatch,
1578 fromsec, fromsym, tosec, tosym)) {
1579 report_sec_mismatch(modname, mismatch,
1580 fromsec, r->r_offset, fromsym,
1581 is_function(from), tosec, tosym,
1586 static int is_executable_section(struct elf_info* elf, unsigned int section_index)
1588 if (section_index > elf->num_sections)
1589 fatal("section_index is outside elf->num_sections!\n");
1591 return ((elf->sechdrs[section_index].sh_flags & SHF_EXECINSTR) == SHF_EXECINSTR);
1595 * We rely on a gross hack in section_rel[a]() calling find_extable_entry_size()
1596 * to know the sizeof(struct exception_table_entry) for the target architecture.
1598 static unsigned int extable_entry_size = 0;
1599 static void find_extable_entry_size(const char* const sec, const Elf_Rela* r)
1602 * If we're currently checking the second relocation within __ex_table,
1603 * that relocation offset tells us the offsetof(struct
1604 * exception_table_entry, fixup) which is equal to sizeof(struct
1605 * exception_table_entry) divided by two. We use that to our advantage
1606 * since there's no portable way to get that size as every architecture
1607 * seems to go with different sized types. Not pretty but better than
1608 * hard-coding the size for every architecture..
1610 if (!extable_entry_size)
1611 extable_entry_size = r->r_offset * 2;
1614 static inline bool is_extable_fault_address(Elf_Rela *r)
1617 * extable_entry_size is only discovered after we've handled the
1618 * _second_ relocation in __ex_table, so only abort when we're not
1619 * handling the first reloc and extable_entry_size is zero.
1621 if (r->r_offset && extable_entry_size == 0)
1622 fatal("extable_entry size hasn't been discovered!\n");
1624 return ((r->r_offset == 0) ||
1625 (r->r_offset % extable_entry_size == 0));
1628 #define is_second_extable_reloc(Start, Cur, Sec) \
1629 (((Cur) == (Start) + 1) && (strcmp("__ex_table", (Sec)) == 0))
1631 static void report_extable_warnings(const char* modname, struct elf_info* elf,
1632 const struct sectioncheck* const mismatch,
1633 Elf_Rela* r, Elf_Sym* sym,
1634 const char* fromsec, const char* tosec)
1636 Elf_Sym* fromsym = find_elf_symbol2(elf, r->r_offset, fromsec);
1637 const char* fromsym_name = sym_name(elf, fromsym);
1638 Elf_Sym* tosym = find_elf_symbol(elf, r->r_addend, sym);
1639 const char* tosym_name = sym_name(elf, tosym);
1640 const char* from_pretty_name;
1641 const char* from_pretty_name_p;
1642 const char* to_pretty_name;
1643 const char* to_pretty_name_p;
1645 get_pretty_name(is_function(fromsym),
1646 &from_pretty_name, &from_pretty_name_p);
1647 get_pretty_name(is_function(tosym),
1648 &to_pretty_name, &to_pretty_name_p);
1650 warn("%s(%s+0x%lx): Section mismatch in reference"
1651 " from the %s %s%s to the %s %s:%s%s\n",
1652 modname, fromsec, (long)r->r_offset, from_pretty_name,
1653 fromsym_name, from_pretty_name_p,
1654 to_pretty_name, tosec, tosym_name, to_pretty_name_p);
1656 if (!match(tosec, mismatch->bad_tosec) &&
1657 is_executable_section(elf, get_secindex(elf, sym)))
1659 "The relocation at %s+0x%lx references\n"
1660 "section \"%s\" which is not in the list of\n"
1661 "authorized sections. If you're adding a new section\n"
1662 "and/or if this reference is valid, add \"%s\" to the\n"
1663 "list of authorized sections to jump to on fault.\n"
1664 "This can be achieved by adding \"%s\" to \n"
1665 "OTHER_TEXT_SECTIONS in scripts/mod/modpost.c.\n",
1666 fromsec, (long)r->r_offset, tosec, tosec, tosec);
1669 static void extable_mismatch_handler(const char* modname, struct elf_info *elf,
1670 const struct sectioncheck* const mismatch,
1671 Elf_Rela* r, Elf_Sym* sym,
1672 const char *fromsec)
1674 const char* tosec = sec_name(elf, get_secindex(elf, sym));
1676 sec_mismatch_count++;
1678 report_extable_warnings(modname, elf, mismatch, r, sym, fromsec, tosec);
1680 if (match(tosec, mismatch->bad_tosec))
1681 fatal("The relocation at %s+0x%lx references\n"
1682 "section \"%s\" which is black-listed.\n"
1683 "Something is seriously wrong and should be fixed.\n"
1684 "You might get more information about where this is\n"
1685 "coming from by using scripts/check_extable.sh %s\n",
1686 fromsec, (long)r->r_offset, tosec, modname);
1687 else if (!is_executable_section(elf, get_secindex(elf, sym))) {
1688 if (is_extable_fault_address(r))
1689 fatal("The relocation at %s+0x%lx references\n"
1690 "section \"%s\" which is not executable, IOW\n"
1691 "it is not possible for the kernel to fault\n"
1692 "at that address. Something is seriously wrong\n"
1693 "and should be fixed.\n",
1694 fromsec, (long)r->r_offset, tosec);
1696 fatal("The relocation at %s+0x%lx references\n"
1697 "section \"%s\" which is not executable, IOW\n"
1698 "the kernel will fault if it ever tries to\n"
1699 "jump to it. Something is seriously wrong\n"
1700 "and should be fixed.\n",
1701 fromsec, (long)r->r_offset, tosec);
1705 static void check_section_mismatch(const char *modname, struct elf_info *elf,
1706 Elf_Rela *r, Elf_Sym *sym, const char *fromsec)
1708 const char *tosec = sec_name(elf, get_secindex(elf, sym));
1709 const struct sectioncheck *mismatch = section_mismatch(fromsec, tosec);
1712 if (mismatch->handler)
1713 mismatch->handler(modname, elf, mismatch,
1716 default_mismatch_handler(modname, elf, mismatch,
1721 static unsigned int *reloc_location(struct elf_info *elf,
1722 Elf_Shdr *sechdr, Elf_Rela *r)
1724 return sym_get_data_by_offset(elf, sechdr->sh_info, r->r_offset);
1727 static int addend_386_rel(struct elf_info *elf, Elf_Shdr *sechdr, Elf_Rela *r)
1729 unsigned int r_typ = ELF_R_TYPE(r->r_info);
1730 unsigned int *location = reloc_location(elf, sechdr, r);
1734 r->r_addend = TO_NATIVE(*location);
1737 r->r_addend = TO_NATIVE(*location) + 4;
1738 /* For CONFIG_RELOCATABLE=y */
1739 if (elf->hdr->e_type == ET_EXEC)
1740 r->r_addend += r->r_offset;
1747 #define R_ARM_CALL 28
1749 #ifndef R_ARM_JUMP24
1750 #define R_ARM_JUMP24 29
1753 #ifndef R_ARM_THM_CALL
1754 #define R_ARM_THM_CALL 10
1756 #ifndef R_ARM_THM_JUMP24
1757 #define R_ARM_THM_JUMP24 30
1759 #ifndef R_ARM_THM_JUMP19
1760 #define R_ARM_THM_JUMP19 51
1763 static int addend_arm_rel(struct elf_info *elf, Elf_Shdr *sechdr, Elf_Rela *r)
1765 unsigned int r_typ = ELF_R_TYPE(r->r_info);
1769 /* From ARM ABI: (S + A) | T */
1770 r->r_addend = (int)(long)
1771 (elf->symtab_start + ELF_R_SYM(r->r_info));
1776 case R_ARM_THM_CALL:
1777 case R_ARM_THM_JUMP24:
1778 case R_ARM_THM_JUMP19:
1779 /* From ARM ABI: ((S + A) | T) - P */
1780 r->r_addend = (int)(long)(elf->hdr +
1782 (r->r_offset - sechdr->sh_addr));
1790 static int addend_mips_rel(struct elf_info *elf, Elf_Shdr *sechdr, Elf_Rela *r)
1792 unsigned int r_typ = ELF_R_TYPE(r->r_info);
1793 unsigned int *location = reloc_location(elf, sechdr, r);
1796 if (r_typ == R_MIPS_HI16)
1797 return 1; /* skip this */
1798 inst = TO_NATIVE(*location);
1801 r->r_addend = inst & 0xffff;
1804 r->r_addend = (inst & 0x03ffffff) << 2;
1814 #define EM_RISCV 243
1817 #ifndef R_RISCV_SUB32
1818 #define R_RISCV_SUB32 39
1821 static void section_rela(const char *modname, struct elf_info *elf,
1828 const char *fromsec;
1830 Elf_Rela *start = (void *)elf->hdr + sechdr->sh_offset;
1831 Elf_Rela *stop = (void *)start + sechdr->sh_size;
1833 fromsec = sech_name(elf, sechdr);
1834 fromsec += strlen(".rela");
1835 /* if from section (name) is know good then skip it */
1836 if (match(fromsec, section_white_list))
1839 for (rela = start; rela < stop; rela++) {
1840 r.r_offset = TO_NATIVE(rela->r_offset);
1841 #if KERNEL_ELFCLASS == ELFCLASS64
1842 if (elf->hdr->e_machine == EM_MIPS) {
1844 r_sym = ELF64_MIPS_R_SYM(rela->r_info);
1845 r_sym = TO_NATIVE(r_sym);
1846 r_typ = ELF64_MIPS_R_TYPE(rela->r_info);
1847 r.r_info = ELF64_R_INFO(r_sym, r_typ);
1849 r.r_info = TO_NATIVE(rela->r_info);
1850 r_sym = ELF_R_SYM(r.r_info);
1853 r.r_info = TO_NATIVE(rela->r_info);
1854 r_sym = ELF_R_SYM(r.r_info);
1856 r.r_addend = TO_NATIVE(rela->r_addend);
1857 switch (elf->hdr->e_machine) {
1859 if (!strcmp("__ex_table", fromsec) &&
1860 ELF_R_TYPE(r.r_info) == R_RISCV_SUB32)
1864 sym = elf->symtab_start + r_sym;
1865 /* Skip special sections */
1866 if (is_shndx_special(sym->st_shndx))
1868 if (is_second_extable_reloc(start, rela, fromsec))
1869 find_extable_entry_size(fromsec, &r);
1870 check_section_mismatch(modname, elf, &r, sym, fromsec);
1874 static void section_rel(const char *modname, struct elf_info *elf,
1881 const char *fromsec;
1883 Elf_Rel *start = (void *)elf->hdr + sechdr->sh_offset;
1884 Elf_Rel *stop = (void *)start + sechdr->sh_size;
1886 fromsec = sech_name(elf, sechdr);
1887 fromsec += strlen(".rel");
1888 /* if from section (name) is know good then skip it */
1889 if (match(fromsec, section_white_list))
1892 for (rel = start; rel < stop; rel++) {
1893 r.r_offset = TO_NATIVE(rel->r_offset);
1894 #if KERNEL_ELFCLASS == ELFCLASS64
1895 if (elf->hdr->e_machine == EM_MIPS) {
1897 r_sym = ELF64_MIPS_R_SYM(rel->r_info);
1898 r_sym = TO_NATIVE(r_sym);
1899 r_typ = ELF64_MIPS_R_TYPE(rel->r_info);
1900 r.r_info = ELF64_R_INFO(r_sym, r_typ);
1902 r.r_info = TO_NATIVE(rel->r_info);
1903 r_sym = ELF_R_SYM(r.r_info);
1906 r.r_info = TO_NATIVE(rel->r_info);
1907 r_sym = ELF_R_SYM(r.r_info);
1910 switch (elf->hdr->e_machine) {
1912 if (addend_386_rel(elf, sechdr, &r))
1916 if (addend_arm_rel(elf, sechdr, &r))
1920 if (addend_mips_rel(elf, sechdr, &r))
1924 sym = elf->symtab_start + r_sym;
1925 /* Skip special sections */
1926 if (is_shndx_special(sym->st_shndx))
1928 if (is_second_extable_reloc(start, rel, fromsec))
1929 find_extable_entry_size(fromsec, &r);
1930 check_section_mismatch(modname, elf, &r, sym, fromsec);
1935 * A module includes a number of sections that are discarded
1936 * either when loaded or when used as built-in.
1937 * For loaded modules all functions marked __init and all data
1938 * marked __initdata will be discarded when the module has been initialized.
1939 * Likewise for modules used built-in the sections marked __exit
1940 * are discarded because __exit marked function are supposed to be called
1941 * only when a module is unloaded which never happens for built-in modules.
1942 * The check_sec_ref() function traverses all relocation records
1943 * to find all references to a section that reference a section that will
1944 * be discarded and warns about it.
1946 static void check_sec_ref(struct module *mod, const char *modname,
1947 struct elf_info *elf)
1950 Elf_Shdr *sechdrs = elf->sechdrs;
1952 /* Walk through all sections */
1953 for (i = 0; i < elf->num_sections; i++) {
1954 check_section(modname, elf, &elf->sechdrs[i]);
1955 /* We want to process only relocation sections and not .init */
1956 if (sechdrs[i].sh_type == SHT_RELA)
1957 section_rela(modname, elf, &elf->sechdrs[i]);
1958 else if (sechdrs[i].sh_type == SHT_REL)
1959 section_rel(modname, elf, &elf->sechdrs[i]);
1963 static char *remove_dot(char *s)
1965 size_t n = strcspn(s, ".");
1968 size_t m = strspn(s + n + 1, "0123456789");
1969 if (m && (s[n + m] == '.' || s[n + m] == 0))
1972 /* strip trailing .prelink */
1973 if (strends(s, ".prelink"))
1974 s[strlen(s) - 8] = '\0';
1979 static void read_symbols(const char *modname)
1981 const char *symname;
1986 struct elf_info info = { };
1989 if (!parse_elf(&info, modname))
1995 /* strip trailing .o */
1996 tmp = NOFAIL(strdup(modname));
1997 tmp[strlen(tmp) - 2] = '\0';
1998 /* strip trailing .prelink */
1999 if (strends(tmp, ".prelink"))
2000 tmp[strlen(tmp) - 8] = '\0';
2001 mod = new_module(tmp);
2005 if (!mod->is_vmlinux) {
2006 license = get_modinfo(&info, "license");
2008 error("missing MODULE_LICENSE() in %s\n", modname);
2010 if (license_is_gpl_compatible(license))
2011 mod->gpl_compatible = 1;
2013 mod->gpl_compatible = 0;
2016 license = get_next_modinfo(&info, "license", license);
2019 namespace = get_modinfo(&info, "import_ns");
2021 add_namespace(&mod->imported_namespaces, namespace);
2022 namespace = get_next_modinfo(&info, "import_ns",
2027 for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
2028 symname = remove_dot(info.strtab + sym->st_name);
2030 handle_symbol(mod, &info, sym, symname);
2031 handle_moddevtable(mod, &info, sym, symname);
2034 for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
2035 symname = remove_dot(info.strtab + sym->st_name);
2037 /* Apply symbol namespaces from __kstrtabns_<symbol> entries. */
2038 if (strstarts(symname, "__kstrtabns_"))
2039 sym_update_namespace(symname + strlen("__kstrtabns_"),
2040 sym_get_data(&info, sym));
2041 if (strstarts(symname, "__crc_"))
2042 handle_modversion(mod, &info, sym,
2043 symname + strlen("__crc_"));
2046 // check for static EXPORT_SYMBOL_* functions && global vars
2047 for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
2048 unsigned char bind = ELF_ST_BIND(sym->st_info);
2050 if (bind == STB_GLOBAL || bind == STB_WEAK) {
2052 find_symbol(remove_dot(info.strtab +
2060 check_sec_ref(mod, modname, &info);
2062 if (!mod->is_vmlinux) {
2063 version = get_modinfo(&info, "version");
2064 if (version || all_versions)
2065 get_src_version(mod->name, mod->srcversion,
2066 sizeof(mod->srcversion) - 1);
2069 parse_elf_finish(&info);
2071 /* Our trick to get versioning for module struct etc. - it's
2072 * never passed as an argument to an exported function, so
2073 * the automatic versioning doesn't pick it up, but it's really
2074 * important anyhow */
2076 mod->unres = alloc_symbol("module_layout", 0, mod->unres);
2079 static void read_symbols_from_files(const char *filename)
2082 char fname[PATH_MAX];
2084 if (strcmp(filename, "-") != 0) {
2085 in = fopen(filename, "r");
2087 fatal("Can't open filenames file %s: %m", filename);
2090 while (fgets(fname, PATH_MAX, in) != NULL) {
2091 if (strends(fname, "\n"))
2092 fname[strlen(fname)-1] = '\0';
2093 read_symbols(fname);
2102 /* We first write the generated file into memory using the
2103 * following helper, then compare to the file on disk and
2104 * only update the later if anything changed */
2106 void __attribute__((format(printf, 2, 3))) buf_printf(struct buffer *buf,
2107 const char *fmt, ...)
2114 len = vsnprintf(tmp, SZ, fmt, ap);
2115 buf_write(buf, tmp, len);
2119 void buf_write(struct buffer *buf, const char *s, int len)
2121 if (buf->size - buf->pos < len) {
2122 buf->size += len + SZ;
2123 buf->p = NOFAIL(realloc(buf->p, buf->size));
2125 strncpy(buf->p + buf->pos, s, len);
2129 static void check_for_gpl_usage(enum export exp, const char *m, const char *s)
2133 error("GPL-incompatible module %s.ko uses GPL-only symbol '%s'\n",
2137 case export_unknown:
2143 static void check_exports(struct module *mod)
2145 struct symbol *s, *exp;
2147 for (s = mod->unres; s; s = s->next) {
2148 const char *basename;
2149 exp = find_symbol(s->name);
2151 if (!s->weak && nr_unresolved++ < MAX_UNRESOLVED_REPORTS)
2152 modpost_log(warn_unresolved ? LOG_WARN : LOG_ERROR,
2153 "\"%s\" [%s.ko] undefined!\n",
2154 s->name, mod->name);
2157 if (exp->module == mod) {
2158 error("\"%s\" [%s.ko] was exported without definition\n",
2159 s->name, mod->name);
2163 s->module = exp->module;
2164 s->crc_valid = exp->crc_valid;
2167 basename = strrchr(mod->name, '/');
2171 basename = mod->name;
2173 if (exp->namespace &&
2174 !module_imports_namespace(mod, exp->namespace)) {
2175 modpost_log(allow_missing_ns_imports ? LOG_WARN : LOG_ERROR,
2176 "module %s uses symbol %s from namespace %s, but does not import it.\n",
2177 basename, exp->name, exp->namespace);
2178 add_namespace(&mod->missing_namespaces, exp->namespace);
2181 if (!mod->gpl_compatible)
2182 check_for_gpl_usage(exp->export, basename, exp->name);
2186 static void check_modname_len(struct module *mod)
2188 const char *mod_name;
2190 mod_name = strrchr(mod->name, '/');
2191 if (mod_name == NULL)
2192 mod_name = mod->name;
2195 if (strlen(mod_name) >= MODULE_NAME_LEN)
2196 error("module name is too long [%s.ko]\n", mod->name);
2200 * Header for the generated file
2202 static void add_header(struct buffer *b, struct module *mod)
2204 buf_printf(b, "#include <linux/module.h>\n");
2206 * Include build-salt.h after module.h in order to
2207 * inherit the definitions.
2209 buf_printf(b, "#define INCLUDE_VERMAGIC\n");
2210 buf_printf(b, "#include <linux/build-salt.h>\n");
2211 buf_printf(b, "#include <linux/elfnote-lto.h>\n");
2212 buf_printf(b, "#include <linux/vermagic.h>\n");
2213 buf_printf(b, "#include <linux/compiler.h>\n");
2214 buf_printf(b, "\n");
2215 buf_printf(b, "BUILD_SALT;\n");
2216 buf_printf(b, "BUILD_LTO_INFO;\n");
2217 buf_printf(b, "\n");
2218 buf_printf(b, "MODULE_INFO(vermagic, VERMAGIC_STRING);\n");
2219 buf_printf(b, "MODULE_INFO(name, KBUILD_MODNAME);\n");
2220 buf_printf(b, "\n");
2221 buf_printf(b, "__visible struct module __this_module\n");
2222 buf_printf(b, "__section(\".gnu.linkonce.this_module\") = {\n");
2223 buf_printf(b, "\t.name = KBUILD_MODNAME,\n");
2225 buf_printf(b, "\t.init = init_module,\n");
2226 if (mod->has_cleanup)
2227 buf_printf(b, "#ifdef CONFIG_MODULE_UNLOAD\n"
2228 "\t.exit = cleanup_module,\n"
2230 buf_printf(b, "\t.arch = MODULE_ARCH_INIT,\n");
2231 buf_printf(b, "};\n");
2234 static void add_intree_flag(struct buffer *b, int is_intree)
2237 buf_printf(b, "\nMODULE_INFO(intree, \"Y\");\n");
2240 /* Cannot check for assembler */
2241 static void add_retpoline(struct buffer *b)
2243 buf_printf(b, "\n#ifdef CONFIG_RETPOLINE\n");
2244 buf_printf(b, "MODULE_INFO(retpoline, \"Y\");\n");
2245 buf_printf(b, "#endif\n");
2248 static void add_staging_flag(struct buffer *b, const char *name)
2250 if (strstarts(name, "drivers/staging"))
2251 buf_printf(b, "\nMODULE_INFO(staging, \"Y\");\n");
2255 * Record CRCs for unresolved symbols
2257 static void add_versions(struct buffer *b, struct module *mod)
2264 buf_printf(b, "\n");
2265 buf_printf(b, "static const struct modversion_info ____versions[]\n");
2266 buf_printf(b, "__used __section(\"__versions\") = {\n");
2268 for (s = mod->unres; s; s = s->next) {
2271 if (!s->crc_valid) {
2272 warn("\"%s\" [%s.ko] has no CRC!\n",
2273 s->name, mod->name);
2276 if (strlen(s->name) >= MODULE_NAME_LEN) {
2277 error("too long symbol \"%s\" [%s.ko]\n",
2278 s->name, mod->name);
2281 buf_printf(b, "\t{ %#8x, \"%s\" },\n",
2285 buf_printf(b, "};\n");
2288 static void add_depends(struct buffer *b, struct module *mod)
2293 /* Clear ->seen flag of modules that own symbols needed by this. */
2294 for (s = mod->unres; s; s = s->next)
2296 s->module->seen = s->module->is_vmlinux;
2298 buf_printf(b, "\n");
2299 buf_printf(b, "MODULE_INFO(depends, \"");
2300 for (s = mod->unres; s; s = s->next) {
2305 if (s->module->seen)
2308 s->module->seen = 1;
2309 p = strrchr(s->module->name, '/');
2313 p = s->module->name;
2314 buf_printf(b, "%s%s", first ? "" : ",", p);
2317 buf_printf(b, "\");\n");
2320 static void add_srcversion(struct buffer *b, struct module *mod)
2322 if (mod->srcversion[0]) {
2323 buf_printf(b, "\n");
2324 buf_printf(b, "MODULE_INFO(srcversion, \"%s\");\n",
2329 static void write_buf(struct buffer *b, const char *fname)
2336 file = fopen(fname, "w");
2341 if (fwrite(b->p, 1, b->pos, file) != b->pos) {
2345 if (fclose(file) != 0) {
2351 static void write_if_changed(struct buffer *b, const char *fname)
2357 file = fopen(fname, "r");
2361 if (fstat(fileno(file), &st) < 0)
2364 if (st.st_size != b->pos)
2367 tmp = NOFAIL(malloc(b->pos));
2368 if (fread(tmp, 1, b->pos, file) != b->pos)
2371 if (memcmp(tmp, b->p, b->pos) != 0)
2383 write_buf(b, fname);
2386 /* parse Module.symvers file. line format:
2387 * 0x12345678<tab>symbol<tab>module<tab>export<tab>namespace
2389 static void read_dump(const char *fname)
2391 char *buf, *pos, *line;
2393 buf = read_text_file(fname);
2395 /* No symbol versions, silently ignore */
2400 while ((line = get_line(&pos))) {
2401 char *symname, *namespace, *modname, *d, *export;
2406 if (!(symname = strchr(line, '\t')))
2409 if (!(modname = strchr(symname, '\t')))
2412 if (!(export = strchr(modname, '\t')))
2415 if (!(namespace = strchr(export, '\t')))
2417 *namespace++ = '\0';
2419 crc = strtoul(line, &d, 16);
2420 if (*symname == '\0' || *modname == '\0' || *d != '\0')
2422 mod = find_module(modname);
2424 mod = new_module(modname);
2427 s = sym_add_exported(symname, mod, export_no(export));
2429 sym_set_crc(symname, crc);
2430 sym_update_namespace(symname, namespace);
2436 fatal("parse error in symbol dump file\n");
2439 static void write_dump(const char *fname)
2441 struct buffer buf = { };
2442 struct symbol *symbol;
2443 const char *namespace;
2446 for (n = 0; n < SYMBOL_HASH_SIZE ; n++) {
2447 symbol = symbolhash[n];
2449 if (!symbol->module->from_dump) {
2450 namespace = symbol->namespace;
2451 buf_printf(&buf, "0x%08x\t%s\t%s\t%s\t%s\n",
2452 symbol->crc, symbol->name,
2453 symbol->module->name,
2454 export_str(symbol->export),
2455 namespace ? namespace : "");
2457 symbol = symbol->next;
2460 write_buf(&buf, fname);
2464 static void write_namespace_deps_files(const char *fname)
2467 struct namespace_list *ns;
2468 struct buffer ns_deps_buf = {};
2470 for (mod = modules; mod; mod = mod->next) {
2472 if (mod->from_dump || !mod->missing_namespaces)
2475 buf_printf(&ns_deps_buf, "%s.ko:", mod->name);
2477 for (ns = mod->missing_namespaces; ns; ns = ns->next)
2478 buf_printf(&ns_deps_buf, " %s", ns->namespace);
2480 buf_printf(&ns_deps_buf, "\n");
2483 write_if_changed(&ns_deps_buf, fname);
2484 free(ns_deps_buf.p);
2488 struct dump_list *next;
2492 int main(int argc, char **argv)
2495 struct buffer buf = { };
2496 char *missing_namespace_deps = NULL;
2497 char *dump_write = NULL, *files_source = NULL;
2500 struct dump_list *dump_read_start = NULL;
2501 struct dump_list **dump_read_iter = &dump_read_start;
2503 while ((opt = getopt(argc, argv, "ei:mnT:o:awENd:")) != -1) {
2506 external_module = 1;
2510 NOFAIL(calloc(1, sizeof(**dump_read_iter)));
2511 (*dump_read_iter)->file = optarg;
2512 dump_read_iter = &(*dump_read_iter)->next;
2518 ignore_missing_files = 1;
2521 dump_write = optarg;
2527 files_source = optarg;
2530 warn_unresolved = 1;
2533 sec_mismatch_warn_only = false;
2536 allow_missing_ns_imports = 1;
2539 missing_namespace_deps = optarg;
2546 while (dump_read_start) {
2547 struct dump_list *tmp;
2549 read_dump(dump_read_start->file);
2550 tmp = dump_read_start->next;
2551 free(dump_read_start);
2552 dump_read_start = tmp;
2555 while (optind < argc)
2556 read_symbols(argv[optind++]);
2559 read_symbols_from_files(files_source);
2561 for (mod = modules; mod; mod = mod->next) {
2562 char fname[PATH_MAX];
2565 if (mod->is_vmlinux || mod->from_dump)
2570 check_modname_len(mod);
2573 add_header(&buf, mod);
2574 add_intree_flag(&buf, !external_module);
2575 add_retpoline(&buf);
2576 add_staging_flag(&buf, mod->name);
2577 add_versions(&buf, mod);
2578 add_depends(&buf, mod);
2579 add_moddevtable(&buf, mod);
2580 add_srcversion(&buf, mod);
2582 ret = snprintf(fname, sizeof(fname), "%s.mod.c", mod->name);
2583 if (ret >= sizeof(fname)) {
2584 error("%s: too long path was truncated\n", fname);
2588 write_if_changed(&buf, fname);
2591 if (missing_namespace_deps)
2592 write_namespace_deps_files(missing_namespace_deps);
2595 write_dump(dump_write);
2596 if (sec_mismatch_count && !sec_mismatch_warn_only)
2597 error("Section mismatches detected.\n"
2598 "Set CONFIG_SECTION_MISMATCH_WARN_ONLY=y to allow them.\n");
2599 for (n = 0; n < SYMBOL_HASH_SIZE; n++) {
2602 for (s = symbolhash[n]; s; s = s->next) {
2604 error("\"%s\" [%s] is a static %s\n",
2605 s->name, s->module->name,
2606 export_str(s->export));
2610 if (nr_unresolved > MAX_UNRESOLVED_REPORTS)
2611 warn("suppressed %u unresolved symbol warnings because there were too many)\n",
2612 nr_unresolved - MAX_UNRESOLVED_REPORTS);
2616 return error_occurred ? 1 : 0;