xref: /linux-6.15/scripts/mod/modpost.c (revision 9c65810c)
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 static void get_rel_type_and_sym(struct elf_info *elf, uint64_t r_info,
1349 				 unsigned int *r_type, unsigned int *r_sym)
1350 {
1351 	typedef struct {
1352 		Elf64_Word    r_sym;	/* Symbol index */
1353 		unsigned char r_ssym;	/* Special symbol for 2nd relocation */
1354 		unsigned char r_type3;	/* 3rd relocation type */
1355 		unsigned char r_type2;	/* 2nd relocation type */
1356 		unsigned char r_type;	/* 1st relocation type */
1357 	} Elf64_Mips_R_Info;
1358 
1359 	bool is_64bit = (elf->hdr->e_ident[EI_CLASS] == ELFCLASS64);
1360 
1361 	if (elf->hdr->e_machine == EM_MIPS && is_64bit) {
1362 		Elf64_Mips_R_Info *mips64_r_info = (void *)&r_info;
1363 
1364 		*r_type = mips64_r_info->r_type;
1365 		*r_sym = TO_NATIVE(mips64_r_info->r_sym);
1366 		return;
1367 	}
1368 
1369 	if (is_64bit)
1370 		r_info = TO_NATIVE((Elf64_Xword)r_info);
1371 	else
1372 		r_info = TO_NATIVE((Elf32_Word)r_info);
1373 
1374 	*r_type = ELF_R_TYPE(r_info);
1375 	*r_sym = ELF_R_SYM(r_info);
1376 }
1377 
1378 static void section_rela(struct module *mod, struct elf_info *elf,
1379 			 unsigned int fsecndx, const char *fromsec,
1380 			 const Elf_Rela *start, const Elf_Rela *stop)
1381 {
1382 	const Elf_Rela *rela;
1383 
1384 	for (rela = start; rela < stop; rela++) {
1385 		Elf_Sym *tsym;
1386 		Elf_Addr taddr, r_offset;
1387 		unsigned int r_type, r_sym;
1388 
1389 		r_offset = TO_NATIVE(rela->r_offset);
1390 		get_rel_type_and_sym(elf, rela->r_info, &r_type, &r_sym);
1391 
1392 		tsym = elf->symtab_start + r_sym;
1393 		taddr = tsym->st_value + TO_NATIVE(rela->r_addend);
1394 
1395 		switch (elf->hdr->e_machine) {
1396 		case EM_RISCV:
1397 			if (!strcmp("__ex_table", fromsec) &&
1398 			    r_type == R_RISCV_SUB32)
1399 				continue;
1400 			break;
1401 		case EM_LOONGARCH:
1402 			if (!strcmp("__ex_table", fromsec) &&
1403 			    r_type == R_LARCH_SUB32)
1404 				continue;
1405 			break;
1406 		}
1407 
1408 		check_section_mismatch(mod, elf, tsym,
1409 				       fsecndx, fromsec, r_offset, taddr);
1410 	}
1411 }
1412 
1413 static void section_rel(struct module *mod, struct elf_info *elf,
1414 			unsigned int fsecndx, const char *fromsec,
1415 			const Elf_Rel *start, const Elf_Rel *stop)
1416 {
1417 	const Elf_Rel *rel;
1418 
1419 	for (rel = start; rel < stop; rel++) {
1420 		Elf_Sym *tsym;
1421 		Elf_Addr taddr, r_offset;
1422 		unsigned int r_type, r_sym;
1423 		void *loc;
1424 
1425 		r_offset = TO_NATIVE(rel->r_offset);
1426 		get_rel_type_and_sym(elf, rel->r_info, &r_type, &r_sym);
1427 
1428 		loc = sym_get_data_by_offset(elf, fsecndx, r_offset);
1429 		tsym = elf->symtab_start + r_sym;
1430 
1431 		switch (elf->hdr->e_machine) {
1432 		case EM_386:
1433 			taddr = addend_386_rel(loc, r_type);
1434 			break;
1435 		case EM_ARM:
1436 			taddr = addend_arm_rel(loc, tsym, r_type);
1437 			break;
1438 		case EM_MIPS:
1439 			taddr = addend_mips_rel(loc, r_type);
1440 			break;
1441 		default:
1442 			fatal("Please add code to calculate addend for this architecture\n");
1443 		}
1444 
1445 		check_section_mismatch(mod, elf, tsym,
1446 				       fsecndx, fromsec, r_offset, taddr);
1447 	}
1448 }
1449 
1450 /**
1451  * A module includes a number of sections that are discarded
1452  * either when loaded or when used as built-in.
1453  * For loaded modules all functions marked __init and all data
1454  * marked __initdata will be discarded when the module has been initialized.
1455  * Likewise for modules used built-in the sections marked __exit
1456  * are discarded because __exit marked function are supposed to be called
1457  * only when a module is unloaded which never happens for built-in modules.
1458  * The check_sec_ref() function traverses all relocation records
1459  * to find all references to a section that reference a section that will
1460  * be discarded and warns about it.
1461  **/
1462 static void check_sec_ref(struct module *mod, struct elf_info *elf)
1463 {
1464 	int i;
1465 
1466 	/* Walk through all sections */
1467 	for (i = 0; i < elf->num_sections; i++) {
1468 		Elf_Shdr *sechdr = &elf->sechdrs[i];
1469 
1470 		check_section(mod->name, elf, sechdr);
1471 		/* We want to process only relocation sections and not .init */
1472 		if (sechdr->sh_type == SHT_REL || sechdr->sh_type == SHT_RELA) {
1473 			/* section to which the relocation applies */
1474 			unsigned int secndx = sechdr->sh_info;
1475 			const char *secname = sec_name(elf, secndx);
1476 			const void *start, *stop;
1477 
1478 			/* If the section is known good, skip it */
1479 			if (match(secname, section_white_list))
1480 				continue;
1481 
1482 			start = sym_get_data_by_offset(elf, i, 0);
1483 			stop = start + sechdr->sh_size;
1484 
1485 			if (sechdr->sh_type == SHT_RELA)
1486 				section_rela(mod, elf, secndx, secname,
1487 					     start, stop);
1488 			else
1489 				section_rel(mod, elf, secndx, secname,
1490 					    start, stop);
1491 		}
1492 	}
1493 }
1494 
1495 static char *remove_dot(char *s)
1496 {
1497 	size_t n = strcspn(s, ".");
1498 
1499 	if (n && s[n]) {
1500 		size_t m = strspn(s + n + 1, "0123456789");
1501 		if (m && (s[n + m + 1] == '.' || s[n + m + 1] == 0))
1502 			s[n] = 0;
1503 	}
1504 	return s;
1505 }
1506 
1507 /*
1508  * The CRCs are recorded in .*.cmd files in the form of:
1509  * #SYMVER <name> <crc>
1510  */
1511 static void extract_crcs_for_object(const char *object, struct module *mod)
1512 {
1513 	char cmd_file[PATH_MAX];
1514 	char *buf, *p;
1515 	const char *base;
1516 	int dirlen, ret;
1517 
1518 	base = strrchr(object, '/');
1519 	if (base) {
1520 		base++;
1521 		dirlen = base - object;
1522 	} else {
1523 		dirlen = 0;
1524 		base = object;
1525 	}
1526 
1527 	ret = snprintf(cmd_file, sizeof(cmd_file), "%.*s.%s.cmd",
1528 		       dirlen, object, base);
1529 	if (ret >= sizeof(cmd_file)) {
1530 		error("%s: too long path was truncated\n", cmd_file);
1531 		return;
1532 	}
1533 
1534 	buf = read_text_file(cmd_file);
1535 	p = buf;
1536 
1537 	while ((p = strstr(p, "\n#SYMVER "))) {
1538 		char *name;
1539 		size_t namelen;
1540 		unsigned int crc;
1541 		struct symbol *sym;
1542 
1543 		name = p + strlen("\n#SYMVER ");
1544 
1545 		p = strchr(name, ' ');
1546 		if (!p)
1547 			break;
1548 
1549 		namelen = p - name;
1550 		p++;
1551 
1552 		if (!isdigit(*p))
1553 			continue;	/* skip this line */
1554 
1555 		crc = strtoul(p, &p, 0);
1556 		if (*p != '\n')
1557 			continue;	/* skip this line */
1558 
1559 		name[namelen] = '\0';
1560 
1561 		/*
1562 		 * sym_find_with_module() may return NULL here.
1563 		 * It typically occurs when CONFIG_TRIM_UNUSED_KSYMS=y.
1564 		 * Since commit e1327a127703, genksyms calculates CRCs of all
1565 		 * symbols, including trimmed ones. Ignore orphan CRCs.
1566 		 */
1567 		sym = sym_find_with_module(name, mod);
1568 		if (sym)
1569 			sym_set_crc(sym, crc);
1570 	}
1571 
1572 	free(buf);
1573 }
1574 
1575 /*
1576  * The symbol versions (CRC) are recorded in the .*.cmd files.
1577  * Parse them to retrieve CRCs for the current module.
1578  */
1579 static void mod_set_crcs(struct module *mod)
1580 {
1581 	char objlist[PATH_MAX];
1582 	char *buf, *p, *obj;
1583 	int ret;
1584 
1585 	if (mod->is_vmlinux) {
1586 		strcpy(objlist, ".vmlinux.objs");
1587 	} else {
1588 		/* objects for a module are listed in the *.mod file. */
1589 		ret = snprintf(objlist, sizeof(objlist), "%s.mod", mod->name);
1590 		if (ret >= sizeof(objlist)) {
1591 			error("%s: too long path was truncated\n", objlist);
1592 			return;
1593 		}
1594 	}
1595 
1596 	buf = read_text_file(objlist);
1597 	p = buf;
1598 
1599 	while ((obj = strsep(&p, "\n")) && obj[0])
1600 		extract_crcs_for_object(obj, mod);
1601 
1602 	free(buf);
1603 }
1604 
1605 static void read_symbols(const char *modname)
1606 {
1607 	const char *symname;
1608 	char *version;
1609 	char *license;
1610 	char *namespace;
1611 	struct module *mod;
1612 	struct elf_info info = { };
1613 	Elf_Sym *sym;
1614 
1615 	if (!parse_elf(&info, modname))
1616 		return;
1617 
1618 	if (!strends(modname, ".o")) {
1619 		error("%s: filename must be suffixed with .o\n", modname);
1620 		return;
1621 	}
1622 
1623 	/* strip trailing .o */
1624 	mod = new_module(modname, strlen(modname) - strlen(".o"));
1625 
1626 	if (!mod->is_vmlinux) {
1627 		license = get_modinfo(&info, "license");
1628 		if (!license)
1629 			error("missing MODULE_LICENSE() in %s\n", modname);
1630 		while (license) {
1631 			if (!license_is_gpl_compatible(license)) {
1632 				mod->is_gpl_compatible = false;
1633 				break;
1634 			}
1635 			license = get_next_modinfo(&info, "license", license);
1636 		}
1637 
1638 		namespace = get_modinfo(&info, "import_ns");
1639 		while (namespace) {
1640 			add_namespace(&mod->imported_namespaces, namespace);
1641 			namespace = get_next_modinfo(&info, "import_ns",
1642 						     namespace);
1643 		}
1644 	}
1645 
1646 	if (extra_warn && !get_modinfo(&info, "description"))
1647 		warn("missing MODULE_DESCRIPTION() in %s\n", modname);
1648 	for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
1649 		symname = remove_dot(info.strtab + sym->st_name);
1650 
1651 		handle_symbol(mod, &info, sym, symname);
1652 		handle_moddevtable(mod, &info, sym, symname);
1653 	}
1654 
1655 	check_sec_ref(mod, &info);
1656 
1657 	if (!mod->is_vmlinux) {
1658 		version = get_modinfo(&info, "version");
1659 		if (version || all_versions)
1660 			get_src_version(mod->name, mod->srcversion,
1661 					sizeof(mod->srcversion) - 1);
1662 	}
1663 
1664 	parse_elf_finish(&info);
1665 
1666 	if (modversions) {
1667 		/*
1668 		 * Our trick to get versioning for module struct etc. - it's
1669 		 * never passed as an argument to an exported function, so
1670 		 * the automatic versioning doesn't pick it up, but it's really
1671 		 * important anyhow.
1672 		 */
1673 		sym_add_unresolved("module_layout", mod, false);
1674 
1675 		mod_set_crcs(mod);
1676 	}
1677 }
1678 
1679 static void read_symbols_from_files(const char *filename)
1680 {
1681 	FILE *in = stdin;
1682 	char fname[PATH_MAX];
1683 
1684 	in = fopen(filename, "r");
1685 	if (!in)
1686 		fatal("Can't open filenames file %s: %m", filename);
1687 
1688 	while (fgets(fname, PATH_MAX, in) != NULL) {
1689 		if (strends(fname, "\n"))
1690 			fname[strlen(fname)-1] = '\0';
1691 		read_symbols(fname);
1692 	}
1693 
1694 	fclose(in);
1695 }
1696 
1697 #define SZ 500
1698 
1699 /* We first write the generated file into memory using the
1700  * following helper, then compare to the file on disk and
1701  * only update the later if anything changed */
1702 
1703 void __attribute__((format(printf, 2, 3))) buf_printf(struct buffer *buf,
1704 						      const char *fmt, ...)
1705 {
1706 	char tmp[SZ];
1707 	int len;
1708 	va_list ap;
1709 
1710 	va_start(ap, fmt);
1711 	len = vsnprintf(tmp, SZ, fmt, ap);
1712 	buf_write(buf, tmp, len);
1713 	va_end(ap);
1714 }
1715 
1716 void buf_write(struct buffer *buf, const char *s, int len)
1717 {
1718 	if (buf->size - buf->pos < len) {
1719 		buf->size += len + SZ;
1720 		buf->p = NOFAIL(realloc(buf->p, buf->size));
1721 	}
1722 	strncpy(buf->p + buf->pos, s, len);
1723 	buf->pos += len;
1724 }
1725 
1726 static void check_exports(struct module *mod)
1727 {
1728 	struct symbol *s, *exp;
1729 
1730 	list_for_each_entry(s, &mod->unresolved_symbols, list) {
1731 		const char *basename;
1732 		exp = find_symbol(s->name);
1733 		if (!exp) {
1734 			if (!s->weak && nr_unresolved++ < MAX_UNRESOLVED_REPORTS)
1735 				modpost_log(warn_unresolved ? LOG_WARN : LOG_ERROR,
1736 					    "\"%s\" [%s.ko] undefined!\n",
1737 					    s->name, mod->name);
1738 			continue;
1739 		}
1740 		if (exp->module == mod) {
1741 			error("\"%s\" [%s.ko] was exported without definition\n",
1742 			      s->name, mod->name);
1743 			continue;
1744 		}
1745 
1746 		exp->used = true;
1747 		s->module = exp->module;
1748 		s->crc_valid = exp->crc_valid;
1749 		s->crc = exp->crc;
1750 
1751 		basename = strrchr(mod->name, '/');
1752 		if (basename)
1753 			basename++;
1754 		else
1755 			basename = mod->name;
1756 
1757 		if (!contains_namespace(&mod->imported_namespaces, exp->namespace)) {
1758 			modpost_log(allow_missing_ns_imports ? LOG_WARN : LOG_ERROR,
1759 				    "module %s uses symbol %s from namespace %s, but does not import it.\n",
1760 				    basename, exp->name, exp->namespace);
1761 			add_namespace(&mod->missing_namespaces, exp->namespace);
1762 		}
1763 
1764 		if (!mod->is_gpl_compatible && exp->is_gpl_only)
1765 			error("GPL-incompatible module %s.ko uses GPL-only symbol '%s'\n",
1766 			      basename, exp->name);
1767 	}
1768 }
1769 
1770 static void handle_white_list_exports(const char *white_list)
1771 {
1772 	char *buf, *p, *name;
1773 
1774 	buf = read_text_file(white_list);
1775 	p = buf;
1776 
1777 	while ((name = strsep(&p, "\n"))) {
1778 		struct symbol *sym = find_symbol(name);
1779 
1780 		if (sym)
1781 			sym->used = true;
1782 	}
1783 
1784 	free(buf);
1785 }
1786 
1787 static void check_modname_len(struct module *mod)
1788 {
1789 	const char *mod_name;
1790 
1791 	mod_name = strrchr(mod->name, '/');
1792 	if (mod_name == NULL)
1793 		mod_name = mod->name;
1794 	else
1795 		mod_name++;
1796 	if (strlen(mod_name) >= MODULE_NAME_LEN)
1797 		error("module name is too long [%s.ko]\n", mod->name);
1798 }
1799 
1800 /**
1801  * Header for the generated file
1802  **/
1803 static void add_header(struct buffer *b, struct module *mod)
1804 {
1805 	buf_printf(b, "#include <linux/module.h>\n");
1806 	/*
1807 	 * Include build-salt.h after module.h in order to
1808 	 * inherit the definitions.
1809 	 */
1810 	buf_printf(b, "#define INCLUDE_VERMAGIC\n");
1811 	buf_printf(b, "#include <linux/build-salt.h>\n");
1812 	buf_printf(b, "#include <linux/elfnote-lto.h>\n");
1813 	buf_printf(b, "#include <linux/export-internal.h>\n");
1814 	buf_printf(b, "#include <linux/vermagic.h>\n");
1815 	buf_printf(b, "#include <linux/compiler.h>\n");
1816 	buf_printf(b, "\n");
1817 	buf_printf(b, "#ifdef CONFIG_UNWINDER_ORC\n");
1818 	buf_printf(b, "#include <asm/orc_header.h>\n");
1819 	buf_printf(b, "ORC_HEADER;\n");
1820 	buf_printf(b, "#endif\n");
1821 	buf_printf(b, "\n");
1822 	buf_printf(b, "BUILD_SALT;\n");
1823 	buf_printf(b, "BUILD_LTO_INFO;\n");
1824 	buf_printf(b, "\n");
1825 	buf_printf(b, "MODULE_INFO(vermagic, VERMAGIC_STRING);\n");
1826 	buf_printf(b, "MODULE_INFO(name, KBUILD_MODNAME);\n");
1827 	buf_printf(b, "\n");
1828 	buf_printf(b, "__visible struct module __this_module\n");
1829 	buf_printf(b, "__section(\".gnu.linkonce.this_module\") = {\n");
1830 	buf_printf(b, "\t.name = KBUILD_MODNAME,\n");
1831 	if (mod->has_init)
1832 		buf_printf(b, "\t.init = init_module,\n");
1833 	if (mod->has_cleanup)
1834 		buf_printf(b, "#ifdef CONFIG_MODULE_UNLOAD\n"
1835 			      "\t.exit = cleanup_module,\n"
1836 			      "#endif\n");
1837 	buf_printf(b, "\t.arch = MODULE_ARCH_INIT,\n");
1838 	buf_printf(b, "};\n");
1839 
1840 	if (!external_module)
1841 		buf_printf(b, "\nMODULE_INFO(intree, \"Y\");\n");
1842 
1843 	buf_printf(b,
1844 		   "\n"
1845 		   "#ifdef CONFIG_RETPOLINE\n"
1846 		   "MODULE_INFO(retpoline, \"Y\");\n"
1847 		   "#endif\n");
1848 
1849 	if (strstarts(mod->name, "drivers/staging"))
1850 		buf_printf(b, "\nMODULE_INFO(staging, \"Y\");\n");
1851 
1852 	if (strstarts(mod->name, "tools/testing"))
1853 		buf_printf(b, "\nMODULE_INFO(test, \"Y\");\n");
1854 }
1855 
1856 static void add_exported_symbols(struct buffer *buf, struct module *mod)
1857 {
1858 	struct symbol *sym;
1859 
1860 	/* generate struct for exported symbols */
1861 	buf_printf(buf, "\n");
1862 	list_for_each_entry(sym, &mod->exported_symbols, list) {
1863 		if (trim_unused_exports && !sym->used)
1864 			continue;
1865 
1866 		buf_printf(buf, "KSYMTAB_%s(%s, \"%s\", \"%s\");\n",
1867 			   sym->is_func ? "FUNC" : "DATA", sym->name,
1868 			   sym->is_gpl_only ? "_gpl" : "", sym->namespace);
1869 	}
1870 
1871 	if (!modversions)
1872 		return;
1873 
1874 	/* record CRCs for exported symbols */
1875 	buf_printf(buf, "\n");
1876 	list_for_each_entry(sym, &mod->exported_symbols, list) {
1877 		if (trim_unused_exports && !sym->used)
1878 			continue;
1879 
1880 		if (!sym->crc_valid)
1881 			warn("EXPORT symbol \"%s\" [%s%s] version generation failed, symbol will not be versioned.\n"
1882 			     "Is \"%s\" prototyped in <asm/asm-prototypes.h>?\n",
1883 			     sym->name, mod->name, mod->is_vmlinux ? "" : ".ko",
1884 			     sym->name);
1885 
1886 		buf_printf(buf, "SYMBOL_CRC(%s, 0x%08x, \"%s\");\n",
1887 			   sym->name, sym->crc, sym->is_gpl_only ? "_gpl" : "");
1888 	}
1889 }
1890 
1891 /**
1892  * Record CRCs for unresolved symbols
1893  **/
1894 static void add_versions(struct buffer *b, struct module *mod)
1895 {
1896 	struct symbol *s;
1897 
1898 	if (!modversions)
1899 		return;
1900 
1901 	buf_printf(b, "\n");
1902 	buf_printf(b, "static const struct modversion_info ____versions[]\n");
1903 	buf_printf(b, "__used __section(\"__versions\") = {\n");
1904 
1905 	list_for_each_entry(s, &mod->unresolved_symbols, list) {
1906 		if (!s->module)
1907 			continue;
1908 		if (!s->crc_valid) {
1909 			warn("\"%s\" [%s.ko] has no CRC!\n",
1910 				s->name, mod->name);
1911 			continue;
1912 		}
1913 		if (strlen(s->name) >= MODULE_NAME_LEN) {
1914 			error("too long symbol \"%s\" [%s.ko]\n",
1915 			      s->name, mod->name);
1916 			break;
1917 		}
1918 		buf_printf(b, "\t{ %#8x, \"%s\" },\n",
1919 			   s->crc, s->name);
1920 	}
1921 
1922 	buf_printf(b, "};\n");
1923 }
1924 
1925 static void add_depends(struct buffer *b, struct module *mod)
1926 {
1927 	struct symbol *s;
1928 	int first = 1;
1929 
1930 	/* Clear ->seen flag of modules that own symbols needed by this. */
1931 	list_for_each_entry(s, &mod->unresolved_symbols, list) {
1932 		if (s->module)
1933 			s->module->seen = s->module->is_vmlinux;
1934 	}
1935 
1936 	buf_printf(b, "\n");
1937 	buf_printf(b, "MODULE_INFO(depends, \"");
1938 	list_for_each_entry(s, &mod->unresolved_symbols, list) {
1939 		const char *p;
1940 		if (!s->module)
1941 			continue;
1942 
1943 		if (s->module->seen)
1944 			continue;
1945 
1946 		s->module->seen = true;
1947 		p = strrchr(s->module->name, '/');
1948 		if (p)
1949 			p++;
1950 		else
1951 			p = s->module->name;
1952 		buf_printf(b, "%s%s", first ? "" : ",", p);
1953 		first = 0;
1954 	}
1955 	buf_printf(b, "\");\n");
1956 }
1957 
1958 static void add_srcversion(struct buffer *b, struct module *mod)
1959 {
1960 	if (mod->srcversion[0]) {
1961 		buf_printf(b, "\n");
1962 		buf_printf(b, "MODULE_INFO(srcversion, \"%s\");\n",
1963 			   mod->srcversion);
1964 	}
1965 }
1966 
1967 static void write_buf(struct buffer *b, const char *fname)
1968 {
1969 	FILE *file;
1970 
1971 	if (error_occurred)
1972 		return;
1973 
1974 	file = fopen(fname, "w");
1975 	if (!file) {
1976 		perror(fname);
1977 		exit(1);
1978 	}
1979 	if (fwrite(b->p, 1, b->pos, file) != b->pos) {
1980 		perror(fname);
1981 		exit(1);
1982 	}
1983 	if (fclose(file) != 0) {
1984 		perror(fname);
1985 		exit(1);
1986 	}
1987 }
1988 
1989 static void write_if_changed(struct buffer *b, const char *fname)
1990 {
1991 	char *tmp;
1992 	FILE *file;
1993 	struct stat st;
1994 
1995 	file = fopen(fname, "r");
1996 	if (!file)
1997 		goto write;
1998 
1999 	if (fstat(fileno(file), &st) < 0)
2000 		goto close_write;
2001 
2002 	if (st.st_size != b->pos)
2003 		goto close_write;
2004 
2005 	tmp = NOFAIL(malloc(b->pos));
2006 	if (fread(tmp, 1, b->pos, file) != b->pos)
2007 		goto free_write;
2008 
2009 	if (memcmp(tmp, b->p, b->pos) != 0)
2010 		goto free_write;
2011 
2012 	free(tmp);
2013 	fclose(file);
2014 	return;
2015 
2016  free_write:
2017 	free(tmp);
2018  close_write:
2019 	fclose(file);
2020  write:
2021 	write_buf(b, fname);
2022 }
2023 
2024 static void write_vmlinux_export_c_file(struct module *mod)
2025 {
2026 	struct buffer buf = { };
2027 
2028 	buf_printf(&buf,
2029 		   "#include <linux/export-internal.h>\n");
2030 
2031 	add_exported_symbols(&buf, mod);
2032 	write_if_changed(&buf, ".vmlinux.export.c");
2033 	free(buf.p);
2034 }
2035 
2036 /* do sanity checks, and generate *.mod.c file */
2037 static void write_mod_c_file(struct module *mod)
2038 {
2039 	struct buffer buf = { };
2040 	char fname[PATH_MAX];
2041 	int ret;
2042 
2043 	add_header(&buf, mod);
2044 	add_exported_symbols(&buf, mod);
2045 	add_versions(&buf, mod);
2046 	add_depends(&buf, mod);
2047 	add_moddevtable(&buf, mod);
2048 	add_srcversion(&buf, mod);
2049 
2050 	ret = snprintf(fname, sizeof(fname), "%s.mod.c", mod->name);
2051 	if (ret >= sizeof(fname)) {
2052 		error("%s: too long path was truncated\n", fname);
2053 		goto free;
2054 	}
2055 
2056 	write_if_changed(&buf, fname);
2057 
2058 free:
2059 	free(buf.p);
2060 }
2061 
2062 /* parse Module.symvers file. line format:
2063  * 0x12345678<tab>symbol<tab>module<tab>export<tab>namespace
2064  **/
2065 static void read_dump(const char *fname)
2066 {
2067 	char *buf, *pos, *line;
2068 
2069 	buf = read_text_file(fname);
2070 	if (!buf)
2071 		/* No symbol versions, silently ignore */
2072 		return;
2073 
2074 	pos = buf;
2075 
2076 	while ((line = get_line(&pos))) {
2077 		char *symname, *namespace, *modname, *d, *export;
2078 		unsigned int crc;
2079 		struct module *mod;
2080 		struct symbol *s;
2081 		bool gpl_only;
2082 
2083 		if (!(symname = strchr(line, '\t')))
2084 			goto fail;
2085 		*symname++ = '\0';
2086 		if (!(modname = strchr(symname, '\t')))
2087 			goto fail;
2088 		*modname++ = '\0';
2089 		if (!(export = strchr(modname, '\t')))
2090 			goto fail;
2091 		*export++ = '\0';
2092 		if (!(namespace = strchr(export, '\t')))
2093 			goto fail;
2094 		*namespace++ = '\0';
2095 
2096 		crc = strtoul(line, &d, 16);
2097 		if (*symname == '\0' || *modname == '\0' || *d != '\0')
2098 			goto fail;
2099 
2100 		if (!strcmp(export, "EXPORT_SYMBOL_GPL")) {
2101 			gpl_only = true;
2102 		} else if (!strcmp(export, "EXPORT_SYMBOL")) {
2103 			gpl_only = false;
2104 		} else {
2105 			error("%s: unknown license %s. skip", symname, export);
2106 			continue;
2107 		}
2108 
2109 		mod = find_module(modname);
2110 		if (!mod) {
2111 			mod = new_module(modname, strlen(modname));
2112 			mod->from_dump = true;
2113 		}
2114 		s = sym_add_exported(symname, mod, gpl_only, namespace);
2115 		sym_set_crc(s, crc);
2116 	}
2117 	free(buf);
2118 	return;
2119 fail:
2120 	free(buf);
2121 	fatal("parse error in symbol dump file\n");
2122 }
2123 
2124 static void write_dump(const char *fname)
2125 {
2126 	struct buffer buf = { };
2127 	struct module *mod;
2128 	struct symbol *sym;
2129 
2130 	list_for_each_entry(mod, &modules, list) {
2131 		if (mod->from_dump)
2132 			continue;
2133 		list_for_each_entry(sym, &mod->exported_symbols, list) {
2134 			if (trim_unused_exports && !sym->used)
2135 				continue;
2136 
2137 			buf_printf(&buf, "0x%08x\t%s\t%s\tEXPORT_SYMBOL%s\t%s\n",
2138 				   sym->crc, sym->name, mod->name,
2139 				   sym->is_gpl_only ? "_GPL" : "",
2140 				   sym->namespace);
2141 		}
2142 	}
2143 	write_buf(&buf, fname);
2144 	free(buf.p);
2145 }
2146 
2147 static void write_namespace_deps_files(const char *fname)
2148 {
2149 	struct module *mod;
2150 	struct namespace_list *ns;
2151 	struct buffer ns_deps_buf = {};
2152 
2153 	list_for_each_entry(mod, &modules, list) {
2154 
2155 		if (mod->from_dump || list_empty(&mod->missing_namespaces))
2156 			continue;
2157 
2158 		buf_printf(&ns_deps_buf, "%s.ko:", mod->name);
2159 
2160 		list_for_each_entry(ns, &mod->missing_namespaces, list)
2161 			buf_printf(&ns_deps_buf, " %s", ns->namespace);
2162 
2163 		buf_printf(&ns_deps_buf, "\n");
2164 	}
2165 
2166 	write_if_changed(&ns_deps_buf, fname);
2167 	free(ns_deps_buf.p);
2168 }
2169 
2170 struct dump_list {
2171 	struct list_head list;
2172 	const char *file;
2173 };
2174 
2175 int main(int argc, char **argv)
2176 {
2177 	struct module *mod;
2178 	char *missing_namespace_deps = NULL;
2179 	char *unused_exports_white_list = NULL;
2180 	char *dump_write = NULL, *files_source = NULL;
2181 	int opt;
2182 	LIST_HEAD(dump_lists);
2183 	struct dump_list *dl, *dl2;
2184 
2185 	while ((opt = getopt(argc, argv, "ei:MmnT:to:au:WwENd:")) != -1) {
2186 		switch (opt) {
2187 		case 'e':
2188 			external_module = true;
2189 			break;
2190 		case 'i':
2191 			dl = NOFAIL(malloc(sizeof(*dl)));
2192 			dl->file = optarg;
2193 			list_add_tail(&dl->list, &dump_lists);
2194 			break;
2195 		case 'M':
2196 			module_enabled = true;
2197 			break;
2198 		case 'm':
2199 			modversions = true;
2200 			break;
2201 		case 'n':
2202 			ignore_missing_files = true;
2203 			break;
2204 		case 'o':
2205 			dump_write = optarg;
2206 			break;
2207 		case 'a':
2208 			all_versions = true;
2209 			break;
2210 		case 'T':
2211 			files_source = optarg;
2212 			break;
2213 		case 't':
2214 			trim_unused_exports = true;
2215 			break;
2216 		case 'u':
2217 			unused_exports_white_list = optarg;
2218 			break;
2219 		case 'W':
2220 			extra_warn = true;
2221 			break;
2222 		case 'w':
2223 			warn_unresolved = true;
2224 			break;
2225 		case 'E':
2226 			sec_mismatch_warn_only = false;
2227 			break;
2228 		case 'N':
2229 			allow_missing_ns_imports = true;
2230 			break;
2231 		case 'd':
2232 			missing_namespace_deps = optarg;
2233 			break;
2234 		default:
2235 			exit(1);
2236 		}
2237 	}
2238 
2239 	list_for_each_entry_safe(dl, dl2, &dump_lists, list) {
2240 		read_dump(dl->file);
2241 		list_del(&dl->list);
2242 		free(dl);
2243 	}
2244 
2245 	while (optind < argc)
2246 		read_symbols(argv[optind++]);
2247 
2248 	if (files_source)
2249 		read_symbols_from_files(files_source);
2250 
2251 	list_for_each_entry(mod, &modules, list) {
2252 		if (mod->from_dump || mod->is_vmlinux)
2253 			continue;
2254 
2255 		check_modname_len(mod);
2256 		check_exports(mod);
2257 	}
2258 
2259 	if (unused_exports_white_list)
2260 		handle_white_list_exports(unused_exports_white_list);
2261 
2262 	list_for_each_entry(mod, &modules, list) {
2263 		if (mod->from_dump)
2264 			continue;
2265 
2266 		if (mod->is_vmlinux)
2267 			write_vmlinux_export_c_file(mod);
2268 		else
2269 			write_mod_c_file(mod);
2270 	}
2271 
2272 	if (missing_namespace_deps)
2273 		write_namespace_deps_files(missing_namespace_deps);
2274 
2275 	if (dump_write)
2276 		write_dump(dump_write);
2277 	if (sec_mismatch_count && !sec_mismatch_warn_only)
2278 		error("Section mismatches detected.\n"
2279 		      "Set CONFIG_SECTION_MISMATCH_WARN_ONLY=y to allow them.\n");
2280 
2281 	if (nr_unresolved > MAX_UNRESOLVED_REPORTS)
2282 		warn("suppressed %u unresolved symbol warnings because there were too many)\n",
2283 		     nr_unresolved - MAX_UNRESOLVED_REPORTS);
2284 
2285 	return error_occurred ? 1 : 0;
2286 }
2287