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