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