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