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