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