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