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