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