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 <hashtable.h>
28 #include "../../include/linux/license.h"
30 static bool module_enabled;
31 /* Are we using CONFIG_MODVERSIONS? */
32 static bool modversions;
33 /* Is CONFIG_MODULE_SRCVERSION_ALL set? */
34 static bool all_versions;
35 /* If we are modposting external module set to 1 */
36 static bool external_module;
37 /* Only warn about unresolved symbols */
38 static bool warn_unresolved;
40 static int sec_mismatch_count;
41 static bool sec_mismatch_warn_only = true;
42 /* Trim EXPORT_SYMBOLs that are unused by in-tree modules */
43 static bool trim_unused_exports;
45 /* ignore missing files */
46 static bool ignore_missing_files;
47 /* If set to 1, only warn (instead of error) about missing ns imports */
48 static bool allow_missing_ns_imports;
50 static bool error_occurred;
52 static bool extra_warn;
54 bool target_is_big_endian;
55 bool host_is_big_endian;
58 * Cut off the warnings when there are too many. This typically occurs when
59 * vmlinux is missing. ('make modules' without building vmlinux.)
61 #define MAX_UNRESOLVED_REPORTS 10
62 static unsigned int nr_unresolved;
64 /* In kernel, this size is defined in linux/module.h;
65 * here we use Elf_Addr instead of long for covering cross-compile
68 #define MODULE_NAME_LEN (64 - sizeof(Elf_Addr))
70 void modpost_log(bool is_error, const char *fmt, ...)
75 fprintf(stderr, "ERROR: ");
76 error_occurred = true;
78 fprintf(stderr, "WARNING: ");
81 fprintf(stderr, "modpost: ");
83 va_start(arglist, fmt);
84 vfprintf(stderr, fmt, arglist);
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 char *read_text_file(const char *filename)
103 fd = open(filename, O_RDONLY);
109 if (fstat(fd, &st) < 0) {
114 buf = xmalloc(st.st_size + 1);
121 bytes_read = read(fd, buf, nbytes);
122 if (bytes_read < 0) {
127 nbytes -= bytes_read;
129 buf[st.st_size] = '\0';
136 char *get_line(char **stringp)
138 char *orig = *stringp, *next;
140 /* do not return the unwanted extra line at EOF */
141 if (!orig || *orig == '\0')
144 /* don't use strsep here, it is not available everywhere */
145 next = strchr(orig, '\n');
154 /* A list of all modules we processed */
157 static struct module *find_module(const char *modname)
161 list_for_each_entry(mod, &modules, list) {
162 if (strcmp(mod->name, modname) == 0)
168 static struct module *new_module(const char *name, size_t namelen)
172 mod = xmalloc(sizeof(*mod) + namelen + 1);
173 memset(mod, 0, sizeof(*mod));
175 INIT_LIST_HEAD(&mod->exported_symbols);
176 INIT_LIST_HEAD(&mod->unresolved_symbols);
177 INIT_LIST_HEAD(&mod->missing_namespaces);
178 INIT_LIST_HEAD(&mod->imported_namespaces);
180 memcpy(mod->name, name, namelen);
181 mod->name[namelen] = '\0';
182 mod->is_vmlinux = (strcmp(mod->name, "vmlinux") == 0);
185 * Set mod->is_gpl_compatible to true by default. If MODULE_LICENSE()
186 * is missing, do not check the use for EXPORT_SYMBOL_GPL() becasue
187 * modpost will exit wiht error anyway.
189 mod->is_gpl_compatible = true;
191 list_add_tail(&mod->list, &modules);
197 struct hlist_node hnode;/* link to hash table */
198 struct list_head list; /* link to module::exported_symbols or module::unresolved_symbols */
199 struct module *module;
205 bool is_gpl_only; /* exported by EXPORT_SYMBOL_GPL */
206 bool used; /* there exists a user of this symbol */
210 static HASHTABLE_DEFINE(symbol_hashtable, 1U << 10);
212 /* This is based on the hash algorithm from gdbm, via tdb */
213 static inline unsigned int tdb_hash(const char *name)
215 unsigned value; /* Used to compute the hash value. */
216 unsigned i; /* Used to cycle through random values. */
218 /* Set the initial value from the key size. */
219 for (value = 0x238F13AF * strlen(name), i = 0; name[i]; i++)
220 value = (value + (((unsigned char *)name)[i] << (i*5 % 24)));
222 return (1103515243 * value + 12345);
226 * Allocate a new symbols for use in the hash of exported symbols or
227 * the list of unresolved symbols per module
229 static struct symbol *alloc_symbol(const char *name)
231 struct symbol *s = xmalloc(sizeof(*s) + strlen(name) + 1);
233 memset(s, 0, sizeof(*s));
234 strcpy(s->name, name);
239 /* For the hash of exported symbols */
240 static void hash_add_symbol(struct symbol *sym)
242 hash_add(symbol_hashtable, &sym->hnode, tdb_hash(sym->name));
245 static void sym_add_unresolved(const char *name, struct module *mod, bool weak)
249 sym = alloc_symbol(name);
252 list_add_tail(&sym->list, &mod->unresolved_symbols);
255 static struct symbol *sym_find_with_module(const char *name, struct module *mod)
259 /* For our purposes, .foo matches foo. PPC64 needs this. */
263 hash_for_each_possible(symbol_hashtable, s, hnode, tdb_hash(name)) {
264 if (strcmp(s->name, name) == 0 && (!mod || s->module == mod))
270 static struct symbol *find_symbol(const char *name)
272 return sym_find_with_module(name, NULL);
275 struct namespace_list {
276 struct list_head list;
280 static bool contains_namespace(struct list_head *head, const char *namespace)
282 struct namespace_list *list;
285 * The default namespace is null string "", which is always implicitly
291 list_for_each_entry(list, head, list) {
292 if (!strcmp(list->namespace, namespace))
299 static void add_namespace(struct list_head *head, const char *namespace)
301 struct namespace_list *ns_entry;
303 if (!contains_namespace(head, namespace)) {
304 ns_entry = xmalloc(sizeof(*ns_entry) + strlen(namespace) + 1);
305 strcpy(ns_entry->namespace, namespace);
306 list_add_tail(&ns_entry->list, head);
310 static void *sym_get_data_by_offset(const struct elf_info *info,
311 unsigned int secindex, unsigned long offset)
313 Elf_Shdr *sechdr = &info->sechdrs[secindex];
315 return (void *)info->hdr + sechdr->sh_offset + offset;
318 void *sym_get_data(const struct elf_info *info, const Elf_Sym *sym)
320 return sym_get_data_by_offset(info, get_secindex(info, sym),
324 static const char *sech_name(const struct elf_info *info, Elf_Shdr *sechdr)
326 return sym_get_data_by_offset(info, info->secindex_strings,
330 static const char *sec_name(const struct elf_info *info, unsigned int secindex)
333 * If sym->st_shndx is a special section index, there is no
334 * corresponding section header.
335 * Return "" if the index is out of range of info->sechdrs[] array.
337 if (secindex >= info->num_sections)
340 return sech_name(info, &info->sechdrs[secindex]);
343 #define strstarts(str, prefix) (strncmp(str, prefix, strlen(prefix)) == 0)
345 static struct symbol *sym_add_exported(const char *name, struct module *mod,
346 bool gpl_only, const char *namespace)
348 struct symbol *s = find_symbol(name);
350 if (s && (!external_module || s->module->is_vmlinux || s->module == mod)) {
351 error("%s: '%s' exported twice. Previous export was in %s%s\n",
352 mod->name, name, s->module->name,
353 s->module->is_vmlinux ? "" : ".ko");
356 s = alloc_symbol(name);
358 s->is_gpl_only = gpl_only;
359 s->namespace = xstrdup(namespace);
360 list_add_tail(&s->list, &mod->exported_symbols);
366 static void sym_set_crc(struct symbol *sym, unsigned int crc)
369 sym->crc_valid = true;
372 static void *grab_file(const char *filename, size_t *size)
375 void *map = MAP_FAILED;
378 fd = open(filename, O_RDONLY);
385 map = mmap(NULL, *size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
389 if (map == MAP_FAILED)
394 static void release_file(void *file, size_t size)
399 static int parse_elf(struct elf_info *info, const char *filename)
405 const char *secstrings;
406 unsigned int symtab_idx = ~0U, symtab_shndx_idx = ~0U;
408 hdr = grab_file(filename, &info->size);
410 if (ignore_missing_files) {
411 fprintf(stderr, "%s: %s (ignored)\n", filename,
419 if (info->size < sizeof(*hdr)) {
420 /* file too small, assume this is an empty .o file */
423 /* Is this a valid ELF file? */
424 if ((hdr->e_ident[EI_MAG0] != ELFMAG0) ||
425 (hdr->e_ident[EI_MAG1] != ELFMAG1) ||
426 (hdr->e_ident[EI_MAG2] != ELFMAG2) ||
427 (hdr->e_ident[EI_MAG3] != ELFMAG3)) {
428 /* Not an ELF file - silently ignore it */
432 switch (hdr->e_ident[EI_DATA]) {
434 target_is_big_endian = false;
437 target_is_big_endian = true;
440 fatal("target endian is unknown\n");
443 /* Fix endianness in ELF header */
444 hdr->e_type = TO_NATIVE(hdr->e_type);
445 hdr->e_machine = TO_NATIVE(hdr->e_machine);
446 hdr->e_version = TO_NATIVE(hdr->e_version);
447 hdr->e_entry = TO_NATIVE(hdr->e_entry);
448 hdr->e_phoff = TO_NATIVE(hdr->e_phoff);
449 hdr->e_shoff = TO_NATIVE(hdr->e_shoff);
450 hdr->e_flags = TO_NATIVE(hdr->e_flags);
451 hdr->e_ehsize = TO_NATIVE(hdr->e_ehsize);
452 hdr->e_phentsize = TO_NATIVE(hdr->e_phentsize);
453 hdr->e_phnum = TO_NATIVE(hdr->e_phnum);
454 hdr->e_shentsize = TO_NATIVE(hdr->e_shentsize);
455 hdr->e_shnum = TO_NATIVE(hdr->e_shnum);
456 hdr->e_shstrndx = TO_NATIVE(hdr->e_shstrndx);
457 sechdrs = (void *)hdr + hdr->e_shoff;
458 info->sechdrs = sechdrs;
460 /* modpost only works for relocatable objects */
461 if (hdr->e_type != ET_REL)
462 fatal("%s: not relocatable object.", filename);
464 /* Check if file offset is correct */
465 if (hdr->e_shoff > info->size)
466 fatal("section header offset=%lu in file '%s' is bigger than filesize=%zu\n",
467 (unsigned long)hdr->e_shoff, filename, info->size);
469 if (hdr->e_shnum == SHN_UNDEF) {
471 * There are more than 64k sections,
472 * read count from .sh_size.
474 info->num_sections = TO_NATIVE(sechdrs[0].sh_size);
477 info->num_sections = hdr->e_shnum;
479 if (hdr->e_shstrndx == SHN_XINDEX) {
480 info->secindex_strings = TO_NATIVE(sechdrs[0].sh_link);
483 info->secindex_strings = hdr->e_shstrndx;
486 /* Fix endianness in section headers */
487 for (i = 0; i < info->num_sections; i++) {
488 sechdrs[i].sh_name = TO_NATIVE(sechdrs[i].sh_name);
489 sechdrs[i].sh_type = TO_NATIVE(sechdrs[i].sh_type);
490 sechdrs[i].sh_flags = TO_NATIVE(sechdrs[i].sh_flags);
491 sechdrs[i].sh_addr = TO_NATIVE(sechdrs[i].sh_addr);
492 sechdrs[i].sh_offset = TO_NATIVE(sechdrs[i].sh_offset);
493 sechdrs[i].sh_size = TO_NATIVE(sechdrs[i].sh_size);
494 sechdrs[i].sh_link = TO_NATIVE(sechdrs[i].sh_link);
495 sechdrs[i].sh_info = TO_NATIVE(sechdrs[i].sh_info);
496 sechdrs[i].sh_addralign = TO_NATIVE(sechdrs[i].sh_addralign);
497 sechdrs[i].sh_entsize = TO_NATIVE(sechdrs[i].sh_entsize);
499 /* Find symbol table. */
500 secstrings = (void *)hdr + sechdrs[info->secindex_strings].sh_offset;
501 for (i = 1; i < info->num_sections; i++) {
503 int nobits = sechdrs[i].sh_type == SHT_NOBITS;
505 if (!nobits && sechdrs[i].sh_offset > info->size)
506 fatal("%s is truncated. sechdrs[i].sh_offset=%lu > sizeof(*hrd)=%zu\n",
507 filename, (unsigned long)sechdrs[i].sh_offset,
510 secname = secstrings + sechdrs[i].sh_name;
511 if (strcmp(secname, ".modinfo") == 0) {
513 fatal("%s has NOBITS .modinfo\n", filename);
514 info->modinfo = (void *)hdr + sechdrs[i].sh_offset;
515 info->modinfo_len = sechdrs[i].sh_size;
516 } else if (!strcmp(secname, ".export_symbol")) {
517 info->export_symbol_secndx = i;
520 if (sechdrs[i].sh_type == SHT_SYMTAB) {
521 unsigned int sh_link_idx;
523 info->symtab_start = (void *)hdr +
524 sechdrs[i].sh_offset;
525 info->symtab_stop = (void *)hdr +
526 sechdrs[i].sh_offset + sechdrs[i].sh_size;
527 sh_link_idx = sechdrs[i].sh_link;
528 info->strtab = (void *)hdr +
529 sechdrs[sh_link_idx].sh_offset;
532 /* 32bit section no. table? ("more than 64k sections") */
533 if (sechdrs[i].sh_type == SHT_SYMTAB_SHNDX) {
534 symtab_shndx_idx = i;
535 info->symtab_shndx_start = (void *)hdr +
536 sechdrs[i].sh_offset;
537 info->symtab_shndx_stop = (void *)hdr +
538 sechdrs[i].sh_offset + sechdrs[i].sh_size;
541 if (!info->symtab_start)
542 fatal("%s has no symtab?\n", filename);
544 /* Fix endianness in symbols */
545 for (sym = info->symtab_start; sym < info->symtab_stop; sym++) {
546 sym->st_shndx = TO_NATIVE(sym->st_shndx);
547 sym->st_name = TO_NATIVE(sym->st_name);
548 sym->st_value = TO_NATIVE(sym->st_value);
549 sym->st_size = TO_NATIVE(sym->st_size);
552 if (symtab_shndx_idx != ~0U) {
554 if (symtab_idx != sechdrs[symtab_shndx_idx].sh_link)
555 fatal("%s: SYMTAB_SHNDX has bad sh_link: %u!=%u\n",
556 filename, sechdrs[symtab_shndx_idx].sh_link,
559 for (p = info->symtab_shndx_start; p < info->symtab_shndx_stop;
564 symsearch_init(info);
569 static void parse_elf_finish(struct elf_info *info)
571 symsearch_finish(info);
572 release_file(info->hdr, info->size);
575 static int ignore_undef_symbol(struct elf_info *info, const char *symname)
577 /* ignore __this_module, it will be resolved shortly */
578 if (strcmp(symname, "__this_module") == 0)
580 /* ignore global offset table */
581 if (strcmp(symname, "_GLOBAL_OFFSET_TABLE_") == 0)
583 if (info->hdr->e_machine == EM_PPC)
584 /* Special register function linked on all modules during final link of .ko */
585 if (strstarts(symname, "_restgpr_") ||
586 strstarts(symname, "_savegpr_") ||
587 strstarts(symname, "_rest32gpr_") ||
588 strstarts(symname, "_save32gpr_") ||
589 strstarts(symname, "_restvr_") ||
590 strstarts(symname, "_savevr_"))
592 if (info->hdr->e_machine == EM_PPC64)
593 /* Special register function linked on all modules during final link of .ko */
594 if (strstarts(symname, "_restgpr0_") ||
595 strstarts(symname, "_savegpr0_") ||
596 strstarts(symname, "_restvr_") ||
597 strstarts(symname, "_savevr_") ||
598 strcmp(symname, ".TOC.") == 0)
600 /* Do not ignore this symbol */
604 static void handle_symbol(struct module *mod, struct elf_info *info,
605 const Elf_Sym *sym, const char *symname)
607 switch (sym->st_shndx) {
609 if (strstarts(symname, "__gnu_lto_")) {
610 /* Should warn here, but modpost runs before the linker */
612 warn("\"%s\" [%s] is COMMON symbol\n", symname, mod->name);
615 /* undefined symbol */
616 if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL &&
617 ELF_ST_BIND(sym->st_info) != STB_WEAK)
619 if (ignore_undef_symbol(info, symname))
621 if (info->hdr->e_machine == EM_SPARC ||
622 info->hdr->e_machine == EM_SPARCV9) {
623 /* Ignore register directives. */
624 if (ELF_ST_TYPE(sym->st_info) == STT_SPARC_REGISTER)
626 if (symname[0] == '.') {
627 char *munged = xstrdup(symname);
629 munged[1] = toupper(munged[1]);
634 sym_add_unresolved(symname, mod,
635 ELF_ST_BIND(sym->st_info) == STB_WEAK);
638 if (strcmp(symname, "init_module") == 0)
639 mod->has_init = true;
640 if (strcmp(symname, "cleanup_module") == 0)
641 mod->has_cleanup = true;
647 * Parse tag=value strings from .modinfo section
649 static char *next_string(char *string, unsigned long *secsize)
651 /* Skip non-zero chars */
654 if ((*secsize)-- <= 1)
658 /* Skip any zero padding. */
661 if ((*secsize)-- <= 1)
667 static char *get_next_modinfo(struct elf_info *info, const char *tag,
671 unsigned int taglen = strlen(tag);
672 char *modinfo = info->modinfo;
673 unsigned long size = info->modinfo_len;
676 size -= prev - modinfo;
677 modinfo = next_string(prev, &size);
680 for (p = modinfo; p; p = next_string(p, &size)) {
681 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
682 return p + taglen + 1;
687 static char *get_modinfo(struct elf_info *info, const char *tag)
690 return get_next_modinfo(info, tag, NULL);
693 static const char *sym_name(struct elf_info *elf, Elf_Sym *sym)
695 return sym ? elf->strtab + sym->st_name : "";
699 * Check whether the 'string' argument matches one of the 'patterns',
700 * an array of shell wildcard patterns (glob).
702 * Return true is there is a match.
704 static bool match(const char *string, const char *const patterns[])
708 while ((pattern = *patterns++)) {
709 if (!fnmatch(pattern, string, 0))
716 /* useful to pass patterns to match() directly */
717 #define PATTERNS(...) \
719 static const char *const patterns[] = {__VA_ARGS__, NULL}; \
723 /* sections that we do not want to do full section mismatch check on */
724 static const char *const section_white_list[] =
728 ".zdebug*", /* Compressed debug sections. */
729 ".GCC.command.line", /* record-gcc-switches */
730 ".mdebug*", /* alpha, score, mips etc. */
731 ".pdr", /* alpha, score, mips etc. */
736 ".xt.prop", /* xtensa */
737 ".xt.lit", /* xtensa */
738 ".arcextmap*", /* arc */
739 ".gnu.linkonce.arcext*", /* arc : modules */
740 ".cmem*", /* EZchip */
741 ".fmt_slot*", /* EZchip */
744 ".llvm.call-graph-profile", /* call graph */
749 * This is used to find sections missing the SHF_ALLOC flag.
750 * The cause of this is often a section specified in assembler
751 * without "ax" / "aw".
753 static void check_section(const char *modname, struct elf_info *elf,
756 const char *sec = sech_name(elf, sechdr);
758 if (sechdr->sh_type == SHT_PROGBITS &&
759 !(sechdr->sh_flags & SHF_ALLOC) &&
760 !match(sec, section_white_list)) {
761 warn("%s (%s): unexpected non-allocatable section.\n"
762 "Did you forget to use \"ax\"/\"aw\" in a .S file?\n"
763 "Note that for example <linux/init.h> contains\n"
764 "section definitions for use in .S files.\n\n",
771 #define ALL_INIT_DATA_SECTIONS \
772 ".init.setup", ".init.rodata", ".init.data"
774 #define ALL_PCI_INIT_SECTIONS \
775 ".pci_fixup_early", ".pci_fixup_header", ".pci_fixup_final", \
776 ".pci_fixup_enable", ".pci_fixup_resume", \
777 ".pci_fixup_resume_early", ".pci_fixup_suspend"
779 #define ALL_INIT_SECTIONS ".init.*"
780 #define ALL_EXIT_SECTIONS ".exit.*"
782 #define DATA_SECTIONS ".data", ".data.rel"
783 #define TEXT_SECTIONS ".text", ".text.*", ".sched.text", \
784 ".kprobes.text", ".cpuidle.text", ".noinstr.text", \
786 #define OTHER_TEXT_SECTIONS ".ref.text", ".head.text", ".spinlock.text", \
787 ".fixup", ".entry.text", ".exception.text", \
788 ".coldtext", ".softirqentry.text"
790 #define ALL_TEXT_SECTIONS ".init.text", ".exit.text", \
791 TEXT_SECTIONS, OTHER_TEXT_SECTIONS
794 TEXTDATA_TO_ANY_INIT_EXIT,
795 XXXINIT_TO_SOME_INIT,
796 ANY_INIT_TO_ANY_EXIT,
797 ANY_EXIT_TO_ANY_INIT,
802 * Describe how to match sections on different criteria:
804 * @fromsec: Array of sections to be matched.
806 * @bad_tosec: Relocations applied to a section in @fromsec to a section in
807 * this array is forbidden (black-list). Can be empty.
809 * @good_tosec: Relocations applied to a section in @fromsec must be
810 * targeting sections in this array (white-list). Can be empty.
812 * @mismatch: Type of mismatch.
814 struct sectioncheck {
815 const char *fromsec[20];
816 const char *bad_tosec[20];
817 const char *good_tosec[20];
818 enum mismatch mismatch;
821 static const struct sectioncheck sectioncheck[] = {
822 /* Do not reference init/exit code/data from
823 * normal code and data
826 .fromsec = { TEXT_SECTIONS, DATA_SECTIONS, NULL },
827 .bad_tosec = { ALL_INIT_SECTIONS, ALL_EXIT_SECTIONS, NULL },
828 .mismatch = TEXTDATA_TO_ANY_INIT_EXIT,
830 /* Do not use exit code/data from init code */
832 .fromsec = { ALL_INIT_SECTIONS, NULL },
833 .bad_tosec = { ALL_EXIT_SECTIONS, NULL },
834 .mismatch = ANY_INIT_TO_ANY_EXIT,
836 /* Do not use init code/data from exit code */
838 .fromsec = { ALL_EXIT_SECTIONS, NULL },
839 .bad_tosec = { ALL_INIT_SECTIONS, NULL },
840 .mismatch = ANY_EXIT_TO_ANY_INIT,
843 .fromsec = { ALL_PCI_INIT_SECTIONS, NULL },
844 .bad_tosec = { ALL_INIT_SECTIONS, NULL },
845 .mismatch = ANY_INIT_TO_ANY_EXIT,
848 .fromsec = { "__ex_table", NULL },
849 /* If you're adding any new black-listed sections in here, consider
850 * adding a special 'printer' for them in scripts/check_extable.
852 .bad_tosec = { ".altinstr_replacement", NULL },
853 .good_tosec = {ALL_TEXT_SECTIONS , NULL},
854 .mismatch = EXTABLE_TO_NON_TEXT,
858 static const struct sectioncheck *section_mismatch(
859 const char *fromsec, const char *tosec)
864 * The target section could be the SHT_NUL section when we're
865 * handling relocations to un-resolved symbols, trying to match it
866 * doesn't make much sense and causes build failures on parisc
872 for (i = 0; i < ARRAY_SIZE(sectioncheck); i++) {
873 const struct sectioncheck *check = §ioncheck[i];
875 if (match(fromsec, check->fromsec)) {
876 if (check->bad_tosec[0] && match(tosec, check->bad_tosec))
878 if (check->good_tosec[0] && !match(tosec, check->good_tosec))
886 * Whitelist to allow certain references to pass with no warning.
889 * If a module parameter is declared __initdata and permissions=0
890 * then this is legal despite the warning generated.
891 * We cannot see value of permissions here, so just ignore
893 * The pattern is identified by:
899 * module_param_call() ops can refer to __init set function if permissions=0
900 * The pattern is identified by:
903 * atsym = __param_ops_*
906 * Whitelist all references from .head.text to any init section
909 * Some symbols belong to init section but still it is ok to reference
910 * these from non-init sections as these symbols don't have any memory
911 * allocated for them and symbol address and value are same. So even
912 * if init section is freed, its ok to reference those symbols.
913 * For ex. symbols marking the init section boundaries.
914 * This pattern is identified by
915 * refsymname = __init_begin, _sinittext, _einittext
918 * GCC may optimize static inlines when fed constant arg(s) resulting
919 * in functions like cpumask_empty() -- generating an associated symbol
920 * cpumask_empty.constprop.3 that appears in the audit. If the const that
921 * is passed in comes from __init, like say nmi_ipi_mask, we get a
922 * meaningless section warning. May need to add isra symbols too...
923 * This pattern is identified by
924 * tosec = init section
925 * fromsec = text section
926 * refsymname = *.constprop.*
929 static int secref_whitelist(const char *fromsec, const char *fromsym,
930 const char *tosec, const char *tosym)
932 /* Check for pattern 1 */
933 if (match(tosec, PATTERNS(ALL_INIT_DATA_SECTIONS)) &&
934 match(fromsec, PATTERNS(DATA_SECTIONS)) &&
935 strstarts(fromsym, "__param"))
938 /* Check for pattern 1a */
939 if (strcmp(tosec, ".init.text") == 0 &&
940 match(fromsec, PATTERNS(DATA_SECTIONS)) &&
941 strstarts(fromsym, "__param_ops_"))
944 /* symbols in data sections that may refer to any init/exit sections */
945 if (match(fromsec, PATTERNS(DATA_SECTIONS)) &&
946 match(tosec, PATTERNS(ALL_INIT_SECTIONS, ALL_EXIT_SECTIONS)) &&
947 match(fromsym, PATTERNS("*_ops", "*_probe", "*_console")))
950 /* Check for pattern 3 */
951 if (strstarts(fromsec, ".head.text") &&
952 match(tosec, PATTERNS(ALL_INIT_SECTIONS)))
955 /* Check for pattern 4 */
956 if (match(tosym, PATTERNS("__init_begin", "_sinittext", "_einittext")))
959 /* Check for pattern 5 */
960 if (match(fromsec, PATTERNS(ALL_TEXT_SECTIONS)) &&
961 match(tosec, PATTERNS(ALL_INIT_SECTIONS)) &&
962 match(fromsym, PATTERNS("*.constprop.*")))
968 static Elf_Sym *find_fromsym(struct elf_info *elf, Elf_Addr addr,
971 return symsearch_find_nearest(elf, addr, secndx, false, ~0);
974 static Elf_Sym *find_tosym(struct elf_info *elf, Elf_Addr addr, Elf_Sym *sym)
978 /* If the supplied symbol has a valid name, return it */
979 if (is_valid_name(elf, sym))
983 * Strive to find a better symbol name, but the resulting name may not
984 * match the symbol referenced in the original code.
986 new_sym = symsearch_find_nearest(elf, addr, get_secindex(elf, sym),
988 return new_sym ? new_sym : sym;
991 static bool is_executable_section(struct elf_info *elf, unsigned int secndx)
993 if (secndx >= elf->num_sections)
996 return (elf->sechdrs[secndx].sh_flags & SHF_EXECINSTR) != 0;
999 static void default_mismatch_handler(const char *modname, struct elf_info *elf,
1000 const struct sectioncheck* const mismatch,
1002 unsigned int fsecndx, const char *fromsec, Elf_Addr faddr,
1003 const char *tosec, Elf_Addr taddr)
1007 const char *fromsym;
1010 from = find_fromsym(elf, faddr, fsecndx);
1011 fromsym = sym_name(elf, from);
1013 tsym = find_tosym(elf, taddr, tsym);
1014 tosym = sym_name(elf, tsym);
1016 /* check whitelist - we may ignore it */
1017 if (!secref_whitelist(fromsec, fromsym, tosec, tosym))
1020 sec_mismatch_count++;
1023 snprintf(taddr_str, sizeof(taddr_str), "0x%x", (unsigned int)taddr);
1026 * The format for the reference source: <symbol_name>+<offset> or <address>
1027 * The format for the reference destination: <symbol_name> or <address>
1029 warn("%s: section mismatch in reference: %s%s0x%x (section: %s) -> %s (section: %s)\n",
1030 modname, fromsym, fromsym[0] ? "+" : "",
1031 (unsigned int)(faddr - (fromsym[0] ? from->st_value : 0)),
1032 fromsec, tosym[0] ? tosym : taddr_str, tosec);
1034 if (mismatch->mismatch == EXTABLE_TO_NON_TEXT) {
1035 if (match(tosec, mismatch->bad_tosec))
1036 fatal("The relocation at %s+0x%lx references\n"
1037 "section \"%s\" which is black-listed.\n"
1038 "Something is seriously wrong and should be fixed.\n"
1039 "You might get more information about where this is\n"
1040 "coming from by using scripts/check_extable.sh %s\n",
1041 fromsec, (long)faddr, tosec, modname);
1042 else if (is_executable_section(elf, get_secindex(elf, tsym)))
1043 warn("The relocation at %s+0x%lx references\n"
1044 "section \"%s\" which is not in the list of\n"
1045 "authorized sections. If you're adding a new section\n"
1046 "and/or if this reference is valid, add \"%s\" to the\n"
1047 "list of authorized sections to jump to on fault.\n"
1048 "This can be achieved by adding \"%s\" to\n"
1049 "OTHER_TEXT_SECTIONS in scripts/mod/modpost.c.\n",
1050 fromsec, (long)faddr, tosec, tosec, tosec);
1052 error("%s+0x%lx references non-executable section '%s'\n",
1053 fromsec, (long)faddr, tosec);
1057 static void check_export_symbol(struct module *mod, struct elf_info *elf,
1058 Elf_Addr faddr, const char *secname,
1061 static const char *prefix = "__export_symbol_";
1062 const char *label_name, *name, *data;
1067 label = find_fromsym(elf, faddr, elf->export_symbol_secndx);
1068 label_name = sym_name(elf, label);
1070 if (!strstarts(label_name, prefix)) {
1071 error("%s: .export_symbol section contains strange symbol '%s'\n",
1072 mod->name, label_name);
1076 if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL &&
1077 ELF_ST_BIND(sym->st_info) != STB_WEAK) {
1078 error("%s: local symbol '%s' was exported\n", mod->name,
1079 label_name + strlen(prefix));
1083 name = sym_name(elf, sym);
1084 if (strcmp(label_name + strlen(prefix), name)) {
1085 error("%s: .export_symbol section references '%s', but it does not seem to be an export symbol\n",
1090 data = sym_get_data(elf, label); /* license */
1091 if (!strcmp(data, "GPL")) {
1093 } else if (!strcmp(data, "")) {
1096 error("%s: unknown license '%s' was specified for '%s'\n",
1097 mod->name, data, name);
1101 data += strlen(data) + 1; /* namespace */
1102 s = sym_add_exported(name, mod, is_gpl, data);
1105 * We need to be aware whether we are exporting a function or
1106 * a data on some architectures.
1108 s->is_func = (ELF_ST_TYPE(sym->st_info) == STT_FUNC);
1111 * For parisc64, symbols prefixed $$ from the library have the symbol type
1112 * STT_LOPROC. They should be handled as functions too.
1114 if (elf->hdr->e_ident[EI_CLASS] == ELFCLASS64 &&
1115 elf->hdr->e_machine == EM_PARISC &&
1116 ELF_ST_TYPE(sym->st_info) == STT_LOPROC)
1119 if (match(secname, PATTERNS(ALL_INIT_SECTIONS)))
1120 warn("%s: %s: EXPORT_SYMBOL used for init symbol. Remove __init or EXPORT_SYMBOL.\n",
1122 else if (match(secname, PATTERNS(ALL_EXIT_SECTIONS)))
1123 warn("%s: %s: EXPORT_SYMBOL used for exit symbol. Remove __exit or EXPORT_SYMBOL.\n",
1127 static void check_section_mismatch(struct module *mod, struct elf_info *elf,
1129 unsigned int fsecndx, const char *fromsec,
1130 Elf_Addr faddr, Elf_Addr taddr)
1132 const char *tosec = sec_name(elf, get_secindex(elf, sym));
1133 const struct sectioncheck *mismatch;
1135 if (module_enabled && elf->export_symbol_secndx == fsecndx) {
1136 check_export_symbol(mod, elf, faddr, tosec, sym);
1140 mismatch = section_mismatch(fromsec, tosec);
1144 default_mismatch_handler(mod->name, elf, mismatch, sym,
1145 fsecndx, fromsec, faddr,
1149 static Elf_Addr addend_386_rel(uint32_t *location, unsigned int r_type)
1153 return TO_NATIVE(*location);
1155 return TO_NATIVE(*location) + 4;
1158 return (Elf_Addr)(-1);
1161 static int32_t sign_extend32(int32_t value, int index)
1163 uint8_t shift = 31 - index;
1165 return (int32_t)(value << shift) >> shift;
1168 static Elf_Addr addend_arm_rel(void *loc, Elf_Sym *sym, unsigned int r_type)
1170 uint32_t inst, upper, lower, sign, j1, j2;
1176 inst = TO_NATIVE(*(uint32_t *)loc);
1177 return inst + sym->st_value;
1178 case R_ARM_MOVW_ABS_NC:
1179 case R_ARM_MOVT_ABS:
1180 inst = TO_NATIVE(*(uint32_t *)loc);
1181 offset = sign_extend32(((inst & 0xf0000) >> 4) | (inst & 0xfff),
1183 return offset + sym->st_value;
1187 inst = TO_NATIVE(*(uint32_t *)loc);
1188 offset = sign_extend32((inst & 0x00ffffff) << 2, 25);
1189 return offset + sym->st_value + 8;
1190 case R_ARM_THM_MOVW_ABS_NC:
1191 case R_ARM_THM_MOVT_ABS:
1192 upper = TO_NATIVE(*(uint16_t *)loc);
1193 lower = TO_NATIVE(*((uint16_t *)loc + 1));
1194 offset = sign_extend32(((upper & 0x000f) << 12) |
1195 ((upper & 0x0400) << 1) |
1196 ((lower & 0x7000) >> 4) |
1199 return offset + sym->st_value;
1200 case R_ARM_THM_JUMP19:
1207 * imm11 = lower[10:0]
1208 * imm32 = SignExtend(S:J2:J1:imm6:imm11:'0')
1210 upper = TO_NATIVE(*(uint16_t *)loc);
1211 lower = TO_NATIVE(*((uint16_t *)loc + 1));
1213 sign = (upper >> 10) & 1;
1214 j1 = (lower >> 13) & 1;
1215 j2 = (lower >> 11) & 1;
1216 offset = sign_extend32((sign << 20) | (j2 << 19) | (j1 << 18) |
1217 ((upper & 0x03f) << 12) |
1218 ((lower & 0x07ff) << 1),
1220 return offset + sym->st_value + 4;
1221 case R_ARM_THM_PC22:
1222 case R_ARM_THM_JUMP24:
1226 * imm10 = upper[9:0]
1229 * imm11 = lower[10:0]
1230 * I1 = NOT(J1 XOR S)
1231 * I2 = NOT(J2 XOR S)
1232 * imm32 = SignExtend(S:I1:I2:imm10:imm11:'0')
1234 upper = TO_NATIVE(*(uint16_t *)loc);
1235 lower = TO_NATIVE(*((uint16_t *)loc + 1));
1237 sign = (upper >> 10) & 1;
1238 j1 = (lower >> 13) & 1;
1239 j2 = (lower >> 11) & 1;
1240 offset = sign_extend32((sign << 24) |
1241 ((~(j1 ^ sign) & 1) << 23) |
1242 ((~(j2 ^ sign) & 1) << 22) |
1243 ((upper & 0x03ff) << 12) |
1244 ((lower & 0x07ff) << 1),
1246 return offset + sym->st_value + 4;
1249 return (Elf_Addr)(-1);
1252 static Elf_Addr addend_mips_rel(uint32_t *location, unsigned int r_type)
1256 inst = TO_NATIVE(*location);
1259 return inst & 0xffff;
1261 return (inst & 0x03ffffff) << 2;
1265 return (Elf_Addr)(-1);
1269 #define EM_RISCV 243
1272 #ifndef R_RISCV_SUB32
1273 #define R_RISCV_SUB32 39
1276 #ifndef EM_LOONGARCH
1277 #define EM_LOONGARCH 258
1280 #ifndef R_LARCH_SUB32
1281 #define R_LARCH_SUB32 55
1284 #ifndef R_LARCH_RELAX
1285 #define R_LARCH_RELAX 100
1288 #ifndef R_LARCH_ALIGN
1289 #define R_LARCH_ALIGN 102
1292 static void get_rel_type_and_sym(struct elf_info *elf, uint64_t r_info,
1293 unsigned int *r_type, unsigned int *r_sym)
1296 Elf64_Word r_sym; /* Symbol index */
1297 unsigned char r_ssym; /* Special symbol for 2nd relocation */
1298 unsigned char r_type3; /* 3rd relocation type */
1299 unsigned char r_type2; /* 2nd relocation type */
1300 unsigned char r_type; /* 1st relocation type */
1301 } Elf64_Mips_R_Info;
1303 bool is_64bit = (elf->hdr->e_ident[EI_CLASS] == ELFCLASS64);
1305 if (elf->hdr->e_machine == EM_MIPS && is_64bit) {
1306 Elf64_Mips_R_Info *mips64_r_info = (void *)&r_info;
1308 *r_type = mips64_r_info->r_type;
1309 *r_sym = TO_NATIVE(mips64_r_info->r_sym);
1314 r_info = TO_NATIVE((Elf64_Xword)r_info);
1316 r_info = TO_NATIVE((Elf32_Word)r_info);
1318 *r_type = ELF_R_TYPE(r_info);
1319 *r_sym = ELF_R_SYM(r_info);
1322 static void section_rela(struct module *mod, struct elf_info *elf,
1323 unsigned int fsecndx, const char *fromsec,
1324 const Elf_Rela *start, const Elf_Rela *stop)
1326 const Elf_Rela *rela;
1328 for (rela = start; rela < stop; rela++) {
1330 Elf_Addr taddr, r_offset;
1331 unsigned int r_type, r_sym;
1333 r_offset = TO_NATIVE(rela->r_offset);
1334 get_rel_type_and_sym(elf, rela->r_info, &r_type, &r_sym);
1336 tsym = elf->symtab_start + r_sym;
1337 taddr = tsym->st_value + TO_NATIVE(rela->r_addend);
1339 switch (elf->hdr->e_machine) {
1341 if (!strcmp("__ex_table", fromsec) &&
1342 r_type == R_RISCV_SUB32)
1348 if (!strcmp("__ex_table", fromsec))
1353 /* These relocs do not refer to symbols */
1359 check_section_mismatch(mod, elf, tsym,
1360 fsecndx, fromsec, r_offset, taddr);
1364 static void section_rel(struct module *mod, struct elf_info *elf,
1365 unsigned int fsecndx, const char *fromsec,
1366 const Elf_Rel *start, const Elf_Rel *stop)
1370 for (rel = start; rel < stop; rel++) {
1372 Elf_Addr taddr, r_offset;
1373 unsigned int r_type, r_sym;
1376 r_offset = TO_NATIVE(rel->r_offset);
1377 get_rel_type_and_sym(elf, rel->r_info, &r_type, &r_sym);
1379 loc = sym_get_data_by_offset(elf, fsecndx, r_offset);
1380 tsym = elf->symtab_start + r_sym;
1382 switch (elf->hdr->e_machine) {
1384 taddr = addend_386_rel(loc, r_type);
1387 taddr = addend_arm_rel(loc, tsym, r_type);
1390 taddr = addend_mips_rel(loc, r_type);
1393 fatal("Please add code to calculate addend for this architecture\n");
1396 check_section_mismatch(mod, elf, tsym,
1397 fsecndx, fromsec, r_offset, taddr);
1402 * A module includes a number of sections that are discarded
1403 * either when loaded or when used as built-in.
1404 * For loaded modules all functions marked __init and all data
1405 * marked __initdata will be discarded when the module has been initialized.
1406 * Likewise for modules used built-in the sections marked __exit
1407 * are discarded because __exit marked function are supposed to be called
1408 * only when a module is unloaded which never happens for built-in modules.
1409 * The check_sec_ref() function traverses all relocation records
1410 * to find all references to a section that reference a section that will
1411 * be discarded and warns about it.
1413 static void check_sec_ref(struct module *mod, struct elf_info *elf)
1417 /* Walk through all sections */
1418 for (i = 0; i < elf->num_sections; i++) {
1419 Elf_Shdr *sechdr = &elf->sechdrs[i];
1421 check_section(mod->name, elf, sechdr);
1422 /* We want to process only relocation sections and not .init */
1423 if (sechdr->sh_type == SHT_REL || sechdr->sh_type == SHT_RELA) {
1424 /* section to which the relocation applies */
1425 unsigned int secndx = sechdr->sh_info;
1426 const char *secname = sec_name(elf, secndx);
1427 const void *start, *stop;
1429 /* If the section is known good, skip it */
1430 if (match(secname, section_white_list))
1433 start = sym_get_data_by_offset(elf, i, 0);
1434 stop = start + sechdr->sh_size;
1436 if (sechdr->sh_type == SHT_RELA)
1437 section_rela(mod, elf, secndx, secname,
1440 section_rel(mod, elf, secndx, secname,
1446 static char *remove_dot(char *s)
1448 size_t n = strcspn(s, ".");
1451 size_t m = strspn(s + n + 1, "0123456789");
1452 if (m && (s[n + m + 1] == '.' || s[n + m + 1] == 0))
1459 * The CRCs are recorded in .*.cmd files in the form of:
1460 * #SYMVER <name> <crc>
1462 static void extract_crcs_for_object(const char *object, struct module *mod)
1464 char cmd_file[PATH_MAX];
1469 base = strrchr(object, '/');
1472 dirlen = base - object;
1478 ret = snprintf(cmd_file, sizeof(cmd_file), "%.*s.%s.cmd",
1479 dirlen, object, base);
1480 if (ret >= sizeof(cmd_file)) {
1481 error("%s: too long path was truncated\n", cmd_file);
1485 buf = read_text_file(cmd_file);
1488 while ((p = strstr(p, "\n#SYMVER "))) {
1494 name = p + strlen("\n#SYMVER ");
1496 p = strchr(name, ' ');
1504 continue; /* skip this line */
1506 crc = strtoul(p, &p, 0);
1508 continue; /* skip this line */
1510 name[namelen] = '\0';
1513 * sym_find_with_module() may return NULL here.
1514 * It typically occurs when CONFIG_TRIM_UNUSED_KSYMS=y.
1515 * Since commit e1327a127703, genksyms calculates CRCs of all
1516 * symbols, including trimmed ones. Ignore orphan CRCs.
1518 sym = sym_find_with_module(name, mod);
1520 sym_set_crc(sym, crc);
1527 * The symbol versions (CRC) are recorded in the .*.cmd files.
1528 * Parse them to retrieve CRCs for the current module.
1530 static void mod_set_crcs(struct module *mod)
1532 char objlist[PATH_MAX];
1533 char *buf, *p, *obj;
1536 if (mod->is_vmlinux) {
1537 strcpy(objlist, ".vmlinux.objs");
1539 /* objects for a module are listed in the *.mod file. */
1540 ret = snprintf(objlist, sizeof(objlist), "%s.mod", mod->name);
1541 if (ret >= sizeof(objlist)) {
1542 error("%s: too long path was truncated\n", objlist);
1547 buf = read_text_file(objlist);
1550 while ((obj = strsep(&p, "\n")) && obj[0])
1551 extract_crcs_for_object(obj, mod);
1556 static void read_symbols(const char *modname)
1558 const char *symname;
1563 struct elf_info info = { };
1566 if (!parse_elf(&info, modname))
1569 if (!strends(modname, ".o")) {
1570 error("%s: filename must be suffixed with .o\n", modname);
1574 /* strip trailing .o */
1575 mod = new_module(modname, strlen(modname) - strlen(".o"));
1577 if (!mod->is_vmlinux) {
1578 license = get_modinfo(&info, "license");
1580 error("missing MODULE_LICENSE() in %s\n", modname);
1582 if (!license_is_gpl_compatible(license)) {
1583 mod->is_gpl_compatible = false;
1586 license = get_next_modinfo(&info, "license", license);
1589 namespace = get_modinfo(&info, "import_ns");
1591 add_namespace(&mod->imported_namespaces, namespace);
1592 namespace = get_next_modinfo(&info, "import_ns",
1596 if (extra_warn && !get_modinfo(&info, "description"))
1597 warn("missing MODULE_DESCRIPTION() in %s\n", modname);
1600 for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
1601 symname = remove_dot(info.strtab + sym->st_name);
1603 handle_symbol(mod, &info, sym, symname);
1604 handle_moddevtable(mod, &info, sym, symname);
1607 check_sec_ref(mod, &info);
1609 if (!mod->is_vmlinux) {
1610 version = get_modinfo(&info, "version");
1611 if (version || all_versions)
1612 get_src_version(mod->name, mod->srcversion,
1613 sizeof(mod->srcversion) - 1);
1616 parse_elf_finish(&info);
1620 * Our trick to get versioning for module struct etc. - it's
1621 * never passed as an argument to an exported function, so
1622 * the automatic versioning doesn't pick it up, but it's really
1625 sym_add_unresolved("module_layout", mod, false);
1631 static void read_symbols_from_files(const char *filename)
1634 char fname[PATH_MAX];
1636 in = fopen(filename, "r");
1638 fatal("Can't open filenames file %s: %m", filename);
1640 while (fgets(fname, PATH_MAX, in) != NULL) {
1641 if (strends(fname, "\n"))
1642 fname[strlen(fname)-1] = '\0';
1643 read_symbols(fname);
1651 /* We first write the generated file into memory using the
1652 * following helper, then compare to the file on disk and
1653 * only update the later if anything changed */
1655 void __attribute__((format(printf, 2, 3))) buf_printf(struct buffer *buf,
1656 const char *fmt, ...)
1663 len = vsnprintf(tmp, SZ, fmt, ap);
1664 buf_write(buf, tmp, len);
1668 void buf_write(struct buffer *buf, const char *s, int len)
1670 if (buf->size - buf->pos < len) {
1671 buf->size += len + SZ;
1672 buf->p = xrealloc(buf->p, buf->size);
1674 strncpy(buf->p + buf->pos, s, len);
1678 static void check_exports(struct module *mod)
1680 struct symbol *s, *exp;
1682 list_for_each_entry(s, &mod->unresolved_symbols, list) {
1683 const char *basename;
1684 exp = find_symbol(s->name);
1686 if (!s->weak && nr_unresolved++ < MAX_UNRESOLVED_REPORTS)
1687 modpost_log(!warn_unresolved,
1688 "\"%s\" [%s.ko] undefined!\n",
1689 s->name, mod->name);
1692 if (exp->module == mod) {
1693 error("\"%s\" [%s.ko] was exported without definition\n",
1694 s->name, mod->name);
1699 s->module = exp->module;
1700 s->crc_valid = exp->crc_valid;
1703 basename = strrchr(mod->name, '/');
1707 basename = mod->name;
1709 if (!contains_namespace(&mod->imported_namespaces, exp->namespace)) {
1710 modpost_log(!allow_missing_ns_imports,
1711 "module %s uses symbol %s from namespace %s, but does not import it.\n",
1712 basename, exp->name, exp->namespace);
1713 add_namespace(&mod->missing_namespaces, exp->namespace);
1716 if (!mod->is_gpl_compatible && exp->is_gpl_only)
1717 error("GPL-incompatible module %s.ko uses GPL-only symbol '%s'\n",
1718 basename, exp->name);
1722 static void handle_white_list_exports(const char *white_list)
1724 char *buf, *p, *name;
1726 buf = read_text_file(white_list);
1729 while ((name = strsep(&p, "\n"))) {
1730 struct symbol *sym = find_symbol(name);
1739 static void check_modname_len(struct module *mod)
1741 const char *mod_name;
1743 mod_name = strrchr(mod->name, '/');
1744 if (mod_name == NULL)
1745 mod_name = mod->name;
1748 if (strlen(mod_name) >= MODULE_NAME_LEN)
1749 error("module name is too long [%s.ko]\n", mod->name);
1753 * Header for the generated file
1755 static void add_header(struct buffer *b, struct module *mod)
1757 buf_printf(b, "#include <linux/module.h>\n");
1758 buf_printf(b, "#include <linux/export-internal.h>\n");
1759 buf_printf(b, "#include <linux/compiler.h>\n");
1760 buf_printf(b, "\n");
1761 buf_printf(b, "MODULE_INFO(name, KBUILD_MODNAME);\n");
1762 buf_printf(b, "\n");
1763 buf_printf(b, "__visible struct module __this_module\n");
1764 buf_printf(b, "__section(\".gnu.linkonce.this_module\") = {\n");
1765 buf_printf(b, "\t.name = KBUILD_MODNAME,\n");
1767 buf_printf(b, "\t.init = init_module,\n");
1768 if (mod->has_cleanup)
1769 buf_printf(b, "#ifdef CONFIG_MODULE_UNLOAD\n"
1770 "\t.exit = cleanup_module,\n"
1772 buf_printf(b, "\t.arch = MODULE_ARCH_INIT,\n");
1773 buf_printf(b, "};\n");
1775 if (!external_module)
1776 buf_printf(b, "\nMODULE_INFO(intree, \"Y\");\n");
1778 if (strstarts(mod->name, "drivers/staging"))
1779 buf_printf(b, "\nMODULE_INFO(staging, \"Y\");\n");
1781 if (strstarts(mod->name, "tools/testing"))
1782 buf_printf(b, "\nMODULE_INFO(test, \"Y\");\n");
1785 static void add_exported_symbols(struct buffer *buf, struct module *mod)
1789 /* generate struct for exported symbols */
1790 buf_printf(buf, "\n");
1791 list_for_each_entry(sym, &mod->exported_symbols, list) {
1792 if (trim_unused_exports && !sym->used)
1795 buf_printf(buf, "KSYMTAB_%s(%s, \"%s\", \"%s\");\n",
1796 sym->is_func ? "FUNC" : "DATA", sym->name,
1797 sym->is_gpl_only ? "_gpl" : "", sym->namespace);
1803 /* record CRCs for exported symbols */
1804 buf_printf(buf, "\n");
1805 list_for_each_entry(sym, &mod->exported_symbols, list) {
1806 if (trim_unused_exports && !sym->used)
1809 if (!sym->crc_valid)
1810 warn("EXPORT symbol \"%s\" [%s%s] version generation failed, symbol will not be versioned.\n"
1811 "Is \"%s\" prototyped in <asm/asm-prototypes.h>?\n",
1812 sym->name, mod->name, mod->is_vmlinux ? "" : ".ko",
1815 buf_printf(buf, "SYMBOL_CRC(%s, 0x%08x, \"%s\");\n",
1816 sym->name, sym->crc, sym->is_gpl_only ? "_gpl" : "");
1821 * Record CRCs for unresolved symbols
1823 static void add_versions(struct buffer *b, struct module *mod)
1830 buf_printf(b, "\n");
1831 buf_printf(b, "static const struct modversion_info ____versions[]\n");
1832 buf_printf(b, "__used __section(\"__versions\") = {\n");
1834 list_for_each_entry(s, &mod->unresolved_symbols, list) {
1837 if (!s->crc_valid) {
1838 warn("\"%s\" [%s.ko] has no CRC!\n",
1839 s->name, mod->name);
1842 if (strlen(s->name) >= MODULE_NAME_LEN) {
1843 error("too long symbol \"%s\" [%s.ko]\n",
1844 s->name, mod->name);
1847 buf_printf(b, "\t{ %#8x, \"%s\" },\n",
1851 buf_printf(b, "};\n");
1854 static void add_depends(struct buffer *b, struct module *mod)
1859 /* Clear ->seen flag of modules that own symbols needed by this. */
1860 list_for_each_entry(s, &mod->unresolved_symbols, list) {
1862 s->module->seen = s->module->is_vmlinux;
1865 buf_printf(b, "\n");
1866 buf_printf(b, "MODULE_INFO(depends, \"");
1867 list_for_each_entry(s, &mod->unresolved_symbols, list) {
1872 if (s->module->seen)
1875 s->module->seen = true;
1876 p = strrchr(s->module->name, '/');
1880 p = s->module->name;
1881 buf_printf(b, "%s%s", first ? "" : ",", p);
1884 buf_printf(b, "\");\n");
1887 static void add_srcversion(struct buffer *b, struct module *mod)
1889 if (mod->srcversion[0]) {
1890 buf_printf(b, "\n");
1891 buf_printf(b, "MODULE_INFO(srcversion, \"%s\");\n",
1896 static void write_buf(struct buffer *b, const char *fname)
1903 file = fopen(fname, "w");
1908 if (fwrite(b->p, 1, b->pos, file) != b->pos) {
1912 if (fclose(file) != 0) {
1918 static void write_if_changed(struct buffer *b, const char *fname)
1924 file = fopen(fname, "r");
1928 if (fstat(fileno(file), &st) < 0)
1931 if (st.st_size != b->pos)
1934 tmp = xmalloc(b->pos);
1935 if (fread(tmp, 1, b->pos, file) != b->pos)
1938 if (memcmp(tmp, b->p, b->pos) != 0)
1950 write_buf(b, fname);
1953 static void write_vmlinux_export_c_file(struct module *mod)
1955 struct buffer buf = { };
1958 "#include <linux/export-internal.h>\n");
1960 add_exported_symbols(&buf, mod);
1961 write_if_changed(&buf, ".vmlinux.export.c");
1965 /* do sanity checks, and generate *.mod.c file */
1966 static void write_mod_c_file(struct module *mod)
1968 struct buffer buf = { };
1969 char fname[PATH_MAX];
1972 add_header(&buf, mod);
1973 add_exported_symbols(&buf, mod);
1974 add_versions(&buf, mod);
1975 add_depends(&buf, mod);
1976 add_moddevtable(&buf, mod);
1977 add_srcversion(&buf, mod);
1979 ret = snprintf(fname, sizeof(fname), "%s.mod.c", mod->name);
1980 if (ret >= sizeof(fname)) {
1981 error("%s: too long path was truncated\n", fname);
1985 write_if_changed(&buf, fname);
1991 /* parse Module.symvers file. line format:
1992 * 0x12345678<tab>symbol<tab>module<tab>export<tab>namespace
1994 static void read_dump(const char *fname)
1996 char *buf, *pos, *line;
1998 buf = read_text_file(fname);
2000 /* No symbol versions, silently ignore */
2005 while ((line = get_line(&pos))) {
2006 char *symname, *namespace, *modname, *d, *export;
2012 if (!(symname = strchr(line, '\t')))
2015 if (!(modname = strchr(symname, '\t')))
2018 if (!(export = strchr(modname, '\t')))
2021 if (!(namespace = strchr(export, '\t')))
2023 *namespace++ = '\0';
2025 crc = strtoul(line, &d, 16);
2026 if (*symname == '\0' || *modname == '\0' || *d != '\0')
2029 if (!strcmp(export, "EXPORT_SYMBOL_GPL")) {
2031 } else if (!strcmp(export, "EXPORT_SYMBOL")) {
2034 error("%s: unknown license %s. skip", symname, export);
2038 mod = find_module(modname);
2040 mod = new_module(modname, strlen(modname));
2041 mod->from_dump = true;
2043 s = sym_add_exported(symname, mod, gpl_only, namespace);
2044 sym_set_crc(s, crc);
2050 fatal("parse error in symbol dump file\n");
2053 static void write_dump(const char *fname)
2055 struct buffer buf = { };
2059 list_for_each_entry(mod, &modules, list) {
2062 list_for_each_entry(sym, &mod->exported_symbols, list) {
2063 if (trim_unused_exports && !sym->used)
2066 buf_printf(&buf, "0x%08x\t%s\t%s\tEXPORT_SYMBOL%s\t%s\n",
2067 sym->crc, sym->name, mod->name,
2068 sym->is_gpl_only ? "_GPL" : "",
2072 write_buf(&buf, fname);
2076 static void write_namespace_deps_files(const char *fname)
2079 struct namespace_list *ns;
2080 struct buffer ns_deps_buf = {};
2082 list_for_each_entry(mod, &modules, list) {
2084 if (mod->from_dump || list_empty(&mod->missing_namespaces))
2087 buf_printf(&ns_deps_buf, "%s.ko:", mod->name);
2089 list_for_each_entry(ns, &mod->missing_namespaces, list)
2090 buf_printf(&ns_deps_buf, " %s", ns->namespace);
2092 buf_printf(&ns_deps_buf, "\n");
2095 write_if_changed(&ns_deps_buf, fname);
2096 free(ns_deps_buf.p);
2100 struct list_head list;
2104 static void check_host_endian(void)
2106 static const union {
2109 } endian_test = { .c = {0x01, 0x02} };
2111 switch (endian_test.s) {
2113 host_is_big_endian = true;
2116 host_is_big_endian = false;
2119 fatal("Unknown host endian\n");
2123 int main(int argc, char **argv)
2126 char *missing_namespace_deps = NULL;
2127 char *unused_exports_white_list = NULL;
2128 char *dump_write = NULL, *files_source = NULL;
2130 LIST_HEAD(dump_lists);
2131 struct dump_list *dl, *dl2;
2133 while ((opt = getopt(argc, argv, "ei:MmnT:to:au:WwENd:")) != -1) {
2136 external_module = true;
2139 dl = xmalloc(sizeof(*dl));
2141 list_add_tail(&dl->list, &dump_lists);
2144 module_enabled = true;
2150 ignore_missing_files = true;
2153 dump_write = optarg;
2156 all_versions = true;
2159 files_source = optarg;
2162 trim_unused_exports = true;
2165 unused_exports_white_list = optarg;
2171 warn_unresolved = true;
2174 sec_mismatch_warn_only = false;
2177 allow_missing_ns_imports = true;
2180 missing_namespace_deps = optarg;
2187 check_host_endian();
2189 list_for_each_entry_safe(dl, dl2, &dump_lists, list) {
2190 read_dump(dl->file);
2191 list_del(&dl->list);
2195 while (optind < argc)
2196 read_symbols(argv[optind++]);
2199 read_symbols_from_files(files_source);
2201 list_for_each_entry(mod, &modules, list) {
2202 if (mod->from_dump || mod->is_vmlinux)
2205 check_modname_len(mod);
2209 if (unused_exports_white_list)
2210 handle_white_list_exports(unused_exports_white_list);
2212 list_for_each_entry(mod, &modules, list) {
2216 if (mod->is_vmlinux)
2217 write_vmlinux_export_c_file(mod);
2219 write_mod_c_file(mod);
2222 if (missing_namespace_deps)
2223 write_namespace_deps_files(missing_namespace_deps);
2226 write_dump(dump_write);
2227 if (sec_mismatch_count && !sec_mismatch_warn_only)
2228 error("Section mismatches detected.\n"
2229 "Set CONFIG_SECTION_MISMATCH_WARN_ONLY=y to allow them.\n");
2231 if (nr_unresolved > MAX_UNRESOLVED_REPORTS)
2232 warn("suppressed %u unresolved symbol warnings because there were too many)\n",
2233 nr_unresolved - MAX_UNRESOLVED_REPORTS);
2235 return error_occurred ? 1 : 0;