• 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 "modpost.h"
18 #include "../../include/linux/license.h"
19 
20 /* Are we using CONFIG_MODVERSIONS? */
21 int modversions = 0;
22 /* Warn about undefined symbols? (do so if we have vmlinux) */
23 int have_vmlinux = 0;
24 /* Is CONFIG_MODULE_SRCVERSION_ALL set? */
25 static int all_versions = 0;
26 /* If we are modposting external module set to 1 */
27 static int external_module = 0;
28 /* Warn about section mismatch in vmlinux if set to 1 */
29 static int vmlinux_section_warnings = 1;
30 /* Only warn about unresolved symbols */
31 static int warn_unresolved = 0;
32 /* How a symbol is exported */
33 static int sec_mismatch_count = 0;
34 static int sec_mismatch_verbose = 1;
35 
36 enum export {
37 	export_plain,      export_unused,     export_gpl,
38 	export_unused_gpl, export_gpl_future, export_unknown
39 };
40 
41 #define PRINTF __attribute__ ((format (printf, 1, 2)))
42 
fatal(const char * fmt,...)43 PRINTF void fatal(const char *fmt, ...)
44 {
45 	va_list arglist;
46 
47 	fprintf(stderr, "FATAL: ");
48 
49 	va_start(arglist, fmt);
50 	vfprintf(stderr, fmt, arglist);
51 	va_end(arglist);
52 
53 	exit(1);
54 }
55 
warn(const char * fmt,...)56 PRINTF void warn(const char *fmt, ...)
57 {
58 	va_list arglist;
59 
60 	fprintf(stderr, "WARNING: ");
61 
62 	va_start(arglist, fmt);
63 	vfprintf(stderr, fmt, arglist);
64 	va_end(arglist);
65 }
66 
merror(const char * fmt,...)67 PRINTF void merror(const char *fmt, ...)
68 {
69 	va_list arglist;
70 
71 	fprintf(stderr, "ERROR: ");
72 
73 	va_start(arglist, fmt);
74 	vfprintf(stderr, fmt, arglist);
75 	va_end(arglist);
76 }
77 
is_vmlinux(const char * modname)78 static int is_vmlinux(const char *modname)
79 {
80 	const char *myname;
81 
82 	myname = strrchr(modname, '/');
83 	if (myname)
84 		myname++;
85 	else
86 		myname = modname;
87 
88 	return (strcmp(myname, "vmlinux") == 0) ||
89 	       (strcmp(myname, "vmlinux.o") == 0);
90 }
91 
do_nofail(void * ptr,const char * expr)92 void *do_nofail(void *ptr, const char *expr)
93 {
94 	if (!ptr)
95 		fatal("modpost: Memory allocation failure: %s.\n", expr);
96 
97 	return ptr;
98 }
99 
100 /* A list of all modules we processed */
101 static struct module *modules;
102 
find_module(char * modname)103 static struct module *find_module(char *modname)
104 {
105 	struct module *mod;
106 
107 	for (mod = modules; mod; mod = mod->next)
108 		if (strcmp(mod->name, modname) == 0)
109 			break;
110 	return mod;
111 }
112 
new_module(char * modname)113 static struct module *new_module(char *modname)
114 {
115 	struct module *mod;
116 	char *p, *s;
117 
118 	mod = NOFAIL(malloc(sizeof(*mod)));
119 	memset(mod, 0, sizeof(*mod));
120 	p = NOFAIL(strdup(modname));
121 
122 	/* strip trailing .o */
123 	s = strrchr(p, '.');
124 	if (s != NULL)
125 		if (strcmp(s, ".o") == 0)
126 			*s = '\0';
127 
128 	/* add to list */
129 	mod->name = p;
130 	mod->gpl_compatible = -1;
131 	mod->next = modules;
132 	modules = mod;
133 
134 	return mod;
135 }
136 
137 /* A hash of all exported symbols,
138  * struct symbol is also used for lists of unresolved symbols */
139 
140 #define SYMBOL_HASH_SIZE 1024
141 
142 struct symbol {
143 	struct symbol *next;
144 	struct module *module;
145 	unsigned int crc;
146 	int crc_valid;
147 	unsigned int weak:1;
148 	unsigned int vmlinux:1;    /* 1 if symbol is defined in vmlinux */
149 	unsigned int kernel:1;     /* 1 if symbol is from kernel
150 				    *  (only for external modules) **/
151 	unsigned int preloaded:1;  /* 1 if symbol from Module.symvers */
152 	enum export  export;       /* Type of export */
153 	char name[0];
154 };
155 
156 static struct symbol *symbolhash[SYMBOL_HASH_SIZE];
157 
158 /* This is based on the hash agorithm from gdbm, via tdb */
tdb_hash(const char * name)159 static inline unsigned int tdb_hash(const char *name)
160 {
161 	unsigned value;	/* Used to compute the hash value.  */
162 	unsigned   i;	/* Used to cycle through random values. */
163 
164 	/* Set the initial value from the key size. */
165 	for (value = 0x238F13AF * strlen(name), i = 0; name[i]; i++)
166 		value = (value + (((unsigned char *)name)[i] << (i*5 % 24)));
167 
168 	return (1103515243 * value + 12345);
169 }
170 
171 /**
172  * Allocate a new symbols for use in the hash of exported symbols or
173  * the list of unresolved symbols per module
174  **/
alloc_symbol(const char * name,unsigned int weak,struct symbol * next)175 static struct symbol *alloc_symbol(const char *name, unsigned int weak,
176 				   struct symbol *next)
177 {
178 	struct symbol *s = NOFAIL(malloc(sizeof(*s) + strlen(name) + 1));
179 
180 	memset(s, 0, sizeof(*s));
181 	strcpy(s->name, name);
182 	s->weak = weak;
183 	s->next = next;
184 	return s;
185 }
186 
187 /* For the hash of exported symbols */
new_symbol(const char * name,struct module * module,enum export export)188 static struct symbol *new_symbol(const char *name, struct module *module,
189 				 enum export export)
190 {
191 	unsigned int hash;
192 	struct symbol *new;
193 
194 	hash = tdb_hash(name) % SYMBOL_HASH_SIZE;
195 	new = symbolhash[hash] = alloc_symbol(name, 0, symbolhash[hash]);
196 	new->module = module;
197 	new->export = export;
198 	return new;
199 }
200 
find_symbol(const char * name)201 static struct symbol *find_symbol(const char *name)
202 {
203 	struct symbol *s;
204 
205 	/* For our purposes, .foo matches foo.  PPC64 needs this. */
206 	if (name[0] == '.')
207 		name++;
208 
209 	for (s = symbolhash[tdb_hash(name) % SYMBOL_HASH_SIZE]; s; s = s->next) {
210 		if (strcmp(s->name, name) == 0)
211 			return s;
212 	}
213 	return NULL;
214 }
215 
216 static struct {
217 	const char *str;
218 	enum export export;
219 } export_list[] = {
220 	{ .str = "EXPORT_SYMBOL",            .export = export_plain },
221 	{ .str = "EXPORT_UNUSED_SYMBOL",     .export = export_unused },
222 	{ .str = "EXPORT_SYMBOL_GPL",        .export = export_gpl },
223 	{ .str = "EXPORT_UNUSED_SYMBOL_GPL", .export = export_unused_gpl },
224 	{ .str = "EXPORT_SYMBOL_GPL_FUTURE", .export = export_gpl_future },
225 	{ .str = "(unknown)",                .export = export_unknown },
226 };
227 
228 
export_str(enum export ex)229 static const char *export_str(enum export ex)
230 {
231 	return export_list[ex].str;
232 }
233 
export_no(const char * s)234 static enum export export_no(const char *s)
235 {
236 	int i;
237 
238 	if (!s)
239 		return export_unknown;
240 	for (i = 0; export_list[i].export != export_unknown; i++) {
241 		if (strcmp(export_list[i].str, s) == 0)
242 			return export_list[i].export;
243 	}
244 	return export_unknown;
245 }
246 
export_from_sec(struct elf_info * elf,Elf_Section sec)247 static enum export export_from_sec(struct elf_info *elf, Elf_Section sec)
248 {
249 	if (sec == elf->export_sec)
250 		return export_plain;
251 	else if (sec == elf->export_unused_sec)
252 		return export_unused;
253 	else if (sec == elf->export_gpl_sec)
254 		return export_gpl;
255 	else if (sec == elf->export_unused_gpl_sec)
256 		return export_unused_gpl;
257 	else if (sec == elf->export_gpl_future_sec)
258 		return export_gpl_future;
259 	else
260 		return export_unknown;
261 }
262 
263 /**
264  * Add an exported symbol - it may have already been added without a
265  * CRC, in this case just update the CRC
266  **/
sym_add_exported(const char * name,struct module * mod,enum export export)267 static struct symbol *sym_add_exported(const char *name, struct module *mod,
268 				       enum export export)
269 {
270 	struct symbol *s = find_symbol(name);
271 
272 	if (!s) {
273 		s = new_symbol(name, mod, export);
274 	} else {
275 		if (!s->preloaded) {
276 			warn("%s: '%s' exported twice. Previous export "
277 			     "was in %s%s\n", mod->name, name,
278 			     s->module->name,
279 			     is_vmlinux(s->module->name) ?"":".ko");
280 		} else {
281 			/* In case Modules.symvers was out of date */
282 			s->module = mod;
283 		}
284 	}
285 	s->preloaded = 0;
286 	s->vmlinux   = is_vmlinux(mod->name);
287 	s->kernel    = 0;
288 	s->export    = export;
289 	return s;
290 }
291 
sym_update_crc(const char * name,struct module * mod,unsigned int crc,enum export export)292 static void sym_update_crc(const char *name, struct module *mod,
293 			   unsigned int crc, enum export export)
294 {
295 	struct symbol *s = find_symbol(name);
296 
297 	if (!s)
298 		s = new_symbol(name, mod, export);
299 	s->crc = crc;
300 	s->crc_valid = 1;
301 }
302 
grab_file(const char * filename,unsigned long * size)303 void *grab_file(const char *filename, unsigned long *size)
304 {
305 	struct stat st;
306 	void *map;
307 	int fd;
308 
309 	fd = open(filename, O_RDONLY);
310 	if (fd < 0 || fstat(fd, &st) != 0)
311 		return NULL;
312 
313 	*size = st.st_size;
314 	map = mmap(NULL, *size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
315 	close(fd);
316 
317 	if (map == MAP_FAILED)
318 		return NULL;
319 	return map;
320 }
321 
322 /**
323   * Return a copy of the next line in a mmap'ed file.
324   * spaces in the beginning of the line is trimmed away.
325   * Return a pointer to a static buffer.
326   **/
get_next_line(unsigned long * pos,void * file,unsigned long size)327 char *get_next_line(unsigned long *pos, void *file, unsigned long size)
328 {
329 	static char line[4096];
330 	int skip = 1;
331 	size_t len = 0;
332 	signed char *p = (signed char *)file + *pos;
333 	char *s = line;
334 
335 	for (; *pos < size ; (*pos)++) {
336 		if (skip && isspace(*p)) {
337 			p++;
338 			continue;
339 		}
340 		skip = 0;
341 		if (*p != '\n' && (*pos < size)) {
342 			len++;
343 			*s++ = *p++;
344 			if (len > 4095)
345 				break; /* Too long, stop */
346 		} else {
347 			/* End of string */
348 			*s = '\0';
349 			return line;
350 		}
351 	}
352 	/* End of buffer */
353 	return NULL;
354 }
355 
release_file(void * file,unsigned long size)356 void release_file(void *file, unsigned long size)
357 {
358 	munmap(file, size);
359 }
360 
parse_elf(struct elf_info * info,const char * filename)361 static int parse_elf(struct elf_info *info, const char *filename)
362 {
363 	unsigned int i;
364 	Elf_Ehdr *hdr;
365 	Elf_Shdr *sechdrs;
366 	Elf_Sym  *sym;
367 
368 	hdr = grab_file(filename, &info->size);
369 	if (!hdr) {
370 		perror(filename);
371 		exit(1);
372 	}
373 	info->hdr = hdr;
374 	if (info->size < sizeof(*hdr)) {
375 		/* file too small, assume this is an empty .o file */
376 		return 0;
377 	}
378 	/* Is this a valid ELF file? */
379 	if ((hdr->e_ident[EI_MAG0] != ELFMAG0) ||
380 	    (hdr->e_ident[EI_MAG1] != ELFMAG1) ||
381 	    (hdr->e_ident[EI_MAG2] != ELFMAG2) ||
382 	    (hdr->e_ident[EI_MAG3] != ELFMAG3)) {
383 		/* Not an ELF file - silently ignore it */
384 		return 0;
385 	}
386 	/* Fix endianness in ELF header */
387 	hdr->e_shoff    = TO_NATIVE(hdr->e_shoff);
388 	hdr->e_shstrndx = TO_NATIVE(hdr->e_shstrndx);
389 	hdr->e_shnum    = TO_NATIVE(hdr->e_shnum);
390 	hdr->e_machine  = TO_NATIVE(hdr->e_machine);
391 	hdr->e_type     = TO_NATIVE(hdr->e_type);
392 	sechdrs = (void *)hdr + hdr->e_shoff;
393 	info->sechdrs = sechdrs;
394 
395 	/* Check if file offset is correct */
396 	if (hdr->e_shoff > info->size) {
397 		fatal("section header offset=%lu in file '%s' is bigger than "
398 		      "filesize=%lu\n", (unsigned long)hdr->e_shoff,
399 		      filename, info->size);
400 		return 0;
401 	}
402 
403 	/* Fix endianness in section headers */
404 	for (i = 0; i < hdr->e_shnum; i++) {
405 		sechdrs[i].sh_type   = TO_NATIVE(sechdrs[i].sh_type);
406 		sechdrs[i].sh_offset = TO_NATIVE(sechdrs[i].sh_offset);
407 		sechdrs[i].sh_size   = TO_NATIVE(sechdrs[i].sh_size);
408 		sechdrs[i].sh_link   = TO_NATIVE(sechdrs[i].sh_link);
409 		sechdrs[i].sh_name   = TO_NATIVE(sechdrs[i].sh_name);
410 		sechdrs[i].sh_info   = TO_NATIVE(sechdrs[i].sh_info);
411 		sechdrs[i].sh_addr   = TO_NATIVE(sechdrs[i].sh_addr);
412 	}
413 	/* Find symbol table. */
414 	for (i = 1; i < hdr->e_shnum; i++) {
415 		const char *secstrings
416 			= (void *)hdr + sechdrs[hdr->e_shstrndx].sh_offset;
417 		const char *secname;
418 
419 		if (sechdrs[i].sh_offset > info->size) {
420 			fatal("%s is truncated. sechdrs[i].sh_offset=%lu > "
421 			      "sizeof(*hrd)=%zu\n", filename,
422 			      (unsigned long)sechdrs[i].sh_offset,
423 			      sizeof(*hdr));
424 			return 0;
425 		}
426 		secname = secstrings + sechdrs[i].sh_name;
427 		if (strcmp(secname, ".modinfo") == 0) {
428 			info->modinfo = (void *)hdr + sechdrs[i].sh_offset;
429 			info->modinfo_len = sechdrs[i].sh_size;
430 		} else if (strcmp(secname, "__ksymtab") == 0)
431 			info->export_sec = i;
432 		else if (strcmp(secname, "__ksymtab_unused") == 0)
433 			info->export_unused_sec = i;
434 		else if (strcmp(secname, "__ksymtab_gpl") == 0)
435 			info->export_gpl_sec = i;
436 		else if (strcmp(secname, "__ksymtab_unused_gpl") == 0)
437 			info->export_unused_gpl_sec = i;
438 		else if (strcmp(secname, "__ksymtab_gpl_future") == 0)
439 			info->export_gpl_future_sec = i;
440 		else if (strcmp(secname, "__markers_strings") == 0)
441 			info->markers_strings_sec = i;
442 
443 		if (sechdrs[i].sh_type != SHT_SYMTAB)
444 			continue;
445 
446 		info->symtab_start = (void *)hdr + sechdrs[i].sh_offset;
447 		info->symtab_stop  = (void *)hdr + sechdrs[i].sh_offset
448 			                         + sechdrs[i].sh_size;
449 		info->strtab       = (void *)hdr +
450 			             sechdrs[sechdrs[i].sh_link].sh_offset;
451 	}
452 	if (!info->symtab_start)
453 		fatal("%s has no symtab?\n", filename);
454 
455 	/* Fix endianness in symbols */
456 	for (sym = info->symtab_start; sym < info->symtab_stop; sym++) {
457 		sym->st_shndx = TO_NATIVE(sym->st_shndx);
458 		sym->st_name  = TO_NATIVE(sym->st_name);
459 		sym->st_value = TO_NATIVE(sym->st_value);
460 		sym->st_size  = TO_NATIVE(sym->st_size);
461 	}
462 	return 1;
463 }
464 
parse_elf_finish(struct elf_info * info)465 static void parse_elf_finish(struct elf_info *info)
466 {
467 	release_file(info->hdr, info->size);
468 }
469 
ignore_undef_symbol(struct elf_info * info,const char * symname)470 static int ignore_undef_symbol(struct elf_info *info, const char *symname)
471 {
472 	/* ignore __this_module, it will be resolved shortly */
473 	if (strcmp(symname, MODULE_SYMBOL_PREFIX "__this_module") == 0)
474 		return 1;
475 	/* ignore global offset table */
476 	if (strcmp(symname, "_GLOBAL_OFFSET_TABLE_") == 0)
477 		return 1;
478 	if (info->hdr->e_machine == EM_PPC)
479 		/* Special register function linked on all modules during final link of .ko */
480 		if (strncmp(symname, "_restgpr_", sizeof("_restgpr_") - 1) == 0 ||
481 		    strncmp(symname, "_savegpr_", sizeof("_savegpr_") - 1) == 0 ||
482 		    strncmp(symname, "_rest32gpr_", sizeof("_rest32gpr_") - 1) == 0 ||
483 		    strncmp(symname, "_save32gpr_", sizeof("_save32gpr_") - 1) == 0)
484 			return 1;
485 	/* Do not ignore this symbol */
486 	return 0;
487 }
488 
489 #define CRC_PFX     MODULE_SYMBOL_PREFIX "__crc_"
490 #define KSYMTAB_PFX MODULE_SYMBOL_PREFIX "__ksymtab_"
491 
handle_modversions(struct module * mod,struct elf_info * info,Elf_Sym * sym,const char * symname)492 static void handle_modversions(struct module *mod, struct elf_info *info,
493 			       Elf_Sym *sym, const char *symname)
494 {
495 	unsigned int crc;
496 	enum export export = export_from_sec(info, sym->st_shndx);
497 
498 	switch (sym->st_shndx) {
499 	case SHN_COMMON:
500 		warn("\"%s\" [%s] is COMMON symbol\n", symname, mod->name);
501 		break;
502 	case SHN_ABS:
503 		/* CRC'd symbol */
504 		if (memcmp(symname, CRC_PFX, strlen(CRC_PFX)) == 0) {
505 			crc = (unsigned int) sym->st_value;
506 			sym_update_crc(symname + strlen(CRC_PFX), mod, crc,
507 					export);
508 		}
509 		break;
510 	case SHN_UNDEF:
511 		/* undefined symbol */
512 		if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL &&
513 		    ELF_ST_BIND(sym->st_info) != STB_WEAK)
514 			break;
515 		if (ignore_undef_symbol(info, symname))
516 			break;
517 /* cope with newer glibc (2.3.4 or higher) STT_ definition in elf.h */
518 #if defined(STT_REGISTER) || defined(STT_SPARC_REGISTER)
519 /* add compatibility with older glibc */
520 #ifndef STT_SPARC_REGISTER
521 #define STT_SPARC_REGISTER STT_REGISTER
522 #endif
523 		if (info->hdr->e_machine == EM_SPARC ||
524 		    info->hdr->e_machine == EM_SPARCV9) {
525 			/* Ignore register directives. */
526 			if (ELF_ST_TYPE(sym->st_info) == STT_SPARC_REGISTER)
527 				break;
528 			if (symname[0] == '.') {
529 				char *munged = strdup(symname);
530 				munged[0] = '_';
531 				munged[1] = toupper(munged[1]);
532 				symname = munged;
533 			}
534 		}
535 #endif
536 
537 		if (memcmp(symname, MODULE_SYMBOL_PREFIX,
538 			   strlen(MODULE_SYMBOL_PREFIX)) == 0) {
539 			mod->unres =
540 			  alloc_symbol(symname +
541 			               strlen(MODULE_SYMBOL_PREFIX),
542 			               ELF_ST_BIND(sym->st_info) == STB_WEAK,
543 			               mod->unres);
544 		}
545 		break;
546 	default:
547 		/* All exported symbols */
548 		if (memcmp(symname, KSYMTAB_PFX, strlen(KSYMTAB_PFX)) == 0) {
549 			sym_add_exported(symname + strlen(KSYMTAB_PFX), mod,
550 					export);
551 		}
552 		if (strcmp(symname, MODULE_SYMBOL_PREFIX "init_module") == 0)
553 			mod->has_init = 1;
554 		if (strcmp(symname, MODULE_SYMBOL_PREFIX "cleanup_module") == 0)
555 			mod->has_cleanup = 1;
556 		break;
557 	}
558 }
559 
560 /**
561  * Parse tag=value strings from .modinfo section
562  **/
next_string(char * string,unsigned long * secsize)563 static char *next_string(char *string, unsigned long *secsize)
564 {
565 	/* Skip non-zero chars */
566 	while (string[0]) {
567 		string++;
568 		if ((*secsize)-- <= 1)
569 			return NULL;
570 	}
571 
572 	/* Skip any zero padding. */
573 	while (!string[0]) {
574 		string++;
575 		if ((*secsize)-- <= 1)
576 			return NULL;
577 	}
578 	return string;
579 }
580 
get_next_modinfo(void * modinfo,unsigned long modinfo_len,const char * tag,char * info)581 static char *get_next_modinfo(void *modinfo, unsigned long modinfo_len,
582 			      const char *tag, char *info)
583 {
584 	char *p;
585 	unsigned int taglen = strlen(tag);
586 	unsigned long size = modinfo_len;
587 
588 	if (info) {
589 		size -= info - (char *)modinfo;
590 		modinfo = next_string(info, &size);
591 	}
592 
593 	for (p = modinfo; p; p = next_string(p, &size)) {
594 		if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
595 			return p + taglen + 1;
596 	}
597 	return NULL;
598 }
599 
get_modinfo(void * modinfo,unsigned long modinfo_len,const char * tag)600 static char *get_modinfo(void *modinfo, unsigned long modinfo_len,
601 			 const char *tag)
602 
603 {
604 	return get_next_modinfo(modinfo, modinfo_len, tag, NULL);
605 }
606 
607 /**
608  * Test if string s ends in string sub
609  * return 0 if match
610  **/
strrcmp(const char * s,const char * sub)611 static int strrcmp(const char *s, const char *sub)
612 {
613 	int slen, sublen;
614 
615 	if (!s || !sub)
616 		return 1;
617 
618 	slen = strlen(s);
619 	sublen = strlen(sub);
620 
621 	if ((slen == 0) || (sublen == 0))
622 		return 1;
623 
624 	if (sublen > slen)
625 		return 1;
626 
627 	return memcmp(s + slen - sublen, sub, sublen);
628 }
629 
sym_name(struct elf_info * elf,Elf_Sym * sym)630 static const char *sym_name(struct elf_info *elf, Elf_Sym *sym)
631 {
632 	if (sym)
633 		return elf->strtab + sym->st_name;
634 	else
635 		return "(unknown)";
636 }
637 
sec_name(struct elf_info * elf,int shndx)638 static const char *sec_name(struct elf_info *elf, int shndx)
639 {
640 	Elf_Shdr *sechdrs = elf->sechdrs;
641 	return (void *)elf->hdr +
642 	        elf->sechdrs[elf->hdr->e_shstrndx].sh_offset +
643 	        sechdrs[shndx].sh_name;
644 }
645 
sech_name(struct elf_info * elf,Elf_Shdr * sechdr)646 static const char *sech_name(struct elf_info *elf, Elf_Shdr *sechdr)
647 {
648 	return (void *)elf->hdr +
649 	        elf->sechdrs[elf->hdr->e_shstrndx].sh_offset +
650 	        sechdr->sh_name;
651 }
652 
653 /* if sym is empty or point to a string
654  * like ".[0-9]+" then return 1.
655  * This is the optional prefix added by ld to some sections
656  */
number_prefix(const char * sym)657 static int number_prefix(const char *sym)
658 {
659 	if (*sym++ == '\0')
660 		return 1;
661 	if (*sym != '.')
662 		return 0;
663 	do {
664 		char c = *sym++;
665 		if (c < '0' || c > '9')
666 			return 0;
667 	} while (*sym);
668 	return 1;
669 }
670 
671 /* The pattern is an array of simple patterns.
672  * "foo" will match an exact string equal to "foo"
673  * "*foo" will match a string that ends with "foo"
674  * "foo*" will match a string that begins with "foo"
675  * "foo$" will match a string equal to "foo" or "foo.1"
676  *   where the '1' can be any number including several digits.
677  *   The $ syntax is for sections where ld append a dot number
678  *   to make section name unique.
679  */
match(const char * sym,const char * const pat[])680 int match(const char *sym, const char * const pat[])
681 {
682 	const char *p;
683 	while (*pat) {
684 		p = *pat++;
685 		const char *endp = p + strlen(p) - 1;
686 
687 		/* "*foo" */
688 		if (*p == '*') {
689 			if (strrcmp(sym, p + 1) == 0)
690 				return 1;
691 		}
692 		/* "foo*" */
693 		else if (*endp == '*') {
694 			if (strncmp(sym, p, strlen(p) - 1) == 0)
695 				return 1;
696 		}
697 		/* "foo$" */
698 		else if (*endp == '$') {
699 			if (strncmp(sym, p, strlen(p) - 1) == 0) {
700 				if (number_prefix(sym + strlen(p) - 1))
701 					return 1;
702 			}
703 		}
704 		/* no wildcards */
705 		else {
706 			if (strcmp(p, sym) == 0)
707 				return 1;
708 		}
709 	}
710 	/* no match */
711 	return 0;
712 }
713 
714 /* sections that we do not want to do full section mismatch check on */
715 static const char *section_white_list[] =
716 {
717 	".comment*",
718 	".debug*",
719 	".mdebug*",        /* alpha, score, mips etc. */
720 	".pdr",            /* alpha, score, mips etc. */
721 	".stab*",
722 	".note*",
723 	".got*",
724 	".toc*",
725 	NULL
726 };
727 
728 /*
729  * This is used to find sections missing the SHF_ALLOC flag.
730  * The cause of this is often a section specified in assembler
731  * without "ax" / "aw".
732  */
check_section(const char * modname,struct elf_info * elf,Elf_Shdr * sechdr)733 static void check_section(const char *modname, struct elf_info *elf,
734                           Elf_Shdr *sechdr)
735 {
736 	const char *sec = sech_name(elf, sechdr);
737 
738 	if (sechdr->sh_type == SHT_PROGBITS &&
739 	    !(sechdr->sh_flags & SHF_ALLOC) &&
740 	    !match(sec, section_white_list)) {
741 		warn("%s (%s): unexpected non-allocatable section.\n"
742 		     "Did you forget to use \"ax\"/\"aw\" in a .S file?\n"
743 		     "Note that for example <linux/init.h> contains\n"
744 		     "section definitions for use in .S files.\n\n",
745 		     modname, sec);
746 	}
747 }
748 
749 
750 
751 #define ALL_INIT_DATA_SECTIONS \
752 	".init.data$", ".devinit.data$", ".cpuinit.data$", ".meminit.data$"
753 #define ALL_EXIT_DATA_SECTIONS \
754 	".exit.data$", ".devexit.data$", ".cpuexit.data$", ".memexit.data$"
755 
756 #define ALL_INIT_TEXT_SECTIONS \
757 	".init.text$", ".devinit.text$", ".cpuinit.text$", ".meminit.text$"
758 #define ALL_EXIT_TEXT_SECTIONS \
759 	".exit.text$", ".devexit.text$", ".cpuexit.text$", ".memexit.text$"
760 
761 #define ALL_INIT_SECTIONS ALL_INIT_DATA_SECTIONS, ALL_INIT_TEXT_SECTIONS
762 #define ALL_EXIT_SECTIONS ALL_EXIT_DATA_SECTIONS, ALL_EXIT_TEXT_SECTIONS
763 
764 #define DATA_SECTIONS ".data$", ".data.rel$"
765 #define TEXT_SECTIONS ".text$"
766 
767 #define INIT_SECTIONS      ".init.data$", ".init.text$"
768 #define DEV_INIT_SECTIONS  ".devinit.data$", ".devinit.text$"
769 #define CPU_INIT_SECTIONS  ".cpuinit.data$", ".cpuinit.text$"
770 #define MEM_INIT_SECTIONS  ".meminit.data$", ".meminit.text$"
771 
772 #define EXIT_SECTIONS      ".exit.data$", ".exit.text$"
773 #define DEV_EXIT_SECTIONS  ".devexit.data$", ".devexit.text$"
774 #define CPU_EXIT_SECTIONS  ".cpuexit.data$", ".cpuexit.text$"
775 #define MEM_EXIT_SECTIONS  ".memexit.data$", ".memexit.text$"
776 
777 /* init data sections */
778 static const char *init_data_sections[] = { ALL_INIT_DATA_SECTIONS, NULL };
779 
780 /* all init sections */
781 static const char *init_sections[] = { ALL_INIT_SECTIONS, NULL };
782 
783 /* All init and exit sections (code + data) */
784 static const char *init_exit_sections[] =
785 	{ALL_INIT_SECTIONS, ALL_EXIT_SECTIONS, NULL };
786 
787 /* data section */
788 static const char *data_sections[] = { DATA_SECTIONS, NULL };
789 
790 /* sections that may refer to an init/exit section with no warning */
791 static const char *initref_sections[] =
792 {
793 	".text.init.refok*",
794 	".exit.text.refok*",
795 	".data.init.refok*",
796 	NULL
797 };
798 
799 
800 /* symbols in .data that may refer to init/exit sections */
801 static const char *symbol_white_list[] =
802 {
803 	"*driver",
804 	"*_template", /* scsi uses *_template a lot */
805 	"*_timer",    /* arm uses ops structures named _timer a lot */
806 	"*_sht",      /* scsi also used *_sht to some extent */
807 	"*_ops",
808 	"*_probe",
809 	"*_probe_one",
810 	"*_console",
811 	NULL
812 };
813 
814 static const char *head_sections[] = { ".head.text*", NULL };
815 static const char *linker_symbols[] =
816 	{ "__init_begin", "_sinittext", "_einittext", NULL };
817 
818 enum mismatch {
819 	NO_MISMATCH,
820 	TEXT_TO_INIT,
821 	DATA_TO_INIT,
822 	TEXT_TO_EXIT,
823 	DATA_TO_EXIT,
824 	XXXINIT_TO_INIT,
825 	XXXEXIT_TO_EXIT,
826 	INIT_TO_EXIT,
827 	EXIT_TO_INIT,
828 	EXPORT_TO_INIT_EXIT,
829 };
830 
831 struct sectioncheck {
832 	const char *fromsec[20];
833 	const char *tosec[20];
834 	enum mismatch mismatch;
835 };
836 
837 const struct sectioncheck sectioncheck[] = {
838 /* Do not reference init/exit code/data from
839  * normal code and data
840  */
841 {
842 	.fromsec = { TEXT_SECTIONS, NULL },
843 	.tosec   = { ALL_INIT_SECTIONS, NULL },
844 	.mismatch = TEXT_TO_INIT,
845 },
846 {
847 	.fromsec = { DATA_SECTIONS, NULL },
848 	.tosec   = { ALL_INIT_SECTIONS, NULL },
849 	.mismatch = DATA_TO_INIT,
850 },
851 {
852 	.fromsec = { TEXT_SECTIONS, NULL },
853 	.tosec   = { ALL_EXIT_SECTIONS, NULL },
854 	.mismatch = TEXT_TO_EXIT,
855 },
856 {
857 	.fromsec = { DATA_SECTIONS, NULL },
858 	.tosec   = { ALL_EXIT_SECTIONS, NULL },
859 	.mismatch = DATA_TO_EXIT,
860 },
861 /* Do not reference init code/data from devinit/cpuinit/meminit code/data */
862 {
863 	.fromsec = { DEV_INIT_SECTIONS, CPU_INIT_SECTIONS, MEM_INIT_SECTIONS, NULL },
864 	.tosec   = { INIT_SECTIONS, NULL },
865 	.mismatch = XXXINIT_TO_INIT,
866 },
867 /* Do not reference exit code/data from devexit/cpuexit/memexit code/data */
868 {
869 	.fromsec = { DEV_EXIT_SECTIONS, CPU_EXIT_SECTIONS, MEM_EXIT_SECTIONS, NULL },
870 	.tosec   = { EXIT_SECTIONS, NULL },
871 	.mismatch = XXXEXIT_TO_EXIT,
872 },
873 /* Do not use exit code/data from init code */
874 {
875 	.fromsec = { ALL_INIT_SECTIONS, NULL },
876 	.tosec   = { ALL_EXIT_SECTIONS, NULL },
877 	.mismatch = INIT_TO_EXIT,
878 },
879 /* Do not use init code/data from exit code */
880 {
881 	.fromsec = { ALL_EXIT_SECTIONS, NULL },
882 	.tosec   = { ALL_INIT_SECTIONS, NULL },
883 	.mismatch = EXIT_TO_INIT,
884 },
885 /* Do not export init/exit functions or data */
886 {
887 	.fromsec = { "__ksymtab*", NULL },
888 	.tosec   = { INIT_SECTIONS, EXIT_SECTIONS, NULL },
889 	.mismatch = EXPORT_TO_INIT_EXIT
890 }
891 };
892 
section_mismatch(const char * fromsec,const char * tosec)893 static int section_mismatch(const char *fromsec, const char *tosec)
894 {
895 	int i;
896 	int elems = sizeof(sectioncheck) / sizeof(struct sectioncheck);
897 	const struct sectioncheck *check = &sectioncheck[0];
898 
899 	for (i = 0; i < elems; i++) {
900 		if (match(fromsec, check->fromsec) &&
901 		    match(tosec, check->tosec))
902 			return check->mismatch;
903 		check++;
904 	}
905 	return NO_MISMATCH;
906 }
907 
908 /**
909  * Whitelist to allow certain references to pass with no warning.
910  *
911  * Pattern 0:
912  *   Do not warn if funtion/data are marked with __init_refok/__initdata_refok.
913  *   The pattern is identified by:
914  *   fromsec = .text.init.refok* | .data.init.refok*
915  *
916  * Pattern 1:
917  *   If a module parameter is declared __initdata and permissions=0
918  *   then this is legal despite the warning generated.
919  *   We cannot see value of permissions here, so just ignore
920  *   this pattern.
921  *   The pattern is identified by:
922  *   tosec   = .init.data
923  *   fromsec = .data*
924  *   atsym   =__param*
925  *
926  * Pattern 2:
927  *   Many drivers utilise a *driver container with references to
928  *   add, remove, probe functions etc.
929  *   These functions may often be marked __init and we do not want to
930  *   warn here.
931  *   the pattern is identified by:
932  *   tosec   = init or exit section
933  *   fromsec = data section
934  *   atsym = *driver, *_template, *_sht, *_ops, *_probe,
935  *           *probe_one, *_console, *_timer
936  *
937  * Pattern 3:
938  *   Whitelist all refereces from .text.head to .init.data
939  *   Whitelist all refereces from .text.head to .init.text
940  *
941  * Pattern 4:
942  *   Some symbols belong to init section but still it is ok to reference
943  *   these from non-init sections as these symbols don't have any memory
944  *   allocated for them and symbol address and value are same. So even
945  *   if init section is freed, its ok to reference those symbols.
946  *   For ex. symbols marking the init section boundaries.
947  *   This pattern is identified by
948  *   refsymname = __init_begin, _sinittext, _einittext
949  *
950  **/
secref_whitelist(const char * fromsec,const char * fromsym,const char * tosec,const char * tosym)951 static int secref_whitelist(const char *fromsec, const char *fromsym,
952 			    const char *tosec, const char *tosym)
953 {
954 	/* Check for pattern 0 */
955 	if (match(fromsec, initref_sections))
956 		return 0;
957 
958 	/* Check for pattern 1 */
959 	if (match(tosec, init_data_sections) &&
960 	    match(fromsec, data_sections) &&
961 	    (strncmp(fromsym, "__param", strlen("__param")) == 0))
962 		return 0;
963 
964 	/* Check for pattern 2 */
965 	if (match(tosec, init_exit_sections) &&
966 	    match(fromsec, data_sections) &&
967 	    match(fromsym, symbol_white_list))
968 		return 0;
969 
970 	/* Check for pattern 3 */
971 	if (match(fromsec, head_sections) &&
972 	    match(tosec, init_sections))
973 		return 0;
974 
975 	/* Check for pattern 4 */
976 	if (match(tosym, linker_symbols))
977 		return 0;
978 
979 	return 1;
980 }
981 
982 /**
983  * Find symbol based on relocation record info.
984  * In some cases the symbol supplied is a valid symbol so
985  * return refsym. If st_name != 0 we assume this is a valid symbol.
986  * In other cases the symbol needs to be looked up in the symbol table
987  * based on section and address.
988  *  **/
find_elf_symbol(struct elf_info * elf,Elf64_Sword addr,Elf_Sym * relsym)989 static Elf_Sym *find_elf_symbol(struct elf_info *elf, Elf64_Sword addr,
990 				Elf_Sym *relsym)
991 {
992 	Elf_Sym *sym;
993 	Elf_Sym *near = NULL;
994 	Elf64_Sword distance = 20;
995 	Elf64_Sword d;
996 
997 	if (relsym->st_name != 0)
998 		return relsym;
999 	for (sym = elf->symtab_start; sym < elf->symtab_stop; sym++) {
1000 		if (sym->st_shndx != relsym->st_shndx)
1001 			continue;
1002 		if (ELF_ST_TYPE(sym->st_info) == STT_SECTION)
1003 			continue;
1004 		if (sym->st_value == addr)
1005 			return sym;
1006 		/* Find a symbol nearby - addr are maybe negative */
1007 		d = sym->st_value - addr;
1008 		if (d < 0)
1009 			d = addr - sym->st_value;
1010 		if (d < distance) {
1011 			distance = d;
1012 			near = sym;
1013 		}
1014 	}
1015 	/* We need a close match */
1016 	if (distance < 20)
1017 		return near;
1018 	else
1019 		return NULL;
1020 }
1021 
is_arm_mapping_symbol(const char * str)1022 static inline int is_arm_mapping_symbol(const char *str)
1023 {
1024 	return str[0] == '$' && strchr("atd", str[1])
1025 	       && (str[2] == '\0' || str[2] == '.');
1026 }
1027 
1028 /*
1029  * If there's no name there, ignore it; likewise, ignore it if it's
1030  * one of the magic symbols emitted used by current ARM tools.
1031  *
1032  * Otherwise if find_symbols_between() returns those symbols, they'll
1033  * fail the whitelist tests and cause lots of false alarms ... fixable
1034  * only by merging __exit and __init sections into __text, bloating
1035  * the kernel (which is especially evil on embedded platforms).
1036  */
is_valid_name(struct elf_info * elf,Elf_Sym * sym)1037 static inline int is_valid_name(struct elf_info *elf, Elf_Sym *sym)
1038 {
1039 	const char *name = elf->strtab + sym->st_name;
1040 
1041 	if (!name || !strlen(name))
1042 		return 0;
1043 	return !is_arm_mapping_symbol(name);
1044 }
1045 
1046 /*
1047  * Find symbols before or equal addr and after addr - in the section sec.
1048  * If we find two symbols with equal offset prefer one with a valid name.
1049  * The ELF format may have a better way to detect what type of symbol
1050  * it is, but this works for now.
1051  **/
find_elf_symbol2(struct elf_info * elf,Elf_Addr addr,const char * sec)1052 static Elf_Sym *find_elf_symbol2(struct elf_info *elf, Elf_Addr addr,
1053 				 const char *sec)
1054 {
1055 	Elf_Sym *sym;
1056 	Elf_Sym *near = NULL;
1057 	Elf_Addr distance = ~0;
1058 
1059 	for (sym = elf->symtab_start; sym < elf->symtab_stop; sym++) {
1060 		const char *symsec;
1061 
1062 		if (sym->st_shndx >= SHN_LORESERVE)
1063 			continue;
1064 		symsec = sec_name(elf, sym->st_shndx);
1065 		if (strcmp(symsec, sec) != 0)
1066 			continue;
1067 		if (!is_valid_name(elf, sym))
1068 			continue;
1069 		if (sym->st_value <= addr) {
1070 			if ((addr - sym->st_value) < distance) {
1071 				distance = addr - sym->st_value;
1072 				near = sym;
1073 			} else if ((addr - sym->st_value) == distance) {
1074 				near = sym;
1075 			}
1076 		}
1077 	}
1078 	return near;
1079 }
1080 
1081 /*
1082  * Convert a section name to the function/data attribute
1083  * .init.text => __init
1084  * .cpuinit.data => __cpudata
1085  * .memexitconst => __memconst
1086  * etc.
1087 */
sec2annotation(const char * s)1088 static char *sec2annotation(const char *s)
1089 {
1090 	if (match(s, init_exit_sections)) {
1091 		char *p = malloc(20);
1092 		char *r = p;
1093 
1094 		*p++ = '_';
1095 		*p++ = '_';
1096 		if (*s == '.')
1097 			s++;
1098 		while (*s && *s != '.')
1099 			*p++ = *s++;
1100 		*p = '\0';
1101 		if (*s == '.')
1102 			s++;
1103 		if (strstr(s, "rodata") != NULL)
1104 			strcat(p, "const ");
1105 		else if (strstr(s, "data") != NULL)
1106 			strcat(p, "data ");
1107 		else
1108 			strcat(p, " ");
1109 		return r; /* we leak her but we do not care */
1110 	} else {
1111 		return "";
1112 	}
1113 }
1114 
is_function(Elf_Sym * sym)1115 static int is_function(Elf_Sym *sym)
1116 {
1117 	if (sym)
1118 		return ELF_ST_TYPE(sym->st_info) == STT_FUNC;
1119 	else
1120 		return -1;
1121 }
1122 
1123 /*
1124  * Print a warning about a section mismatch.
1125  * Try to find symbols near it so user can find it.
1126  * Check whitelist before warning - it may be a false positive.
1127  */
report_sec_mismatch(const char * modname,enum mismatch 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)1128 static void report_sec_mismatch(const char *modname, enum mismatch mismatch,
1129                                 const char *fromsec,
1130                                 unsigned long long fromaddr,
1131                                 const char *fromsym,
1132                                 int from_is_func,
1133                                 const char *tosec, const char *tosym,
1134                                 int to_is_func)
1135 {
1136 	const char *from, *from_p;
1137 	const char *to, *to_p;
1138 
1139 	switch (from_is_func) {
1140 	case 0: from = "variable"; from_p = "";   break;
1141 	case 1: from = "function"; from_p = "()"; break;
1142 	default: from = "(unknown reference)"; from_p = ""; break;
1143 	}
1144 	switch (to_is_func) {
1145 	case 0: to = "variable"; to_p = "";   break;
1146 	case 1: to = "function"; to_p = "()"; break;
1147 	default: to = "(unknown reference)"; to_p = ""; break;
1148 	}
1149 
1150 	sec_mismatch_count++;
1151 	if (!sec_mismatch_verbose)
1152 		return;
1153 
1154 	warn("%s(%s+0x%llx): Section mismatch in reference from the %s %s%s "
1155 	     "to the %s %s:%s%s\n",
1156 	     modname, fromsec, fromaddr, from, fromsym, from_p, to, tosec,
1157 	     tosym, to_p);
1158 
1159 	switch (mismatch) {
1160 	case TEXT_TO_INIT:
1161 		fprintf(stderr,
1162 		"The function %s%s() references\n"
1163 		"the %s %s%s%s.\n"
1164 		"This is often because %s lacks a %s\n"
1165 		"annotation or the annotation of %s is wrong.\n",
1166 		sec2annotation(fromsec), fromsym,
1167 		to, sec2annotation(tosec), tosym, to_p,
1168 		fromsym, sec2annotation(tosec), tosym);
1169 		break;
1170 	case DATA_TO_INIT: {
1171 		const char **s = symbol_white_list;
1172 		fprintf(stderr,
1173 		"The variable %s references\n"
1174 		"the %s %s%s%s\n"
1175 		"If the reference is valid then annotate the\n"
1176 		"variable with __init* (see linux/init.h) "
1177 		"or name the variable:\n",
1178 		fromsym, to, sec2annotation(tosec), tosym, to_p);
1179 		while (*s)
1180 			fprintf(stderr, "%s, ", *s++);
1181 		fprintf(stderr, "\n");
1182 		break;
1183 	}
1184 	case TEXT_TO_EXIT:
1185 		fprintf(stderr,
1186 		"The function %s() references a %s in an exit section.\n"
1187 		"Often the %s %s%s has valid usage outside the exit section\n"
1188 		"and the fix is to remove the %sannotation of %s.\n",
1189 		fromsym, to, to, tosym, to_p, sec2annotation(tosec), tosym);
1190 		break;
1191 	case DATA_TO_EXIT: {
1192 		const char **s = symbol_white_list;
1193 		fprintf(stderr,
1194 		"The variable %s references\n"
1195 		"the %s %s%s%s\n"
1196 		"If the reference is valid then annotate the\n"
1197 		"variable with __exit* (see linux/init.h) or "
1198 		"name the variable:\n",
1199 		fromsym, to, sec2annotation(tosec), tosym, to_p);
1200 		while (*s)
1201 			fprintf(stderr, "%s, ", *s++);
1202 		fprintf(stderr, "\n");
1203 		break;
1204 	}
1205 	case XXXINIT_TO_INIT:
1206 	case XXXEXIT_TO_EXIT:
1207 		fprintf(stderr,
1208 		"The %s %s%s%s references\n"
1209 		"a %s %s%s%s.\n"
1210 		"If %s is only used by %s then\n"
1211 		"annotate %s with a matching annotation.\n",
1212 		from, sec2annotation(fromsec), fromsym, from_p,
1213 		to, sec2annotation(tosec), tosym, to_p,
1214 		tosym, fromsym, tosym);
1215 		break;
1216 	case INIT_TO_EXIT:
1217 		fprintf(stderr,
1218 		"The %s %s%s%s references\n"
1219 		"a %s %s%s%s.\n"
1220 		"This is often seen when error handling "
1221 		"in the init function\n"
1222 		"uses functionality in the exit path.\n"
1223 		"The fix is often to remove the %sannotation of\n"
1224 		"%s%s so it may be used outside an exit section.\n",
1225 		from, sec2annotation(fromsec), fromsym, from_p,
1226 		to, sec2annotation(tosec), tosym, to_p,
1227 		sec2annotation(tosec), tosym, to_p);
1228 		break;
1229 	case EXIT_TO_INIT:
1230 		fprintf(stderr,
1231 		"The %s %s%s%s references\n"
1232 		"a %s %s%s%s.\n"
1233 		"This is often seen when error handling "
1234 		"in the exit function\n"
1235 		"uses functionality in the init path.\n"
1236 		"The fix is often to remove the %sannotation of\n"
1237 		"%s%s so it may be used outside an init section.\n",
1238 		from, sec2annotation(fromsec), fromsym, from_p,
1239 		to, sec2annotation(tosec), tosym, to_p,
1240 		sec2annotation(tosec), tosym, to_p);
1241 		break;
1242 	case EXPORT_TO_INIT_EXIT:
1243 		fprintf(stderr,
1244 		"The symbol %s is exported and annotated %s\n"
1245 		"Fix this by removing the %sannotation of %s "
1246 		"or drop the export.\n",
1247 		tosym, sec2annotation(tosec), sec2annotation(tosec), tosym);
1248 	case NO_MISMATCH:
1249 		/* To get warnings on missing members */
1250 		break;
1251 	}
1252 	fprintf(stderr, "\n");
1253 }
1254 
check_section_mismatch(const char * modname,struct elf_info * elf,Elf_Rela * r,Elf_Sym * sym,const char * fromsec)1255 static void check_section_mismatch(const char *modname, struct elf_info *elf,
1256                                    Elf_Rela *r, Elf_Sym *sym, const char *fromsec)
1257 {
1258 	const char *tosec;
1259 	enum mismatch mismatch;
1260 
1261 	tosec = sec_name(elf, sym->st_shndx);
1262 	mismatch = section_mismatch(fromsec, tosec);
1263 	if (mismatch != NO_MISMATCH) {
1264 		Elf_Sym *to;
1265 		Elf_Sym *from;
1266 		const char *tosym;
1267 		const char *fromsym;
1268 
1269 		from = find_elf_symbol2(elf, r->r_offset, fromsec);
1270 		fromsym = sym_name(elf, from);
1271 		to = find_elf_symbol(elf, r->r_addend, sym);
1272 		tosym = sym_name(elf, to);
1273 
1274 		/* check whitelist - we may ignore it */
1275 		if (secref_whitelist(fromsec, fromsym, tosec, tosym)) {
1276 			report_sec_mismatch(modname, mismatch,
1277 			   fromsec, r->r_offset, fromsym,
1278 			   is_function(from), tosec, tosym,
1279 			   is_function(to));
1280 		}
1281 	}
1282 }
1283 
reloc_location(struct elf_info * elf,Elf_Shdr * sechdr,Elf_Rela * r)1284 static unsigned int *reloc_location(struct elf_info *elf,
1285 				    Elf_Shdr *sechdr, Elf_Rela *r)
1286 {
1287 	Elf_Shdr *sechdrs = elf->sechdrs;
1288 	int section = sechdr->sh_info;
1289 
1290 	return (void *)elf->hdr + sechdrs[section].sh_offset +
1291 		r->r_offset - sechdrs[section].sh_addr;
1292 }
1293 
addend_386_rel(struct elf_info * elf,Elf_Shdr * sechdr,Elf_Rela * r)1294 static int addend_386_rel(struct elf_info *elf, Elf_Shdr *sechdr, Elf_Rela *r)
1295 {
1296 	unsigned int r_typ = ELF_R_TYPE(r->r_info);
1297 	unsigned int *location = reloc_location(elf, sechdr, r);
1298 
1299 	switch (r_typ) {
1300 	case R_386_32:
1301 		r->r_addend = TO_NATIVE(*location);
1302 		break;
1303 	case R_386_PC32:
1304 		r->r_addend = TO_NATIVE(*location) + 4;
1305 		/* For CONFIG_RELOCATABLE=y */
1306 		if (elf->hdr->e_type == ET_EXEC)
1307 			r->r_addend += r->r_offset;
1308 		break;
1309 	}
1310 	return 0;
1311 }
1312 
addend_arm_rel(struct elf_info * elf,Elf_Shdr * sechdr,Elf_Rela * r)1313 static int addend_arm_rel(struct elf_info *elf, Elf_Shdr *sechdr, Elf_Rela *r)
1314 {
1315 	unsigned int r_typ = ELF_R_TYPE(r->r_info);
1316 
1317 	switch (r_typ) {
1318 	case R_ARM_ABS32:
1319 		/* From ARM ABI: (S + A) | T */
1320 		r->r_addend = (int)(long)
1321 		              (elf->symtab_start + ELF_R_SYM(r->r_info));
1322 		break;
1323 	case R_ARM_PC24:
1324 		/* From ARM ABI: ((S + A) | T) - P */
1325 		r->r_addend = (int)(long)(elf->hdr +
1326 		              sechdr->sh_offset +
1327 		              (r->r_offset - sechdr->sh_addr));
1328 		break;
1329 	default:
1330 		return 1;
1331 	}
1332 	return 0;
1333 }
1334 
addend_mips_rel(struct elf_info * elf,Elf_Shdr * sechdr,Elf_Rela * r)1335 static int addend_mips_rel(struct elf_info *elf, Elf_Shdr *sechdr, Elf_Rela *r)
1336 {
1337 	unsigned int r_typ = ELF_R_TYPE(r->r_info);
1338 	unsigned int *location = reloc_location(elf, sechdr, r);
1339 	unsigned int inst;
1340 
1341 	if (r_typ == R_MIPS_HI16)
1342 		return 1;	/* skip this */
1343 	inst = TO_NATIVE(*location);
1344 	switch (r_typ) {
1345 	case R_MIPS_LO16:
1346 		r->r_addend = inst & 0xffff;
1347 		break;
1348 	case R_MIPS_26:
1349 		r->r_addend = (inst & 0x03ffffff) << 2;
1350 		break;
1351 	case R_MIPS_32:
1352 		r->r_addend = inst;
1353 		break;
1354 	}
1355 	return 0;
1356 }
1357 
section_rela(const char * modname,struct elf_info * elf,Elf_Shdr * sechdr)1358 static void section_rela(const char *modname, struct elf_info *elf,
1359                          Elf_Shdr *sechdr)
1360 {
1361 	Elf_Sym  *sym;
1362 	Elf_Rela *rela;
1363 	Elf_Rela r;
1364 	unsigned int r_sym;
1365 	const char *fromsec;
1366 
1367 	Elf_Rela *start = (void *)elf->hdr + sechdr->sh_offset;
1368 	Elf_Rela *stop  = (void *)start + sechdr->sh_size;
1369 
1370 	fromsec = sech_name(elf, sechdr);
1371 	fromsec += strlen(".rela");
1372 	/* if from section (name) is know good then skip it */
1373 	if (match(fromsec, section_white_list))
1374 		return;
1375 
1376 	for (rela = start; rela < stop; rela++) {
1377 		r.r_offset = TO_NATIVE(rela->r_offset);
1378 #if KERNEL_ELFCLASS == ELFCLASS64
1379 		if (elf->hdr->e_machine == EM_MIPS) {
1380 			unsigned int r_typ;
1381 			r_sym = ELF64_MIPS_R_SYM(rela->r_info);
1382 			r_sym = TO_NATIVE(r_sym);
1383 			r_typ = ELF64_MIPS_R_TYPE(rela->r_info);
1384 			r.r_info = ELF64_R_INFO(r_sym, r_typ);
1385 		} else {
1386 			r.r_info = TO_NATIVE(rela->r_info);
1387 			r_sym = ELF_R_SYM(r.r_info);
1388 		}
1389 #else
1390 		r.r_info = TO_NATIVE(rela->r_info);
1391 		r_sym = ELF_R_SYM(r.r_info);
1392 #endif
1393 		r.r_addend = TO_NATIVE(rela->r_addend);
1394 		sym = elf->symtab_start + r_sym;
1395 		/* Skip special sections */
1396 		if (sym->st_shndx >= SHN_LORESERVE)
1397 			continue;
1398 		check_section_mismatch(modname, elf, &r, sym, fromsec);
1399 	}
1400 }
1401 
section_rel(const char * modname,struct elf_info * elf,Elf_Shdr * sechdr)1402 static void section_rel(const char *modname, struct elf_info *elf,
1403                         Elf_Shdr *sechdr)
1404 {
1405 	Elf_Sym *sym;
1406 	Elf_Rel *rel;
1407 	Elf_Rela r;
1408 	unsigned int r_sym;
1409 	const char *fromsec;
1410 
1411 	Elf_Rel *start = (void *)elf->hdr + sechdr->sh_offset;
1412 	Elf_Rel *stop  = (void *)start + sechdr->sh_size;
1413 
1414 	fromsec = sech_name(elf, sechdr);
1415 	fromsec += strlen(".rel");
1416 	/* if from section (name) is know good then skip it */
1417 	if (match(fromsec, section_white_list))
1418 		return;
1419 
1420 	for (rel = start; rel < stop; rel++) {
1421 		r.r_offset = TO_NATIVE(rel->r_offset);
1422 #if KERNEL_ELFCLASS == ELFCLASS64
1423 		if (elf->hdr->e_machine == EM_MIPS) {
1424 			unsigned int r_typ;
1425 			r_sym = ELF64_MIPS_R_SYM(rel->r_info);
1426 			r_sym = TO_NATIVE(r_sym);
1427 			r_typ = ELF64_MIPS_R_TYPE(rel->r_info);
1428 			r.r_info = ELF64_R_INFO(r_sym, r_typ);
1429 		} else {
1430 			r.r_info = TO_NATIVE(rel->r_info);
1431 			r_sym = ELF_R_SYM(r.r_info);
1432 		}
1433 #else
1434 		r.r_info = TO_NATIVE(rel->r_info);
1435 		r_sym = ELF_R_SYM(r.r_info);
1436 #endif
1437 		r.r_addend = 0;
1438 		switch (elf->hdr->e_machine) {
1439 		case EM_386:
1440 			if (addend_386_rel(elf, sechdr, &r))
1441 				continue;
1442 			break;
1443 		case EM_ARM:
1444 			if (addend_arm_rel(elf, sechdr, &r))
1445 				continue;
1446 			break;
1447 		case EM_MIPS:
1448 			if (addend_mips_rel(elf, sechdr, &r))
1449 				continue;
1450 			break;
1451 		}
1452 		sym = elf->symtab_start + r_sym;
1453 		/* Skip special sections */
1454 		if (sym->st_shndx >= SHN_LORESERVE)
1455 			continue;
1456 		check_section_mismatch(modname, elf, &r, sym, fromsec);
1457 	}
1458 }
1459 
1460 /**
1461  * A module includes a number of sections that are discarded
1462  * either when loaded or when used as built-in.
1463  * For loaded modules all functions marked __init and all data
1464  * marked __initdata will be discarded when the module has been intialized.
1465  * Likewise for modules used built-in the sections marked __exit
1466  * are discarded because __exit marked function are supposed to be called
1467  * only when a module is unloaded which never happens for built-in modules.
1468  * The check_sec_ref() function traverses all relocation records
1469  * to find all references to a section that reference a section that will
1470  * be discarded and warns about it.
1471  **/
check_sec_ref(struct module * mod,const char * modname,struct elf_info * elf)1472 static void check_sec_ref(struct module *mod, const char *modname,
1473                           struct elf_info *elf)
1474 {
1475 	int i;
1476 	Elf_Shdr *sechdrs = elf->sechdrs;
1477 
1478 	/* Walk through all sections */
1479 	for (i = 0; i < elf->hdr->e_shnum; i++) {
1480 		check_section(modname, elf, &elf->sechdrs[i]);
1481 		/* We want to process only relocation sections and not .init */
1482 		if (sechdrs[i].sh_type == SHT_RELA)
1483 			section_rela(modname, elf, &elf->sechdrs[i]);
1484 		else if (sechdrs[i].sh_type == SHT_REL)
1485 			section_rel(modname, elf, &elf->sechdrs[i]);
1486 	}
1487 }
1488 
get_markers(struct elf_info * info,struct module * mod)1489 static void get_markers(struct elf_info *info, struct module *mod)
1490 {
1491 	const Elf_Shdr *sh = &info->sechdrs[info->markers_strings_sec];
1492 	const char *strings = (const char *) info->hdr + sh->sh_offset;
1493 	const Elf_Sym *sym, *first_sym, *last_sym;
1494 	size_t n;
1495 
1496 	if (!info->markers_strings_sec)
1497 		return;
1498 
1499 	/*
1500 	 * First count the strings.  We look for all the symbols defined
1501 	 * in the __markers_strings section named __mstrtab_*.  For
1502 	 * these local names, the compiler puts a random .NNN suffix on,
1503 	 * so the names don't correspond exactly.
1504 	 */
1505 	first_sym = last_sym = NULL;
1506 	n = 0;
1507 	for (sym = info->symtab_start; sym < info->symtab_stop; sym++)
1508 		if (ELF_ST_TYPE(sym->st_info) == STT_OBJECT &&
1509 		    sym->st_shndx == info->markers_strings_sec &&
1510 		    !strncmp(info->strtab + sym->st_name,
1511 			     "__mstrtab_", sizeof "__mstrtab_" - 1)) {
1512 			if (first_sym == NULL)
1513 				first_sym = sym;
1514 			last_sym = sym;
1515 			++n;
1516 		}
1517 
1518 	if (n == 0)
1519 		return;
1520 
1521 	/*
1522 	 * Now collect each name and format into a line for the output.
1523 	 * Lines look like:
1524 	 *	marker_name	vmlinux	marker %s format %d
1525 	 * The format string after the second \t can use whitespace.
1526 	 */
1527 	mod->markers = NOFAIL(malloc(sizeof mod->markers[0] * n));
1528 	mod->nmarkers = n;
1529 
1530 	n = 0;
1531 	for (sym = first_sym; sym <= last_sym; sym++)
1532 		if (ELF_ST_TYPE(sym->st_info) == STT_OBJECT &&
1533 		    sym->st_shndx == info->markers_strings_sec &&
1534 		    !strncmp(info->strtab + sym->st_name,
1535 			     "__mstrtab_", sizeof "__mstrtab_" - 1)) {
1536 			const char *name = strings + sym->st_value;
1537 			const char *fmt = strchr(name, '\0') + 1;
1538 			char *line = NULL;
1539 			asprintf(&line, "%s\t%s\t%s\n", name, mod->name, fmt);
1540 			NOFAIL(line);
1541 			mod->markers[n++] = line;
1542 		}
1543 }
1544 
read_symbols(char * modname)1545 static void read_symbols(char *modname)
1546 {
1547 	const char *symname;
1548 	char *version;
1549 	char *license;
1550 	struct module *mod;
1551 	struct elf_info info = { };
1552 	Elf_Sym *sym;
1553 
1554 	if (!parse_elf(&info, modname))
1555 		return;
1556 
1557 	mod = new_module(modname);
1558 
1559 	/* When there's no vmlinux, don't print warnings about
1560 	 * unresolved symbols (since there'll be too many ;) */
1561 	if (is_vmlinux(modname)) {
1562 		have_vmlinux = 1;
1563 		mod->skip = 1;
1564 	}
1565 
1566 	license = get_modinfo(info.modinfo, info.modinfo_len, "license");
1567 	if (info.modinfo && !license && !is_vmlinux(modname))
1568 		warn("modpost: missing MODULE_LICENSE() in %s\n"
1569 		     "see include/linux/module.h for "
1570 		     "more information\n", modname);
1571 	while (license) {
1572 		if (license_is_gpl_compatible(license))
1573 			mod->gpl_compatible = 1;
1574 		else {
1575 			mod->gpl_compatible = 0;
1576 			break;
1577 		}
1578 		license = get_next_modinfo(info.modinfo, info.modinfo_len,
1579 					   "license", license);
1580 	}
1581 
1582 	for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
1583 		symname = info.strtab + sym->st_name;
1584 
1585 		handle_modversions(mod, &info, sym, symname);
1586 		handle_moddevtable(mod, &info, sym, symname);
1587 	}
1588 	if (!is_vmlinux(modname) ||
1589 	     (is_vmlinux(modname) && vmlinux_section_warnings))
1590 		check_sec_ref(mod, modname, &info);
1591 
1592 	version = get_modinfo(info.modinfo, info.modinfo_len, "version");
1593 	if (version)
1594 		maybe_frob_rcs_version(modname, version, info.modinfo,
1595 				       version - (char *)info.hdr);
1596 	if (version || (all_versions && !is_vmlinux(modname)))
1597 		get_src_version(modname, mod->srcversion,
1598 				sizeof(mod->srcversion)-1);
1599 
1600 	get_markers(&info, mod);
1601 
1602 	parse_elf_finish(&info);
1603 
1604 	/* Our trick to get versioning for struct_module - it's
1605 	 * never passed as an argument to an exported function, so
1606 	 * the automatic versioning doesn't pick it up, but it's really
1607 	 * important anyhow */
1608 	if (modversions)
1609 		mod->unres = alloc_symbol("struct_module", 0, mod->unres);
1610 }
1611 
1612 #define SZ 500
1613 
1614 /* We first write the generated file into memory using the
1615  * following helper, then compare to the file on disk and
1616  * only update the later if anything changed */
1617 
buf_printf(struct buffer * buf,const char * fmt,...)1618 void __attribute__((format(printf, 2, 3))) buf_printf(struct buffer *buf,
1619 						      const char *fmt, ...)
1620 {
1621 	char tmp[SZ];
1622 	int len;
1623 	va_list ap;
1624 
1625 	va_start(ap, fmt);
1626 	len = vsnprintf(tmp, SZ, fmt, ap);
1627 	buf_write(buf, tmp, len);
1628 	va_end(ap);
1629 }
1630 
buf_write(struct buffer * buf,const char * s,int len)1631 void buf_write(struct buffer *buf, const char *s, int len)
1632 {
1633 	if (buf->size - buf->pos < len) {
1634 		buf->size += len + SZ;
1635 		buf->p = realloc(buf->p, buf->size);
1636 	}
1637 	strncpy(buf->p + buf->pos, s, len);
1638 	buf->pos += len;
1639 }
1640 
check_for_gpl_usage(enum export exp,const char * m,const char * s)1641 static void check_for_gpl_usage(enum export exp, const char *m, const char *s)
1642 {
1643 	const char *e = is_vmlinux(m) ?"":".ko";
1644 
1645 	switch (exp) {
1646 	case export_gpl:
1647 		fatal("modpost: GPL-incompatible module %s%s "
1648 		      "uses GPL-only symbol '%s'\n", m, e, s);
1649 		break;
1650 	case export_unused_gpl:
1651 		fatal("modpost: GPL-incompatible module %s%s "
1652 		      "uses GPL-only symbol marked UNUSED '%s'\n", m, e, s);
1653 		break;
1654 	case export_gpl_future:
1655 		warn("modpost: GPL-incompatible module %s%s "
1656 		      "uses future GPL-only symbol '%s'\n", m, e, s);
1657 		break;
1658 	case export_plain:
1659 	case export_unused:
1660 	case export_unknown:
1661 		/* ignore */
1662 		break;
1663 	}
1664 }
1665 
check_for_unused(enum export exp,const char * m,const char * s)1666 static void check_for_unused(enum export exp, const char *m, const char *s)
1667 {
1668 	const char *e = is_vmlinux(m) ?"":".ko";
1669 
1670 	switch (exp) {
1671 	case export_unused:
1672 	case export_unused_gpl:
1673 		warn("modpost: module %s%s "
1674 		      "uses symbol '%s' marked UNUSED\n", m, e, s);
1675 		break;
1676 	default:
1677 		/* ignore */
1678 		break;
1679 	}
1680 }
1681 
check_exports(struct module * mod)1682 static void check_exports(struct module *mod)
1683 {
1684 	struct symbol *s, *exp;
1685 
1686 	for (s = mod->unres; s; s = s->next) {
1687 		const char *basename;
1688 		exp = find_symbol(s->name);
1689 		if (!exp || exp->module == mod)
1690 			continue;
1691 		basename = strrchr(mod->name, '/');
1692 		if (basename)
1693 			basename++;
1694 		else
1695 			basename = mod->name;
1696 		if (!mod->gpl_compatible)
1697 			check_for_gpl_usage(exp->export, basename, exp->name);
1698 		check_for_unused(exp->export, basename, exp->name);
1699 	}
1700 }
1701 
1702 /**
1703  * Header for the generated file
1704  **/
add_header(struct buffer * b,struct module * mod)1705 static void add_header(struct buffer *b, struct module *mod)
1706 {
1707 	buf_printf(b, "#include <linux/module.h>\n");
1708 	buf_printf(b, "#include <linux/vermagic.h>\n");
1709 	buf_printf(b, "#include <linux/compiler.h>\n");
1710 	buf_printf(b, "\n");
1711 	buf_printf(b, "MODULE_INFO(vermagic, VERMAGIC_STRING);\n");
1712 	buf_printf(b, "\n");
1713 	buf_printf(b, "struct module __this_module\n");
1714 	buf_printf(b, "__attribute__((section(\".gnu.linkonce.this_module\"))) = {\n");
1715 	buf_printf(b, " .name = KBUILD_MODNAME,\n");
1716 	if (mod->has_init)
1717 		buf_printf(b, " .init = init_module,\n");
1718 	if (mod->has_cleanup)
1719 		buf_printf(b, "#ifdef CONFIG_MODULE_UNLOAD\n"
1720 			      " .exit = cleanup_module,\n"
1721 			      "#endif\n");
1722 	buf_printf(b, " .arch = MODULE_ARCH_INIT,\n");
1723 	buf_printf(b, "};\n");
1724 }
1725 
add_staging_flag(struct buffer * b,const char * name)1726 void add_staging_flag(struct buffer *b, const char *name)
1727 {
1728 	static const char *staging_dir = "drivers/staging";
1729 
1730 	if (strncmp(staging_dir, name, strlen(staging_dir)) == 0)
1731 		buf_printf(b, "\nMODULE_INFO(staging, \"Y\");\n");
1732 }
1733 
1734 /**
1735  * Record CRCs for unresolved symbols
1736  **/
add_versions(struct buffer * b,struct module * mod)1737 static int add_versions(struct buffer *b, struct module *mod)
1738 {
1739 	struct symbol *s, *exp;
1740 	int err = 0;
1741 
1742 	for (s = mod->unres; s; s = s->next) {
1743 		exp = find_symbol(s->name);
1744 		if (!exp || exp->module == mod) {
1745 			if (have_vmlinux && !s->weak) {
1746 				if (warn_unresolved) {
1747 					warn("\"%s\" [%s.ko] undefined!\n",
1748 					     s->name, mod->name);
1749 				} else {
1750 					merror("\"%s\" [%s.ko] undefined!\n",
1751 					          s->name, mod->name);
1752 					err = 1;
1753 				}
1754 			}
1755 			continue;
1756 		}
1757 		s->module = exp->module;
1758 		s->crc_valid = exp->crc_valid;
1759 		s->crc = exp->crc;
1760 	}
1761 
1762 	if (!modversions)
1763 		return err;
1764 
1765 	buf_printf(b, "\n");
1766 	buf_printf(b, "static const struct modversion_info ____versions[]\n");
1767 	buf_printf(b, "__used\n");
1768 	buf_printf(b, "__attribute__((section(\"__versions\"))) = {\n");
1769 
1770 	for (s = mod->unres; s; s = s->next) {
1771 		if (!s->module)
1772 			continue;
1773 		if (!s->crc_valid) {
1774 			warn("\"%s\" [%s.ko] has no CRC!\n",
1775 				s->name, mod->name);
1776 			continue;
1777 		}
1778 		buf_printf(b, "\t{ %#8x, \"%s\" },\n", s->crc, s->name);
1779 	}
1780 
1781 	buf_printf(b, "};\n");
1782 
1783 	return err;
1784 }
1785 
add_depends(struct buffer * b,struct module * mod,struct module * modules)1786 static void add_depends(struct buffer *b, struct module *mod,
1787 			struct module *modules)
1788 {
1789 	struct symbol *s;
1790 	struct module *m;
1791 	int first = 1;
1792 
1793 	for (m = modules; m; m = m->next)
1794 		m->seen = is_vmlinux(m->name);
1795 
1796 	buf_printf(b, "\n");
1797 	buf_printf(b, "static const char __module_depends[]\n");
1798 	buf_printf(b, "__used\n");
1799 	buf_printf(b, "__attribute__((section(\".modinfo\"))) =\n");
1800 	buf_printf(b, "\"depends=");
1801 	for (s = mod->unres; s; s = s->next) {
1802 		const char *p;
1803 		if (!s->module)
1804 			continue;
1805 
1806 		if (s->module->seen)
1807 			continue;
1808 
1809 		s->module->seen = 1;
1810 		p = strrchr(s->module->name, '/');
1811 		if (p)
1812 			p++;
1813 		else
1814 			p = s->module->name;
1815 		buf_printf(b, "%s%s", first ? "" : ",", p);
1816 		first = 0;
1817 	}
1818 	buf_printf(b, "\";\n");
1819 }
1820 
add_srcversion(struct buffer * b,struct module * mod)1821 static void add_srcversion(struct buffer *b, struct module *mod)
1822 {
1823 	if (mod->srcversion[0]) {
1824 		buf_printf(b, "\n");
1825 		buf_printf(b, "MODULE_INFO(srcversion, \"%s\");\n",
1826 			   mod->srcversion);
1827 	}
1828 }
1829 
write_if_changed(struct buffer * b,const char * fname)1830 static void write_if_changed(struct buffer *b, const char *fname)
1831 {
1832 	char *tmp;
1833 	FILE *file;
1834 	struct stat st;
1835 
1836 	file = fopen(fname, "r");
1837 	if (!file)
1838 		goto write;
1839 
1840 	if (fstat(fileno(file), &st) < 0)
1841 		goto close_write;
1842 
1843 	if (st.st_size != b->pos)
1844 		goto close_write;
1845 
1846 	tmp = NOFAIL(malloc(b->pos));
1847 	if (fread(tmp, 1, b->pos, file) != b->pos)
1848 		goto free_write;
1849 
1850 	if (memcmp(tmp, b->p, b->pos) != 0)
1851 		goto free_write;
1852 
1853 	free(tmp);
1854 	fclose(file);
1855 	return;
1856 
1857  free_write:
1858 	free(tmp);
1859  close_write:
1860 	fclose(file);
1861  write:
1862 	file = fopen(fname, "w");
1863 	if (!file) {
1864 		perror(fname);
1865 		exit(1);
1866 	}
1867 	if (fwrite(b->p, 1, b->pos, file) != b->pos) {
1868 		perror(fname);
1869 		exit(1);
1870 	}
1871 	fclose(file);
1872 }
1873 
1874 /* parse Module.symvers file. line format:
1875  * 0x12345678<tab>symbol<tab>module[[<tab>export]<tab>something]
1876  **/
read_dump(const char * fname,unsigned int kernel)1877 static void read_dump(const char *fname, unsigned int kernel)
1878 {
1879 	unsigned long size, pos = 0;
1880 	void *file = grab_file(fname, &size);
1881 	char *line;
1882 
1883 	if (!file)
1884 		/* No symbol versions, silently ignore */
1885 		return;
1886 
1887 	while ((line = get_next_line(&pos, file, size))) {
1888 		char *symname, *modname, *d, *export, *end;
1889 		unsigned int crc;
1890 		struct module *mod;
1891 		struct symbol *s;
1892 
1893 		if (!(symname = strchr(line, '\t')))
1894 			goto fail;
1895 		*symname++ = '\0';
1896 		if (!(modname = strchr(symname, '\t')))
1897 			goto fail;
1898 		*modname++ = '\0';
1899 		if ((export = strchr(modname, '\t')) != NULL)
1900 			*export++ = '\0';
1901 		if (export && ((end = strchr(export, '\t')) != NULL))
1902 			*end = '\0';
1903 		crc = strtoul(line, &d, 16);
1904 		if (*symname == '\0' || *modname == '\0' || *d != '\0')
1905 			goto fail;
1906 		mod = find_module(modname);
1907 		if (!mod) {
1908 			if (is_vmlinux(modname))
1909 				have_vmlinux = 1;
1910 			mod = new_module(NOFAIL(strdup(modname)));
1911 			mod->skip = 1;
1912 		}
1913 		s = sym_add_exported(symname, mod, export_no(export));
1914 		s->kernel    = kernel;
1915 		s->preloaded = 1;
1916 		sym_update_crc(symname, mod, crc, export_no(export));
1917 	}
1918 	return;
1919 fail:
1920 	fatal("parse error in symbol dump file\n");
1921 }
1922 
1923 /* For normal builds always dump all symbols.
1924  * For external modules only dump symbols
1925  * that are not read from kernel Module.symvers.
1926  **/
dump_sym(struct symbol * sym)1927 static int dump_sym(struct symbol *sym)
1928 {
1929 	if (!external_module)
1930 		return 1;
1931 	if (sym->vmlinux || sym->kernel)
1932 		return 0;
1933 	return 1;
1934 }
1935 
write_dump(const char * fname)1936 static void write_dump(const char *fname)
1937 {
1938 	struct buffer buf = { };
1939 	struct symbol *symbol;
1940 	int n;
1941 
1942 	for (n = 0; n < SYMBOL_HASH_SIZE ; n++) {
1943 		symbol = symbolhash[n];
1944 		while (symbol) {
1945 			if (dump_sym(symbol))
1946 				buf_printf(&buf, "0x%08x\t%s\t%s\t%s\n",
1947 					symbol->crc, symbol->name,
1948 					symbol->module->name,
1949 					export_str(symbol->export));
1950 			symbol = symbol->next;
1951 		}
1952 	}
1953 	write_if_changed(&buf, fname);
1954 }
1955 
add_marker(struct module * mod,const char * name,const char * fmt)1956 static void add_marker(struct module *mod, const char *name, const char *fmt)
1957 {
1958 	char *line = NULL;
1959 	asprintf(&line, "%s\t%s\t%s\n", name, mod->name, fmt);
1960 	NOFAIL(line);
1961 
1962 	mod->markers = NOFAIL(realloc(mod->markers, ((mod->nmarkers + 1) *
1963 						     sizeof mod->markers[0])));
1964 	mod->markers[mod->nmarkers++] = line;
1965 }
1966 
read_markers(const char * fname)1967 static void read_markers(const char *fname)
1968 {
1969 	unsigned long size, pos = 0;
1970 	void *file = grab_file(fname, &size);
1971 	char *line;
1972 
1973 	if (!file)		/* No old markers, silently ignore */
1974 		return;
1975 
1976 	while ((line = get_next_line(&pos, file, size))) {
1977 		char *marker, *modname, *fmt;
1978 		struct module *mod;
1979 
1980 		marker = line;
1981 		modname = strchr(marker, '\t');
1982 		if (!modname)
1983 			goto fail;
1984 		*modname++ = '\0';
1985 		fmt = strchr(modname, '\t');
1986 		if (!fmt)
1987 			goto fail;
1988 		*fmt++ = '\0';
1989 		if (*marker == '\0' || *modname == '\0')
1990 			goto fail;
1991 
1992 		mod = find_module(modname);
1993 		if (!mod) {
1994 			mod = new_module(NOFAIL(strdup(modname)));
1995 			mod->skip = 1;
1996 		}
1997 		if (is_vmlinux(modname)) {
1998 			have_vmlinux = 1;
1999 			mod->skip = 0;
2000 		}
2001 
2002 		if (!mod->skip)
2003 			add_marker(mod, marker, fmt);
2004 	}
2005 	return;
2006 fail:
2007 	fatal("parse error in markers list file\n");
2008 }
2009 
compare_strings(const void * a,const void * b)2010 static int compare_strings(const void *a, const void *b)
2011 {
2012 	return strcmp(*(const char **) a, *(const char **) b);
2013 }
2014 
write_markers(const char * fname)2015 static void write_markers(const char *fname)
2016 {
2017 	struct buffer buf = { };
2018 	struct module *mod;
2019 	size_t i;
2020 
2021 	for (mod = modules; mod; mod = mod->next)
2022 		if ((!external_module || !mod->skip) && mod->markers != NULL) {
2023 			/*
2024 			 * Sort the strings so we can skip duplicates when
2025 			 * we write them out.
2026 			 */
2027 			qsort(mod->markers, mod->nmarkers,
2028 			      sizeof mod->markers[0], &compare_strings);
2029 			for (i = 0; i < mod->nmarkers; ++i) {
2030 				char *line = mod->markers[i];
2031 				buf_write(&buf, line, strlen(line));
2032 				while (i + 1 < mod->nmarkers &&
2033 				       !strcmp(mod->markers[i],
2034 					       mod->markers[i + 1]))
2035 					free(mod->markers[i++]);
2036 				free(mod->markers[i]);
2037 			}
2038 			free(mod->markers);
2039 			mod->markers = NULL;
2040 		}
2041 
2042 	write_if_changed(&buf, fname);
2043 }
2044 
2045 struct ext_sym_list {
2046 	struct ext_sym_list *next;
2047 	const char *file;
2048 };
2049 
main(int argc,char ** argv)2050 int main(int argc, char **argv)
2051 {
2052 	struct module *mod;
2053 	struct buffer buf = { };
2054 	char *kernel_read = NULL, *module_read = NULL;
2055 	char *dump_write = NULL;
2056 	char *markers_read = NULL;
2057 	char *markers_write = NULL;
2058 	int opt;
2059 	int err;
2060 	struct ext_sym_list *extsym_iter;
2061 	struct ext_sym_list *extsym_start = NULL;
2062 
2063 	while ((opt = getopt(argc, argv, "i:I:e:cmsSo:awM:K:")) != -1) {
2064 		switch (opt) {
2065 		case 'i':
2066 			kernel_read = optarg;
2067 			break;
2068 		case 'I':
2069 			module_read = optarg;
2070 			external_module = 1;
2071 			break;
2072 		case 'c':
2073 			cross_build = 1;
2074 			break;
2075 		case 'e':
2076 			external_module = 1;
2077 			extsym_iter =
2078 			   NOFAIL(malloc(sizeof(*extsym_iter)));
2079 			extsym_iter->next = extsym_start;
2080 			extsym_iter->file = optarg;
2081 			extsym_start = extsym_iter;
2082 			break;
2083 		case 'm':
2084 			modversions = 1;
2085 			break;
2086 		case 'o':
2087 			dump_write = optarg;
2088 			break;
2089 		case 'a':
2090 			all_versions = 1;
2091 			break;
2092 		case 's':
2093 			vmlinux_section_warnings = 0;
2094 			break;
2095 		case 'S':
2096 			sec_mismatch_verbose = 0;
2097 			break;
2098 		case 'w':
2099 			warn_unresolved = 1;
2100 			break;
2101 			case 'M':
2102 				markers_write = optarg;
2103 				break;
2104 			case 'K':
2105 				markers_read = optarg;
2106 				break;
2107 		default:
2108 			exit(1);
2109 		}
2110 	}
2111 
2112 	if (kernel_read)
2113 		read_dump(kernel_read, 1);
2114 	if (module_read)
2115 		read_dump(module_read, 0);
2116 	while (extsym_start) {
2117 		read_dump(extsym_start->file, 0);
2118 		extsym_iter = extsym_start->next;
2119 		free(extsym_start);
2120 		extsym_start = extsym_iter;
2121 	}
2122 
2123 	while (optind < argc)
2124 		read_symbols(argv[optind++]);
2125 
2126 	for (mod = modules; mod; mod = mod->next) {
2127 		if (mod->skip)
2128 			continue;
2129 		check_exports(mod);
2130 	}
2131 
2132 	err = 0;
2133 
2134 	for (mod = modules; mod; mod = mod->next) {
2135 		char fname[strlen(mod->name) + 10];
2136 
2137 		if (mod->skip)
2138 			continue;
2139 
2140 		buf.pos = 0;
2141 
2142 		add_header(&buf, mod);
2143 		add_staging_flag(&buf, mod->name);
2144 		err |= add_versions(&buf, mod);
2145 		add_depends(&buf, mod, modules);
2146 		add_moddevtable(&buf, mod);
2147 		add_srcversion(&buf, mod);
2148 
2149 		sprintf(fname, "%s.mod.c", mod->name);
2150 		write_if_changed(&buf, fname);
2151 	}
2152 
2153 	if (dump_write)
2154 		write_dump(dump_write);
2155 	if (sec_mismatch_count && !sec_mismatch_verbose)
2156 		warn("modpost: Found %d section mismatch(es).\n"
2157 		     "To see full details build your kernel with:\n"
2158 		     "'make CONFIG_DEBUG_SECTION_MISMATCH=y'\n",
2159 		     sec_mismatch_count);
2160 
2161 	if (markers_read)
2162 		read_markers(markers_read);
2163 
2164 	if (markers_write)
2165 		write_markers(markers_write);
2166 
2167 	return err;
2168 }
2169