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