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