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