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