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>
27 #include "../../include/linux/license.h"
29 static bool module_enabled;
30 /* Are we using CONFIG_MODVERSIONS? */
31 static bool modversions;
32 /* Is CONFIG_MODULE_SRCVERSION_ALL set? */
33 static bool all_versions;
34 /* If we are modposting external module set to 1 */
35 static bool external_module;
36 /* Only warn about unresolved symbols */
37 static bool warn_unresolved;
39 static int sec_mismatch_count;
40 static bool sec_mismatch_warn_only = true;
41 /* Trim EXPORT_SYMBOLs that are unused by in-tree modules */
42 static bool trim_unused_exports;
44 /* ignore missing files */
45 static bool ignore_missing_files;
46 /* If set to 1, only warn (instead of error) about missing ns imports */
47 static bool allow_missing_ns_imports;
49 static bool error_occurred;
51 static bool extra_warn;
54 * Cut off the warnings when there are too many. This typically occurs when
55 * vmlinux is missing. ('make modules' without building vmlinux.)
57 #define MAX_UNRESOLVED_REPORTS 10
58 static unsigned int nr_unresolved;
60 /* In kernel, this size is defined in linux/module.h;
61 * here we use Elf_Addr instead of long for covering cross-compile
64 #define MODULE_NAME_LEN (64 - sizeof(Elf_Addr))
66 void modpost_log(enum loglevel loglevel, const char *fmt, ...)
72 fprintf(stderr, "WARNING: ");
75 fprintf(stderr, "ERROR: ");
76 error_occurred = true;
78 default: /* invalid loglevel, ignore */
82 fprintf(stderr, "modpost: ");
84 va_start(arglist, fmt);
85 vfprintf(stderr, fmt, arglist);
89 static inline bool strends(const char *str, const char *postfix)
91 if (strlen(str) < strlen(postfix))
94 return strcmp(str + strlen(str) - strlen(postfix), postfix) == 0;
97 void *do_nofail(void *ptr, const char *expr)
100 fatal("Memory allocation failure: %s.\n", expr);
105 char *read_text_file(const char *filename)
112 fd = open(filename, O_RDONLY);
118 if (fstat(fd, &st) < 0) {
123 buf = NOFAIL(malloc(st.st_size + 1));
130 bytes_read = read(fd, buf, nbytes);
131 if (bytes_read < 0) {
136 nbytes -= bytes_read;
138 buf[st.st_size] = '\0';
145 char *get_line(char **stringp)
147 char *orig = *stringp, *next;
149 /* do not return the unwanted extra line at EOF */
150 if (!orig || *orig == '\0')
153 /* don't use strsep here, it is not available everywhere */
154 next = strchr(orig, '\n');
163 /* A list of all modules we processed */
166 static struct module *find_module(const char *modname)
170 list_for_each_entry(mod, &modules, list) {
171 if (strcmp(mod->name, modname) == 0)
177 static struct module *new_module(const char *name, size_t namelen)
181 mod = NOFAIL(malloc(sizeof(*mod) + namelen + 1));
182 memset(mod, 0, sizeof(*mod));
184 INIT_LIST_HEAD(&mod->exported_symbols);
185 INIT_LIST_HEAD(&mod->unresolved_symbols);
186 INIT_LIST_HEAD(&mod->missing_namespaces);
187 INIT_LIST_HEAD(&mod->imported_namespaces);
189 memcpy(mod->name, name, namelen);
190 mod->name[namelen] = '\0';
191 mod->is_vmlinux = (strcmp(mod->name, "vmlinux") == 0);
194 * Set mod->is_gpl_compatible to true by default. If MODULE_LICENSE()
195 * is missing, do not check the use for EXPORT_SYMBOL_GPL() becasue
196 * modpost will exit wiht error anyway.
198 mod->is_gpl_compatible = true;
200 list_add_tail(&mod->list, &modules);
206 struct hlist_node hnode;/* link to hash table */
207 struct list_head list; /* link to module::exported_symbols or module::unresolved_symbols */
208 struct module *module;
214 bool is_gpl_only; /* exported by EXPORT_SYMBOL_GPL */
215 bool used; /* there exists a user of this symbol */
219 static HASHTABLE_DEFINE(symbol_hashtable, 1U << 10);
221 /* This is based on the hash algorithm from gdbm, via tdb */
222 static inline unsigned int tdb_hash(const char *name)
224 unsigned value; /* Used to compute the hash value. */
225 unsigned i; /* Used to cycle through random values. */
227 /* Set the initial value from the key size. */
228 for (value = 0x238F13AF * strlen(name), i = 0; name[i]; i++)
229 value = (value + (((unsigned char *)name)[i] << (i*5 % 24)));
231 return (1103515243 * value + 12345);
235 * Allocate a new symbols for use in the hash of exported symbols or
236 * the list of unresolved symbols per module
238 static struct symbol *alloc_symbol(const char *name)
240 struct symbol *s = NOFAIL(malloc(sizeof(*s) + strlen(name) + 1));
242 memset(s, 0, sizeof(*s));
243 strcpy(s->name, name);
248 /* For the hash of exported symbols */
249 static void hash_add_symbol(struct symbol *sym)
251 hash_add(symbol_hashtable, &sym->hnode, tdb_hash(sym->name));
254 static void sym_add_unresolved(const char *name, struct module *mod, bool weak)
258 sym = alloc_symbol(name);
261 list_add_tail(&sym->list, &mod->unresolved_symbols);
264 static struct symbol *sym_find_with_module(const char *name, struct module *mod)
268 /* For our purposes, .foo matches foo. PPC64 needs this. */
272 hash_for_each_possible(symbol_hashtable, s, hnode, tdb_hash(name)) {
273 if (strcmp(s->name, name) == 0 && (!mod || s->module == mod))
279 static struct symbol *find_symbol(const char *name)
281 return sym_find_with_module(name, NULL);
284 struct namespace_list {
285 struct list_head list;
289 static bool contains_namespace(struct list_head *head, const char *namespace)
291 struct namespace_list *list;
294 * The default namespace is null string "", which is always implicitly
300 list_for_each_entry(list, head, list) {
301 if (!strcmp(list->namespace, namespace))
308 static void add_namespace(struct list_head *head, const char *namespace)
310 struct namespace_list *ns_entry;
312 if (!contains_namespace(head, namespace)) {
313 ns_entry = NOFAIL(malloc(sizeof(*ns_entry) +
314 strlen(namespace) + 1));
315 strcpy(ns_entry->namespace, namespace);
316 list_add_tail(&ns_entry->list, head);
320 static void *sym_get_data_by_offset(const struct elf_info *info,
321 unsigned int secindex, unsigned long offset)
323 Elf_Shdr *sechdr = &info->sechdrs[secindex];
325 return (void *)info->hdr + sechdr->sh_offset + offset;
328 void *sym_get_data(const struct elf_info *info, const Elf_Sym *sym)
330 return sym_get_data_by_offset(info, get_secindex(info, sym),
334 static const char *sech_name(const struct elf_info *info, Elf_Shdr *sechdr)
336 return sym_get_data_by_offset(info, info->secindex_strings,
340 static const char *sec_name(const struct elf_info *info, unsigned int secindex)
343 * If sym->st_shndx is a special section index, there is no
344 * corresponding section header.
345 * Return "" if the index is out of range of info->sechdrs[] array.
347 if (secindex >= info->num_sections)
350 return sech_name(info, &info->sechdrs[secindex]);
353 #define strstarts(str, prefix) (strncmp(str, prefix, strlen(prefix)) == 0)
355 static struct symbol *sym_add_exported(const char *name, struct module *mod,
356 bool gpl_only, const char *namespace)
358 struct symbol *s = find_symbol(name);
360 if (s && (!external_module || s->module->is_vmlinux || s->module == mod)) {
361 error("%s: '%s' exported twice. Previous export was in %s%s\n",
362 mod->name, name, s->module->name,
363 s->module->is_vmlinux ? "" : ".ko");
366 s = alloc_symbol(name);
368 s->is_gpl_only = gpl_only;
369 s->namespace = NOFAIL(strdup(namespace));
370 list_add_tail(&s->list, &mod->exported_symbols);
376 static void sym_set_crc(struct symbol *sym, unsigned int crc)
379 sym->crc_valid = true;
382 static void *grab_file(const char *filename, size_t *size)
385 void *map = MAP_FAILED;
388 fd = open(filename, O_RDONLY);
395 map = mmap(NULL, *size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
399 if (map == MAP_FAILED)
404 static void release_file(void *file, size_t size)
409 static int parse_elf(struct elf_info *info, const char *filename)
415 const char *secstrings;
416 unsigned int symtab_idx = ~0U, symtab_shndx_idx = ~0U;
418 hdr = grab_file(filename, &info->size);
420 if (ignore_missing_files) {
421 fprintf(stderr, "%s: %s (ignored)\n", filename,
429 if (info->size < sizeof(*hdr)) {
430 /* file too small, assume this is an empty .o file */
433 /* Is this a valid ELF file? */
434 if ((hdr->e_ident[EI_MAG0] != ELFMAG0) ||
435 (hdr->e_ident[EI_MAG1] != ELFMAG1) ||
436 (hdr->e_ident[EI_MAG2] != ELFMAG2) ||
437 (hdr->e_ident[EI_MAG3] != ELFMAG3)) {
438 /* Not an ELF file - silently ignore it */
441 /* Fix endianness in ELF header */
442 hdr->e_type = TO_NATIVE(hdr->e_type);
443 hdr->e_machine = TO_NATIVE(hdr->e_machine);
444 hdr->e_version = TO_NATIVE(hdr->e_version);
445 hdr->e_entry = TO_NATIVE(hdr->e_entry);
446 hdr->e_phoff = TO_NATIVE(hdr->e_phoff);
447 hdr->e_shoff = TO_NATIVE(hdr->e_shoff);
448 hdr->e_flags = TO_NATIVE(hdr->e_flags);
449 hdr->e_ehsize = TO_NATIVE(hdr->e_ehsize);
450 hdr->e_phentsize = TO_NATIVE(hdr->e_phentsize);
451 hdr->e_phnum = TO_NATIVE(hdr->e_phnum);
452 hdr->e_shentsize = TO_NATIVE(hdr->e_shentsize);
453 hdr->e_shnum = TO_NATIVE(hdr->e_shnum);
454 hdr->e_shstrndx = TO_NATIVE(hdr->e_shstrndx);
455 sechdrs = (void *)hdr + hdr->e_shoff;
456 info->sechdrs = sechdrs;
458 /* modpost only works for relocatable objects */
459 if (hdr->e_type != ET_REL)
460 fatal("%s: not relocatable object.", filename);
462 /* Check if file offset is correct */
463 if (hdr->e_shoff > info->size)
464 fatal("section header offset=%lu in file '%s' is bigger than filesize=%zu\n",
465 (unsigned long)hdr->e_shoff, filename, info->size);
467 if (hdr->e_shnum == SHN_UNDEF) {
469 * There are more than 64k sections,
470 * read count from .sh_size.
472 info->num_sections = TO_NATIVE(sechdrs[0].sh_size);
475 info->num_sections = hdr->e_shnum;
477 if (hdr->e_shstrndx == SHN_XINDEX) {
478 info->secindex_strings = TO_NATIVE(sechdrs[0].sh_link);
481 info->secindex_strings = hdr->e_shstrndx;
484 /* Fix endianness in section headers */
485 for (i = 0; i < info->num_sections; i++) {
486 sechdrs[i].sh_name = TO_NATIVE(sechdrs[i].sh_name);
487 sechdrs[i].sh_type = TO_NATIVE(sechdrs[i].sh_type);
488 sechdrs[i].sh_flags = TO_NATIVE(sechdrs[i].sh_flags);
489 sechdrs[i].sh_addr = TO_NATIVE(sechdrs[i].sh_addr);
490 sechdrs[i].sh_offset = TO_NATIVE(sechdrs[i].sh_offset);
491 sechdrs[i].sh_size = TO_NATIVE(sechdrs[i].sh_size);
492 sechdrs[i].sh_link = TO_NATIVE(sechdrs[i].sh_link);
493 sechdrs[i].sh_info = TO_NATIVE(sechdrs[i].sh_info);
494 sechdrs[i].sh_addralign = TO_NATIVE(sechdrs[i].sh_addralign);
495 sechdrs[i].sh_entsize = TO_NATIVE(sechdrs[i].sh_entsize);
497 /* Find symbol table. */
498 secstrings = (void *)hdr + sechdrs[info->secindex_strings].sh_offset;
499 for (i = 1; i < info->num_sections; i++) {
501 int nobits = sechdrs[i].sh_type == SHT_NOBITS;
503 if (!nobits && sechdrs[i].sh_offset > info->size)
504 fatal("%s is truncated. sechdrs[i].sh_offset=%lu > sizeof(*hrd)=%zu\n",
505 filename, (unsigned long)sechdrs[i].sh_offset,
508 secname = secstrings + sechdrs[i].sh_name;
509 if (strcmp(secname, ".modinfo") == 0) {
511 fatal("%s has NOBITS .modinfo\n", filename);
512 info->modinfo = (void *)hdr + sechdrs[i].sh_offset;
513 info->modinfo_len = sechdrs[i].sh_size;
514 } else if (!strcmp(secname, ".export_symbol")) {
515 info->export_symbol_secndx = i;
518 if (sechdrs[i].sh_type == SHT_SYMTAB) {
519 unsigned int sh_link_idx;
521 info->symtab_start = (void *)hdr +
522 sechdrs[i].sh_offset;
523 info->symtab_stop = (void *)hdr +
524 sechdrs[i].sh_offset + sechdrs[i].sh_size;
525 sh_link_idx = sechdrs[i].sh_link;
526 info->strtab = (void *)hdr +
527 sechdrs[sh_link_idx].sh_offset;
530 /* 32bit section no. table? ("more than 64k sections") */
531 if (sechdrs[i].sh_type == SHT_SYMTAB_SHNDX) {
532 symtab_shndx_idx = i;
533 info->symtab_shndx_start = (void *)hdr +
534 sechdrs[i].sh_offset;
535 info->symtab_shndx_stop = (void *)hdr +
536 sechdrs[i].sh_offset + sechdrs[i].sh_size;
539 if (!info->symtab_start)
540 fatal("%s has no symtab?\n", filename);
542 /* Fix endianness in symbols */
543 for (sym = info->symtab_start; sym < info->symtab_stop; sym++) {
544 sym->st_shndx = TO_NATIVE(sym->st_shndx);
545 sym->st_name = TO_NATIVE(sym->st_name);
546 sym->st_value = TO_NATIVE(sym->st_value);
547 sym->st_size = TO_NATIVE(sym->st_size);
550 if (symtab_shndx_idx != ~0U) {
552 if (symtab_idx != sechdrs[symtab_shndx_idx].sh_link)
553 fatal("%s: SYMTAB_SHNDX has bad sh_link: %u!=%u\n",
554 filename, sechdrs[symtab_shndx_idx].sh_link,
557 for (p = info->symtab_shndx_start; p < info->symtab_shndx_stop;
562 symsearch_init(info);
567 static void parse_elf_finish(struct elf_info *info)
569 symsearch_finish(info);
570 release_file(info->hdr, info->size);
573 static int ignore_undef_symbol(struct elf_info *info, const char *symname)
575 /* ignore __this_module, it will be resolved shortly */
576 if (strcmp(symname, "__this_module") == 0)
578 /* ignore global offset table */
579 if (strcmp(symname, "_GLOBAL_OFFSET_TABLE_") == 0)
581 if (info->hdr->e_machine == EM_PPC)
582 /* Special register function linked on all modules during final link of .ko */
583 if (strstarts(symname, "_restgpr_") ||
584 strstarts(symname, "_savegpr_") ||
585 strstarts(symname, "_rest32gpr_") ||
586 strstarts(symname, "_save32gpr_") ||
587 strstarts(symname, "_restvr_") ||
588 strstarts(symname, "_savevr_"))
590 if (info->hdr->e_machine == EM_PPC64)
591 /* Special register function linked on all modules during final link of .ko */
592 if (strstarts(symname, "_restgpr0_") ||
593 strstarts(symname, "_savegpr0_") ||
594 strstarts(symname, "_restvr_") ||
595 strstarts(symname, "_savevr_") ||
596 strcmp(symname, ".TOC.") == 0)
598 /* Do not ignore this symbol */
602 static void handle_symbol(struct module *mod, struct elf_info *info,
603 const Elf_Sym *sym, const char *symname)
605 switch (sym->st_shndx) {
607 if (strstarts(symname, "__gnu_lto_")) {
608 /* Should warn here, but modpost runs before the linker */
610 warn("\"%s\" [%s] is COMMON symbol\n", symname, mod->name);
613 /* undefined symbol */
614 if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL &&
615 ELF_ST_BIND(sym->st_info) != STB_WEAK)
617 if (ignore_undef_symbol(info, symname))
619 if (info->hdr->e_machine == EM_SPARC ||
620 info->hdr->e_machine == EM_SPARCV9) {
621 /* Ignore register directives. */
622 if (ELF_ST_TYPE(sym->st_info) == STT_SPARC_REGISTER)
624 if (symname[0] == '.') {
625 char *munged = NOFAIL(strdup(symname));
627 munged[1] = toupper(munged[1]);
632 sym_add_unresolved(symname, mod,
633 ELF_ST_BIND(sym->st_info) == STB_WEAK);
636 if (strcmp(symname, "init_module") == 0)
637 mod->has_init = true;
638 if (strcmp(symname, "cleanup_module") == 0)
639 mod->has_cleanup = true;
645 * Parse tag=value strings from .modinfo section
647 static char *next_string(char *string, unsigned long *secsize)
649 /* Skip non-zero chars */
652 if ((*secsize)-- <= 1)
656 /* Skip any zero padding. */
659 if ((*secsize)-- <= 1)
665 static char *get_next_modinfo(struct elf_info *info, const char *tag,
669 unsigned int taglen = strlen(tag);
670 char *modinfo = info->modinfo;
671 unsigned long size = info->modinfo_len;
674 size -= prev - modinfo;
675 modinfo = next_string(prev, &size);
678 for (p = modinfo; p; p = next_string(p, &size)) {
679 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
680 return p + taglen + 1;
685 static char *get_modinfo(struct elf_info *info, const char *tag)
688 return get_next_modinfo(info, tag, NULL);
691 static const char *sym_name(struct elf_info *elf, Elf_Sym *sym)
694 return elf->strtab + sym->st_name;
700 * Check whether the 'string' argument matches one of the 'patterns',
701 * an array of shell wildcard patterns (glob).
703 * Return true is there is a match.
705 static bool match(const char *string, const char *const patterns[])
709 while ((pattern = *patterns++)) {
710 if (!fnmatch(pattern, string, 0))
717 /* useful to pass patterns to match() directly */
718 #define PATTERNS(...) \
720 static const char *const patterns[] = {__VA_ARGS__, NULL}; \
724 /* sections that we do not want to do full section mismatch check on */
725 static const char *const section_white_list[] =
729 ".zdebug*", /* Compressed debug sections. */
730 ".GCC.command.line", /* record-gcc-switches */
731 ".mdebug*", /* alpha, score, mips etc. */
732 ".pdr", /* alpha, score, mips etc. */
737 ".xt.prop", /* xtensa */
738 ".xt.lit", /* xtensa */
739 ".arcextmap*", /* arc */
740 ".gnu.linkonce.arcext*", /* arc : modules */
741 ".cmem*", /* EZchip */
742 ".fmt_slot*", /* EZchip */
745 ".llvm.call-graph-profile", /* call graph */
750 * This is used to find sections missing the SHF_ALLOC flag.
751 * The cause of this is often a section specified in assembler
752 * without "ax" / "aw".
754 static void check_section(const char *modname, struct elf_info *elf,
757 const char *sec = sech_name(elf, sechdr);
759 if (sechdr->sh_type == SHT_PROGBITS &&
760 !(sechdr->sh_flags & SHF_ALLOC) &&
761 !match(sec, section_white_list)) {
762 warn("%s (%s): unexpected non-allocatable section.\n"
763 "Did you forget to use \"ax\"/\"aw\" in a .S file?\n"
764 "Note that for example <linux/init.h> contains\n"
765 "section definitions for use in .S files.\n\n",
772 #define ALL_INIT_DATA_SECTIONS \
773 ".init.setup", ".init.rodata", ".init.data"
775 #define ALL_PCI_INIT_SECTIONS \
776 ".pci_fixup_early", ".pci_fixup_header", ".pci_fixup_final", \
777 ".pci_fixup_enable", ".pci_fixup_resume", \
778 ".pci_fixup_resume_early", ".pci_fixup_suspend"
780 #define ALL_INIT_SECTIONS ".init.*"
781 #define ALL_EXIT_SECTIONS ".exit.*"
783 #define DATA_SECTIONS ".data", ".data.rel"
784 #define TEXT_SECTIONS ".text", ".text.*", ".sched.text", \
785 ".kprobes.text", ".cpuidle.text", ".noinstr.text", \
787 #define OTHER_TEXT_SECTIONS ".ref.text", ".head.text", ".spinlock.text", \
788 ".fixup", ".entry.text", ".exception.text", \
789 ".coldtext", ".softirqentry.text"
791 #define ALL_TEXT_SECTIONS ".init.text", ".exit.text", \
792 TEXT_SECTIONS, OTHER_TEXT_SECTIONS
795 TEXTDATA_TO_ANY_INIT_EXIT,
796 XXXINIT_TO_SOME_INIT,
797 ANY_INIT_TO_ANY_EXIT,
798 ANY_EXIT_TO_ANY_INIT,
803 * Describe how to match sections on different criteria:
805 * @fromsec: Array of sections to be matched.
807 * @bad_tosec: Relocations applied to a section in @fromsec to a section in
808 * this array is forbidden (black-list). Can be empty.
810 * @good_tosec: Relocations applied to a section in @fromsec must be
811 * targeting sections in this array (white-list). Can be empty.
813 * @mismatch: Type of mismatch.
815 struct sectioncheck {
816 const char *fromsec[20];
817 const char *bad_tosec[20];
818 const char *good_tosec[20];
819 enum mismatch mismatch;
822 static const struct sectioncheck sectioncheck[] = {
823 /* Do not reference init/exit code/data from
824 * normal code and data
827 .fromsec = { TEXT_SECTIONS, DATA_SECTIONS, NULL },
828 .bad_tosec = { ALL_INIT_SECTIONS, ALL_EXIT_SECTIONS, NULL },
829 .mismatch = TEXTDATA_TO_ANY_INIT_EXIT,
831 /* Do not use exit code/data from init code */
833 .fromsec = { ALL_INIT_SECTIONS, NULL },
834 .bad_tosec = { ALL_EXIT_SECTIONS, NULL },
835 .mismatch = ANY_INIT_TO_ANY_EXIT,
837 /* Do not use init code/data from exit code */
839 .fromsec = { ALL_EXIT_SECTIONS, NULL },
840 .bad_tosec = { ALL_INIT_SECTIONS, NULL },
841 .mismatch = ANY_EXIT_TO_ANY_INIT,
844 .fromsec = { ALL_PCI_INIT_SECTIONS, NULL },
845 .bad_tosec = { ALL_INIT_SECTIONS, NULL },
846 .mismatch = ANY_INIT_TO_ANY_EXIT,
849 .fromsec = { "__ex_table", NULL },
850 /* If you're adding any new black-listed sections in here, consider
851 * adding a special 'printer' for them in scripts/check_extable.
853 .bad_tosec = { ".altinstr_replacement", NULL },
854 .good_tosec = {ALL_TEXT_SECTIONS , NULL},
855 .mismatch = EXTABLE_TO_NON_TEXT,
859 static const struct sectioncheck *section_mismatch(
860 const char *fromsec, const char *tosec)
865 * The target section could be the SHT_NUL section when we're
866 * handling relocations to un-resolved symbols, trying to match it
867 * doesn't make much sense and causes build failures on parisc
873 for (i = 0; i < ARRAY_SIZE(sectioncheck); i++) {
874 const struct sectioncheck *check = §ioncheck[i];
876 if (match(fromsec, check->fromsec)) {
877 if (check->bad_tosec[0] && match(tosec, check->bad_tosec))
879 if (check->good_tosec[0] && !match(tosec, check->good_tosec))
887 * Whitelist to allow certain references to pass with no warning.
890 * If a module parameter is declared __initdata and permissions=0
891 * then this is legal despite the warning generated.
892 * We cannot see value of permissions here, so just ignore
894 * The pattern is identified by:
900 * module_param_call() ops can refer to __init set function if permissions=0
901 * The pattern is identified by:
904 * atsym = __param_ops_*
907 * Whitelist all references from .head.text to any init section
910 * Some symbols belong to init section but still it is ok to reference
911 * these from non-init sections as these symbols don't have any memory
912 * allocated for them and symbol address and value are same. So even
913 * if init section is freed, its ok to reference those symbols.
914 * For ex. symbols marking the init section boundaries.
915 * This pattern is identified by
916 * refsymname = __init_begin, _sinittext, _einittext
919 * GCC may optimize static inlines when fed constant arg(s) resulting
920 * in functions like cpumask_empty() -- generating an associated symbol
921 * cpumask_empty.constprop.3 that appears in the audit. If the const that
922 * is passed in comes from __init, like say nmi_ipi_mask, we get a
923 * meaningless section warning. May need to add isra symbols too...
924 * This pattern is identified by
925 * tosec = init section
926 * fromsec = text section
927 * refsymname = *.constprop.*
930 static int secref_whitelist(const char *fromsec, const char *fromsym,
931 const char *tosec, const char *tosym)
933 /* Check for pattern 1 */
934 if (match(tosec, PATTERNS(ALL_INIT_DATA_SECTIONS)) &&
935 match(fromsec, PATTERNS(DATA_SECTIONS)) &&
936 strstarts(fromsym, "__param"))
939 /* Check for pattern 1a */
940 if (strcmp(tosec, ".init.text") == 0 &&
941 match(fromsec, PATTERNS(DATA_SECTIONS)) &&
942 strstarts(fromsym, "__param_ops_"))
945 /* symbols in data sections that may refer to any init/exit sections */
946 if (match(fromsec, PATTERNS(DATA_SECTIONS)) &&
947 match(tosec, PATTERNS(ALL_INIT_SECTIONS, ALL_EXIT_SECTIONS)) &&
948 match(fromsym, PATTERNS("*_ops", "*_probe", "*_console")))
951 /* Check for pattern 3 */
952 if (strstarts(fromsec, ".head.text") &&
953 match(tosec, PATTERNS(ALL_INIT_SECTIONS)))
956 /* Check for pattern 4 */
957 if (match(tosym, PATTERNS("__init_begin", "_sinittext", "_einittext")))
960 /* Check for pattern 5 */
961 if (match(fromsec, PATTERNS(ALL_TEXT_SECTIONS)) &&
962 match(tosec, PATTERNS(ALL_INIT_SECTIONS)) &&
963 match(fromsym, PATTERNS("*.constprop.*")))
969 static Elf_Sym *find_fromsym(struct elf_info *elf, Elf_Addr addr,
972 return symsearch_find_nearest(elf, addr, secndx, false, ~0);
975 static Elf_Sym *find_tosym(struct elf_info *elf, Elf_Addr addr, Elf_Sym *sym)
979 /* If the supplied symbol has a valid name, return it */
980 if (is_valid_name(elf, sym))
984 * Strive to find a better symbol name, but the resulting name may not
985 * match the symbol referenced in the original code.
987 new_sym = symsearch_find_nearest(elf, addr, get_secindex(elf, sym),
989 return new_sym ? new_sym : sym;
992 static bool is_executable_section(struct elf_info *elf, unsigned int secndx)
994 if (secndx >= elf->num_sections)
997 return (elf->sechdrs[secndx].sh_flags & SHF_EXECINSTR) != 0;
1000 static void default_mismatch_handler(const char *modname, struct elf_info *elf,
1001 const struct sectioncheck* const mismatch,
1003 unsigned int fsecndx, const char *fromsec, Elf_Addr faddr,
1004 const char *tosec, Elf_Addr taddr)
1008 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++;
1022 warn("%s: section mismatch in reference: %s+0x%x (section: %s) -> %s (section: %s)\n",
1024 (unsigned int)(faddr - (from ? from->st_value : 0)),
1025 fromsec, tosym, tosec);
1027 if (mismatch->mismatch == EXTABLE_TO_NON_TEXT) {
1028 if (match(tosec, mismatch->bad_tosec))
1029 fatal("The relocation at %s+0x%lx references\n"
1030 "section \"%s\" which is black-listed.\n"
1031 "Something is seriously wrong and should be fixed.\n"
1032 "You might get more information about where this is\n"
1033 "coming from by using scripts/check_extable.sh %s\n",
1034 fromsec, (long)faddr, tosec, modname);
1035 else if (is_executable_section(elf, get_secindex(elf, tsym)))
1036 warn("The relocation at %s+0x%lx references\n"
1037 "section \"%s\" which is not in the list of\n"
1038 "authorized sections. If you're adding a new section\n"
1039 "and/or if this reference is valid, add \"%s\" to the\n"
1040 "list of authorized sections to jump to on fault.\n"
1041 "This can be achieved by adding \"%s\" to\n"
1042 "OTHER_TEXT_SECTIONS in scripts/mod/modpost.c.\n",
1043 fromsec, (long)faddr, tosec, tosec, tosec);
1045 error("%s+0x%lx references non-executable section '%s'\n",
1046 fromsec, (long)faddr, tosec);
1050 static void check_export_symbol(struct module *mod, struct elf_info *elf,
1051 Elf_Addr faddr, const char *secname,
1054 static const char *prefix = "__export_symbol_";
1055 const char *label_name, *name, *data;
1060 label = find_fromsym(elf, faddr, elf->export_symbol_secndx);
1061 label_name = sym_name(elf, label);
1063 if (!strstarts(label_name, prefix)) {
1064 error("%s: .export_symbol section contains strange symbol '%s'\n",
1065 mod->name, label_name);
1069 if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL &&
1070 ELF_ST_BIND(sym->st_info) != STB_WEAK) {
1071 error("%s: local symbol '%s' was exported\n", mod->name,
1072 label_name + strlen(prefix));
1076 name = sym_name(elf, sym);
1077 if (strcmp(label_name + strlen(prefix), name)) {
1078 error("%s: .export_symbol section references '%s', but it does not seem to be an export symbol\n",
1083 data = sym_get_data(elf, label); /* license */
1084 if (!strcmp(data, "GPL")) {
1086 } else if (!strcmp(data, "")) {
1089 error("%s: unknown license '%s' was specified for '%s'\n",
1090 mod->name, data, name);
1094 data += strlen(data) + 1; /* namespace */
1095 s = sym_add_exported(name, mod, is_gpl, data);
1098 * We need to be aware whether we are exporting a function or
1099 * a data on some architectures.
1101 s->is_func = (ELF_ST_TYPE(sym->st_info) == STT_FUNC);
1104 * For parisc64, symbols prefixed $$ from the library have the symbol type
1105 * STT_LOPROC. They should be handled as functions too.
1107 if (elf->hdr->e_ident[EI_CLASS] == ELFCLASS64 &&
1108 elf->hdr->e_machine == EM_PARISC &&
1109 ELF_ST_TYPE(sym->st_info) == STT_LOPROC)
1112 if (match(secname, PATTERNS(ALL_INIT_SECTIONS)))
1113 warn("%s: %s: EXPORT_SYMBOL used for init symbol. Remove __init or EXPORT_SYMBOL.\n",
1115 else if (match(secname, PATTERNS(ALL_EXIT_SECTIONS)))
1116 warn("%s: %s: EXPORT_SYMBOL used for exit symbol. Remove __exit or EXPORT_SYMBOL.\n",
1120 static void check_section_mismatch(struct module *mod, struct elf_info *elf,
1122 unsigned int fsecndx, const char *fromsec,
1123 Elf_Addr faddr, Elf_Addr taddr)
1125 const char *tosec = sec_name(elf, get_secindex(elf, sym));
1126 const struct sectioncheck *mismatch;
1128 if (module_enabled && elf->export_symbol_secndx == fsecndx) {
1129 check_export_symbol(mod, elf, faddr, tosec, sym);
1133 mismatch = section_mismatch(fromsec, tosec);
1137 default_mismatch_handler(mod->name, elf, mismatch, sym,
1138 fsecndx, fromsec, faddr,
1142 static Elf_Addr addend_386_rel(uint32_t *location, unsigned int r_type)
1146 return TO_NATIVE(*location);
1148 return TO_NATIVE(*location) + 4;
1151 return (Elf_Addr)(-1);
1154 static int32_t sign_extend32(int32_t value, int index)
1156 uint8_t shift = 31 - index;
1158 return (int32_t)(value << shift) >> shift;
1161 static Elf_Addr addend_arm_rel(void *loc, Elf_Sym *sym, unsigned int r_type)
1163 uint32_t inst, upper, lower, sign, j1, j2;
1169 inst = TO_NATIVE(*(uint32_t *)loc);
1170 return inst + sym->st_value;
1171 case R_ARM_MOVW_ABS_NC:
1172 case R_ARM_MOVT_ABS:
1173 inst = TO_NATIVE(*(uint32_t *)loc);
1174 offset = sign_extend32(((inst & 0xf0000) >> 4) | (inst & 0xfff),
1176 return offset + sym->st_value;
1180 inst = TO_NATIVE(*(uint32_t *)loc);
1181 offset = sign_extend32((inst & 0x00ffffff) << 2, 25);
1182 return offset + sym->st_value + 8;
1183 case R_ARM_THM_MOVW_ABS_NC:
1184 case R_ARM_THM_MOVT_ABS:
1185 upper = TO_NATIVE(*(uint16_t *)loc);
1186 lower = TO_NATIVE(*((uint16_t *)loc + 1));
1187 offset = sign_extend32(((upper & 0x000f) << 12) |
1188 ((upper & 0x0400) << 1) |
1189 ((lower & 0x7000) >> 4) |
1192 return offset + sym->st_value;
1193 case R_ARM_THM_JUMP19:
1200 * imm11 = lower[10:0]
1201 * imm32 = SignExtend(S:J2:J1:imm6:imm11:'0')
1203 upper = TO_NATIVE(*(uint16_t *)loc);
1204 lower = TO_NATIVE(*((uint16_t *)loc + 1));
1206 sign = (upper >> 10) & 1;
1207 j1 = (lower >> 13) & 1;
1208 j2 = (lower >> 11) & 1;
1209 offset = sign_extend32((sign << 20) | (j2 << 19) | (j1 << 18) |
1210 ((upper & 0x03f) << 12) |
1211 ((lower & 0x07ff) << 1),
1213 return offset + sym->st_value + 4;
1214 case R_ARM_THM_PC22:
1215 case R_ARM_THM_JUMP24:
1219 * imm10 = upper[9:0]
1222 * imm11 = lower[10:0]
1223 * I1 = NOT(J1 XOR S)
1224 * I2 = NOT(J2 XOR S)
1225 * imm32 = SignExtend(S:I1:I2:imm10:imm11:'0')
1227 upper = TO_NATIVE(*(uint16_t *)loc);
1228 lower = TO_NATIVE(*((uint16_t *)loc + 1));
1230 sign = (upper >> 10) & 1;
1231 j1 = (lower >> 13) & 1;
1232 j2 = (lower >> 11) & 1;
1233 offset = sign_extend32((sign << 24) |
1234 ((~(j1 ^ sign) & 1) << 23) |
1235 ((~(j2 ^ sign) & 1) << 22) |
1236 ((upper & 0x03ff) << 12) |
1237 ((lower & 0x07ff) << 1),
1239 return offset + sym->st_value + 4;
1242 return (Elf_Addr)(-1);
1245 static Elf_Addr addend_mips_rel(uint32_t *location, unsigned int r_type)
1249 inst = TO_NATIVE(*location);
1252 return inst & 0xffff;
1254 return (inst & 0x03ffffff) << 2;
1258 return (Elf_Addr)(-1);
1262 #define EM_RISCV 243
1265 #ifndef R_RISCV_SUB32
1266 #define R_RISCV_SUB32 39
1269 #ifndef EM_LOONGARCH
1270 #define EM_LOONGARCH 258
1273 #ifndef R_LARCH_SUB32
1274 #define R_LARCH_SUB32 55
1277 #ifndef R_LARCH_RELAX
1278 #define R_LARCH_RELAX 100
1281 #ifndef R_LARCH_ALIGN
1282 #define R_LARCH_ALIGN 102
1285 static void get_rel_type_and_sym(struct elf_info *elf, uint64_t r_info,
1286 unsigned int *r_type, unsigned int *r_sym)
1289 Elf64_Word r_sym; /* Symbol index */
1290 unsigned char r_ssym; /* Special symbol for 2nd relocation */
1291 unsigned char r_type3; /* 3rd relocation type */
1292 unsigned char r_type2; /* 2nd relocation type */
1293 unsigned char r_type; /* 1st relocation type */
1294 } Elf64_Mips_R_Info;
1296 bool is_64bit = (elf->hdr->e_ident[EI_CLASS] == ELFCLASS64);
1298 if (elf->hdr->e_machine == EM_MIPS && is_64bit) {
1299 Elf64_Mips_R_Info *mips64_r_info = (void *)&r_info;
1301 *r_type = mips64_r_info->r_type;
1302 *r_sym = TO_NATIVE(mips64_r_info->r_sym);
1307 r_info = TO_NATIVE((Elf64_Xword)r_info);
1309 r_info = TO_NATIVE((Elf32_Word)r_info);
1311 *r_type = ELF_R_TYPE(r_info);
1312 *r_sym = ELF_R_SYM(r_info);
1315 static void section_rela(struct module *mod, struct elf_info *elf,
1316 unsigned int fsecndx, const char *fromsec,
1317 const Elf_Rela *start, const Elf_Rela *stop)
1319 const Elf_Rela *rela;
1321 for (rela = start; rela < stop; rela++) {
1323 Elf_Addr taddr, r_offset;
1324 unsigned int r_type, r_sym;
1326 r_offset = TO_NATIVE(rela->r_offset);
1327 get_rel_type_and_sym(elf, rela->r_info, &r_type, &r_sym);
1329 tsym = elf->symtab_start + r_sym;
1330 taddr = tsym->st_value + TO_NATIVE(rela->r_addend);
1332 switch (elf->hdr->e_machine) {
1334 if (!strcmp("__ex_table", fromsec) &&
1335 r_type == R_RISCV_SUB32)
1341 if (!strcmp("__ex_table", fromsec))
1346 /* These relocs do not refer to symbols */
1352 check_section_mismatch(mod, elf, tsym,
1353 fsecndx, fromsec, r_offset, taddr);
1357 static void section_rel(struct module *mod, struct elf_info *elf,
1358 unsigned int fsecndx, const char *fromsec,
1359 const Elf_Rel *start, const Elf_Rel *stop)
1363 for (rel = start; rel < stop; rel++) {
1365 Elf_Addr taddr, r_offset;
1366 unsigned int r_type, r_sym;
1369 r_offset = TO_NATIVE(rel->r_offset);
1370 get_rel_type_and_sym(elf, rel->r_info, &r_type, &r_sym);
1372 loc = sym_get_data_by_offset(elf, fsecndx, r_offset);
1373 tsym = elf->symtab_start + r_sym;
1375 switch (elf->hdr->e_machine) {
1377 taddr = addend_386_rel(loc, r_type);
1380 taddr = addend_arm_rel(loc, tsym, r_type);
1383 taddr = addend_mips_rel(loc, r_type);
1386 fatal("Please add code to calculate addend for this architecture\n");
1389 check_section_mismatch(mod, elf, tsym,
1390 fsecndx, fromsec, r_offset, taddr);
1395 * A module includes a number of sections that are discarded
1396 * either when loaded or when used as built-in.
1397 * For loaded modules all functions marked __init and all data
1398 * marked __initdata will be discarded when the module has been initialized.
1399 * Likewise for modules used built-in the sections marked __exit
1400 * are discarded because __exit marked function are supposed to be called
1401 * only when a module is unloaded which never happens for built-in modules.
1402 * The check_sec_ref() function traverses all relocation records
1403 * to find all references to a section that reference a section that will
1404 * be discarded and warns about it.
1406 static void check_sec_ref(struct module *mod, struct elf_info *elf)
1410 /* Walk through all sections */
1411 for (i = 0; i < elf->num_sections; i++) {
1412 Elf_Shdr *sechdr = &elf->sechdrs[i];
1414 check_section(mod->name, elf, sechdr);
1415 /* We want to process only relocation sections and not .init */
1416 if (sechdr->sh_type == SHT_REL || sechdr->sh_type == SHT_RELA) {
1417 /* section to which the relocation applies */
1418 unsigned int secndx = sechdr->sh_info;
1419 const char *secname = sec_name(elf, secndx);
1420 const void *start, *stop;
1422 /* If the section is known good, skip it */
1423 if (match(secname, section_white_list))
1426 start = sym_get_data_by_offset(elf, i, 0);
1427 stop = start + sechdr->sh_size;
1429 if (sechdr->sh_type == SHT_RELA)
1430 section_rela(mod, elf, secndx, secname,
1433 section_rel(mod, elf, secndx, secname,
1439 static char *remove_dot(char *s)
1441 size_t n = strcspn(s, ".");
1444 size_t m = strspn(s + n + 1, "0123456789");
1445 if (m && (s[n + m + 1] == '.' || s[n + m + 1] == 0))
1452 * The CRCs are recorded in .*.cmd files in the form of:
1453 * #SYMVER <name> <crc>
1455 static void extract_crcs_for_object(const char *object, struct module *mod)
1457 char cmd_file[PATH_MAX];
1462 base = strrchr(object, '/');
1465 dirlen = base - object;
1471 ret = snprintf(cmd_file, sizeof(cmd_file), "%.*s.%s.cmd",
1472 dirlen, object, base);
1473 if (ret >= sizeof(cmd_file)) {
1474 error("%s: too long path was truncated\n", cmd_file);
1478 buf = read_text_file(cmd_file);
1481 while ((p = strstr(p, "\n#SYMVER "))) {
1487 name = p + strlen("\n#SYMVER ");
1489 p = strchr(name, ' ');
1497 continue; /* skip this line */
1499 crc = strtoul(p, &p, 0);
1501 continue; /* skip this line */
1503 name[namelen] = '\0';
1506 * sym_find_with_module() may return NULL here.
1507 * It typically occurs when CONFIG_TRIM_UNUSED_KSYMS=y.
1508 * Since commit e1327a127703, genksyms calculates CRCs of all
1509 * symbols, including trimmed ones. Ignore orphan CRCs.
1511 sym = sym_find_with_module(name, mod);
1513 sym_set_crc(sym, crc);
1520 * The symbol versions (CRC) are recorded in the .*.cmd files.
1521 * Parse them to retrieve CRCs for the current module.
1523 static void mod_set_crcs(struct module *mod)
1525 char objlist[PATH_MAX];
1526 char *buf, *p, *obj;
1529 if (mod->is_vmlinux) {
1530 strcpy(objlist, ".vmlinux.objs");
1532 /* objects for a module are listed in the *.mod file. */
1533 ret = snprintf(objlist, sizeof(objlist), "%s.mod", mod->name);
1534 if (ret >= sizeof(objlist)) {
1535 error("%s: too long path was truncated\n", objlist);
1540 buf = read_text_file(objlist);
1543 while ((obj = strsep(&p, "\n")) && obj[0])
1544 extract_crcs_for_object(obj, mod);
1549 static void read_symbols(const char *modname)
1551 const char *symname;
1556 struct elf_info info = { };
1559 if (!parse_elf(&info, modname))
1562 if (!strends(modname, ".o")) {
1563 error("%s: filename must be suffixed with .o\n", modname);
1567 /* strip trailing .o */
1568 mod = new_module(modname, strlen(modname) - strlen(".o"));
1570 if (!mod->is_vmlinux) {
1571 license = get_modinfo(&info, "license");
1573 error("missing MODULE_LICENSE() in %s\n", modname);
1575 if (!license_is_gpl_compatible(license)) {
1576 mod->is_gpl_compatible = false;
1579 license = get_next_modinfo(&info, "license", license);
1582 namespace = get_modinfo(&info, "import_ns");
1584 add_namespace(&mod->imported_namespaces, namespace);
1585 namespace = get_next_modinfo(&info, "import_ns",
1589 if (extra_warn && !get_modinfo(&info, "description"))
1590 warn("missing MODULE_DESCRIPTION() in %s\n", modname);
1593 for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
1594 symname = remove_dot(info.strtab + sym->st_name);
1596 handle_symbol(mod, &info, sym, symname);
1597 handle_moddevtable(mod, &info, sym, symname);
1600 check_sec_ref(mod, &info);
1602 if (!mod->is_vmlinux) {
1603 version = get_modinfo(&info, "version");
1604 if (version || all_versions)
1605 get_src_version(mod->name, mod->srcversion,
1606 sizeof(mod->srcversion) - 1);
1609 parse_elf_finish(&info);
1613 * Our trick to get versioning for module struct etc. - it's
1614 * never passed as an argument to an exported function, so
1615 * the automatic versioning doesn't pick it up, but it's really
1618 sym_add_unresolved("module_layout", mod, false);
1624 static void read_symbols_from_files(const char *filename)
1627 char fname[PATH_MAX];
1629 in = fopen(filename, "r");
1631 fatal("Can't open filenames file %s: %m", filename);
1633 while (fgets(fname, PATH_MAX, in) != NULL) {
1634 if (strends(fname, "\n"))
1635 fname[strlen(fname)-1] = '\0';
1636 read_symbols(fname);
1644 /* We first write the generated file into memory using the
1645 * following helper, then compare to the file on disk and
1646 * only update the later if anything changed */
1648 void __attribute__((format(printf, 2, 3))) buf_printf(struct buffer *buf,
1649 const char *fmt, ...)
1656 len = vsnprintf(tmp, SZ, fmt, ap);
1657 buf_write(buf, tmp, len);
1661 void buf_write(struct buffer *buf, const char *s, int len)
1663 if (buf->size - buf->pos < len) {
1664 buf->size += len + SZ;
1665 buf->p = NOFAIL(realloc(buf->p, buf->size));
1667 strncpy(buf->p + buf->pos, s, len);
1671 static void check_exports(struct module *mod)
1673 struct symbol *s, *exp;
1675 list_for_each_entry(s, &mod->unresolved_symbols, list) {
1676 const char *basename;
1677 exp = find_symbol(s->name);
1679 if (!s->weak && nr_unresolved++ < MAX_UNRESOLVED_REPORTS)
1680 modpost_log(warn_unresolved ? LOG_WARN : LOG_ERROR,
1681 "\"%s\" [%s.ko] undefined!\n",
1682 s->name, mod->name);
1685 if (exp->module == mod) {
1686 error("\"%s\" [%s.ko] was exported without definition\n",
1687 s->name, mod->name);
1692 s->module = exp->module;
1693 s->crc_valid = exp->crc_valid;
1696 basename = strrchr(mod->name, '/');
1700 basename = mod->name;
1702 if (!contains_namespace(&mod->imported_namespaces, exp->namespace)) {
1703 modpost_log(allow_missing_ns_imports ? LOG_WARN : LOG_ERROR,
1704 "module %s uses symbol %s from namespace %s, but does not import it.\n",
1705 basename, exp->name, exp->namespace);
1706 add_namespace(&mod->missing_namespaces, exp->namespace);
1709 if (!mod->is_gpl_compatible && exp->is_gpl_only)
1710 error("GPL-incompatible module %s.ko uses GPL-only symbol '%s'\n",
1711 basename, exp->name);
1715 static void handle_white_list_exports(const char *white_list)
1717 char *buf, *p, *name;
1719 buf = read_text_file(white_list);
1722 while ((name = strsep(&p, "\n"))) {
1723 struct symbol *sym = find_symbol(name);
1732 static void check_modname_len(struct module *mod)
1734 const char *mod_name;
1736 mod_name = strrchr(mod->name, '/');
1737 if (mod_name == NULL)
1738 mod_name = mod->name;
1741 if (strlen(mod_name) >= MODULE_NAME_LEN)
1742 error("module name is too long [%s.ko]\n", mod->name);
1746 * Header for the generated file
1748 static void add_header(struct buffer *b, struct module *mod)
1750 buf_printf(b, "#include <linux/module.h>\n");
1752 * Include build-salt.h after module.h in order to
1753 * inherit the definitions.
1755 buf_printf(b, "#define INCLUDE_VERMAGIC\n");
1756 buf_printf(b, "#include <linux/build-salt.h>\n");
1757 buf_printf(b, "#include <linux/elfnote-lto.h>\n");
1758 buf_printf(b, "#include <linux/export-internal.h>\n");
1759 buf_printf(b, "#include <linux/vermagic.h>\n");
1760 buf_printf(b, "#include <linux/compiler.h>\n");
1761 buf_printf(b, "\n");
1762 buf_printf(b, "#ifdef CONFIG_UNWINDER_ORC\n");
1763 buf_printf(b, "#include <asm/orc_header.h>\n");
1764 buf_printf(b, "ORC_HEADER;\n");
1765 buf_printf(b, "#endif\n");
1766 buf_printf(b, "\n");
1767 buf_printf(b, "BUILD_SALT;\n");
1768 buf_printf(b, "BUILD_LTO_INFO;\n");
1769 buf_printf(b, "\n");
1770 buf_printf(b, "MODULE_INFO(vermagic, VERMAGIC_STRING);\n");
1771 buf_printf(b, "MODULE_INFO(name, KBUILD_MODNAME);\n");
1772 buf_printf(b, "\n");
1773 buf_printf(b, "__visible struct module __this_module\n");
1774 buf_printf(b, "__section(\".gnu.linkonce.this_module\") = {\n");
1775 buf_printf(b, "\t.name = KBUILD_MODNAME,\n");
1777 buf_printf(b, "\t.init = init_module,\n");
1778 if (mod->has_cleanup)
1779 buf_printf(b, "#ifdef CONFIG_MODULE_UNLOAD\n"
1780 "\t.exit = cleanup_module,\n"
1782 buf_printf(b, "\t.arch = MODULE_ARCH_INIT,\n");
1783 buf_printf(b, "};\n");
1785 if (!external_module)
1786 buf_printf(b, "\nMODULE_INFO(intree, \"Y\");\n");
1790 "#ifdef CONFIG_MITIGATION_RETPOLINE\n"
1791 "MODULE_INFO(retpoline, \"Y\");\n"
1794 if (strstarts(mod->name, "drivers/staging"))
1795 buf_printf(b, "\nMODULE_INFO(staging, \"Y\");\n");
1797 if (strstarts(mod->name, "tools/testing"))
1798 buf_printf(b, "\nMODULE_INFO(test, \"Y\");\n");
1801 static void add_exported_symbols(struct buffer *buf, struct module *mod)
1805 /* generate struct for exported symbols */
1806 buf_printf(buf, "\n");
1807 list_for_each_entry(sym, &mod->exported_symbols, list) {
1808 if (trim_unused_exports && !sym->used)
1811 buf_printf(buf, "KSYMTAB_%s(%s, \"%s\", \"%s\");\n",
1812 sym->is_func ? "FUNC" : "DATA", sym->name,
1813 sym->is_gpl_only ? "_gpl" : "", sym->namespace);
1819 /* record CRCs for exported symbols */
1820 buf_printf(buf, "\n");
1821 list_for_each_entry(sym, &mod->exported_symbols, list) {
1822 if (trim_unused_exports && !sym->used)
1825 if (!sym->crc_valid)
1826 warn("EXPORT symbol \"%s\" [%s%s] version generation failed, symbol will not be versioned.\n"
1827 "Is \"%s\" prototyped in <asm/asm-prototypes.h>?\n",
1828 sym->name, mod->name, mod->is_vmlinux ? "" : ".ko",
1831 buf_printf(buf, "SYMBOL_CRC(%s, 0x%08x, \"%s\");\n",
1832 sym->name, sym->crc, sym->is_gpl_only ? "_gpl" : "");
1837 * Record CRCs for unresolved symbols
1839 static void add_versions(struct buffer *b, struct module *mod)
1846 buf_printf(b, "\n");
1847 buf_printf(b, "static const struct modversion_info ____versions[]\n");
1848 buf_printf(b, "__used __section(\"__versions\") = {\n");
1850 list_for_each_entry(s, &mod->unresolved_symbols, list) {
1853 if (!s->crc_valid) {
1854 warn("\"%s\" [%s.ko] has no CRC!\n",
1855 s->name, mod->name);
1858 if (strlen(s->name) >= MODULE_NAME_LEN) {
1859 error("too long symbol \"%s\" [%s.ko]\n",
1860 s->name, mod->name);
1863 buf_printf(b, "\t{ %#8x, \"%s\" },\n",
1867 buf_printf(b, "};\n");
1870 static void add_depends(struct buffer *b, struct module *mod)
1875 /* Clear ->seen flag of modules that own symbols needed by this. */
1876 list_for_each_entry(s, &mod->unresolved_symbols, list) {
1878 s->module->seen = s->module->is_vmlinux;
1881 buf_printf(b, "\n");
1882 buf_printf(b, "MODULE_INFO(depends, \"");
1883 list_for_each_entry(s, &mod->unresolved_symbols, list) {
1888 if (s->module->seen)
1891 s->module->seen = true;
1892 p = strrchr(s->module->name, '/');
1896 p = s->module->name;
1897 buf_printf(b, "%s%s", first ? "" : ",", p);
1900 buf_printf(b, "\");\n");
1903 static void add_srcversion(struct buffer *b, struct module *mod)
1905 if (mod->srcversion[0]) {
1906 buf_printf(b, "\n");
1907 buf_printf(b, "MODULE_INFO(srcversion, \"%s\");\n",
1912 static void write_buf(struct buffer *b, const char *fname)
1919 file = fopen(fname, "w");
1924 if (fwrite(b->p, 1, b->pos, file) != b->pos) {
1928 if (fclose(file) != 0) {
1934 static void write_if_changed(struct buffer *b, const char *fname)
1940 file = fopen(fname, "r");
1944 if (fstat(fileno(file), &st) < 0)
1947 if (st.st_size != b->pos)
1950 tmp = NOFAIL(malloc(b->pos));
1951 if (fread(tmp, 1, b->pos, file) != b->pos)
1954 if (memcmp(tmp, b->p, b->pos) != 0)
1966 write_buf(b, fname);
1969 static void write_vmlinux_export_c_file(struct module *mod)
1971 struct buffer buf = { };
1974 "#include <linux/export-internal.h>\n");
1976 add_exported_symbols(&buf, mod);
1977 write_if_changed(&buf, ".vmlinux.export.c");
1981 /* do sanity checks, and generate *.mod.c file */
1982 static void write_mod_c_file(struct module *mod)
1984 struct buffer buf = { };
1985 char fname[PATH_MAX];
1988 add_header(&buf, mod);
1989 add_exported_symbols(&buf, mod);
1990 add_versions(&buf, mod);
1991 add_depends(&buf, mod);
1992 add_moddevtable(&buf, mod);
1993 add_srcversion(&buf, mod);
1995 ret = snprintf(fname, sizeof(fname), "%s.mod.c", mod->name);
1996 if (ret >= sizeof(fname)) {
1997 error("%s: too long path was truncated\n", fname);
2001 write_if_changed(&buf, fname);
2007 /* parse Module.symvers file. line format:
2008 * 0x12345678<tab>symbol<tab>module<tab>export<tab>namespace
2010 static void read_dump(const char *fname)
2012 char *buf, *pos, *line;
2014 buf = read_text_file(fname);
2016 /* No symbol versions, silently ignore */
2021 while ((line = get_line(&pos))) {
2022 char *symname, *namespace, *modname, *d, *export;
2028 if (!(symname = strchr(line, '\t')))
2031 if (!(modname = strchr(symname, '\t')))
2034 if (!(export = strchr(modname, '\t')))
2037 if (!(namespace = strchr(export, '\t')))
2039 *namespace++ = '\0';
2041 crc = strtoul(line, &d, 16);
2042 if (*symname == '\0' || *modname == '\0' || *d != '\0')
2045 if (!strcmp(export, "EXPORT_SYMBOL_GPL")) {
2047 } else if (!strcmp(export, "EXPORT_SYMBOL")) {
2050 error("%s: unknown license %s. skip", symname, export);
2054 mod = find_module(modname);
2056 mod = new_module(modname, strlen(modname));
2057 mod->from_dump = true;
2059 s = sym_add_exported(symname, mod, gpl_only, namespace);
2060 sym_set_crc(s, crc);
2066 fatal("parse error in symbol dump file\n");
2069 static void write_dump(const char *fname)
2071 struct buffer buf = { };
2075 list_for_each_entry(mod, &modules, list) {
2078 list_for_each_entry(sym, &mod->exported_symbols, list) {
2079 if (trim_unused_exports && !sym->used)
2082 buf_printf(&buf, "0x%08x\t%s\t%s\tEXPORT_SYMBOL%s\t%s\n",
2083 sym->crc, sym->name, mod->name,
2084 sym->is_gpl_only ? "_GPL" : "",
2088 write_buf(&buf, fname);
2092 static void write_namespace_deps_files(const char *fname)
2095 struct namespace_list *ns;
2096 struct buffer ns_deps_buf = {};
2098 list_for_each_entry(mod, &modules, list) {
2100 if (mod->from_dump || list_empty(&mod->missing_namespaces))
2103 buf_printf(&ns_deps_buf, "%s.ko:", mod->name);
2105 list_for_each_entry(ns, &mod->missing_namespaces, list)
2106 buf_printf(&ns_deps_buf, " %s", ns->namespace);
2108 buf_printf(&ns_deps_buf, "\n");
2111 write_if_changed(&ns_deps_buf, fname);
2112 free(ns_deps_buf.p);
2116 struct list_head list;
2120 int main(int argc, char **argv)
2123 char *missing_namespace_deps = NULL;
2124 char *unused_exports_white_list = NULL;
2125 char *dump_write = NULL, *files_source = NULL;
2127 LIST_HEAD(dump_lists);
2128 struct dump_list *dl, *dl2;
2130 while ((opt = getopt(argc, argv, "ei:MmnT:to:au:WwENd:")) != -1) {
2133 external_module = true;
2136 dl = NOFAIL(malloc(sizeof(*dl)));
2138 list_add_tail(&dl->list, &dump_lists);
2141 module_enabled = true;
2147 ignore_missing_files = true;
2150 dump_write = optarg;
2153 all_versions = true;
2156 files_source = optarg;
2159 trim_unused_exports = true;
2162 unused_exports_white_list = optarg;
2168 warn_unresolved = true;
2171 sec_mismatch_warn_only = false;
2174 allow_missing_ns_imports = true;
2177 missing_namespace_deps = optarg;
2184 list_for_each_entry_safe(dl, dl2, &dump_lists, list) {
2185 read_dump(dl->file);
2186 list_del(&dl->list);
2190 while (optind < argc)
2191 read_symbols(argv[optind++]);
2194 read_symbols_from_files(files_source);
2196 list_for_each_entry(mod, &modules, list) {
2197 if (mod->from_dump || mod->is_vmlinux)
2200 check_modname_len(mod);
2204 if (unused_exports_white_list)
2205 handle_white_list_exports(unused_exports_white_list);
2207 list_for_each_entry(mod, &modules, list) {
2211 if (mod->is_vmlinux)
2212 write_vmlinux_export_c_file(mod);
2214 write_mod_c_file(mod);
2217 if (missing_namespace_deps)
2218 write_namespace_deps_files(missing_namespace_deps);
2221 write_dump(dump_write);
2222 if (sec_mismatch_count && !sec_mismatch_warn_only)
2223 error("Section mismatches detected.\n"
2224 "Set CONFIG_SECTION_MISMATCH_WARN_ONLY=y to allow them.\n");
2226 if (nr_unresolved > MAX_UNRESOLVED_REPORTS)
2227 warn("suppressed %u unresolved symbol warnings because there were too many)\n",
2228 nr_unresolved - MAX_UNRESOLVED_REPORTS);
2230 return error_occurred ? 1 : 0;