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