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