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