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