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