linux/tools/lib/bpf/linker.c
<<
>>
Prefs
   1// SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
   2/*
   3 * BPF static linker
   4 *
   5 * Copyright (c) 2021 Facebook
   6 */
   7#include <stdbool.h>
   8#include <stddef.h>
   9#include <stdio.h>
  10#include <stdlib.h>
  11#include <string.h>
  12#include <unistd.h>
  13#include <errno.h>
  14#include <linux/err.h>
  15#include <linux/btf.h>
  16#include <elf.h>
  17#include <libelf.h>
  18#include <fcntl.h>
  19#include "libbpf.h"
  20#include "btf.h"
  21#include "libbpf_internal.h"
  22#include "strset.h"
  23
  24#define BTF_EXTERN_SEC ".extern"
  25
  26struct src_sec {
  27        const char *sec_name;
  28        /* positional (not necessarily ELF) index in an array of sections */
  29        int id;
  30        /* positional (not necessarily ELF) index of a matching section in a final object file */
  31        int dst_id;
  32        /* section data offset in a matching output section */
  33        int dst_off;
  34        /* whether section is omitted from the final ELF file */
  35        bool skipped;
  36        /* whether section is an ephemeral section, not mapped to an ELF section */
  37        bool ephemeral;
  38
  39        /* ELF info */
  40        size_t sec_idx;
  41        Elf_Scn *scn;
  42        Elf64_Shdr *shdr;
  43        Elf_Data *data;
  44
  45        /* corresponding BTF DATASEC type ID */
  46        int sec_type_id;
  47};
  48
  49struct src_obj {
  50        const char *filename;
  51        int fd;
  52        Elf *elf;
  53        /* Section header strings section index */
  54        size_t shstrs_sec_idx;
  55        /* SYMTAB section index */
  56        size_t symtab_sec_idx;
  57
  58        struct btf *btf;
  59        struct btf_ext *btf_ext;
  60
  61        /* List of sections (including ephemeral). Slot zero is unused. */
  62        struct src_sec *secs;
  63        int sec_cnt;
  64
  65        /* mapping of symbol indices from src to dst ELF */
  66        int *sym_map;
  67        /* mapping from the src BTF type IDs to dst ones */
  68        int *btf_type_map;
  69};
  70
  71/* single .BTF.ext data section */
  72struct btf_ext_sec_data {
  73        size_t rec_cnt;
  74        __u32 rec_sz;
  75        void *recs;
  76};
  77
  78struct glob_sym {
  79        /* ELF symbol index */
  80        int sym_idx;
  81        /* associated section id for .ksyms, .kconfig, etc, but not .extern */
  82        int sec_id;
  83        /* extern name offset in STRTAB */
  84        int name_off;
  85        /* optional associated BTF type ID */
  86        int btf_id;
  87        /* BTF type ID to which VAR/FUNC type is pointing to; used for
  88         * rewriting types when extern VAR/FUNC is resolved to a concrete
  89         * definition
  90         */
  91        int underlying_btf_id;
  92        /* sec_var index in the corresponding dst_sec, if exists */
  93        int var_idx;
  94
  95        /* extern or resolved/global symbol */
  96        bool is_extern;
  97        /* weak or strong symbol, never goes back from strong to weak */
  98        bool is_weak;
  99};
 100
 101struct dst_sec {
 102        char *sec_name;
 103        /* positional (not necessarily ELF) index in an array of sections */
 104        int id;
 105
 106        bool ephemeral;
 107
 108        /* ELF info */
 109        size_t sec_idx;
 110        Elf_Scn *scn;
 111        Elf64_Shdr *shdr;
 112        Elf_Data *data;
 113
 114        /* final output section size */
 115        int sec_sz;
 116        /* final output contents of the section */
 117        void *raw_data;
 118
 119        /* corresponding STT_SECTION symbol index in SYMTAB */
 120        int sec_sym_idx;
 121
 122        /* section's DATASEC variable info, emitted on BTF finalization */
 123        bool has_btf;
 124        int sec_var_cnt;
 125        struct btf_var_secinfo *sec_vars;
 126
 127        /* section's .BTF.ext data */
 128        struct btf_ext_sec_data func_info;
 129        struct btf_ext_sec_data line_info;
 130        struct btf_ext_sec_data core_relo_info;
 131};
 132
 133struct bpf_linker {
 134        char *filename;
 135        int fd;
 136        Elf *elf;
 137        Elf64_Ehdr *elf_hdr;
 138
 139        /* Output sections metadata */
 140        struct dst_sec *secs;
 141        int sec_cnt;
 142
 143        struct strset *strtab_strs; /* STRTAB unique strings */
 144        size_t strtab_sec_idx; /* STRTAB section index */
 145        size_t symtab_sec_idx; /* SYMTAB section index */
 146
 147        struct btf *btf;
 148        struct btf_ext *btf_ext;
 149
 150        /* global (including extern) ELF symbols */
 151        int glob_sym_cnt;
 152        struct glob_sym *glob_syms;
 153};
 154
 155#define pr_warn_elf(fmt, ...)                                                                   \
 156        libbpf_print(LIBBPF_WARN, "libbpf: " fmt ": %s\n", ##__VA_ARGS__, elf_errmsg(-1))
 157
 158static int init_output_elf(struct bpf_linker *linker, const char *file);
 159
 160static int linker_load_obj_file(struct bpf_linker *linker, const char *filename,
 161                                const struct bpf_linker_file_opts *opts,
 162                                struct src_obj *obj);
 163static int linker_sanity_check_elf(struct src_obj *obj);
 164static int linker_sanity_check_elf_symtab(struct src_obj *obj, struct src_sec *sec);
 165static int linker_sanity_check_elf_relos(struct src_obj *obj, struct src_sec *sec);
 166static int linker_sanity_check_btf(struct src_obj *obj);
 167static int linker_sanity_check_btf_ext(struct src_obj *obj);
 168static int linker_fixup_btf(struct src_obj *obj);
 169static int linker_append_sec_data(struct bpf_linker *linker, struct src_obj *obj);
 170static int linker_append_elf_syms(struct bpf_linker *linker, struct src_obj *obj);
 171static int linker_append_elf_sym(struct bpf_linker *linker, struct src_obj *obj,
 172                                 Elf64_Sym *sym, const char *sym_name, int src_sym_idx);
 173static int linker_append_elf_relos(struct bpf_linker *linker, struct src_obj *obj);
 174static int linker_append_btf(struct bpf_linker *linker, struct src_obj *obj);
 175static int linker_append_btf_ext(struct bpf_linker *linker, struct src_obj *obj);
 176
 177static int finalize_btf(struct bpf_linker *linker);
 178static int finalize_btf_ext(struct bpf_linker *linker);
 179
 180void bpf_linker__free(struct bpf_linker *linker)
 181{
 182        int i;
 183
 184        if (!linker)
 185                return;
 186
 187        free(linker->filename);
 188
 189        if (linker->elf)
 190                elf_end(linker->elf);
 191
 192        if (linker->fd >= 0)
 193                close(linker->fd);
 194
 195        strset__free(linker->strtab_strs);
 196
 197        btf__free(linker->btf);
 198        btf_ext__free(linker->btf_ext);
 199
 200        for (i = 1; i < linker->sec_cnt; i++) {
 201                struct dst_sec *sec = &linker->secs[i];
 202
 203                free(sec->sec_name);
 204                free(sec->raw_data);
 205                free(sec->sec_vars);
 206
 207                free(sec->func_info.recs);
 208                free(sec->line_info.recs);
 209                free(sec->core_relo_info.recs);
 210        }
 211        free(linker->secs);
 212
 213        free(linker);
 214}
 215
 216struct bpf_linker *bpf_linker__new(const char *filename, struct bpf_linker_opts *opts)
 217{
 218        struct bpf_linker *linker;
 219        int err;
 220
 221        if (!OPTS_VALID(opts, bpf_linker_opts))
 222                return errno = EINVAL, NULL;
 223
 224        if (elf_version(EV_CURRENT) == EV_NONE) {
 225                pr_warn_elf("libelf initialization failed");
 226                return errno = EINVAL, NULL;
 227        }
 228
 229        linker = calloc(1, sizeof(*linker));
 230        if (!linker)
 231                return errno = ENOMEM, NULL;
 232
 233        linker->fd = -1;
 234
 235        err = init_output_elf(linker, filename);
 236        if (err)
 237                goto err_out;
 238
 239        return linker;
 240
 241err_out:
 242        bpf_linker__free(linker);
 243        return errno = -err, NULL;
 244}
 245
 246static struct dst_sec *add_dst_sec(struct bpf_linker *linker, const char *sec_name)
 247{
 248        struct dst_sec *secs = linker->secs, *sec;
 249        size_t new_cnt = linker->sec_cnt ? linker->sec_cnt + 1 : 2;
 250
 251        secs = libbpf_reallocarray(secs, new_cnt, sizeof(*secs));
 252        if (!secs)
 253                return NULL;
 254
 255        /* zero out newly allocated memory */
 256        memset(secs + linker->sec_cnt, 0, (new_cnt - linker->sec_cnt) * sizeof(*secs));
 257
 258        linker->secs = secs;
 259        linker->sec_cnt = new_cnt;
 260
 261        sec = &linker->secs[new_cnt - 1];
 262        sec->id = new_cnt - 1;
 263        sec->sec_name = strdup(sec_name);
 264        if (!sec->sec_name)
 265                return NULL;
 266
 267        return sec;
 268}
 269
 270static Elf64_Sym *add_new_sym(struct bpf_linker *linker, size_t *sym_idx)
 271{
 272        struct dst_sec *symtab = &linker->secs[linker->symtab_sec_idx];
 273        Elf64_Sym *syms, *sym;
 274        size_t sym_cnt = symtab->sec_sz / sizeof(*sym);
 275
 276        syms = libbpf_reallocarray(symtab->raw_data, sym_cnt + 1, sizeof(*sym));
 277        if (!syms)
 278                return NULL;
 279
 280        sym = &syms[sym_cnt];
 281        memset(sym, 0, sizeof(*sym));
 282
 283        symtab->raw_data = syms;
 284        symtab->sec_sz += sizeof(*sym);
 285        symtab->shdr->sh_size += sizeof(*sym);
 286        symtab->data->d_size += sizeof(*sym);
 287
 288        if (sym_idx)
 289                *sym_idx = sym_cnt;
 290
 291        return sym;
 292}
 293
 294static int init_output_elf(struct bpf_linker *linker, const char *file)
 295{
 296        int err, str_off;
 297        Elf64_Sym *init_sym;
 298        struct dst_sec *sec;
 299
 300        linker->filename = strdup(file);
 301        if (!linker->filename)
 302                return -ENOMEM;
 303
 304        linker->fd = open(file, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
 305        if (linker->fd < 0) {
 306                err = -errno;
 307                pr_warn("failed to create '%s': %d\n", file, err);
 308                return err;
 309        }
 310
 311        linker->elf = elf_begin(linker->fd, ELF_C_WRITE, NULL);
 312        if (!linker->elf) {
 313                pr_warn_elf("failed to create ELF object");
 314                return -EINVAL;
 315        }
 316
 317        /* ELF header */
 318        linker->elf_hdr = elf64_newehdr(linker->elf);
 319        if (!linker->elf_hdr) {
 320                pr_warn_elf("failed to create ELF header");
 321                return -EINVAL;
 322        }
 323
 324        linker->elf_hdr->e_machine = EM_BPF;
 325        linker->elf_hdr->e_type = ET_REL;
 326#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
 327        linker->elf_hdr->e_ident[EI_DATA] = ELFDATA2LSB;
 328#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
 329        linker->elf_hdr->e_ident[EI_DATA] = ELFDATA2MSB;
 330#else
 331#error "Unknown __BYTE_ORDER__"
 332#endif
 333
 334        /* STRTAB */
 335        /* initialize strset with an empty string to conform to ELF */
 336        linker->strtab_strs = strset__new(INT_MAX, "", sizeof(""));
 337        if (libbpf_get_error(linker->strtab_strs))
 338                return libbpf_get_error(linker->strtab_strs);
 339
 340        sec = add_dst_sec(linker, ".strtab");
 341        if (!sec)
 342                return -ENOMEM;
 343
 344        sec->scn = elf_newscn(linker->elf);
 345        if (!sec->scn) {
 346                pr_warn_elf("failed to create STRTAB section");
 347                return -EINVAL;
 348        }
 349
 350        sec->shdr = elf64_getshdr(sec->scn);
 351        if (!sec->shdr)
 352                return -EINVAL;
 353
 354        sec->data = elf_newdata(sec->scn);
 355        if (!sec->data) {
 356                pr_warn_elf("failed to create STRTAB data");
 357                return -EINVAL;
 358        }
 359
 360        str_off = strset__add_str(linker->strtab_strs, sec->sec_name);
 361        if (str_off < 0)
 362                return str_off;
 363
 364        sec->sec_idx = elf_ndxscn(sec->scn);
 365        linker->elf_hdr->e_shstrndx = sec->sec_idx;
 366        linker->strtab_sec_idx = sec->sec_idx;
 367
 368        sec->shdr->sh_name = str_off;
 369        sec->shdr->sh_type = SHT_STRTAB;
 370        sec->shdr->sh_flags = SHF_STRINGS;
 371        sec->shdr->sh_offset = 0;
 372        sec->shdr->sh_link = 0;
 373        sec->shdr->sh_info = 0;
 374        sec->shdr->sh_addralign = 1;
 375        sec->shdr->sh_size = sec->sec_sz = 0;
 376        sec->shdr->sh_entsize = 0;
 377
 378        /* SYMTAB */
 379        sec = add_dst_sec(linker, ".symtab");
 380        if (!sec)
 381                return -ENOMEM;
 382
 383        sec->scn = elf_newscn(linker->elf);
 384        if (!sec->scn) {
 385                pr_warn_elf("failed to create SYMTAB section");
 386                return -EINVAL;
 387        }
 388
 389        sec->shdr = elf64_getshdr(sec->scn);
 390        if (!sec->shdr)
 391                return -EINVAL;
 392
 393        sec->data = elf_newdata(sec->scn);
 394        if (!sec->data) {
 395                pr_warn_elf("failed to create SYMTAB data");
 396                return -EINVAL;
 397        }
 398
 399        str_off = strset__add_str(linker->strtab_strs, sec->sec_name);
 400        if (str_off < 0)
 401                return str_off;
 402
 403        sec->sec_idx = elf_ndxscn(sec->scn);
 404        linker->symtab_sec_idx = sec->sec_idx;
 405
 406        sec->shdr->sh_name = str_off;
 407        sec->shdr->sh_type = SHT_SYMTAB;
 408        sec->shdr->sh_flags = 0;
 409        sec->shdr->sh_offset = 0;
 410        sec->shdr->sh_link = linker->strtab_sec_idx;
 411        /* sh_info should be one greater than the index of the last local
 412         * symbol (i.e., binding is STB_LOCAL). But why and who cares?
 413         */
 414        sec->shdr->sh_info = 0;
 415        sec->shdr->sh_addralign = 8;
 416        sec->shdr->sh_entsize = sizeof(Elf64_Sym);
 417
 418        /* .BTF */
 419        linker->btf = btf__new_empty();
 420        err = libbpf_get_error(linker->btf);
 421        if (err)
 422                return err;
 423
 424        /* add the special all-zero symbol */
 425        init_sym = add_new_sym(linker, NULL);
 426        if (!init_sym)
 427                return -EINVAL;
 428
 429        init_sym->st_name = 0;
 430        init_sym->st_info = 0;
 431        init_sym->st_other = 0;
 432        init_sym->st_shndx = SHN_UNDEF;
 433        init_sym->st_value = 0;
 434        init_sym->st_size = 0;
 435
 436        return 0;
 437}
 438
 439int bpf_linker__add_file(struct bpf_linker *linker, const char *filename,
 440                         const struct bpf_linker_file_opts *opts)
 441{
 442        struct src_obj obj = {};
 443        int err = 0;
 444
 445        if (!OPTS_VALID(opts, bpf_linker_file_opts))
 446                return libbpf_err(-EINVAL);
 447
 448        if (!linker->elf)
 449                return libbpf_err(-EINVAL);
 450
 451        err = err ?: linker_load_obj_file(linker, filename, opts, &obj);
 452        err = err ?: linker_append_sec_data(linker, &obj);
 453        err = err ?: linker_append_elf_syms(linker, &obj);
 454        err = err ?: linker_append_elf_relos(linker, &obj);
 455        err = err ?: linker_append_btf(linker, &obj);
 456        err = err ?: linker_append_btf_ext(linker, &obj);
 457
 458        /* free up src_obj resources */
 459        free(obj.btf_type_map);
 460        btf__free(obj.btf);
 461        btf_ext__free(obj.btf_ext);
 462        free(obj.secs);
 463        free(obj.sym_map);
 464        if (obj.elf)
 465                elf_end(obj.elf);
 466        if (obj.fd >= 0)
 467                close(obj.fd);
 468
 469        return libbpf_err(err);
 470}
 471
 472static bool is_dwarf_sec_name(const char *name)
 473{
 474        /* approximation, but the actual list is too long */
 475        return strncmp(name, ".debug_", sizeof(".debug_") - 1) == 0;
 476}
 477
 478static bool is_ignored_sec(struct src_sec *sec)
 479{
 480        Elf64_Shdr *shdr = sec->shdr;
 481        const char *name = sec->sec_name;
 482
 483        /* no special handling of .strtab */
 484        if (shdr->sh_type == SHT_STRTAB)
 485                return true;
 486
 487        /* ignore .llvm_addrsig section as well */
 488        if (shdr->sh_type == SHT_LLVM_ADDRSIG)
 489                return true;
 490
 491        /* no subprograms will lead to an empty .text section, ignore it */
 492        if (shdr->sh_type == SHT_PROGBITS && shdr->sh_size == 0 &&
 493            strcmp(sec->sec_name, ".text") == 0)
 494                return true;
 495
 496        /* DWARF sections */
 497        if (is_dwarf_sec_name(sec->sec_name))
 498                return true;
 499
 500        if (strncmp(name, ".rel", sizeof(".rel") - 1) == 0) {
 501                name += sizeof(".rel") - 1;
 502                /* DWARF section relocations */
 503                if (is_dwarf_sec_name(name))
 504                        return true;
 505
 506                /* .BTF and .BTF.ext don't need relocations */
 507                if (strcmp(name, BTF_ELF_SEC) == 0 ||
 508                    strcmp(name, BTF_EXT_ELF_SEC) == 0)
 509                        return true;
 510        }
 511
 512        return false;
 513}
 514
 515static struct src_sec *add_src_sec(struct src_obj *obj, const char *sec_name)
 516{
 517        struct src_sec *secs = obj->secs, *sec;
 518        size_t new_cnt = obj->sec_cnt ? obj->sec_cnt + 1 : 2;
 519
 520        secs = libbpf_reallocarray(secs, new_cnt, sizeof(*secs));
 521        if (!secs)
 522                return NULL;
 523
 524        /* zero out newly allocated memory */
 525        memset(secs + obj->sec_cnt, 0, (new_cnt - obj->sec_cnt) * sizeof(*secs));
 526
 527        obj->secs = secs;
 528        obj->sec_cnt = new_cnt;
 529
 530        sec = &obj->secs[new_cnt - 1];
 531        sec->id = new_cnt - 1;
 532        sec->sec_name = sec_name;
 533
 534        return sec;
 535}
 536
 537static int linker_load_obj_file(struct bpf_linker *linker, const char *filename,
 538                                const struct bpf_linker_file_opts *opts,
 539                                struct src_obj *obj)
 540{
 541#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
 542        const int host_endianness = ELFDATA2LSB;
 543#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
 544        const int host_endianness = ELFDATA2MSB;
 545#else
 546#error "Unknown __BYTE_ORDER__"
 547#endif
 548        int err = 0;
 549        Elf_Scn *scn;
 550        Elf_Data *data;
 551        Elf64_Ehdr *ehdr;
 552        Elf64_Shdr *shdr;
 553        struct src_sec *sec;
 554
 555        pr_debug("linker: adding object file '%s'...\n", filename);
 556
 557        obj->filename = filename;
 558
 559        obj->fd = open(filename, O_RDONLY | O_CLOEXEC);
 560        if (obj->fd < 0) {
 561                err = -errno;
 562                pr_warn("failed to open file '%s': %d\n", filename, err);
 563                return err;
 564        }
 565        obj->elf = elf_begin(obj->fd, ELF_C_READ_MMAP, NULL);
 566        if (!obj->elf) {
 567                err = -errno;
 568                pr_warn_elf("failed to parse ELF file '%s'", filename);
 569                return err;
 570        }
 571
 572        /* Sanity check ELF file high-level properties */
 573        ehdr = elf64_getehdr(obj->elf);
 574        if (!ehdr) {
 575                err = -errno;
 576                pr_warn_elf("failed to get ELF header for %s", filename);
 577                return err;
 578        }
 579        if (ehdr->e_ident[EI_DATA] != host_endianness) {
 580                err = -EOPNOTSUPP;
 581                pr_warn_elf("unsupported byte order of ELF file %s", filename);
 582                return err;
 583        }
 584        if (ehdr->e_type != ET_REL
 585            || ehdr->e_machine != EM_BPF
 586            || ehdr->e_ident[EI_CLASS] != ELFCLASS64) {
 587                err = -EOPNOTSUPP;
 588                pr_warn_elf("unsupported kind of ELF file %s", filename);
 589                return err;
 590        }
 591
 592        if (elf_getshdrstrndx(obj->elf, &obj->shstrs_sec_idx)) {
 593                err = -errno;
 594                pr_warn_elf("failed to get SHSTRTAB section index for %s", filename);
 595                return err;
 596        }
 597
 598        scn = NULL;
 599        while ((scn = elf_nextscn(obj->elf, scn)) != NULL) {
 600                size_t sec_idx = elf_ndxscn(scn);
 601                const char *sec_name;
 602
 603                shdr = elf64_getshdr(scn);
 604                if (!shdr) {
 605                        err = -errno;
 606                        pr_warn_elf("failed to get section #%zu header for %s",
 607                                    sec_idx, filename);
 608                        return err;
 609                }
 610
 611                sec_name = elf_strptr(obj->elf, obj->shstrs_sec_idx, shdr->sh_name);
 612                if (!sec_name) {
 613                        err = -errno;
 614                        pr_warn_elf("failed to get section #%zu name for %s",
 615                                    sec_idx, filename);
 616                        return err;
 617                }
 618
 619                data = elf_getdata(scn, 0);
 620                if (!data) {
 621                        err = -errno;
 622                        pr_warn_elf("failed to get section #%zu (%s) data from %s",
 623                                    sec_idx, sec_name, filename);
 624                        return err;
 625                }
 626
 627                sec = add_src_sec(obj, sec_name);
 628                if (!sec)
 629                        return -ENOMEM;
 630
 631                sec->scn = scn;
 632                sec->shdr = shdr;
 633                sec->data = data;
 634                sec->sec_idx = elf_ndxscn(scn);
 635
 636                if (is_ignored_sec(sec)) {
 637                        sec->skipped = true;
 638                        continue;
 639                }
 640
 641                switch (shdr->sh_type) {
 642                case SHT_SYMTAB:
 643                        if (obj->symtab_sec_idx) {
 644                                err = -EOPNOTSUPP;
 645                                pr_warn("multiple SYMTAB sections found, not supported\n");
 646                                return err;
 647                        }
 648                        obj->symtab_sec_idx = sec_idx;
 649                        break;
 650                case SHT_STRTAB:
 651                        /* we'll construct our own string table */
 652                        break;
 653                case SHT_PROGBITS:
 654                        if (strcmp(sec_name, BTF_ELF_SEC) == 0) {
 655                                obj->btf = btf__new(data->d_buf, shdr->sh_size);
 656                                err = libbpf_get_error(obj->btf);
 657                                if (err) {
 658                                        pr_warn("failed to parse .BTF from %s: %d\n", filename, err);
 659                                        return err;
 660                                }
 661                                sec->skipped = true;
 662                                continue;
 663                        }
 664                        if (strcmp(sec_name, BTF_EXT_ELF_SEC) == 0) {
 665                                obj->btf_ext = btf_ext__new(data->d_buf, shdr->sh_size);
 666                                err = libbpf_get_error(obj->btf_ext);
 667                                if (err) {
 668                                        pr_warn("failed to parse .BTF.ext from '%s': %d\n", filename, err);
 669                                        return err;
 670                                }
 671                                sec->skipped = true;
 672                                continue;
 673                        }
 674
 675                        /* data & code */
 676                        break;
 677                case SHT_NOBITS:
 678                        /* BSS */
 679                        break;
 680                case SHT_REL:
 681                        /* relocations */
 682                        break;
 683                default:
 684                        pr_warn("unrecognized section #%zu (%s) in %s\n",
 685                                sec_idx, sec_name, filename);
 686                        err = -EINVAL;
 687                        return err;
 688                }
 689        }
 690
 691        err = err ?: linker_sanity_check_elf(obj);
 692        err = err ?: linker_sanity_check_btf(obj);
 693        err = err ?: linker_sanity_check_btf_ext(obj);
 694        err = err ?: linker_fixup_btf(obj);
 695
 696        return err;
 697}
 698
 699static bool is_pow_of_2(size_t x)
 700{
 701        return x && (x & (x - 1)) == 0;
 702}
 703
 704static int linker_sanity_check_elf(struct src_obj *obj)
 705{
 706        struct src_sec *sec;
 707        int i, err;
 708
 709        if (!obj->symtab_sec_idx) {
 710                pr_warn("ELF is missing SYMTAB section in %s\n", obj->filename);
 711                return -EINVAL;
 712        }
 713        if (!obj->shstrs_sec_idx) {
 714                pr_warn("ELF is missing section headers STRTAB section in %s\n", obj->filename);
 715                return -EINVAL;
 716        }
 717
 718        for (i = 1; i < obj->sec_cnt; i++) {
 719                sec = &obj->secs[i];
 720
 721                if (sec->sec_name[0] == '\0') {
 722                        pr_warn("ELF section #%zu has empty name in %s\n", sec->sec_idx, obj->filename);
 723                        return -EINVAL;
 724                }
 725
 726                if (sec->shdr->sh_addralign && !is_pow_of_2(sec->shdr->sh_addralign))
 727                        return -EINVAL;
 728                if (sec->shdr->sh_addralign != sec->data->d_align)
 729                        return -EINVAL;
 730
 731                if (sec->shdr->sh_size != sec->data->d_size)
 732                        return -EINVAL;
 733
 734                switch (sec->shdr->sh_type) {
 735                case SHT_SYMTAB:
 736                        err = linker_sanity_check_elf_symtab(obj, sec);
 737                        if (err)
 738                                return err;
 739                        break;
 740                case SHT_STRTAB:
 741                        break;
 742                case SHT_PROGBITS:
 743                        if (sec->shdr->sh_flags & SHF_EXECINSTR) {
 744                                if (sec->shdr->sh_size % sizeof(struct bpf_insn) != 0)
 745                                        return -EINVAL;
 746                        }
 747                        break;
 748                case SHT_NOBITS:
 749                        break;
 750                case SHT_REL:
 751                        err = linker_sanity_check_elf_relos(obj, sec);
 752                        if (err)
 753                                return err;
 754                        break;
 755                case SHT_LLVM_ADDRSIG:
 756                        break;
 757                default:
 758                        pr_warn("ELF section #%zu (%s) has unrecognized type %zu in %s\n",
 759                                sec->sec_idx, sec->sec_name, (size_t)sec->shdr->sh_type, obj->filename);
 760                        return -EINVAL;
 761                }
 762        }
 763
 764        return 0;
 765}
 766
 767static int linker_sanity_check_elf_symtab(struct src_obj *obj, struct src_sec *sec)
 768{
 769        struct src_sec *link_sec;
 770        Elf64_Sym *sym;
 771        int i, n;
 772
 773        if (sec->shdr->sh_entsize != sizeof(Elf64_Sym))
 774                return -EINVAL;
 775        if (sec->shdr->sh_size % sec->shdr->sh_entsize != 0)
 776                return -EINVAL;
 777
 778        if (!sec->shdr->sh_link || sec->shdr->sh_link >= obj->sec_cnt) {
 779                pr_warn("ELF SYMTAB section #%zu points to missing STRTAB section #%zu in %s\n",
 780                        sec->sec_idx, (size_t)sec->shdr->sh_link, obj->filename);
 781                return -EINVAL;
 782        }
 783        link_sec = &obj->secs[sec->shdr->sh_link];
 784        if (link_sec->shdr->sh_type != SHT_STRTAB) {
 785                pr_warn("ELF SYMTAB section #%zu points to invalid STRTAB section #%zu in %s\n",
 786                        sec->sec_idx, (size_t)sec->shdr->sh_link, obj->filename);
 787                return -EINVAL;
 788        }
 789
 790        n = sec->shdr->sh_size / sec->shdr->sh_entsize;
 791        sym = sec->data->d_buf;
 792        for (i = 0; i < n; i++, sym++) {
 793                int sym_type = ELF64_ST_TYPE(sym->st_info);
 794                int sym_bind = ELF64_ST_BIND(sym->st_info);
 795                int sym_vis = ELF64_ST_VISIBILITY(sym->st_other);
 796
 797                if (i == 0) {
 798                        if (sym->st_name != 0 || sym->st_info != 0
 799                            || sym->st_other != 0 || sym->st_shndx != 0
 800                            || sym->st_value != 0 || sym->st_size != 0) {
 801                                pr_warn("ELF sym #0 is invalid in %s\n", obj->filename);
 802                                return -EINVAL;
 803                        }
 804                        continue;
 805                }
 806                if (sym_bind != STB_LOCAL && sym_bind != STB_GLOBAL && sym_bind != STB_WEAK) {
 807                        pr_warn("ELF sym #%d in section #%zu has unsupported symbol binding %d\n",
 808                                i, sec->sec_idx, sym_bind);
 809                        return -EINVAL;
 810                }
 811                if (sym_vis != STV_DEFAULT && sym_vis != STV_HIDDEN) {
 812                        pr_warn("ELF sym #%d in section #%zu has unsupported symbol visibility %d\n",
 813                                i, sec->sec_idx, sym_vis);
 814                        return -EINVAL;
 815                }
 816                if (sym->st_shndx == 0) {
 817                        if (sym_type != STT_NOTYPE || sym_bind == STB_LOCAL
 818                            || sym->st_value != 0 || sym->st_size != 0) {
 819                                pr_warn("ELF sym #%d is invalid extern symbol in %s\n",
 820                                        i, obj->filename);
 821
 822                                return -EINVAL;
 823                        }
 824                        continue;
 825                }
 826                if (sym->st_shndx < SHN_LORESERVE && sym->st_shndx >= obj->sec_cnt) {
 827                        pr_warn("ELF sym #%d in section #%zu points to missing section #%zu in %s\n",
 828                                i, sec->sec_idx, (size_t)sym->st_shndx, obj->filename);
 829                        return -EINVAL;
 830                }
 831                if (sym_type == STT_SECTION) {
 832                        if (sym->st_value != 0)
 833                                return -EINVAL;
 834                        continue;
 835                }
 836        }
 837
 838        return 0;
 839}
 840
 841static int linker_sanity_check_elf_relos(struct src_obj *obj, struct src_sec *sec)
 842{
 843        struct src_sec *link_sec, *sym_sec;
 844        Elf64_Rel *relo;
 845        int i, n;
 846
 847        if (sec->shdr->sh_entsize != sizeof(Elf64_Rel))
 848                return -EINVAL;
 849        if (sec->shdr->sh_size % sec->shdr->sh_entsize != 0)
 850                return -EINVAL;
 851
 852        /* SHT_REL's sh_link should point to SYMTAB */
 853        if (sec->shdr->sh_link != obj->symtab_sec_idx) {
 854                pr_warn("ELF relo section #%zu points to invalid SYMTAB section #%zu in %s\n",
 855                        sec->sec_idx, (size_t)sec->shdr->sh_link, obj->filename);
 856                return -EINVAL;
 857        }
 858
 859        /* SHT_REL's sh_info points to relocated section */
 860        if (!sec->shdr->sh_info || sec->shdr->sh_info >= obj->sec_cnt) {
 861                pr_warn("ELF relo section #%zu points to missing section #%zu in %s\n",
 862                        sec->sec_idx, (size_t)sec->shdr->sh_info, obj->filename);
 863                return -EINVAL;
 864        }
 865        link_sec = &obj->secs[sec->shdr->sh_info];
 866
 867        /* .rel<secname> -> <secname> pattern is followed */
 868        if (strncmp(sec->sec_name, ".rel", sizeof(".rel") - 1) != 0
 869            || strcmp(sec->sec_name + sizeof(".rel") - 1, link_sec->sec_name) != 0) {
 870                pr_warn("ELF relo section #%zu name has invalid name in %s\n",
 871                        sec->sec_idx, obj->filename);
 872                return -EINVAL;
 873        }
 874
 875        /* don't further validate relocations for ignored sections */
 876        if (link_sec->skipped)
 877                return 0;
 878
 879        /* relocatable section is data or instructions */
 880        if (link_sec->shdr->sh_type != SHT_PROGBITS && link_sec->shdr->sh_type != SHT_NOBITS) {
 881                pr_warn("ELF relo section #%zu points to invalid section #%zu in %s\n",
 882                        sec->sec_idx, (size_t)sec->shdr->sh_info, obj->filename);
 883                return -EINVAL;
 884        }
 885
 886        /* check sanity of each relocation */
 887        n = sec->shdr->sh_size / sec->shdr->sh_entsize;
 888        relo = sec->data->d_buf;
 889        sym_sec = &obj->secs[obj->symtab_sec_idx];
 890        for (i = 0; i < n; i++, relo++) {
 891                size_t sym_idx = ELF64_R_SYM(relo->r_info);
 892                size_t sym_type = ELF64_R_TYPE(relo->r_info);
 893
 894                if (sym_type != R_BPF_64_64 && sym_type != R_BPF_64_32 &&
 895                    sym_type != R_BPF_64_ABS64 && sym_type != R_BPF_64_ABS32) {
 896                        pr_warn("ELF relo #%d in section #%zu has unexpected type %zu in %s\n",
 897                                i, sec->sec_idx, sym_type, obj->filename);
 898                        return -EINVAL;
 899                }
 900
 901                if (!sym_idx || sym_idx * sizeof(Elf64_Sym) >= sym_sec->shdr->sh_size) {
 902                        pr_warn("ELF relo #%d in section #%zu points to invalid symbol #%zu in %s\n",
 903                                i, sec->sec_idx, sym_idx, obj->filename);
 904                        return -EINVAL;
 905                }
 906
 907                if (link_sec->shdr->sh_flags & SHF_EXECINSTR) {
 908                        if (relo->r_offset % sizeof(struct bpf_insn) != 0) {
 909                                pr_warn("ELF relo #%d in section #%zu points to missing symbol #%zu in %s\n",
 910                                        i, sec->sec_idx, sym_idx, obj->filename);
 911                                return -EINVAL;
 912                        }
 913                }
 914        }
 915
 916        return 0;
 917}
 918
 919static int check_btf_type_id(__u32 *type_id, void *ctx)
 920{
 921        struct btf *btf = ctx;
 922
 923        if (*type_id >= btf__type_cnt(btf))
 924                return -EINVAL;
 925
 926        return 0;
 927}
 928
 929static int check_btf_str_off(__u32 *str_off, void *ctx)
 930{
 931        struct btf *btf = ctx;
 932        const char *s;
 933
 934        s = btf__str_by_offset(btf, *str_off);
 935
 936        if (!s)
 937                return -EINVAL;
 938
 939        return 0;
 940}
 941
 942static int linker_sanity_check_btf(struct src_obj *obj)
 943{
 944        struct btf_type *t;
 945        int i, n, err = 0;
 946
 947        if (!obj->btf)
 948                return 0;
 949
 950        n = btf__type_cnt(obj->btf);
 951        for (i = 1; i < n; i++) {
 952                t = btf_type_by_id(obj->btf, i);
 953
 954                err = err ?: btf_type_visit_type_ids(t, check_btf_type_id, obj->btf);
 955                err = err ?: btf_type_visit_str_offs(t, check_btf_str_off, obj->btf);
 956                if (err)
 957                        return err;
 958        }
 959
 960        return 0;
 961}
 962
 963static int linker_sanity_check_btf_ext(struct src_obj *obj)
 964{
 965        int err = 0;
 966
 967        if (!obj->btf_ext)
 968                return 0;
 969
 970        /* can't use .BTF.ext without .BTF */
 971        if (!obj->btf)
 972                return -EINVAL;
 973
 974        err = err ?: btf_ext_visit_type_ids(obj->btf_ext, check_btf_type_id, obj->btf);
 975        err = err ?: btf_ext_visit_str_offs(obj->btf_ext, check_btf_str_off, obj->btf);
 976        if (err)
 977                return err;
 978
 979        return 0;
 980}
 981
 982static int init_sec(struct bpf_linker *linker, struct dst_sec *dst_sec, struct src_sec *src_sec)
 983{
 984        Elf_Scn *scn;
 985        Elf_Data *data;
 986        Elf64_Shdr *shdr;
 987        int name_off;
 988
 989        dst_sec->sec_sz = 0;
 990        dst_sec->sec_idx = 0;
 991        dst_sec->ephemeral = src_sec->ephemeral;
 992
 993        /* ephemeral sections are just thin section shells lacking most parts */
 994        if (src_sec->ephemeral)
 995                return 0;
 996
 997        scn = elf_newscn(linker->elf);
 998        if (!scn)
 999                return -ENOMEM;
1000        data = elf_newdata(scn);
1001        if (!data)
1002                return -ENOMEM;
1003        shdr = elf64_getshdr(scn);
1004        if (!shdr)
1005                return -ENOMEM;
1006
1007        dst_sec->scn = scn;
1008        dst_sec->shdr = shdr;
1009        dst_sec->data = data;
1010        dst_sec->sec_idx = elf_ndxscn(scn);
1011
1012        name_off = strset__add_str(linker->strtab_strs, src_sec->sec_name);
1013        if (name_off < 0)
1014                return name_off;
1015
1016        shdr->sh_name = name_off;
1017        shdr->sh_type = src_sec->shdr->sh_type;
1018        shdr->sh_flags = src_sec->shdr->sh_flags;
1019        shdr->sh_size = 0;
1020        /* sh_link and sh_info have different meaning for different types of
1021         * sections, so we leave it up to the caller code to fill them in, if
1022         * necessary
1023         */
1024        shdr->sh_link = 0;
1025        shdr->sh_info = 0;
1026        shdr->sh_addralign = src_sec->shdr->sh_addralign;
1027        shdr->sh_entsize = src_sec->shdr->sh_entsize;
1028
1029        data->d_type = src_sec->data->d_type;
1030        data->d_size = 0;
1031        data->d_buf = NULL;
1032        data->d_align = src_sec->data->d_align;
1033        data->d_off = 0;
1034
1035        return 0;
1036}
1037
1038static struct dst_sec *find_dst_sec_by_name(struct bpf_linker *linker, const char *sec_name)
1039{
1040        struct dst_sec *sec;
1041        int i;
1042
1043        for (i = 1; i < linker->sec_cnt; i++) {
1044                sec = &linker->secs[i];
1045
1046                if (strcmp(sec->sec_name, sec_name) == 0)
1047                        return sec;
1048        }
1049
1050        return NULL;
1051}
1052
1053static bool secs_match(struct dst_sec *dst, struct src_sec *src)
1054{
1055        if (dst->ephemeral || src->ephemeral)
1056                return true;
1057
1058        if (dst->shdr->sh_type != src->shdr->sh_type) {
1059                pr_warn("sec %s types mismatch\n", dst->sec_name);
1060                return false;
1061        }
1062        if (dst->shdr->sh_flags != src->shdr->sh_flags) {
1063                pr_warn("sec %s flags mismatch\n", dst->sec_name);
1064                return false;
1065        }
1066        if (dst->shdr->sh_entsize != src->shdr->sh_entsize) {
1067                pr_warn("sec %s entsize mismatch\n", dst->sec_name);
1068                return false;
1069        }
1070
1071        return true;
1072}
1073
1074static bool sec_content_is_same(struct dst_sec *dst_sec, struct src_sec *src_sec)
1075{
1076        if (dst_sec->sec_sz != src_sec->shdr->sh_size)
1077                return false;
1078        if (memcmp(dst_sec->raw_data, src_sec->data->d_buf, dst_sec->sec_sz) != 0)
1079                return false;
1080        return true;
1081}
1082
1083static int extend_sec(struct bpf_linker *linker, struct dst_sec *dst, struct src_sec *src)
1084{
1085        void *tmp;
1086        size_t dst_align, src_align;
1087        size_t dst_align_sz, dst_final_sz;
1088        int err;
1089
1090        /* Ephemeral source section doesn't contribute anything to ELF
1091         * section data.
1092         */
1093        if (src->ephemeral)
1094                return 0;
1095
1096        /* Some sections (like .maps) can contain both externs (and thus be
1097         * ephemeral) and non-externs (map definitions). So it's possible that
1098         * it has to be "upgraded" from ephemeral to non-ephemeral when the
1099         * first non-ephemeral entity appears. In such case, we add ELF
1100         * section, data, etc.
1101         */
1102        if (dst->ephemeral) {
1103                err = init_sec(linker, dst, src);
1104                if (err)
1105                        return err;
1106        }
1107
1108        dst_align = dst->shdr->sh_addralign;
1109        src_align = src->shdr->sh_addralign;
1110        if (dst_align == 0)
1111                dst_align = 1;
1112        if (dst_align < src_align)
1113                dst_align = src_align;
1114
1115        dst_align_sz = (dst->sec_sz + dst_align - 1) / dst_align * dst_align;
1116
1117        /* no need to re-align final size */
1118        dst_final_sz = dst_align_sz + src->shdr->sh_size;
1119
1120        if (src->shdr->sh_type != SHT_NOBITS) {
1121                tmp = realloc(dst->raw_data, dst_final_sz);
1122                if (!tmp)
1123                        return -ENOMEM;
1124                dst->raw_data = tmp;
1125
1126                /* pad dst section, if it's alignment forced size increase */
1127                memset(dst->raw_data + dst->sec_sz, 0, dst_align_sz - dst->sec_sz);
1128                /* now copy src data at a properly aligned offset */
1129                memcpy(dst->raw_data + dst_align_sz, src->data->d_buf, src->shdr->sh_size);
1130        }
1131
1132        dst->sec_sz = dst_final_sz;
1133        dst->shdr->sh_size = dst_final_sz;
1134        dst->data->d_size = dst_final_sz;
1135
1136        dst->shdr->sh_addralign = dst_align;
1137        dst->data->d_align = dst_align;
1138
1139        src->dst_off = dst_align_sz;
1140
1141        return 0;
1142}
1143
1144static bool is_data_sec(struct src_sec *sec)
1145{
1146        if (!sec || sec->skipped)
1147                return false;
1148        /* ephemeral sections are data sections, e.g., .kconfig, .ksyms */
1149        if (sec->ephemeral)
1150                return true;
1151        return sec->shdr->sh_type == SHT_PROGBITS || sec->shdr->sh_type == SHT_NOBITS;
1152}
1153
1154static bool is_relo_sec(struct src_sec *sec)
1155{
1156        if (!sec || sec->skipped || sec->ephemeral)
1157                return false;
1158        return sec->shdr->sh_type == SHT_REL;
1159}
1160
1161static int linker_append_sec_data(struct bpf_linker *linker, struct src_obj *obj)
1162{
1163        int i, err;
1164
1165        for (i = 1; i < obj->sec_cnt; i++) {
1166                struct src_sec *src_sec;
1167                struct dst_sec *dst_sec;
1168
1169                src_sec = &obj->secs[i];
1170                if (!is_data_sec(src_sec))
1171                        continue;
1172
1173                dst_sec = find_dst_sec_by_name(linker, src_sec->sec_name);
1174                if (!dst_sec) {
1175                        dst_sec = add_dst_sec(linker, src_sec->sec_name);
1176                        if (!dst_sec)
1177                                return -ENOMEM;
1178                        err = init_sec(linker, dst_sec, src_sec);
1179                        if (err) {
1180                                pr_warn("failed to init section '%s'\n", src_sec->sec_name);
1181                                return err;
1182                        }
1183                } else {
1184                        if (!secs_match(dst_sec, src_sec)) {
1185                                pr_warn("ELF sections %s are incompatible\n", src_sec->sec_name);
1186                                return -1;
1187                        }
1188
1189                        /* "license" and "version" sections are deduped */
1190                        if (strcmp(src_sec->sec_name, "license") == 0
1191                            || strcmp(src_sec->sec_name, "version") == 0) {
1192                                if (!sec_content_is_same(dst_sec, src_sec)) {
1193                                        pr_warn("non-identical contents of section '%s' are not supported\n", src_sec->sec_name);
1194                                        return -EINVAL;
1195                                }
1196                                src_sec->skipped = true;
1197                                src_sec->dst_id = dst_sec->id;
1198                                continue;
1199                        }
1200                }
1201
1202                /* record mapped section index */
1203                src_sec->dst_id = dst_sec->id;
1204
1205                err = extend_sec(linker, dst_sec, src_sec);
1206                if (err)
1207                        return err;
1208        }
1209
1210        return 0;
1211}
1212
1213static int linker_append_elf_syms(struct bpf_linker *linker, struct src_obj *obj)
1214{
1215        struct src_sec *symtab = &obj->secs[obj->symtab_sec_idx];
1216        Elf64_Sym *sym = symtab->data->d_buf;
1217        int i, n = symtab->shdr->sh_size / symtab->shdr->sh_entsize, err;
1218        int str_sec_idx = symtab->shdr->sh_link;
1219        const char *sym_name;
1220
1221        obj->sym_map = calloc(n + 1, sizeof(*obj->sym_map));
1222        if (!obj->sym_map)
1223                return -ENOMEM;
1224
1225        for (i = 0; i < n; i++, sym++) {
1226                /* We already validated all-zero symbol #0 and we already
1227                 * appended it preventively to the final SYMTAB, so skip it.
1228                 */
1229                if (i == 0)
1230                        continue;
1231
1232                sym_name = elf_strptr(obj->elf, str_sec_idx, sym->st_name);
1233                if (!sym_name) {
1234                        pr_warn("can't fetch symbol name for symbol #%d in '%s'\n", i, obj->filename);
1235                        return -EINVAL;
1236                }
1237
1238                err = linker_append_elf_sym(linker, obj, sym, sym_name, i);
1239                if (err)
1240                        return err;
1241        }
1242
1243        return 0;
1244}
1245
1246static Elf64_Sym *get_sym_by_idx(struct bpf_linker *linker, size_t sym_idx)
1247{
1248        struct dst_sec *symtab = &linker->secs[linker->symtab_sec_idx];
1249        Elf64_Sym *syms = symtab->raw_data;
1250
1251        return &syms[sym_idx];
1252}
1253
1254static struct glob_sym *find_glob_sym(struct bpf_linker *linker, const char *sym_name)
1255{
1256        struct glob_sym *glob_sym;
1257        const char *name;
1258        int i;
1259
1260        for (i = 0; i < linker->glob_sym_cnt; i++) {
1261                glob_sym = &linker->glob_syms[i];
1262                name = strset__data(linker->strtab_strs) + glob_sym->name_off;
1263
1264                if (strcmp(name, sym_name) == 0)
1265                        return glob_sym;
1266        }
1267
1268        return NULL;
1269}
1270
1271static struct glob_sym *add_glob_sym(struct bpf_linker *linker)
1272{
1273        struct glob_sym *syms, *sym;
1274
1275        syms = libbpf_reallocarray(linker->glob_syms, linker->glob_sym_cnt + 1,
1276                                   sizeof(*linker->glob_syms));
1277        if (!syms)
1278                return NULL;
1279
1280        sym = &syms[linker->glob_sym_cnt];
1281        memset(sym, 0, sizeof(*sym));
1282        sym->var_idx = -1;
1283
1284        linker->glob_syms = syms;
1285        linker->glob_sym_cnt++;
1286
1287        return sym;
1288}
1289
1290static bool glob_sym_btf_matches(const char *sym_name, bool exact,
1291                                 const struct btf *btf1, __u32 id1,
1292                                 const struct btf *btf2, __u32 id2)
1293{
1294        const struct btf_type *t1, *t2;
1295        bool is_static1, is_static2;
1296        const char *n1, *n2;
1297        int i, n;
1298
1299recur:
1300        n1 = n2 = NULL;
1301        t1 = skip_mods_and_typedefs(btf1, id1, &id1);
1302        t2 = skip_mods_and_typedefs(btf2, id2, &id2);
1303
1304        /* check if only one side is FWD, otherwise handle with common logic */
1305        if (!exact && btf_is_fwd(t1) != btf_is_fwd(t2)) {
1306                n1 = btf__str_by_offset(btf1, t1->name_off);
1307                n2 = btf__str_by_offset(btf2, t2->name_off);
1308                if (strcmp(n1, n2) != 0) {
1309                        pr_warn("global '%s': incompatible forward declaration names '%s' and '%s'\n",
1310                                sym_name, n1, n2);
1311                        return false;
1312                }
1313                /* validate if FWD kind matches concrete kind */
1314                if (btf_is_fwd(t1)) {
1315                        if (btf_kflag(t1) && btf_is_union(t2))
1316                                return true;
1317                        if (!btf_kflag(t1) && btf_is_struct(t2))
1318                                return true;
1319                        pr_warn("global '%s': incompatible %s forward declaration and concrete kind %s\n",
1320                                sym_name, btf_kflag(t1) ? "union" : "struct", btf_kind_str(t2));
1321                } else {
1322                        if (btf_kflag(t2) && btf_is_union(t1))
1323                                return true;
1324                        if (!btf_kflag(t2) && btf_is_struct(t1))
1325                                return true;
1326                        pr_warn("global '%s': incompatible %s forward declaration and concrete kind %s\n",
1327                                sym_name, btf_kflag(t2) ? "union" : "struct", btf_kind_str(t1));
1328                }
1329                return false;
1330        }
1331
1332        if (btf_kind(t1) != btf_kind(t2)) {
1333                pr_warn("global '%s': incompatible BTF kinds %s and %s\n",
1334                        sym_name, btf_kind_str(t1), btf_kind_str(t2));
1335                return false;
1336        }
1337
1338        switch (btf_kind(t1)) {
1339        case BTF_KIND_STRUCT:
1340        case BTF_KIND_UNION:
1341        case BTF_KIND_ENUM:
1342        case BTF_KIND_FWD:
1343        case BTF_KIND_FUNC:
1344        case BTF_KIND_VAR:
1345                n1 = btf__str_by_offset(btf1, t1->name_off);
1346                n2 = btf__str_by_offset(btf2, t2->name_off);
1347                if (strcmp(n1, n2) != 0) {
1348                        pr_warn("global '%s': incompatible %s names '%s' and '%s'\n",
1349                                sym_name, btf_kind_str(t1), n1, n2);
1350                        return false;
1351                }
1352                break;
1353        default:
1354                break;
1355        }
1356
1357        switch (btf_kind(t1)) {
1358        case BTF_KIND_UNKN: /* void */
1359        case BTF_KIND_FWD:
1360                return true;
1361        case BTF_KIND_INT:
1362        case BTF_KIND_FLOAT:
1363        case BTF_KIND_ENUM:
1364                /* ignore encoding for int and enum values for enum */
1365                if (t1->size != t2->size) {
1366                        pr_warn("global '%s': incompatible %s '%s' size %u and %u\n",
1367                                sym_name, btf_kind_str(t1), n1, t1->size, t2->size);
1368                        return false;
1369                }
1370                return true;
1371        case BTF_KIND_PTR:
1372                /* just validate overall shape of the referenced type, so no
1373                 * contents comparison for struct/union, and allowd fwd vs
1374                 * struct/union
1375                 */
1376                exact = false;
1377                id1 = t1->type;
1378                id2 = t2->type;
1379                goto recur;
1380        case BTF_KIND_ARRAY:
1381                /* ignore index type and array size */
1382                id1 = btf_array(t1)->type;
1383                id2 = btf_array(t2)->type;
1384                goto recur;
1385        case BTF_KIND_FUNC:
1386                /* extern and global linkages are compatible */
1387                is_static1 = btf_func_linkage(t1) == BTF_FUNC_STATIC;
1388                is_static2 = btf_func_linkage(t2) == BTF_FUNC_STATIC;
1389                if (is_static1 != is_static2) {
1390                        pr_warn("global '%s': incompatible func '%s' linkage\n", sym_name, n1);
1391                        return false;
1392                }
1393
1394                id1 = t1->type;
1395                id2 = t2->type;
1396                goto recur;
1397        case BTF_KIND_VAR:
1398                /* extern and global linkages are compatible */
1399                is_static1 = btf_var(t1)->linkage == BTF_VAR_STATIC;
1400                is_static2 = btf_var(t2)->linkage == BTF_VAR_STATIC;
1401                if (is_static1 != is_static2) {
1402                        pr_warn("global '%s': incompatible var '%s' linkage\n", sym_name, n1);
1403                        return false;
1404                }
1405
1406                id1 = t1->type;
1407                id2 = t2->type;
1408                goto recur;
1409        case BTF_KIND_STRUCT:
1410        case BTF_KIND_UNION: {
1411                const struct btf_member *m1, *m2;
1412
1413                if (!exact)
1414                        return true;
1415
1416                if (btf_vlen(t1) != btf_vlen(t2)) {
1417                        pr_warn("global '%s': incompatible number of %s fields %u and %u\n",
1418                                sym_name, btf_kind_str(t1), btf_vlen(t1), btf_vlen(t2));
1419                        return false;
1420                }
1421
1422                n = btf_vlen(t1);
1423                m1 = btf_members(t1);
1424                m2 = btf_members(t2);
1425                for (i = 0; i < n; i++, m1++, m2++) {
1426                        n1 = btf__str_by_offset(btf1, m1->name_off);
1427                        n2 = btf__str_by_offset(btf2, m2->name_off);
1428                        if (strcmp(n1, n2) != 0) {
1429                                pr_warn("global '%s': incompatible field #%d names '%s' and '%s'\n",
1430                                        sym_name, i, n1, n2);
1431                                return false;
1432                        }
1433                        if (m1->offset != m2->offset) {
1434                                pr_warn("global '%s': incompatible field #%d ('%s') offsets\n",
1435                                        sym_name, i, n1);
1436                                return false;
1437                        }
1438                        if (!glob_sym_btf_matches(sym_name, exact, btf1, m1->type, btf2, m2->type))
1439                                return false;
1440                }
1441
1442                return true;
1443        }
1444        case BTF_KIND_FUNC_PROTO: {
1445                const struct btf_param *m1, *m2;
1446
1447                if (btf_vlen(t1) != btf_vlen(t2)) {
1448                        pr_warn("global '%s': incompatible number of %s params %u and %u\n",
1449                                sym_name, btf_kind_str(t1), btf_vlen(t1), btf_vlen(t2));
1450                        return false;
1451                }
1452
1453                n = btf_vlen(t1);
1454                m1 = btf_params(t1);
1455                m2 = btf_params(t2);
1456                for (i = 0; i < n; i++, m1++, m2++) {
1457                        /* ignore func arg names */
1458                        if (!glob_sym_btf_matches(sym_name, exact, btf1, m1->type, btf2, m2->type))
1459                                return false;
1460                }
1461
1462                /* now check return type as well */
1463                id1 = t1->type;
1464                id2 = t2->type;
1465                goto recur;
1466        }
1467
1468        /* skip_mods_and_typedefs() make this impossible */
1469        case BTF_KIND_TYPEDEF:
1470        case BTF_KIND_VOLATILE:
1471        case BTF_KIND_CONST:
1472        case BTF_KIND_RESTRICT:
1473        /* DATASECs are never compared with each other */
1474        case BTF_KIND_DATASEC:
1475        default:
1476                pr_warn("global '%s': unsupported BTF kind %s\n",
1477                        sym_name, btf_kind_str(t1));
1478                return false;
1479        }
1480}
1481
1482static bool map_defs_match(const char *sym_name,
1483                           const struct btf *main_btf,
1484                           const struct btf_map_def *main_def,
1485                           const struct btf_map_def *main_inner_def,
1486                           const struct btf *extra_btf,
1487                           const struct btf_map_def *extra_def,
1488                           const struct btf_map_def *extra_inner_def)
1489{
1490        const char *reason;
1491
1492        if (main_def->map_type != extra_def->map_type) {
1493                reason = "type";
1494                goto mismatch;
1495        }
1496
1497        /* check key type/size match */
1498        if (main_def->key_size != extra_def->key_size) {
1499                reason = "key_size";
1500                goto mismatch;
1501        }
1502        if (!!main_def->key_type_id != !!extra_def->key_type_id) {
1503                reason = "key type";
1504                goto mismatch;
1505        }
1506        if ((main_def->parts & MAP_DEF_KEY_TYPE)
1507             && !glob_sym_btf_matches(sym_name, true /*exact*/,
1508                                      main_btf, main_def->key_type_id,
1509                                      extra_btf, extra_def->key_type_id)) {
1510                reason = "key type";
1511                goto mismatch;
1512        }
1513
1514        /* validate value type/size match */
1515        if (main_def->value_size != extra_def->value_size) {
1516                reason = "value_size";
1517                goto mismatch;
1518        }
1519        if (!!main_def->value_type_id != !!extra_def->value_type_id) {
1520                reason = "value type";
1521                goto mismatch;
1522        }
1523        if ((main_def->parts & MAP_DEF_VALUE_TYPE)
1524             && !glob_sym_btf_matches(sym_name, true /*exact*/,
1525                                      main_btf, main_def->value_type_id,
1526                                      extra_btf, extra_def->value_type_id)) {
1527                reason = "key type";
1528                goto mismatch;
1529        }
1530
1531        if (main_def->max_entries != extra_def->max_entries) {
1532                reason = "max_entries";
1533                goto mismatch;
1534        }
1535        if (main_def->map_flags != extra_def->map_flags) {
1536                reason = "map_flags";
1537                goto mismatch;
1538        }
1539        if (main_def->numa_node != extra_def->numa_node) {
1540                reason = "numa_node";
1541                goto mismatch;
1542        }
1543        if (main_def->pinning != extra_def->pinning) {
1544                reason = "pinning";
1545                goto mismatch;
1546        }
1547
1548        if ((main_def->parts & MAP_DEF_INNER_MAP) != (extra_def->parts & MAP_DEF_INNER_MAP)) {
1549                reason = "inner map";
1550                goto mismatch;
1551        }
1552
1553        if (main_def->parts & MAP_DEF_INNER_MAP) {
1554                char inner_map_name[128];
1555
1556                snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", sym_name);
1557
1558                return map_defs_match(inner_map_name,
1559                                      main_btf, main_inner_def, NULL,
1560                                      extra_btf, extra_inner_def, NULL);
1561        }
1562
1563        return true;
1564
1565mismatch:
1566        pr_warn("global '%s': map %s mismatch\n", sym_name, reason);
1567        return false;
1568}
1569
1570static bool glob_map_defs_match(const char *sym_name,
1571                                struct bpf_linker *linker, struct glob_sym *glob_sym,
1572                                struct src_obj *obj, Elf64_Sym *sym, int btf_id)
1573{
1574        struct btf_map_def dst_def = {}, dst_inner_def = {};
1575        struct btf_map_def src_def = {}, src_inner_def = {};
1576        const struct btf_type *t;
1577        int err;
1578
1579        t = btf__type_by_id(obj->btf, btf_id);
1580        if (!btf_is_var(t)) {
1581                pr_warn("global '%s': invalid map definition type [%d]\n", sym_name, btf_id);
1582                return false;
1583        }
1584        t = skip_mods_and_typedefs(obj->btf, t->type, NULL);
1585
1586        err = parse_btf_map_def(sym_name, obj->btf, t, true /*strict*/, &src_def, &src_inner_def);
1587        if (err) {
1588                pr_warn("global '%s': invalid map definition\n", sym_name);
1589                return false;
1590        }
1591
1592        /* re-parse existing map definition */
1593        t = btf__type_by_id(linker->btf, glob_sym->btf_id);
1594        t = skip_mods_and_typedefs(linker->btf, t->type, NULL);
1595        err = parse_btf_map_def(sym_name, linker->btf, t, true /*strict*/, &dst_def, &dst_inner_def);
1596        if (err) {
1597                /* this should not happen, because we already validated it */
1598                pr_warn("global '%s': invalid dst map definition\n", sym_name);
1599                return false;
1600        }
1601
1602        /* Currently extern map definition has to be complete and match
1603         * concrete map definition exactly. This restriction might be lifted
1604         * in the future.
1605         */
1606        return map_defs_match(sym_name, linker->btf, &dst_def, &dst_inner_def,
1607                              obj->btf, &src_def, &src_inner_def);
1608}
1609
1610static bool glob_syms_match(const char *sym_name,
1611                            struct bpf_linker *linker, struct glob_sym *glob_sym,
1612                            struct src_obj *obj, Elf64_Sym *sym, size_t sym_idx, int btf_id)
1613{
1614        const struct btf_type *src_t;
1615
1616        /* if we are dealing with externs, BTF types describing both global
1617         * and extern VARs/FUNCs should be completely present in all files
1618         */
1619        if (!glob_sym->btf_id || !btf_id) {
1620                pr_warn("BTF info is missing for global symbol '%s'\n", sym_name);
1621                return false;
1622        }
1623
1624        src_t = btf__type_by_id(obj->btf, btf_id);
1625        if (!btf_is_var(src_t) && !btf_is_func(src_t)) {
1626                pr_warn("only extern variables and functions are supported, but got '%s' for '%s'\n",
1627                        btf_kind_str(src_t), sym_name);
1628                return false;
1629        }
1630
1631        /* deal with .maps definitions specially */
1632        if (glob_sym->sec_id && strcmp(linker->secs[glob_sym->sec_id].sec_name, MAPS_ELF_SEC) == 0)
1633                return glob_map_defs_match(sym_name, linker, glob_sym, obj, sym, btf_id);
1634
1635        if (!glob_sym_btf_matches(sym_name, true /*exact*/,
1636                                  linker->btf, glob_sym->btf_id, obj->btf, btf_id))
1637                return false;
1638
1639        return true;
1640}
1641
1642static bool btf_is_non_static(const struct btf_type *t)
1643{
1644        return (btf_is_var(t) && btf_var(t)->linkage != BTF_VAR_STATIC)
1645               || (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_STATIC);
1646}
1647
1648static int find_glob_sym_btf(struct src_obj *obj, Elf64_Sym *sym, const char *sym_name,
1649                             int *out_btf_sec_id, int *out_btf_id)
1650{
1651        int i, j, n, m, btf_id = 0;
1652        const struct btf_type *t;
1653        const struct btf_var_secinfo *vi;
1654        const char *name;
1655
1656        if (!obj->btf) {
1657                pr_warn("failed to find BTF info for object '%s'\n", obj->filename);
1658                return -EINVAL;
1659        }
1660
1661        n = btf__type_cnt(obj->btf);
1662        for (i = 1; i < n; i++) {
1663                t = btf__type_by_id(obj->btf, i);
1664
1665                /* some global and extern FUNCs and VARs might not be associated with any
1666                 * DATASEC, so try to detect them in the same pass
1667                 */
1668                if (btf_is_non_static(t)) {
1669                        name = btf__str_by_offset(obj->btf, t->name_off);
1670                        if (strcmp(name, sym_name) != 0)
1671                                continue;
1672
1673                        /* remember and still try to find DATASEC */
1674                        btf_id = i;
1675                        continue;
1676                }
1677
1678                if (!btf_is_datasec(t))
1679                        continue;
1680
1681                vi = btf_var_secinfos(t);
1682                for (j = 0, m = btf_vlen(t); j < m; j++, vi++) {
1683                        t = btf__type_by_id(obj->btf, vi->type);
1684                        name = btf__str_by_offset(obj->btf, t->name_off);
1685
1686                        if (strcmp(name, sym_name) != 0)
1687                                continue;
1688                        if (btf_is_var(t) && btf_var(t)->linkage == BTF_VAR_STATIC)
1689                                continue;
1690                        if (btf_is_func(t) && btf_func_linkage(t) == BTF_FUNC_STATIC)
1691                                continue;
1692
1693                        if (btf_id && btf_id != vi->type) {
1694                                pr_warn("global/extern '%s' BTF is ambiguous: both types #%d and #%u match\n",
1695                                        sym_name, btf_id, vi->type);
1696                                return -EINVAL;
1697                        }
1698
1699                        *out_btf_sec_id = i;
1700                        *out_btf_id = vi->type;
1701
1702                        return 0;
1703                }
1704        }
1705
1706        /* free-floating extern or global FUNC */
1707        if (btf_id) {
1708                *out_btf_sec_id = 0;
1709                *out_btf_id = btf_id;
1710                return 0;
1711        }
1712
1713        pr_warn("failed to find BTF info for global/extern symbol '%s'\n", sym_name);
1714        return -ENOENT;
1715}
1716
1717static struct src_sec *find_src_sec_by_name(struct src_obj *obj, const char *sec_name)
1718{
1719        struct src_sec *sec;
1720        int i;
1721
1722        for (i = 1; i < obj->sec_cnt; i++) {
1723                sec = &obj->secs[i];
1724
1725                if (strcmp(sec->sec_name, sec_name) == 0)
1726                        return sec;
1727        }
1728
1729        return NULL;
1730}
1731
1732static int complete_extern_btf_info(struct btf *dst_btf, int dst_id,
1733                                    struct btf *src_btf, int src_id)
1734{
1735        struct btf_type *dst_t = btf_type_by_id(dst_btf, dst_id);
1736        struct btf_type *src_t = btf_type_by_id(src_btf, src_id);
1737        struct btf_param *src_p, *dst_p;
1738        const char *s;
1739        int i, n, off;
1740
1741        /* We already made sure that source and destination types (FUNC or
1742         * VAR) match in terms of types and argument names.
1743         */
1744        if (btf_is_var(dst_t)) {
1745                btf_var(dst_t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
1746                return 0;
1747        }
1748
1749        dst_t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_GLOBAL, 0);
1750
1751        /* now onto FUNC_PROTO types */
1752        src_t = btf_type_by_id(src_btf, src_t->type);
1753        dst_t = btf_type_by_id(dst_btf, dst_t->type);
1754
1755        /* Fill in all the argument names, which for extern FUNCs are missing.
1756         * We'll end up with two copies of FUNCs/VARs for externs, but that
1757         * will be taken care of by BTF dedup at the very end.
1758         * It might be that BTF types for extern in one file has less/more BTF
1759         * information (e.g., FWD instead of full STRUCT/UNION information),
1760         * but that should be (in most cases, subject to BTF dedup rules)
1761         * handled and resolved by BTF dedup algorithm as well, so we won't
1762         * worry about it. Our only job is to make sure that argument names
1763         * are populated on both sides, otherwise BTF dedup will pedantically
1764         * consider them different.
1765         */
1766        src_p = btf_params(src_t);
1767        dst_p = btf_params(dst_t);
1768        for (i = 0, n = btf_vlen(dst_t); i < n; i++, src_p++, dst_p++) {
1769                if (!src_p->name_off)
1770                        continue;
1771
1772                /* src_btf has more complete info, so add name to dst_btf */
1773                s = btf__str_by_offset(src_btf, src_p->name_off);
1774                off = btf__add_str(dst_btf, s);
1775                if (off < 0)
1776                        return off;
1777                dst_p->name_off = off;
1778        }
1779        return 0;
1780}
1781
1782static void sym_update_bind(Elf64_Sym *sym, int sym_bind)
1783{
1784        sym->st_info = ELF64_ST_INFO(sym_bind, ELF64_ST_TYPE(sym->st_info));
1785}
1786
1787static void sym_update_type(Elf64_Sym *sym, int sym_type)
1788{
1789        sym->st_info = ELF64_ST_INFO(ELF64_ST_BIND(sym->st_info), sym_type);
1790}
1791
1792static void sym_update_visibility(Elf64_Sym *sym, int sym_vis)
1793{
1794        /* libelf doesn't provide setters for ST_VISIBILITY,
1795         * but it is stored in the lower 2 bits of st_other
1796         */
1797        sym->st_other &= ~0x03;
1798        sym->st_other |= sym_vis;
1799}
1800
1801static int linker_append_elf_sym(struct bpf_linker *linker, struct src_obj *obj,
1802                                 Elf64_Sym *sym, const char *sym_name, int src_sym_idx)
1803{
1804        struct src_sec *src_sec = NULL;
1805        struct dst_sec *dst_sec = NULL;
1806        struct glob_sym *glob_sym = NULL;
1807        int name_off, sym_type, sym_bind, sym_vis, err;
1808        int btf_sec_id = 0, btf_id = 0;
1809        size_t dst_sym_idx;
1810        Elf64_Sym *dst_sym;
1811        bool sym_is_extern;
1812
1813        sym_type = ELF64_ST_TYPE(sym->st_info);
1814        sym_bind = ELF64_ST_BIND(sym->st_info);
1815        sym_vis = ELF64_ST_VISIBILITY(sym->st_other);
1816        sym_is_extern = sym->st_shndx == SHN_UNDEF;
1817
1818        if (sym_is_extern) {
1819                if (!obj->btf) {
1820                        pr_warn("externs without BTF info are not supported\n");
1821                        return -ENOTSUP;
1822                }
1823        } else if (sym->st_shndx < SHN_LORESERVE) {
1824                src_sec = &obj->secs[sym->st_shndx];
1825                if (src_sec->skipped)
1826                        return 0;
1827                dst_sec = &linker->secs[src_sec->dst_id];
1828
1829                /* allow only one STT_SECTION symbol per section */
1830                if (sym_type == STT_SECTION && dst_sec->sec_sym_idx) {
1831                        obj->sym_map[src_sym_idx] = dst_sec->sec_sym_idx;
1832                        return 0;
1833                }
1834        }
1835
1836        if (sym_bind == STB_LOCAL)
1837                goto add_sym;
1838
1839        /* find matching BTF info */
1840        err = find_glob_sym_btf(obj, sym, sym_name, &btf_sec_id, &btf_id);
1841        if (err)
1842                return err;
1843
1844        if (sym_is_extern && btf_sec_id) {
1845                const char *sec_name = NULL;
1846                const struct btf_type *t;
1847
1848                t = btf__type_by_id(obj->btf, btf_sec_id);
1849                sec_name = btf__str_by_offset(obj->btf, t->name_off);
1850
1851                /* Clang puts unannotated extern vars into
1852                 * '.extern' BTF DATASEC. Treat them the same
1853                 * as unannotated extern funcs (which are
1854                 * currently not put into any DATASECs).
1855                 * Those don't have associated src_sec/dst_sec.
1856                 */
1857                if (strcmp(sec_name, BTF_EXTERN_SEC) != 0) {
1858                        src_sec = find_src_sec_by_name(obj, sec_name);
1859                        if (!src_sec) {
1860                                pr_warn("failed to find matching ELF sec '%s'\n", sec_name);
1861                                return -ENOENT;
1862                        }
1863                        dst_sec = &linker->secs[src_sec->dst_id];
1864                }
1865        }
1866
1867        glob_sym = find_glob_sym(linker, sym_name);
1868        if (glob_sym) {
1869                /* Preventively resolve to existing symbol. This is
1870                 * needed for further relocation symbol remapping in
1871                 * the next step of linking.
1872                 */
1873                obj->sym_map[src_sym_idx] = glob_sym->sym_idx;
1874
1875                /* If both symbols are non-externs, at least one of
1876                 * them has to be STB_WEAK, otherwise they are in
1877                 * a conflict with each other.
1878                 */
1879                if (!sym_is_extern && !glob_sym->is_extern
1880                    && !glob_sym->is_weak && sym_bind != STB_WEAK) {
1881                        pr_warn("conflicting non-weak symbol #%d (%s) definition in '%s'\n",
1882                                src_sym_idx, sym_name, obj->filename);
1883                        return -EINVAL;
1884                }
1885
1886                if (!glob_syms_match(sym_name, linker, glob_sym, obj, sym, src_sym_idx, btf_id))
1887                        return -EINVAL;
1888
1889                dst_sym = get_sym_by_idx(linker, glob_sym->sym_idx);
1890
1891                /* If new symbol is strong, then force dst_sym to be strong as
1892                 * well; this way a mix of weak and non-weak extern
1893                 * definitions will end up being strong.
1894                 */
1895                if (sym_bind == STB_GLOBAL) {
1896                        /* We still need to preserve type (NOTYPE or
1897                         * OBJECT/FUNC, depending on whether the symbol is
1898                         * extern or not)
1899                         */
1900                        sym_update_bind(dst_sym, STB_GLOBAL);
1901                        glob_sym->is_weak = false;
1902                }
1903
1904                /* Non-default visibility is "contaminating", with stricter
1905                 * visibility overwriting more permissive ones, even if more
1906                 * permissive visibility comes from just an extern definition.
1907                 * Currently only STV_DEFAULT and STV_HIDDEN are allowed and
1908                 * ensured by ELF symbol sanity checks above.
1909                 */
1910                if (sym_vis > ELF64_ST_VISIBILITY(dst_sym->st_other))
1911                        sym_update_visibility(dst_sym, sym_vis);
1912
1913                /* If the new symbol is extern, then regardless if
1914                 * existing symbol is extern or resolved global, just
1915                 * keep the existing one untouched.
1916                 */
1917                if (sym_is_extern)
1918                        return 0;
1919
1920                /* If existing symbol is a strong resolved symbol, bail out,
1921                 * because we lost resolution battle have nothing to
1922                 * contribute. We already checked abover that there is no
1923                 * strong-strong conflict. We also already tightened binding
1924                 * and visibility, so nothing else to contribute at that point.
1925                 */
1926                if (!glob_sym->is_extern && sym_bind == STB_WEAK)
1927                        return 0;
1928
1929                /* At this point, new symbol is strong non-extern,
1930                 * so overwrite glob_sym with new symbol information.
1931                 * Preserve binding and visibility.
1932                 */
1933                sym_update_type(dst_sym, sym_type);
1934                dst_sym->st_shndx = dst_sec->sec_idx;
1935                dst_sym->st_value = src_sec->dst_off + sym->st_value;
1936                dst_sym->st_size = sym->st_size;
1937
1938                /* see comment below about dst_sec->id vs dst_sec->sec_idx */
1939                glob_sym->sec_id = dst_sec->id;
1940                glob_sym->is_extern = false;
1941
1942                if (complete_extern_btf_info(linker->btf, glob_sym->btf_id,
1943                                             obj->btf, btf_id))
1944                        return -EINVAL;
1945
1946                /* request updating VAR's/FUNC's underlying BTF type when appending BTF type */
1947                glob_sym->underlying_btf_id = 0;
1948
1949                obj->sym_map[src_sym_idx] = glob_sym->sym_idx;
1950                return 0;
1951        }
1952
1953add_sym:
1954        name_off = strset__add_str(linker->strtab_strs, sym_name);
1955        if (name_off < 0)
1956                return name_off;
1957
1958        dst_sym = add_new_sym(linker, &dst_sym_idx);
1959        if (!dst_sym)
1960                return -ENOMEM;
1961
1962        dst_sym->st_name = name_off;
1963        dst_sym->st_info = sym->st_info;
1964        dst_sym->st_other = sym->st_other;
1965        dst_sym->st_shndx = dst_sec ? dst_sec->sec_idx : sym->st_shndx;
1966        dst_sym->st_value = (src_sec ? src_sec->dst_off : 0) + sym->st_value;
1967        dst_sym->st_size = sym->st_size;
1968
1969        obj->sym_map[src_sym_idx] = dst_sym_idx;
1970
1971        if (sym_type == STT_SECTION && dst_sym) {
1972                dst_sec->sec_sym_idx = dst_sym_idx;
1973                dst_sym->st_value = 0;
1974        }
1975
1976        if (sym_bind != STB_LOCAL) {
1977                glob_sym = add_glob_sym(linker);
1978                if (!glob_sym)
1979                        return -ENOMEM;
1980
1981                glob_sym->sym_idx = dst_sym_idx;
1982                /* we use dst_sec->id (and not dst_sec->sec_idx), because
1983                 * ephemeral sections (.kconfig, .ksyms, etc) don't have
1984                 * sec_idx (as they don't have corresponding ELF section), but
1985                 * still have id. .extern doesn't have even ephemeral section
1986                 * associated with it, so dst_sec->id == dst_sec->sec_idx == 0.
1987                 */
1988                glob_sym->sec_id = dst_sec ? dst_sec->id : 0;
1989                glob_sym->name_off = name_off;
1990                /* we will fill btf_id in during BTF merging step */
1991                glob_sym->btf_id = 0;
1992                glob_sym->is_extern = sym_is_extern;
1993                glob_sym->is_weak = sym_bind == STB_WEAK;
1994        }
1995
1996        return 0;
1997}
1998
1999static int linker_append_elf_relos(struct bpf_linker *linker, struct src_obj *obj)
2000{
2001        struct src_sec *src_symtab = &obj->secs[obj->symtab_sec_idx];
2002        struct dst_sec *dst_symtab = &linker->secs[linker->symtab_sec_idx];
2003        int i, err;
2004
2005        for (i = 1; i < obj->sec_cnt; i++) {
2006                struct src_sec *src_sec, *src_linked_sec;
2007                struct dst_sec *dst_sec, *dst_linked_sec;
2008                Elf64_Rel *src_rel, *dst_rel;
2009                int j, n;
2010
2011                src_sec = &obj->secs[i];
2012                if (!is_relo_sec(src_sec))
2013                        continue;
2014
2015                /* shdr->sh_info points to relocatable section */
2016                src_linked_sec = &obj->secs[src_sec->shdr->sh_info];
2017                if (src_linked_sec->skipped)
2018                        continue;
2019
2020                dst_sec = find_dst_sec_by_name(linker, src_sec->sec_name);
2021                if (!dst_sec) {
2022                        dst_sec = add_dst_sec(linker, src_sec->sec_name);
2023                        if (!dst_sec)
2024                                return -ENOMEM;
2025                        err = init_sec(linker, dst_sec, src_sec);
2026                        if (err) {
2027                                pr_warn("failed to init section '%s'\n", src_sec->sec_name);
2028                                return err;
2029                        }
2030                } else if (!secs_match(dst_sec, src_sec)) {
2031                        pr_warn("sections %s are not compatible\n", src_sec->sec_name);
2032                        return -1;
2033                }
2034
2035                /* shdr->sh_link points to SYMTAB */
2036                dst_sec->shdr->sh_link = linker->symtab_sec_idx;
2037
2038                /* shdr->sh_info points to relocated section */
2039                dst_linked_sec = &linker->secs[src_linked_sec->dst_id];
2040                dst_sec->shdr->sh_info = dst_linked_sec->sec_idx;
2041
2042                src_sec->dst_id = dst_sec->id;
2043                err = extend_sec(linker, dst_sec, src_sec);
2044                if (err)
2045                        return err;
2046
2047                src_rel = src_sec->data->d_buf;
2048                dst_rel = dst_sec->raw_data + src_sec->dst_off;
2049                n = src_sec->shdr->sh_size / src_sec->shdr->sh_entsize;
2050                for (j = 0; j < n; j++, src_rel++, dst_rel++) {
2051                        size_t src_sym_idx = ELF64_R_SYM(src_rel->r_info);
2052                        size_t sym_type = ELF64_R_TYPE(src_rel->r_info);
2053                        Elf64_Sym *src_sym, *dst_sym;
2054                        size_t dst_sym_idx;
2055
2056                        src_sym_idx = ELF64_R_SYM(src_rel->r_info);
2057                        src_sym = src_symtab->data->d_buf + sizeof(*src_sym) * src_sym_idx;
2058
2059                        dst_sym_idx = obj->sym_map[src_sym_idx];
2060                        dst_sym = dst_symtab->raw_data + sizeof(*dst_sym) * dst_sym_idx;
2061                        dst_rel->r_offset += src_linked_sec->dst_off;
2062                        sym_type = ELF64_R_TYPE(src_rel->r_info);
2063                        dst_rel->r_info = ELF64_R_INFO(dst_sym_idx, sym_type);
2064
2065                        if (ELF64_ST_TYPE(src_sym->st_info) == STT_SECTION) {
2066                                struct src_sec *sec = &obj->secs[src_sym->st_shndx];
2067                                struct bpf_insn *insn;
2068
2069                                if (src_linked_sec->shdr->sh_flags & SHF_EXECINSTR) {
2070                                        /* calls to the very first static function inside
2071                                         * .text section at offset 0 will
2072                                         * reference section symbol, not the
2073                                         * function symbol. Fix that up,
2074                                         * otherwise it won't be possible to
2075                                         * relocate calls to two different
2076                                         * static functions with the same name
2077                                         * (rom two different object files)
2078                                         */
2079                                        insn = dst_linked_sec->raw_data + dst_rel->r_offset;
2080                                        if (insn->code == (BPF_JMP | BPF_CALL))
2081                                                insn->imm += sec->dst_off / sizeof(struct bpf_insn);
2082                                        else
2083                                                insn->imm += sec->dst_off;
2084                                } else {
2085                                        pr_warn("relocation against STT_SECTION in non-exec section is not supported!\n");
2086                                        return -EINVAL;
2087                                }
2088                        }
2089
2090                }
2091        }
2092
2093        return 0;
2094}
2095
2096static Elf64_Sym *find_sym_by_name(struct src_obj *obj, size_t sec_idx,
2097                                   int sym_type, const char *sym_name)
2098{
2099        struct src_sec *symtab = &obj->secs[obj->symtab_sec_idx];
2100        Elf64_Sym *sym = symtab->data->d_buf;
2101        int i, n = symtab->shdr->sh_size / symtab->shdr->sh_entsize;
2102        int str_sec_idx = symtab->shdr->sh_link;
2103        const char *name;
2104
2105        for (i = 0; i < n; i++, sym++) {
2106                if (sym->st_shndx != sec_idx)
2107                        continue;
2108                if (ELF64_ST_TYPE(sym->st_info) != sym_type)
2109                        continue;
2110
2111                name = elf_strptr(obj->elf, str_sec_idx, sym->st_name);
2112                if (!name)
2113                        return NULL;
2114
2115                if (strcmp(sym_name, name) != 0)
2116                        continue;
2117
2118                return sym;
2119        }
2120
2121        return NULL;
2122}
2123
2124static int linker_fixup_btf(struct src_obj *obj)
2125{
2126        const char *sec_name;
2127        struct src_sec *sec;
2128        int i, j, n, m;
2129
2130        if (!obj->btf)
2131                return 0;
2132
2133        n = btf__type_cnt(obj->btf);
2134        for (i = 1; i < n; i++) {
2135                struct btf_var_secinfo *vi;
2136                struct btf_type *t;
2137
2138                t = btf_type_by_id(obj->btf, i);
2139                if (btf_kind(t) != BTF_KIND_DATASEC)
2140                        continue;
2141
2142                sec_name = btf__str_by_offset(obj->btf, t->name_off);
2143                sec = find_src_sec_by_name(obj, sec_name);
2144                if (sec) {
2145                        /* record actual section size, unless ephemeral */
2146                        if (sec->shdr)
2147                                t->size = sec->shdr->sh_size;
2148                } else {
2149                        /* BTF can have some sections that are not represented
2150                         * in ELF, e.g., .kconfig, .ksyms, .extern, which are used
2151                         * for special extern variables.
2152                         *
2153                         * For all but one such special (ephemeral)
2154                         * sections, we pre-create "section shells" to be able
2155                         * to keep track of extra per-section metadata later
2156                         * (e.g., those BTF extern variables).
2157                         *
2158                         * .extern is even more special, though, because it
2159                         * contains extern variables that need to be resolved
2160                         * by static linker, not libbpf and kernel. When such
2161                         * externs are resolved, we are going to remove them
2162                         * from .extern BTF section and might end up not
2163                         * needing it at all. Each resolved extern should have
2164                         * matching non-extern VAR/FUNC in other sections.
2165                         *
2166                         * We do support leaving some of the externs
2167                         * unresolved, though, to support cases of building
2168                         * libraries, which will later be linked against final
2169                         * BPF applications. So if at finalization we still
2170                         * see unresolved externs, we'll create .extern
2171                         * section on our own.
2172                         */
2173                        if (strcmp(sec_name, BTF_EXTERN_SEC) == 0)
2174                                continue;
2175
2176                        sec = add_src_sec(obj, sec_name);
2177                        if (!sec)
2178                                return -ENOMEM;
2179
2180                        sec->ephemeral = true;
2181                        sec->sec_idx = 0; /* will match UNDEF shndx in ELF */
2182                }
2183
2184                /* remember ELF section and its BTF type ID match */
2185                sec->sec_type_id = i;
2186
2187                /* fix up variable offsets */
2188                vi = btf_var_secinfos(t);
2189                for (j = 0, m = btf_vlen(t); j < m; j++, vi++) {
2190                        const struct btf_type *vt = btf__type_by_id(obj->btf, vi->type);
2191                        const char *var_name = btf__str_by_offset(obj->btf, vt->name_off);
2192                        int var_linkage = btf_var(vt)->linkage;
2193                        Elf64_Sym *sym;
2194
2195                        /* no need to patch up static or extern vars */
2196                        if (var_linkage != BTF_VAR_GLOBAL_ALLOCATED)
2197                                continue;
2198
2199                        sym = find_sym_by_name(obj, sec->sec_idx, STT_OBJECT, var_name);
2200                        if (!sym) {
2201                                pr_warn("failed to find symbol for variable '%s' in section '%s'\n", var_name, sec_name);
2202                                return -ENOENT;
2203                        }
2204
2205                        vi->offset = sym->st_value;
2206                }
2207        }
2208
2209        return 0;
2210}
2211
2212static int remap_type_id(__u32 *type_id, void *ctx)
2213{
2214        int *id_map = ctx;
2215        int new_id = id_map[*type_id];
2216
2217        /* Error out if the type wasn't remapped. Ignore VOID which stays VOID. */
2218        if (new_id == 0 && *type_id != 0) {
2219                pr_warn("failed to find new ID mapping for original BTF type ID %u\n", *type_id);
2220                return -EINVAL;
2221        }
2222
2223        *type_id = id_map[*type_id];
2224
2225        return 0;
2226}
2227
2228static int linker_append_btf(struct bpf_linker *linker, struct src_obj *obj)
2229{
2230        const struct btf_type *t;
2231        int i, j, n, start_id, id;
2232        const char *name;
2233
2234        if (!obj->btf)
2235                return 0;
2236
2237        start_id = btf__type_cnt(linker->btf);
2238        n = btf__type_cnt(obj->btf);
2239
2240        obj->btf_type_map = calloc(n + 1, sizeof(int));
2241        if (!obj->btf_type_map)
2242                return -ENOMEM;
2243
2244        for (i = 1; i < n; i++) {
2245                struct glob_sym *glob_sym = NULL;
2246
2247                t = btf__type_by_id(obj->btf, i);
2248
2249                /* DATASECs are handled specially below */
2250                if (btf_kind(t) == BTF_KIND_DATASEC)
2251                        continue;
2252
2253                if (btf_is_non_static(t)) {
2254                        /* there should be glob_sym already */
2255                        name = btf__str_by_offset(obj->btf, t->name_off);
2256                        glob_sym = find_glob_sym(linker, name);
2257
2258                        /* VARs without corresponding glob_sym are those that
2259                         * belong to skipped/deduplicated sections (i.e.,
2260                         * license and version), so just skip them
2261                         */
2262                        if (!glob_sym)
2263                                continue;
2264
2265                        /* linker_append_elf_sym() might have requested
2266                         * updating underlying type ID, if extern was resolved
2267                         * to strong symbol or weak got upgraded to non-weak
2268                         */
2269                        if (glob_sym->underlying_btf_id == 0)
2270                                glob_sym->underlying_btf_id = -t->type;
2271
2272                        /* globals from previous object files that match our
2273                         * VAR/FUNC already have a corresponding associated
2274                         * BTF type, so just make sure to use it
2275                         */
2276                        if (glob_sym->btf_id) {
2277                                /* reuse existing BTF type for global var/func */
2278                                obj->btf_type_map[i] = glob_sym->btf_id;
2279                                continue;
2280                        }
2281                }
2282
2283                id = btf__add_type(linker->btf, obj->btf, t);
2284                if (id < 0) {
2285                        pr_warn("failed to append BTF type #%d from file '%s'\n", i, obj->filename);
2286                        return id;
2287                }
2288
2289                obj->btf_type_map[i] = id;
2290
2291                /* record just appended BTF type for var/func */
2292                if (glob_sym) {
2293                        glob_sym->btf_id = id;
2294                        glob_sym->underlying_btf_id = -t->type;
2295                }
2296        }
2297
2298        /* remap all the types except DATASECs */
2299        n = btf__type_cnt(linker->btf);
2300        for (i = start_id; i < n; i++) {
2301                struct btf_type *dst_t = btf_type_by_id(linker->btf, i);
2302
2303                if (btf_type_visit_type_ids(dst_t, remap_type_id, obj->btf_type_map))
2304                        return -EINVAL;
2305        }
2306
2307        /* Rewrite VAR/FUNC underlying types (i.e., FUNC's FUNC_PROTO and VAR's
2308         * actual type), if necessary
2309         */
2310        for (i = 0; i < linker->glob_sym_cnt; i++) {
2311                struct glob_sym *glob_sym = &linker->glob_syms[i];
2312                struct btf_type *glob_t;
2313
2314                if (glob_sym->underlying_btf_id >= 0)
2315                        continue;
2316
2317                glob_sym->underlying_btf_id = obj->btf_type_map[-glob_sym->underlying_btf_id];
2318
2319                glob_t = btf_type_by_id(linker->btf, glob_sym->btf_id);
2320                glob_t->type = glob_sym->underlying_btf_id;
2321        }
2322
2323        /* append DATASEC info */
2324        for (i = 1; i < obj->sec_cnt; i++) {
2325                struct src_sec *src_sec;
2326                struct dst_sec *dst_sec;
2327                const struct btf_var_secinfo *src_var;
2328                struct btf_var_secinfo *dst_var;
2329
2330                src_sec = &obj->secs[i];
2331                if (!src_sec->sec_type_id || src_sec->skipped)
2332                        continue;
2333                dst_sec = &linker->secs[src_sec->dst_id];
2334
2335                /* Mark section as having BTF regardless of the presence of
2336                 * variables. In some cases compiler might generate empty BTF
2337                 * with no variables information. E.g., when promoting local
2338                 * array/structure variable initial values and BPF object
2339                 * file otherwise has no read-only static variables in
2340                 * .rodata. We need to preserve such empty BTF and just set
2341                 * correct section size.
2342                 */
2343                dst_sec->has_btf = true;
2344
2345                t = btf__type_by_id(obj->btf, src_sec->sec_type_id);
2346                src_var = btf_var_secinfos(t);
2347                n = btf_vlen(t);
2348                for (j = 0; j < n; j++, src_var++) {
2349                        void *sec_vars = dst_sec->sec_vars;
2350                        int new_id = obj->btf_type_map[src_var->type];
2351                        struct glob_sym *glob_sym = NULL;
2352
2353                        t = btf_type_by_id(linker->btf, new_id);
2354                        if (btf_is_non_static(t)) {
2355                                name = btf__str_by_offset(linker->btf, t->name_off);
2356                                glob_sym = find_glob_sym(linker, name);
2357                                if (glob_sym->sec_id != dst_sec->id) {
2358                                        pr_warn("global '%s': section mismatch %d vs %d\n",
2359                                                name, glob_sym->sec_id, dst_sec->id);
2360                                        return -EINVAL;
2361                                }
2362                        }
2363
2364                        /* If there is already a member (VAR or FUNC) mapped
2365                         * to the same type, don't add a duplicate entry.
2366                         * This will happen when multiple object files define
2367                         * the same extern VARs/FUNCs.
2368                         */
2369                        if (glob_sym && glob_sym->var_idx >= 0) {
2370                                __s64 sz;
2371
2372                                dst_var = &dst_sec->sec_vars[glob_sym->var_idx];
2373                                /* Because underlying BTF type might have
2374                                 * changed, so might its size have changed, so
2375                                 * re-calculate and update it in sec_var.
2376                                 */
2377                                sz = btf__resolve_size(linker->btf, glob_sym->underlying_btf_id);
2378                                if (sz < 0) {
2379                                        pr_warn("global '%s': failed to resolve size of underlying type: %d\n",
2380                                                name, (int)sz);
2381                                        return -EINVAL;
2382                                }
2383                                dst_var->size = sz;
2384                                continue;
2385                        }
2386
2387                        sec_vars = libbpf_reallocarray(sec_vars,
2388                                                       dst_sec->sec_var_cnt + 1,
2389                                                       sizeof(*dst_sec->sec_vars));
2390                        if (!sec_vars)
2391                                return -ENOMEM;
2392
2393                        dst_sec->sec_vars = sec_vars;
2394                        dst_sec->sec_var_cnt++;
2395
2396                        dst_var = &dst_sec->sec_vars[dst_sec->sec_var_cnt - 1];
2397                        dst_var->type = obj->btf_type_map[src_var->type];
2398                        dst_var->size = src_var->size;
2399                        dst_var->offset = src_sec->dst_off + src_var->offset;
2400
2401                        if (glob_sym)
2402                                glob_sym->var_idx = dst_sec->sec_var_cnt - 1;
2403                }
2404        }
2405
2406        return 0;
2407}
2408
2409static void *add_btf_ext_rec(struct btf_ext_sec_data *ext_data, const void *src_rec)
2410{
2411        void *tmp;
2412
2413        tmp = libbpf_reallocarray(ext_data->recs, ext_data->rec_cnt + 1, ext_data->rec_sz);
2414        if (!tmp)
2415                return NULL;
2416        ext_data->recs = tmp;
2417
2418        tmp += ext_data->rec_cnt * ext_data->rec_sz;
2419        memcpy(tmp, src_rec, ext_data->rec_sz);
2420
2421        ext_data->rec_cnt++;
2422
2423        return tmp;
2424}
2425
2426static int linker_append_btf_ext(struct bpf_linker *linker, struct src_obj *obj)
2427{
2428        const struct btf_ext_info_sec *ext_sec;
2429        const char *sec_name, *s;
2430        struct src_sec *src_sec;
2431        struct dst_sec *dst_sec;
2432        int rec_sz, str_off, i;
2433
2434        if (!obj->btf_ext)
2435                return 0;
2436
2437        rec_sz = obj->btf_ext->func_info.rec_size;
2438        for_each_btf_ext_sec(&obj->btf_ext->func_info, ext_sec) {
2439                struct bpf_func_info_min *src_rec, *dst_rec;
2440
2441                sec_name = btf__name_by_offset(obj->btf, ext_sec->sec_name_off);
2442                src_sec = find_src_sec_by_name(obj, sec_name);
2443                if (!src_sec) {
2444                        pr_warn("can't find section '%s' referenced from .BTF.ext\n", sec_name);
2445                        return -EINVAL;
2446                }
2447                dst_sec = &linker->secs[src_sec->dst_id];
2448
2449                if (dst_sec->func_info.rec_sz == 0)
2450                        dst_sec->func_info.rec_sz = rec_sz;
2451                if (dst_sec->func_info.rec_sz != rec_sz) {
2452                        pr_warn("incompatible .BTF.ext record sizes for section '%s'\n", sec_name);
2453                        return -EINVAL;
2454                }
2455
2456                for_each_btf_ext_rec(&obj->btf_ext->func_info, ext_sec, i, src_rec) {
2457                        dst_rec = add_btf_ext_rec(&dst_sec->func_info, src_rec);
2458                        if (!dst_rec)
2459                                return -ENOMEM;
2460
2461                        dst_rec->insn_off += src_sec->dst_off;
2462                        dst_rec->type_id = obj->btf_type_map[dst_rec->type_id];
2463                }
2464        }
2465
2466        rec_sz = obj->btf_ext->line_info.rec_size;
2467        for_each_btf_ext_sec(&obj->btf_ext->line_info, ext_sec) {
2468                struct bpf_line_info_min *src_rec, *dst_rec;
2469
2470                sec_name = btf__name_by_offset(obj->btf, ext_sec->sec_name_off);
2471                src_sec = find_src_sec_by_name(obj, sec_name);
2472                if (!src_sec) {
2473                        pr_warn("can't find section '%s' referenced from .BTF.ext\n", sec_name);
2474                        return -EINVAL;
2475                }
2476                dst_sec = &linker->secs[src_sec->dst_id];
2477
2478                if (dst_sec->line_info.rec_sz == 0)
2479                        dst_sec->line_info.rec_sz = rec_sz;
2480                if (dst_sec->line_info.rec_sz != rec_sz) {
2481                        pr_warn("incompatible .BTF.ext record sizes for section '%s'\n", sec_name);
2482                        return -EINVAL;
2483                }
2484
2485                for_each_btf_ext_rec(&obj->btf_ext->line_info, ext_sec, i, src_rec) {
2486                        dst_rec = add_btf_ext_rec(&dst_sec->line_info, src_rec);
2487                        if (!dst_rec)
2488                                return -ENOMEM;
2489
2490                        dst_rec->insn_off += src_sec->dst_off;
2491
2492                        s = btf__str_by_offset(obj->btf, src_rec->file_name_off);
2493                        str_off = btf__add_str(linker->btf, s);
2494                        if (str_off < 0)
2495                                return -ENOMEM;
2496                        dst_rec->file_name_off = str_off;
2497
2498                        s = btf__str_by_offset(obj->btf, src_rec->line_off);
2499                        str_off = btf__add_str(linker->btf, s);
2500                        if (str_off < 0)
2501                                return -ENOMEM;
2502                        dst_rec->line_off = str_off;
2503
2504                        /* dst_rec->line_col is fine */
2505                }
2506        }
2507
2508        rec_sz = obj->btf_ext->core_relo_info.rec_size;
2509        for_each_btf_ext_sec(&obj->btf_ext->core_relo_info, ext_sec) {
2510                struct bpf_core_relo *src_rec, *dst_rec;
2511
2512                sec_name = btf__name_by_offset(obj->btf, ext_sec->sec_name_off);
2513                src_sec = find_src_sec_by_name(obj, sec_name);
2514                if (!src_sec) {
2515                        pr_warn("can't find section '%s' referenced from .BTF.ext\n", sec_name);
2516                        return -EINVAL;
2517                }
2518                dst_sec = &linker->secs[src_sec->dst_id];
2519
2520                if (dst_sec->core_relo_info.rec_sz == 0)
2521                        dst_sec->core_relo_info.rec_sz = rec_sz;
2522                if (dst_sec->core_relo_info.rec_sz != rec_sz) {
2523                        pr_warn("incompatible .BTF.ext record sizes for section '%s'\n", sec_name);
2524                        return -EINVAL;
2525                }
2526
2527                for_each_btf_ext_rec(&obj->btf_ext->core_relo_info, ext_sec, i, src_rec) {
2528                        dst_rec = add_btf_ext_rec(&dst_sec->core_relo_info, src_rec);
2529                        if (!dst_rec)
2530                                return -ENOMEM;
2531
2532                        dst_rec->insn_off += src_sec->dst_off;
2533                        dst_rec->type_id = obj->btf_type_map[dst_rec->type_id];
2534
2535                        s = btf__str_by_offset(obj->btf, src_rec->access_str_off);
2536                        str_off = btf__add_str(linker->btf, s);
2537                        if (str_off < 0)
2538                                return -ENOMEM;
2539                        dst_rec->access_str_off = str_off;
2540
2541                        /* dst_rec->kind is fine */
2542                }
2543        }
2544
2545        return 0;
2546}
2547
2548int bpf_linker__finalize(struct bpf_linker *linker)
2549{
2550        struct dst_sec *sec;
2551        size_t strs_sz;
2552        const void *strs;
2553        int err, i;
2554
2555        if (!linker->elf)
2556                return libbpf_err(-EINVAL);
2557
2558        err = finalize_btf(linker);
2559        if (err)
2560                return libbpf_err(err);
2561
2562        /* Finalize strings */
2563        strs_sz = strset__data_size(linker->strtab_strs);
2564        strs = strset__data(linker->strtab_strs);
2565
2566        sec = &linker->secs[linker->strtab_sec_idx];
2567        sec->data->d_align = 1;
2568        sec->data->d_off = 0LL;
2569        sec->data->d_buf = (void *)strs;
2570        sec->data->d_type = ELF_T_BYTE;
2571        sec->data->d_size = strs_sz;
2572        sec->shdr->sh_size = strs_sz;
2573
2574        for (i = 1; i < linker->sec_cnt; i++) {
2575                sec = &linker->secs[i];
2576
2577                /* STRTAB is handled specially above */
2578                if (sec->sec_idx == linker->strtab_sec_idx)
2579                        continue;
2580
2581                /* special ephemeral sections (.ksyms, .kconfig, etc) */
2582                if (!sec->scn)
2583                        continue;
2584
2585                sec->data->d_buf = sec->raw_data;
2586        }
2587
2588        /* Finalize ELF layout */
2589        if (elf_update(linker->elf, ELF_C_NULL) < 0) {
2590                err = -errno;
2591                pr_warn_elf("failed to finalize ELF layout");
2592                return libbpf_err(err);
2593        }
2594
2595        /* Write out final ELF contents */
2596        if (elf_update(linker->elf, ELF_C_WRITE) < 0) {
2597                err = -errno;
2598                pr_warn_elf("failed to write ELF contents");
2599                return libbpf_err(err);
2600        }
2601
2602        elf_end(linker->elf);
2603        close(linker->fd);
2604
2605        linker->elf = NULL;
2606        linker->fd = -1;
2607
2608        return 0;
2609}
2610
2611static int emit_elf_data_sec(struct bpf_linker *linker, const char *sec_name,
2612                             size_t align, const void *raw_data, size_t raw_sz)
2613{
2614        Elf_Scn *scn;
2615        Elf_Data *data;
2616        Elf64_Shdr *shdr;
2617        int name_off;
2618
2619        name_off = strset__add_str(linker->strtab_strs, sec_name);
2620        if (name_off < 0)
2621                return name_off;
2622
2623        scn = elf_newscn(linker->elf);
2624        if (!scn)
2625                return -ENOMEM;
2626        data = elf_newdata(scn);
2627        if (!data)
2628                return -ENOMEM;
2629        shdr = elf64_getshdr(scn);
2630        if (!shdr)
2631                return -EINVAL;
2632
2633        shdr->sh_name = name_off;
2634        shdr->sh_type = SHT_PROGBITS;
2635        shdr->sh_flags = 0;
2636        shdr->sh_size = raw_sz;
2637        shdr->sh_link = 0;
2638        shdr->sh_info = 0;
2639        shdr->sh_addralign = align;
2640        shdr->sh_entsize = 0;
2641
2642        data->d_type = ELF_T_BYTE;
2643        data->d_size = raw_sz;
2644        data->d_buf = (void *)raw_data;
2645        data->d_align = align;
2646        data->d_off = 0;
2647
2648        return 0;
2649}
2650
2651static int finalize_btf(struct bpf_linker *linker)
2652{
2653        struct btf *btf = linker->btf;
2654        const void *raw_data;
2655        int i, j, id, err;
2656        __u32 raw_sz;
2657
2658        /* bail out if no BTF data was produced */
2659        if (btf__type_cnt(linker->btf) == 1)
2660                return 0;
2661
2662        for (i = 1; i < linker->sec_cnt; i++) {
2663                struct dst_sec *sec = &linker->secs[i];
2664
2665                if (!sec->has_btf)
2666                        continue;
2667
2668                id = btf__add_datasec(btf, sec->sec_name, sec->sec_sz);
2669                if (id < 0) {
2670                        pr_warn("failed to add consolidated BTF type for datasec '%s': %d\n",
2671                                sec->sec_name, id);
2672                        return id;
2673                }
2674
2675                for (j = 0; j < sec->sec_var_cnt; j++) {
2676                        struct btf_var_secinfo *vi = &sec->sec_vars[j];
2677
2678                        if (btf__add_datasec_var_info(btf, vi->type, vi->offset, vi->size))
2679                                return -EINVAL;
2680                }
2681        }
2682
2683        err = finalize_btf_ext(linker);
2684        if (err) {
2685                pr_warn(".BTF.ext generation failed: %d\n", err);
2686                return err;
2687        }
2688
2689        err = btf__dedup(linker->btf, linker->btf_ext, NULL);
2690        if (err) {
2691                pr_warn("BTF dedup failed: %d\n", err);
2692                return err;
2693        }
2694
2695        /* Emit .BTF section */
2696        raw_data = btf__raw_data(linker->btf, &raw_sz);
2697        if (!raw_data)
2698                return -ENOMEM;
2699
2700        err = emit_elf_data_sec(linker, BTF_ELF_SEC, 8, raw_data, raw_sz);
2701        if (err) {
2702                pr_warn("failed to write out .BTF ELF section: %d\n", err);
2703                return err;
2704        }
2705
2706        /* Emit .BTF.ext section */
2707        if (linker->btf_ext) {
2708                raw_data = btf_ext__get_raw_data(linker->btf_ext, &raw_sz);
2709                if (!raw_data)
2710                        return -ENOMEM;
2711
2712                err = emit_elf_data_sec(linker, BTF_EXT_ELF_SEC, 8, raw_data, raw_sz);
2713                if (err) {
2714                        pr_warn("failed to write out .BTF.ext ELF section: %d\n", err);
2715                        return err;
2716                }
2717        }
2718
2719        return 0;
2720}
2721
2722static int emit_btf_ext_data(struct bpf_linker *linker, void *output,
2723                             const char *sec_name, struct btf_ext_sec_data *sec_data)
2724{
2725        struct btf_ext_info_sec *sec_info;
2726        void *cur = output;
2727        int str_off;
2728        size_t sz;
2729
2730        if (!sec_data->rec_cnt)
2731                return 0;
2732
2733        str_off = btf__add_str(linker->btf, sec_name);
2734        if (str_off < 0)
2735                return -ENOMEM;
2736
2737        sec_info = cur;
2738        sec_info->sec_name_off = str_off;
2739        sec_info->num_info = sec_data->rec_cnt;
2740        cur += sizeof(struct btf_ext_info_sec);
2741
2742        sz = sec_data->rec_cnt * sec_data->rec_sz;
2743        memcpy(cur, sec_data->recs, sz);
2744        cur += sz;
2745
2746        return cur - output;
2747}
2748
2749static int finalize_btf_ext(struct bpf_linker *linker)
2750{
2751        size_t funcs_sz = 0, lines_sz = 0, core_relos_sz = 0, total_sz = 0;
2752        size_t func_rec_sz = 0, line_rec_sz = 0, core_relo_rec_sz = 0;
2753        struct btf_ext_header *hdr;
2754        void *data, *cur;
2755        int i, err, sz;
2756
2757        /* validate that all sections have the same .BTF.ext record sizes
2758         * and calculate total data size for each type of data (func info,
2759         * line info, core relos)
2760         */
2761        for (i = 1; i < linker->sec_cnt; i++) {
2762                struct dst_sec *sec = &linker->secs[i];
2763
2764                if (sec->func_info.rec_cnt) {
2765                        if (func_rec_sz == 0)
2766                                func_rec_sz = sec->func_info.rec_sz;
2767                        if (func_rec_sz != sec->func_info.rec_sz) {
2768                                pr_warn("mismatch in func_info record size %zu != %u\n",
2769                                        func_rec_sz, sec->func_info.rec_sz);
2770                                return -EINVAL;
2771                        }
2772
2773                        funcs_sz += sizeof(struct btf_ext_info_sec) + func_rec_sz * sec->func_info.rec_cnt;
2774                }
2775                if (sec->line_info.rec_cnt) {
2776                        if (line_rec_sz == 0)
2777                                line_rec_sz = sec->line_info.rec_sz;
2778                        if (line_rec_sz != sec->line_info.rec_sz) {
2779                                pr_warn("mismatch in line_info record size %zu != %u\n",
2780                                        line_rec_sz, sec->line_info.rec_sz);
2781                                return -EINVAL;
2782                        }
2783
2784                        lines_sz += sizeof(struct btf_ext_info_sec) + line_rec_sz * sec->line_info.rec_cnt;
2785                }
2786                if (sec->core_relo_info.rec_cnt) {
2787                        if (core_relo_rec_sz == 0)
2788                                core_relo_rec_sz = sec->core_relo_info.rec_sz;
2789                        if (core_relo_rec_sz != sec->core_relo_info.rec_sz) {
2790                                pr_warn("mismatch in core_relo_info record size %zu != %u\n",
2791                                        core_relo_rec_sz, sec->core_relo_info.rec_sz);
2792                                return -EINVAL;
2793                        }
2794
2795                        core_relos_sz += sizeof(struct btf_ext_info_sec) + core_relo_rec_sz * sec->core_relo_info.rec_cnt;
2796                }
2797        }
2798
2799        if (!funcs_sz && !lines_sz && !core_relos_sz)
2800                return 0;
2801
2802        total_sz += sizeof(struct btf_ext_header);
2803        if (funcs_sz) {
2804                funcs_sz += sizeof(__u32); /* record size prefix */
2805                total_sz += funcs_sz;
2806        }
2807        if (lines_sz) {
2808                lines_sz += sizeof(__u32); /* record size prefix */
2809                total_sz += lines_sz;
2810        }
2811        if (core_relos_sz) {
2812                core_relos_sz += sizeof(__u32); /* record size prefix */
2813                total_sz += core_relos_sz;
2814        }
2815
2816        cur = data = calloc(1, total_sz);
2817        if (!data)
2818                return -ENOMEM;
2819
2820        hdr = cur;
2821        hdr->magic = BTF_MAGIC;
2822        hdr->version = BTF_VERSION;
2823        hdr->flags = 0;
2824        hdr->hdr_len = sizeof(struct btf_ext_header);
2825        cur += sizeof(struct btf_ext_header);
2826
2827        /* All offsets are in bytes relative to the end of this header */
2828        hdr->func_info_off = 0;
2829        hdr->func_info_len = funcs_sz;
2830        hdr->line_info_off = funcs_sz;
2831        hdr->line_info_len = lines_sz;
2832        hdr->core_relo_off = funcs_sz + lines_sz;
2833        hdr->core_relo_len = core_relos_sz;
2834
2835        if (funcs_sz) {
2836                *(__u32 *)cur = func_rec_sz;
2837                cur += sizeof(__u32);
2838
2839                for (i = 1; i < linker->sec_cnt; i++) {
2840                        struct dst_sec *sec = &linker->secs[i];
2841
2842                        sz = emit_btf_ext_data(linker, cur, sec->sec_name, &sec->func_info);
2843                        if (sz < 0) {
2844                                err = sz;
2845                                goto out;
2846                        }
2847
2848                        cur += sz;
2849                }
2850        }
2851
2852        if (lines_sz) {
2853                *(__u32 *)cur = line_rec_sz;
2854                cur += sizeof(__u32);
2855
2856                for (i = 1; i < linker->sec_cnt; i++) {
2857                        struct dst_sec *sec = &linker->secs[i];
2858
2859                        sz = emit_btf_ext_data(linker, cur, sec->sec_name, &sec->line_info);
2860                        if (sz < 0) {
2861                                err = sz;
2862                                goto out;
2863                        }
2864
2865                        cur += sz;
2866                }
2867        }
2868
2869        if (core_relos_sz) {
2870                *(__u32 *)cur = core_relo_rec_sz;
2871                cur += sizeof(__u32);
2872
2873                for (i = 1; i < linker->sec_cnt; i++) {
2874                        struct dst_sec *sec = &linker->secs[i];
2875
2876                        sz = emit_btf_ext_data(linker, cur, sec->sec_name, &sec->core_relo_info);
2877                        if (sz < 0) {
2878                                err = sz;
2879                                goto out;
2880                        }
2881
2882                        cur += sz;
2883                }
2884        }
2885
2886        linker->btf_ext = btf_ext__new(data, total_sz);
2887        err = libbpf_get_error(linker->btf_ext);
2888        if (err) {
2889                linker->btf_ext = NULL;
2890                pr_warn("failed to parse final .BTF.ext data: %d\n", err);
2891                goto out;
2892        }
2893
2894out:
2895        free(data);
2896        return err;
2897}
2898