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