File Index
Files and directories
Sign in
FILE

modpost.c

File preview with syntax highlighting.

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