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