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