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