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