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