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