projects/linux·blob v7.2-rc2 · refs

2419 lines · 60.1 KiB

1/* Postprocess module symbol versions
2 *
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
7 *
8 * This software may be used and distributed according to the terms
9 * of the GNU General Public License, incorporated herein by reference.
10 *
11 * Usage: modpost vmlinux module1.o module2.o ...
12 */
13
14#define _GNU_SOURCE
15#include <elf.h>
16#include <fnmatch.h>
17#include <stdio.h>
18#include <ctype.h>
19#include <string.h>
20#include <limits.h>
21#include <stdbool.h>
22#include <errno.h>
23
24#include <hash.h>
25#include <hashtable.h>
26#include <list.h>
27#include <xalloc.h>
28#include "modpost.h"
29#include "../../include/linux/license.h"
30
31#define MODULE_NS_PREFIX "module:"
32
33static bool module_enabled;
34/* Are we using CONFIG_MODVERSIONS? */
35static bool modversions;
36/* Is CONFIG_MODULE_SRCVERSION_ALL set? */
37static bool all_versions;
38/* Is CONFIG_BASIC_MODVERSIONS set? */
39static bool basic_modversions;
40/* Is CONFIG_EXTENDED_MODVERSIONS set? */
41static bool extended_modversions;
42/* If we are modposting external module set to 1 */
43static bool external_module;
44/* Only warn about unresolved symbols */
45static bool warn_unresolved;
46
47static int sec_mismatch_count;
48static bool sec_mismatch_warn_only = true;
49/* Trim EXPORT_SYMBOLs that are unused by in-tree modules */
50static bool trim_unused_exports;
51
52/* ignore missing files */
53static bool ignore_missing_files;
54/* If set to 1, only warn (instead of error) about missing ns imports */
55static bool allow_missing_ns_imports;
56
57static bool error_occurred;
58
59static bool extra_warn __attribute__((unused));
60
61bool target_is_big_endian;
62bool host_is_big_endian;
63
64/*
65 * Cut off the warnings when there are too many. This typically occurs when
66 * vmlinux is missing. ('make modules' without building vmlinux.)
67 */
68#define MAX_UNRESOLVED_REPORTS 10
69static unsigned int nr_unresolved;
70
71/* In kernel, this size is defined in linux/module.h;
72 * here we use Elf_Addr instead of long for covering cross-compile
73 */
74
75#define MODULE_NAME_LEN (64 - sizeof(Elf_Addr))
76
77void modpost_log(bool is_error, const char *fmt, ...)
78{
79 va_list arglist;
80
81 if (is_error) {
82 fprintf(stderr, "ERROR: ");
83 error_occurred = true;
84 } else {
85 fprintf(stderr, "WARNING: ");
86 }
87
88 fprintf(stderr, "modpost: ");
89
90 va_start(arglist, fmt);
91 vfprintf(stderr, fmt, arglist);
92 va_end(arglist);
93}
94
95static inline bool strends(const char *str, const char *postfix)
96{
97 if (strlen(str) < strlen(postfix))
98 return false;
99
100 return strcmp(str + strlen(str) - strlen(postfix), postfix) == 0;
101}
102
103/**
104 * get_basename - return the last part of a pathname.
105 *
106 * @path: path to extract the filename from.
107 */
108const char *get_basename(const char *path)
109{
110 const char *tail = strrchr(path, '/');
111
112 return tail ? tail + 1 : path;
113}
114
115char *read_text_file(const char *filename)
116{
117 struct stat st;
118 size_t nbytes;
119 int fd;
120 char *buf;
121
122 fd = open(filename, O_RDONLY);
123 if (fd < 0) {
124 perror(filename);
125 exit(1);
126 }
127
128 if (fstat(fd, &st) < 0) {
129 perror(filename);
130 exit(1);
131 }
132
133 buf = xmalloc(st.st_size + 1);
134
135 nbytes = st.st_size;
136
137 while (nbytes) {
138 ssize_t bytes_read;
139
140 bytes_read = read(fd, buf, nbytes);
141 if (bytes_read < 0) {
142 perror(filename);
143 exit(1);
144 }
145
146 nbytes -= bytes_read;
147 }
148 buf[st.st_size] = '\0';
149
150 close(fd);
151
152 return buf;
153}
154
155char *get_line(char **stringp)
156{
157 char *orig = *stringp, *next;
158
159 /* do not return the unwanted extra line at EOF */
160 if (!orig || *orig == '\0')
161 return NULL;
162
163 /* don't use strsep here, it is not available everywhere */
164 next = strchr(orig, '\n');
165 if (next)
166 *next++ = '\0';
167
168 *stringp = next;
169
170 return orig;
171}
172
173/* A list of all modules we processed */
174LIST_HEAD(modules);
175
176static struct module *find_module(const char *filename, const char *modname)
177{
178 struct module *mod;
179
180 list_for_each_entry(mod, &modules, list) {
181 if (!strcmp(mod->dump_file, filename) &&
182 !strcmp(mod->name, modname))
183 return mod;
184 }
185 return NULL;
186}
187
188static struct module *new_module(const char *name, size_t namelen)
189{
190 struct module *mod;
191
192 mod = xmalloc(sizeof(*mod) + namelen + 1);
193 memset(mod, 0, sizeof(*mod));
194
195 INIT_LIST_HEAD(&mod->exported_symbols);
196 INIT_LIST_HEAD(&mod->unresolved_symbols);
197 INIT_LIST_HEAD(&mod->missing_namespaces);
198 INIT_LIST_HEAD(&mod->imported_namespaces);
199 INIT_LIST_HEAD(&mod->aliases);
200
201 memcpy(mod->name, name, namelen);
202 mod->name[namelen] = '\0';
203 mod->is_vmlinux = (strcmp(mod->name, "vmlinux") == 0);
204
205 /*
206 * Set mod->is_gpl_compatible to true by default. If MODULE_LICENSE()
207 * is missing, do not check the use for EXPORT_SYMBOL_GPL() because
208 * modpost will exit with an error anyway.
209 */
210 mod->is_gpl_compatible = true;
211
212 list_add_tail(&mod->list, &modules);
213
214 return mod;
215}
216
217struct symbol {
218 struct hlist_node hnode;/* link to hash table */
219 struct list_head list; /* link to module::exported_symbols or module::unresolved_symbols */
220 struct module *module;
221 char *namespace;
222 unsigned int crc;
223 bool crc_valid;
224 bool weak;
225 bool is_func;
226 bool is_gpl_only; /* exported by EXPORT_SYMBOL_GPL */
227 bool used; /* there exists a user of this symbol */
228 char name[];
229};
230
231static HASHTABLE_DEFINE(symbol_hashtable, 1U << 10);
232
233/**
234 * Allocate a new symbols for use in the hash of exported symbols or
235 * the list of unresolved symbols per module
236 **/
237static struct symbol *alloc_symbol(const char *name)
238{
239 struct symbol *s = xmalloc(sizeof(*s) + strlen(name) + 1);
240
241 memset(s, 0, sizeof(*s));
242 strcpy(s->name, name);
243
244 return s;
245}
246
247static uint8_t get_symbol_flags(const struct symbol *sym)
248{
249 return sym->is_gpl_only ? KSYM_FLAG_GPL_ONLY : 0;
250}
251
252/* For the hash of exported symbols */
253static void hash_add_symbol(struct symbol *sym)
254{
255 hash_add(symbol_hashtable, &sym->hnode, hash_str(sym->name));
256}
257
258static void sym_add_unresolved(const char *name, struct module *mod, bool weak)
259{
260 struct symbol *sym;
261
262 sym = alloc_symbol(name);
263 sym->weak = weak;
264
265 list_add_tail(&sym->list, &mod->unresolved_symbols);
266}
267
268static struct symbol *sym_find_with_module(const char *name, struct module *mod)
269{
270 struct symbol *s;
271
272 /* For our purposes, .foo matches foo. PPC64 needs this. */
273 if (name[0] == '.')
274 name++;
275
276 hash_for_each_possible(symbol_hashtable, s, hnode, hash_str(name)) {
277 if (strcmp(s->name, name) == 0 && (!mod || s->module == mod))
278 return s;
279 }
280 return NULL;
281}
282
283static struct symbol *find_symbol(const char *name)
284{
285 return sym_find_with_module(name, NULL);
286}
287
288struct namespace_list {
289 struct list_head list;
290 char namespace[];
291};
292
293static bool contains_namespace(struct list_head *head, const char *namespace)
294{
295 struct namespace_list *list;
296
297 /*
298 * The default namespace is null string "", which is always implicitly
299 * contained.
300 */
301 if (!namespace[0])
302 return true;
303
304 list_for_each_entry(list, head, list) {
305 if (!strcmp(list->namespace, namespace))
306 return true;
307 }
308
309 return false;
310}
311
312static void add_namespace(struct list_head *head, const char *namespace)
313{
314 struct namespace_list *ns_entry;
315
316 if (!contains_namespace(head, namespace)) {
317 ns_entry = xmalloc(sizeof(*ns_entry) + strlen(namespace) + 1);
318 strcpy(ns_entry->namespace, namespace);
319 list_add_tail(&ns_entry->list, head);
320 }
321}
322
323static void *sym_get_data_by_offset(const struct elf_info *info,
324 unsigned int secindex, unsigned long offset)
325{
326 Elf_Shdr *sechdr = &info->sechdrs[secindex];
327
328 return (void *)info->hdr + sechdr->sh_offset + offset;
329}
330
331void *sym_get_data(const struct elf_info *info, const Elf_Sym *sym)
332{
333 return sym_get_data_by_offset(info, get_secindex(info, sym),
334 sym->st_value);
335}
336
337static const char *sech_name(const struct elf_info *info, Elf_Shdr *sechdr)
338{
339 return sym_get_data_by_offset(info, info->secindex_strings,
340 sechdr->sh_name);
341}
342
343static const char *sec_name(const struct elf_info *info, unsigned int secindex)
344{
345 /*
346 * If sym->st_shndx is a special section index, there is no
347 * corresponding section header.
348 * Return "" if the index is out of range of info->sechdrs[] array.
349 */
350 if (secindex >= info->num_sections)
351 return "";
352
353 return sech_name(info, &info->sechdrs[secindex]);
354}
355
356static struct symbol *sym_add_exported(const char *name, struct module *mod,
357 bool gpl_only, const char *namespace)
358{
359 struct symbol *s = find_symbol(name);
360
361 if (s && (!external_module || s->module->is_vmlinux || s->module == mod)) {
362 error("%s: '%s' exported twice. Previous export was in %s%s\n",
363 mod->name, name, s->module->name,
364 s->module->is_vmlinux ? "" : ".ko");
365 }
366
367 s = alloc_symbol(name);
368 s->module = mod;
369 s->is_gpl_only = gpl_only;
370 s->namespace = xstrdup(namespace);
371 list_add_tail(&s->list, &mod->exported_symbols);
372 hash_add_symbol(s);
373
374 return s;
375}
376
377static void sym_set_crc(struct symbol *sym, unsigned int crc)
378{
379 sym->crc = crc;
380 sym->crc_valid = true;
381}
382
383static void *grab_file(const char *filename, size_t *size)
384{
385 struct stat st;
386 void *map = MAP_FAILED;
387 int fd;
388
389 fd = open(filename, O_RDONLY);
390 if (fd < 0)
391 return NULL;
392 if (fstat(fd, &st))
393 goto failed;
394
395 *size = st.st_size;
396 map = mmap(NULL, *size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
397
398failed:
399 close(fd);
400 if (map == MAP_FAILED)
401 return NULL;
402 return map;
403}
404
405static void release_file(void *file, size_t size)
406{
407 munmap(file, size);
408}
409
410static int parse_elf(struct elf_info *info, const char *filename)
411{
412 unsigned int i;
413 Elf_Ehdr *hdr;
414 Elf_Shdr *sechdrs;
415 Elf_Sym *sym;
416 const char *secstrings;
417 unsigned int symtab_idx = ~0U, symtab_shndx_idx = ~0U;
418
419 hdr = grab_file(filename, &info->size);
420 if (!hdr) {
421 if (ignore_missing_files) {
422 fprintf(stderr, "%s: %s (ignored)\n", filename,
423 strerror(errno));
424 return 0;
425 }
426 perror(filename);
427 exit(1);
428 }
429 info->hdr = hdr;
430 if (info->size < sizeof(*hdr)) {
431 /* file too small, assume this is an empty .o file */
432 return 0;
433 }
434 /* Is this a valid ELF file? */
435 if ((hdr->e_ident[EI_MAG0] != ELFMAG0) ||
436 (hdr->e_ident[EI_MAG1] != ELFMAG1) ||
437 (hdr->e_ident[EI_MAG2] != ELFMAG2) ||
438 (hdr->e_ident[EI_MAG3] != ELFMAG3)) {
439 /* Not an ELF file - silently ignore it */
440 return 0;
441 }
442
443 switch (hdr->e_ident[EI_DATA]) {
444 case ELFDATA2LSB:
445 target_is_big_endian = false;
446 break;
447 case ELFDATA2MSB:
448 target_is_big_endian = true;
449 break;
450 default:
451 fatal("target endian is unknown\n");
452 }
453
454 /* Fix endianness in ELF header */
455 hdr->e_type = TO_NATIVE(hdr->e_type);
456 hdr->e_machine = TO_NATIVE(hdr->e_machine);
457 hdr->e_version = TO_NATIVE(hdr->e_version);
458 hdr->e_entry = TO_NATIVE(hdr->e_entry);
459 hdr->e_phoff = TO_NATIVE(hdr->e_phoff);
460 hdr->e_shoff = TO_NATIVE(hdr->e_shoff);
461 hdr->e_flags = TO_NATIVE(hdr->e_flags);
462 hdr->e_ehsize = TO_NATIVE(hdr->e_ehsize);
463 hdr->e_phentsize = TO_NATIVE(hdr->e_phentsize);
464 hdr->e_phnum = TO_NATIVE(hdr->e_phnum);
465 hdr->e_shentsize = TO_NATIVE(hdr->e_shentsize);
466 hdr->e_shnum = TO_NATIVE(hdr->e_shnum);
467 hdr->e_shstrndx = TO_NATIVE(hdr->e_shstrndx);
468 sechdrs = (void *)hdr + hdr->e_shoff;
469 info->sechdrs = sechdrs;
470
471 /* modpost only works for relocatable objects */
472 if (hdr->e_type != ET_REL)
473 fatal("%s: not relocatable object.", filename);
474
475 /* Check if file offset is correct */
476 if (hdr->e_shoff > info->size)
477 fatal("section header offset=%lu in file '%s' is bigger than filesize=%zu\n",
478 (unsigned long)hdr->e_shoff, filename, info->size);
479
480 if (hdr->e_shnum == SHN_UNDEF) {
481 /*
482 * There are more than 64k sections,
483 * read count from .sh_size.
484 */
485 info->num_sections = TO_NATIVE(sechdrs[0].sh_size);
486 }
487 else {
488 info->num_sections = hdr->e_shnum;
489 }
490 if (hdr->e_shstrndx == SHN_XINDEX) {
491 info->secindex_strings = TO_NATIVE(sechdrs[0].sh_link);
492 }
493 else {
494 info->secindex_strings = hdr->e_shstrndx;
495 }
496
497 /* Fix endianness in section headers */
498 for (i = 0; i < info->num_sections; i++) {
499 sechdrs[i].sh_name = TO_NATIVE(sechdrs[i].sh_name);
500 sechdrs[i].sh_type = TO_NATIVE(sechdrs[i].sh_type);
501 sechdrs[i].sh_flags = TO_NATIVE(sechdrs[i].sh_flags);
502 sechdrs[i].sh_addr = TO_NATIVE(sechdrs[i].sh_addr);
503 sechdrs[i].sh_offset = TO_NATIVE(sechdrs[i].sh_offset);
504 sechdrs[i].sh_size = TO_NATIVE(sechdrs[i].sh_size);
505 sechdrs[i].sh_link = TO_NATIVE(sechdrs[i].sh_link);
506 sechdrs[i].sh_info = TO_NATIVE(sechdrs[i].sh_info);
507 sechdrs[i].sh_addralign = TO_NATIVE(sechdrs[i].sh_addralign);
508 sechdrs[i].sh_entsize = TO_NATIVE(sechdrs[i].sh_entsize);
509 }
510 /* Find symbol table. */
511 secstrings = (void *)hdr + sechdrs[info->secindex_strings].sh_offset;
512 for (i = 1; i < info->num_sections; i++) {
513 const char *secname;
514 int nobits = sechdrs[i].sh_type == SHT_NOBITS;
515
516 if (!nobits && sechdrs[i].sh_offset > info->size)
517 fatal("%s is truncated. sechdrs[i].sh_offset=%lu > sizeof(*hrd)=%zu\n",
518 filename, (unsigned long)sechdrs[i].sh_offset,
519 sizeof(*hdr));
520
521 secname = secstrings + sechdrs[i].sh_name;
522 if (strcmp(secname, ".modinfo") == 0) {
523 if (nobits)
524 fatal("%s has NOBITS .modinfo\n", filename);
525 info->modinfo = (void *)hdr + sechdrs[i].sh_offset;
526 info->modinfo_len = sechdrs[i].sh_size;
527 } else if (!strcmp(secname, ".export_symbol")) {
528 info->export_symbol_secndx = i;
529 } else if (!strcmp(secname, ".no_trim_symbol")) {
530 info->no_trim_symbol = (void *)hdr + sechdrs[i].sh_offset;
531 info->no_trim_symbol_len = sechdrs[i].sh_size;
532 }
533
534 if (sechdrs[i].sh_type == SHT_SYMTAB) {
535 unsigned int sh_link_idx;
536 symtab_idx = i;
537 info->symtab_start = (void *)hdr +
538 sechdrs[i].sh_offset;
539 info->symtab_stop = (void *)hdr +
540 sechdrs[i].sh_offset + sechdrs[i].sh_size;
541 sh_link_idx = sechdrs[i].sh_link;
542 info->strtab = (void *)hdr +
543 sechdrs[sh_link_idx].sh_offset;
544 }
545
546 /* 32bit section no. table? ("more than 64k sections") */
547 if (sechdrs[i].sh_type == SHT_SYMTAB_SHNDX) {
548 symtab_shndx_idx = i;
549 info->symtab_shndx_start = (void *)hdr +
550 sechdrs[i].sh_offset;
551 info->symtab_shndx_stop = (void *)hdr +
552 sechdrs[i].sh_offset + sechdrs[i].sh_size;
553 }
554 }
555 if (!info->symtab_start)
556 fatal("%s has no symtab?\n", filename);
557
558 /* Fix endianness in symbols */
559 for (sym = info->symtab_start; sym < info->symtab_stop; sym++) {
560 sym->st_shndx = TO_NATIVE(sym->st_shndx);
561 sym->st_name = TO_NATIVE(sym->st_name);
562 sym->st_value = TO_NATIVE(sym->st_value);
563 sym->st_size = TO_NATIVE(sym->st_size);
564 }
565
566 if (symtab_shndx_idx != ~0U) {
567 Elf32_Word *p;
568 if (symtab_idx != sechdrs[symtab_shndx_idx].sh_link)
569 fatal("%s: SYMTAB_SHNDX has bad sh_link: %u!=%u\n",
570 filename, sechdrs[symtab_shndx_idx].sh_link,
571 symtab_idx);
572 /* Fix endianness */
573 for (p = info->symtab_shndx_start; p < info->symtab_shndx_stop;
574 p++)
575 *p = TO_NATIVE(*p);
576 }
577
578 symsearch_init(info);
579
580 return 1;
581}
582
583static void parse_elf_finish(struct elf_info *info)
584{
585 symsearch_finish(info);
586 release_file(info->hdr, info->size);
587}
588
589static int ignore_undef_symbol(struct elf_info *info, const char *symname)
590{
591 /* ignore __this_module, it will be resolved shortly */
592 if (strcmp(symname, "__this_module") == 0)
593 return 1;
594 /* ignore global offset table */
595 if (strcmp(symname, "_GLOBAL_OFFSET_TABLE_") == 0)
596 return 1;
597 if (info->hdr->e_machine == EM_PPC)
598 /* Special register function linked on all modules during final link of .ko */
599 if (strstarts(symname, "_restgpr_") ||
600 strstarts(symname, "_savegpr_") ||
601 strstarts(symname, "_rest32gpr_") ||
602 strstarts(symname, "_save32gpr_") ||
603 strstarts(symname, "_restvr_") ||
604 strstarts(symname, "_savevr_"))
605 return 1;
606 if (info->hdr->e_machine == EM_PPC64)
607 /* Special register function linked on all modules during final link of .ko */
608 if (strstarts(symname, "_restgpr0_") ||
609 strstarts(symname, "_savegpr0_") ||
610 strstarts(symname, "_restgpr1_") ||
611 strstarts(symname, "_savegpr1_") ||
612 strstarts(symname, "_restfpr_") ||
613 strstarts(symname, "_savefpr_") ||
614 strstarts(symname, "_restvr_") ||
615 strstarts(symname, "_savevr_") ||
616 strcmp(symname, ".TOC.") == 0)
617 return 1;
618
619 /* ignore linker-created section bounds variables */
620 if (strstarts(symname, "__start_") || strstarts(symname, "__stop_"))
621 return 1;
622
623 /* Do not ignore this symbol */
624 return 0;
625}
626
627static void handle_symbol(struct module *mod, struct elf_info *info,
628 const Elf_Sym *sym, const char *symname)
629{
630 switch (sym->st_shndx) {
631 case SHN_COMMON:
632 if (strstarts(symname, "__gnu_lto_")) {
633 /* Should warn here, but modpost runs before the linker */
634 } else
635 warn("\"%s\" [%s] is COMMON symbol\n", symname, mod->name);
636 break;
637 case SHN_UNDEF:
638 /* undefined symbol */
639 if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL &&
640 ELF_ST_BIND(sym->st_info) != STB_WEAK)
641 break;
642 if (ignore_undef_symbol(info, symname))
643 break;
644 if (info->hdr->e_machine == EM_SPARC ||
645 info->hdr->e_machine == EM_SPARCV9) {
646 /* Ignore register directives. */
647 if (ELF_ST_TYPE(sym->st_info) == STT_SPARC_REGISTER)
648 break;
649 if (symname[0] == '.') {
650 char *munged = xstrdup(symname);
651 munged[0] = '_';
652 munged[1] = toupper(munged[1]);
653 symname = munged;
654 }
655 }
656
657 sym_add_unresolved(symname, mod,
658 ELF_ST_BIND(sym->st_info) == STB_WEAK);
659 break;
660 default:
661 if (strcmp(symname, "init_module") == 0)
662 mod->has_init = true;
663 if (strcmp(symname, "cleanup_module") == 0)
664 mod->has_cleanup = true;
665 break;
666 }
667}
668
669/**
670 * Parse tag=value strings from .modinfo section
671 **/
672static char *next_string(char *string, unsigned long *secsize)
673{
674 /* Skip non-zero chars */
675 while (string[0]) {
676 string++;
677 if ((*secsize)-- <= 1)
678 return NULL;
679 }
680
681 /* Skip any zero padding. */
682 while (!string[0]) {
683 string++;
684 if ((*secsize)-- <= 1)
685 return NULL;
686 }
687 return string;
688}
689
690static char *get_next_modinfo(struct elf_info *info, const char *tag,
691 char *prev)
692{
693 char *p;
694 unsigned int taglen = strlen(tag);
695 char *modinfo = info->modinfo;
696 unsigned long size = info->modinfo_len;
697
698 if (prev) {
699 size -= prev - modinfo;
700 modinfo = next_string(prev, &size);
701 }
702
703 for (p = modinfo; p; p = next_string(p, &size)) {
704 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
705 return p + taglen + 1;
706 }
707 return NULL;
708}
709
710static char *get_modinfo(struct elf_info *info, const char *tag)
711
712{
713 return get_next_modinfo(info, tag, NULL);
714}
715
716static const char *sym_name(struct elf_info *elf, Elf_Sym *sym)
717{
718 return sym ? elf->strtab + sym->st_name : "";
719}
720
721/*
722 * Check whether the 'string' argument matches one of the 'patterns',
723 * an array of shell wildcard patterns (glob).
724 *
725 * Return true is there is a match.
726 */
727static bool match(const char *string, const char *const patterns[])
728{
729 const char *pattern;
730
731 while ((pattern = *patterns++)) {
732 if (!fnmatch(pattern, string, 0))
733 return true;
734 }
735
736 return false;
737}
738
739/* useful to pass patterns to match() directly */
740#define PATTERNS(...) \
741 ({ \
742 static const char *const patterns[] = {__VA_ARGS__, NULL}; \
743 patterns; \
744 })
745
746/* sections that we do not want to do full section mismatch check on */
747static const char *const section_white_list[] =
748{
749 ".comment*",
750 ".debug*",
751 ".zdebug*", /* Compressed debug sections. */
752 ".GCC.command.line", /* record-gcc-switches */
753 ".mdebug*", /* alpha, score, mips etc. */
754 ".pdr", /* alpha, score, mips etc. */
755 ".stab*",
756 ".note*",
757 ".got*",
758 ".toc*",
759 ".xt.prop", /* xtensa */
760 ".xt.lit", /* xtensa */
761 ".arcextmap*", /* arc */
762 ".gnu.linkonce.arcext*", /* arc : modules */
763 ".cmem*", /* EZchip */
764 ".fmt_slot*", /* EZchip */
765 ".gnu.lto*",
766 ".discard.*",
767 ".llvm.call-graph-profile", /* call graph */
768 "__llvm_covfun",
769 "__llvm_covmap",
770 NULL
771};
772
773/*
774 * This is used to find sections missing the SHF_ALLOC flag.
775 * The cause of this is often a section specified in assembler
776 * without "ax" / "aw".
777 */
778static void check_section(const char *modname, struct elf_info *elf,
779 Elf_Shdr *sechdr)
780{
781 const char *sec = sech_name(elf, sechdr);
782
783 if (sechdr->sh_type == SHT_PROGBITS &&
784 !(sechdr->sh_flags & SHF_ALLOC) &&
785 !match(sec, section_white_list)) {
786 warn("%s (%s): unexpected non-allocatable section.\n"
787 "Did you forget to use \"ax\"/\"aw\" in a .S file?\n"
788 "Note that for example <linux/init.h> contains\n"
789 "section definitions for use in .S files.\n\n",
790 modname, sec);
791 }
792}
793
794
795
796#define ALL_INIT_DATA_SECTIONS \
797 ".init.setup", ".init.rodata", ".init.data"
798
799#define ALL_PCI_INIT_SECTIONS \
800 ".pci_fixup_early", ".pci_fixup_header", ".pci_fixup_final", \
801 ".pci_fixup_enable", ".pci_fixup_resume", \
802 ".pci_fixup_resume_early", ".pci_fixup_suspend"
803
804#define ALL_INIT_SECTIONS ".init.*"
805#define ALL_EXIT_SECTIONS ".exit.*"
806
807#define DATA_SECTIONS ".data", ".data.rel"
808#define TEXT_SECTIONS ".text", ".text.*", ".sched.text", \
809 ".kprobes.text", ".cpuidle.text", ".noinstr.text", \
810 ".ltext", ".ltext.*"
811#define OTHER_TEXT_SECTIONS ".ref.text", ".head.text", ".spinlock.text", \
812 ".fixup", ".entry.text", ".exception.text", \
813 ".coldtext", ".softirqentry.text", ".irqentry.text"
814
815#define ALL_TEXT_SECTIONS ".init.text", ".exit.text", \
816 TEXT_SECTIONS, OTHER_TEXT_SECTIONS
817
818enum mismatch {
819 TEXTDATA_TO_ANY_INIT_EXIT,
820 XXXINIT_TO_SOME_INIT,
821 ANY_INIT_TO_ANY_EXIT,
822 ANY_EXIT_TO_ANY_INIT,
823 EXTABLE_TO_NON_TEXT,
824};
825
826/**
827 * Describe how to match sections on different criteria:
828 *
829 * @fromsec: Array of sections to be matched.
830 *
831 * @bad_tosec: Relocations applied to a section in @fromsec to a section in
832 * this array is forbidden (black-list). Can be empty.
833 *
834 * @good_tosec: Relocations applied to a section in @fromsec must be
835 * targeting sections in this array (white-list). Can be empty.
836 *
837 * @mismatch: Type of mismatch.
838 */
839struct sectioncheck {
840 const char *fromsec[20];
841 const char *bad_tosec[20];
842 const char *good_tosec[20];
843 enum mismatch mismatch;
844};
845
846static const struct sectioncheck sectioncheck[] = {
847/* Do not reference init/exit code/data from
848 * normal code and data
849 */
850{
851 .fromsec = { TEXT_SECTIONS, DATA_SECTIONS, NULL },
852 .bad_tosec = { ALL_INIT_SECTIONS, ALL_EXIT_SECTIONS, NULL },
853 .mismatch = TEXTDATA_TO_ANY_INIT_EXIT,
854},
855/* Do not use exit code/data from init code */
856{
857 .fromsec = { ALL_INIT_SECTIONS, NULL },
858 .bad_tosec = { ALL_EXIT_SECTIONS, NULL },
859 .mismatch = ANY_INIT_TO_ANY_EXIT,
860},
861/* Do not use init code/data from exit code */
862{
863 .fromsec = { ALL_EXIT_SECTIONS, NULL },
864 .bad_tosec = { ALL_INIT_SECTIONS, NULL },
865 .mismatch = ANY_EXIT_TO_ANY_INIT,
866},
867{
868 .fromsec = { ALL_PCI_INIT_SECTIONS, NULL },
869 .bad_tosec = { ALL_INIT_SECTIONS, NULL },
870 .mismatch = ANY_INIT_TO_ANY_EXIT,
871},
872{
873 .fromsec = { "__ex_table", NULL },
874 /* If you're adding any new black-listed sections in here, consider
875 * adding a special 'printer' for them in scripts/check_extable.
876 */
877 .bad_tosec = { ".altinstr_replacement", NULL },
878 .good_tosec = {ALL_TEXT_SECTIONS , NULL},
879 .mismatch = EXTABLE_TO_NON_TEXT,
880}
881};
882
883static const struct sectioncheck *section_mismatch(
884 const char *fromsec, const char *tosec)
885{
886 int i;
887
888 /*
889 * The target section could be the SHT_NUL section when we're
890 * handling relocations to un-resolved symbols, trying to match it
891 * doesn't make much sense and causes build failures on parisc
892 * architectures.
893 */
894 if (*tosec == '\0')
895 return NULL;
896
897 for (i = 0; i < ARRAY_SIZE(sectioncheck); i++) {
898 const struct sectioncheck *check = &sectioncheck[i];
899
900 if (match(fromsec, check->fromsec)) {
901 if (check->bad_tosec[0] && match(tosec, check->bad_tosec))
902 return check;
903 if (check->good_tosec[0] && !match(tosec, check->good_tosec))
904 return check;
905 }
906 }
907 return NULL;
908}
909
910/**
911 * Whitelist to allow certain references to pass with no warning.
912 *
913 * Pattern 1:
914 * If a module parameter is declared __initdata and permissions=0
915 * then this is legal despite the warning generated.
916 * We cannot see value of permissions here, so just ignore
917 * this pattern.
918 * The pattern is identified by:
919 * tosec = .init.data
920 * fromsec = .data*
921 * atsym =__param*
922 *
923 * Pattern 1a:
924 * module_param_call() ops can refer to __init set function if permissions=0
925 * The pattern is identified by:
926 * tosec = .init.text
927 * fromsec = .data*
928 * atsym = __param_ops_*
929 *
930 * Pattern 3:
931 * Whitelist all references from .head.text to any init section
932 *
933 * Pattern 4:
934 * Some symbols belong to init section but still it is ok to reference
935 * these from non-init sections as these symbols don't have any memory
936 * allocated for them and symbol address and value are same. So even
937 * if init section is freed, its ok to reference those symbols.
938 * For ex. symbols marking the init section boundaries.
939 * This pattern is identified by
940 * refsymname = __init_begin, _sinittext, _einittext
941 *
942 * Pattern 5:
943 * GCC may optimize static inlines when fed constant arg(s) resulting
944 * in functions like cpumask_empty() -- generating an associated symbol
945 * cpumask_empty.constprop.3 that appears in the audit. If the const that
946 * is passed in comes from __init, like say nmi_ipi_mask, we get a
947 * meaningless section warning. May need to add isra symbols too...
948 * This pattern is identified by
949 * tosec = init section
950 * fromsec = text section
951 * refsymname = *.constprop.*
952 *
953 **/
954static int secref_whitelist(const char *fromsec, const char *fromsym,
955 const char *tosec, const char *tosym)
956{
957 /* Check for pattern 1 */
958 if (match(tosec, PATTERNS(ALL_INIT_DATA_SECTIONS)) &&
959 match(fromsec, PATTERNS(DATA_SECTIONS)) &&
960 strstarts(fromsym, "__param"))
961 return 0;
962
963 /* Check for pattern 1a */
964 if (strcmp(tosec, ".init.text") == 0 &&
965 match(fromsec, PATTERNS(DATA_SECTIONS)) &&
966 strstarts(fromsym, "__param_ops_"))
967 return 0;
968
969 /* symbols in data sections that may refer to any init/exit sections */
970 if (match(fromsec, PATTERNS(DATA_SECTIONS)) &&
971 match(tosec, PATTERNS(ALL_INIT_SECTIONS, ALL_EXIT_SECTIONS)) &&
972 match(fromsym, PATTERNS("*_ops", "*_ops.llvm.*", "*_console")))
973 return 0;
974
975 /* Check for pattern 3 */
976 if (strstarts(fromsec, ".head.text") &&
977 match(tosec, PATTERNS(ALL_INIT_SECTIONS)))
978 return 0;
979
980 /* Check for pattern 4 */
981 if (match(tosym, PATTERNS("__init_begin", "_sinittext", "_einittext")))
982 return 0;
983
984 /* Check for pattern 5 */
985 if (match(fromsec, PATTERNS(ALL_TEXT_SECTIONS)) &&
986 match(tosec, PATTERNS(ALL_INIT_SECTIONS)) &&
987 match(fromsym, PATTERNS("*.constprop.*")))
988 return 0;
989
990 return 1;
991}
992
993static Elf_Sym *find_fromsym(struct elf_info *elf, Elf_Addr addr,
994 unsigned int secndx)
995{
996 return symsearch_find_nearest(elf, addr, secndx, false, ~0);
997}
998
999static Elf_Sym *find_tosym(struct elf_info *elf, Elf_Addr addr, Elf_Sym *sym)
1000{
1001 Elf_Sym *new_sym;
1002
1003 /* If the supplied symbol has a valid name, return it */
1004 if (is_valid_name(elf, sym))
1005 return sym;
1006
1007 /*
1008 * Strive to find a better symbol name, but the resulting name may not
1009 * match the symbol referenced in the original code.
1010 */
1011 new_sym = symsearch_find_nearest(elf, addr, get_secindex(elf, sym),
1012 true, 20);
1013 return new_sym ? new_sym : sym;
1014}
1015
1016static bool is_executable_section(struct elf_info *elf, unsigned int secndx)
1017{
1018 if (secndx >= elf->num_sections)
1019 return false;
1020
1021 return (elf->sechdrs[secndx].sh_flags & SHF_EXECINSTR) != 0;
1022}
1023
1024static void default_mismatch_handler(const char *modname, struct elf_info *elf,
1025 const struct sectioncheck* const mismatch,
1026 Elf_Sym *tsym,
1027 unsigned int fsecndx, const char *fromsec, Elf_Addr faddr,
1028 const char *tosec, Elf_Addr taddr)
1029{
1030 Elf_Sym *from;
1031 const char *tosym;
1032 const char *fromsym;
1033 char taddr_str[16];
1034
1035 from = find_fromsym(elf, faddr, fsecndx);
1036 fromsym = sym_name(elf, from);
1037
1038 tsym = find_tosym(elf, taddr, tsym);
1039 tosym = sym_name(elf, tsym);
1040
1041 /* check whitelist - we may ignore it */
1042 if (!secref_whitelist(fromsec, fromsym, tosec, tosym))
1043 return;
1044
1045 sec_mismatch_count++;
1046
1047 if (!tosym[0])
1048 snprintf(taddr_str, sizeof(taddr_str), "0x%x", (unsigned int)taddr);
1049
1050 /*
1051 * The format for the reference source: <symbol_name>+<offset> or <address>
1052 * The format for the reference destination: <symbol_name> or <address>
1053 */
1054 warn("%s: section mismatch in reference: %s%s0x%x (section: %s) -> %s (section: %s)\n",
1055 modname, fromsym, fromsym[0] ? "+" : "",
1056 (unsigned int)(faddr - (fromsym[0] ? from->st_value : 0)),
1057 fromsec, tosym[0] ? tosym : taddr_str, tosec);
1058
1059 if (mismatch->mismatch == EXTABLE_TO_NON_TEXT) {
1060 if (match(tosec, mismatch->bad_tosec))
1061 fatal("The relocation at %s+0x%lx references\n"
1062 "section \"%s\" which is black-listed.\n"
1063 "Something is seriously wrong and should be fixed.\n"
1064 "You might get more information about where this is\n"
1065 "coming from by using scripts/check_extable.sh %s\n",
1066 fromsec, (long)faddr, tosec, modname);
1067 else if (is_executable_section(elf, get_secindex(elf, tsym)))
1068 warn("The relocation at %s+0x%lx references\n"
1069 "section \"%s\" which is not in the list of\n"
1070 "authorized sections. If you're adding a new section\n"
1071 "and/or if this reference is valid, add \"%s\" to the\n"
1072 "list of authorized sections to jump to on fault.\n"
1073 "This can be achieved by adding \"%s\" to\n"
1074 "OTHER_TEXT_SECTIONS in scripts/mod/modpost.c.\n",
1075 fromsec, (long)faddr, tosec, tosec, tosec);
1076 else
1077 error("%s+0x%lx references non-executable section '%s'\n",
1078 fromsec, (long)faddr, tosec);
1079 }
1080}
1081
1082static void check_export_symbol(struct module *mod, struct elf_info *elf,
1083 Elf_Addr faddr, const char *secname,
1084 Elf_Sym *sym)
1085{
1086 static const char *prefix = "__export_symbol_";
1087 const char *label_name, *name, *data;
1088 Elf_Sym *label;
1089 struct symbol *s;
1090 bool is_gpl;
1091
1092 label = find_fromsym(elf, faddr, elf->export_symbol_secndx);
1093 label_name = sym_name(elf, label);
1094
1095 if (!strstarts(label_name, prefix)) {
1096 error("%s: .export_symbol section contains strange symbol '%s'\n",
1097 mod->name, label_name);
1098 return;
1099 }
1100
1101 if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL &&
1102 ELF_ST_BIND(sym->st_info) != STB_WEAK) {
1103 error("%s: local symbol '%s' was exported\n", mod->name,
1104 label_name + strlen(prefix));
1105 return;
1106 }
1107
1108 name = sym_name(elf, sym);
1109 if (strcmp(label_name + strlen(prefix), name)) {
1110 error("%s: .export_symbol section references '%s', but it does not seem to be an export symbol\n",
1111 mod->name, name);
1112 return;
1113 }
1114
1115 data = sym_get_data(elf, label); /* license */
1116 if (!strcmp(data, "GPL")) {
1117 is_gpl = true;
1118 } else if (!strcmp(data, "")) {
1119 is_gpl = false;
1120 } else {
1121 error("%s: unknown license '%s' was specified for '%s'\n",
1122 mod->name, data, name);
1123 return;
1124 }
1125
1126 data += strlen(data) + 1; /* namespace */
1127 s = sym_add_exported(name, mod, is_gpl, data);
1128
1129 /*
1130 * We need to be aware whether we are exporting a function or
1131 * a data on some architectures.
1132 */
1133 s->is_func = (ELF_ST_TYPE(sym->st_info) == STT_FUNC);
1134
1135 /*
1136 * For parisc64, symbols prefixed $$ from the library have the symbol type
1137 * STT_LOPROC. They should be handled as functions too.
1138 */
1139 if (elf->hdr->e_ident[EI_CLASS] == ELFCLASS64 &&
1140 elf->hdr->e_machine == EM_PARISC &&
1141 ELF_ST_TYPE(sym->st_info) == STT_LOPROC)
1142 s->is_func = true;
1143
1144 if (match(secname, PATTERNS(ALL_INIT_SECTIONS)))
1145 warn("%s: %s: EXPORT_SYMBOL used for init symbol. Remove __init or EXPORT_SYMBOL.\n",
1146 mod->name, name);
1147 else if (match(secname, PATTERNS(ALL_EXIT_SECTIONS)))
1148 warn("%s: %s: EXPORT_SYMBOL used for exit symbol. Remove __exit or EXPORT_SYMBOL.\n",
1149 mod->name, name);
1150}
1151
1152static void check_section_mismatch(struct module *mod, struct elf_info *elf,
1153 Elf_Sym *sym,
1154 unsigned int fsecndx, const char *fromsec,
1155 Elf_Addr faddr, Elf_Addr taddr)
1156{
1157 const char *tosec = sec_name(elf, get_secindex(elf, sym));
1158 const struct sectioncheck *mismatch;
1159
1160 if (module_enabled && elf->export_symbol_secndx == fsecndx) {
1161 check_export_symbol(mod, elf, faddr, tosec, sym);
1162 return;
1163 }
1164
1165 mismatch = section_mismatch(fromsec, tosec);
1166 if (!mismatch)
1167 return;
1168
1169 default_mismatch_handler(mod->name, elf, mismatch, sym,
1170 fsecndx, fromsec, faddr,
1171 tosec, taddr);
1172}
1173
1174static Elf_Addr addend_386_rel(uint32_t *location, unsigned int r_type)
1175{
1176 switch (r_type) {
1177 case R_386_32:
1178 return get_unaligned_native(location);
1179 case R_386_PC32:
1180 return get_unaligned_native(location) + 4;
1181 }
1182
1183 return (Elf_Addr)(-1);
1184}
1185
1186static int32_t sign_extend32(int32_t value, int index)
1187{
1188 uint8_t shift = 31 - index;
1189
1190 return (int32_t)(value << shift) >> shift;
1191}
1192
1193static Elf_Addr addend_arm_rel(void *loc, Elf_Sym *sym, unsigned int r_type)
1194{
1195 uint32_t inst, upper, lower, sign, j1, j2;
1196 int32_t offset;
1197
1198 switch (r_type) {
1199 case R_ARM_ABS32:
1200 case R_ARM_REL32:
1201 inst = get_unaligned_native((uint32_t *)loc);
1202 return inst + sym->st_value;
1203 case R_ARM_MOVW_ABS_NC:
1204 case R_ARM_MOVT_ABS:
1205 inst = get_unaligned_native((uint32_t *)loc);
1206 offset = sign_extend32(((inst & 0xf0000) >> 4) | (inst & 0xfff),
1207 15);
1208 return offset + sym->st_value;
1209 case R_ARM_PC24:
1210 case R_ARM_CALL:
1211 case R_ARM_JUMP24:
1212 inst = get_unaligned_native((uint32_t *)loc);
1213 offset = sign_extend32((inst & 0x00ffffff) << 2, 25);
1214 return offset + sym->st_value + 8;
1215 case R_ARM_THM_MOVW_ABS_NC:
1216 case R_ARM_THM_MOVT_ABS:
1217 upper = get_unaligned_native((uint16_t *)loc);
1218 lower = get_unaligned_native((uint16_t *)loc + 1);
1219 offset = sign_extend32(((upper & 0x000f) << 12) |
1220 ((upper & 0x0400) << 1) |
1221 ((lower & 0x7000) >> 4) |
1222 (lower & 0x00ff),
1223 15);
1224 return offset + sym->st_value;
1225 case R_ARM_THM_JUMP19:
1226 /*
1227 * Encoding T3:
1228 * S = upper[10]
1229 * imm6 = upper[5:0]
1230 * J1 = lower[13]
1231 * J2 = lower[11]
1232 * imm11 = lower[10:0]
1233 * imm32 = SignExtend(S:J2:J1:imm6:imm11:'0')
1234 */
1235 upper = get_unaligned_native((uint16_t *)loc);
1236 lower = get_unaligned_native((uint16_t *)loc + 1);
1237
1238 sign = (upper >> 10) & 1;
1239 j1 = (lower >> 13) & 1;
1240 j2 = (lower >> 11) & 1;
1241 offset = sign_extend32((sign << 20) | (j2 << 19) | (j1 << 18) |
1242 ((upper & 0x03f) << 12) |
1243 ((lower & 0x07ff) << 1),
1244 20);
1245 return offset + sym->st_value + 4;
1246 case R_ARM_THM_PC22:
1247 case R_ARM_THM_JUMP24:
1248 /*
1249 * Encoding T4:
1250 * S = upper[10]
1251 * imm10 = upper[9:0]
1252 * J1 = lower[13]
1253 * J2 = lower[11]
1254 * imm11 = lower[10:0]
1255 * I1 = NOT(J1 XOR S)
1256 * I2 = NOT(J2 XOR S)
1257 * imm32 = SignExtend(S:I1:I2:imm10:imm11:'0')
1258 */
1259 upper = get_unaligned_native((uint16_t *)loc);
1260 lower = get_unaligned_native((uint16_t *)loc + 1);
1261
1262 sign = (upper >> 10) & 1;
1263 j1 = (lower >> 13) & 1;
1264 j2 = (lower >> 11) & 1;
1265 offset = sign_extend32((sign << 24) |
1266 ((~(j1 ^ sign) & 1) << 23) |
1267 ((~(j2 ^ sign) & 1) << 22) |
1268 ((upper & 0x03ff) << 12) |
1269 ((lower & 0x07ff) << 1),
1270 24);
1271 return offset + sym->st_value + 4;
1272 }
1273
1274 return (Elf_Addr)(-1);
1275}
1276
1277static Elf_Addr addend_mips_rel(uint32_t *location, unsigned int r_type)
1278{
1279 uint32_t inst;
1280
1281 inst = get_unaligned_native(location);
1282 switch (r_type) {
1283 case R_MIPS_LO16:
1284 return inst & 0xffff;
1285 case R_MIPS_26:
1286 return (inst & 0x03ffffff) << 2;
1287 case R_MIPS_32:
1288 return inst;
1289 }
1290 return (Elf_Addr)(-1);
1291}
1292
1293#ifndef EM_RISCV
1294#define EM_RISCV 243
1295#endif
1296
1297#ifndef R_RISCV_SUB32
1298#define R_RISCV_SUB32 39
1299#endif
1300
1301#ifndef EM_LOONGARCH
1302#define EM_LOONGARCH 258
1303#endif
1304
1305#ifndef R_LARCH_SUB32
1306#define R_LARCH_SUB32 55
1307#endif
1308
1309#ifndef R_LARCH_RELAX
1310#define R_LARCH_RELAX 100
1311#endif
1312
1313#ifndef R_LARCH_ALIGN
1314#define R_LARCH_ALIGN 102
1315#endif
1316
1317static void get_rel_type_and_sym(struct elf_info *elf, uint64_t r_info,
1318 unsigned int *r_type, unsigned int *r_sym)
1319{
1320 typedef struct {
1321 Elf64_Word r_sym; /* Symbol index */
1322 unsigned char r_ssym; /* Special symbol for 2nd relocation */
1323 unsigned char r_type3; /* 3rd relocation type */
1324 unsigned char r_type2; /* 2nd relocation type */
1325 unsigned char r_type; /* 1st relocation type */
1326 } Elf64_Mips_R_Info;
1327
1328 bool is_64bit = (elf->hdr->e_ident[EI_CLASS] == ELFCLASS64);
1329
1330 if (elf->hdr->e_machine == EM_MIPS && is_64bit) {
1331 Elf64_Mips_R_Info *mips64_r_info = (void *)&r_info;
1332
1333 *r_type = mips64_r_info->r_type;
1334 *r_sym = TO_NATIVE(mips64_r_info->r_sym);
1335 return;
1336 }
1337
1338 if (is_64bit)
1339 r_info = TO_NATIVE((Elf64_Xword)r_info);
1340 else
1341 r_info = TO_NATIVE((Elf32_Word)r_info);
1342
1343 *r_type = ELF_R_TYPE(r_info);
1344 *r_sym = ELF_R_SYM(r_info);
1345}
1346
1347static void section_rela(struct module *mod, struct elf_info *elf,
1348 unsigned int fsecndx, const char *fromsec,
1349 const Elf_Rela *start, const Elf_Rela *stop)
1350{
1351 const Elf_Rela *rela;
1352
1353 for (rela = start; rela < stop; rela++) {
1354 Elf_Sym *tsym;
1355 Elf_Addr taddr, r_offset;
1356 unsigned int r_type, r_sym;
1357
1358 r_offset = TO_NATIVE(rela->r_offset);
1359 get_rel_type_and_sym(elf, rela->r_info, &r_type, &r_sym);
1360
1361 tsym = elf->symtab_start + r_sym;
1362 taddr = tsym->st_value + TO_NATIVE(rela->r_addend);
1363
1364 switch (elf->hdr->e_machine) {
1365 case EM_RISCV:
1366 if (!strcmp("__ex_table", fromsec) &&
1367 r_type == R_RISCV_SUB32)
1368 continue;
1369 break;
1370 case EM_LOONGARCH:
1371 switch (r_type) {
1372 case R_LARCH_SUB32:
1373 if (!strcmp("__ex_table", fromsec))
1374 continue;
1375 break;
1376 case R_LARCH_RELAX:
1377 case R_LARCH_ALIGN:
1378 /* These relocs do not refer to symbols */
1379 continue;
1380 }
1381 break;
1382 }
1383
1384 check_section_mismatch(mod, elf, tsym,
1385 fsecndx, fromsec, r_offset, taddr);
1386 }
1387}
1388
1389static void section_rel(struct module *mod, struct elf_info *elf,
1390 unsigned int fsecndx, const char *fromsec,
1391 const Elf_Rel *start, const Elf_Rel *stop)
1392{
1393 const Elf_Rel *rel;
1394
1395 for (rel = start; rel < stop; rel++) {
1396 Elf_Sym *tsym;
1397 Elf_Addr taddr, r_offset;
1398 unsigned int r_type, r_sym;
1399 void *loc;
1400
1401 r_offset = TO_NATIVE(rel->r_offset);
1402 get_rel_type_and_sym(elf, rel->r_info, &r_type, &r_sym);
1403
1404 loc = sym_get_data_by_offset(elf, fsecndx, r_offset);
1405 tsym = elf->symtab_start + r_sym;
1406
1407 switch (elf->hdr->e_machine) {
1408 case EM_386:
1409 taddr = addend_386_rel(loc, r_type);
1410 break;
1411 case EM_ARM:
1412 taddr = addend_arm_rel(loc, tsym, r_type);
1413 break;
1414 case EM_MIPS:
1415 taddr = addend_mips_rel(loc, r_type);
1416 break;
1417 default:
1418 fatal("Please add code to calculate addend for this architecture\n");
1419 }
1420
1421 check_section_mismatch(mod, elf, tsym,
1422 fsecndx, fromsec, r_offset, taddr);
1423 }
1424}
1425
1426/**
1427 * A module includes a number of sections that are discarded
1428 * either when loaded or when used as built-in.
1429 * For loaded modules all functions marked __init and all data
1430 * marked __initdata will be discarded when the module has been initialized.
1431 * Likewise for modules used built-in the sections marked __exit
1432 * are discarded because __exit marked function are supposed to be called
1433 * only when a module is unloaded which never happens for built-in modules.
1434 * The check_sec_ref() function traverses all relocation records
1435 * to find all references to a section that reference a section that will
1436 * be discarded and warns about it.
1437 **/
1438static void check_sec_ref(struct module *mod, struct elf_info *elf)
1439{
1440 int i;
1441
1442 /* Walk through all sections */
1443 for (i = 0; i < elf->num_sections; i++) {
1444 Elf_Shdr *sechdr = &elf->sechdrs[i];
1445
1446 check_section(mod->name, elf, sechdr);
1447 /* We want to process only relocation sections and not .init */
1448 if (sechdr->sh_type == SHT_REL || sechdr->sh_type == SHT_RELA) {
1449 /* section to which the relocation applies */
1450 unsigned int secndx = sechdr->sh_info;
1451 const char *secname = sec_name(elf, secndx);
1452 const void *start, *stop;
1453
1454 /* If the section is known good, skip it */
1455 if (match(secname, section_white_list))
1456 continue;
1457
1458 start = sym_get_data_by_offset(elf, i, 0);
1459 stop = start + sechdr->sh_size;
1460
1461 if (sechdr->sh_type == SHT_RELA)
1462 section_rela(mod, elf, secndx, secname,
1463 start, stop);
1464 else
1465 section_rel(mod, elf, secndx, secname,
1466 start, stop);
1467 }
1468 }
1469}
1470
1471static char *remove_dot(char *s)
1472{
1473 size_t n = strcspn(s, ".");
1474
1475 if (n && s[n]) {
1476 size_t m = strspn(s + n + 1, "0123456789");
1477 if (m && (s[n + m + 1] == '.' || s[n + m + 1] == 0))
1478 s[n] = 0;
1479 }
1480 return s;
1481}
1482
1483/*
1484 * The CRCs are recorded in .*.cmd files in the form of:
1485 * #SYMVER <name> <crc>
1486 */
1487static void extract_crcs_for_object(const char *object, struct module *mod)
1488{
1489 char cmd_file[PATH_MAX];
1490 char *buf, *p;
1491 const char *base;
1492 int dirlen, baselen_without_suffix, ret;
1493
1494 base = get_basename(object);
1495 dirlen = base - object;
1496
1497 baselen_without_suffix = strlen(object) - dirlen - strlen(".o");
1498
1499 /*
1500 * When CONFIG_LTO_CLANG_THIN_DIST=y, the ELF is *.thinlto-native.o
1501 * but the symbol CRCs are recorded in *.o.cmd file.
1502 */
1503 if (strends(object, ".thinlto-native.o"))
1504 baselen_without_suffix -= strlen(".thinlto-native");
1505
1506 ret = snprintf(cmd_file, sizeof(cmd_file), "%.*s.%.*s.o.cmd",
1507 dirlen, object, baselen_without_suffix, base);
1508 if (ret >= sizeof(cmd_file)) {
1509 error("%s: too long path was truncated\n", cmd_file);
1510 return;
1511 }
1512
1513 buf = read_text_file(cmd_file);
1514 p = buf;
1515
1516 while ((p = strstr(p, "\n#SYMVER "))) {
1517 char *name;
1518 size_t namelen;
1519 unsigned int crc;
1520 struct symbol *sym;
1521
1522 name = p + strlen("\n#SYMVER ");
1523
1524 p = strchr(name, ' ');
1525 if (!p)
1526 break;
1527
1528 namelen = p - name;
1529 p++;
1530
1531 if (!isdigit(*p))
1532 continue; /* skip this line */
1533
1534 crc = strtoul(p, &p, 0);
1535 if (*p != '\n')
1536 continue; /* skip this line */
1537
1538 name[namelen] = '\0';
1539
1540 /*
1541 * sym_find_with_module() may return NULL here.
1542 * It typically occurs when CONFIG_TRIM_UNUSED_KSYMS=y.
1543 * Since commit e1327a127703, genksyms calculates CRCs of all
1544 * symbols, including trimmed ones. Ignore orphan CRCs.
1545 */
1546 sym = sym_find_with_module(name, mod);
1547 if (sym)
1548 sym_set_crc(sym, crc);
1549 }
1550
1551 free(buf);
1552}
1553
1554/*
1555 * The symbol versions (CRC) are recorded in the .*.cmd files.
1556 * Parse them to retrieve CRCs for the current module.
1557 */
1558static void mod_set_crcs(struct module *mod)
1559{
1560 char objlist[PATH_MAX];
1561 char *buf, *p, *obj;
1562 int ret;
1563
1564 if (mod->is_vmlinux) {
1565 strcpy(objlist, ".vmlinux.objs");
1566 } else {
1567 /* objects for a module are listed in the *.mod file. */
1568 ret = snprintf(objlist, sizeof(objlist), "%s.mod", mod->name);
1569 if (ret >= sizeof(objlist)) {
1570 error("%s: too long path was truncated\n", objlist);
1571 return;
1572 }
1573 }
1574
1575 buf = read_text_file(objlist);
1576 p = buf;
1577
1578 while ((obj = strsep(&p, "\n")) && obj[0])
1579 extract_crcs_for_object(obj, mod);
1580
1581 free(buf);
1582}
1583
1584static void read_symbols(const char *modname)
1585{
1586 const char *symname;
1587 char *version;
1588 char *license;
1589 char *namespace;
1590 struct module *mod;
1591 struct elf_info info = { };
1592 Elf_Sym *sym;
1593
1594 if (!parse_elf(&info, modname))
1595 return;
1596
1597 if (!strends(modname, ".o")) {
1598 error("%s: filename must be suffixed with .o\n", modname);
1599 return;
1600 }
1601
1602 /* strip trailing .o */
1603 mod = new_module(modname, strlen(modname) - strlen(".o"));
1604
1605 /* save .no_trim_symbol section for later use */
1606 if (info.no_trim_symbol_len) {
1607 mod->no_trim_symbol = xmalloc(info.no_trim_symbol_len);
1608 memcpy(mod->no_trim_symbol, info.no_trim_symbol,
1609 info.no_trim_symbol_len);
1610 mod->no_trim_symbol_len = info.no_trim_symbol_len;
1611 }
1612
1613 if (!mod->is_vmlinux) {
1614 license = get_modinfo(&info, "license");
1615 if (!license)
1616 error("missing MODULE_LICENSE() in %s\n", modname);
1617 while (license) {
1618 if (!license_is_gpl_compatible(license)) {
1619 mod->is_gpl_compatible = false;
1620 break;
1621 }
1622 license = get_next_modinfo(&info, "license", license);
1623 }
1624
1625 for (namespace = get_modinfo(&info, "import_ns");
1626 namespace;
1627 namespace = get_next_modinfo(&info, "import_ns", namespace)) {
1628 if (strstarts(namespace, MODULE_NS_PREFIX))
1629 error("%s: explicitly importing namespace \"%s\" is not allowed.\n",
1630 mod->name, namespace);
1631
1632 add_namespace(&mod->imported_namespaces, namespace);
1633 }
1634
1635 if (!get_modinfo(&info, "description"))
1636 warn("missing MODULE_DESCRIPTION() in %s\n", modname);
1637 }
1638
1639 for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
1640 symname = remove_dot(info.strtab + sym->st_name);
1641
1642 handle_symbol(mod, &info, sym, symname);
1643 handle_moddevtable(mod, &info, sym, symname);
1644 }
1645
1646 check_sec_ref(mod, &info);
1647
1648 if (!mod->is_vmlinux) {
1649 version = get_modinfo(&info, "version");
1650 if (version || all_versions)
1651 get_src_version(mod->name, mod->srcversion,
1652 sizeof(mod->srcversion) - 1);
1653 }
1654
1655 parse_elf_finish(&info);
1656
1657 if (modversions) {
1658 /*
1659 * Our trick to get versioning for module struct etc. - it's
1660 * never passed as an argument to an exported function, so
1661 * the automatic versioning doesn't pick it up, but it's really
1662 * important anyhow.
1663 */
1664 sym_add_unresolved("module_layout", mod, false);
1665
1666 mod_set_crcs(mod);
1667 }
1668}
1669
1670static void read_symbols_from_files(const char *filename)
1671{
1672 FILE *in = stdin;
1673 char fname[PATH_MAX];
1674
1675 in = fopen(filename, "r");
1676 if (!in)
1677 fatal("Can't open filenames file %s: %m", filename);
1678
1679 while (fgets(fname, PATH_MAX, in) != NULL) {
1680 if (strends(fname, "\n"))
1681 fname[strlen(fname)-1] = '\0';
1682 read_symbols(fname);
1683 }
1684
1685 fclose(in);
1686}
1687
1688#define SZ 500
1689
1690/* We first write the generated file into memory using the
1691 * following helper, then compare to the file on disk and
1692 * only update the later if anything changed */
1693
1694void __attribute__((format(printf, 2, 3))) buf_printf(struct buffer *buf,
1695 const char *fmt, ...)
1696{
1697 char tmp[SZ];
1698 int len;
1699 va_list ap;
1700
1701 va_start(ap, fmt);
1702 len = vsnprintf(tmp, SZ, fmt, ap);
1703 va_end(ap);
1704
1705 if (len < 0) {
1706 perror("vsnprintf failed");
1707 exit(1);
1708 }
1709 if (len >= SZ)
1710 fatal("buf_printf output truncated for string %s: %d bytes needed, %d available\n",
1711 tmp, len + 1, SZ);
1712
1713 buf_write(buf, tmp, len);
1714}
1715
1716void buf_write(struct buffer *buf, const char *s, int len)
1717{
1718 if (buf->size - buf->pos < len) {
1719 buf->size += len + SZ;
1720 buf->p = xrealloc(buf->p, buf->size);
1721 }
1722 strncpy(buf->p + buf->pos, s, len);
1723 buf->pos += len;
1724}
1725
1726/**
1727 * verify_module_namespace() - does @modname have access to this symbol's @namespace
1728 * @namespace: export symbol namespace
1729 * @modname: module name
1730 *
1731 * If @namespace is prefixed with "module:" to indicate it is a module namespace
1732 * then test if @modname matches any of the comma separated patterns.
1733 *
1734 * The patterns only support tail-glob.
1735 */
1736static bool verify_module_namespace(const char *namespace, const char *modname)
1737{
1738 size_t len, modlen = strlen(modname);
1739 const char *prefix = "module:";
1740 const char *sep;
1741 bool glob;
1742
1743 if (!strstarts(namespace, prefix))
1744 return false;
1745
1746 for (namespace += strlen(prefix); *namespace; namespace = sep) {
1747 sep = strchrnul(namespace, ',');
1748 len = sep - namespace;
1749
1750 glob = false;
1751 if (sep[-1] == '*') {
1752 len--;
1753 glob = true;
1754 }
1755
1756 if (*sep)
1757 sep++;
1758
1759 if (strncmp(namespace, modname, len) == 0 && (glob || len == modlen))
1760 return true;
1761 }
1762
1763 return false;
1764}
1765
1766static void check_exports(struct module *mod)
1767{
1768 struct symbol *s, *exp;
1769
1770 list_for_each_entry(s, &mod->unresolved_symbols, list) {
1771 const char *basename;
1772 exp = find_symbol(s->name);
1773 if (!exp) {
1774 if (!s->weak && nr_unresolved++ < MAX_UNRESOLVED_REPORTS)
1775 modpost_log(!warn_unresolved,
1776 "\"%s\" [%s.ko] undefined!\n",
1777 s->name, mod->name);
1778 continue;
1779 }
1780 if (exp->module == mod) {
1781 error("\"%s\" [%s.ko] was exported without definition\n",
1782 s->name, mod->name);
1783 continue;
1784 }
1785
1786 exp->used = true;
1787 s->module = exp->module;
1788 s->crc_valid = exp->crc_valid;
1789 s->crc = exp->crc;
1790
1791 basename = get_basename(mod->name);
1792
1793 if (!verify_module_namespace(exp->namespace, basename) &&
1794 !contains_namespace(&mod->imported_namespaces, exp->namespace)) {
1795 modpost_log(!allow_missing_ns_imports,
1796 "module %s uses symbol %s from namespace %s, but does not import it.\n",
1797 basename, exp->name, exp->namespace);
1798 add_namespace(&mod->missing_namespaces, exp->namespace);
1799 }
1800
1801 if (!mod->is_gpl_compatible && exp->is_gpl_only)
1802 error("GPL-incompatible module %s.ko uses GPL-only symbol '%s'\n",
1803 basename, exp->name);
1804 }
1805}
1806
1807static void handle_white_list_exports(const char *white_list)
1808{
1809 char *buf, *p, *name;
1810
1811 buf = read_text_file(white_list);
1812 p = buf;
1813
1814 while ((name = strsep(&p, "\n"))) {
1815 struct symbol *sym = find_symbol(name);
1816
1817 if (sym)
1818 sym->used = true;
1819 }
1820
1821 free(buf);
1822}
1823
1824/*
1825 * Keep symbols recorded in the .no_trim_symbol section. This is necessary to
1826 * prevent CONFIG_TRIM_UNUSED_KSYMS from dropping EXPORT_SYMBOL because
1827 * symbol_get() relies on the symbol being present in the ksymtab for lookups.
1828 */
1829static void keep_no_trim_symbols(struct module *mod)
1830{
1831 unsigned long size = mod->no_trim_symbol_len;
1832
1833 for (char *s = mod->no_trim_symbol; s; s = next_string(s , &size)) {
1834 struct symbol *sym;
1835
1836 /*
1837 * If find_symbol() returns NULL, this symbol is not provided
1838 * by any module, and symbol_get() will fail.
1839 */
1840 sym = find_symbol(s);
1841 if (sym)
1842 sym->used = true;
1843 }
1844}
1845
1846static void check_modname_len(struct module *mod)
1847{
1848 const char *mod_name;
1849
1850 mod_name = get_basename(mod->name);
1851
1852 if (strlen(mod_name) >= MODULE_NAME_LEN)
1853 error("module name is too long [%s.ko]\n", mod->name);
1854}
1855
1856/**
1857 * Header for the generated file
1858 **/
1859static void add_header(struct buffer *b, struct module *mod)
1860{
1861 buf_printf(b, "#include <linux/module.h>\n");
1862 buf_printf(b, "#include <linux/export-internal.h>\n");
1863 buf_printf(b, "#include <linux/compiler.h>\n");
1864 buf_printf(b, "\n");
1865 buf_printf(b, "MODULE_INFO(name, KBUILD_MODNAME);\n");
1866 buf_printf(b, "\n");
1867 buf_printf(b, "__visible struct module __this_module\n");
1868 buf_printf(b, "__section(\".gnu.linkonce.this_module\") = {\n");
1869 buf_printf(b, "\t.name = KBUILD_MODNAME,\n");
1870 if (mod->has_init)
1871 buf_printf(b, "\t.init = init_module,\n");
1872 if (mod->has_cleanup)
1873 buf_printf(b, "#ifdef CONFIG_MODULE_UNLOAD\n"
1874 "\t.exit = cleanup_module,\n"
1875 "#endif\n");
1876 buf_printf(b, "\t.arch = MODULE_ARCH_INIT,\n");
1877 buf_printf(b, "};\n");
1878
1879 if (!external_module)
1880 buf_printf(b, "\nMODULE_INFO(intree, \"Y\");\n");
1881
1882 if (strstarts(mod->name, "drivers/staging"))
1883 buf_printf(b, "\nMODULE_INFO(staging, \"Y\");\n");
1884
1885 if (strstarts(mod->name, "tools/testing"))
1886 buf_printf(b, "\nMODULE_INFO(test, \"Y\");\n");
1887}
1888
1889static void add_exported_symbols(struct buffer *buf, struct module *mod)
1890{
1891 struct symbol *sym;
1892
1893 /* generate struct for exported symbols */
1894 buf_printf(buf, "\n");
1895 list_for_each_entry(sym, &mod->exported_symbols, list) {
1896 if (trim_unused_exports && !sym->used)
1897 continue;
1898
1899 buf_printf(buf, "KSYMTAB_%s(%s, \"%s\");\n",
1900 sym->is_func ? "FUNC" : "DATA", sym->name,
1901 sym->namespace);
1902
1903 buf_printf(buf, "SYMBOL_FLAGS(%s, 0x%02x);\n",
1904 sym->name, get_symbol_flags(sym));
1905 }
1906
1907 if (!modversions)
1908 return;
1909
1910 /* record CRCs for exported symbols */
1911 buf_printf(buf, "\n");
1912 list_for_each_entry(sym, &mod->exported_symbols, list) {
1913 if (trim_unused_exports && !sym->used)
1914 continue;
1915
1916 if (!sym->crc_valid)
1917 warn("EXPORT symbol \"%s\" [%s%s] version generation failed, symbol will not be versioned.\n"
1918 "Is \"%s\" prototyped in <asm/asm-prototypes.h>?\n",
1919 sym->name, mod->name, mod->is_vmlinux ? "" : ".ko",
1920 sym->name);
1921
1922 buf_printf(buf, "SYMBOL_CRC(%s, 0x%08x);\n",
1923 sym->name, sym->crc);
1924 }
1925}
1926
1927/**
1928 * Record CRCs for unresolved symbols, supporting long names
1929 */
1930static void add_extended_versions(struct buffer *b, struct module *mod)
1931{
1932 struct symbol *s;
1933
1934 if (!extended_modversions)
1935 return;
1936
1937 buf_printf(b, "\n");
1938 buf_printf(b, "static const u32 ____version_ext_crcs[]\n");
1939 buf_printf(b, "__used __section(\"__version_ext_crcs\") = {\n");
1940 list_for_each_entry(s, &mod->unresolved_symbols, list) {
1941 if (!s->module)
1942 continue;
1943 if (!s->crc_valid) {
1944 warn("\"%s\" [%s.ko] has no CRC!\n",
1945 s->name, mod->name);
1946 continue;
1947 }
1948 buf_printf(b, "\t0x%08x,\n", s->crc);
1949 }
1950 buf_printf(b, "};\n");
1951
1952 buf_printf(b, "static const char ____version_ext_names[]\n");
1953 buf_printf(b, "__used __section(\"__version_ext_names\") =\n");
1954 list_for_each_entry(s, &mod->unresolved_symbols, list) {
1955 if (!s->module)
1956 continue;
1957 if (!s->crc_valid)
1958 /*
1959 * We already warned on this when producing the crc
1960 * table.
1961 * We need to skip its name too, as the indexes in
1962 * both tables need to align.
1963 */
1964 continue;
1965 buf_printf(b, "\t\"%s\\0\"\n", s->name);
1966 }
1967 buf_printf(b, ";\n");
1968}
1969
1970/**
1971 * Record CRCs for unresolved symbols
1972 **/
1973static void add_versions(struct buffer *b, struct module *mod)
1974{
1975 struct symbol *s;
1976
1977 if (!basic_modversions)
1978 return;
1979
1980 buf_printf(b, "\n");
1981 buf_printf(b, "static const struct modversion_info ____versions[]\n");
1982 buf_printf(b, "__used __section(\"__versions\") = {\n");
1983
1984 list_for_each_entry(s, &mod->unresolved_symbols, list) {
1985 if (!s->module)
1986 continue;
1987 if (!s->crc_valid) {
1988 warn("\"%s\" [%s.ko] has no CRC!\n",
1989 s->name, mod->name);
1990 continue;
1991 }
1992 if (strlen(s->name) >= MODULE_NAME_LEN) {
1993 if (extended_modversions) {
1994 /* this symbol will only be in the extended info */
1995 continue;
1996 } else {
1997 error("too long symbol \"%s\" [%s.ko]\n",
1998 s->name, mod->name);
1999 break;
2000 }
2001 }
2002 buf_printf(b, "\t{ 0x%08x, \"%s\" },\n",
2003 s->crc, s->name);
2004 }
2005
2006 buf_printf(b, "};\n");
2007}
2008
2009static void add_depends(struct buffer *b, struct module *mod)
2010{
2011 struct symbol *s;
2012 int first = 1;
2013
2014 /* Clear ->seen flag of modules that own symbols needed by this. */
2015 list_for_each_entry(s, &mod->unresolved_symbols, list) {
2016 if (s->module)
2017 s->module->seen = s->module->is_vmlinux;
2018 }
2019
2020 buf_printf(b, "\n");
2021 buf_printf(b, "MODULE_INFO(depends, \"");
2022 list_for_each_entry(s, &mod->unresolved_symbols, list) {
2023 const char *p;
2024 if (!s->module)
2025 continue;
2026
2027 if (s->module->seen)
2028 continue;
2029
2030 s->module->seen = true;
2031 p = get_basename(s->module->name);
2032 buf_printf(b, "%s%s", first ? "" : ",", p);
2033 first = 0;
2034 }
2035 buf_printf(b, "\");\n");
2036}
2037
2038static void add_srcversion(struct buffer *b, struct module *mod)
2039{
2040 if (mod->srcversion[0]) {
2041 buf_printf(b, "\n");
2042 buf_printf(b, "MODULE_INFO(srcversion, \"%s\");\n",
2043 mod->srcversion);
2044 }
2045}
2046
2047static void write_buf(struct buffer *b, const char *fname)
2048{
2049 FILE *file;
2050
2051 if (error_occurred)
2052 return;
2053
2054 file = fopen(fname, "w");
2055 if (!file) {
2056 perror(fname);
2057 exit(1);
2058 }
2059 if (fwrite(b->p, 1, b->pos, file) != b->pos) {
2060 perror(fname);
2061 exit(1);
2062 }
2063 if (fclose(file) != 0) {
2064 perror(fname);
2065 exit(1);
2066 }
2067}
2068
2069static void write_if_changed(struct buffer *b, const char *fname)
2070{
2071 char *tmp;
2072 FILE *file;
2073 struct stat st;
2074
2075 file = fopen(fname, "r");
2076 if (!file)
2077 goto write;
2078
2079 if (fstat(fileno(file), &st) < 0)
2080 goto close_write;
2081
2082 if (st.st_size != b->pos)
2083 goto close_write;
2084
2085 tmp = xmalloc(b->pos);
2086 if (fread(tmp, 1, b->pos, file) != b->pos)
2087 goto free_write;
2088
2089 if (memcmp(tmp, b->p, b->pos) != 0)
2090 goto free_write;
2091
2092 free(tmp);
2093 fclose(file);
2094 return;
2095
2096 free_write:
2097 free(tmp);
2098 close_write:
2099 fclose(file);
2100 write:
2101 write_buf(b, fname);
2102}
2103
2104static void write_vmlinux_export_c_file(struct module *mod)
2105{
2106 struct buffer buf = { };
2107 struct module_alias *alias, *next;
2108
2109 buf_printf(&buf,
2110 "#include <linux/export-internal.h>\n");
2111
2112 add_exported_symbols(&buf, mod);
2113
2114 buf_printf(&buf,
2115 "#include <linux/module.h>\n"
2116 "#undef __MODULE_INFO_PREFIX\n"
2117 "#define __MODULE_INFO_PREFIX\n");
2118
2119 list_for_each_entry_safe(alias, next, &mod->aliases, node) {
2120 buf_printf(&buf, "MODULE_INFO(%s.alias, \"%s\");\n",
2121 alias->builtin_modname, alias->str);
2122 list_del(&alias->node);
2123 free(alias->builtin_modname);
2124 free(alias);
2125 }
2126
2127 write_if_changed(&buf, ".vmlinux.export.c");
2128 free(buf.p);
2129}
2130
2131/* do sanity checks, and generate *.mod.c file */
2132static void write_mod_c_file(struct module *mod)
2133{
2134 struct buffer buf = { };
2135 struct module_alias *alias, *next;
2136 char fname[PATH_MAX];
2137 int ret;
2138
2139 add_header(&buf, mod);
2140 add_exported_symbols(&buf, mod);
2141 add_versions(&buf, mod);
2142 add_extended_versions(&buf, mod);
2143 add_depends(&buf, mod);
2144
2145 buf_printf(&buf, "\n");
2146 list_for_each_entry_safe(alias, next, &mod->aliases, node) {
2147 buf_printf(&buf, "MODULE_ALIAS(\"%s\");\n", alias->str);
2148 list_del(&alias->node);
2149 free(alias);
2150 }
2151
2152 add_srcversion(&buf, mod);
2153
2154 ret = snprintf(fname, sizeof(fname), "%s.mod.c", mod->name);
2155 if (ret >= sizeof(fname)) {
2156 error("%s: too long path was truncated\n", fname);
2157 goto free;
2158 }
2159
2160 write_if_changed(&buf, fname);
2161
2162free:
2163 free(buf.p);
2164}
2165
2166/* parse Module.symvers file. line format:
2167 * 0x12345678<tab>symbol<tab>module<tab>export<tab>namespace
2168 **/
2169static void read_dump(const char *fname)
2170{
2171 char *buf, *pos, *line;
2172
2173 buf = read_text_file(fname);
2174 if (!buf)
2175 /* No symbol versions, silently ignore */
2176 return;
2177
2178 pos = buf;
2179
2180 while ((line = get_line(&pos))) {
2181 char *symname, *namespace, *modname, *d, *export;
2182 unsigned int crc;
2183 struct module *mod;
2184 struct symbol *s;
2185 bool gpl_only;
2186
2187 if (!(symname = strchr(line, '\t')))
2188 goto fail;
2189 *symname++ = '\0';
2190 if (!(modname = strchr(symname, '\t')))
2191 goto fail;
2192 *modname++ = '\0';
2193 if (!(export = strchr(modname, '\t')))
2194 goto fail;
2195 *export++ = '\0';
2196 if (!(namespace = strchr(export, '\t')))
2197 goto fail;
2198 *namespace++ = '\0';
2199
2200 crc = strtoul(line, &d, 16);
2201 if (*symname == '\0' || *modname == '\0' || *d != '\0')
2202 goto fail;
2203
2204 if (!strcmp(export, "EXPORT_SYMBOL_GPL")) {
2205 gpl_only = true;
2206 } else if (!strcmp(export, "EXPORT_SYMBOL")) {
2207 gpl_only = false;
2208 } else {
2209 error("%s: unknown license %s. skip", symname, export);
2210 continue;
2211 }
2212
2213 mod = find_module(fname, modname);
2214 if (!mod) {
2215 mod = new_module(modname, strlen(modname));
2216 mod->dump_file = fname;
2217 }
2218 s = sym_add_exported(symname, mod, gpl_only, namespace);
2219 sym_set_crc(s, crc);
2220 }
2221 free(buf);
2222 return;
2223fail:
2224 free(buf);
2225 fatal("parse error in symbol dump file\n");
2226}
2227
2228static void write_dump(const char *fname)
2229{
2230 struct buffer buf = { };
2231 struct module *mod;
2232 struct symbol *sym;
2233
2234 list_for_each_entry(mod, &modules, list) {
2235 if (mod->dump_file)
2236 continue;
2237 list_for_each_entry(sym, &mod->exported_symbols, list) {
2238 if (trim_unused_exports && !sym->used)
2239 continue;
2240
2241 buf_printf(&buf, "0x%08x\t%s\t%s\tEXPORT_SYMBOL%s\t%s\n",
2242 sym->crc, sym->name, mod->name,
2243 sym->is_gpl_only ? "_GPL" : "",
2244 sym->namespace);
2245 }
2246 }
2247 write_buf(&buf, fname);
2248 free(buf.p);
2249}
2250
2251static void write_namespace_deps_files(const char *fname)
2252{
2253 struct module *mod;
2254 struct namespace_list *ns;
2255 struct buffer ns_deps_buf = {};
2256
2257 list_for_each_entry(mod, &modules, list) {
2258
2259 if (mod->dump_file || list_empty(&mod->missing_namespaces))
2260 continue;
2261
2262 buf_printf(&ns_deps_buf, "%s.ko:", mod->name);
2263
2264 list_for_each_entry(ns, &mod->missing_namespaces, list)
2265 buf_printf(&ns_deps_buf, " %s", ns->namespace);
2266
2267 buf_printf(&ns_deps_buf, "\n");
2268 }
2269
2270 write_if_changed(&ns_deps_buf, fname);
2271 free(ns_deps_buf.p);
2272}
2273
2274struct dump_list {
2275 struct list_head list;
2276 const char *file;
2277};
2278
2279static void check_host_endian(void)
2280{
2281 static const union {
2282 short s;
2283 char c[2];
2284 } endian_test = { .c = {0x01, 0x02} };
2285
2286 switch (endian_test.s) {
2287 case 0x0102:
2288 host_is_big_endian = true;
2289 break;
2290 case 0x0201:
2291 host_is_big_endian = false;
2292 break;
2293 default:
2294 fatal("Unknown host endian\n");
2295 }
2296}
2297
2298int main(int argc, char **argv)
2299{
2300 struct module *mod;
2301 char *missing_namespace_deps = NULL;
2302 char *unused_exports_white_list = NULL;
2303 char *dump_write = NULL, *files_source = NULL;
2304 int opt;
2305 LIST_HEAD(dump_lists);
2306 struct dump_list *dl, *dl2;
2307
2308 while ((opt = getopt(argc, argv, "ei:MmnT:to:au:WwENd:xb")) != -1) {
2309 switch (opt) {
2310 case 'e':
2311 external_module = true;
2312 break;
2313 case 'i':
2314 dl = xmalloc(sizeof(*dl));
2315 dl->file = optarg;
2316 list_add_tail(&dl->list, &dump_lists);
2317 break;
2318 case 'M':
2319 module_enabled = true;
2320 break;
2321 case 'm':
2322 modversions = true;
2323 break;
2324 case 'n':
2325 ignore_missing_files = true;
2326 break;
2327 case 'o':
2328 dump_write = optarg;
2329 break;
2330 case 'a':
2331 all_versions = true;
2332 break;
2333 case 'T':
2334 files_source = optarg;
2335 break;
2336 case 't':
2337 trim_unused_exports = true;
2338 break;
2339 case 'u':
2340 unused_exports_white_list = optarg;
2341 break;
2342 case 'W':
2343 extra_warn = true;
2344 break;
2345 case 'w':
2346 warn_unresolved = true;
2347 break;
2348 case 'E':
2349 sec_mismatch_warn_only = false;
2350 break;
2351 case 'N':
2352 allow_missing_ns_imports = true;
2353 break;
2354 case 'd':
2355 missing_namespace_deps = optarg;
2356 break;
2357 case 'b':
2358 basic_modversions = true;
2359 break;
2360 case 'x':
2361 extended_modversions = true;
2362 break;
2363 default:
2364 exit(1);
2365 }
2366 }
2367
2368 check_host_endian();
2369
2370 list_for_each_entry_safe(dl, dl2, &dump_lists, list) {
2371 read_dump(dl->file);
2372 list_del(&dl->list);
2373 free(dl);
2374 }
2375
2376 while (optind < argc)
2377 read_symbols(argv[optind++]);
2378
2379 if (files_source)
2380 read_symbols_from_files(files_source);
2381
2382 list_for_each_entry(mod, &modules, list) {
2383 keep_no_trim_symbols(mod);
2384
2385 if (mod->dump_file || mod->is_vmlinux)
2386 continue;
2387
2388 check_modname_len(mod);
2389 check_exports(mod);
2390 }
2391
2392 if (unused_exports_white_list)
2393 handle_white_list_exports(unused_exports_white_list);
2394
2395 list_for_each_entry(mod, &modules, list) {
2396 if (mod->dump_file)
2397 continue;
2398
2399 if (mod->is_vmlinux)
2400 write_vmlinux_export_c_file(mod);
2401 else
2402 write_mod_c_file(mod);
2403 }
2404
2405 if (missing_namespace_deps)
2406 write_namespace_deps_files(missing_namespace_deps);
2407
2408 if (dump_write)
2409 write_dump(dump_write);
2410 if (sec_mismatch_count && !sec_mismatch_warn_only)
2411 error("Section mismatches detected.\n"
2412 "Set CONFIG_SECTION_MISMATCH_WARN_ONLY=y to allow them.\n");
2413
2414 if (nr_unresolved > MAX_UNRESOLVED_REPORTS)
2415 warn("suppressed %u unresolved symbol warnings because there were too many)\n",
2416 nr_unresolved - MAX_UNRESOLVED_REPORTS);
2417
2418 return error_occurred ? 1 : 0;
2419}