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_flags & SHF_ALLOC) &&
906 !match(sec, section_white_list)) {
907 warn("%s (%s): unexpected non-allocatable section.\n"
908 "Did you forget to use \"ax\"/\"aw\" in a .S file?\n"
909 "Note that for example <linux/init.h> contains\n"
910 "section definitions for use in .S files.\n\n",
911 modname, sec);
912 }
913 }
914
915
916
917 #define ALL_INIT_DATA_SECTIONS \
918 ".init.setup", ".init.rodata", ".meminit.rodata", \
919 ".init.data", ".meminit.data"
920 #define ALL_EXIT_DATA_SECTIONS \
921 ".exit.data", ".memexit.data"
922
923 #define ALL_INIT_TEXT_SECTIONS \
924 ".init.text", ".meminit.text"
925 #define ALL_EXIT_TEXT_SECTIONS \
926 ".exit.text", ".memexit.text"
927
928 #define ALL_PCI_INIT_SECTIONS \
929 ".pci_fixup_early", ".pci_fixup_header", ".pci_fixup_final", \
930 ".pci_fixup_enable", ".pci_fixup_resume", \
931 ".pci_fixup_resume_early", ".pci_fixup_suspend"
932
933 #define ALL_XXXINIT_SECTIONS MEM_INIT_SECTIONS
934 #define ALL_XXXEXIT_SECTIONS MEM_EXIT_SECTIONS
935
936 #define ALL_INIT_SECTIONS INIT_SECTIONS, ALL_XXXINIT_SECTIONS
937 #define ALL_EXIT_SECTIONS EXIT_SECTIONS, ALL_XXXEXIT_SECTIONS
938
939 #define DATA_SECTIONS ".data", ".data.rel"
940 #define TEXT_SECTIONS ".text", ".text.unlikely", ".sched.text", \
941 ".kprobes.text", ".cpuidle.text", ".noinstr.text"
942 #define OTHER_TEXT_SECTIONS ".ref.text", ".head.text", ".spinlock.text", \
943 ".fixup", ".entry.text", ".exception.text", ".text.*", \
944 ".coldtext", ".softirqentry.text"
945
946 #define INIT_SECTIONS ".init.*"
947 #define MEM_INIT_SECTIONS ".meminit.*"
948
949 #define EXIT_SECTIONS ".exit.*"
950 #define MEM_EXIT_SECTIONS ".memexit.*"
951
952 #define ALL_TEXT_SECTIONS ALL_INIT_TEXT_SECTIONS, ALL_EXIT_TEXT_SECTIONS, \
953 TEXT_SECTIONS, OTHER_TEXT_SECTIONS
954
955 /* init data sections */
956 static const char *const init_data_sections[] =
957 { ALL_INIT_DATA_SECTIONS, NULL };
958
959 /* all init sections */
960 static const char *const init_sections[] = { ALL_INIT_SECTIONS, NULL };
961
962 /* All init and exit sections (code + data) */
963 static const char *const init_exit_sections[] =
964 {ALL_INIT_SECTIONS, ALL_EXIT_SECTIONS, NULL };
965
966 /* all text sections */
967 static const char *const text_sections[] = { ALL_TEXT_SECTIONS, NULL };
968
969 /* data section */
970 static const char *const data_sections[] = { DATA_SECTIONS, NULL };
971
972
973 /* symbols in .data that may refer to init/exit sections */
974 #define DEFAULT_SYMBOL_WHITE_LIST \
975 "*driver", \
976 "*_template", /* scsi uses *_template a lot */ \
977 "*_timer", /* arm uses ops structures named _timer a lot */ \
978 "*_sht", /* scsi also used *_sht to some extent */ \
979 "*_ops", \
980 "*_probe", \
981 "*_probe_one", \
982 "*_console"
983
984 static const char *const head_sections[] = { ".head.text*", NULL };
985 static const char *const linker_symbols[] =
986 { "__init_begin", "_sinittext", "_einittext", NULL };
987 static const char *const optim_symbols[] = { "*.constprop.*", NULL };
988
989 enum mismatch {
990 TEXT_TO_ANY_INIT,
991 DATA_TO_ANY_INIT,
992 TEXT_TO_ANY_EXIT,
993 DATA_TO_ANY_EXIT,
994 XXXINIT_TO_SOME_INIT,
995 XXXEXIT_TO_SOME_EXIT,
996 ANY_INIT_TO_ANY_EXIT,
997 ANY_EXIT_TO_ANY_INIT,
998 EXPORT_TO_INIT_EXIT,
999 EXTABLE_TO_NON_TEXT,
1000 };
1001
1002 /**
1003 * Describe how to match sections on different criteria:
1004 *
1005 * @fromsec: Array of sections to be matched.
1006 *
1007 * @bad_tosec: Relocations applied to a section in @fromsec to a section in
1008 * this array is forbidden (black-list). Can be empty.
1009 *
1010 * @good_tosec: Relocations applied to a section in @fromsec must be
1011 * targeting sections in this array (white-list). Can be empty.
1012 *
1013 * @mismatch: Type of mismatch.
1014 *
1015 * @symbol_white_list: Do not match a relocation to a symbol in this list
1016 * even if it is targeting a section in @bad_to_sec.
1017 *
1018 * @handler: Specific handler to call when a match is found. If NULL,
1019 * default_mismatch_handler() will be called.
1020 *
1021 */
1022 struct sectioncheck {
1023 const char *fromsec[20];
1024 const char *bad_tosec[20];
1025 const char *good_tosec[20];
1026 enum mismatch mismatch;
1027 const char *symbol_white_list[20];
1028 void (*handler)(const char *modname, struct elf_info *elf,
1029 const struct sectioncheck* const mismatch,
1030 Elf_Rela *r, Elf_Sym *sym, const char *fromsec);
1031
1032 };
1033
1034 static void extable_mismatch_handler(const char *modname, struct elf_info *elf,
1035 const struct sectioncheck* const mismatch,
1036 Elf_Rela *r, Elf_Sym *sym,
1037 const char *fromsec);
1038
1039 static const struct sectioncheck sectioncheck[] = {
1040 /* Do not reference init/exit code/data from
1041 * normal code and data
1042 */
1043 {
1044 .fromsec = { TEXT_SECTIONS, NULL },
1045 .bad_tosec = { ALL_INIT_SECTIONS, NULL },
1046 .mismatch = TEXT_TO_ANY_INIT,
1047 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1048 },
1049 {
1050 .fromsec = { DATA_SECTIONS, NULL },
1051 .bad_tosec = { ALL_XXXINIT_SECTIONS, NULL },
1052 .mismatch = DATA_TO_ANY_INIT,
1053 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1054 },
1055 {
1056 .fromsec = { DATA_SECTIONS, NULL },
1057 .bad_tosec = { INIT_SECTIONS, NULL },
1058 .mismatch = DATA_TO_ANY_INIT,
1059 .symbol_white_list = {
1060 "*_template", "*_timer", "*_sht", "*_ops",
1061 "*_probe", "*_probe_one", "*_console", NULL
1062 },
1063 },
1064 {
1065 .fromsec = { TEXT_SECTIONS, NULL },
1066 .bad_tosec = { ALL_EXIT_SECTIONS, NULL },
1067 .mismatch = TEXT_TO_ANY_EXIT,
1068 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1069 },
1070 {
1071 .fromsec = { DATA_SECTIONS, NULL },
1072 .bad_tosec = { ALL_EXIT_SECTIONS, NULL },
1073 .mismatch = DATA_TO_ANY_EXIT,
1074 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1075 },
1076 /* Do not reference init code/data from meminit code/data */
1077 {
1078 .fromsec = { ALL_XXXINIT_SECTIONS, NULL },
1079 .bad_tosec = { INIT_SECTIONS, NULL },
1080 .mismatch = XXXINIT_TO_SOME_INIT,
1081 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1082 },
1083 /* Do not reference exit code/data from memexit code/data */
1084 {
1085 .fromsec = { ALL_XXXEXIT_SECTIONS, NULL },
1086 .bad_tosec = { EXIT_SECTIONS, NULL },
1087 .mismatch = XXXEXIT_TO_SOME_EXIT,
1088 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1089 },
1090 /* Do not use exit code/data from init code */
1091 {
1092 .fromsec = { ALL_INIT_SECTIONS, NULL },
1093 .bad_tosec = { ALL_EXIT_SECTIONS, NULL },
1094 .mismatch = ANY_INIT_TO_ANY_EXIT,
1095 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1096 },
1097 /* Do not use init code/data from exit code */
1098 {
1099 .fromsec = { ALL_EXIT_SECTIONS, NULL },
1100 .bad_tosec = { ALL_INIT_SECTIONS, NULL },
1101 .mismatch = ANY_EXIT_TO_ANY_INIT,
1102 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1103 },
1104 {
1105 .fromsec = { ALL_PCI_INIT_SECTIONS, NULL },
1106 .bad_tosec = { INIT_SECTIONS, NULL },
1107 .mismatch = ANY_INIT_TO_ANY_EXIT,
1108 .symbol_white_list = { NULL },
1109 },
1110 /* Do not export init/exit functions or data */
1111 {
1112 .fromsec = { "___ksymtab*", NULL },
1113 .bad_tosec = { INIT_SECTIONS, EXIT_SECTIONS, NULL },
1114 .mismatch = EXPORT_TO_INIT_EXIT,
1115 .symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1116 },
1117 {
1118 .fromsec = { "__ex_table", NULL },
1119 /* If you're adding any new black-listed sections in here, consider
1120 * adding a special 'printer' for them in scripts/check_extable.
1121 */
1122 .bad_tosec = { ".altinstr_replacement", NULL },
1123 .good_tosec = {ALL_TEXT_SECTIONS , NULL},
1124 .mismatch = EXTABLE_TO_NON_TEXT,
1125 .handler = extable_mismatch_handler,
1126 }
1127 };
1128
section_mismatch(const char * fromsec,const char * tosec)1129 static const struct sectioncheck *section_mismatch(
1130 const char *fromsec, const char *tosec)
1131 {
1132 int i;
1133 int elems = sizeof(sectioncheck) / sizeof(struct sectioncheck);
1134 const struct sectioncheck *check = §ioncheck[0];
1135
1136 /*
1137 * The target section could be the SHT_NUL section when we're
1138 * handling relocations to un-resolved symbols, trying to match it
1139 * doesn't make much sense and causes build failures on parisc
1140 * architectures.
1141 */
1142 if (*tosec == '\0')
1143 return NULL;
1144
1145 for (i = 0; i < elems; i++) {
1146 if (match(fromsec, check->fromsec)) {
1147 if (check->bad_tosec[0] && match(tosec, check->bad_tosec))
1148 return check;
1149 if (check->good_tosec[0] && !match(tosec, check->good_tosec))
1150 return check;
1151 }
1152 check++;
1153 }
1154 return NULL;
1155 }
1156
1157 /**
1158 * Whitelist to allow certain references to pass with no warning.
1159 *
1160 * Pattern 1:
1161 * If a module parameter is declared __initdata and permissions=0
1162 * then this is legal despite the warning generated.
1163 * We cannot see value of permissions here, so just ignore
1164 * this pattern.
1165 * The pattern is identified by:
1166 * tosec = .init.data
1167 * fromsec = .data*
1168 * atsym =__param*
1169 *
1170 * Pattern 1a:
1171 * module_param_call() ops can refer to __init set function if permissions=0
1172 * The pattern is identified by:
1173 * tosec = .init.text
1174 * fromsec = .data*
1175 * atsym = __param_ops_*
1176 *
1177 * Pattern 2:
1178 * Many drivers utilise a *driver container with references to
1179 * add, remove, probe functions etc.
1180 * the pattern is identified by:
1181 * tosec = init or exit section
1182 * fromsec = data section
1183 * atsym = *driver, *_template, *_sht, *_ops, *_probe,
1184 * *probe_one, *_console, *_timer
1185 *
1186 * Pattern 3:
1187 * Whitelist all references from .head.text to any init section
1188 *
1189 * Pattern 4:
1190 * Some symbols belong to init section but still it is ok to reference
1191 * these from non-init sections as these symbols don't have any memory
1192 * allocated for them and symbol address and value are same. So even
1193 * if init section is freed, its ok to reference those symbols.
1194 * For ex. symbols marking the init section boundaries.
1195 * This pattern is identified by
1196 * refsymname = __init_begin, _sinittext, _einittext
1197 *
1198 * Pattern 5:
1199 * GCC may optimize static inlines when fed constant arg(s) resulting
1200 * in functions like cpumask_empty() -- generating an associated symbol
1201 * cpumask_empty.constprop.3 that appears in the audit. If the const that
1202 * is passed in comes from __init, like say nmi_ipi_mask, we get a
1203 * meaningless section warning. May need to add isra symbols too...
1204 * This pattern is identified by
1205 * tosec = init section
1206 * fromsec = text section
1207 * refsymname = *.constprop.*
1208 *
1209 * Pattern 6:
1210 * Hide section mismatch warnings for ELF local symbols. The goal
1211 * is to eliminate false positive modpost warnings caused by
1212 * compiler-generated ELF local symbol names such as ".LANCHOR1".
1213 * Autogenerated symbol names bypass modpost's "Pattern 2"
1214 * whitelisting, which relies on pattern-matching against symbol
1215 * names to work. (One situation where gcc can autogenerate ELF
1216 * local symbols is when "-fsection-anchors" is used.)
1217 **/
secref_whitelist(const struct sectioncheck * mismatch,const char * fromsec,const char * fromsym,const char * tosec,const char * tosym)1218 static int secref_whitelist(const struct sectioncheck *mismatch,
1219 const char *fromsec, const char *fromsym,
1220 const char *tosec, const char *tosym)
1221 {
1222 /* Check for pattern 1 */
1223 if (match(tosec, init_data_sections) &&
1224 match(fromsec, data_sections) &&
1225 strstarts(fromsym, "__param"))
1226 return 0;
1227
1228 /* Check for pattern 1a */
1229 if (strcmp(tosec, ".init.text") == 0 &&
1230 match(fromsec, data_sections) &&
1231 strstarts(fromsym, "__param_ops_"))
1232 return 0;
1233
1234 /* Check for pattern 2 */
1235 if (match(tosec, init_exit_sections) &&
1236 match(fromsec, data_sections) &&
1237 match(fromsym, mismatch->symbol_white_list))
1238 return 0;
1239
1240 /* Check for pattern 3 */
1241 if (match(fromsec, head_sections) &&
1242 match(tosec, init_sections))
1243 return 0;
1244
1245 /* Check for pattern 4 */
1246 if (match(tosym, linker_symbols))
1247 return 0;
1248
1249 /* Check for pattern 5 */
1250 if (match(fromsec, text_sections) &&
1251 match(tosec, init_sections) &&
1252 match(fromsym, optim_symbols))
1253 return 0;
1254
1255 /* Check for pattern 6 */
1256 if (strstarts(fromsym, ".L"))
1257 return 0;
1258
1259 return 1;
1260 }
1261
is_arm_mapping_symbol(const char * str)1262 static inline int is_arm_mapping_symbol(const char *str)
1263 {
1264 return str[0] == '$' &&
1265 (str[1] == 'a' || str[1] == 'd' || str[1] == 't' || str[1] == 'x')
1266 && (str[2] == '\0' || str[2] == '.');
1267 }
1268
1269 /*
1270 * If there's no name there, ignore it; likewise, ignore it if it's
1271 * one of the magic symbols emitted used by current ARM tools.
1272 *
1273 * Otherwise if find_symbols_between() returns those symbols, they'll
1274 * fail the whitelist tests and cause lots of false alarms ... fixable
1275 * only by merging __exit and __init sections into __text, bloating
1276 * the kernel (which is especially evil on embedded platforms).
1277 */
is_valid_name(struct elf_info * elf,Elf_Sym * sym)1278 static inline int is_valid_name(struct elf_info *elf, Elf_Sym *sym)
1279 {
1280 const char *name = elf->strtab + sym->st_name;
1281
1282 if (!name || !strlen(name))
1283 return 0;
1284 return !is_arm_mapping_symbol(name);
1285 }
1286
1287 /**
1288 * Find symbol based on relocation record info.
1289 * In some cases the symbol supplied is a valid symbol so
1290 * return refsym. If st_name != 0 we assume this is a valid symbol.
1291 * In other cases the symbol needs to be looked up in the symbol table
1292 * based on section and address.
1293 * **/
find_elf_symbol(struct elf_info * elf,Elf64_Sword addr,Elf_Sym * relsym)1294 static Elf_Sym *find_elf_symbol(struct elf_info *elf, Elf64_Sword addr,
1295 Elf_Sym *relsym)
1296 {
1297 Elf_Sym *sym;
1298 Elf_Sym *near = NULL;
1299 Elf64_Sword distance = 20;
1300 Elf64_Sword d;
1301 unsigned int relsym_secindex;
1302
1303 if (relsym->st_name != 0)
1304 return relsym;
1305
1306 /*
1307 * Strive to find a better symbol name, but the resulting name may not
1308 * match the symbol referenced in the original code.
1309 */
1310 relsym_secindex = get_secindex(elf, relsym);
1311 for (sym = elf->symtab_start; sym < elf->symtab_stop; sym++) {
1312 if (get_secindex(elf, sym) != relsym_secindex)
1313 continue;
1314 if (ELF_ST_TYPE(sym->st_info) == STT_SECTION)
1315 continue;
1316 if (!is_valid_name(elf, sym))
1317 continue;
1318 if (sym->st_value == addr)
1319 return sym;
1320 /* Find a symbol nearby - addr are maybe negative */
1321 d = sym->st_value - addr;
1322 if (d < 0)
1323 d = addr - sym->st_value;
1324 if (d < distance) {
1325 distance = d;
1326 near = sym;
1327 }
1328 }
1329 /* We need a close match */
1330 if (distance < 20)
1331 return near;
1332 else
1333 return NULL;
1334 }
1335
1336 /*
1337 * Find symbols before or equal addr and after addr - in the section sec.
1338 * If we find two symbols with equal offset prefer one with a valid name.
1339 * The ELF format may have a better way to detect what type of symbol
1340 * it is, but this works for now.
1341 **/
find_elf_symbol2(struct elf_info * elf,Elf_Addr addr,const char * sec)1342 static Elf_Sym *find_elf_symbol2(struct elf_info *elf, Elf_Addr addr,
1343 const char *sec)
1344 {
1345 Elf_Sym *sym;
1346 Elf_Sym *near = NULL;
1347 Elf_Addr distance = ~0;
1348
1349 for (sym = elf->symtab_start; sym < elf->symtab_stop; sym++) {
1350 const char *symsec;
1351
1352 if (is_shndx_special(sym->st_shndx))
1353 continue;
1354 symsec = sec_name(elf, get_secindex(elf, sym));
1355 if (strcmp(symsec, sec) != 0)
1356 continue;
1357 if (!is_valid_name(elf, sym))
1358 continue;
1359 if (sym->st_value <= addr) {
1360 if ((addr - sym->st_value) < distance) {
1361 distance = addr - sym->st_value;
1362 near = sym;
1363 } else if ((addr - sym->st_value) == distance) {
1364 near = sym;
1365 }
1366 }
1367 }
1368 return near;
1369 }
1370
1371 /*
1372 * Convert a section name to the function/data attribute
1373 * .init.text => __init
1374 * .memexitconst => __memconst
1375 * etc.
1376 *
1377 * The memory of returned value has been allocated on a heap. The user of this
1378 * method should free it after usage.
1379 */
sec2annotation(const char * s)1380 static char *sec2annotation(const char *s)
1381 {
1382 if (match(s, init_exit_sections)) {
1383 char *p = NOFAIL(malloc(20));
1384 char *r = p;
1385
1386 *p++ = '_';
1387 *p++ = '_';
1388 if (*s == '.')
1389 s++;
1390 while (*s && *s != '.')
1391 *p++ = *s++;
1392 *p = '\0';
1393 if (*s == '.')
1394 s++;
1395 if (strstr(s, "rodata") != NULL)
1396 strcat(p, "const ");
1397 else if (strstr(s, "data") != NULL)
1398 strcat(p, "data ");
1399 else
1400 strcat(p, " ");
1401 return r;
1402 } else {
1403 return NOFAIL(strdup(""));
1404 }
1405 }
1406
is_function(Elf_Sym * sym)1407 static int is_function(Elf_Sym *sym)
1408 {
1409 if (sym)
1410 return ELF_ST_TYPE(sym->st_info) == STT_FUNC;
1411 else
1412 return -1;
1413 }
1414
print_section_list(const char * const list[20])1415 static void print_section_list(const char * const list[20])
1416 {
1417 const char *const *s = list;
1418
1419 while (*s) {
1420 fprintf(stderr, "%s", *s);
1421 s++;
1422 if (*s)
1423 fprintf(stderr, ", ");
1424 }
1425 fprintf(stderr, "\n");
1426 }
1427
get_pretty_name(int is_func,const char ** name,const char ** name_p)1428 static inline void get_pretty_name(int is_func, const char** name, const char** name_p)
1429 {
1430 switch (is_func) {
1431 case 0: *name = "variable"; *name_p = ""; break;
1432 case 1: *name = "function"; *name_p = "()"; break;
1433 default: *name = "(unknown reference)"; *name_p = ""; break;
1434 }
1435 }
1436
1437 /*
1438 * Print a warning about a section mismatch.
1439 * Try to find symbols near it so user can find it.
1440 * Check whitelist before warning - it may be a false positive.
1441 */
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)1442 static void report_sec_mismatch(const char *modname,
1443 const struct sectioncheck *mismatch,
1444 const char *fromsec,
1445 unsigned long long fromaddr,
1446 const char *fromsym,
1447 int from_is_func,
1448 const char *tosec, const char *tosym,
1449 int to_is_func)
1450 {
1451 const char *from, *from_p;
1452 const char *to, *to_p;
1453 char *prl_from;
1454 char *prl_to;
1455
1456 sec_mismatch_count++;
1457
1458 get_pretty_name(from_is_func, &from, &from_p);
1459 get_pretty_name(to_is_func, &to, &to_p);
1460
1461 warn("%s(%s+0x%llx): Section mismatch in reference from the %s %s%s "
1462 "to the %s %s:%s%s\n",
1463 modname, fromsec, fromaddr, from, fromsym, from_p, to, tosec,
1464 tosym, to_p);
1465
1466 switch (mismatch->mismatch) {
1467 case TEXT_TO_ANY_INIT:
1468 prl_from = sec2annotation(fromsec);
1469 prl_to = sec2annotation(tosec);
1470 fprintf(stderr,
1471 "The function %s%s() references\n"
1472 "the %s %s%s%s.\n"
1473 "This is often because %s lacks a %s\n"
1474 "annotation or the annotation of %s is wrong.\n",
1475 prl_from, fromsym,
1476 to, prl_to, tosym, to_p,
1477 fromsym, prl_to, tosym);
1478 free(prl_from);
1479 free(prl_to);
1480 break;
1481 case DATA_TO_ANY_INIT: {
1482 prl_to = sec2annotation(tosec);
1483 fprintf(stderr,
1484 "The variable %s references\n"
1485 "the %s %s%s%s\n"
1486 "If the reference is valid then annotate the\n"
1487 "variable with __init* or __refdata (see linux/init.h) "
1488 "or name the variable:\n",
1489 fromsym, to, prl_to, tosym, to_p);
1490 print_section_list(mismatch->symbol_white_list);
1491 free(prl_to);
1492 break;
1493 }
1494 case TEXT_TO_ANY_EXIT:
1495 prl_to = sec2annotation(tosec);
1496 fprintf(stderr,
1497 "The function %s() references a %s in an exit section.\n"
1498 "Often the %s %s%s has valid usage outside the exit section\n"
1499 "and the fix is to remove the %sannotation of %s.\n",
1500 fromsym, to, to, tosym, to_p, prl_to, tosym);
1501 free(prl_to);
1502 break;
1503 case DATA_TO_ANY_EXIT: {
1504 prl_to = sec2annotation(tosec);
1505 fprintf(stderr,
1506 "The variable %s references\n"
1507 "the %s %s%s%s\n"
1508 "If the reference is valid then annotate the\n"
1509 "variable with __exit* (see linux/init.h) or "
1510 "name the variable:\n",
1511 fromsym, to, prl_to, tosym, to_p);
1512 print_section_list(mismatch->symbol_white_list);
1513 free(prl_to);
1514 break;
1515 }
1516 case XXXINIT_TO_SOME_INIT:
1517 case XXXEXIT_TO_SOME_EXIT:
1518 prl_from = sec2annotation(fromsec);
1519 prl_to = sec2annotation(tosec);
1520 fprintf(stderr,
1521 "The %s %s%s%s references\n"
1522 "a %s %s%s%s.\n"
1523 "If %s is only used by %s then\n"
1524 "annotate %s with a matching annotation.\n",
1525 from, prl_from, fromsym, from_p,
1526 to, prl_to, tosym, to_p,
1527 tosym, fromsym, tosym);
1528 free(prl_from);
1529 free(prl_to);
1530 break;
1531 case ANY_INIT_TO_ANY_EXIT:
1532 prl_from = sec2annotation(fromsec);
1533 prl_to = sec2annotation(tosec);
1534 fprintf(stderr,
1535 "The %s %s%s%s references\n"
1536 "a %s %s%s%s.\n"
1537 "This is often seen when error handling "
1538 "in the init function\n"
1539 "uses functionality in the exit path.\n"
1540 "The fix is often to remove the %sannotation of\n"
1541 "%s%s so it may be used outside an exit section.\n",
1542 from, prl_from, fromsym, from_p,
1543 to, prl_to, tosym, to_p,
1544 prl_to, tosym, to_p);
1545 free(prl_from);
1546 free(prl_to);
1547 break;
1548 case ANY_EXIT_TO_ANY_INIT:
1549 prl_from = sec2annotation(fromsec);
1550 prl_to = sec2annotation(tosec);
1551 fprintf(stderr,
1552 "The %s %s%s%s references\n"
1553 "a %s %s%s%s.\n"
1554 "This is often seen when error handling "
1555 "in the exit function\n"
1556 "uses functionality in the init path.\n"
1557 "The fix is often to remove the %sannotation of\n"
1558 "%s%s so it may be used outside an init section.\n",
1559 from, prl_from, fromsym, from_p,
1560 to, prl_to, tosym, to_p,
1561 prl_to, tosym, to_p);
1562 free(prl_from);
1563 free(prl_to);
1564 break;
1565 case EXPORT_TO_INIT_EXIT:
1566 prl_to = sec2annotation(tosec);
1567 fprintf(stderr,
1568 "The symbol %s is exported and annotated %s\n"
1569 "Fix this by removing the %sannotation of %s "
1570 "or drop the export.\n",
1571 tosym, prl_to, prl_to, tosym);
1572 free(prl_to);
1573 break;
1574 case EXTABLE_TO_NON_TEXT:
1575 fatal("There's a special handler for this mismatch type, "
1576 "we should never get here.");
1577 break;
1578 }
1579 fprintf(stderr, "\n");
1580 }
1581
default_mismatch_handler(const char * modname,struct elf_info * elf,const struct sectioncheck * const mismatch,Elf_Rela * r,Elf_Sym * sym,const char * fromsec)1582 static void default_mismatch_handler(const char *modname, struct elf_info *elf,
1583 const struct sectioncheck* const mismatch,
1584 Elf_Rela *r, Elf_Sym *sym, const char *fromsec)
1585 {
1586 const char *tosec;
1587 Elf_Sym *to;
1588 Elf_Sym *from;
1589 const char *tosym;
1590 const char *fromsym;
1591
1592 from = find_elf_symbol2(elf, r->r_offset, fromsec);
1593 fromsym = sym_name(elf, from);
1594
1595 if (strstarts(fromsym, "reference___initcall"))
1596 return;
1597
1598 tosec = sec_name(elf, get_secindex(elf, sym));
1599 to = find_elf_symbol(elf, r->r_addend, sym);
1600 tosym = sym_name(elf, to);
1601
1602 /* check whitelist - we may ignore it */
1603 if (secref_whitelist(mismatch,
1604 fromsec, fromsym, tosec, tosym)) {
1605 report_sec_mismatch(modname, mismatch,
1606 fromsec, r->r_offset, fromsym,
1607 is_function(from), tosec, tosym,
1608 is_function(to));
1609 }
1610 }
1611
is_executable_section(struct elf_info * elf,unsigned int section_index)1612 static int is_executable_section(struct elf_info* elf, unsigned int section_index)
1613 {
1614 if (section_index >= elf->num_sections)
1615 fatal("section_index is outside elf->num_sections!\n");
1616
1617 return ((elf->sechdrs[section_index].sh_flags & SHF_EXECINSTR) == SHF_EXECINSTR);
1618 }
1619
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)1620 static void report_extable_warnings(const char* modname, struct elf_info* elf,
1621 const struct sectioncheck* const mismatch,
1622 Elf_Rela* r, Elf_Sym* sym,
1623 const char* fromsec, const char* tosec)
1624 {
1625 Elf_Sym* fromsym = find_elf_symbol2(elf, r->r_offset, fromsec);
1626 const char* fromsym_name = sym_name(elf, fromsym);
1627 Elf_Sym* tosym = find_elf_symbol(elf, r->r_addend, sym);
1628 const char* tosym_name = sym_name(elf, tosym);
1629 const char* from_pretty_name;
1630 const char* from_pretty_name_p;
1631 const char* to_pretty_name;
1632 const char* to_pretty_name_p;
1633
1634 get_pretty_name(is_function(fromsym),
1635 &from_pretty_name, &from_pretty_name_p);
1636 get_pretty_name(is_function(tosym),
1637 &to_pretty_name, &to_pretty_name_p);
1638
1639 warn("%s(%s+0x%lx): Section mismatch in reference"
1640 " from the %s %s%s to the %s %s:%s%s\n",
1641 modname, fromsec, (long)r->r_offset, from_pretty_name,
1642 fromsym_name, from_pretty_name_p,
1643 to_pretty_name, tosec, tosym_name, to_pretty_name_p);
1644
1645 if (!match(tosec, mismatch->bad_tosec) &&
1646 is_executable_section(elf, get_secindex(elf, sym)))
1647 fprintf(stderr,
1648 "The relocation at %s+0x%lx references\n"
1649 "section \"%s\" which is not in the list of\n"
1650 "authorized sections. If you're adding a new section\n"
1651 "and/or if this reference is valid, add \"%s\" to the\n"
1652 "list of authorized sections to jump to on fault.\n"
1653 "This can be achieved by adding \"%s\" to \n"
1654 "OTHER_TEXT_SECTIONS in scripts/mod/modpost.c.\n",
1655 fromsec, (long)r->r_offset, tosec, tosec, tosec);
1656 }
1657
extable_mismatch_handler(const char * modname,struct elf_info * elf,const struct sectioncheck * const mismatch,Elf_Rela * r,Elf_Sym * sym,const char * fromsec)1658 static void extable_mismatch_handler(const char* modname, struct elf_info *elf,
1659 const struct sectioncheck* const mismatch,
1660 Elf_Rela* r, Elf_Sym* sym,
1661 const char *fromsec)
1662 {
1663 const char* tosec = sec_name(elf, get_secindex(elf, sym));
1664
1665 sec_mismatch_count++;
1666
1667 report_extable_warnings(modname, elf, mismatch, r, sym, fromsec, tosec);
1668
1669 if (match(tosec, mismatch->bad_tosec))
1670 fatal("The relocation at %s+0x%lx references\n"
1671 "section \"%s\" which is black-listed.\n"
1672 "Something is seriously wrong and should be fixed.\n"
1673 "You might get more information about where this is\n"
1674 "coming from by using scripts/check_extable.sh %s\n",
1675 fromsec, (long)r->r_offset, tosec, modname);
1676 else if (!is_executable_section(elf, get_secindex(elf, sym)))
1677 error("%s+0x%lx references non-executable section '%s'\n",
1678 fromsec, (long)r->r_offset, tosec);
1679 }
1680
check_section_mismatch(const char * modname,struct elf_info * elf,Elf_Rela * r,Elf_Sym * sym,const char * fromsec)1681 static void check_section_mismatch(const char *modname, struct elf_info *elf,
1682 Elf_Rela *r, Elf_Sym *sym, const char *fromsec)
1683 {
1684 const char *tosec = sec_name(elf, get_secindex(elf, sym));
1685 const struct sectioncheck *mismatch = section_mismatch(fromsec, tosec);
1686
1687 if (mismatch) {
1688 if (mismatch->handler)
1689 mismatch->handler(modname, elf, mismatch,
1690 r, sym, fromsec);
1691 else
1692 default_mismatch_handler(modname, elf, mismatch,
1693 r, sym, fromsec);
1694 }
1695 }
1696
reloc_location(struct elf_info * elf,Elf_Shdr * sechdr,Elf_Rela * r)1697 static unsigned int *reloc_location(struct elf_info *elf,
1698 Elf_Shdr *sechdr, Elf_Rela *r)
1699 {
1700 return sym_get_data_by_offset(elf, sechdr->sh_info, r->r_offset);
1701 }
1702
addend_386_rel(struct elf_info * elf,Elf_Shdr * sechdr,Elf_Rela * r)1703 static int addend_386_rel(struct elf_info *elf, Elf_Shdr *sechdr, Elf_Rela *r)
1704 {
1705 unsigned int r_typ = ELF_R_TYPE(r->r_info);
1706 unsigned int *location = reloc_location(elf, sechdr, r);
1707
1708 switch (r_typ) {
1709 case R_386_32:
1710 r->r_addend = TO_NATIVE(*location);
1711 break;
1712 case R_386_PC32:
1713 r->r_addend = TO_NATIVE(*location) + 4;
1714 /* For CONFIG_RELOCATABLE=y */
1715 if (elf->hdr->e_type == ET_EXEC)
1716 r->r_addend += r->r_offset;
1717 break;
1718 }
1719 return 0;
1720 }
1721
1722 #ifndef R_ARM_CALL
1723 #define R_ARM_CALL 28
1724 #endif
1725 #ifndef R_ARM_JUMP24
1726 #define R_ARM_JUMP24 29
1727 #endif
1728
1729 #ifndef R_ARM_THM_CALL
1730 #define R_ARM_THM_CALL 10
1731 #endif
1732 #ifndef R_ARM_THM_JUMP24
1733 #define R_ARM_THM_JUMP24 30
1734 #endif
1735 #ifndef R_ARM_THM_JUMP19
1736 #define R_ARM_THM_JUMP19 51
1737 #endif
1738
sign_extend32(int32_t value,int index)1739 static int32_t sign_extend32(int32_t value, int index)
1740 {
1741 uint8_t shift = 31 - index;
1742
1743 return (int32_t)(value << shift) >> shift;
1744 }
1745
addend_arm_rel(struct elf_info * elf,Elf_Shdr * sechdr,Elf_Rela * r)1746 static int addend_arm_rel(struct elf_info *elf, Elf_Shdr *sechdr, Elf_Rela *r)
1747 {
1748 unsigned int r_typ = ELF_R_TYPE(r->r_info);
1749 Elf_Sym *sym = elf->symtab_start + ELF_R_SYM(r->r_info);
1750 void *loc = reloc_location(elf, sechdr, r);
1751 uint32_t inst;
1752 int32_t offset;
1753
1754 switch (r_typ) {
1755 case R_ARM_ABS32:
1756 inst = TO_NATIVE(*(uint32_t *)loc);
1757 r->r_addend = inst + sym->st_value;
1758 break;
1759 case R_ARM_PC24:
1760 case R_ARM_CALL:
1761 case R_ARM_JUMP24:
1762 inst = TO_NATIVE(*(uint32_t *)loc);
1763 offset = sign_extend32((inst & 0x00ffffff) << 2, 25);
1764 r->r_addend = offset + sym->st_value + 8;
1765 break;
1766 case R_ARM_THM_CALL:
1767 case R_ARM_THM_JUMP24:
1768 case R_ARM_THM_JUMP19:
1769 /* From ARM ABI: ((S + A) | T) - P */
1770 r->r_addend = (int)(long)(elf->hdr +
1771 sechdr->sh_offset +
1772 (r->r_offset - sechdr->sh_addr));
1773 break;
1774 default:
1775 return 1;
1776 }
1777 return 0;
1778 }
1779
addend_mips_rel(struct elf_info * elf,Elf_Shdr * sechdr,Elf_Rela * r)1780 static int addend_mips_rel(struct elf_info *elf, Elf_Shdr *sechdr, Elf_Rela *r)
1781 {
1782 unsigned int r_typ = ELF_R_TYPE(r->r_info);
1783 unsigned int *location = reloc_location(elf, sechdr, r);
1784 unsigned int inst;
1785
1786 if (r_typ == R_MIPS_HI16)
1787 return 1; /* skip this */
1788 inst = TO_NATIVE(*location);
1789 switch (r_typ) {
1790 case R_MIPS_LO16:
1791 r->r_addend = inst & 0xffff;
1792 break;
1793 case R_MIPS_26:
1794 r->r_addend = (inst & 0x03ffffff) << 2;
1795 break;
1796 case R_MIPS_32:
1797 r->r_addend = inst;
1798 break;
1799 }
1800 return 0;
1801 }
1802
section_rela(const char * modname,struct elf_info * elf,Elf_Shdr * sechdr)1803 static void section_rela(const char *modname, struct elf_info *elf,
1804 Elf_Shdr *sechdr)
1805 {
1806 Elf_Sym *sym;
1807 Elf_Rela *rela;
1808 Elf_Rela r;
1809 unsigned int r_sym;
1810 const char *fromsec;
1811
1812 Elf_Rela *start = (void *)elf->hdr + sechdr->sh_offset;
1813 Elf_Rela *stop = (void *)start + sechdr->sh_size;
1814
1815 fromsec = sech_name(elf, sechdr);
1816 fromsec += strlen(".rela");
1817 /* if from section (name) is know good then skip it */
1818 if (match(fromsec, section_white_list))
1819 return;
1820
1821 for (rela = start; rela < stop; rela++) {
1822 r.r_offset = TO_NATIVE(rela->r_offset);
1823 #if KERNEL_ELFCLASS == ELFCLASS64
1824 if (elf->hdr->e_machine == EM_MIPS) {
1825 unsigned int r_typ;
1826 r_sym = ELF64_MIPS_R_SYM(rela->r_info);
1827 r_sym = TO_NATIVE(r_sym);
1828 r_typ = ELF64_MIPS_R_TYPE(rela->r_info);
1829 r.r_info = ELF64_R_INFO(r_sym, r_typ);
1830 } else {
1831 r.r_info = TO_NATIVE(rela->r_info);
1832 r_sym = ELF_R_SYM(r.r_info);
1833 }
1834 #else
1835 r.r_info = TO_NATIVE(rela->r_info);
1836 r_sym = ELF_R_SYM(r.r_info);
1837 #endif
1838 r.r_addend = TO_NATIVE(rela->r_addend);
1839 sym = elf->symtab_start + r_sym;
1840 /* Skip special sections */
1841 if (is_shndx_special(sym->st_shndx))
1842 continue;
1843 check_section_mismatch(modname, elf, &r, sym, fromsec);
1844 }
1845 }
1846
section_rel(const char * modname,struct elf_info * elf,Elf_Shdr * sechdr)1847 static void section_rel(const char *modname, struct elf_info *elf,
1848 Elf_Shdr *sechdr)
1849 {
1850 Elf_Sym *sym;
1851 Elf_Rel *rel;
1852 Elf_Rela r;
1853 unsigned int r_sym;
1854 const char *fromsec;
1855
1856 Elf_Rel *start = (void *)elf->hdr + sechdr->sh_offset;
1857 Elf_Rel *stop = (void *)start + sechdr->sh_size;
1858
1859 fromsec = sech_name(elf, sechdr);
1860 fromsec += strlen(".rel");
1861 /* if from section (name) is know good then skip it */
1862 if (match(fromsec, section_white_list))
1863 return;
1864
1865 for (rel = start; rel < stop; rel++) {
1866 r.r_offset = TO_NATIVE(rel->r_offset);
1867 #if KERNEL_ELFCLASS == ELFCLASS64
1868 if (elf->hdr->e_machine == EM_MIPS) {
1869 unsigned int r_typ;
1870 r_sym = ELF64_MIPS_R_SYM(rel->r_info);
1871 r_sym = TO_NATIVE(r_sym);
1872 r_typ = ELF64_MIPS_R_TYPE(rel->r_info);
1873 r.r_info = ELF64_R_INFO(r_sym, r_typ);
1874 } else {
1875 r.r_info = TO_NATIVE(rel->r_info);
1876 r_sym = ELF_R_SYM(r.r_info);
1877 }
1878 #else
1879 r.r_info = TO_NATIVE(rel->r_info);
1880 r_sym = ELF_R_SYM(r.r_info);
1881 #endif
1882 r.r_addend = 0;
1883 switch (elf->hdr->e_machine) {
1884 case EM_386:
1885 if (addend_386_rel(elf, sechdr, &r))
1886 continue;
1887 break;
1888 case EM_ARM:
1889 if (addend_arm_rel(elf, sechdr, &r))
1890 continue;
1891 break;
1892 case EM_MIPS:
1893 if (addend_mips_rel(elf, sechdr, &r))
1894 continue;
1895 break;
1896 }
1897 sym = elf->symtab_start + r_sym;
1898 /* Skip special sections */
1899 if (is_shndx_special(sym->st_shndx))
1900 continue;
1901 check_section_mismatch(modname, elf, &r, sym, fromsec);
1902 }
1903 }
1904
1905 /**
1906 * A module includes a number of sections that are discarded
1907 * either when loaded or when used as built-in.
1908 * For loaded modules all functions marked __init and all data
1909 * marked __initdata will be discarded when the module has been initialized.
1910 * Likewise for modules used built-in the sections marked __exit
1911 * are discarded because __exit marked function are supposed to be called
1912 * only when a module is unloaded which never happens for built-in modules.
1913 * The check_sec_ref() function traverses all relocation records
1914 * to find all references to a section that reference a section that will
1915 * be discarded and warns about it.
1916 **/
check_sec_ref(struct module * mod,const char * modname,struct elf_info * elf)1917 static void check_sec_ref(struct module *mod, const char *modname,
1918 struct elf_info *elf)
1919 {
1920 int i;
1921 Elf_Shdr *sechdrs = elf->sechdrs;
1922
1923 /* Walk through all sections */
1924 for (i = 0; i < elf->num_sections; i++) {
1925 check_section(modname, elf, &elf->sechdrs[i]);
1926 /* We want to process only relocation sections and not .init */
1927 if (sechdrs[i].sh_type == SHT_RELA)
1928 section_rela(modname, elf, &elf->sechdrs[i]);
1929 else if (sechdrs[i].sh_type == SHT_REL)
1930 section_rel(modname, elf, &elf->sechdrs[i]);
1931 }
1932 }
1933
remove_dot(char * s)1934 static char *remove_dot(char *s)
1935 {
1936 size_t n = strcspn(s, ".");
1937
1938 if (n && s[n]) {
1939 size_t m = strspn(s + n + 1, "0123456789");
1940 if (m && (s[n + m + 1] == '.' || s[n + m + 1] == 0))
1941 s[n] = 0;
1942
1943 /* strip trailing .lto */
1944 if (strends(s, ".lto"))
1945 s[strlen(s) - 4] = '\0';
1946 }
1947 return s;
1948 }
1949
read_symbols(const char * modname)1950 static void read_symbols(const char *modname)
1951 {
1952 const char *symname;
1953 char *version;
1954 char *license;
1955 char *namespace;
1956 struct module *mod;
1957 struct elf_info info = { };
1958 Elf_Sym *sym;
1959
1960 if (!parse_elf(&info, modname))
1961 return;
1962
1963 {
1964 char *tmp;
1965
1966 /* strip trailing .o */
1967 tmp = NOFAIL(strdup(modname));
1968 tmp[strlen(tmp) - 2] = '\0';
1969 /* strip trailing .lto */
1970 if (strends(tmp, ".lto"))
1971 tmp[strlen(tmp) - 4] = '\0';
1972 mod = new_module(tmp);
1973 free(tmp);
1974 }
1975
1976 if (!mod->is_vmlinux) {
1977 license = get_modinfo(&info, "license");
1978 if (!license)
1979 error("missing MODULE_LICENSE() in %s\n", modname);
1980 while (license) {
1981 if (license_is_gpl_compatible(license))
1982 mod->gpl_compatible = 1;
1983 else {
1984 mod->gpl_compatible = 0;
1985 break;
1986 }
1987 license = get_next_modinfo(&info, "license", license);
1988 }
1989
1990 namespace = get_modinfo(&info, "import_ns");
1991 while (namespace) {
1992 add_namespace(&mod->imported_namespaces, namespace);
1993 namespace = get_next_modinfo(&info, "import_ns",
1994 namespace);
1995 }
1996 }
1997
1998 for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
1999 symname = remove_dot(info.strtab + sym->st_name);
2000
2001 handle_symbol(mod, &info, sym, symname);
2002 handle_moddevtable(mod, &info, sym, symname);
2003 }
2004
2005 for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
2006 symname = remove_dot(info.strtab + sym->st_name);
2007
2008 /* Apply symbol namespaces from __kstrtabns_<symbol> entries. */
2009 if (strstarts(symname, "__kstrtabns_"))
2010 sym_update_namespace(symname + strlen("__kstrtabns_"),
2011 namespace_from_kstrtabns(&info,
2012 sym));
2013
2014 if (strstarts(symname, "__crc_"))
2015 handle_modversion(mod, &info, sym,
2016 symname + strlen("__crc_"));
2017 }
2018
2019 // check for static EXPORT_SYMBOL_* functions && global vars
2020 for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
2021 unsigned char bind = ELF_ST_BIND(sym->st_info);
2022
2023 if (bind == STB_GLOBAL || bind == STB_WEAK) {
2024 struct symbol *s =
2025 find_symbol(remove_dot(info.strtab +
2026 sym->st_name));
2027
2028 if (s)
2029 s->is_static = 0;
2030 }
2031 }
2032
2033 check_sec_ref(mod, modname, &info);
2034
2035 if (!mod->is_vmlinux) {
2036 version = get_modinfo(&info, "version");
2037 if (version || all_versions)
2038 get_src_version(mod->name, mod->srcversion,
2039 sizeof(mod->srcversion) - 1);
2040 }
2041
2042 parse_elf_finish(&info);
2043
2044 /* Our trick to get versioning for module struct etc. - it's
2045 * never passed as an argument to an exported function, so
2046 * the automatic versioning doesn't pick it up, but it's really
2047 * important anyhow */
2048 if (modversions)
2049 mod->unres = alloc_symbol("module_layout", 0, mod->unres);
2050 }
2051
read_symbols_from_files(const char * filename)2052 static void read_symbols_from_files(const char *filename)
2053 {
2054 FILE *in = stdin;
2055 char fname[PATH_MAX];
2056
2057 if (strcmp(filename, "-") != 0) {
2058 in = fopen(filename, "r");
2059 if (!in)
2060 fatal("Can't open filenames file %s: %m", filename);
2061 }
2062
2063 while (fgets(fname, PATH_MAX, in) != NULL) {
2064 if (strends(fname, "\n"))
2065 fname[strlen(fname)-1] = '\0';
2066 read_symbols(fname);
2067 }
2068
2069 if (in != stdin)
2070 fclose(in);
2071 }
2072
2073 #define SZ 500
2074
2075 /* We first write the generated file into memory using the
2076 * following helper, then compare to the file on disk and
2077 * only update the later if anything changed */
2078
buf_printf(struct buffer * buf,const char * fmt,...)2079 void __attribute__((format(printf, 2, 3))) buf_printf(struct buffer *buf,
2080 const char *fmt, ...)
2081 {
2082 char tmp[SZ];
2083 int len;
2084 va_list ap;
2085
2086 va_start(ap, fmt);
2087 len = vsnprintf(tmp, SZ, fmt, ap);
2088 buf_write(buf, tmp, len);
2089 va_end(ap);
2090 }
2091
buf_write(struct buffer * buf,const char * s,int len)2092 void buf_write(struct buffer *buf, const char *s, int len)
2093 {
2094 if (buf->size - buf->pos < len) {
2095 buf->size += len + SZ;
2096 buf->p = NOFAIL(realloc(buf->p, buf->size));
2097 }
2098 strncpy(buf->p + buf->pos, s, len);
2099 buf->pos += len;
2100 }
2101
check_for_gpl_usage(enum export exp,const char * m,const char * s)2102 static void check_for_gpl_usage(enum export exp, const char *m, const char *s)
2103 {
2104 switch (exp) {
2105 case export_gpl:
2106 error("GPL-incompatible module %s.ko uses GPL-only symbol '%s'\n",
2107 m, s);
2108 break;
2109 case export_plain:
2110 case export_unknown:
2111 /* ignore */
2112 break;
2113 }
2114 }
2115
check_exports(struct module * mod)2116 static void check_exports(struct module *mod)
2117 {
2118 struct symbol *s, *exp;
2119
2120 for (s = mod->unres; s; s = s->next) {
2121 const char *basename;
2122 exp = find_symbol(s->name);
2123 if (!exp || exp->module == mod) {
2124 if (!s->weak && nr_unresolved++ < MAX_UNRESOLVED_REPORTS)
2125 modpost_log(warn_unresolved ? LOG_WARN : LOG_ERROR,
2126 "\"%s\" [%s.ko] undefined!\n",
2127 s->name, mod->name);
2128 continue;
2129 }
2130 basename = strrchr(mod->name, '/');
2131 if (basename)
2132 basename++;
2133 else
2134 basename = mod->name;
2135
2136 if (exp->namespace &&
2137 !module_imports_namespace(mod, exp->namespace)) {
2138 modpost_log(allow_missing_ns_imports ? LOG_WARN : LOG_ERROR,
2139 "module %s uses symbol %s from namespace %s, but does not import it.\n",
2140 basename, exp->name, exp->namespace);
2141 add_namespace(&mod->missing_namespaces, exp->namespace);
2142 }
2143
2144 if (!mod->gpl_compatible)
2145 check_for_gpl_usage(exp->export, basename, exp->name);
2146 }
2147 }
2148
check_modname_len(struct module * mod)2149 static void check_modname_len(struct module *mod)
2150 {
2151 const char *mod_name;
2152
2153 mod_name = strrchr(mod->name, '/');
2154 if (mod_name == NULL)
2155 mod_name = mod->name;
2156 else
2157 mod_name++;
2158 if (strlen(mod_name) >= MODULE_NAME_LEN)
2159 error("module name is too long [%s.ko]\n", mod->name);
2160 }
2161
2162 /**
2163 * Header for the generated file
2164 **/
add_header(struct buffer * b,struct module * mod)2165 static void add_header(struct buffer *b, struct module *mod)
2166 {
2167 buf_printf(b, "#include <linux/module.h>\n");
2168 /*
2169 * Include build-salt.h after module.h in order to
2170 * inherit the definitions.
2171 */
2172 buf_printf(b, "#define INCLUDE_VERMAGIC\n");
2173 buf_printf(b, "#include <linux/build-salt.h>\n");
2174 buf_printf(b, "#include <linux/elfnote-lto.h>\n");
2175 buf_printf(b, "#include <linux/vermagic.h>\n");
2176 buf_printf(b, "#include <linux/compiler.h>\n");
2177 buf_printf(b, "\n");
2178 buf_printf(b, "BUILD_SALT;\n");
2179 buf_printf(b, "BUILD_LTO_INFO;\n");
2180 buf_printf(b, "\n");
2181 buf_printf(b, "MODULE_INFO(vermagic, VERMAGIC_STRING);\n");
2182 buf_printf(b, "MODULE_INFO(name, KBUILD_MODNAME);\n");
2183 buf_printf(b, "\n");
2184 buf_printf(b, "__visible struct module __this_module\n");
2185 buf_printf(b, "__section(\".gnu.linkonce.this_module\") = {\n");
2186 buf_printf(b, "\t.name = KBUILD_MODNAME,\n");
2187 if (mod->has_init)
2188 buf_printf(b, "\t.init = init_module,\n");
2189 if (mod->has_cleanup)
2190 buf_printf(b, "#ifdef CONFIG_MODULE_UNLOAD\n"
2191 "\t.exit = cleanup_module,\n"
2192 "#endif\n");
2193 buf_printf(b, "\t.arch = MODULE_ARCH_INIT,\n");
2194 buf_printf(b, "};\n");
2195 }
2196
add_intree_flag(struct buffer * b,int is_intree)2197 static void add_intree_flag(struct buffer *b, int is_intree)
2198 {
2199 if (is_intree)
2200 buf_printf(b, "\nMODULE_INFO(intree, \"Y\");\n");
2201 }
2202
2203 /**
2204 * add_scmversion() - Adds the MODULE_INFO macro for the scmversion.
2205 * @b: Buffer to append to.
2206 *
2207 * This function fills in the module attribute `scmversion` for the kernel
2208 * module. This is useful for determining a given module's SCM version on
2209 * device via /sys/modules/<module>/scmversion and/or using the modinfo tool.
2210 */
add_scmversion(struct buffer * b)2211 static void add_scmversion(struct buffer *b)
2212 {
2213 if (module_scmversion[0] != '\0')
2214 buf_printf(b, "\nMODULE_INFO(scmversion, \"%s\");\n", module_scmversion);
2215 }
2216
2217 /* Cannot check for assembler */
add_retpoline(struct buffer * b)2218 static void add_retpoline(struct buffer *b)
2219 {
2220 buf_printf(b, "\n#ifdef CONFIG_RETPOLINE\n");
2221 buf_printf(b, "MODULE_INFO(retpoline, \"Y\");\n");
2222 buf_printf(b, "#endif\n");
2223 }
2224
add_staging_flag(struct buffer * b,const char * name)2225 static void add_staging_flag(struct buffer *b, const char *name)
2226 {
2227 if (strstarts(name, "drivers/staging"))
2228 buf_printf(b, "\nMODULE_INFO(staging, \"Y\");\n");
2229 }
2230
2231 /**
2232 * Record CRCs for unresolved symbols
2233 **/
add_versions(struct buffer * b,struct module * mod)2234 static void add_versions(struct buffer *b, struct module *mod)
2235 {
2236 struct symbol *s, *exp;
2237
2238 for (s = mod->unres; s; s = s->next) {
2239 exp = find_symbol(s->name);
2240 if (!exp || exp->module == mod)
2241 continue;
2242 s->module = exp->module;
2243 s->crc_valid = exp->crc_valid;
2244 s->crc = exp->crc;
2245 }
2246
2247 if (!modversions)
2248 return;
2249
2250 buf_printf(b, "\n");
2251 buf_printf(b, "static const struct modversion_info ____versions[]\n");
2252 buf_printf(b, "__used __section(\"__versions\") = {\n");
2253
2254 for (s = mod->unres; s; s = s->next) {
2255 if (!s->module)
2256 continue;
2257 if (!s->crc_valid) {
2258 warn("\"%s\" [%s.ko] has no CRC!\n",
2259 s->name, mod->name);
2260 continue;
2261 }
2262 if (strlen(s->name) >= MODULE_NAME_LEN) {
2263 error("too long symbol \"%s\" [%s.ko]\n",
2264 s->name, mod->name);
2265 break;
2266 }
2267 buf_printf(b, "\t{ %#8x, \"%s\" },\n",
2268 s->crc, s->name);
2269 }
2270
2271 buf_printf(b, "};\n");
2272 }
2273
add_depends(struct buffer * b,struct module * mod)2274 static void add_depends(struct buffer *b, struct module *mod)
2275 {
2276 struct symbol *s;
2277 int first = 1;
2278
2279 /* Clear ->seen flag of modules that own symbols needed by this. */
2280 for (s = mod->unres; s; s = s->next)
2281 if (s->module)
2282 s->module->seen = s->module->is_vmlinux;
2283
2284 buf_printf(b, "\n");
2285 buf_printf(b, "MODULE_INFO(depends, \"");
2286 for (s = mod->unres; s; s = s->next) {
2287 const char *p;
2288 if (!s->module)
2289 continue;
2290
2291 if (s->module->seen)
2292 continue;
2293
2294 s->module->seen = 1;
2295 p = strrchr(s->module->name, '/');
2296 if (p)
2297 p++;
2298 else
2299 p = s->module->name;
2300 buf_printf(b, "%s%s", first ? "" : ",", p);
2301 first = 0;
2302 }
2303 buf_printf(b, "\");\n");
2304 }
2305
add_srcversion(struct buffer * b,struct module * mod)2306 static void add_srcversion(struct buffer *b, struct module *mod)
2307 {
2308 if (mod->srcversion[0]) {
2309 buf_printf(b, "\n");
2310 buf_printf(b, "MODULE_INFO(srcversion, \"%s\");\n",
2311 mod->srcversion);
2312 }
2313 }
2314
write_buf(struct buffer * b,const char * fname)2315 static void write_buf(struct buffer *b, const char *fname)
2316 {
2317 FILE *file;
2318
2319 file = fopen(fname, "w");
2320 if (!file) {
2321 perror(fname);
2322 exit(1);
2323 }
2324 if (fwrite(b->p, 1, b->pos, file) != b->pos) {
2325 perror(fname);
2326 exit(1);
2327 }
2328 if (fclose(file) != 0) {
2329 perror(fname);
2330 exit(1);
2331 }
2332 }
2333
write_if_changed(struct buffer * b,const char * fname)2334 static void write_if_changed(struct buffer *b, const char *fname)
2335 {
2336 char *tmp;
2337 FILE *file;
2338 struct stat st;
2339
2340 file = fopen(fname, "r");
2341 if (!file)
2342 goto write;
2343
2344 if (fstat(fileno(file), &st) < 0)
2345 goto close_write;
2346
2347 if (st.st_size != b->pos)
2348 goto close_write;
2349
2350 tmp = NOFAIL(malloc(b->pos));
2351 if (fread(tmp, 1, b->pos, file) != b->pos)
2352 goto free_write;
2353
2354 if (memcmp(tmp, b->p, b->pos) != 0)
2355 goto free_write;
2356
2357 free(tmp);
2358 fclose(file);
2359 return;
2360
2361 free_write:
2362 free(tmp);
2363 close_write:
2364 fclose(file);
2365 write:
2366 write_buf(b, fname);
2367 }
2368
2369 /* parse Module.symvers file. line format:
2370 * 0x12345678<tab>symbol<tab>module<tab>export<tab>namespace
2371 **/
read_dump(const char * fname)2372 static void read_dump(const char *fname)
2373 {
2374 char *buf, *pos, *line;
2375
2376 buf = read_text_file(fname);
2377 if (!buf)
2378 /* No symbol versions, silently ignore */
2379 return;
2380
2381 pos = buf;
2382
2383 while ((line = get_line(&pos))) {
2384 char *symname, *namespace, *modname, *d, *export;
2385 unsigned int crc;
2386 struct module *mod;
2387 struct symbol *s;
2388
2389 if (!(symname = strchr(line, '\t')))
2390 goto fail;
2391 *symname++ = '\0';
2392 if (!(modname = strchr(symname, '\t')))
2393 goto fail;
2394 *modname++ = '\0';
2395 if (!(export = strchr(modname, '\t')))
2396 goto fail;
2397 *export++ = '\0';
2398 if (!(namespace = strchr(export, '\t')))
2399 goto fail;
2400 *namespace++ = '\0';
2401
2402 crc = strtoul(line, &d, 16);
2403 if (*symname == '\0' || *modname == '\0' || *d != '\0')
2404 goto fail;
2405 mod = find_module(modname);
2406 if (!mod) {
2407 mod = new_module(modname);
2408 mod->from_dump = 1;
2409 }
2410 s = sym_add_exported(symname, mod, export_no(export));
2411 s->is_static = 0;
2412 sym_set_crc(symname, crc);
2413 sym_update_namespace(symname, namespace);
2414 }
2415 free(buf);
2416 return;
2417 fail:
2418 free(buf);
2419 fatal("parse error in symbol dump file\n");
2420 }
2421
write_dump(const char * fname)2422 static void write_dump(const char *fname)
2423 {
2424 struct buffer buf = { };
2425 struct symbol *symbol;
2426 const char *namespace;
2427 int n;
2428
2429 for (n = 0; n < SYMBOL_HASH_SIZE ; n++) {
2430 symbol = symbolhash[n];
2431 while (symbol) {
2432 if (!symbol->module->from_dump) {
2433 namespace = symbol->namespace;
2434 buf_printf(&buf, "0x%08x\t%s\t%s\t%s\t%s\n",
2435 symbol->crc, symbol->name,
2436 symbol->module->name,
2437 export_str(symbol->export),
2438 namespace ? namespace : "");
2439 }
2440 symbol = symbol->next;
2441 }
2442 }
2443 write_buf(&buf, fname);
2444 free(buf.p);
2445 }
2446
write_namespace_deps_files(const char * fname)2447 static void write_namespace_deps_files(const char *fname)
2448 {
2449 struct module *mod;
2450 struct namespace_list *ns;
2451 struct buffer ns_deps_buf = {};
2452
2453 for (mod = modules; mod; mod = mod->next) {
2454
2455 if (mod->from_dump || !mod->missing_namespaces)
2456 continue;
2457
2458 buf_printf(&ns_deps_buf, "%s.ko:", mod->name);
2459
2460 for (ns = mod->missing_namespaces; ns; ns = ns->next)
2461 buf_printf(&ns_deps_buf, " %s", ns->namespace);
2462
2463 buf_printf(&ns_deps_buf, "\n");
2464 }
2465
2466 write_if_changed(&ns_deps_buf, fname);
2467 free(ns_deps_buf.p);
2468 }
2469
2470 struct dump_list {
2471 struct dump_list *next;
2472 const char *file;
2473 };
2474
main(int argc,char ** argv)2475 int main(int argc, char **argv)
2476 {
2477 struct module *mod;
2478 struct buffer buf = { };
2479 char *missing_namespace_deps = NULL;
2480 char *dump_write = NULL, *files_source = NULL;
2481 int opt;
2482 int n;
2483 struct dump_list *dump_read_start = NULL;
2484 struct dump_list **dump_read_iter = &dump_read_start;
2485
2486 while ((opt = getopt(argc, argv, "ei:mnT:o:awENd:v:")) != -1) {
2487 switch (opt) {
2488 case 'e':
2489 external_module = 1;
2490 break;
2491 case 'i':
2492 *dump_read_iter =
2493 NOFAIL(calloc(1, sizeof(**dump_read_iter)));
2494 (*dump_read_iter)->file = optarg;
2495 dump_read_iter = &(*dump_read_iter)->next;
2496 break;
2497 case 'm':
2498 modversions = 1;
2499 break;
2500 case 'n':
2501 ignore_missing_files = 1;
2502 break;
2503 case 'o':
2504 dump_write = optarg;
2505 break;
2506 case 'a':
2507 all_versions = 1;
2508 break;
2509 case 'T':
2510 files_source = optarg;
2511 break;
2512 case 'w':
2513 warn_unresolved = 1;
2514 break;
2515 case 'E':
2516 sec_mismatch_warn_only = false;
2517 break;
2518 case 'N':
2519 allow_missing_ns_imports = 1;
2520 break;
2521 case 'd':
2522 missing_namespace_deps = optarg;
2523 break;
2524 case 'v':
2525 strncpy(module_scmversion, optarg, sizeof(module_scmversion) - 1);
2526 break;
2527 default:
2528 exit(1);
2529 }
2530 }
2531
2532 while (dump_read_start) {
2533 struct dump_list *tmp;
2534
2535 read_dump(dump_read_start->file);
2536 tmp = dump_read_start->next;
2537 free(dump_read_start);
2538 dump_read_start = tmp;
2539 }
2540
2541 while (optind < argc)
2542 read_symbols(argv[optind++]);
2543
2544 if (files_source)
2545 read_symbols_from_files(files_source);
2546
2547 for (mod = modules; mod; mod = mod->next) {
2548 char fname[PATH_MAX];
2549
2550 if (mod->is_vmlinux || mod->from_dump)
2551 continue;
2552
2553 buf.pos = 0;
2554
2555 check_modname_len(mod);
2556 check_exports(mod);
2557
2558 add_header(&buf, mod);
2559 add_intree_flag(&buf, !external_module);
2560 add_retpoline(&buf);
2561 add_staging_flag(&buf, mod->name);
2562 add_versions(&buf, mod);
2563 add_depends(&buf, mod);
2564 add_moddevtable(&buf, mod);
2565 add_srcversion(&buf, mod);
2566 add_scmversion(&buf);
2567
2568 sprintf(fname, "%s.mod.c", mod->name);
2569 write_if_changed(&buf, fname);
2570 }
2571
2572 if (missing_namespace_deps)
2573 write_namespace_deps_files(missing_namespace_deps);
2574
2575 if (dump_write)
2576 write_dump(dump_write);
2577 if (sec_mismatch_count && !sec_mismatch_warn_only)
2578 error("Section mismatches detected.\n"
2579 "Set CONFIG_SECTION_MISMATCH_WARN_ONLY=y to allow them.\n");
2580 for (n = 0; n < SYMBOL_HASH_SIZE; n++) {
2581 struct symbol *s;
2582
2583 for (s = symbolhash[n]; s; s = s->next) {
2584 if (s->is_static)
2585 error("\"%s\" [%s] is a static %s\n",
2586 s->name, s->module->name,
2587 export_str(s->export));
2588 }
2589 }
2590
2591 if (nr_unresolved > MAX_UNRESOLVED_REPORTS)
2592 warn("suppressed %u unresolved symbol warnings because there were too many)\n",
2593 nr_unresolved - MAX_UNRESOLVED_REPORTS);
2594
2595 free(buf.p);
2596
2597 return error_occurred ? 1 : 0;
2598 }
2599