xref: /OK3568_Linux_fs/kernel/scripts/mod/modpost.c (revision 4882a59341e53eb6f0b4789bf948001014eff981)
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 <stdio.h>
17 #include <ctype.h>
18 #include <string.h>
19 #include <limits.h>
20 #include <errno.h>
21 #include "modpost.h"
22 #include "../../include/linux/license.h"
23 
24 /* Are we using CONFIG_MODVERSIONS? */
25 static int modversions = 0;
26 /* Warn about undefined symbols? (do so if we have vmlinux) */
27 static int have_vmlinux = 0;
28 /* Is CONFIG_MODULE_SRCVERSION_ALL set? */
29 static int all_versions = 0;
30 /* If we are modposting external module set to 1 */
31 static int external_module = 0;
32 #define MODULE_SCMVERSION_SIZE 64
33 static char module_scmversion[MODULE_SCMVERSION_SIZE];
34 /* Only warn about unresolved symbols */
35 static int warn_unresolved = 0;
36 /* How a symbol is exported */
37 static int sec_mismatch_count = 0;
38 static int sec_mismatch_warn_only = true;
39 /* ignore missing files */
40 static int ignore_missing_files;
41 /* If set to 1, only warn (instead of error) about missing ns imports */
42 static int allow_missing_ns_imports;
43 
44 static bool error_occurred;
45 
46 enum export {
47 	export_plain,      export_unused,     export_gpl,
48 	export_unused_gpl, export_gpl_future, export_unknown
49 };
50 
51 /* In kernel, this size is defined in linux/module.h;
52  * here we use Elf_Addr instead of long for covering cross-compile
53  */
54 
55 #define MODULE_NAME_LEN (64 - sizeof(Elf_Addr))
56 
57 void __attribute__((format(printf, 2, 3)))
modpost_log(enum loglevel loglevel,const char * fmt,...)58 modpost_log(enum loglevel loglevel, const char *fmt, ...)
59 {
60 	va_list arglist;
61 
62 	switch (loglevel) {
63 	case LOG_WARN:
64 		fprintf(stderr, "WARNING: ");
65 		break;
66 	case LOG_ERROR:
67 		fprintf(stderr, "ERROR: ");
68 		break;
69 	case LOG_FATAL:
70 		fprintf(stderr, "FATAL: ");
71 		break;
72 	default: /* invalid loglevel, ignore */
73 		break;
74 	}
75 
76 	fprintf(stderr, "modpost: ");
77 
78 	va_start(arglist, fmt);
79 	vfprintf(stderr, fmt, arglist);
80 	va_end(arglist);
81 
82 	if (loglevel == LOG_FATAL)
83 		exit(1);
84 	if (loglevel == LOG_ERROR)
85 		error_occurred = true;
86 }
87 
do_nofail(void * ptr,const char * expr)88 void *do_nofail(void *ptr, const char *expr)
89 {
90 	if (!ptr)
91 		fatal("Memory allocation failure: %s.\n", expr);
92 
93 	return ptr;
94 }
95 
read_text_file(const char * filename)96 char *read_text_file(const char *filename)
97 {
98 	struct stat st;
99 	size_t nbytes;
100 	int fd;
101 	char *buf;
102 
103 	fd = open(filename, O_RDONLY);
104 	if (fd < 0) {
105 		perror(filename);
106 		exit(1);
107 	}
108 
109 	if (fstat(fd, &st) < 0) {
110 		perror(filename);
111 		exit(1);
112 	}
113 
114 	buf = NOFAIL(malloc(st.st_size + 1));
115 
116 	nbytes = st.st_size;
117 
118 	while (nbytes) {
119 		ssize_t bytes_read;
120 
121 		bytes_read = read(fd, buf, nbytes);
122 		if (bytes_read < 0) {
123 			perror(filename);
124 			exit(1);
125 		}
126 
127 		nbytes -= bytes_read;
128 	}
129 	buf[st.st_size] = '\0';
130 
131 	close(fd);
132 
133 	return buf;
134 }
135 
get_line(char ** stringp)136 char *get_line(char **stringp)
137 {
138 	char *orig = *stringp, *next;
139 
140 	/* do not return the unwanted extra line at EOF */
141 	if (!orig || *orig == '\0')
142 		return NULL;
143 
144 	/* don't use strsep here, it is not available everywhere */
145 	next = strchr(orig, '\n');
146 	if (next)
147 		*next++ = '\0';
148 
149 	*stringp = next;
150 
151 	return orig;
152 }
153 
154 /* A list of all modules we processed */
155 static struct module *modules;
156 
find_module(const char * modname)157 static struct module *find_module(const char *modname)
158 {
159 	struct module *mod;
160 
161 	for (mod = modules; mod; mod = mod->next)
162 		if (strcmp(mod->name, modname) == 0)
163 			break;
164 	return mod;
165 }
166 
new_module(const char * modname)167 static struct module *new_module(const char *modname)
168 {
169 	struct module *mod;
170 
171 	mod = NOFAIL(malloc(sizeof(*mod) + strlen(modname) + 1));
172 	memset(mod, 0, sizeof(*mod));
173 
174 	/* add to list */
175 	strcpy(mod->name, modname);
176 	mod->is_vmlinux = (strcmp(modname, "vmlinux") == 0);
177 	mod->gpl_compatible = -1;
178 	mod->next = modules;
179 	modules = mod;
180 
181 	if (mod->is_vmlinux)
182 		have_vmlinux = 1;
183 
184 	return mod;
185 }
186 
187 /* A hash of all exported symbols,
188  * struct symbol is also used for lists of unresolved symbols */
189 
190 #define SYMBOL_HASH_SIZE 1024
191 
192 struct symbol {
193 	struct symbol *next;
194 	struct module *module;
195 	unsigned int crc;
196 	int crc_valid;
197 	char *namespace;
198 	unsigned int weak:1;
199 	unsigned int is_static:1;  /* 1 if symbol is not global */
200 	enum export  export;       /* Type of export */
201 	char name[];
202 };
203 
204 static struct symbol *symbolhash[SYMBOL_HASH_SIZE];
205 
206 /* This is based on the hash agorithm from gdbm, via tdb */
tdb_hash(const char * name)207 static inline unsigned int tdb_hash(const char *name)
208 {
209 	unsigned value;	/* Used to compute the hash value.  */
210 	unsigned   i;	/* Used to cycle through random values. */
211 
212 	/* Set the initial value from the key size. */
213 	for (value = 0x238F13AF * strlen(name), i = 0; name[i]; i++)
214 		value = (value + (((unsigned char *)name)[i] << (i*5 % 24)));
215 
216 	return (1103515243 * value + 12345);
217 }
218 
219 /**
220  * Allocate a new symbols for use in the hash of exported symbols or
221  * the list of unresolved symbols per module
222  **/
alloc_symbol(const char * name,unsigned int weak,struct symbol * next)223 static struct symbol *alloc_symbol(const char *name, unsigned int weak,
224 				   struct symbol *next)
225 {
226 	struct symbol *s = NOFAIL(malloc(sizeof(*s) + strlen(name) + 1));
227 
228 	memset(s, 0, sizeof(*s));
229 	strcpy(s->name, name);
230 	s->weak = weak;
231 	s->next = next;
232 	s->is_static = 1;
233 	return s;
234 }
235 
236 /* For the hash of exported symbols */
new_symbol(const char * name,struct module * module,enum export export)237 static struct symbol *new_symbol(const char *name, struct module *module,
238 				 enum export export)
239 {
240 	unsigned int hash;
241 
242 	hash = tdb_hash(name) % SYMBOL_HASH_SIZE;
243 	symbolhash[hash] = alloc_symbol(name, 0, symbolhash[hash]);
244 
245 	return symbolhash[hash];
246 }
247 
find_symbol(const char * name)248 static struct symbol *find_symbol(const char *name)
249 {
250 	struct symbol *s;
251 
252 	/* For our purposes, .foo matches foo.  PPC64 needs this. */
253 	if (name[0] == '.')
254 		name++;
255 
256 	for (s = symbolhash[tdb_hash(name) % SYMBOL_HASH_SIZE]; s; s = s->next) {
257 		if (strcmp(s->name, name) == 0)
258 			return s;
259 	}
260 	return NULL;
261 }
262 
contains_namespace(struct namespace_list * list,const char * namespace)263 static bool contains_namespace(struct namespace_list *list,
264 			       const char *namespace)
265 {
266 	for (; list; list = list->next)
267 		if (!strcmp(list->namespace, namespace))
268 			return true;
269 
270 	return false;
271 }
272 
add_namespace(struct namespace_list ** list,const char * namespace)273 static void add_namespace(struct namespace_list **list, const char *namespace)
274 {
275 	struct namespace_list *ns_entry;
276 
277 	if (!contains_namespace(*list, namespace)) {
278 		ns_entry = NOFAIL(malloc(sizeof(struct namespace_list) +
279 					 strlen(namespace) + 1));
280 		strcpy(ns_entry->namespace, namespace);
281 		ns_entry->next = *list;
282 		*list = ns_entry;
283 	}
284 }
285 
module_imports_namespace(struct module * module,const char * namespace)286 static bool module_imports_namespace(struct module *module,
287 				     const char *namespace)
288 {
289 	return contains_namespace(module->imported_namespaces, namespace);
290 }
291 
292 static const struct {
293 	const char *str;
294 	enum export export;
295 } export_list[] = {
296 	{ .str = "EXPORT_SYMBOL",            .export = export_plain },
297 	{ .str = "EXPORT_UNUSED_SYMBOL",     .export = export_unused },
298 	{ .str = "EXPORT_SYMBOL_GPL",        .export = export_gpl },
299 	{ .str = "EXPORT_UNUSED_SYMBOL_GPL", .export = export_unused_gpl },
300 	{ .str = "EXPORT_SYMBOL_GPL_FUTURE", .export = export_gpl_future },
301 	{ .str = "(unknown)",                .export = export_unknown },
302 };
303 
304 
export_str(enum export ex)305 static const char *export_str(enum export ex)
306 {
307 	return export_list[ex].str;
308 }
309 
export_no(const char * s)310 static enum export export_no(const char *s)
311 {
312 	int i;
313 
314 	if (!s)
315 		return export_unknown;
316 	for (i = 0; export_list[i].export != export_unknown; i++) {
317 		if (strcmp(export_list[i].str, s) == 0)
318 			return export_list[i].export;
319 	}
320 	return export_unknown;
321 }
322 
sym_get_data_by_offset(const struct elf_info * info,unsigned int secindex,unsigned long offset)323 static void *sym_get_data_by_offset(const struct elf_info *info,
324 				    unsigned int secindex, unsigned long offset)
325 {
326 	Elf_Shdr *sechdr = &info->sechdrs[secindex];
327 
328 	if (info->hdr->e_type != ET_REL)
329 		offset -= sechdr->sh_addr;
330 
331 	return (void *)info->hdr + sechdr->sh_offset + offset;
332 }
333 
sym_get_data(const struct elf_info * info,const Elf_Sym * sym)334 static void *sym_get_data(const struct elf_info *info, const Elf_Sym *sym)
335 {
336 	return sym_get_data_by_offset(info, get_secindex(info, sym),
337 				      sym->st_value);
338 }
339 
sech_name(const struct elf_info * info,Elf_Shdr * sechdr)340 static const char *sech_name(const struct elf_info *info, Elf_Shdr *sechdr)
341 {
342 	return sym_get_data_by_offset(info, info->secindex_strings,
343 				      sechdr->sh_name);
344 }
345 
sec_name(const struct elf_info * info,int secindex)346 static const char *sec_name(const struct elf_info *info, int secindex)
347 {
348 	return sech_name(info, &info->sechdrs[secindex]);
349 }
350 
351 #define strstarts(str, prefix) (strncmp(str, prefix, strlen(prefix)) == 0)
352 
export_from_secname(struct elf_info * elf,unsigned int sec)353 static enum export export_from_secname(struct elf_info *elf, unsigned int sec)
354 {
355 	const char *secname = sec_name(elf, sec);
356 
357 	if (strstarts(secname, "___ksymtab+"))
358 		return export_plain;
359 	else if (strstarts(secname, "___ksymtab_unused+"))
360 		return export_unused;
361 	else if (strstarts(secname, "___ksymtab_gpl+"))
362 		return export_gpl;
363 	else if (strstarts(secname, "___ksymtab_unused_gpl+"))
364 		return export_unused_gpl;
365 	else if (strstarts(secname, "___ksymtab_gpl_future+"))
366 		return export_gpl_future;
367 	else
368 		return export_unknown;
369 }
370 
export_from_sec(struct elf_info * elf,unsigned int sec)371 static enum export export_from_sec(struct elf_info *elf, unsigned int sec)
372 {
373 	if (sec == elf->export_sec)
374 		return export_plain;
375 	else if (sec == elf->export_unused_sec)
376 		return export_unused;
377 	else if (sec == elf->export_gpl_sec)
378 		return export_gpl;
379 	else if (sec == elf->export_unused_gpl_sec)
380 		return export_unused_gpl;
381 	else if (sec == elf->export_gpl_future_sec)
382 		return export_gpl_future;
383 	else
384 		return export_unknown;
385 }
386 
namespace_from_kstrtabns(const struct elf_info * info,const Elf_Sym * sym)387 static const char *namespace_from_kstrtabns(const struct elf_info *info,
388 					    const Elf_Sym *sym)
389 {
390 	const char *value = sym_get_data(info, sym);
391 	return value[0] ? value : NULL;
392 }
393 
sym_update_namespace(const char * symname,const char * namespace)394 static void sym_update_namespace(const char *symname, const char *namespace)
395 {
396 	struct symbol *s = find_symbol(symname);
397 
398 	/*
399 	 * That symbol should have been created earlier and thus this is
400 	 * actually an assertion.
401 	 */
402 	if (!s) {
403 		error("Could not update namespace(%s) for symbol %s\n",
404 		      namespace, symname);
405 		return;
406 	}
407 
408 	free(s->namespace);
409 	s->namespace =
410 		namespace && namespace[0] ? NOFAIL(strdup(namespace)) : NULL;
411 }
412 
413 /**
414  * Add an exported symbol - it may have already been added without a
415  * CRC, in this case just update the CRC
416  **/
sym_add_exported(const char * name,struct module * mod,enum export export)417 static struct symbol *sym_add_exported(const char *name, struct module *mod,
418 				       enum export export)
419 {
420 	struct symbol *s = find_symbol(name);
421 
422 	if (!s) {
423 		s = new_symbol(name, mod, export);
424 	} else if (!external_module || s->module->is_vmlinux ||
425 		   s->module == mod) {
426 		fatal("%s: '%s' exported twice. Previous export was in %s%s\n",
427 		      mod->name, name, s->module->name,
428 		      s->module->is_vmlinux ? "" : ".ko");
429 	}
430 
431 	s->module = mod;
432 	s->export    = export;
433 	return s;
434 }
435 
sym_set_crc(const char * name,unsigned int crc)436 static void sym_set_crc(const char *name, unsigned int crc)
437 {
438 	struct symbol *s = find_symbol(name);
439 
440 	/*
441 	 * Ignore stand-alone __crc_*, which might be auto-generated symbols
442 	 * such as __*_veneer in ARM ELF.
443 	 */
444 	if (!s)
445 		return;
446 
447 	s->crc = crc;
448 	s->crc_valid = 1;
449 }
450 
grab_file(const char * filename,size_t * size)451 static void *grab_file(const char *filename, size_t *size)
452 {
453 	struct stat st;
454 	void *map = MAP_FAILED;
455 	int fd;
456 
457 	fd = open(filename, O_RDONLY);
458 	if (fd < 0)
459 		return NULL;
460 	if (fstat(fd, &st))
461 		goto failed;
462 
463 	*size = st.st_size;
464 	map = mmap(NULL, *size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
465 
466 failed:
467 	close(fd);
468 	if (map == MAP_FAILED)
469 		return NULL;
470 	return map;
471 }
472 
release_file(void * file,size_t size)473 static void release_file(void *file, size_t size)
474 {
475 	munmap(file, size);
476 }
477 
parse_elf(struct elf_info * info,const char * filename)478 static int parse_elf(struct elf_info *info, const char *filename)
479 {
480 	unsigned int i;
481 	Elf_Ehdr *hdr;
482 	Elf_Shdr *sechdrs;
483 	Elf_Sym  *sym;
484 	const char *secstrings;
485 	unsigned int symtab_idx = ~0U, symtab_shndx_idx = ~0U;
486 
487 	hdr = grab_file(filename, &info->size);
488 	if (!hdr) {
489 		if (ignore_missing_files) {
490 			fprintf(stderr, "%s: %s (ignored)\n", filename,
491 				strerror(errno));
492 			return 0;
493 		}
494 		perror(filename);
495 		exit(1);
496 	}
497 	info->hdr = hdr;
498 	if (info->size < sizeof(*hdr)) {
499 		/* file too small, assume this is an empty .o file */
500 		return 0;
501 	}
502 	/* Is this a valid ELF file? */
503 	if ((hdr->e_ident[EI_MAG0] != ELFMAG0) ||
504 	    (hdr->e_ident[EI_MAG1] != ELFMAG1) ||
505 	    (hdr->e_ident[EI_MAG2] != ELFMAG2) ||
506 	    (hdr->e_ident[EI_MAG3] != ELFMAG3)) {
507 		/* Not an ELF file - silently ignore it */
508 		return 0;
509 	}
510 	/* Fix endianness in ELF header */
511 	hdr->e_type      = TO_NATIVE(hdr->e_type);
512 	hdr->e_machine   = TO_NATIVE(hdr->e_machine);
513 	hdr->e_version   = TO_NATIVE(hdr->e_version);
514 	hdr->e_entry     = TO_NATIVE(hdr->e_entry);
515 	hdr->e_phoff     = TO_NATIVE(hdr->e_phoff);
516 	hdr->e_shoff     = TO_NATIVE(hdr->e_shoff);
517 	hdr->e_flags     = TO_NATIVE(hdr->e_flags);
518 	hdr->e_ehsize    = TO_NATIVE(hdr->e_ehsize);
519 	hdr->e_phentsize = TO_NATIVE(hdr->e_phentsize);
520 	hdr->e_phnum     = TO_NATIVE(hdr->e_phnum);
521 	hdr->e_shentsize = TO_NATIVE(hdr->e_shentsize);
522 	hdr->e_shnum     = TO_NATIVE(hdr->e_shnum);
523 	hdr->e_shstrndx  = TO_NATIVE(hdr->e_shstrndx);
524 	sechdrs = (void *)hdr + hdr->e_shoff;
525 	info->sechdrs = sechdrs;
526 
527 	/* Check if file offset is correct */
528 	if (hdr->e_shoff > info->size) {
529 		fatal("section header offset=%lu in file '%s' is bigger than filesize=%zu\n",
530 		      (unsigned long)hdr->e_shoff, filename, info->size);
531 		return 0;
532 	}
533 
534 	if (hdr->e_shnum == SHN_UNDEF) {
535 		/*
536 		 * There are more than 64k sections,
537 		 * read count from .sh_size.
538 		 */
539 		info->num_sections = TO_NATIVE(sechdrs[0].sh_size);
540 	}
541 	else {
542 		info->num_sections = hdr->e_shnum;
543 	}
544 	if (hdr->e_shstrndx == SHN_XINDEX) {
545 		info->secindex_strings = TO_NATIVE(sechdrs[0].sh_link);
546 	}
547 	else {
548 		info->secindex_strings = hdr->e_shstrndx;
549 	}
550 
551 	/* Fix endianness in section headers */
552 	for (i = 0; i < info->num_sections; i++) {
553 		sechdrs[i].sh_name      = TO_NATIVE(sechdrs[i].sh_name);
554 		sechdrs[i].sh_type      = TO_NATIVE(sechdrs[i].sh_type);
555 		sechdrs[i].sh_flags     = TO_NATIVE(sechdrs[i].sh_flags);
556 		sechdrs[i].sh_addr      = TO_NATIVE(sechdrs[i].sh_addr);
557 		sechdrs[i].sh_offset    = TO_NATIVE(sechdrs[i].sh_offset);
558 		sechdrs[i].sh_size      = TO_NATIVE(sechdrs[i].sh_size);
559 		sechdrs[i].sh_link      = TO_NATIVE(sechdrs[i].sh_link);
560 		sechdrs[i].sh_info      = TO_NATIVE(sechdrs[i].sh_info);
561 		sechdrs[i].sh_addralign = TO_NATIVE(sechdrs[i].sh_addralign);
562 		sechdrs[i].sh_entsize   = TO_NATIVE(sechdrs[i].sh_entsize);
563 	}
564 	/* Find symbol table. */
565 	secstrings = (void *)hdr + sechdrs[info->secindex_strings].sh_offset;
566 	for (i = 1; i < info->num_sections; i++) {
567 		const char *secname;
568 		int nobits = sechdrs[i].sh_type == SHT_NOBITS;
569 
570 		if (!nobits && sechdrs[i].sh_offset > info->size) {
571 			fatal("%s is truncated. sechdrs[i].sh_offset=%lu > "
572 			      "sizeof(*hrd)=%zu\n", filename,
573 			      (unsigned long)sechdrs[i].sh_offset,
574 			      sizeof(*hdr));
575 			return 0;
576 		}
577 		secname = secstrings + sechdrs[i].sh_name;
578 		if (strcmp(secname, ".modinfo") == 0) {
579 			if (nobits)
580 				fatal("%s has NOBITS .modinfo\n", filename);
581 			info->modinfo = (void *)hdr + sechdrs[i].sh_offset;
582 			info->modinfo_len = sechdrs[i].sh_size;
583 		} else if (strcmp(secname, "__ksymtab") == 0)
584 			info->export_sec = i;
585 		else if (strcmp(secname, "__ksymtab_unused") == 0)
586 			info->export_unused_sec = i;
587 		else if (strcmp(secname, "__ksymtab_gpl") == 0)
588 			info->export_gpl_sec = i;
589 		else if (strcmp(secname, "__ksymtab_unused_gpl") == 0)
590 			info->export_unused_gpl_sec = i;
591 		else if (strcmp(secname, "__ksymtab_gpl_future") == 0)
592 			info->export_gpl_future_sec = i;
593 
594 		if (sechdrs[i].sh_type == SHT_SYMTAB) {
595 			unsigned int sh_link_idx;
596 			symtab_idx = i;
597 			info->symtab_start = (void *)hdr +
598 			    sechdrs[i].sh_offset;
599 			info->symtab_stop  = (void *)hdr +
600 			    sechdrs[i].sh_offset + sechdrs[i].sh_size;
601 			sh_link_idx = sechdrs[i].sh_link;
602 			info->strtab       = (void *)hdr +
603 			    sechdrs[sh_link_idx].sh_offset;
604 		}
605 
606 		/* 32bit section no. table? ("more than 64k sections") */
607 		if (sechdrs[i].sh_type == SHT_SYMTAB_SHNDX) {
608 			symtab_shndx_idx = i;
609 			info->symtab_shndx_start = (void *)hdr +
610 			    sechdrs[i].sh_offset;
611 			info->symtab_shndx_stop  = (void *)hdr +
612 			    sechdrs[i].sh_offset + sechdrs[i].sh_size;
613 		}
614 	}
615 	if (!info->symtab_start)
616 		fatal("%s has no symtab?\n", filename);
617 
618 	/* Fix endianness in symbols */
619 	for (sym = info->symtab_start; sym < info->symtab_stop; sym++) {
620 		sym->st_shndx = TO_NATIVE(sym->st_shndx);
621 		sym->st_name  = TO_NATIVE(sym->st_name);
622 		sym->st_value = TO_NATIVE(sym->st_value);
623 		sym->st_size  = TO_NATIVE(sym->st_size);
624 	}
625 
626 	if (symtab_shndx_idx != ~0U) {
627 		Elf32_Word *p;
628 		if (symtab_idx != sechdrs[symtab_shndx_idx].sh_link)
629 			fatal("%s: SYMTAB_SHNDX has bad sh_link: %u!=%u\n",
630 			      filename, sechdrs[symtab_shndx_idx].sh_link,
631 			      symtab_idx);
632 		/* Fix endianness */
633 		for (p = info->symtab_shndx_start; p < info->symtab_shndx_stop;
634 		     p++)
635 			*p = TO_NATIVE(*p);
636 	}
637 
638 	return 1;
639 }
640 
parse_elf_finish(struct elf_info * info)641 static void parse_elf_finish(struct elf_info *info)
642 {
643 	release_file(info->hdr, info->size);
644 }
645 
ignore_undef_symbol(struct elf_info * info,const char * symname)646 static int ignore_undef_symbol(struct elf_info *info, const char *symname)
647 {
648 	/* ignore __this_module, it will be resolved shortly */
649 	if (strcmp(symname, "__this_module") == 0)
650 		return 1;
651 	/* ignore global offset table */
652 	if (strcmp(symname, "_GLOBAL_OFFSET_TABLE_") == 0)
653 		return 1;
654 	if (info->hdr->e_machine == EM_PPC)
655 		/* Special register function linked on all modules during final link of .ko */
656 		if (strstarts(symname, "_restgpr_") ||
657 		    strstarts(symname, "_savegpr_") ||
658 		    strstarts(symname, "_rest32gpr_") ||
659 		    strstarts(symname, "_save32gpr_") ||
660 		    strstarts(symname, "_restvr_") ||
661 		    strstarts(symname, "_savevr_"))
662 			return 1;
663 	if (info->hdr->e_machine == EM_PPC64)
664 		/* Special register function linked on all modules during final link of .ko */
665 		if (strstarts(symname, "_restgpr0_") ||
666 		    strstarts(symname, "_savegpr0_") ||
667 		    strstarts(symname, "_restvr_") ||
668 		    strstarts(symname, "_savevr_") ||
669 		    strcmp(symname, ".TOC.") == 0)
670 			return 1;
671 	/* Do not ignore this symbol */
672 	return 0;
673 }
674 
handle_modversion(const struct module * mod,const struct elf_info * info,const Elf_Sym * sym,const char * symname)675 static void handle_modversion(const struct module *mod,
676 			      const struct elf_info *info,
677 			      const Elf_Sym *sym, const char *symname)
678 {
679 	unsigned int crc;
680 
681 	if (sym->st_shndx == SHN_UNDEF) {
682 		warn("EXPORT symbol \"%s\" [%s%s] version generation failed, symbol will not be versioned.\n",
683 		     symname, mod->name, mod->is_vmlinux ? "" : ".ko");
684 		return;
685 	}
686 
687 	if (sym->st_shndx == SHN_ABS) {
688 		crc = sym->st_value;
689 	} else {
690 		unsigned int *crcp;
691 
692 		/* symbol points to the CRC in the ELF object */
693 		crcp = sym_get_data(info, sym);
694 		crc = TO_NATIVE(*crcp);
695 	}
696 	sym_set_crc(symname, crc);
697 }
698 
handle_symbol(struct module * mod,struct elf_info * info,const Elf_Sym * sym,const char * symname)699 static void handle_symbol(struct module *mod, struct elf_info *info,
700 			  const Elf_Sym *sym, const char *symname)
701 {
702 	enum export export;
703 	const char *name;
704 
705 	if (strstarts(symname, "__ksymtab"))
706 		export = export_from_secname(info, get_secindex(info, sym));
707 	else
708 		export = export_from_sec(info, get_secindex(info, sym));
709 
710 	switch (sym->st_shndx) {
711 	case SHN_COMMON:
712 		if (strstarts(symname, "__gnu_lto_")) {
713 			/* Should warn here, but modpost runs before the linker */
714 		} else
715 			warn("\"%s\" [%s] is COMMON symbol\n", symname, mod->name);
716 		break;
717 	case SHN_UNDEF:
718 		/* undefined symbol */
719 		if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL &&
720 		    ELF_ST_BIND(sym->st_info) != STB_WEAK)
721 			break;
722 		if (ignore_undef_symbol(info, symname))
723 			break;
724 		if (info->hdr->e_machine == EM_SPARC ||
725 		    info->hdr->e_machine == EM_SPARCV9) {
726 			/* Ignore register directives. */
727 			if (ELF_ST_TYPE(sym->st_info) == STT_SPARC_REGISTER)
728 				break;
729 			if (symname[0] == '.') {
730 				char *munged = NOFAIL(strdup(symname));
731 				munged[0] = '_';
732 				munged[1] = toupper(munged[1]);
733 				symname = munged;
734 			}
735 		}
736 
737 		mod->unres = alloc_symbol(symname,
738 					  ELF_ST_BIND(sym->st_info) == STB_WEAK,
739 					  mod->unres);
740 		break;
741 	default:
742 		/* All exported symbols */
743 		if (strstarts(symname, "__ksymtab_")) {
744 			name = symname + strlen("__ksymtab_");
745 			sym_add_exported(name, mod, export);
746 		}
747 		if (strcmp(symname, "init_module") == 0)
748 			mod->has_init = 1;
749 		if (strcmp(symname, "cleanup_module") == 0)
750 			mod->has_cleanup = 1;
751 		break;
752 	}
753 }
754 
755 /**
756  * Parse tag=value strings from .modinfo section
757  **/
next_string(char * string,unsigned long * secsize)758 static char *next_string(char *string, unsigned long *secsize)
759 {
760 	/* Skip non-zero chars */
761 	while (string[0]) {
762 		string++;
763 		if ((*secsize)-- <= 1)
764 			return NULL;
765 	}
766 
767 	/* Skip any zero padding. */
768 	while (!string[0]) {
769 		string++;
770 		if ((*secsize)-- <= 1)
771 			return NULL;
772 	}
773 	return string;
774 }
775 
get_next_modinfo(struct elf_info * info,const char * tag,char * prev)776 static char *get_next_modinfo(struct elf_info *info, const char *tag,
777 			      char *prev)
778 {
779 	char *p;
780 	unsigned int taglen = strlen(tag);
781 	char *modinfo = info->modinfo;
782 	unsigned long size = info->modinfo_len;
783 
784 	if (prev) {
785 		size -= prev - modinfo;
786 		modinfo = next_string(prev, &size);
787 	}
788 
789 	for (p = modinfo; p; p = next_string(p, &size)) {
790 		if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
791 			return p + taglen + 1;
792 	}
793 	return NULL;
794 }
795 
get_modinfo(struct elf_info * info,const char * tag)796 static char *get_modinfo(struct elf_info *info, const char *tag)
797 
798 {
799 	return get_next_modinfo(info, tag, NULL);
800 }
801 
802 /**
803  * Test if string s ends in string sub
804  * return 0 if match
805  **/
strrcmp(const char * s,const char * sub)806 static int strrcmp(const char *s, const char *sub)
807 {
808 	int slen, sublen;
809 
810 	if (!s || !sub)
811 		return 1;
812 
813 	slen = strlen(s);
814 	sublen = strlen(sub);
815 
816 	if ((slen == 0) || (sublen == 0))
817 		return 1;
818 
819 	if (sublen > slen)
820 		return 1;
821 
822 	return memcmp(s + slen - sublen, sub, sublen);
823 }
824 
sym_name(struct elf_info * elf,Elf_Sym * sym)825 static const char *sym_name(struct elf_info *elf, Elf_Sym *sym)
826 {
827 	if (sym)
828 		return elf->strtab + sym->st_name;
829 	else
830 		return "(unknown)";
831 }
832 
833 /* The pattern is an array of simple patterns.
834  * "foo" will match an exact string equal to "foo"
835  * "*foo" will match a string that ends with "foo"
836  * "foo*" will match a string that begins with "foo"
837  * "*foo*" will match a string that contains "foo"
838  */
match(const char * sym,const char * const pat[])839 static int match(const char *sym, const char * const pat[])
840 {
841 	const char *p;
842 	while (*pat) {
843 		p = *pat++;
844 		const char *endp = p + strlen(p) - 1;
845 
846 		/* "*foo*" */
847 		if (*p == '*' && *endp == '*') {
848 			char *bare = NOFAIL(strndup(p + 1, strlen(p) - 2));
849 			char *here = strstr(sym, bare);
850 
851 			free(bare);
852 			if (here != NULL)
853 				return 1;
854 		}
855 		/* "*foo" */
856 		else if (*p == '*') {
857 			if (strrcmp(sym, p + 1) == 0)
858 				return 1;
859 		}
860 		/* "foo*" */
861 		else if (*endp == '*') {
862 			if (strncmp(sym, p, strlen(p) - 1) == 0)
863 				return 1;
864 		}
865 		/* no wildcards */
866 		else {
867 			if (strcmp(p, sym) == 0)
868 				return 1;
869 		}
870 	}
871 	/* no match */
872 	return 0;
873 }
874 
875 /* sections that we do not want to do full section mismatch check on */
876 static const char *const section_white_list[] =
877 {
878 	".comment*",
879 	".debug*",
880 	".cranges",		/* sh64 */
881 	".zdebug*",		/* Compressed debug sections. */
882 	".GCC.command.line",	/* record-gcc-switches */
883 	".mdebug*",        /* alpha, score, mips etc. */
884 	".pdr",            /* alpha, score, mips etc. */
885 	".stab*",
886 	".note*",
887 	".got*",
888 	".toc*",
889 	".xt.prop",				 /* xtensa */
890 	".xt.lit",         /* xtensa */
891 	".arcextmap*",			/* arc */
892 	".gnu.linkonce.arcext*",	/* arc : modules */
893 	".cmem*",			/* EZchip */
894 	".fmt_slot*",			/* EZchip */
895 	".gnu.lto*",
896 	".discard.*",
897 	NULL
898 };
899 
900 /*
901  * This is used to find sections missing the SHF_ALLOC flag.
902  * The cause of this is often a section specified in assembler
903  * without "ax" / "aw".
904  */
check_section(const char * modname,struct elf_info * elf,Elf_Shdr * sechdr)905 static void check_section(const char *modname, struct elf_info *elf,
906 			  Elf_Shdr *sechdr)
907 {
908 	const char *sec = sech_name(elf, sechdr);
909 
910 	if (sechdr->sh_type == SHT_PROGBITS &&
911 	    !(sechdr->sh_flags & SHF_ALLOC) &&
912 	    !match(sec, section_white_list)) {
913 		warn("%s (%s): unexpected non-allocatable section.\n"
914 		     "Did you forget to use \"ax\"/\"aw\" in a .S file?\n"
915 		     "Note that for example <linux/init.h> contains\n"
916 		     "section definitions for use in .S files.\n\n",
917 		     modname, sec);
918 	}
919 }
920 
921 
922 
923 #define ALL_INIT_DATA_SECTIONS \
924 	".init.setup", ".init.rodata", ".meminit.rodata", \
925 	".init.data", ".meminit.data"
926 #define ALL_EXIT_DATA_SECTIONS \
927 	".exit.data", ".memexit.data"
928 
929 #define ALL_INIT_TEXT_SECTIONS \
930 	".init.text", ".meminit.text"
931 #define ALL_EXIT_TEXT_SECTIONS \
932 	".exit.text", ".memexit.text"
933 
934 #define ALL_PCI_INIT_SECTIONS	\
935 	".pci_fixup_early", ".pci_fixup_header", ".pci_fixup_final", \
936 	".pci_fixup_enable", ".pci_fixup_resume", \
937 	".pci_fixup_resume_early", ".pci_fixup_suspend"
938 
939 #define ALL_XXXINIT_SECTIONS MEM_INIT_SECTIONS
940 #define ALL_XXXEXIT_SECTIONS MEM_EXIT_SECTIONS
941 
942 #define ALL_INIT_SECTIONS INIT_SECTIONS, ALL_XXXINIT_SECTIONS
943 #define ALL_EXIT_SECTIONS EXIT_SECTIONS, ALL_XXXEXIT_SECTIONS
944 
945 #define DATA_SECTIONS ".data", ".data.rel"
946 #define TEXT_SECTIONS ".text", ".text.unlikely", ".sched.text", \
947 		".kprobes.text", ".cpuidle.text", ".noinstr.text"
948 #define OTHER_TEXT_SECTIONS ".ref.text", ".head.text", ".spinlock.text", \
949 		".fixup", ".entry.text", ".exception.text", ".text.*", \
950 		".coldtext"
951 
952 #define INIT_SECTIONS      ".init.*"
953 #define MEM_INIT_SECTIONS  ".meminit.*"
954 
955 #define EXIT_SECTIONS      ".exit.*"
956 #define MEM_EXIT_SECTIONS  ".memexit.*"
957 
958 #define ALL_TEXT_SECTIONS  ALL_INIT_TEXT_SECTIONS, ALL_EXIT_TEXT_SECTIONS, \
959 		TEXT_SECTIONS, OTHER_TEXT_SECTIONS
960 
961 /* init data sections */
962 static const char *const init_data_sections[] =
963 	{ ALL_INIT_DATA_SECTIONS, NULL };
964 
965 /* all init sections */
966 static const char *const init_sections[] = { ALL_INIT_SECTIONS, NULL };
967 
968 /* All init and exit sections (code + data) */
969 static const char *const init_exit_sections[] =
970 	{ALL_INIT_SECTIONS, ALL_EXIT_SECTIONS, NULL };
971 
972 /* all text sections */
973 static const char *const text_sections[] = { ALL_TEXT_SECTIONS, NULL };
974 
975 /* data section */
976 static const char *const data_sections[] = { DATA_SECTIONS, NULL };
977 
978 
979 /* symbols in .data that may refer to init/exit sections */
980 #define DEFAULT_SYMBOL_WHITE_LIST					\
981 	"*driver",							\
982 	"*_template", /* scsi uses *_template a lot */			\
983 	"*_timer",    /* arm uses ops structures named _timer a lot */	\
984 	"*_sht",      /* scsi also used *_sht to some extent */		\
985 	"*_ops",							\
986 	"*_probe",							\
987 	"*_probe_one",							\
988 	"*_console"
989 
990 static const char *const head_sections[] = { ".head.text*", NULL };
991 static const char *const linker_symbols[] =
992 	{ "__init_begin", "_sinittext", "_einittext", NULL };
993 static const char *const optim_symbols[] = { "*.constprop.*", NULL };
994 
995 enum mismatch {
996 	TEXT_TO_ANY_INIT,
997 	DATA_TO_ANY_INIT,
998 	TEXT_TO_ANY_EXIT,
999 	DATA_TO_ANY_EXIT,
1000 	XXXINIT_TO_SOME_INIT,
1001 	XXXEXIT_TO_SOME_EXIT,
1002 	ANY_INIT_TO_ANY_EXIT,
1003 	ANY_EXIT_TO_ANY_INIT,
1004 	EXPORT_TO_INIT_EXIT,
1005 	EXTABLE_TO_NON_TEXT,
1006 };
1007 
1008 /**
1009  * Describe how to match sections on different criterias:
1010  *
1011  * @fromsec: Array of sections to be matched.
1012  *
1013  * @bad_tosec: Relocations applied to a section in @fromsec to a section in
1014  * this array is forbidden (black-list).  Can be empty.
1015  *
1016  * @good_tosec: Relocations applied to a section in @fromsec must be
1017  * targetting sections in this array (white-list).  Can be empty.
1018  *
1019  * @mismatch: Type of mismatch.
1020  *
1021  * @symbol_white_list: Do not match a relocation to a symbol in this list
1022  * even if it is targetting a section in @bad_to_sec.
1023  *
1024  * @handler: Specific handler to call when a match is found.  If NULL,
1025  * default_mismatch_handler() will be called.
1026  *
1027  */
1028 struct sectioncheck {
1029 	const char *fromsec[20];
1030 	const char *bad_tosec[20];
1031 	const char *good_tosec[20];
1032 	enum mismatch mismatch;
1033 	const char *symbol_white_list[20];
1034 	void (*handler)(const char *modname, struct elf_info *elf,
1035 			const struct sectioncheck* const mismatch,
1036 			Elf_Rela *r, Elf_Sym *sym, const char *fromsec);
1037 
1038 };
1039 
1040 static void extable_mismatch_handler(const char *modname, struct elf_info *elf,
1041 				     const struct sectioncheck* const mismatch,
1042 				     Elf_Rela *r, Elf_Sym *sym,
1043 				     const char *fromsec);
1044 
1045 static const struct sectioncheck sectioncheck[] = {
1046 /* Do not reference init/exit code/data from
1047  * normal code and data
1048  */
1049 {
1050 	.fromsec = { TEXT_SECTIONS, NULL },
1051 	.bad_tosec = { ALL_INIT_SECTIONS, NULL },
1052 	.mismatch = TEXT_TO_ANY_INIT,
1053 	.symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1054 },
1055 {
1056 	.fromsec = { DATA_SECTIONS, NULL },
1057 	.bad_tosec = { ALL_XXXINIT_SECTIONS, NULL },
1058 	.mismatch = DATA_TO_ANY_INIT,
1059 	.symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1060 },
1061 {
1062 	.fromsec = { DATA_SECTIONS, NULL },
1063 	.bad_tosec = { INIT_SECTIONS, NULL },
1064 	.mismatch = DATA_TO_ANY_INIT,
1065 	.symbol_white_list = {
1066 		"*_template", "*_timer", "*_sht", "*_ops",
1067 		"*_probe", "*_probe_one", "*_console", NULL
1068 	},
1069 },
1070 {
1071 	.fromsec = { TEXT_SECTIONS, NULL },
1072 	.bad_tosec = { ALL_EXIT_SECTIONS, NULL },
1073 	.mismatch = TEXT_TO_ANY_EXIT,
1074 	.symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1075 },
1076 {
1077 	.fromsec = { DATA_SECTIONS, NULL },
1078 	.bad_tosec = { ALL_EXIT_SECTIONS, NULL },
1079 	.mismatch = DATA_TO_ANY_EXIT,
1080 	.symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1081 },
1082 /* Do not reference init code/data from meminit code/data */
1083 {
1084 	.fromsec = { ALL_XXXINIT_SECTIONS, NULL },
1085 	.bad_tosec = { INIT_SECTIONS, NULL },
1086 	.mismatch = XXXINIT_TO_SOME_INIT,
1087 	.symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1088 },
1089 /* Do not reference exit code/data from memexit code/data */
1090 {
1091 	.fromsec = { ALL_XXXEXIT_SECTIONS, NULL },
1092 	.bad_tosec = { EXIT_SECTIONS, NULL },
1093 	.mismatch = XXXEXIT_TO_SOME_EXIT,
1094 	.symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1095 },
1096 /* Do not use exit code/data from init code */
1097 {
1098 	.fromsec = { ALL_INIT_SECTIONS, NULL },
1099 	.bad_tosec = { ALL_EXIT_SECTIONS, NULL },
1100 	.mismatch = ANY_INIT_TO_ANY_EXIT,
1101 	.symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1102 },
1103 /* Do not use init code/data from exit code */
1104 {
1105 	.fromsec = { ALL_EXIT_SECTIONS, NULL },
1106 	.bad_tosec = { ALL_INIT_SECTIONS, NULL },
1107 	.mismatch = ANY_EXIT_TO_ANY_INIT,
1108 	.symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1109 },
1110 {
1111 	.fromsec = { ALL_PCI_INIT_SECTIONS, NULL },
1112 	.bad_tosec = { INIT_SECTIONS, NULL },
1113 	.mismatch = ANY_INIT_TO_ANY_EXIT,
1114 	.symbol_white_list = { NULL },
1115 },
1116 /* Do not export init/exit functions or data */
1117 {
1118 	.fromsec = { "___ksymtab*", NULL },
1119 	.bad_tosec = { INIT_SECTIONS, EXIT_SECTIONS, NULL },
1120 	.mismatch = EXPORT_TO_INIT_EXIT,
1121 	.symbol_white_list = { DEFAULT_SYMBOL_WHITE_LIST, NULL },
1122 },
1123 {
1124 	.fromsec = { "__ex_table", NULL },
1125 	/* If you're adding any new black-listed sections in here, consider
1126 	 * adding a special 'printer' for them in scripts/check_extable.
1127 	 */
1128 	.bad_tosec = { ".altinstr_replacement", NULL },
1129 	.good_tosec = {ALL_TEXT_SECTIONS , NULL},
1130 	.mismatch = EXTABLE_TO_NON_TEXT,
1131 	.handler = extable_mismatch_handler,
1132 }
1133 };
1134 
section_mismatch(const char * fromsec,const char * tosec)1135 static const struct sectioncheck *section_mismatch(
1136 		const char *fromsec, const char *tosec)
1137 {
1138 	int i;
1139 	int elems = sizeof(sectioncheck) / sizeof(struct sectioncheck);
1140 	const struct sectioncheck *check = &sectioncheck[0];
1141 
1142 	/*
1143 	 * The target section could be the SHT_NUL section when we're
1144 	 * handling relocations to un-resolved symbols, trying to match it
1145 	 * doesn't make much sense and causes build failures on parisc
1146 	 * architectures.
1147 	 */
1148 	if (*tosec == '\0')
1149 		return NULL;
1150 
1151 	for (i = 0; i < elems; i++) {
1152 		if (match(fromsec, check->fromsec)) {
1153 			if (check->bad_tosec[0] && match(tosec, check->bad_tosec))
1154 				return check;
1155 			if (check->good_tosec[0] && !match(tosec, check->good_tosec))
1156 				return check;
1157 		}
1158 		check++;
1159 	}
1160 	return NULL;
1161 }
1162 
1163 /**
1164  * Whitelist to allow certain references to pass with no warning.
1165  *
1166  * Pattern 1:
1167  *   If a module parameter is declared __initdata and permissions=0
1168  *   then this is legal despite the warning generated.
1169  *   We cannot see value of permissions here, so just ignore
1170  *   this pattern.
1171  *   The pattern is identified by:
1172  *   tosec   = .init.data
1173  *   fromsec = .data*
1174  *   atsym   =__param*
1175  *
1176  * Pattern 1a:
1177  *   module_param_call() ops can refer to __init set function if permissions=0
1178  *   The pattern is identified by:
1179  *   tosec   = .init.text
1180  *   fromsec = .data*
1181  *   atsym   = __param_ops_*
1182  *
1183  * Pattern 2:
1184  *   Many drivers utilise a *driver container with references to
1185  *   add, remove, probe functions etc.
1186  *   the pattern is identified by:
1187  *   tosec   = init or exit section
1188  *   fromsec = data section
1189  *   atsym = *driver, *_template, *_sht, *_ops, *_probe,
1190  *           *probe_one, *_console, *_timer
1191  *
1192  * Pattern 3:
1193  *   Whitelist all references from .head.text to any init section
1194  *
1195  * Pattern 4:
1196  *   Some symbols belong to init section but still it is ok to reference
1197  *   these from non-init sections as these symbols don't have any memory
1198  *   allocated for them and symbol address and value are same. So even
1199  *   if init section is freed, its ok to reference those symbols.
1200  *   For ex. symbols marking the init section boundaries.
1201  *   This pattern is identified by
1202  *   refsymname = __init_begin, _sinittext, _einittext
1203  *
1204  * Pattern 5:
1205  *   GCC may optimize static inlines when fed constant arg(s) resulting
1206  *   in functions like cpumask_empty() -- generating an associated symbol
1207  *   cpumask_empty.constprop.3 that appears in the audit.  If the const that
1208  *   is passed in comes from __init, like say nmi_ipi_mask, we get a
1209  *   meaningless section warning.  May need to add isra symbols too...
1210  *   This pattern is identified by
1211  *   tosec   = init section
1212  *   fromsec = text section
1213  *   refsymname = *.constprop.*
1214  *
1215  * Pattern 6:
1216  *   Hide section mismatch warnings for ELF local symbols.  The goal
1217  *   is to eliminate false positive modpost warnings caused by
1218  *   compiler-generated ELF local symbol names such as ".LANCHOR1".
1219  *   Autogenerated symbol names bypass modpost's "Pattern 2"
1220  *   whitelisting, which relies on pattern-matching against symbol
1221  *   names to work.  (One situation where gcc can autogenerate ELF
1222  *   local symbols is when "-fsection-anchors" is used.)
1223  **/
secref_whitelist(const struct sectioncheck * mismatch,const char * fromsec,const char * fromsym,const char * tosec,const char * tosym)1224 static int secref_whitelist(const struct sectioncheck *mismatch,
1225 			    const char *fromsec, const char *fromsym,
1226 			    const char *tosec, const char *tosym)
1227 {
1228 	/* Check for pattern 1 */
1229 	if (match(tosec, init_data_sections) &&
1230 	    match(fromsec, data_sections) &&
1231 	    strstarts(fromsym, "__param"))
1232 		return 0;
1233 
1234 	/* Check for pattern 1a */
1235 	if (strcmp(tosec, ".init.text") == 0 &&
1236 	    match(fromsec, data_sections) &&
1237 	    strstarts(fromsym, "__param_ops_"))
1238 		return 0;
1239 
1240 	/* Check for pattern 2 */
1241 	if (match(tosec, init_exit_sections) &&
1242 	    match(fromsec, data_sections) &&
1243 	    match(fromsym, mismatch->symbol_white_list))
1244 		return 0;
1245 
1246 	/* Check for pattern 3 */
1247 	if (match(fromsec, head_sections) &&
1248 	    match(tosec, init_sections))
1249 		return 0;
1250 
1251 	/* Check for pattern 4 */
1252 	if (match(tosym, linker_symbols))
1253 		return 0;
1254 
1255 	/* Check for pattern 5 */
1256 	if (match(fromsec, text_sections) &&
1257 	    match(tosec, init_sections) &&
1258 	    match(fromsym, optim_symbols))
1259 		return 0;
1260 
1261 	/* Check for pattern 6 */
1262 	if (strstarts(fromsym, ".L"))
1263 		return 0;
1264 
1265 	return 1;
1266 }
1267 
is_arm_mapping_symbol(const char * str)1268 static inline int is_arm_mapping_symbol(const char *str)
1269 {
1270 	return str[0] == '$' &&
1271 	       (str[1] == 'a' || str[1] == 'd' || str[1] == 't' || str[1] == 'x')
1272 	       && (str[2] == '\0' || str[2] == '.');
1273 }
1274 
1275 /*
1276  * If there's no name there, ignore it; likewise, ignore it if it's
1277  * one of the magic symbols emitted used by current ARM tools.
1278  *
1279  * Otherwise if find_symbols_between() returns those symbols, they'll
1280  * fail the whitelist tests and cause lots of false alarms ... fixable
1281  * only by merging __exit and __init sections into __text, bloating
1282  * the kernel (which is especially evil on embedded platforms).
1283  */
is_valid_name(struct elf_info * elf,Elf_Sym * sym)1284 static inline int is_valid_name(struct elf_info *elf, Elf_Sym *sym)
1285 {
1286 	const char *name = elf->strtab + sym->st_name;
1287 
1288 	if (!name || !strlen(name))
1289 		return 0;
1290 	return !is_arm_mapping_symbol(name);
1291 }
1292 
1293 /**
1294  * Find symbol based on relocation record info.
1295  * In some cases the symbol supplied is a valid symbol so
1296  * return refsym. If st_name != 0 we assume this is a valid symbol.
1297  * In other cases the symbol needs to be looked up in the symbol table
1298  * based on section and address.
1299  *  **/
find_elf_symbol(struct elf_info * elf,Elf64_Sword addr,Elf_Sym * relsym)1300 static Elf_Sym *find_elf_symbol(struct elf_info *elf, Elf64_Sword addr,
1301 				Elf_Sym *relsym)
1302 {
1303 	Elf_Sym *sym;
1304 	Elf_Sym *near = NULL;
1305 	Elf64_Sword distance = 20;
1306 	Elf64_Sword d;
1307 	unsigned int relsym_secindex;
1308 
1309 	if (relsym->st_name != 0)
1310 		return relsym;
1311 
1312 	relsym_secindex = get_secindex(elf, relsym);
1313 	for (sym = elf->symtab_start; sym < elf->symtab_stop; sym++) {
1314 		if (get_secindex(elf, sym) != relsym_secindex)
1315 			continue;
1316 		if (ELF_ST_TYPE(sym->st_info) == STT_SECTION)
1317 			continue;
1318 		if (!is_valid_name(elf, sym))
1319 			continue;
1320 		if (sym->st_value == addr)
1321 			return sym;
1322 		/* Find a symbol nearby - addr are maybe negative */
1323 		d = sym->st_value - addr;
1324 		if (d < 0)
1325 			d = addr - sym->st_value;
1326 		if (d < distance) {
1327 			distance = d;
1328 			near = sym;
1329 		}
1330 	}
1331 	/* We need a close match */
1332 	if (distance < 20)
1333 		return near;
1334 	else
1335 		return NULL;
1336 }
1337 
1338 /*
1339  * Find symbols before or equal addr and after addr - in the section sec.
1340  * If we find two symbols with equal offset prefer one with a valid name.
1341  * The ELF format may have a better way to detect what type of symbol
1342  * it is, but this works for now.
1343  **/
find_elf_symbol2(struct elf_info * elf,Elf_Addr addr,const char * sec)1344 static Elf_Sym *find_elf_symbol2(struct elf_info *elf, Elf_Addr addr,
1345 				 const char *sec)
1346 {
1347 	Elf_Sym *sym;
1348 	Elf_Sym *near = NULL;
1349 	Elf_Addr distance = ~0;
1350 
1351 	for (sym = elf->symtab_start; sym < elf->symtab_stop; sym++) {
1352 		const char *symsec;
1353 
1354 		if (is_shndx_special(sym->st_shndx))
1355 			continue;
1356 		symsec = sec_name(elf, get_secindex(elf, sym));
1357 		if (strcmp(symsec, sec) != 0)
1358 			continue;
1359 		if (!is_valid_name(elf, sym))
1360 			continue;
1361 		if (sym->st_value <= addr) {
1362 			if ((addr - sym->st_value) < distance) {
1363 				distance = addr - sym->st_value;
1364 				near = sym;
1365 			} else if ((addr - sym->st_value) == distance) {
1366 				near = sym;
1367 			}
1368 		}
1369 	}
1370 	return near;
1371 }
1372 
1373 /*
1374  * Convert a section name to the function/data attribute
1375  * .init.text => __init
1376  * .memexitconst => __memconst
1377  * etc.
1378  *
1379  * The memory of returned value has been allocated on a heap. The user of this
1380  * method should free it after usage.
1381 */
sec2annotation(const char * s)1382 static char *sec2annotation(const char *s)
1383 {
1384 	if (match(s, init_exit_sections)) {
1385 		char *p = NOFAIL(malloc(20));
1386 		char *r = p;
1387 
1388 		*p++ = '_';
1389 		*p++ = '_';
1390 		if (*s == '.')
1391 			s++;
1392 		while (*s && *s != '.')
1393 			*p++ = *s++;
1394 		*p = '\0';
1395 		if (*s == '.')
1396 			s++;
1397 		if (strstr(s, "rodata") != NULL)
1398 			strcat(p, "const ");
1399 		else if (strstr(s, "data") != NULL)
1400 			strcat(p, "data ");
1401 		else
1402 			strcat(p, " ");
1403 		return r;
1404 	} else {
1405 		return NOFAIL(strdup(""));
1406 	}
1407 }
1408 
is_function(Elf_Sym * sym)1409 static int is_function(Elf_Sym *sym)
1410 {
1411 	if (sym)
1412 		return ELF_ST_TYPE(sym->st_info) == STT_FUNC;
1413 	else
1414 		return -1;
1415 }
1416 
print_section_list(const char * const list[20])1417 static void print_section_list(const char * const list[20])
1418 {
1419 	const char *const *s = list;
1420 
1421 	while (*s) {
1422 		fprintf(stderr, "%s", *s);
1423 		s++;
1424 		if (*s)
1425 			fprintf(stderr, ", ");
1426 	}
1427 	fprintf(stderr, "\n");
1428 }
1429 
get_pretty_name(int is_func,const char ** name,const char ** name_p)1430 static inline void get_pretty_name(int is_func, const char** name, const char** name_p)
1431 {
1432 	switch (is_func) {
1433 	case 0:	*name = "variable"; *name_p = ""; break;
1434 	case 1:	*name = "function"; *name_p = "()"; break;
1435 	default: *name = "(unknown reference)"; *name_p = ""; break;
1436 	}
1437 }
1438 
1439 /*
1440  * Print a warning about a section mismatch.
1441  * Try to find symbols near it so user can find it.
1442  * Check whitelist before warning - it may be a false positive.
1443  */
report_sec_mismatch(const char * modname,const struct sectioncheck * mismatch,const char * fromsec,unsigned long long fromaddr,const char * fromsym,int from_is_func,const char * tosec,const char * tosym,int to_is_func)1444 static void report_sec_mismatch(const char *modname,
1445 				const struct sectioncheck *mismatch,
1446 				const char *fromsec,
1447 				unsigned long long fromaddr,
1448 				const char *fromsym,
1449 				int from_is_func,
1450 				const char *tosec, const char *tosym,
1451 				int to_is_func)
1452 {
1453 	const char *from, *from_p;
1454 	const char *to, *to_p;
1455 	char *prl_from;
1456 	char *prl_to;
1457 
1458 	sec_mismatch_count++;
1459 
1460 	get_pretty_name(from_is_func, &from, &from_p);
1461 	get_pretty_name(to_is_func, &to, &to_p);
1462 
1463 	warn("%s(%s+0x%llx): Section mismatch in reference from the %s %s%s "
1464 	     "to the %s %s:%s%s\n",
1465 	     modname, fromsec, fromaddr, from, fromsym, from_p, to, tosec,
1466 	     tosym, to_p);
1467 
1468 	switch (mismatch->mismatch) {
1469 	case TEXT_TO_ANY_INIT:
1470 		prl_from = sec2annotation(fromsec);
1471 		prl_to = sec2annotation(tosec);
1472 		fprintf(stderr,
1473 		"The function %s%s() references\n"
1474 		"the %s %s%s%s.\n"
1475 		"This is often because %s lacks a %s\n"
1476 		"annotation or the annotation of %s is wrong.\n",
1477 		prl_from, fromsym,
1478 		to, prl_to, tosym, to_p,
1479 		fromsym, prl_to, tosym);
1480 		free(prl_from);
1481 		free(prl_to);
1482 		break;
1483 	case DATA_TO_ANY_INIT: {
1484 		prl_to = sec2annotation(tosec);
1485 		fprintf(stderr,
1486 		"The variable %s references\n"
1487 		"the %s %s%s%s\n"
1488 		"If the reference is valid then annotate the\n"
1489 		"variable with __init* or __refdata (see linux/init.h) "
1490 		"or name the variable:\n",
1491 		fromsym, to, prl_to, tosym, to_p);
1492 		print_section_list(mismatch->symbol_white_list);
1493 		free(prl_to);
1494 		break;
1495 	}
1496 	case TEXT_TO_ANY_EXIT:
1497 		prl_to = sec2annotation(tosec);
1498 		fprintf(stderr,
1499 		"The function %s() references a %s in an exit section.\n"
1500 		"Often the %s %s%s has valid usage outside the exit section\n"
1501 		"and the fix is to remove the %sannotation of %s.\n",
1502 		fromsym, to, to, tosym, to_p, prl_to, tosym);
1503 		free(prl_to);
1504 		break;
1505 	case DATA_TO_ANY_EXIT: {
1506 		prl_to = sec2annotation(tosec);
1507 		fprintf(stderr,
1508 		"The variable %s references\n"
1509 		"the %s %s%s%s\n"
1510 		"If the reference is valid then annotate the\n"
1511 		"variable with __exit* (see linux/init.h) or "
1512 		"name the variable:\n",
1513 		fromsym, to, prl_to, tosym, to_p);
1514 		print_section_list(mismatch->symbol_white_list);
1515 		free(prl_to);
1516 		break;
1517 	}
1518 	case XXXINIT_TO_SOME_INIT:
1519 	case XXXEXIT_TO_SOME_EXIT:
1520 		prl_from = sec2annotation(fromsec);
1521 		prl_to = sec2annotation(tosec);
1522 		fprintf(stderr,
1523 		"The %s %s%s%s references\n"
1524 		"a %s %s%s%s.\n"
1525 		"If %s is only used by %s then\n"
1526 		"annotate %s with a matching annotation.\n",
1527 		from, prl_from, fromsym, from_p,
1528 		to, prl_to, tosym, to_p,
1529 		tosym, fromsym, tosym);
1530 		free(prl_from);
1531 		free(prl_to);
1532 		break;
1533 	case ANY_INIT_TO_ANY_EXIT:
1534 		prl_from = sec2annotation(fromsec);
1535 		prl_to = sec2annotation(tosec);
1536 		fprintf(stderr,
1537 		"The %s %s%s%s references\n"
1538 		"a %s %s%s%s.\n"
1539 		"This is often seen when error handling "
1540 		"in the init function\n"
1541 		"uses functionality in the exit path.\n"
1542 		"The fix is often to remove the %sannotation of\n"
1543 		"%s%s so it may be used outside an exit section.\n",
1544 		from, prl_from, fromsym, from_p,
1545 		to, prl_to, tosym, to_p,
1546 		prl_to, tosym, to_p);
1547 		free(prl_from);
1548 		free(prl_to);
1549 		break;
1550 	case ANY_EXIT_TO_ANY_INIT:
1551 		prl_from = sec2annotation(fromsec);
1552 		prl_to = sec2annotation(tosec);
1553 		fprintf(stderr,
1554 		"The %s %s%s%s references\n"
1555 		"a %s %s%s%s.\n"
1556 		"This is often seen when error handling "
1557 		"in the exit function\n"
1558 		"uses functionality in the init path.\n"
1559 		"The fix is often to remove the %sannotation of\n"
1560 		"%s%s so it may be used outside an init section.\n",
1561 		from, prl_from, fromsym, from_p,
1562 		to, prl_to, tosym, to_p,
1563 		prl_to, tosym, to_p);
1564 		free(prl_from);
1565 		free(prl_to);
1566 		break;
1567 	case EXPORT_TO_INIT_EXIT:
1568 		prl_to = sec2annotation(tosec);
1569 		fprintf(stderr,
1570 		"The symbol %s is exported and annotated %s\n"
1571 		"Fix this by removing the %sannotation of %s "
1572 		"or drop the export.\n",
1573 		tosym, prl_to, prl_to, tosym);
1574 		free(prl_to);
1575 		break;
1576 	case EXTABLE_TO_NON_TEXT:
1577 		fatal("There's a special handler for this mismatch type, "
1578 		      "we should never get here.");
1579 		break;
1580 	}
1581 	fprintf(stderr, "\n");
1582 }
1583 
default_mismatch_handler(const char * modname,struct elf_info * elf,const struct sectioncheck * const mismatch,Elf_Rela * r,Elf_Sym * sym,const char * fromsec)1584 static void default_mismatch_handler(const char *modname, struct elf_info *elf,
1585 				     const struct sectioncheck* const mismatch,
1586 				     Elf_Rela *r, Elf_Sym *sym, const char *fromsec)
1587 {
1588 	const char *tosec;
1589 	Elf_Sym *to;
1590 	Elf_Sym *from;
1591 	const char *tosym;
1592 	const char *fromsym;
1593 
1594 	from = find_elf_symbol2(elf, r->r_offset, fromsec);
1595 	fromsym = sym_name(elf, from);
1596 
1597 	if (strstarts(fromsym, "reference___initcall"))
1598 		return;
1599 
1600 	tosec = sec_name(elf, get_secindex(elf, sym));
1601 	to = find_elf_symbol(elf, r->r_addend, sym);
1602 	tosym = sym_name(elf, to);
1603 
1604 	/* check whitelist - we may ignore it */
1605 	if (secref_whitelist(mismatch,
1606 			     fromsec, fromsym, tosec, tosym)) {
1607 		report_sec_mismatch(modname, mismatch,
1608 				    fromsec, r->r_offset, fromsym,
1609 				    is_function(from), tosec, tosym,
1610 				    is_function(to));
1611 	}
1612 }
1613 
is_executable_section(struct elf_info * elf,unsigned int section_index)1614 static int is_executable_section(struct elf_info* elf, unsigned int section_index)
1615 {
1616 	if (section_index > elf->num_sections)
1617 		fatal("section_index is outside elf->num_sections!\n");
1618 
1619 	return ((elf->sechdrs[section_index].sh_flags & SHF_EXECINSTR) == SHF_EXECINSTR);
1620 }
1621 
1622 /*
1623  * We rely on a gross hack in section_rel[a]() calling find_extable_entry_size()
1624  * to know the sizeof(struct exception_table_entry) for the target architecture.
1625  */
1626 static unsigned int extable_entry_size = 0;
find_extable_entry_size(const char * const sec,const Elf_Rela * r)1627 static void find_extable_entry_size(const char* const sec, const Elf_Rela* r)
1628 {
1629 	/*
1630 	 * If we're currently checking the second relocation within __ex_table,
1631 	 * that relocation offset tells us the offsetof(struct
1632 	 * exception_table_entry, fixup) which is equal to sizeof(struct
1633 	 * exception_table_entry) divided by two.  We use that to our advantage
1634 	 * since there's no portable way to get that size as every architecture
1635 	 * seems to go with different sized types.  Not pretty but better than
1636 	 * hard-coding the size for every architecture..
1637 	 */
1638 	if (!extable_entry_size)
1639 		extable_entry_size = r->r_offset * 2;
1640 }
1641 
is_extable_fault_address(Elf_Rela * r)1642 static inline bool is_extable_fault_address(Elf_Rela *r)
1643 {
1644 	/*
1645 	 * extable_entry_size is only discovered after we've handled the
1646 	 * _second_ relocation in __ex_table, so only abort when we're not
1647 	 * handling the first reloc and extable_entry_size is zero.
1648 	 */
1649 	if (r->r_offset && extable_entry_size == 0)
1650 		fatal("extable_entry size hasn't been discovered!\n");
1651 
1652 	return ((r->r_offset == 0) ||
1653 		(r->r_offset % extable_entry_size == 0));
1654 }
1655 
1656 #define is_second_extable_reloc(Start, Cur, Sec)			\
1657 	(((Cur) == (Start) + 1) && (strcmp("__ex_table", (Sec)) == 0))
1658 
report_extable_warnings(const char * modname,struct elf_info * elf,const struct sectioncheck * const mismatch,Elf_Rela * r,Elf_Sym * sym,const char * fromsec,const char * tosec)1659 static void report_extable_warnings(const char* modname, struct elf_info* elf,
1660 				    const struct sectioncheck* const mismatch,
1661 				    Elf_Rela* r, Elf_Sym* sym,
1662 				    const char* fromsec, const char* tosec)
1663 {
1664 	Elf_Sym* fromsym = find_elf_symbol2(elf, r->r_offset, fromsec);
1665 	const char* fromsym_name = sym_name(elf, fromsym);
1666 	Elf_Sym* tosym = find_elf_symbol(elf, r->r_addend, sym);
1667 	const char* tosym_name = sym_name(elf, tosym);
1668 	const char* from_pretty_name;
1669 	const char* from_pretty_name_p;
1670 	const char* to_pretty_name;
1671 	const char* to_pretty_name_p;
1672 
1673 	get_pretty_name(is_function(fromsym),
1674 			&from_pretty_name, &from_pretty_name_p);
1675 	get_pretty_name(is_function(tosym),
1676 			&to_pretty_name, &to_pretty_name_p);
1677 
1678 	warn("%s(%s+0x%lx): Section mismatch in reference"
1679 	     " from the %s %s%s to the %s %s:%s%s\n",
1680 	     modname, fromsec, (long)r->r_offset, from_pretty_name,
1681 	     fromsym_name, from_pretty_name_p,
1682 	     to_pretty_name, tosec, tosym_name, to_pretty_name_p);
1683 
1684 	if (!match(tosec, mismatch->bad_tosec) &&
1685 	    is_executable_section(elf, get_secindex(elf, sym)))
1686 		fprintf(stderr,
1687 			"The relocation at %s+0x%lx references\n"
1688 			"section \"%s\" which is not in the list of\n"
1689 			"authorized sections.  If you're adding a new section\n"
1690 			"and/or if this reference is valid, add \"%s\" to the\n"
1691 			"list of authorized sections to jump to on fault.\n"
1692 			"This can be achieved by adding \"%s\" to \n"
1693 			"OTHER_TEXT_SECTIONS in scripts/mod/modpost.c.\n",
1694 			fromsec, (long)r->r_offset, tosec, tosec, tosec);
1695 }
1696 
extable_mismatch_handler(const char * modname,struct elf_info * elf,const struct sectioncheck * const mismatch,Elf_Rela * r,Elf_Sym * sym,const char * fromsec)1697 static void extable_mismatch_handler(const char* modname, struct elf_info *elf,
1698 				     const struct sectioncheck* const mismatch,
1699 				     Elf_Rela* r, Elf_Sym* sym,
1700 				     const char *fromsec)
1701 {
1702 	const char* tosec = sec_name(elf, get_secindex(elf, sym));
1703 
1704 	sec_mismatch_count++;
1705 
1706 	report_extable_warnings(modname, elf, mismatch, r, sym, fromsec, tosec);
1707 
1708 	if (match(tosec, mismatch->bad_tosec))
1709 		fatal("The relocation at %s+0x%lx references\n"
1710 		      "section \"%s\" which is black-listed.\n"
1711 		      "Something is seriously wrong and should be fixed.\n"
1712 		      "You might get more information about where this is\n"
1713 		      "coming from by using scripts/check_extable.sh %s\n",
1714 		      fromsec, (long)r->r_offset, tosec, modname);
1715 	else if (!is_executable_section(elf, get_secindex(elf, sym))) {
1716 		if (is_extable_fault_address(r))
1717 			fatal("The relocation at %s+0x%lx references\n"
1718 			      "section \"%s\" which is not executable, IOW\n"
1719 			      "it is not possible for the kernel to fault\n"
1720 			      "at that address.  Something is seriously wrong\n"
1721 			      "and should be fixed.\n",
1722 			      fromsec, (long)r->r_offset, tosec);
1723 		else
1724 			fatal("The relocation at %s+0x%lx references\n"
1725 			      "section \"%s\" which is not executable, IOW\n"
1726 			      "the kernel will fault if it ever tries to\n"
1727 			      "jump to it.  Something is seriously wrong\n"
1728 			      "and should be fixed.\n",
1729 			      fromsec, (long)r->r_offset, tosec);
1730 	}
1731 }
1732 
check_section_mismatch(const char * modname,struct elf_info * elf,Elf_Rela * r,Elf_Sym * sym,const char * fromsec)1733 static void check_section_mismatch(const char *modname, struct elf_info *elf,
1734 				   Elf_Rela *r, Elf_Sym *sym, const char *fromsec)
1735 {
1736 	const char *tosec = sec_name(elf, get_secindex(elf, sym));
1737 	const struct sectioncheck *mismatch = section_mismatch(fromsec, tosec);
1738 
1739 	if (mismatch) {
1740 		if (mismatch->handler)
1741 			mismatch->handler(modname, elf,  mismatch,
1742 					  r, sym, fromsec);
1743 		else
1744 			default_mismatch_handler(modname, elf, mismatch,
1745 						 r, sym, fromsec);
1746 	}
1747 }
1748 
reloc_location(struct elf_info * elf,Elf_Shdr * sechdr,Elf_Rela * r)1749 static unsigned int *reloc_location(struct elf_info *elf,
1750 				    Elf_Shdr *sechdr, Elf_Rela *r)
1751 {
1752 	return sym_get_data_by_offset(elf, sechdr->sh_info, r->r_offset);
1753 }
1754 
addend_386_rel(struct elf_info * elf,Elf_Shdr * sechdr,Elf_Rela * r)1755 static int addend_386_rel(struct elf_info *elf, Elf_Shdr *sechdr, Elf_Rela *r)
1756 {
1757 	unsigned int r_typ = ELF_R_TYPE(r->r_info);
1758 	unsigned int *location = reloc_location(elf, sechdr, r);
1759 
1760 	switch (r_typ) {
1761 	case R_386_32:
1762 		r->r_addend = TO_NATIVE(*location);
1763 		break;
1764 	case R_386_PC32:
1765 		r->r_addend = TO_NATIVE(*location) + 4;
1766 		/* For CONFIG_RELOCATABLE=y */
1767 		if (elf->hdr->e_type == ET_EXEC)
1768 			r->r_addend += r->r_offset;
1769 		break;
1770 	}
1771 	return 0;
1772 }
1773 
1774 #ifndef R_ARM_CALL
1775 #define R_ARM_CALL	28
1776 #endif
1777 #ifndef R_ARM_JUMP24
1778 #define R_ARM_JUMP24	29
1779 #endif
1780 
1781 #ifndef	R_ARM_THM_CALL
1782 #define	R_ARM_THM_CALL		10
1783 #endif
1784 #ifndef	R_ARM_THM_JUMP24
1785 #define	R_ARM_THM_JUMP24	30
1786 #endif
1787 #ifndef	R_ARM_THM_JUMP19
1788 #define	R_ARM_THM_JUMP19	51
1789 #endif
1790 
addend_arm_rel(struct elf_info * elf,Elf_Shdr * sechdr,Elf_Rela * r)1791 static int addend_arm_rel(struct elf_info *elf, Elf_Shdr *sechdr, Elf_Rela *r)
1792 {
1793 	unsigned int r_typ = ELF_R_TYPE(r->r_info);
1794 
1795 	switch (r_typ) {
1796 	case R_ARM_ABS32:
1797 		/* From ARM ABI: (S + A) | T */
1798 		r->r_addend = (int)(long)
1799 			      (elf->symtab_start + ELF_R_SYM(r->r_info));
1800 		break;
1801 	case R_ARM_PC24:
1802 	case R_ARM_CALL:
1803 	case R_ARM_JUMP24:
1804 	case R_ARM_THM_CALL:
1805 	case R_ARM_THM_JUMP24:
1806 	case R_ARM_THM_JUMP19:
1807 		/* From ARM ABI: ((S + A) | T) - P */
1808 		r->r_addend = (int)(long)(elf->hdr +
1809 			      sechdr->sh_offset +
1810 			      (r->r_offset - sechdr->sh_addr));
1811 		break;
1812 	default:
1813 		return 1;
1814 	}
1815 	return 0;
1816 }
1817 
addend_mips_rel(struct elf_info * elf,Elf_Shdr * sechdr,Elf_Rela * r)1818 static int addend_mips_rel(struct elf_info *elf, Elf_Shdr *sechdr, Elf_Rela *r)
1819 {
1820 	unsigned int r_typ = ELF_R_TYPE(r->r_info);
1821 	unsigned int *location = reloc_location(elf, sechdr, r);
1822 	unsigned int inst;
1823 
1824 	if (r_typ == R_MIPS_HI16)
1825 		return 1;	/* skip this */
1826 	inst = TO_NATIVE(*location);
1827 	switch (r_typ) {
1828 	case R_MIPS_LO16:
1829 		r->r_addend = inst & 0xffff;
1830 		break;
1831 	case R_MIPS_26:
1832 		r->r_addend = (inst & 0x03ffffff) << 2;
1833 		break;
1834 	case R_MIPS_32:
1835 		r->r_addend = inst;
1836 		break;
1837 	}
1838 	return 0;
1839 }
1840 
section_rela(const char * modname,struct elf_info * elf,Elf_Shdr * sechdr)1841 static void section_rela(const char *modname, struct elf_info *elf,
1842 			 Elf_Shdr *sechdr)
1843 {
1844 	Elf_Sym  *sym;
1845 	Elf_Rela *rela;
1846 	Elf_Rela r;
1847 	unsigned int r_sym;
1848 	const char *fromsec;
1849 
1850 	Elf_Rela *start = (void *)elf->hdr + sechdr->sh_offset;
1851 	Elf_Rela *stop  = (void *)start + sechdr->sh_size;
1852 
1853 	fromsec = sech_name(elf, sechdr);
1854 	fromsec += strlen(".rela");
1855 	/* if from section (name) is know good then skip it */
1856 	if (match(fromsec, section_white_list))
1857 		return;
1858 
1859 	for (rela = start; rela < stop; rela++) {
1860 		r.r_offset = TO_NATIVE(rela->r_offset);
1861 #if KERNEL_ELFCLASS == ELFCLASS64
1862 		if (elf->hdr->e_machine == EM_MIPS) {
1863 			unsigned int r_typ;
1864 			r_sym = ELF64_MIPS_R_SYM(rela->r_info);
1865 			r_sym = TO_NATIVE(r_sym);
1866 			r_typ = ELF64_MIPS_R_TYPE(rela->r_info);
1867 			r.r_info = ELF64_R_INFO(r_sym, r_typ);
1868 		} else {
1869 			r.r_info = TO_NATIVE(rela->r_info);
1870 			r_sym = ELF_R_SYM(r.r_info);
1871 		}
1872 #else
1873 		r.r_info = TO_NATIVE(rela->r_info);
1874 		r_sym = ELF_R_SYM(r.r_info);
1875 #endif
1876 		r.r_addend = TO_NATIVE(rela->r_addend);
1877 		sym = elf->symtab_start + r_sym;
1878 		/* Skip special sections */
1879 		if (is_shndx_special(sym->st_shndx))
1880 			continue;
1881 		if (is_second_extable_reloc(start, rela, fromsec))
1882 			find_extable_entry_size(fromsec, &r);
1883 		check_section_mismatch(modname, elf, &r, sym, fromsec);
1884 	}
1885 }
1886 
section_rel(const char * modname,struct elf_info * elf,Elf_Shdr * sechdr)1887 static void section_rel(const char *modname, struct elf_info *elf,
1888 			Elf_Shdr *sechdr)
1889 {
1890 	Elf_Sym *sym;
1891 	Elf_Rel *rel;
1892 	Elf_Rela r;
1893 	unsigned int r_sym;
1894 	const char *fromsec;
1895 
1896 	Elf_Rel *start = (void *)elf->hdr + sechdr->sh_offset;
1897 	Elf_Rel *stop  = (void *)start + sechdr->sh_size;
1898 
1899 	fromsec = sech_name(elf, sechdr);
1900 	fromsec += strlen(".rel");
1901 	/* if from section (name) is know good then skip it */
1902 	if (match(fromsec, section_white_list))
1903 		return;
1904 
1905 	for (rel = start; rel < stop; rel++) {
1906 		r.r_offset = TO_NATIVE(rel->r_offset);
1907 #if KERNEL_ELFCLASS == ELFCLASS64
1908 		if (elf->hdr->e_machine == EM_MIPS) {
1909 			unsigned int r_typ;
1910 			r_sym = ELF64_MIPS_R_SYM(rel->r_info);
1911 			r_sym = TO_NATIVE(r_sym);
1912 			r_typ = ELF64_MIPS_R_TYPE(rel->r_info);
1913 			r.r_info = ELF64_R_INFO(r_sym, r_typ);
1914 		} else {
1915 			r.r_info = TO_NATIVE(rel->r_info);
1916 			r_sym = ELF_R_SYM(r.r_info);
1917 		}
1918 #else
1919 		r.r_info = TO_NATIVE(rel->r_info);
1920 		r_sym = ELF_R_SYM(r.r_info);
1921 #endif
1922 		r.r_addend = 0;
1923 		switch (elf->hdr->e_machine) {
1924 		case EM_386:
1925 			if (addend_386_rel(elf, sechdr, &r))
1926 				continue;
1927 			break;
1928 		case EM_ARM:
1929 			if (addend_arm_rel(elf, sechdr, &r))
1930 				continue;
1931 			break;
1932 		case EM_MIPS:
1933 			if (addend_mips_rel(elf, sechdr, &r))
1934 				continue;
1935 			break;
1936 		}
1937 		sym = elf->symtab_start + r_sym;
1938 		/* Skip special sections */
1939 		if (is_shndx_special(sym->st_shndx))
1940 			continue;
1941 		if (is_second_extable_reloc(start, rel, fromsec))
1942 			find_extable_entry_size(fromsec, &r);
1943 		check_section_mismatch(modname, elf, &r, sym, fromsec);
1944 	}
1945 }
1946 
1947 /**
1948  * A module includes a number of sections that are discarded
1949  * either when loaded or when used as built-in.
1950  * For loaded modules all functions marked __init and all data
1951  * marked __initdata will be discarded when the module has been initialized.
1952  * Likewise for modules used built-in the sections marked __exit
1953  * are discarded because __exit marked function are supposed to be called
1954  * only when a module is unloaded which never happens for built-in modules.
1955  * The check_sec_ref() function traverses all relocation records
1956  * to find all references to a section that reference a section that will
1957  * be discarded and warns about it.
1958  **/
check_sec_ref(struct module * mod,const char * modname,struct elf_info * elf)1959 static void check_sec_ref(struct module *mod, const char *modname,
1960 			  struct elf_info *elf)
1961 {
1962 	int i;
1963 	Elf_Shdr *sechdrs = elf->sechdrs;
1964 
1965 	/* Walk through all sections */
1966 	for (i = 0; i < elf->num_sections; i++) {
1967 		check_section(modname, elf, &elf->sechdrs[i]);
1968 		/* We want to process only relocation sections and not .init */
1969 		if (sechdrs[i].sh_type == SHT_RELA)
1970 			section_rela(modname, elf, &elf->sechdrs[i]);
1971 		else if (sechdrs[i].sh_type == SHT_REL)
1972 			section_rel(modname, elf, &elf->sechdrs[i]);
1973 	}
1974 }
1975 
remove_dot(char * s)1976 static char *remove_dot(char *s)
1977 {
1978 	size_t n = strcspn(s, ".");
1979 
1980 	if (n && s[n]) {
1981 		size_t m = strspn(s + n + 1, "0123456789");
1982 		if (m && (s[n + m + 1] == '.' || s[n + m + 1] == 0))
1983 			s[n] = 0;
1984 
1985 		/* strip trailing .lto */
1986 		if (strends(s, ".lto"))
1987 			s[strlen(s) - 4] = '\0';
1988 	}
1989 	return s;
1990 }
1991 
read_symbols(const char * modname)1992 static void read_symbols(const char *modname)
1993 {
1994 	const char *symname;
1995 	char *version;
1996 	char *license;
1997 	char *namespace;
1998 	struct module *mod;
1999 	struct elf_info info = { };
2000 	Elf_Sym *sym;
2001 
2002 	if (!parse_elf(&info, modname))
2003 		return;
2004 
2005 	{
2006 		char *tmp;
2007 
2008 		/* strip trailing .o */
2009 		tmp = NOFAIL(strdup(modname));
2010 		tmp[strlen(tmp) - 2] = '\0';
2011 		/* strip trailing .lto */
2012 		if (strends(tmp, ".lto"))
2013 			tmp[strlen(tmp) - 4] = '\0';
2014 		mod = new_module(tmp);
2015 		free(tmp);
2016 	}
2017 
2018 	if (!mod->is_vmlinux) {
2019 		license = get_modinfo(&info, "license");
2020 		if (!license)
2021 			error("missing MODULE_LICENSE() in %s\n", modname);
2022 		while (license) {
2023 			if (license_is_gpl_compatible(license))
2024 				mod->gpl_compatible = 1;
2025 			else {
2026 				mod->gpl_compatible = 0;
2027 				break;
2028 			}
2029 			license = get_next_modinfo(&info, "license", license);
2030 		}
2031 
2032 		namespace = get_modinfo(&info, "import_ns");
2033 		while (namespace) {
2034 			add_namespace(&mod->imported_namespaces, namespace);
2035 			namespace = get_next_modinfo(&info, "import_ns",
2036 						     namespace);
2037 		}
2038 	}
2039 
2040 	for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
2041 		symname = remove_dot(info.strtab + sym->st_name);
2042 
2043 		handle_symbol(mod, &info, sym, symname);
2044 		handle_moddevtable(mod, &info, sym, symname);
2045 	}
2046 
2047 	for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
2048 		symname = remove_dot(info.strtab + sym->st_name);
2049 
2050 		/* Apply symbol namespaces from __kstrtabns_<symbol> entries. */
2051 		if (strstarts(symname, "__kstrtabns_"))
2052 			sym_update_namespace(symname + strlen("__kstrtabns_"),
2053 					     namespace_from_kstrtabns(&info,
2054 								      sym));
2055 
2056 		if (strstarts(symname, "__crc_"))
2057 			handle_modversion(mod, &info, sym,
2058 					  symname + strlen("__crc_"));
2059 	}
2060 
2061 	// check for static EXPORT_SYMBOL_* functions && global vars
2062 	for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
2063 		unsigned char bind = ELF_ST_BIND(sym->st_info);
2064 
2065 		if (bind == STB_GLOBAL || bind == STB_WEAK) {
2066 			struct symbol *s =
2067 				find_symbol(remove_dot(info.strtab +
2068 						       sym->st_name));
2069 
2070 			if (s)
2071 				s->is_static = 0;
2072 		}
2073 	}
2074 
2075 	check_sec_ref(mod, modname, &info);
2076 
2077 	if (!mod->is_vmlinux) {
2078 		version = get_modinfo(&info, "version");
2079 		if (version || all_versions)
2080 			get_src_version(modname, mod->srcversion,
2081 					sizeof(mod->srcversion) - 1);
2082 	}
2083 
2084 	parse_elf_finish(&info);
2085 
2086 	/* Our trick to get versioning for module struct etc. - it's
2087 	 * never passed as an argument to an exported function, so
2088 	 * the automatic versioning doesn't pick it up, but it's really
2089 	 * important anyhow */
2090 	if (modversions)
2091 		mod->unres = alloc_symbol("module_layout", 0, mod->unres);
2092 }
2093 
read_symbols_from_files(const char * filename)2094 static void read_symbols_from_files(const char *filename)
2095 {
2096 	FILE *in = stdin;
2097 	char fname[PATH_MAX];
2098 
2099 	if (strcmp(filename, "-") != 0) {
2100 		in = fopen(filename, "r");
2101 		if (!in)
2102 			fatal("Can't open filenames file %s: %m", filename);
2103 	}
2104 
2105 	while (fgets(fname, PATH_MAX, in) != NULL) {
2106 		if (strends(fname, "\n"))
2107 			fname[strlen(fname)-1] = '\0';
2108 		read_symbols(fname);
2109 	}
2110 
2111 	if (in != stdin)
2112 		fclose(in);
2113 }
2114 
2115 #define SZ 500
2116 
2117 /* We first write the generated file into memory using the
2118  * following helper, then compare to the file on disk and
2119  * only update the later if anything changed */
2120 
buf_printf(struct buffer * buf,const char * fmt,...)2121 void __attribute__((format(printf, 2, 3))) buf_printf(struct buffer *buf,
2122 						      const char *fmt, ...)
2123 {
2124 	char tmp[SZ];
2125 	int len;
2126 	va_list ap;
2127 
2128 	va_start(ap, fmt);
2129 	len = vsnprintf(tmp, SZ, fmt, ap);
2130 	buf_write(buf, tmp, len);
2131 	va_end(ap);
2132 }
2133 
buf_write(struct buffer * buf,const char * s,int len)2134 void buf_write(struct buffer *buf, const char *s, int len)
2135 {
2136 	if (buf->size - buf->pos < len) {
2137 		buf->size += len + SZ;
2138 		buf->p = NOFAIL(realloc(buf->p, buf->size));
2139 	}
2140 	strncpy(buf->p + buf->pos, s, len);
2141 	buf->pos += len;
2142 }
2143 
check_for_gpl_usage(enum export exp,const char * m,const char * s)2144 static void check_for_gpl_usage(enum export exp, const char *m, const char *s)
2145 {
2146 	switch (exp) {
2147 	case export_gpl:
2148 		error("GPL-incompatible module %s.ko uses GPL-only symbol '%s'\n",
2149 		      m, s);
2150 		break;
2151 	case export_unused_gpl:
2152 		error("GPL-incompatible module %s.ko uses GPL-only symbol marked UNUSED '%s'\n",
2153 		      m, s);
2154 		break;
2155 	case export_gpl_future:
2156 		warn("GPL-incompatible module %s.ko uses future GPL-only symbol '%s'\n",
2157 		     m, s);
2158 		break;
2159 	case export_plain:
2160 	case export_unused:
2161 	case export_unknown:
2162 		/* ignore */
2163 		break;
2164 	}
2165 }
2166 
check_for_unused(enum export exp,const char * m,const char * s)2167 static void check_for_unused(enum export exp, const char *m, const char *s)
2168 {
2169 	switch (exp) {
2170 	case export_unused:
2171 	case export_unused_gpl:
2172 		warn("module %s.ko uses symbol '%s' marked UNUSED\n",
2173 		     m, s);
2174 		break;
2175 	default:
2176 		/* ignore */
2177 		break;
2178 	}
2179 }
2180 
check_exports(struct module * mod)2181 static void check_exports(struct module *mod)
2182 {
2183 	struct symbol *s, *exp;
2184 
2185 	for (s = mod->unres; s; s = s->next) {
2186 		const char *basename;
2187 		exp = find_symbol(s->name);
2188 		if (!exp || exp->module == mod) {
2189 			if (have_vmlinux && !s->weak)
2190 				modpost_log(warn_unresolved ? LOG_WARN : LOG_ERROR,
2191 					    "\"%s\" [%s.ko] undefined!\n",
2192 					    s->name, mod->name);
2193 			continue;
2194 		}
2195 		basename = strrchr(mod->name, '/');
2196 		if (basename)
2197 			basename++;
2198 		else
2199 			basename = mod->name;
2200 
2201 		if (exp->namespace &&
2202 		    !module_imports_namespace(mod, exp->namespace)) {
2203 			modpost_log(allow_missing_ns_imports ? LOG_WARN : LOG_ERROR,
2204 				    "module %s uses symbol %s from namespace %s, but does not import it.\n",
2205 				    basename, exp->name, exp->namespace);
2206 			add_namespace(&mod->missing_namespaces, exp->namespace);
2207 		}
2208 
2209 		if (!mod->gpl_compatible)
2210 			check_for_gpl_usage(exp->export, basename, exp->name);
2211 		check_for_unused(exp->export, basename, exp->name);
2212 	}
2213 }
2214 
check_modname_len(struct module * mod)2215 static void check_modname_len(struct module *mod)
2216 {
2217 	const char *mod_name;
2218 
2219 	mod_name = strrchr(mod->name, '/');
2220 	if (mod_name == NULL)
2221 		mod_name = mod->name;
2222 	else
2223 		mod_name++;
2224 	if (strlen(mod_name) >= MODULE_NAME_LEN)
2225 		error("module name is too long [%s.ko]\n", mod->name);
2226 }
2227 
2228 /**
2229  * Header for the generated file
2230  **/
add_header(struct buffer * b,struct module * mod)2231 static void add_header(struct buffer *b, struct module *mod)
2232 {
2233 	buf_printf(b, "#include <linux/module.h>\n");
2234 	/*
2235 	 * Include build-salt.h after module.h in order to
2236 	 * inherit the definitions.
2237 	 */
2238 	buf_printf(b, "#define INCLUDE_VERMAGIC\n");
2239 	buf_printf(b, "#include <linux/build-salt.h>\n");
2240 	buf_printf(b, "#include <linux/vermagic.h>\n");
2241 	buf_printf(b, "#include <linux/compiler.h>\n");
2242 	buf_printf(b, "\n");
2243 	buf_printf(b, "BUILD_SALT;\n");
2244 	buf_printf(b, "\n");
2245 	buf_printf(b, "MODULE_INFO(vermagic, VERMAGIC_STRING);\n");
2246 	buf_printf(b, "MODULE_INFO(name, KBUILD_MODNAME);\n");
2247 	buf_printf(b, "\n");
2248 	buf_printf(b, "__visible struct module __this_module\n");
2249 	buf_printf(b, "__section(\".gnu.linkonce.this_module\") = {\n");
2250 	buf_printf(b, "\t.name = KBUILD_MODNAME,\n");
2251 	if (mod->has_init)
2252 		buf_printf(b, "\t.init = init_module,\n");
2253 	if (mod->has_cleanup)
2254 		buf_printf(b, "#ifdef CONFIG_MODULE_UNLOAD\n"
2255 			      "\t.exit = cleanup_module,\n"
2256 			      "#endif\n");
2257 	buf_printf(b, "\t.arch = MODULE_ARCH_INIT,\n");
2258 	buf_printf(b, "};\n");
2259 }
2260 
add_intree_flag(struct buffer * b,int is_intree)2261 static void add_intree_flag(struct buffer *b, int is_intree)
2262 {
2263 	if (is_intree)
2264 		buf_printf(b, "\nMODULE_INFO(intree, \"Y\");\n");
2265 }
2266 
2267 /**
2268  * add_scmversion() - Adds the MODULE_INFO macro for the scmversion.
2269  * @b: Buffer to append to.
2270  *
2271  * This function fills in the module attribute `scmversion` for the kernel
2272  * module. This is useful for determining a given module's SCM version on
2273  * device via /sys/modules/<module>/scmversion and/or using the modinfo tool.
2274  */
add_scmversion(struct buffer * b)2275 static void add_scmversion(struct buffer *b)
2276 {
2277 	if (module_scmversion[0] != '\0')
2278 		buf_printf(b, "\nMODULE_INFO(scmversion, \"%s\");\n", module_scmversion);
2279 }
2280 
2281 /* Cannot check for assembler */
add_retpoline(struct buffer * b)2282 static void add_retpoline(struct buffer *b)
2283 {
2284 	buf_printf(b, "\n#ifdef CONFIG_RETPOLINE\n");
2285 	buf_printf(b, "MODULE_INFO(retpoline, \"Y\");\n");
2286 	buf_printf(b, "#endif\n");
2287 }
2288 
add_staging_flag(struct buffer * b,const char * name)2289 static void add_staging_flag(struct buffer *b, const char *name)
2290 {
2291 	if (strstarts(name, "drivers/staging"))
2292 		buf_printf(b, "\nMODULE_INFO(staging, \"Y\");\n");
2293 }
2294 
2295 /**
2296  * Record CRCs for unresolved symbols
2297  **/
add_versions(struct buffer * b,struct module * mod)2298 static void add_versions(struct buffer *b, struct module *mod)
2299 {
2300 	struct symbol *s, *exp;
2301 
2302 	for (s = mod->unres; s; s = s->next) {
2303 		exp = find_symbol(s->name);
2304 		if (!exp || exp->module == mod)
2305 			continue;
2306 		s->module = exp->module;
2307 		s->crc_valid = exp->crc_valid;
2308 		s->crc = exp->crc;
2309 	}
2310 
2311 	if (!modversions)
2312 		return;
2313 
2314 	buf_printf(b, "\n");
2315 	buf_printf(b, "static const struct modversion_info ____versions[]\n");
2316 	buf_printf(b, "__used __section(\"__versions\") = {\n");
2317 
2318 	for (s = mod->unres; s; s = s->next) {
2319 		if (!s->module)
2320 			continue;
2321 		if (!s->crc_valid) {
2322 			warn("\"%s\" [%s.ko] has no CRC!\n",
2323 				s->name, mod->name);
2324 			continue;
2325 		}
2326 		if (strlen(s->name) >= MODULE_NAME_LEN) {
2327 			error("too long symbol \"%s\" [%s.ko]\n",
2328 			      s->name, mod->name);
2329 			break;
2330 		}
2331 		buf_printf(b, "\t{ %#8x, \"%s\" },\n",
2332 			   s->crc, s->name);
2333 	}
2334 
2335 	buf_printf(b, "};\n");
2336 }
2337 
add_depends(struct buffer * b,struct module * mod)2338 static void add_depends(struct buffer *b, struct module *mod)
2339 {
2340 	struct symbol *s;
2341 	int first = 1;
2342 
2343 	/* Clear ->seen flag of modules that own symbols needed by this. */
2344 	for (s = mod->unres; s; s = s->next)
2345 		if (s->module)
2346 			s->module->seen = s->module->is_vmlinux;
2347 
2348 	buf_printf(b, "\n");
2349 	buf_printf(b, "MODULE_INFO(depends, \"");
2350 	for (s = mod->unres; s; s = s->next) {
2351 		const char *p;
2352 		if (!s->module)
2353 			continue;
2354 
2355 		if (s->module->seen)
2356 			continue;
2357 
2358 		s->module->seen = 1;
2359 		p = strrchr(s->module->name, '/');
2360 		if (p)
2361 			p++;
2362 		else
2363 			p = s->module->name;
2364 		buf_printf(b, "%s%s", first ? "" : ",", p);
2365 		first = 0;
2366 	}
2367 	buf_printf(b, "\");\n");
2368 }
2369 
add_srcversion(struct buffer * b,struct module * mod)2370 static void add_srcversion(struct buffer *b, struct module *mod)
2371 {
2372 	if (mod->srcversion[0]) {
2373 		buf_printf(b, "\n");
2374 		buf_printf(b, "MODULE_INFO(srcversion, \"%s\");\n",
2375 			   mod->srcversion);
2376 	}
2377 }
2378 
write_buf(struct buffer * b,const char * fname)2379 static void write_buf(struct buffer *b, const char *fname)
2380 {
2381 	FILE *file;
2382 
2383 	file = fopen(fname, "w");
2384 	if (!file) {
2385 		perror(fname);
2386 		exit(1);
2387 	}
2388 	if (fwrite(b->p, 1, b->pos, file) != b->pos) {
2389 		perror(fname);
2390 		exit(1);
2391 	}
2392 	if (fclose(file) != 0) {
2393 		perror(fname);
2394 		exit(1);
2395 	}
2396 }
2397 
write_if_changed(struct buffer * b,const char * fname)2398 static void write_if_changed(struct buffer *b, const char *fname)
2399 {
2400 	char *tmp;
2401 	FILE *file;
2402 	struct stat st;
2403 
2404 	file = fopen(fname, "r");
2405 	if (!file)
2406 		goto write;
2407 
2408 	if (fstat(fileno(file), &st) < 0)
2409 		goto close_write;
2410 
2411 	if (st.st_size != b->pos)
2412 		goto close_write;
2413 
2414 	tmp = NOFAIL(malloc(b->pos));
2415 	if (fread(tmp, 1, b->pos, file) != b->pos)
2416 		goto free_write;
2417 
2418 	if (memcmp(tmp, b->p, b->pos) != 0)
2419 		goto free_write;
2420 
2421 	free(tmp);
2422 	fclose(file);
2423 	return;
2424 
2425  free_write:
2426 	free(tmp);
2427  close_write:
2428 	fclose(file);
2429  write:
2430 	write_buf(b, fname);
2431 }
2432 
2433 /* parse Module.symvers file. line format:
2434  * 0x12345678<tab>symbol<tab>module<tab>export<tab>namespace
2435  **/
read_dump(const char * fname)2436 static void read_dump(const char *fname)
2437 {
2438 	char *buf, *pos, *line;
2439 
2440 	buf = read_text_file(fname);
2441 	if (!buf)
2442 		/* No symbol versions, silently ignore */
2443 		return;
2444 
2445 	pos = buf;
2446 
2447 	while ((line = get_line(&pos))) {
2448 		char *symname, *namespace, *modname, *d, *export;
2449 		unsigned int crc;
2450 		struct module *mod;
2451 		struct symbol *s;
2452 
2453 		if (!(symname = strchr(line, '\t')))
2454 			goto fail;
2455 		*symname++ = '\0';
2456 		if (!(modname = strchr(symname, '\t')))
2457 			goto fail;
2458 		*modname++ = '\0';
2459 		if (!(export = strchr(modname, '\t')))
2460 			goto fail;
2461 		*export++ = '\0';
2462 		if (!(namespace = strchr(export, '\t')))
2463 			goto fail;
2464 		*namespace++ = '\0';
2465 
2466 		crc = strtoul(line, &d, 16);
2467 		if (*symname == '\0' || *modname == '\0' || *d != '\0')
2468 			goto fail;
2469 		mod = find_module(modname);
2470 		if (!mod) {
2471 			mod = new_module(modname);
2472 			mod->from_dump = 1;
2473 		}
2474 		s = sym_add_exported(symname, mod, export_no(export));
2475 		s->is_static = 0;
2476 		sym_set_crc(symname, crc);
2477 		sym_update_namespace(symname, namespace);
2478 	}
2479 	free(buf);
2480 	return;
2481 fail:
2482 	free(buf);
2483 	fatal("parse error in symbol dump file\n");
2484 }
2485 
write_dump(const char * fname)2486 static void write_dump(const char *fname)
2487 {
2488 	struct buffer buf = { };
2489 	struct symbol *symbol;
2490 	const char *namespace;
2491 	int n;
2492 
2493 	for (n = 0; n < SYMBOL_HASH_SIZE ; n++) {
2494 		symbol = symbolhash[n];
2495 		while (symbol) {
2496 			if (!symbol->module->from_dump) {
2497 				namespace = symbol->namespace;
2498 				buf_printf(&buf, "0x%08x\t%s\t%s\t%s\t%s\n",
2499 					   symbol->crc, symbol->name,
2500 					   symbol->module->name,
2501 					   export_str(symbol->export),
2502 					   namespace ? namespace : "");
2503 			}
2504 			symbol = symbol->next;
2505 		}
2506 	}
2507 	write_buf(&buf, fname);
2508 	free(buf.p);
2509 }
2510 
write_namespace_deps_files(const char * fname)2511 static void write_namespace_deps_files(const char *fname)
2512 {
2513 	struct module *mod;
2514 	struct namespace_list *ns;
2515 	struct buffer ns_deps_buf = {};
2516 
2517 	for (mod = modules; mod; mod = mod->next) {
2518 
2519 		if (mod->from_dump || !mod->missing_namespaces)
2520 			continue;
2521 
2522 		buf_printf(&ns_deps_buf, "%s.ko:", mod->name);
2523 
2524 		for (ns = mod->missing_namespaces; ns; ns = ns->next)
2525 			buf_printf(&ns_deps_buf, " %s", ns->namespace);
2526 
2527 		buf_printf(&ns_deps_buf, "\n");
2528 	}
2529 
2530 	write_if_changed(&ns_deps_buf, fname);
2531 	free(ns_deps_buf.p);
2532 }
2533 
2534 struct dump_list {
2535 	struct dump_list *next;
2536 	const char *file;
2537 };
2538 
main(int argc,char ** argv)2539 int main(int argc, char **argv)
2540 {
2541 	struct module *mod;
2542 	struct buffer buf = { };
2543 	char *missing_namespace_deps = NULL;
2544 	char *dump_write = NULL, *files_source = NULL;
2545 	int opt;
2546 	int n;
2547 	struct dump_list *dump_read_start = NULL;
2548 	struct dump_list **dump_read_iter = &dump_read_start;
2549 
2550 	while ((opt = getopt(argc, argv, "ei:mnT:o:awENd:v:")) != -1) {
2551 		switch (opt) {
2552 		case 'e':
2553 			external_module = 1;
2554 			break;
2555 		case 'i':
2556 			*dump_read_iter =
2557 				NOFAIL(calloc(1, sizeof(**dump_read_iter)));
2558 			(*dump_read_iter)->file = optarg;
2559 			dump_read_iter = &(*dump_read_iter)->next;
2560 			break;
2561 		case 'm':
2562 			modversions = 1;
2563 			break;
2564 		case 'n':
2565 			ignore_missing_files = 1;
2566 			break;
2567 		case 'o':
2568 			dump_write = optarg;
2569 			break;
2570 		case 'a':
2571 			all_versions = 1;
2572 			break;
2573 		case 'T':
2574 			files_source = optarg;
2575 			break;
2576 		case 'w':
2577 			warn_unresolved = 1;
2578 			break;
2579 		case 'E':
2580 			sec_mismatch_warn_only = false;
2581 			break;
2582 		case 'N':
2583 			allow_missing_ns_imports = 1;
2584 			break;
2585 		case 'd':
2586 			missing_namespace_deps = optarg;
2587 			break;
2588 		case 'v':
2589 			strncpy(module_scmversion, optarg, sizeof(module_scmversion) - 1);
2590 			break;
2591 		default:
2592 			exit(1);
2593 		}
2594 	}
2595 
2596 	while (dump_read_start) {
2597 		struct dump_list *tmp;
2598 
2599 		read_dump(dump_read_start->file);
2600 		tmp = dump_read_start->next;
2601 		free(dump_read_start);
2602 		dump_read_start = tmp;
2603 	}
2604 
2605 	while (optind < argc)
2606 		read_symbols(argv[optind++]);
2607 
2608 	if (files_source)
2609 		read_symbols_from_files(files_source);
2610 
2611 	/*
2612 	 * When there's no vmlinux, don't print warnings about
2613 	 * unresolved symbols (since there'll be too many ;)
2614 	 */
2615 	if (!have_vmlinux)
2616 		warn("Symbol info of vmlinux is missing. Unresolved symbol check will be entirely skipped.\n");
2617 
2618 	for (mod = modules; mod; mod = mod->next) {
2619 		char fname[PATH_MAX];
2620 
2621 		if (mod->is_vmlinux || mod->from_dump)
2622 			continue;
2623 
2624 		buf.pos = 0;
2625 
2626 		check_modname_len(mod);
2627 		check_exports(mod);
2628 
2629 		add_header(&buf, mod);
2630 		add_intree_flag(&buf, !external_module);
2631 		add_retpoline(&buf);
2632 		add_staging_flag(&buf, mod->name);
2633 		add_versions(&buf, mod);
2634 		add_depends(&buf, mod);
2635 		add_moddevtable(&buf, mod);
2636 		add_srcversion(&buf, mod);
2637 		add_scmversion(&buf);
2638 
2639 		sprintf(fname, "%s.mod.c", mod->name);
2640 		write_if_changed(&buf, fname);
2641 	}
2642 
2643 	if (missing_namespace_deps)
2644 		write_namespace_deps_files(missing_namespace_deps);
2645 
2646 	if (dump_write)
2647 		write_dump(dump_write);
2648 	if (sec_mismatch_count && !sec_mismatch_warn_only)
2649 		error("Section mismatches detected.\n"
2650 		      "Set CONFIG_SECTION_MISMATCH_WARN_ONLY=y to allow them.\n");
2651 	for (n = 0; n < SYMBOL_HASH_SIZE; n++) {
2652 		struct symbol *s;
2653 
2654 		for (s = symbolhash[n]; s; s = s->next) {
2655 			if (s->is_static)
2656 				error("\"%s\" [%s] is a static %s\n",
2657 				      s->name, s->module->name,
2658 				      export_str(s->export));
2659 		}
2660 	}
2661 
2662 	free(buf.p);
2663 
2664 	return error_occurred ? 1 : 0;
2665 }
2666