Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
0002 /*
0003  * BPF static linker
0004  *
0005  * Copyright (c) 2021 Facebook
0006  */
0007 #include <stdbool.h>
0008 #include <stddef.h>
0009 #include <stdio.h>
0010 #include <stdlib.h>
0011 #include <string.h>
0012 #include <unistd.h>
0013 #include <errno.h>
0014 #include <linux/err.h>
0015 #include <linux/btf.h>
0016 #include <elf.h>
0017 #include <libelf.h>
0018 #include <fcntl.h>
0019 #include "libbpf.h"
0020 #include "btf.h"
0021 #include "libbpf_internal.h"
0022 #include "strset.h"
0023 
0024 #define BTF_EXTERN_SEC ".extern"
0025 
0026 struct src_sec {
0027     const char *sec_name;
0028     /* positional (not necessarily ELF) index in an array of sections */
0029     int id;
0030     /* positional (not necessarily ELF) index of a matching section in a final object file */
0031     int dst_id;
0032     /* section data offset in a matching output section */
0033     int dst_off;
0034     /* whether section is omitted from the final ELF file */
0035     bool skipped;
0036     /* whether section is an ephemeral section, not mapped to an ELF section */
0037     bool ephemeral;
0038 
0039     /* ELF info */
0040     size_t sec_idx;
0041     Elf_Scn *scn;
0042     Elf64_Shdr *shdr;
0043     Elf_Data *data;
0044 
0045     /* corresponding BTF DATASEC type ID */
0046     int sec_type_id;
0047 };
0048 
0049 struct src_obj {
0050     const char *filename;
0051     int fd;
0052     Elf *elf;
0053     /* Section header strings section index */
0054     size_t shstrs_sec_idx;
0055     /* SYMTAB section index */
0056     size_t symtab_sec_idx;
0057 
0058     struct btf *btf;
0059     struct btf_ext *btf_ext;
0060 
0061     /* List of sections (including ephemeral). Slot zero is unused. */
0062     struct src_sec *secs;
0063     int sec_cnt;
0064 
0065     /* mapping of symbol indices from src to dst ELF */
0066     int *sym_map;
0067     /* mapping from the src BTF type IDs to dst ones */
0068     int *btf_type_map;
0069 };
0070 
0071 /* single .BTF.ext data section */
0072 struct btf_ext_sec_data {
0073     size_t rec_cnt;
0074     __u32 rec_sz;
0075     void *recs;
0076 };
0077 
0078 struct glob_sym {
0079     /* ELF symbol index */
0080     int sym_idx;
0081     /* associated section id for .ksyms, .kconfig, etc, but not .extern */
0082     int sec_id;
0083     /* extern name offset in STRTAB */
0084     int name_off;
0085     /* optional associated BTF type ID */
0086     int btf_id;
0087     /* BTF type ID to which VAR/FUNC type is pointing to; used for
0088      * rewriting types when extern VAR/FUNC is resolved to a concrete
0089      * definition
0090      */
0091     int underlying_btf_id;
0092     /* sec_var index in the corresponding dst_sec, if exists */
0093     int var_idx;
0094 
0095     /* extern or resolved/global symbol */
0096     bool is_extern;
0097     /* weak or strong symbol, never goes back from strong to weak */
0098     bool is_weak;
0099 };
0100 
0101 struct dst_sec {
0102     char *sec_name;
0103     /* positional (not necessarily ELF) index in an array of sections */
0104     int id;
0105 
0106     bool ephemeral;
0107 
0108     /* ELF info */
0109     size_t sec_idx;
0110     Elf_Scn *scn;
0111     Elf64_Shdr *shdr;
0112     Elf_Data *data;
0113 
0114     /* final output section size */
0115     int sec_sz;
0116     /* final output contents of the section */
0117     void *raw_data;
0118 
0119     /* corresponding STT_SECTION symbol index in SYMTAB */
0120     int sec_sym_idx;
0121 
0122     /* section's DATASEC variable info, emitted on BTF finalization */
0123     bool has_btf;
0124     int sec_var_cnt;
0125     struct btf_var_secinfo *sec_vars;
0126 
0127     /* section's .BTF.ext data */
0128     struct btf_ext_sec_data func_info;
0129     struct btf_ext_sec_data line_info;
0130     struct btf_ext_sec_data core_relo_info;
0131 };
0132 
0133 struct bpf_linker {
0134     char *filename;
0135     int fd;
0136     Elf *elf;
0137     Elf64_Ehdr *elf_hdr;
0138 
0139     /* Output sections metadata */
0140     struct dst_sec *secs;
0141     int sec_cnt;
0142 
0143     struct strset *strtab_strs; /* STRTAB unique strings */
0144     size_t strtab_sec_idx; /* STRTAB section index */
0145     size_t symtab_sec_idx; /* SYMTAB section index */
0146 
0147     struct btf *btf;
0148     struct btf_ext *btf_ext;
0149 
0150     /* global (including extern) ELF symbols */
0151     int glob_sym_cnt;
0152     struct glob_sym *glob_syms;
0153 };
0154 
0155 #define pr_warn_elf(fmt, ...)                                   \
0156     libbpf_print(LIBBPF_WARN, "libbpf: " fmt ": %s\n", ##__VA_ARGS__, elf_errmsg(-1))
0157 
0158 static int init_output_elf(struct bpf_linker *linker, const char *file);
0159 
0160 static int linker_load_obj_file(struct bpf_linker *linker, const char *filename,
0161                 const struct bpf_linker_file_opts *opts,
0162                 struct src_obj *obj);
0163 static int linker_sanity_check_elf(struct src_obj *obj);
0164 static int linker_sanity_check_elf_symtab(struct src_obj *obj, struct src_sec *sec);
0165 static int linker_sanity_check_elf_relos(struct src_obj *obj, struct src_sec *sec);
0166 static int linker_sanity_check_btf(struct src_obj *obj);
0167 static int linker_sanity_check_btf_ext(struct src_obj *obj);
0168 static int linker_fixup_btf(struct src_obj *obj);
0169 static int linker_append_sec_data(struct bpf_linker *linker, struct src_obj *obj);
0170 static int linker_append_elf_syms(struct bpf_linker *linker, struct src_obj *obj);
0171 static int linker_append_elf_sym(struct bpf_linker *linker, struct src_obj *obj,
0172                  Elf64_Sym *sym, const char *sym_name, int src_sym_idx);
0173 static int linker_append_elf_relos(struct bpf_linker *linker, struct src_obj *obj);
0174 static int linker_append_btf(struct bpf_linker *linker, struct src_obj *obj);
0175 static int linker_append_btf_ext(struct bpf_linker *linker, struct src_obj *obj);
0176 
0177 static int finalize_btf(struct bpf_linker *linker);
0178 static int finalize_btf_ext(struct bpf_linker *linker);
0179 
0180 void bpf_linker__free(struct bpf_linker *linker)
0181 {
0182     int i;
0183 
0184     if (!linker)
0185         return;
0186 
0187     free(linker->filename);
0188 
0189     if (linker->elf)
0190         elf_end(linker->elf);
0191 
0192     if (linker->fd >= 0)
0193         close(linker->fd);
0194 
0195     strset__free(linker->strtab_strs);
0196 
0197     btf__free(linker->btf);
0198     btf_ext__free(linker->btf_ext);
0199 
0200     for (i = 1; i < linker->sec_cnt; i++) {
0201         struct dst_sec *sec = &linker->secs[i];
0202 
0203         free(sec->sec_name);
0204         free(sec->raw_data);
0205         free(sec->sec_vars);
0206 
0207         free(sec->func_info.recs);
0208         free(sec->line_info.recs);
0209         free(sec->core_relo_info.recs);
0210     }
0211     free(linker->secs);
0212 
0213     free(linker->glob_syms);
0214     free(linker);
0215 }
0216 
0217 struct bpf_linker *bpf_linker__new(const char *filename, struct bpf_linker_opts *opts)
0218 {
0219     struct bpf_linker *linker;
0220     int err;
0221 
0222     if (!OPTS_VALID(opts, bpf_linker_opts))
0223         return errno = EINVAL, NULL;
0224 
0225     if (elf_version(EV_CURRENT) == EV_NONE) {
0226         pr_warn_elf("libelf initialization failed");
0227         return errno = EINVAL, NULL;
0228     }
0229 
0230     linker = calloc(1, sizeof(*linker));
0231     if (!linker)
0232         return errno = ENOMEM, NULL;
0233 
0234     linker->fd = -1;
0235 
0236     err = init_output_elf(linker, filename);
0237     if (err)
0238         goto err_out;
0239 
0240     return linker;
0241 
0242 err_out:
0243     bpf_linker__free(linker);
0244     return errno = -err, NULL;
0245 }
0246 
0247 static struct dst_sec *add_dst_sec(struct bpf_linker *linker, const char *sec_name)
0248 {
0249     struct dst_sec *secs = linker->secs, *sec;
0250     size_t new_cnt = linker->sec_cnt ? linker->sec_cnt + 1 : 2;
0251 
0252     secs = libbpf_reallocarray(secs, new_cnt, sizeof(*secs));
0253     if (!secs)
0254         return NULL;
0255 
0256     /* zero out newly allocated memory */
0257     memset(secs + linker->sec_cnt, 0, (new_cnt - linker->sec_cnt) * sizeof(*secs));
0258 
0259     linker->secs = secs;
0260     linker->sec_cnt = new_cnt;
0261 
0262     sec = &linker->secs[new_cnt - 1];
0263     sec->id = new_cnt - 1;
0264     sec->sec_name = strdup(sec_name);
0265     if (!sec->sec_name)
0266         return NULL;
0267 
0268     return sec;
0269 }
0270 
0271 static Elf64_Sym *add_new_sym(struct bpf_linker *linker, size_t *sym_idx)
0272 {
0273     struct dst_sec *symtab = &linker->secs[linker->symtab_sec_idx];
0274     Elf64_Sym *syms, *sym;
0275     size_t sym_cnt = symtab->sec_sz / sizeof(*sym);
0276 
0277     syms = libbpf_reallocarray(symtab->raw_data, sym_cnt + 1, sizeof(*sym));
0278     if (!syms)
0279         return NULL;
0280 
0281     sym = &syms[sym_cnt];
0282     memset(sym, 0, sizeof(*sym));
0283 
0284     symtab->raw_data = syms;
0285     symtab->sec_sz += sizeof(*sym);
0286     symtab->shdr->sh_size += sizeof(*sym);
0287     symtab->data->d_size += sizeof(*sym);
0288 
0289     if (sym_idx)
0290         *sym_idx = sym_cnt;
0291 
0292     return sym;
0293 }
0294 
0295 static int init_output_elf(struct bpf_linker *linker, const char *file)
0296 {
0297     int err, str_off;
0298     Elf64_Sym *init_sym;
0299     struct dst_sec *sec;
0300 
0301     linker->filename = strdup(file);
0302     if (!linker->filename)
0303         return -ENOMEM;
0304 
0305     linker->fd = open(file, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
0306     if (linker->fd < 0) {
0307         err = -errno;
0308         pr_warn("failed to create '%s': %d\n", file, err);
0309         return err;
0310     }
0311 
0312     linker->elf = elf_begin(linker->fd, ELF_C_WRITE, NULL);
0313     if (!linker->elf) {
0314         pr_warn_elf("failed to create ELF object");
0315         return -EINVAL;
0316     }
0317 
0318     /* ELF header */
0319     linker->elf_hdr = elf64_newehdr(linker->elf);
0320     if (!linker->elf_hdr) {
0321         pr_warn_elf("failed to create ELF header");
0322         return -EINVAL;
0323     }
0324 
0325     linker->elf_hdr->e_machine = EM_BPF;
0326     linker->elf_hdr->e_type = ET_REL;
0327 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
0328     linker->elf_hdr->e_ident[EI_DATA] = ELFDATA2LSB;
0329 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
0330     linker->elf_hdr->e_ident[EI_DATA] = ELFDATA2MSB;
0331 #else
0332 #error "Unknown __BYTE_ORDER__"
0333 #endif
0334 
0335     /* STRTAB */
0336     /* initialize strset with an empty string to conform to ELF */
0337     linker->strtab_strs = strset__new(INT_MAX, "", sizeof(""));
0338     if (libbpf_get_error(linker->strtab_strs))
0339         return libbpf_get_error(linker->strtab_strs);
0340 
0341     sec = add_dst_sec(linker, ".strtab");
0342     if (!sec)
0343         return -ENOMEM;
0344 
0345     sec->scn = elf_newscn(linker->elf);
0346     if (!sec->scn) {
0347         pr_warn_elf("failed to create STRTAB section");
0348         return -EINVAL;
0349     }
0350 
0351     sec->shdr = elf64_getshdr(sec->scn);
0352     if (!sec->shdr)
0353         return -EINVAL;
0354 
0355     sec->data = elf_newdata(sec->scn);
0356     if (!sec->data) {
0357         pr_warn_elf("failed to create STRTAB data");
0358         return -EINVAL;
0359     }
0360 
0361     str_off = strset__add_str(linker->strtab_strs, sec->sec_name);
0362     if (str_off < 0)
0363         return str_off;
0364 
0365     sec->sec_idx = elf_ndxscn(sec->scn);
0366     linker->elf_hdr->e_shstrndx = sec->sec_idx;
0367     linker->strtab_sec_idx = sec->sec_idx;
0368 
0369     sec->shdr->sh_name = str_off;
0370     sec->shdr->sh_type = SHT_STRTAB;
0371     sec->shdr->sh_flags = SHF_STRINGS;
0372     sec->shdr->sh_offset = 0;
0373     sec->shdr->sh_link = 0;
0374     sec->shdr->sh_info = 0;
0375     sec->shdr->sh_addralign = 1;
0376     sec->shdr->sh_size = sec->sec_sz = 0;
0377     sec->shdr->sh_entsize = 0;
0378 
0379     /* SYMTAB */
0380     sec = add_dst_sec(linker, ".symtab");
0381     if (!sec)
0382         return -ENOMEM;
0383 
0384     sec->scn = elf_newscn(linker->elf);
0385     if (!sec->scn) {
0386         pr_warn_elf("failed to create SYMTAB section");
0387         return -EINVAL;
0388     }
0389 
0390     sec->shdr = elf64_getshdr(sec->scn);
0391     if (!sec->shdr)
0392         return -EINVAL;
0393 
0394     sec->data = elf_newdata(sec->scn);
0395     if (!sec->data) {
0396         pr_warn_elf("failed to create SYMTAB data");
0397         return -EINVAL;
0398     }
0399 
0400     str_off = strset__add_str(linker->strtab_strs, sec->sec_name);
0401     if (str_off < 0)
0402         return str_off;
0403 
0404     sec->sec_idx = elf_ndxscn(sec->scn);
0405     linker->symtab_sec_idx = sec->sec_idx;
0406 
0407     sec->shdr->sh_name = str_off;
0408     sec->shdr->sh_type = SHT_SYMTAB;
0409     sec->shdr->sh_flags = 0;
0410     sec->shdr->sh_offset = 0;
0411     sec->shdr->sh_link = linker->strtab_sec_idx;
0412     /* sh_info should be one greater than the index of the last local
0413      * symbol (i.e., binding is STB_LOCAL). But why and who cares?
0414      */
0415     sec->shdr->sh_info = 0;
0416     sec->shdr->sh_addralign = 8;
0417     sec->shdr->sh_entsize = sizeof(Elf64_Sym);
0418 
0419     /* .BTF */
0420     linker->btf = btf__new_empty();
0421     err = libbpf_get_error(linker->btf);
0422     if (err)
0423         return err;
0424 
0425     /* add the special all-zero symbol */
0426     init_sym = add_new_sym(linker, NULL);
0427     if (!init_sym)
0428         return -EINVAL;
0429 
0430     init_sym->st_name = 0;
0431     init_sym->st_info = 0;
0432     init_sym->st_other = 0;
0433     init_sym->st_shndx = SHN_UNDEF;
0434     init_sym->st_value = 0;
0435     init_sym->st_size = 0;
0436 
0437     return 0;
0438 }
0439 
0440 int bpf_linker__add_file(struct bpf_linker *linker, const char *filename,
0441              const struct bpf_linker_file_opts *opts)
0442 {
0443     struct src_obj obj = {};
0444     int err = 0;
0445 
0446     if (!OPTS_VALID(opts, bpf_linker_file_opts))
0447         return libbpf_err(-EINVAL);
0448 
0449     if (!linker->elf)
0450         return libbpf_err(-EINVAL);
0451 
0452     err = err ?: linker_load_obj_file(linker, filename, opts, &obj);
0453     err = err ?: linker_append_sec_data(linker, &obj);
0454     err = err ?: linker_append_elf_syms(linker, &obj);
0455     err = err ?: linker_append_elf_relos(linker, &obj);
0456     err = err ?: linker_append_btf(linker, &obj);
0457     err = err ?: linker_append_btf_ext(linker, &obj);
0458 
0459     /* free up src_obj resources */
0460     free(obj.btf_type_map);
0461     btf__free(obj.btf);
0462     btf_ext__free(obj.btf_ext);
0463     free(obj.secs);
0464     free(obj.sym_map);
0465     if (obj.elf)
0466         elf_end(obj.elf);
0467     if (obj.fd >= 0)
0468         close(obj.fd);
0469 
0470     return libbpf_err(err);
0471 }
0472 
0473 static bool is_dwarf_sec_name(const char *name)
0474 {
0475     /* approximation, but the actual list is too long */
0476     return strncmp(name, ".debug_", sizeof(".debug_") - 1) == 0;
0477 }
0478 
0479 static bool is_ignored_sec(struct src_sec *sec)
0480 {
0481     Elf64_Shdr *shdr = sec->shdr;
0482     const char *name = sec->sec_name;
0483 
0484     /* no special handling of .strtab */
0485     if (shdr->sh_type == SHT_STRTAB)
0486         return true;
0487 
0488     /* ignore .llvm_addrsig section as well */
0489     if (shdr->sh_type == SHT_LLVM_ADDRSIG)
0490         return true;
0491 
0492     /* no subprograms will lead to an empty .text section, ignore it */
0493     if (shdr->sh_type == SHT_PROGBITS && shdr->sh_size == 0 &&
0494         strcmp(sec->sec_name, ".text") == 0)
0495         return true;
0496 
0497     /* DWARF sections */
0498     if (is_dwarf_sec_name(sec->sec_name))
0499         return true;
0500 
0501     if (strncmp(name, ".rel", sizeof(".rel") - 1) == 0) {
0502         name += sizeof(".rel") - 1;
0503         /* DWARF section relocations */
0504         if (is_dwarf_sec_name(name))
0505             return true;
0506 
0507         /* .BTF and .BTF.ext don't need relocations */
0508         if (strcmp(name, BTF_ELF_SEC) == 0 ||
0509             strcmp(name, BTF_EXT_ELF_SEC) == 0)
0510             return true;
0511     }
0512 
0513     return false;
0514 }
0515 
0516 static struct src_sec *add_src_sec(struct src_obj *obj, const char *sec_name)
0517 {
0518     struct src_sec *secs = obj->secs, *sec;
0519     size_t new_cnt = obj->sec_cnt ? obj->sec_cnt + 1 : 2;
0520 
0521     secs = libbpf_reallocarray(secs, new_cnt, sizeof(*secs));
0522     if (!secs)
0523         return NULL;
0524 
0525     /* zero out newly allocated memory */
0526     memset(secs + obj->sec_cnt, 0, (new_cnt - obj->sec_cnt) * sizeof(*secs));
0527 
0528     obj->secs = secs;
0529     obj->sec_cnt = new_cnt;
0530 
0531     sec = &obj->secs[new_cnt - 1];
0532     sec->id = new_cnt - 1;
0533     sec->sec_name = sec_name;
0534 
0535     return sec;
0536 }
0537 
0538 static int linker_load_obj_file(struct bpf_linker *linker, const char *filename,
0539                 const struct bpf_linker_file_opts *opts,
0540                 struct src_obj *obj)
0541 {
0542 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
0543     const int host_endianness = ELFDATA2LSB;
0544 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
0545     const int host_endianness = ELFDATA2MSB;
0546 #else
0547 #error "Unknown __BYTE_ORDER__"
0548 #endif
0549     int err = 0;
0550     Elf_Scn *scn;
0551     Elf_Data *data;
0552     Elf64_Ehdr *ehdr;
0553     Elf64_Shdr *shdr;
0554     struct src_sec *sec;
0555 
0556     pr_debug("linker: adding object file '%s'...\n", filename);
0557 
0558     obj->filename = filename;
0559 
0560     obj->fd = open(filename, O_RDONLY | O_CLOEXEC);
0561     if (obj->fd < 0) {
0562         err = -errno;
0563         pr_warn("failed to open file '%s': %d\n", filename, err);
0564         return err;
0565     }
0566     obj->elf = elf_begin(obj->fd, ELF_C_READ_MMAP, NULL);
0567     if (!obj->elf) {
0568         err = -errno;
0569         pr_warn_elf("failed to parse ELF file '%s'", filename);
0570         return err;
0571     }
0572 
0573     /* Sanity check ELF file high-level properties */
0574     ehdr = elf64_getehdr(obj->elf);
0575     if (!ehdr) {
0576         err = -errno;
0577         pr_warn_elf("failed to get ELF header for %s", filename);
0578         return err;
0579     }
0580     if (ehdr->e_ident[EI_DATA] != host_endianness) {
0581         err = -EOPNOTSUPP;
0582         pr_warn_elf("unsupported byte order of ELF file %s", filename);
0583         return err;
0584     }
0585     if (ehdr->e_type != ET_REL
0586         || ehdr->e_machine != EM_BPF
0587         || ehdr->e_ident[EI_CLASS] != ELFCLASS64) {
0588         err = -EOPNOTSUPP;
0589         pr_warn_elf("unsupported kind of ELF file %s", filename);
0590         return err;
0591     }
0592 
0593     if (elf_getshdrstrndx(obj->elf, &obj->shstrs_sec_idx)) {
0594         err = -errno;
0595         pr_warn_elf("failed to get SHSTRTAB section index for %s", filename);
0596         return err;
0597     }
0598 
0599     scn = NULL;
0600     while ((scn = elf_nextscn(obj->elf, scn)) != NULL) {
0601         size_t sec_idx = elf_ndxscn(scn);
0602         const char *sec_name;
0603 
0604         shdr = elf64_getshdr(scn);
0605         if (!shdr) {
0606             err = -errno;
0607             pr_warn_elf("failed to get section #%zu header for %s",
0608                     sec_idx, filename);
0609             return err;
0610         }
0611 
0612         sec_name = elf_strptr(obj->elf, obj->shstrs_sec_idx, shdr->sh_name);
0613         if (!sec_name) {
0614             err = -errno;
0615             pr_warn_elf("failed to get section #%zu name for %s",
0616                     sec_idx, filename);
0617             return err;
0618         }
0619 
0620         data = elf_getdata(scn, 0);
0621         if (!data) {
0622             err = -errno;
0623             pr_warn_elf("failed to get section #%zu (%s) data from %s",
0624                     sec_idx, sec_name, filename);
0625             return err;
0626         }
0627 
0628         sec = add_src_sec(obj, sec_name);
0629         if (!sec)
0630             return -ENOMEM;
0631 
0632         sec->scn = scn;
0633         sec->shdr = shdr;
0634         sec->data = data;
0635         sec->sec_idx = elf_ndxscn(scn);
0636 
0637         if (is_ignored_sec(sec)) {
0638             sec->skipped = true;
0639             continue;
0640         }
0641 
0642         switch (shdr->sh_type) {
0643         case SHT_SYMTAB:
0644             if (obj->symtab_sec_idx) {
0645                 err = -EOPNOTSUPP;
0646                 pr_warn("multiple SYMTAB sections found, not supported\n");
0647                 return err;
0648             }
0649             obj->symtab_sec_idx = sec_idx;
0650             break;
0651         case SHT_STRTAB:
0652             /* we'll construct our own string table */
0653             break;
0654         case SHT_PROGBITS:
0655             if (strcmp(sec_name, BTF_ELF_SEC) == 0) {
0656                 obj->btf = btf__new(data->d_buf, shdr->sh_size);
0657                 err = libbpf_get_error(obj->btf);
0658                 if (err) {
0659                     pr_warn("failed to parse .BTF from %s: %d\n", filename, err);
0660                     return err;
0661                 }
0662                 sec->skipped = true;
0663                 continue;
0664             }
0665             if (strcmp(sec_name, BTF_EXT_ELF_SEC) == 0) {
0666                 obj->btf_ext = btf_ext__new(data->d_buf, shdr->sh_size);
0667                 err = libbpf_get_error(obj->btf_ext);
0668                 if (err) {
0669                     pr_warn("failed to parse .BTF.ext from '%s': %d\n", filename, err);
0670                     return err;
0671                 }
0672                 sec->skipped = true;
0673                 continue;
0674             }
0675 
0676             /* data & code */
0677             break;
0678         case SHT_NOBITS:
0679             /* BSS */
0680             break;
0681         case SHT_REL:
0682             /* relocations */
0683             break;
0684         default:
0685             pr_warn("unrecognized section #%zu (%s) in %s\n",
0686                 sec_idx, sec_name, filename);
0687             err = -EINVAL;
0688             return err;
0689         }
0690     }
0691 
0692     err = err ?: linker_sanity_check_elf(obj);
0693     err = err ?: linker_sanity_check_btf(obj);
0694     err = err ?: linker_sanity_check_btf_ext(obj);
0695     err = err ?: linker_fixup_btf(obj);
0696 
0697     return err;
0698 }
0699 
0700 static int linker_sanity_check_elf(struct src_obj *obj)
0701 {
0702     struct src_sec *sec;
0703     int i, err;
0704 
0705     if (!obj->symtab_sec_idx) {
0706         pr_warn("ELF is missing SYMTAB section in %s\n", obj->filename);
0707         return -EINVAL;
0708     }
0709     if (!obj->shstrs_sec_idx) {
0710         pr_warn("ELF is missing section headers STRTAB section in %s\n", obj->filename);
0711         return -EINVAL;
0712     }
0713 
0714     for (i = 1; i < obj->sec_cnt; i++) {
0715         sec = &obj->secs[i];
0716 
0717         if (sec->sec_name[0] == '\0') {
0718             pr_warn("ELF section #%zu has empty name in %s\n", sec->sec_idx, obj->filename);
0719             return -EINVAL;
0720         }
0721 
0722         if (sec->shdr->sh_addralign && !is_pow_of_2(sec->shdr->sh_addralign))
0723             return -EINVAL;
0724         if (sec->shdr->sh_addralign != sec->data->d_align)
0725             return -EINVAL;
0726 
0727         if (sec->shdr->sh_size != sec->data->d_size)
0728             return -EINVAL;
0729 
0730         switch (sec->shdr->sh_type) {
0731         case SHT_SYMTAB:
0732             err = linker_sanity_check_elf_symtab(obj, sec);
0733             if (err)
0734                 return err;
0735             break;
0736         case SHT_STRTAB:
0737             break;
0738         case SHT_PROGBITS:
0739             if (sec->shdr->sh_flags & SHF_EXECINSTR) {
0740                 if (sec->shdr->sh_size % sizeof(struct bpf_insn) != 0)
0741                     return -EINVAL;
0742             }
0743             break;
0744         case SHT_NOBITS:
0745             break;
0746         case SHT_REL:
0747             err = linker_sanity_check_elf_relos(obj, sec);
0748             if (err)
0749                 return err;
0750             break;
0751         case SHT_LLVM_ADDRSIG:
0752             break;
0753         default:
0754             pr_warn("ELF section #%zu (%s) has unrecognized type %zu in %s\n",
0755                 sec->sec_idx, sec->sec_name, (size_t)sec->shdr->sh_type, obj->filename);
0756             return -EINVAL;
0757         }
0758     }
0759 
0760     return 0;
0761 }
0762 
0763 static int linker_sanity_check_elf_symtab(struct src_obj *obj, struct src_sec *sec)
0764 {
0765     struct src_sec *link_sec;
0766     Elf64_Sym *sym;
0767     int i, n;
0768 
0769     if (sec->shdr->sh_entsize != sizeof(Elf64_Sym))
0770         return -EINVAL;
0771     if (sec->shdr->sh_size % sec->shdr->sh_entsize != 0)
0772         return -EINVAL;
0773 
0774     if (!sec->shdr->sh_link || sec->shdr->sh_link >= obj->sec_cnt) {
0775         pr_warn("ELF SYMTAB section #%zu points to missing STRTAB section #%zu in %s\n",
0776             sec->sec_idx, (size_t)sec->shdr->sh_link, obj->filename);
0777         return -EINVAL;
0778     }
0779     link_sec = &obj->secs[sec->shdr->sh_link];
0780     if (link_sec->shdr->sh_type != SHT_STRTAB) {
0781         pr_warn("ELF SYMTAB section #%zu points to invalid STRTAB section #%zu in %s\n",
0782             sec->sec_idx, (size_t)sec->shdr->sh_link, obj->filename);
0783         return -EINVAL;
0784     }
0785 
0786     n = sec->shdr->sh_size / sec->shdr->sh_entsize;
0787     sym = sec->data->d_buf;
0788     for (i = 0; i < n; i++, sym++) {
0789         int sym_type = ELF64_ST_TYPE(sym->st_info);
0790         int sym_bind = ELF64_ST_BIND(sym->st_info);
0791         int sym_vis = ELF64_ST_VISIBILITY(sym->st_other);
0792 
0793         if (i == 0) {
0794             if (sym->st_name != 0 || sym->st_info != 0
0795                 || sym->st_other != 0 || sym->st_shndx != 0
0796                 || sym->st_value != 0 || sym->st_size != 0) {
0797                 pr_warn("ELF sym #0 is invalid in %s\n", obj->filename);
0798                 return -EINVAL;
0799             }
0800             continue;
0801         }
0802         if (sym_bind != STB_LOCAL && sym_bind != STB_GLOBAL && sym_bind != STB_WEAK) {
0803             pr_warn("ELF sym #%d in section #%zu has unsupported symbol binding %d\n",
0804                 i, sec->sec_idx, sym_bind);
0805             return -EINVAL;
0806         }
0807         if (sym_vis != STV_DEFAULT && sym_vis != STV_HIDDEN) {
0808             pr_warn("ELF sym #%d in section #%zu has unsupported symbol visibility %d\n",
0809                 i, sec->sec_idx, sym_vis);
0810             return -EINVAL;
0811         }
0812         if (sym->st_shndx == 0) {
0813             if (sym_type != STT_NOTYPE || sym_bind == STB_LOCAL
0814                 || sym->st_value != 0 || sym->st_size != 0) {
0815                 pr_warn("ELF sym #%d is invalid extern symbol in %s\n",
0816                     i, obj->filename);
0817 
0818                 return -EINVAL;
0819             }
0820             continue;
0821         }
0822         if (sym->st_shndx < SHN_LORESERVE && sym->st_shndx >= obj->sec_cnt) {
0823             pr_warn("ELF sym #%d in section #%zu points to missing section #%zu in %s\n",
0824                 i, sec->sec_idx, (size_t)sym->st_shndx, obj->filename);
0825             return -EINVAL;
0826         }
0827         if (sym_type == STT_SECTION) {
0828             if (sym->st_value != 0)
0829                 return -EINVAL;
0830             continue;
0831         }
0832     }
0833 
0834     return 0;
0835 }
0836 
0837 static int linker_sanity_check_elf_relos(struct src_obj *obj, struct src_sec *sec)
0838 {
0839     struct src_sec *link_sec, *sym_sec;
0840     Elf64_Rel *relo;
0841     int i, n;
0842 
0843     if (sec->shdr->sh_entsize != sizeof(Elf64_Rel))
0844         return -EINVAL;
0845     if (sec->shdr->sh_size % sec->shdr->sh_entsize != 0)
0846         return -EINVAL;
0847 
0848     /* SHT_REL's sh_link should point to SYMTAB */
0849     if (sec->shdr->sh_link != obj->symtab_sec_idx) {
0850         pr_warn("ELF relo section #%zu points to invalid SYMTAB section #%zu in %s\n",
0851             sec->sec_idx, (size_t)sec->shdr->sh_link, obj->filename);
0852         return -EINVAL;
0853     }
0854 
0855     /* SHT_REL's sh_info points to relocated section */
0856     if (!sec->shdr->sh_info || sec->shdr->sh_info >= obj->sec_cnt) {
0857         pr_warn("ELF relo section #%zu points to missing section #%zu in %s\n",
0858             sec->sec_idx, (size_t)sec->shdr->sh_info, obj->filename);
0859         return -EINVAL;
0860     }
0861     link_sec = &obj->secs[sec->shdr->sh_info];
0862 
0863     /* .rel<secname> -> <secname> pattern is followed */
0864     if (strncmp(sec->sec_name, ".rel", sizeof(".rel") - 1) != 0
0865         || strcmp(sec->sec_name + sizeof(".rel") - 1, link_sec->sec_name) != 0) {
0866         pr_warn("ELF relo section #%zu name has invalid name in %s\n",
0867             sec->sec_idx, obj->filename);
0868         return -EINVAL;
0869     }
0870 
0871     /* don't further validate relocations for ignored sections */
0872     if (link_sec->skipped)
0873         return 0;
0874 
0875     /* relocatable section is data or instructions */
0876     if (link_sec->shdr->sh_type != SHT_PROGBITS && link_sec->shdr->sh_type != SHT_NOBITS) {
0877         pr_warn("ELF relo section #%zu points to invalid section #%zu in %s\n",
0878             sec->sec_idx, (size_t)sec->shdr->sh_info, obj->filename);
0879         return -EINVAL;
0880     }
0881 
0882     /* check sanity of each relocation */
0883     n = sec->shdr->sh_size / sec->shdr->sh_entsize;
0884     relo = sec->data->d_buf;
0885     sym_sec = &obj->secs[obj->symtab_sec_idx];
0886     for (i = 0; i < n; i++, relo++) {
0887         size_t sym_idx = ELF64_R_SYM(relo->r_info);
0888         size_t sym_type = ELF64_R_TYPE(relo->r_info);
0889 
0890         if (sym_type != R_BPF_64_64 && sym_type != R_BPF_64_32 &&
0891             sym_type != R_BPF_64_ABS64 && sym_type != R_BPF_64_ABS32) {
0892             pr_warn("ELF relo #%d in section #%zu has unexpected type %zu in %s\n",
0893                 i, sec->sec_idx, sym_type, obj->filename);
0894             return -EINVAL;
0895         }
0896 
0897         if (!sym_idx || sym_idx * sizeof(Elf64_Sym) >= sym_sec->shdr->sh_size) {
0898             pr_warn("ELF relo #%d in section #%zu points to invalid symbol #%zu in %s\n",
0899                 i, sec->sec_idx, sym_idx, obj->filename);
0900             return -EINVAL;
0901         }
0902 
0903         if (link_sec->shdr->sh_flags & SHF_EXECINSTR) {
0904             if (relo->r_offset % sizeof(struct bpf_insn) != 0) {
0905                 pr_warn("ELF relo #%d in section #%zu points to missing symbol #%zu in %s\n",
0906                     i, sec->sec_idx, sym_idx, obj->filename);
0907                 return -EINVAL;
0908             }
0909         }
0910     }
0911 
0912     return 0;
0913 }
0914 
0915 static int check_btf_type_id(__u32 *type_id, void *ctx)
0916 {
0917     struct btf *btf = ctx;
0918 
0919     if (*type_id >= btf__type_cnt(btf))
0920         return -EINVAL;
0921 
0922     return 0;
0923 }
0924 
0925 static int check_btf_str_off(__u32 *str_off, void *ctx)
0926 {
0927     struct btf *btf = ctx;
0928     const char *s;
0929 
0930     s = btf__str_by_offset(btf, *str_off);
0931 
0932     if (!s)
0933         return -EINVAL;
0934 
0935     return 0;
0936 }
0937 
0938 static int linker_sanity_check_btf(struct src_obj *obj)
0939 {
0940     struct btf_type *t;
0941     int i, n, err = 0;
0942 
0943     if (!obj->btf)
0944         return 0;
0945 
0946     n = btf__type_cnt(obj->btf);
0947     for (i = 1; i < n; i++) {
0948         t = btf_type_by_id(obj->btf, i);
0949 
0950         err = err ?: btf_type_visit_type_ids(t, check_btf_type_id, obj->btf);
0951         err = err ?: btf_type_visit_str_offs(t, check_btf_str_off, obj->btf);
0952         if (err)
0953             return err;
0954     }
0955 
0956     return 0;
0957 }
0958 
0959 static int linker_sanity_check_btf_ext(struct src_obj *obj)
0960 {
0961     int err = 0;
0962 
0963     if (!obj->btf_ext)
0964         return 0;
0965 
0966     /* can't use .BTF.ext without .BTF */
0967     if (!obj->btf)
0968         return -EINVAL;
0969 
0970     err = err ?: btf_ext_visit_type_ids(obj->btf_ext, check_btf_type_id, obj->btf);
0971     err = err ?: btf_ext_visit_str_offs(obj->btf_ext, check_btf_str_off, obj->btf);
0972     if (err)
0973         return err;
0974 
0975     return 0;
0976 }
0977 
0978 static int init_sec(struct bpf_linker *linker, struct dst_sec *dst_sec, struct src_sec *src_sec)
0979 {
0980     Elf_Scn *scn;
0981     Elf_Data *data;
0982     Elf64_Shdr *shdr;
0983     int name_off;
0984 
0985     dst_sec->sec_sz = 0;
0986     dst_sec->sec_idx = 0;
0987     dst_sec->ephemeral = src_sec->ephemeral;
0988 
0989     /* ephemeral sections are just thin section shells lacking most parts */
0990     if (src_sec->ephemeral)
0991         return 0;
0992 
0993     scn = elf_newscn(linker->elf);
0994     if (!scn)
0995         return -ENOMEM;
0996     data = elf_newdata(scn);
0997     if (!data)
0998         return -ENOMEM;
0999     shdr = elf64_getshdr(scn);
1000     if (!shdr)
1001         return -ENOMEM;
1002 
1003     dst_sec->scn = scn;
1004     dst_sec->shdr = shdr;
1005     dst_sec->data = data;
1006     dst_sec->sec_idx = elf_ndxscn(scn);
1007 
1008     name_off = strset__add_str(linker->strtab_strs, src_sec->sec_name);
1009     if (name_off < 0)
1010         return name_off;
1011 
1012     shdr->sh_name = name_off;
1013     shdr->sh_type = src_sec->shdr->sh_type;
1014     shdr->sh_flags = src_sec->shdr->sh_flags;
1015     shdr->sh_size = 0;
1016     /* sh_link and sh_info have different meaning for different types of
1017      * sections, so we leave it up to the caller code to fill them in, if
1018      * necessary
1019      */
1020     shdr->sh_link = 0;
1021     shdr->sh_info = 0;
1022     shdr->sh_addralign = src_sec->shdr->sh_addralign;
1023     shdr->sh_entsize = src_sec->shdr->sh_entsize;
1024 
1025     data->d_type = src_sec->data->d_type;
1026     data->d_size = 0;
1027     data->d_buf = NULL;
1028     data->d_align = src_sec->data->d_align;
1029     data->d_off = 0;
1030 
1031     return 0;
1032 }
1033 
1034 static struct dst_sec *find_dst_sec_by_name(struct bpf_linker *linker, const char *sec_name)
1035 {
1036     struct dst_sec *sec;
1037     int i;
1038 
1039     for (i = 1; i < linker->sec_cnt; i++) {
1040         sec = &linker->secs[i];
1041 
1042         if (strcmp(sec->sec_name, sec_name) == 0)
1043             return sec;
1044     }
1045 
1046     return NULL;
1047 }
1048 
1049 static bool secs_match(struct dst_sec *dst, struct src_sec *src)
1050 {
1051     if (dst->ephemeral || src->ephemeral)
1052         return true;
1053 
1054     if (dst->shdr->sh_type != src->shdr->sh_type) {
1055         pr_warn("sec %s types mismatch\n", dst->sec_name);
1056         return false;
1057     }
1058     if (dst->shdr->sh_flags != src->shdr->sh_flags) {
1059         pr_warn("sec %s flags mismatch\n", dst->sec_name);
1060         return false;
1061     }
1062     if (dst->shdr->sh_entsize != src->shdr->sh_entsize) {
1063         pr_warn("sec %s entsize mismatch\n", dst->sec_name);
1064         return false;
1065     }
1066 
1067     return true;
1068 }
1069 
1070 static bool sec_content_is_same(struct dst_sec *dst_sec, struct src_sec *src_sec)
1071 {
1072     if (dst_sec->sec_sz != src_sec->shdr->sh_size)
1073         return false;
1074     if (memcmp(dst_sec->raw_data, src_sec->data->d_buf, dst_sec->sec_sz) != 0)
1075         return false;
1076     return true;
1077 }
1078 
1079 static int extend_sec(struct bpf_linker *linker, struct dst_sec *dst, struct src_sec *src)
1080 {
1081     void *tmp;
1082     size_t dst_align, src_align;
1083     size_t dst_align_sz, dst_final_sz;
1084     int err;
1085 
1086     /* Ephemeral source section doesn't contribute anything to ELF
1087      * section data.
1088      */
1089     if (src->ephemeral)
1090         return 0;
1091 
1092     /* Some sections (like .maps) can contain both externs (and thus be
1093      * ephemeral) and non-externs (map definitions). So it's possible that
1094      * it has to be "upgraded" from ephemeral to non-ephemeral when the
1095      * first non-ephemeral entity appears. In such case, we add ELF
1096      * section, data, etc.
1097      */
1098     if (dst->ephemeral) {
1099         err = init_sec(linker, dst, src);
1100         if (err)
1101             return err;
1102     }
1103 
1104     dst_align = dst->shdr->sh_addralign;
1105     src_align = src->shdr->sh_addralign;
1106     if (dst_align == 0)
1107         dst_align = 1;
1108     if (dst_align < src_align)
1109         dst_align = src_align;
1110 
1111     dst_align_sz = (dst->sec_sz + dst_align - 1) / dst_align * dst_align;
1112 
1113     /* no need to re-align final size */
1114     dst_final_sz = dst_align_sz + src->shdr->sh_size;
1115 
1116     if (src->shdr->sh_type != SHT_NOBITS) {
1117         tmp = realloc(dst->raw_data, dst_final_sz);
1118         if (!tmp)
1119             return -ENOMEM;
1120         dst->raw_data = tmp;
1121 
1122         /* pad dst section, if it's alignment forced size increase */
1123         memset(dst->raw_data + dst->sec_sz, 0, dst_align_sz - dst->sec_sz);
1124         /* now copy src data at a properly aligned offset */
1125         memcpy(dst->raw_data + dst_align_sz, src->data->d_buf, src->shdr->sh_size);
1126     }
1127 
1128     dst->sec_sz = dst_final_sz;
1129     dst->shdr->sh_size = dst_final_sz;
1130     dst->data->d_size = dst_final_sz;
1131 
1132     dst->shdr->sh_addralign = dst_align;
1133     dst->data->d_align = dst_align;
1134 
1135     src->dst_off = dst_align_sz;
1136 
1137     return 0;
1138 }
1139 
1140 static bool is_data_sec(struct src_sec *sec)
1141 {
1142     if (!sec || sec->skipped)
1143         return false;
1144     /* ephemeral sections are data sections, e.g., .kconfig, .ksyms */
1145     if (sec->ephemeral)
1146         return true;
1147     return sec->shdr->sh_type == SHT_PROGBITS || sec->shdr->sh_type == SHT_NOBITS;
1148 }
1149 
1150 static bool is_relo_sec(struct src_sec *sec)
1151 {
1152     if (!sec || sec->skipped || sec->ephemeral)
1153         return false;
1154     return sec->shdr->sh_type == SHT_REL;
1155 }
1156 
1157 static int linker_append_sec_data(struct bpf_linker *linker, struct src_obj *obj)
1158 {
1159     int i, err;
1160 
1161     for (i = 1; i < obj->sec_cnt; i++) {
1162         struct src_sec *src_sec;
1163         struct dst_sec *dst_sec;
1164 
1165         src_sec = &obj->secs[i];
1166         if (!is_data_sec(src_sec))
1167             continue;
1168 
1169         dst_sec = find_dst_sec_by_name(linker, src_sec->sec_name);
1170         if (!dst_sec) {
1171             dst_sec = add_dst_sec(linker, src_sec->sec_name);
1172             if (!dst_sec)
1173                 return -ENOMEM;
1174             err = init_sec(linker, dst_sec, src_sec);
1175             if (err) {
1176                 pr_warn("failed to init section '%s'\n", src_sec->sec_name);
1177                 return err;
1178             }
1179         } else {
1180             if (!secs_match(dst_sec, src_sec)) {
1181                 pr_warn("ELF sections %s are incompatible\n", src_sec->sec_name);
1182                 return -1;
1183             }
1184 
1185             /* "license" and "version" sections are deduped */
1186             if (strcmp(src_sec->sec_name, "license") == 0
1187                 || strcmp(src_sec->sec_name, "version") == 0) {
1188                 if (!sec_content_is_same(dst_sec, src_sec)) {
1189                     pr_warn("non-identical contents of section '%s' are not supported\n", src_sec->sec_name);
1190                     return -EINVAL;
1191                 }
1192                 src_sec->skipped = true;
1193                 src_sec->dst_id = dst_sec->id;
1194                 continue;
1195             }
1196         }
1197 
1198         /* record mapped section index */
1199         src_sec->dst_id = dst_sec->id;
1200 
1201         err = extend_sec(linker, dst_sec, src_sec);
1202         if (err)
1203             return err;
1204     }
1205 
1206     return 0;
1207 }
1208 
1209 static int linker_append_elf_syms(struct bpf_linker *linker, struct src_obj *obj)
1210 {
1211     struct src_sec *symtab = &obj->secs[obj->symtab_sec_idx];
1212     Elf64_Sym *sym = symtab->data->d_buf;
1213     int i, n = symtab->shdr->sh_size / symtab->shdr->sh_entsize, err;
1214     int str_sec_idx = symtab->shdr->sh_link;
1215     const char *sym_name;
1216 
1217     obj->sym_map = calloc(n + 1, sizeof(*obj->sym_map));
1218     if (!obj->sym_map)
1219         return -ENOMEM;
1220 
1221     for (i = 0; i < n; i++, sym++) {
1222         /* We already validated all-zero symbol #0 and we already
1223          * appended it preventively to the final SYMTAB, so skip it.
1224          */
1225         if (i == 0)
1226             continue;
1227 
1228         sym_name = elf_strptr(obj->elf, str_sec_idx, sym->st_name);
1229         if (!sym_name) {
1230             pr_warn("can't fetch symbol name for symbol #%d in '%s'\n", i, obj->filename);
1231             return -EINVAL;
1232         }
1233 
1234         err = linker_append_elf_sym(linker, obj, sym, sym_name, i);
1235         if (err)
1236             return err;
1237     }
1238 
1239     return 0;
1240 }
1241 
1242 static Elf64_Sym *get_sym_by_idx(struct bpf_linker *linker, size_t sym_idx)
1243 {
1244     struct dst_sec *symtab = &linker->secs[linker->symtab_sec_idx];
1245     Elf64_Sym *syms = symtab->raw_data;
1246 
1247     return &syms[sym_idx];
1248 }
1249 
1250 static struct glob_sym *find_glob_sym(struct bpf_linker *linker, const char *sym_name)
1251 {
1252     struct glob_sym *glob_sym;
1253     const char *name;
1254     int i;
1255 
1256     for (i = 0; i < linker->glob_sym_cnt; i++) {
1257         glob_sym = &linker->glob_syms[i];
1258         name = strset__data(linker->strtab_strs) + glob_sym->name_off;
1259 
1260         if (strcmp(name, sym_name) == 0)
1261             return glob_sym;
1262     }
1263 
1264     return NULL;
1265 }
1266 
1267 static struct glob_sym *add_glob_sym(struct bpf_linker *linker)
1268 {
1269     struct glob_sym *syms, *sym;
1270 
1271     syms = libbpf_reallocarray(linker->glob_syms, linker->glob_sym_cnt + 1,
1272                    sizeof(*linker->glob_syms));
1273     if (!syms)
1274         return NULL;
1275 
1276     sym = &syms[linker->glob_sym_cnt];
1277     memset(sym, 0, sizeof(*sym));
1278     sym->var_idx = -1;
1279 
1280     linker->glob_syms = syms;
1281     linker->glob_sym_cnt++;
1282 
1283     return sym;
1284 }
1285 
1286 static bool glob_sym_btf_matches(const char *sym_name, bool exact,
1287                  const struct btf *btf1, __u32 id1,
1288                  const struct btf *btf2, __u32 id2)
1289 {
1290     const struct btf_type *t1, *t2;
1291     bool is_static1, is_static2;
1292     const char *n1, *n2;
1293     int i, n;
1294 
1295 recur:
1296     n1 = n2 = NULL;
1297     t1 = skip_mods_and_typedefs(btf1, id1, &id1);
1298     t2 = skip_mods_and_typedefs(btf2, id2, &id2);
1299 
1300     /* check if only one side is FWD, otherwise handle with common logic */
1301     if (!exact && btf_is_fwd(t1) != btf_is_fwd(t2)) {
1302         n1 = btf__str_by_offset(btf1, t1->name_off);
1303         n2 = btf__str_by_offset(btf2, t2->name_off);
1304         if (strcmp(n1, n2) != 0) {
1305             pr_warn("global '%s': incompatible forward declaration names '%s' and '%s'\n",
1306                 sym_name, n1, n2);
1307             return false;
1308         }
1309         /* validate if FWD kind matches concrete kind */
1310         if (btf_is_fwd(t1)) {
1311             if (btf_kflag(t1) && btf_is_union(t2))
1312                 return true;
1313             if (!btf_kflag(t1) && btf_is_struct(t2))
1314                 return true;
1315             pr_warn("global '%s': incompatible %s forward declaration and concrete kind %s\n",
1316                 sym_name, btf_kflag(t1) ? "union" : "struct", btf_kind_str(t2));
1317         } else {
1318             if (btf_kflag(t2) && btf_is_union(t1))
1319                 return true;
1320             if (!btf_kflag(t2) && btf_is_struct(t1))
1321                 return true;
1322             pr_warn("global '%s': incompatible %s forward declaration and concrete kind %s\n",
1323                 sym_name, btf_kflag(t2) ? "union" : "struct", btf_kind_str(t1));
1324         }
1325         return false;
1326     }
1327 
1328     if (btf_kind(t1) != btf_kind(t2)) {
1329         pr_warn("global '%s': incompatible BTF kinds %s and %s\n",
1330             sym_name, btf_kind_str(t1), btf_kind_str(t2));
1331         return false;
1332     }
1333 
1334     switch (btf_kind(t1)) {
1335     case BTF_KIND_STRUCT:
1336     case BTF_KIND_UNION:
1337     case BTF_KIND_ENUM:
1338     case BTF_KIND_ENUM64:
1339     case BTF_KIND_FWD:
1340     case BTF_KIND_FUNC:
1341     case BTF_KIND_VAR:
1342         n1 = btf__str_by_offset(btf1, t1->name_off);
1343         n2 = btf__str_by_offset(btf2, t2->name_off);
1344         if (strcmp(n1, n2) != 0) {
1345             pr_warn("global '%s': incompatible %s names '%s' and '%s'\n",
1346                 sym_name, btf_kind_str(t1), n1, n2);
1347             return false;
1348         }
1349         break;
1350     default:
1351         break;
1352     }
1353 
1354     switch (btf_kind(t1)) {
1355     case BTF_KIND_UNKN: /* void */
1356     case BTF_KIND_FWD:
1357         return true;
1358     case BTF_KIND_INT:
1359     case BTF_KIND_FLOAT:
1360     case BTF_KIND_ENUM:
1361     case BTF_KIND_ENUM64:
1362         /* ignore encoding for int and enum values for enum */
1363         if (t1->size != t2->size) {
1364             pr_warn("global '%s': incompatible %s '%s' size %u and %u\n",
1365                 sym_name, btf_kind_str(t1), n1, t1->size, t2->size);
1366             return false;
1367         }
1368         return true;
1369     case BTF_KIND_PTR:
1370         /* just validate overall shape of the referenced type, so no
1371          * contents comparison for struct/union, and allowd fwd vs
1372          * struct/union
1373          */
1374         exact = false;
1375         id1 = t1->type;
1376         id2 = t2->type;
1377         goto recur;
1378     case BTF_KIND_ARRAY:
1379         /* ignore index type and array size */
1380         id1 = btf_array(t1)->type;
1381         id2 = btf_array(t2)->type;
1382         goto recur;
1383     case BTF_KIND_FUNC:
1384         /* extern and global linkages are compatible */
1385         is_static1 = btf_func_linkage(t1) == BTF_FUNC_STATIC;
1386         is_static2 = btf_func_linkage(t2) == BTF_FUNC_STATIC;
1387         if (is_static1 != is_static2) {
1388             pr_warn("global '%s': incompatible func '%s' linkage\n", sym_name, n1);
1389             return false;
1390         }
1391 
1392         id1 = t1->type;
1393         id2 = t2->type;
1394         goto recur;
1395     case BTF_KIND_VAR:
1396         /* extern and global linkages are compatible */
1397         is_static1 = btf_var(t1)->linkage == BTF_VAR_STATIC;
1398         is_static2 = btf_var(t2)->linkage == BTF_VAR_STATIC;
1399         if (is_static1 != is_static2) {
1400             pr_warn("global '%s': incompatible var '%s' linkage\n", sym_name, n1);
1401             return false;
1402         }
1403 
1404         id1 = t1->type;
1405         id2 = t2->type;
1406         goto recur;
1407     case BTF_KIND_STRUCT:
1408     case BTF_KIND_UNION: {
1409         const struct btf_member *m1, *m2;
1410 
1411         if (!exact)
1412             return true;
1413 
1414         if (btf_vlen(t1) != btf_vlen(t2)) {
1415             pr_warn("global '%s': incompatible number of %s fields %u and %u\n",
1416                 sym_name, btf_kind_str(t1), btf_vlen(t1), btf_vlen(t2));
1417             return false;
1418         }
1419 
1420         n = btf_vlen(t1);
1421         m1 = btf_members(t1);
1422         m2 = btf_members(t2);
1423         for (i = 0; i < n; i++, m1++, m2++) {
1424             n1 = btf__str_by_offset(btf1, m1->name_off);
1425             n2 = btf__str_by_offset(btf2, m2->name_off);
1426             if (strcmp(n1, n2) != 0) {
1427                 pr_warn("global '%s': incompatible field #%d names '%s' and '%s'\n",
1428                     sym_name, i, n1, n2);
1429                 return false;
1430             }
1431             if (m1->offset != m2->offset) {
1432                 pr_warn("global '%s': incompatible field #%d ('%s') offsets\n",
1433                     sym_name, i, n1);
1434                 return false;
1435             }
1436             if (!glob_sym_btf_matches(sym_name, exact, btf1, m1->type, btf2, m2->type))
1437                 return false;
1438         }
1439 
1440         return true;
1441     }
1442     case BTF_KIND_FUNC_PROTO: {
1443         const struct btf_param *m1, *m2;
1444 
1445         if (btf_vlen(t1) != btf_vlen(t2)) {
1446             pr_warn("global '%s': incompatible number of %s params %u and %u\n",
1447                 sym_name, btf_kind_str(t1), btf_vlen(t1), btf_vlen(t2));
1448             return false;
1449         }
1450 
1451         n = btf_vlen(t1);
1452         m1 = btf_params(t1);
1453         m2 = btf_params(t2);
1454         for (i = 0; i < n; i++, m1++, m2++) {
1455             /* ignore func arg names */
1456             if (!glob_sym_btf_matches(sym_name, exact, btf1, m1->type, btf2, m2->type))
1457                 return false;
1458         }
1459 
1460         /* now check return type as well */
1461         id1 = t1->type;
1462         id2 = t2->type;
1463         goto recur;
1464     }
1465 
1466     /* skip_mods_and_typedefs() make this impossible */
1467     case BTF_KIND_TYPEDEF:
1468     case BTF_KIND_VOLATILE:
1469     case BTF_KIND_CONST:
1470     case BTF_KIND_RESTRICT:
1471     /* DATASECs are never compared with each other */
1472     case BTF_KIND_DATASEC:
1473     default:
1474         pr_warn("global '%s': unsupported BTF kind %s\n",
1475             sym_name, btf_kind_str(t1));
1476         return false;
1477     }
1478 }
1479 
1480 static bool map_defs_match(const char *sym_name,
1481                const struct btf *main_btf,
1482                const struct btf_map_def *main_def,
1483                const struct btf_map_def *main_inner_def,
1484                const struct btf *extra_btf,
1485                const struct btf_map_def *extra_def,
1486                const struct btf_map_def *extra_inner_def)
1487 {
1488     const char *reason;
1489 
1490     if (main_def->map_type != extra_def->map_type) {
1491         reason = "type";
1492         goto mismatch;
1493     }
1494 
1495     /* check key type/size match */
1496     if (main_def->key_size != extra_def->key_size) {
1497         reason = "key_size";
1498         goto mismatch;
1499     }
1500     if (!!main_def->key_type_id != !!extra_def->key_type_id) {
1501         reason = "key type";
1502         goto mismatch;
1503     }
1504     if ((main_def->parts & MAP_DEF_KEY_TYPE)
1505          && !glob_sym_btf_matches(sym_name, true /*exact*/,
1506                       main_btf, main_def->key_type_id,
1507                       extra_btf, extra_def->key_type_id)) {
1508         reason = "key type";
1509         goto mismatch;
1510     }
1511 
1512     /* validate value type/size match */
1513     if (main_def->value_size != extra_def->value_size) {
1514         reason = "value_size";
1515         goto mismatch;
1516     }
1517     if (!!main_def->value_type_id != !!extra_def->value_type_id) {
1518         reason = "value type";
1519         goto mismatch;
1520     }
1521     if ((main_def->parts & MAP_DEF_VALUE_TYPE)
1522          && !glob_sym_btf_matches(sym_name, true /*exact*/,
1523                       main_btf, main_def->value_type_id,
1524                       extra_btf, extra_def->value_type_id)) {
1525         reason = "key type";
1526         goto mismatch;
1527     }
1528 
1529     if (main_def->max_entries != extra_def->max_entries) {
1530         reason = "max_entries";
1531         goto mismatch;
1532     }
1533     if (main_def->map_flags != extra_def->map_flags) {
1534         reason = "map_flags";
1535         goto mismatch;
1536     }
1537     if (main_def->numa_node != extra_def->numa_node) {
1538         reason = "numa_node";
1539         goto mismatch;
1540     }
1541     if (main_def->pinning != extra_def->pinning) {
1542         reason = "pinning";
1543         goto mismatch;
1544     }
1545 
1546     if ((main_def->parts & MAP_DEF_INNER_MAP) != (extra_def->parts & MAP_DEF_INNER_MAP)) {
1547         reason = "inner map";
1548         goto mismatch;
1549     }
1550 
1551     if (main_def->parts & MAP_DEF_INNER_MAP) {
1552         char inner_map_name[128];
1553 
1554         snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", sym_name);
1555 
1556         return map_defs_match(inner_map_name,
1557                       main_btf, main_inner_def, NULL,
1558                       extra_btf, extra_inner_def, NULL);
1559     }
1560 
1561     return true;
1562 
1563 mismatch:
1564     pr_warn("global '%s': map %s mismatch\n", sym_name, reason);
1565     return false;
1566 }
1567 
1568 static bool glob_map_defs_match(const char *sym_name,
1569                 struct bpf_linker *linker, struct glob_sym *glob_sym,
1570                 struct src_obj *obj, Elf64_Sym *sym, int btf_id)
1571 {
1572     struct btf_map_def dst_def = {}, dst_inner_def = {};
1573     struct btf_map_def src_def = {}, src_inner_def = {};
1574     const struct btf_type *t;
1575     int err;
1576 
1577     t = btf__type_by_id(obj->btf, btf_id);
1578     if (!btf_is_var(t)) {
1579         pr_warn("global '%s': invalid map definition type [%d]\n", sym_name, btf_id);
1580         return false;
1581     }
1582     t = skip_mods_and_typedefs(obj->btf, t->type, NULL);
1583 
1584     err = parse_btf_map_def(sym_name, obj->btf, t, true /*strict*/, &src_def, &src_inner_def);
1585     if (err) {
1586         pr_warn("global '%s': invalid map definition\n", sym_name);
1587         return false;
1588     }
1589 
1590     /* re-parse existing map definition */
1591     t = btf__type_by_id(linker->btf, glob_sym->btf_id);
1592     t = skip_mods_and_typedefs(linker->btf, t->type, NULL);
1593     err = parse_btf_map_def(sym_name, linker->btf, t, true /*strict*/, &dst_def, &dst_inner_def);
1594     if (err) {
1595         /* this should not happen, because we already validated it */
1596         pr_warn("global '%s': invalid dst map definition\n", sym_name);
1597         return false;
1598     }
1599 
1600     /* Currently extern map definition has to be complete and match
1601      * concrete map definition exactly. This restriction might be lifted
1602      * in the future.
1603      */
1604     return map_defs_match(sym_name, linker->btf, &dst_def, &dst_inner_def,
1605                   obj->btf, &src_def, &src_inner_def);
1606 }
1607 
1608 static bool glob_syms_match(const char *sym_name,
1609                 struct bpf_linker *linker, struct glob_sym *glob_sym,
1610                 struct src_obj *obj, Elf64_Sym *sym, size_t sym_idx, int btf_id)
1611 {
1612     const struct btf_type *src_t;
1613 
1614     /* if we are dealing with externs, BTF types describing both global
1615      * and extern VARs/FUNCs should be completely present in all files
1616      */
1617     if (!glob_sym->btf_id || !btf_id) {
1618         pr_warn("BTF info is missing for global symbol '%s'\n", sym_name);
1619         return false;
1620     }
1621 
1622     src_t = btf__type_by_id(obj->btf, btf_id);
1623     if (!btf_is_var(src_t) && !btf_is_func(src_t)) {
1624         pr_warn("only extern variables and functions are supported, but got '%s' for '%s'\n",
1625             btf_kind_str(src_t), sym_name);
1626         return false;
1627     }
1628 
1629     /* deal with .maps definitions specially */
1630     if (glob_sym->sec_id && strcmp(linker->secs[glob_sym->sec_id].sec_name, MAPS_ELF_SEC) == 0)
1631         return glob_map_defs_match(sym_name, linker, glob_sym, obj, sym, btf_id);
1632 
1633     if (!glob_sym_btf_matches(sym_name, true /*exact*/,
1634                   linker->btf, glob_sym->btf_id, obj->btf, btf_id))
1635         return false;
1636 
1637     return true;
1638 }
1639 
1640 static bool btf_is_non_static(const struct btf_type *t)
1641 {
1642     return (btf_is_var(t) && btf_var(t)->linkage != BTF_VAR_STATIC)
1643            || (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_STATIC);
1644 }
1645 
1646 static int find_glob_sym_btf(struct src_obj *obj, Elf64_Sym *sym, const char *sym_name,
1647                  int *out_btf_sec_id, int *out_btf_id)
1648 {
1649     int i, j, n, m, btf_id = 0;
1650     const struct btf_type *t;
1651     const struct btf_var_secinfo *vi;
1652     const char *name;
1653 
1654     if (!obj->btf) {
1655         pr_warn("failed to find BTF info for object '%s'\n", obj->filename);
1656         return -EINVAL;
1657     }
1658 
1659     n = btf__type_cnt(obj->btf);
1660     for (i = 1; i < n; i++) {
1661         t = btf__type_by_id(obj->btf, i);
1662 
1663         /* some global and extern FUNCs and VARs might not be associated with any
1664          * DATASEC, so try to detect them in the same pass
1665          */
1666         if (btf_is_non_static(t)) {
1667             name = btf__str_by_offset(obj->btf, t->name_off);
1668             if (strcmp(name, sym_name) != 0)
1669                 continue;
1670 
1671             /* remember and still try to find DATASEC */
1672             btf_id = i;
1673             continue;
1674         }
1675 
1676         if (!btf_is_datasec(t))
1677             continue;
1678 
1679         vi = btf_var_secinfos(t);
1680         for (j = 0, m = btf_vlen(t); j < m; j++, vi++) {
1681             t = btf__type_by_id(obj->btf, vi->type);
1682             name = btf__str_by_offset(obj->btf, t->name_off);
1683 
1684             if (strcmp(name, sym_name) != 0)
1685                 continue;
1686             if (btf_is_var(t) && btf_var(t)->linkage == BTF_VAR_STATIC)
1687                 continue;
1688             if (btf_is_func(t) && btf_func_linkage(t) == BTF_FUNC_STATIC)
1689                 continue;
1690 
1691             if (btf_id && btf_id != vi->type) {
1692                 pr_warn("global/extern '%s' BTF is ambiguous: both types #%d and #%u match\n",
1693                     sym_name, btf_id, vi->type);
1694                 return -EINVAL;
1695             }
1696 
1697             *out_btf_sec_id = i;
1698             *out_btf_id = vi->type;
1699 
1700             return 0;
1701         }
1702     }
1703 
1704     /* free-floating extern or global FUNC */
1705     if (btf_id) {
1706         *out_btf_sec_id = 0;
1707         *out_btf_id = btf_id;
1708         return 0;
1709     }
1710 
1711     pr_warn("failed to find BTF info for global/extern symbol '%s'\n", sym_name);
1712     return -ENOENT;
1713 }
1714 
1715 static struct src_sec *find_src_sec_by_name(struct src_obj *obj, const char *sec_name)
1716 {
1717     struct src_sec *sec;
1718     int i;
1719 
1720     for (i = 1; i < obj->sec_cnt; i++) {
1721         sec = &obj->secs[i];
1722 
1723         if (strcmp(sec->sec_name, sec_name) == 0)
1724             return sec;
1725     }
1726 
1727     return NULL;
1728 }
1729 
1730 static int complete_extern_btf_info(struct btf *dst_btf, int dst_id,
1731                     struct btf *src_btf, int src_id)
1732 {
1733     struct btf_type *dst_t = btf_type_by_id(dst_btf, dst_id);
1734     struct btf_type *src_t = btf_type_by_id(src_btf, src_id);
1735     struct btf_param *src_p, *dst_p;
1736     const char *s;
1737     int i, n, off;
1738 
1739     /* We already made sure that source and destination types (FUNC or
1740      * VAR) match in terms of types and argument names.
1741      */
1742     if (btf_is_var(dst_t)) {
1743         btf_var(dst_t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
1744         return 0;
1745     }
1746 
1747     dst_t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_GLOBAL, 0);
1748 
1749     /* now onto FUNC_PROTO types */
1750     src_t = btf_type_by_id(src_btf, src_t->type);
1751     dst_t = btf_type_by_id(dst_btf, dst_t->type);
1752 
1753     /* Fill in all the argument names, which for extern FUNCs are missing.
1754      * We'll end up with two copies of FUNCs/VARs for externs, but that
1755      * will be taken care of by BTF dedup at the very end.
1756      * It might be that BTF types for extern in one file has less/more BTF
1757      * information (e.g., FWD instead of full STRUCT/UNION information),
1758      * but that should be (in most cases, subject to BTF dedup rules)
1759      * handled and resolved by BTF dedup algorithm as well, so we won't
1760      * worry about it. Our only job is to make sure that argument names
1761      * are populated on both sides, otherwise BTF dedup will pedantically
1762      * consider them different.
1763      */
1764     src_p = btf_params(src_t);
1765     dst_p = btf_params(dst_t);
1766     for (i = 0, n = btf_vlen(dst_t); i < n; i++, src_p++, dst_p++) {
1767         if (!src_p->name_off)
1768             continue;
1769 
1770         /* src_btf has more complete info, so add name to dst_btf */
1771         s = btf__str_by_offset(src_btf, src_p->name_off);
1772         off = btf__add_str(dst_btf, s);
1773         if (off < 0)
1774             return off;
1775         dst_p->name_off = off;
1776     }
1777     return 0;
1778 }
1779 
1780 static void sym_update_bind(Elf64_Sym *sym, int sym_bind)
1781 {
1782     sym->st_info = ELF64_ST_INFO(sym_bind, ELF64_ST_TYPE(sym->st_info));
1783 }
1784 
1785 static void sym_update_type(Elf64_Sym *sym, int sym_type)
1786 {
1787     sym->st_info = ELF64_ST_INFO(ELF64_ST_BIND(sym->st_info), sym_type);
1788 }
1789 
1790 static void sym_update_visibility(Elf64_Sym *sym, int sym_vis)
1791 {
1792     /* libelf doesn't provide setters for ST_VISIBILITY,
1793      * but it is stored in the lower 2 bits of st_other
1794      */
1795     sym->st_other &= ~0x03;
1796     sym->st_other |= sym_vis;
1797 }
1798 
1799 static int linker_append_elf_sym(struct bpf_linker *linker, struct src_obj *obj,
1800                  Elf64_Sym *sym, const char *sym_name, int src_sym_idx)
1801 {
1802     struct src_sec *src_sec = NULL;
1803     struct dst_sec *dst_sec = NULL;
1804     struct glob_sym *glob_sym = NULL;
1805     int name_off, sym_type, sym_bind, sym_vis, err;
1806     int btf_sec_id = 0, btf_id = 0;
1807     size_t dst_sym_idx;
1808     Elf64_Sym *dst_sym;
1809     bool sym_is_extern;
1810 
1811     sym_type = ELF64_ST_TYPE(sym->st_info);
1812     sym_bind = ELF64_ST_BIND(sym->st_info);
1813     sym_vis = ELF64_ST_VISIBILITY(sym->st_other);
1814     sym_is_extern = sym->st_shndx == SHN_UNDEF;
1815 
1816     if (sym_is_extern) {
1817         if (!obj->btf) {
1818             pr_warn("externs without BTF info are not supported\n");
1819             return -ENOTSUP;
1820         }
1821     } else if (sym->st_shndx < SHN_LORESERVE) {
1822         src_sec = &obj->secs[sym->st_shndx];
1823         if (src_sec->skipped)
1824             return 0;
1825         dst_sec = &linker->secs[src_sec->dst_id];
1826 
1827         /* allow only one STT_SECTION symbol per section */
1828         if (sym_type == STT_SECTION && dst_sec->sec_sym_idx) {
1829             obj->sym_map[src_sym_idx] = dst_sec->sec_sym_idx;
1830             return 0;
1831         }
1832     }
1833 
1834     if (sym_bind == STB_LOCAL)
1835         goto add_sym;
1836 
1837     /* find matching BTF info */
1838     err = find_glob_sym_btf(obj, sym, sym_name, &btf_sec_id, &btf_id);
1839     if (err)
1840         return err;
1841 
1842     if (sym_is_extern && btf_sec_id) {
1843         const char *sec_name = NULL;
1844         const struct btf_type *t;
1845 
1846         t = btf__type_by_id(obj->btf, btf_sec_id);
1847         sec_name = btf__str_by_offset(obj->btf, t->name_off);
1848 
1849         /* Clang puts unannotated extern vars into
1850          * '.extern' BTF DATASEC. Treat them the same
1851          * as unannotated extern funcs (which are
1852          * currently not put into any DATASECs).
1853          * Those don't have associated src_sec/dst_sec.
1854          */
1855         if (strcmp(sec_name, BTF_EXTERN_SEC) != 0) {
1856             src_sec = find_src_sec_by_name(obj, sec_name);
1857             if (!src_sec) {
1858                 pr_warn("failed to find matching ELF sec '%s'\n", sec_name);
1859                 return -ENOENT;
1860             }
1861             dst_sec = &linker->secs[src_sec->dst_id];
1862         }
1863     }
1864 
1865     glob_sym = find_glob_sym(linker, sym_name);
1866     if (glob_sym) {
1867         /* Preventively resolve to existing symbol. This is
1868          * needed for further relocation symbol remapping in
1869          * the next step of linking.
1870          */
1871         obj->sym_map[src_sym_idx] = glob_sym->sym_idx;
1872 
1873         /* If both symbols are non-externs, at least one of
1874          * them has to be STB_WEAK, otherwise they are in
1875          * a conflict with each other.
1876          */
1877         if (!sym_is_extern && !glob_sym->is_extern
1878             && !glob_sym->is_weak && sym_bind != STB_WEAK) {
1879             pr_warn("conflicting non-weak symbol #%d (%s) definition in '%s'\n",
1880                 src_sym_idx, sym_name, obj->filename);
1881             return -EINVAL;
1882         }
1883 
1884         if (!glob_syms_match(sym_name, linker, glob_sym, obj, sym, src_sym_idx, btf_id))
1885             return -EINVAL;
1886 
1887         dst_sym = get_sym_by_idx(linker, glob_sym->sym_idx);
1888 
1889         /* If new symbol is strong, then force dst_sym to be strong as
1890          * well; this way a mix of weak and non-weak extern
1891          * definitions will end up being strong.
1892          */
1893         if (sym_bind == STB_GLOBAL) {
1894             /* We still need to preserve type (NOTYPE or
1895              * OBJECT/FUNC, depending on whether the symbol is
1896              * extern or not)
1897              */
1898             sym_update_bind(dst_sym, STB_GLOBAL);
1899             glob_sym->is_weak = false;
1900         }
1901 
1902         /* Non-default visibility is "contaminating", with stricter
1903          * visibility overwriting more permissive ones, even if more
1904          * permissive visibility comes from just an extern definition.
1905          * Currently only STV_DEFAULT and STV_HIDDEN are allowed and
1906          * ensured by ELF symbol sanity checks above.
1907          */
1908         if (sym_vis > ELF64_ST_VISIBILITY(dst_sym->st_other))
1909             sym_update_visibility(dst_sym, sym_vis);
1910 
1911         /* If the new symbol is extern, then regardless if
1912          * existing symbol is extern or resolved global, just
1913          * keep the existing one untouched.
1914          */
1915         if (sym_is_extern)
1916             return 0;
1917 
1918         /* If existing symbol is a strong resolved symbol, bail out,
1919          * because we lost resolution battle have nothing to
1920          * contribute. We already checked abover that there is no
1921          * strong-strong conflict. We also already tightened binding
1922          * and visibility, so nothing else to contribute at that point.
1923          */
1924         if (!glob_sym->is_extern && sym_bind == STB_WEAK)
1925             return 0;
1926 
1927         /* At this point, new symbol is strong non-extern,
1928          * so overwrite glob_sym with new symbol information.
1929          * Preserve binding and visibility.
1930          */
1931         sym_update_type(dst_sym, sym_type);
1932         dst_sym->st_shndx = dst_sec->sec_idx;
1933         dst_sym->st_value = src_sec->dst_off + sym->st_value;
1934         dst_sym->st_size = sym->st_size;
1935 
1936         /* see comment below about dst_sec->id vs dst_sec->sec_idx */
1937         glob_sym->sec_id = dst_sec->id;
1938         glob_sym->is_extern = false;
1939 
1940         if (complete_extern_btf_info(linker->btf, glob_sym->btf_id,
1941                          obj->btf, btf_id))
1942             return -EINVAL;
1943 
1944         /* request updating VAR's/FUNC's underlying BTF type when appending BTF type */
1945         glob_sym->underlying_btf_id = 0;
1946 
1947         obj->sym_map[src_sym_idx] = glob_sym->sym_idx;
1948         return 0;
1949     }
1950 
1951 add_sym:
1952     name_off = strset__add_str(linker->strtab_strs, sym_name);
1953     if (name_off < 0)
1954         return name_off;
1955 
1956     dst_sym = add_new_sym(linker, &dst_sym_idx);
1957     if (!dst_sym)
1958         return -ENOMEM;
1959 
1960     dst_sym->st_name = name_off;
1961     dst_sym->st_info = sym->st_info;
1962     dst_sym->st_other = sym->st_other;
1963     dst_sym->st_shndx = dst_sec ? dst_sec->sec_idx : sym->st_shndx;
1964     dst_sym->st_value = (src_sec ? src_sec->dst_off : 0) + sym->st_value;
1965     dst_sym->st_size = sym->st_size;
1966 
1967     obj->sym_map[src_sym_idx] = dst_sym_idx;
1968 
1969     if (sym_type == STT_SECTION && dst_sym) {
1970         dst_sec->sec_sym_idx = dst_sym_idx;
1971         dst_sym->st_value = 0;
1972     }
1973 
1974     if (sym_bind != STB_LOCAL) {
1975         glob_sym = add_glob_sym(linker);
1976         if (!glob_sym)
1977             return -ENOMEM;
1978 
1979         glob_sym->sym_idx = dst_sym_idx;
1980         /* we use dst_sec->id (and not dst_sec->sec_idx), because
1981          * ephemeral sections (.kconfig, .ksyms, etc) don't have
1982          * sec_idx (as they don't have corresponding ELF section), but
1983          * still have id. .extern doesn't have even ephemeral section
1984          * associated with it, so dst_sec->id == dst_sec->sec_idx == 0.
1985          */
1986         glob_sym->sec_id = dst_sec ? dst_sec->id : 0;
1987         glob_sym->name_off = name_off;
1988         /* we will fill btf_id in during BTF merging step */
1989         glob_sym->btf_id = 0;
1990         glob_sym->is_extern = sym_is_extern;
1991         glob_sym->is_weak = sym_bind == STB_WEAK;
1992     }
1993 
1994     return 0;
1995 }
1996 
1997 static int linker_append_elf_relos(struct bpf_linker *linker, struct src_obj *obj)
1998 {
1999     struct src_sec *src_symtab = &obj->secs[obj->symtab_sec_idx];
2000     struct dst_sec *dst_symtab;
2001     int i, err;
2002 
2003     for (i = 1; i < obj->sec_cnt; i++) {
2004         struct src_sec *src_sec, *src_linked_sec;
2005         struct dst_sec *dst_sec, *dst_linked_sec;
2006         Elf64_Rel *src_rel, *dst_rel;
2007         int j, n;
2008 
2009         src_sec = &obj->secs[i];
2010         if (!is_relo_sec(src_sec))
2011             continue;
2012 
2013         /* shdr->sh_info points to relocatable section */
2014         src_linked_sec = &obj->secs[src_sec->shdr->sh_info];
2015         if (src_linked_sec->skipped)
2016             continue;
2017 
2018         dst_sec = find_dst_sec_by_name(linker, src_sec->sec_name);
2019         if (!dst_sec) {
2020             dst_sec = add_dst_sec(linker, src_sec->sec_name);
2021             if (!dst_sec)
2022                 return -ENOMEM;
2023             err = init_sec(linker, dst_sec, src_sec);
2024             if (err) {
2025                 pr_warn("failed to init section '%s'\n", src_sec->sec_name);
2026                 return err;
2027             }
2028         } else if (!secs_match(dst_sec, src_sec)) {
2029             pr_warn("sections %s are not compatible\n", src_sec->sec_name);
2030             return -1;
2031         }
2032 
2033         /* add_dst_sec() above could have invalidated linker->secs */
2034         dst_symtab = &linker->secs[linker->symtab_sec_idx];
2035 
2036         /* shdr->sh_link points to SYMTAB */
2037         dst_sec->shdr->sh_link = linker->symtab_sec_idx;
2038 
2039         /* shdr->sh_info points to relocated section */
2040         dst_linked_sec = &linker->secs[src_linked_sec->dst_id];
2041         dst_sec->shdr->sh_info = dst_linked_sec->sec_idx;
2042 
2043         src_sec->dst_id = dst_sec->id;
2044         err = extend_sec(linker, dst_sec, src_sec);
2045         if (err)
2046             return err;
2047 
2048         src_rel = src_sec->data->d_buf;
2049         dst_rel = dst_sec->raw_data + src_sec->dst_off;
2050         n = src_sec->shdr->sh_size / src_sec->shdr->sh_entsize;
2051         for (j = 0; j < n; j++, src_rel++, dst_rel++) {
2052             size_t src_sym_idx = ELF64_R_SYM(src_rel->r_info);
2053             size_t sym_type = ELF64_R_TYPE(src_rel->r_info);
2054             Elf64_Sym *src_sym, *dst_sym;
2055             size_t dst_sym_idx;
2056 
2057             src_sym_idx = ELF64_R_SYM(src_rel->r_info);
2058             src_sym = src_symtab->data->d_buf + sizeof(*src_sym) * src_sym_idx;
2059 
2060             dst_sym_idx = obj->sym_map[src_sym_idx];
2061             dst_sym = dst_symtab->raw_data + sizeof(*dst_sym) * dst_sym_idx;
2062             dst_rel->r_offset += src_linked_sec->dst_off;
2063             sym_type = ELF64_R_TYPE(src_rel->r_info);
2064             dst_rel->r_info = ELF64_R_INFO(dst_sym_idx, sym_type);
2065 
2066             if (ELF64_ST_TYPE(src_sym->st_info) == STT_SECTION) {
2067                 struct src_sec *sec = &obj->secs[src_sym->st_shndx];
2068                 struct bpf_insn *insn;
2069 
2070                 if (src_linked_sec->shdr->sh_flags & SHF_EXECINSTR) {
2071                     /* calls to the very first static function inside
2072                      * .text section at offset 0 will
2073                      * reference section symbol, not the
2074                      * function symbol. Fix that up,
2075                      * otherwise it won't be possible to
2076                      * relocate calls to two different
2077                      * static functions with the same name
2078                      * (rom two different object files)
2079                      */
2080                     insn = dst_linked_sec->raw_data + dst_rel->r_offset;
2081                     if (insn->code == (BPF_JMP | BPF_CALL))
2082                         insn->imm += sec->dst_off / sizeof(struct bpf_insn);
2083                     else
2084                         insn->imm += sec->dst_off;
2085                 } else {
2086                     pr_warn("relocation against STT_SECTION in non-exec section is not supported!\n");
2087                     return -EINVAL;
2088                 }
2089             }
2090 
2091         }
2092     }
2093 
2094     return 0;
2095 }
2096 
2097 static Elf64_Sym *find_sym_by_name(struct src_obj *obj, size_t sec_idx,
2098                    int sym_type, const char *sym_name)
2099 {
2100     struct src_sec *symtab = &obj->secs[obj->symtab_sec_idx];
2101     Elf64_Sym *sym = symtab->data->d_buf;
2102     int i, n = symtab->shdr->sh_size / symtab->shdr->sh_entsize;
2103     int str_sec_idx = symtab->shdr->sh_link;
2104     const char *name;
2105 
2106     for (i = 0; i < n; i++, sym++) {
2107         if (sym->st_shndx != sec_idx)
2108             continue;
2109         if (ELF64_ST_TYPE(sym->st_info) != sym_type)
2110             continue;
2111 
2112         name = elf_strptr(obj->elf, str_sec_idx, sym->st_name);
2113         if (!name)
2114             return NULL;
2115 
2116         if (strcmp(sym_name, name) != 0)
2117             continue;
2118 
2119         return sym;
2120     }
2121 
2122     return NULL;
2123 }
2124 
2125 static int linker_fixup_btf(struct src_obj *obj)
2126 {
2127     const char *sec_name;
2128     struct src_sec *sec;
2129     int i, j, n, m;
2130 
2131     if (!obj->btf)
2132         return 0;
2133 
2134     n = btf__type_cnt(obj->btf);
2135     for (i = 1; i < n; i++) {
2136         struct btf_var_secinfo *vi;
2137         struct btf_type *t;
2138 
2139         t = btf_type_by_id(obj->btf, i);
2140         if (btf_kind(t) != BTF_KIND_DATASEC)
2141             continue;
2142 
2143         sec_name = btf__str_by_offset(obj->btf, t->name_off);
2144         sec = find_src_sec_by_name(obj, sec_name);
2145         if (sec) {
2146             /* record actual section size, unless ephemeral */
2147             if (sec->shdr)
2148                 t->size = sec->shdr->sh_size;
2149         } else {
2150             /* BTF can have some sections that are not represented
2151              * in ELF, e.g., .kconfig, .ksyms, .extern, which are used
2152              * for special extern variables.
2153              *
2154              * For all but one such special (ephemeral)
2155              * sections, we pre-create "section shells" to be able
2156              * to keep track of extra per-section metadata later
2157              * (e.g., those BTF extern variables).
2158              *
2159              * .extern is even more special, though, because it
2160              * contains extern variables that need to be resolved
2161              * by static linker, not libbpf and kernel. When such
2162              * externs are resolved, we are going to remove them
2163              * from .extern BTF section and might end up not
2164              * needing it at all. Each resolved extern should have
2165              * matching non-extern VAR/FUNC in other sections.
2166              *
2167              * We do support leaving some of the externs
2168              * unresolved, though, to support cases of building
2169              * libraries, which will later be linked against final
2170              * BPF applications. So if at finalization we still
2171              * see unresolved externs, we'll create .extern
2172              * section on our own.
2173              */
2174             if (strcmp(sec_name, BTF_EXTERN_SEC) == 0)
2175                 continue;
2176 
2177             sec = add_src_sec(obj, sec_name);
2178             if (!sec)
2179                 return -ENOMEM;
2180 
2181             sec->ephemeral = true;
2182             sec->sec_idx = 0; /* will match UNDEF shndx in ELF */
2183         }
2184 
2185         /* remember ELF section and its BTF type ID match */
2186         sec->sec_type_id = i;
2187 
2188         /* fix up variable offsets */
2189         vi = btf_var_secinfos(t);
2190         for (j = 0, m = btf_vlen(t); j < m; j++, vi++) {
2191             const struct btf_type *vt = btf__type_by_id(obj->btf, vi->type);
2192             const char *var_name = btf__str_by_offset(obj->btf, vt->name_off);
2193             int var_linkage = btf_var(vt)->linkage;
2194             Elf64_Sym *sym;
2195 
2196             /* no need to patch up static or extern vars */
2197             if (var_linkage != BTF_VAR_GLOBAL_ALLOCATED)
2198                 continue;
2199 
2200             sym = find_sym_by_name(obj, sec->sec_idx, STT_OBJECT, var_name);
2201             if (!sym) {
2202                 pr_warn("failed to find symbol for variable '%s' in section '%s'\n", var_name, sec_name);
2203                 return -ENOENT;
2204             }
2205 
2206             vi->offset = sym->st_value;
2207         }
2208     }
2209 
2210     return 0;
2211 }
2212 
2213 static int remap_type_id(__u32 *type_id, void *ctx)
2214 {
2215     int *id_map = ctx;
2216     int new_id = id_map[*type_id];
2217 
2218     /* Error out if the type wasn't remapped. Ignore VOID which stays VOID. */
2219     if (new_id == 0 && *type_id != 0) {
2220         pr_warn("failed to find new ID mapping for original BTF type ID %u\n", *type_id);
2221         return -EINVAL;
2222     }
2223 
2224     *type_id = id_map[*type_id];
2225 
2226     return 0;
2227 }
2228 
2229 static int linker_append_btf(struct bpf_linker *linker, struct src_obj *obj)
2230 {
2231     const struct btf_type *t;
2232     int i, j, n, start_id, id;
2233     const char *name;
2234 
2235     if (!obj->btf)
2236         return 0;
2237 
2238     start_id = btf__type_cnt(linker->btf);
2239     n = btf__type_cnt(obj->btf);
2240 
2241     obj->btf_type_map = calloc(n + 1, sizeof(int));
2242     if (!obj->btf_type_map)
2243         return -ENOMEM;
2244 
2245     for (i = 1; i < n; i++) {
2246         struct glob_sym *glob_sym = NULL;
2247 
2248         t = btf__type_by_id(obj->btf, i);
2249 
2250         /* DATASECs are handled specially below */
2251         if (btf_kind(t) == BTF_KIND_DATASEC)
2252             continue;
2253 
2254         if (btf_is_non_static(t)) {
2255             /* there should be glob_sym already */
2256             name = btf__str_by_offset(obj->btf, t->name_off);
2257             glob_sym = find_glob_sym(linker, name);
2258 
2259             /* VARs without corresponding glob_sym are those that
2260              * belong to skipped/deduplicated sections (i.e.,
2261              * license and version), so just skip them
2262              */
2263             if (!glob_sym)
2264                 continue;
2265 
2266             /* linker_append_elf_sym() might have requested
2267              * updating underlying type ID, if extern was resolved
2268              * to strong symbol or weak got upgraded to non-weak
2269              */
2270             if (glob_sym->underlying_btf_id == 0)
2271                 glob_sym->underlying_btf_id = -t->type;
2272 
2273             /* globals from previous object files that match our
2274              * VAR/FUNC already have a corresponding associated
2275              * BTF type, so just make sure to use it
2276              */
2277             if (glob_sym->btf_id) {
2278                 /* reuse existing BTF type for global var/func */
2279                 obj->btf_type_map[i] = glob_sym->btf_id;
2280                 continue;
2281             }
2282         }
2283 
2284         id = btf__add_type(linker->btf, obj->btf, t);
2285         if (id < 0) {
2286             pr_warn("failed to append BTF type #%d from file '%s'\n", i, obj->filename);
2287             return id;
2288         }
2289 
2290         obj->btf_type_map[i] = id;
2291 
2292         /* record just appended BTF type for var/func */
2293         if (glob_sym) {
2294             glob_sym->btf_id = id;
2295             glob_sym->underlying_btf_id = -t->type;
2296         }
2297     }
2298 
2299     /* remap all the types except DATASECs */
2300     n = btf__type_cnt(linker->btf);
2301     for (i = start_id; i < n; i++) {
2302         struct btf_type *dst_t = btf_type_by_id(linker->btf, i);
2303 
2304         if (btf_type_visit_type_ids(dst_t, remap_type_id, obj->btf_type_map))
2305             return -EINVAL;
2306     }
2307 
2308     /* Rewrite VAR/FUNC underlying types (i.e., FUNC's FUNC_PROTO and VAR's
2309      * actual type), if necessary
2310      */
2311     for (i = 0; i < linker->glob_sym_cnt; i++) {
2312         struct glob_sym *glob_sym = &linker->glob_syms[i];
2313         struct btf_type *glob_t;
2314 
2315         if (glob_sym->underlying_btf_id >= 0)
2316             continue;
2317 
2318         glob_sym->underlying_btf_id = obj->btf_type_map[-glob_sym->underlying_btf_id];
2319 
2320         glob_t = btf_type_by_id(linker->btf, glob_sym->btf_id);
2321         glob_t->type = glob_sym->underlying_btf_id;
2322     }
2323 
2324     /* append DATASEC info */
2325     for (i = 1; i < obj->sec_cnt; i++) {
2326         struct src_sec *src_sec;
2327         struct dst_sec *dst_sec;
2328         const struct btf_var_secinfo *src_var;
2329         struct btf_var_secinfo *dst_var;
2330 
2331         src_sec = &obj->secs[i];
2332         if (!src_sec->sec_type_id || src_sec->skipped)
2333             continue;
2334         dst_sec = &linker->secs[src_sec->dst_id];
2335 
2336         /* Mark section as having BTF regardless of the presence of
2337          * variables. In some cases compiler might generate empty BTF
2338          * with no variables information. E.g., when promoting local
2339          * array/structure variable initial values and BPF object
2340          * file otherwise has no read-only static variables in
2341          * .rodata. We need to preserve such empty BTF and just set
2342          * correct section size.
2343          */
2344         dst_sec->has_btf = true;
2345 
2346         t = btf__type_by_id(obj->btf, src_sec->sec_type_id);
2347         src_var = btf_var_secinfos(t);
2348         n = btf_vlen(t);
2349         for (j = 0; j < n; j++, src_var++) {
2350             void *sec_vars = dst_sec->sec_vars;
2351             int new_id = obj->btf_type_map[src_var->type];
2352             struct glob_sym *glob_sym = NULL;
2353 
2354             t = btf_type_by_id(linker->btf, new_id);
2355             if (btf_is_non_static(t)) {
2356                 name = btf__str_by_offset(linker->btf, t->name_off);
2357                 glob_sym = find_glob_sym(linker, name);
2358                 if (glob_sym->sec_id != dst_sec->id) {
2359                     pr_warn("global '%s': section mismatch %d vs %d\n",
2360                         name, glob_sym->sec_id, dst_sec->id);
2361                     return -EINVAL;
2362                 }
2363             }
2364 
2365             /* If there is already a member (VAR or FUNC) mapped
2366              * to the same type, don't add a duplicate entry.
2367              * This will happen when multiple object files define
2368              * the same extern VARs/FUNCs.
2369              */
2370             if (glob_sym && glob_sym->var_idx >= 0) {
2371                 __s64 sz;
2372 
2373                 dst_var = &dst_sec->sec_vars[glob_sym->var_idx];
2374                 /* Because underlying BTF type might have
2375                  * changed, so might its size have changed, so
2376                  * re-calculate and update it in sec_var.
2377                  */
2378                 sz = btf__resolve_size(linker->btf, glob_sym->underlying_btf_id);
2379                 if (sz < 0) {
2380                     pr_warn("global '%s': failed to resolve size of underlying type: %d\n",
2381                         name, (int)sz);
2382                     return -EINVAL;
2383                 }
2384                 dst_var->size = sz;
2385                 continue;
2386             }
2387 
2388             sec_vars = libbpf_reallocarray(sec_vars,
2389                                dst_sec->sec_var_cnt + 1,
2390                                sizeof(*dst_sec->sec_vars));
2391             if (!sec_vars)
2392                 return -ENOMEM;
2393 
2394             dst_sec->sec_vars = sec_vars;
2395             dst_sec->sec_var_cnt++;
2396 
2397             dst_var = &dst_sec->sec_vars[dst_sec->sec_var_cnt - 1];
2398             dst_var->type = obj->btf_type_map[src_var->type];
2399             dst_var->size = src_var->size;
2400             dst_var->offset = src_sec->dst_off + src_var->offset;
2401 
2402             if (glob_sym)
2403                 glob_sym->var_idx = dst_sec->sec_var_cnt - 1;
2404         }
2405     }
2406 
2407     return 0;
2408 }
2409 
2410 static void *add_btf_ext_rec(struct btf_ext_sec_data *ext_data, const void *src_rec)
2411 {
2412     void *tmp;
2413 
2414     tmp = libbpf_reallocarray(ext_data->recs, ext_data->rec_cnt + 1, ext_data->rec_sz);
2415     if (!tmp)
2416         return NULL;
2417     ext_data->recs = tmp;
2418 
2419     tmp += ext_data->rec_cnt * ext_data->rec_sz;
2420     memcpy(tmp, src_rec, ext_data->rec_sz);
2421 
2422     ext_data->rec_cnt++;
2423 
2424     return tmp;
2425 }
2426 
2427 static int linker_append_btf_ext(struct bpf_linker *linker, struct src_obj *obj)
2428 {
2429     const struct btf_ext_info_sec *ext_sec;
2430     const char *sec_name, *s;
2431     struct src_sec *src_sec;
2432     struct dst_sec *dst_sec;
2433     int rec_sz, str_off, i;
2434 
2435     if (!obj->btf_ext)
2436         return 0;
2437 
2438     rec_sz = obj->btf_ext->func_info.rec_size;
2439     for_each_btf_ext_sec(&obj->btf_ext->func_info, ext_sec) {
2440         struct bpf_func_info_min *src_rec, *dst_rec;
2441 
2442         sec_name = btf__name_by_offset(obj->btf, ext_sec->sec_name_off);
2443         src_sec = find_src_sec_by_name(obj, sec_name);
2444         if (!src_sec) {
2445             pr_warn("can't find section '%s' referenced from .BTF.ext\n", sec_name);
2446             return -EINVAL;
2447         }
2448         dst_sec = &linker->secs[src_sec->dst_id];
2449 
2450         if (dst_sec->func_info.rec_sz == 0)
2451             dst_sec->func_info.rec_sz = rec_sz;
2452         if (dst_sec->func_info.rec_sz != rec_sz) {
2453             pr_warn("incompatible .BTF.ext record sizes for section '%s'\n", sec_name);
2454             return -EINVAL;
2455         }
2456 
2457         for_each_btf_ext_rec(&obj->btf_ext->func_info, ext_sec, i, src_rec) {
2458             dst_rec = add_btf_ext_rec(&dst_sec->func_info, src_rec);
2459             if (!dst_rec)
2460                 return -ENOMEM;
2461 
2462             dst_rec->insn_off += src_sec->dst_off;
2463             dst_rec->type_id = obj->btf_type_map[dst_rec->type_id];
2464         }
2465     }
2466 
2467     rec_sz = obj->btf_ext->line_info.rec_size;
2468     for_each_btf_ext_sec(&obj->btf_ext->line_info, ext_sec) {
2469         struct bpf_line_info_min *src_rec, *dst_rec;
2470 
2471         sec_name = btf__name_by_offset(obj->btf, ext_sec->sec_name_off);
2472         src_sec = find_src_sec_by_name(obj, sec_name);
2473         if (!src_sec) {
2474             pr_warn("can't find section '%s' referenced from .BTF.ext\n", sec_name);
2475             return -EINVAL;
2476         }
2477         dst_sec = &linker->secs[src_sec->dst_id];
2478 
2479         if (dst_sec->line_info.rec_sz == 0)
2480             dst_sec->line_info.rec_sz = rec_sz;
2481         if (dst_sec->line_info.rec_sz != rec_sz) {
2482             pr_warn("incompatible .BTF.ext record sizes for section '%s'\n", sec_name);
2483             return -EINVAL;
2484         }
2485 
2486         for_each_btf_ext_rec(&obj->btf_ext->line_info, ext_sec, i, src_rec) {
2487             dst_rec = add_btf_ext_rec(&dst_sec->line_info, src_rec);
2488             if (!dst_rec)
2489                 return -ENOMEM;
2490 
2491             dst_rec->insn_off += src_sec->dst_off;
2492 
2493             s = btf__str_by_offset(obj->btf, src_rec->file_name_off);
2494             str_off = btf__add_str(linker->btf, s);
2495             if (str_off < 0)
2496                 return -ENOMEM;
2497             dst_rec->file_name_off = str_off;
2498 
2499             s = btf__str_by_offset(obj->btf, src_rec->line_off);
2500             str_off = btf__add_str(linker->btf, s);
2501             if (str_off < 0)
2502                 return -ENOMEM;
2503             dst_rec->line_off = str_off;
2504 
2505             /* dst_rec->line_col is fine */
2506         }
2507     }
2508 
2509     rec_sz = obj->btf_ext->core_relo_info.rec_size;
2510     for_each_btf_ext_sec(&obj->btf_ext->core_relo_info, ext_sec) {
2511         struct bpf_core_relo *src_rec, *dst_rec;
2512 
2513         sec_name = btf__name_by_offset(obj->btf, ext_sec->sec_name_off);
2514         src_sec = find_src_sec_by_name(obj, sec_name);
2515         if (!src_sec) {
2516             pr_warn("can't find section '%s' referenced from .BTF.ext\n", sec_name);
2517             return -EINVAL;
2518         }
2519         dst_sec = &linker->secs[src_sec->dst_id];
2520 
2521         if (dst_sec->core_relo_info.rec_sz == 0)
2522             dst_sec->core_relo_info.rec_sz = rec_sz;
2523         if (dst_sec->core_relo_info.rec_sz != rec_sz) {
2524             pr_warn("incompatible .BTF.ext record sizes for section '%s'\n", sec_name);
2525             return -EINVAL;
2526         }
2527 
2528         for_each_btf_ext_rec(&obj->btf_ext->core_relo_info, ext_sec, i, src_rec) {
2529             dst_rec = add_btf_ext_rec(&dst_sec->core_relo_info, src_rec);
2530             if (!dst_rec)
2531                 return -ENOMEM;
2532 
2533             dst_rec->insn_off += src_sec->dst_off;
2534             dst_rec->type_id = obj->btf_type_map[dst_rec->type_id];
2535 
2536             s = btf__str_by_offset(obj->btf, src_rec->access_str_off);
2537             str_off = btf__add_str(linker->btf, s);
2538             if (str_off < 0)
2539                 return -ENOMEM;
2540             dst_rec->access_str_off = str_off;
2541 
2542             /* dst_rec->kind is fine */
2543         }
2544     }
2545 
2546     return 0;
2547 }
2548 
2549 int bpf_linker__finalize(struct bpf_linker *linker)
2550 {
2551     struct dst_sec *sec;
2552     size_t strs_sz;
2553     const void *strs;
2554     int err, i;
2555 
2556     if (!linker->elf)
2557         return libbpf_err(-EINVAL);
2558 
2559     err = finalize_btf(linker);
2560     if (err)
2561         return libbpf_err(err);
2562 
2563     /* Finalize strings */
2564     strs_sz = strset__data_size(linker->strtab_strs);
2565     strs = strset__data(linker->strtab_strs);
2566 
2567     sec = &linker->secs[linker->strtab_sec_idx];
2568     sec->data->d_align = 1;
2569     sec->data->d_off = 0LL;
2570     sec->data->d_buf = (void *)strs;
2571     sec->data->d_type = ELF_T_BYTE;
2572     sec->data->d_size = strs_sz;
2573     sec->shdr->sh_size = strs_sz;
2574 
2575     for (i = 1; i < linker->sec_cnt; i++) {
2576         sec = &linker->secs[i];
2577 
2578         /* STRTAB is handled specially above */
2579         if (sec->sec_idx == linker->strtab_sec_idx)
2580             continue;
2581 
2582         /* special ephemeral sections (.ksyms, .kconfig, etc) */
2583         if (!sec->scn)
2584             continue;
2585 
2586         sec->data->d_buf = sec->raw_data;
2587     }
2588 
2589     /* Finalize ELF layout */
2590     if (elf_update(linker->elf, ELF_C_NULL) < 0) {
2591         err = -errno;
2592         pr_warn_elf("failed to finalize ELF layout");
2593         return libbpf_err(err);
2594     }
2595 
2596     /* Write out final ELF contents */
2597     if (elf_update(linker->elf, ELF_C_WRITE) < 0) {
2598         err = -errno;
2599         pr_warn_elf("failed to write ELF contents");
2600         return libbpf_err(err);
2601     }
2602 
2603     elf_end(linker->elf);
2604     close(linker->fd);
2605 
2606     linker->elf = NULL;
2607     linker->fd = -1;
2608 
2609     return 0;
2610 }
2611 
2612 static int emit_elf_data_sec(struct bpf_linker *linker, const char *sec_name,
2613                  size_t align, const void *raw_data, size_t raw_sz)
2614 {
2615     Elf_Scn *scn;
2616     Elf_Data *data;
2617     Elf64_Shdr *shdr;
2618     int name_off;
2619 
2620     name_off = strset__add_str(linker->strtab_strs, sec_name);
2621     if (name_off < 0)
2622         return name_off;
2623 
2624     scn = elf_newscn(linker->elf);
2625     if (!scn)
2626         return -ENOMEM;
2627     data = elf_newdata(scn);
2628     if (!data)
2629         return -ENOMEM;
2630     shdr = elf64_getshdr(scn);
2631     if (!shdr)
2632         return -EINVAL;
2633 
2634     shdr->sh_name = name_off;
2635     shdr->sh_type = SHT_PROGBITS;
2636     shdr->sh_flags = 0;
2637     shdr->sh_size = raw_sz;
2638     shdr->sh_link = 0;
2639     shdr->sh_info = 0;
2640     shdr->sh_addralign = align;
2641     shdr->sh_entsize = 0;
2642 
2643     data->d_type = ELF_T_BYTE;
2644     data->d_size = raw_sz;
2645     data->d_buf = (void *)raw_data;
2646     data->d_align = align;
2647     data->d_off = 0;
2648 
2649     return 0;
2650 }
2651 
2652 static int finalize_btf(struct bpf_linker *linker)
2653 {
2654     LIBBPF_OPTS(btf_dedup_opts, opts);
2655     struct btf *btf = linker->btf;
2656     const void *raw_data;
2657     int i, j, id, err;
2658     __u32 raw_sz;
2659 
2660     /* bail out if no BTF data was produced */
2661     if (btf__type_cnt(linker->btf) == 1)
2662         return 0;
2663 
2664     for (i = 1; i < linker->sec_cnt; i++) {
2665         struct dst_sec *sec = &linker->secs[i];
2666 
2667         if (!sec->has_btf)
2668             continue;
2669 
2670         id = btf__add_datasec(btf, sec->sec_name, sec->sec_sz);
2671         if (id < 0) {
2672             pr_warn("failed to add consolidated BTF type for datasec '%s': %d\n",
2673                 sec->sec_name, id);
2674             return id;
2675         }
2676 
2677         for (j = 0; j < sec->sec_var_cnt; j++) {
2678             struct btf_var_secinfo *vi = &sec->sec_vars[j];
2679 
2680             if (btf__add_datasec_var_info(btf, vi->type, vi->offset, vi->size))
2681                 return -EINVAL;
2682         }
2683     }
2684 
2685     err = finalize_btf_ext(linker);
2686     if (err) {
2687         pr_warn(".BTF.ext generation failed: %d\n", err);
2688         return err;
2689     }
2690 
2691     opts.btf_ext = linker->btf_ext;
2692     err = btf__dedup(linker->btf, &opts);
2693     if (err) {
2694         pr_warn("BTF dedup failed: %d\n", err);
2695         return err;
2696     }
2697 
2698     /* Emit .BTF section */
2699     raw_data = btf__raw_data(linker->btf, &raw_sz);
2700     if (!raw_data)
2701         return -ENOMEM;
2702 
2703     err = emit_elf_data_sec(linker, BTF_ELF_SEC, 8, raw_data, raw_sz);
2704     if (err) {
2705         pr_warn("failed to write out .BTF ELF section: %d\n", err);
2706         return err;
2707     }
2708 
2709     /* Emit .BTF.ext section */
2710     if (linker->btf_ext) {
2711         raw_data = btf_ext__get_raw_data(linker->btf_ext, &raw_sz);
2712         if (!raw_data)
2713             return -ENOMEM;
2714 
2715         err = emit_elf_data_sec(linker, BTF_EXT_ELF_SEC, 8, raw_data, raw_sz);
2716         if (err) {
2717             pr_warn("failed to write out .BTF.ext ELF section: %d\n", err);
2718             return err;
2719         }
2720     }
2721 
2722     return 0;
2723 }
2724 
2725 static int emit_btf_ext_data(struct bpf_linker *linker, void *output,
2726                  const char *sec_name, struct btf_ext_sec_data *sec_data)
2727 {
2728     struct btf_ext_info_sec *sec_info;
2729     void *cur = output;
2730     int str_off;
2731     size_t sz;
2732 
2733     if (!sec_data->rec_cnt)
2734         return 0;
2735 
2736     str_off = btf__add_str(linker->btf, sec_name);
2737     if (str_off < 0)
2738         return -ENOMEM;
2739 
2740     sec_info = cur;
2741     sec_info->sec_name_off = str_off;
2742     sec_info->num_info = sec_data->rec_cnt;
2743     cur += sizeof(struct btf_ext_info_sec);
2744 
2745     sz = sec_data->rec_cnt * sec_data->rec_sz;
2746     memcpy(cur, sec_data->recs, sz);
2747     cur += sz;
2748 
2749     return cur - output;
2750 }
2751 
2752 static int finalize_btf_ext(struct bpf_linker *linker)
2753 {
2754     size_t funcs_sz = 0, lines_sz = 0, core_relos_sz = 0, total_sz = 0;
2755     size_t func_rec_sz = 0, line_rec_sz = 0, core_relo_rec_sz = 0;
2756     struct btf_ext_header *hdr;
2757     void *data, *cur;
2758     int i, err, sz;
2759 
2760     /* validate that all sections have the same .BTF.ext record sizes
2761      * and calculate total data size for each type of data (func info,
2762      * line info, core relos)
2763      */
2764     for (i = 1; i < linker->sec_cnt; i++) {
2765         struct dst_sec *sec = &linker->secs[i];
2766 
2767         if (sec->func_info.rec_cnt) {
2768             if (func_rec_sz == 0)
2769                 func_rec_sz = sec->func_info.rec_sz;
2770             if (func_rec_sz != sec->func_info.rec_sz) {
2771                 pr_warn("mismatch in func_info record size %zu != %u\n",
2772                     func_rec_sz, sec->func_info.rec_sz);
2773                 return -EINVAL;
2774             }
2775 
2776             funcs_sz += sizeof(struct btf_ext_info_sec) + func_rec_sz * sec->func_info.rec_cnt;
2777         }
2778         if (sec->line_info.rec_cnt) {
2779             if (line_rec_sz == 0)
2780                 line_rec_sz = sec->line_info.rec_sz;
2781             if (line_rec_sz != sec->line_info.rec_sz) {
2782                 pr_warn("mismatch in line_info record size %zu != %u\n",
2783                     line_rec_sz, sec->line_info.rec_sz);
2784                 return -EINVAL;
2785             }
2786 
2787             lines_sz += sizeof(struct btf_ext_info_sec) + line_rec_sz * sec->line_info.rec_cnt;
2788         }
2789         if (sec->core_relo_info.rec_cnt) {
2790             if (core_relo_rec_sz == 0)
2791                 core_relo_rec_sz = sec->core_relo_info.rec_sz;
2792             if (core_relo_rec_sz != sec->core_relo_info.rec_sz) {
2793                 pr_warn("mismatch in core_relo_info record size %zu != %u\n",
2794                     core_relo_rec_sz, sec->core_relo_info.rec_sz);
2795                 return -EINVAL;
2796             }
2797 
2798             core_relos_sz += sizeof(struct btf_ext_info_sec) + core_relo_rec_sz * sec->core_relo_info.rec_cnt;
2799         }
2800     }
2801 
2802     if (!funcs_sz && !lines_sz && !core_relos_sz)
2803         return 0;
2804 
2805     total_sz += sizeof(struct btf_ext_header);
2806     if (funcs_sz) {
2807         funcs_sz += sizeof(__u32); /* record size prefix */
2808         total_sz += funcs_sz;
2809     }
2810     if (lines_sz) {
2811         lines_sz += sizeof(__u32); /* record size prefix */
2812         total_sz += lines_sz;
2813     }
2814     if (core_relos_sz) {
2815         core_relos_sz += sizeof(__u32); /* record size prefix */
2816         total_sz += core_relos_sz;
2817     }
2818 
2819     cur = data = calloc(1, total_sz);
2820     if (!data)
2821         return -ENOMEM;
2822 
2823     hdr = cur;
2824     hdr->magic = BTF_MAGIC;
2825     hdr->version = BTF_VERSION;
2826     hdr->flags = 0;
2827     hdr->hdr_len = sizeof(struct btf_ext_header);
2828     cur += sizeof(struct btf_ext_header);
2829 
2830     /* All offsets are in bytes relative to the end of this header */
2831     hdr->func_info_off = 0;
2832     hdr->func_info_len = funcs_sz;
2833     hdr->line_info_off = funcs_sz;
2834     hdr->line_info_len = lines_sz;
2835     hdr->core_relo_off = funcs_sz + lines_sz;
2836     hdr->core_relo_len = core_relos_sz;
2837 
2838     if (funcs_sz) {
2839         *(__u32 *)cur = func_rec_sz;
2840         cur += sizeof(__u32);
2841 
2842         for (i = 1; i < linker->sec_cnt; i++) {
2843             struct dst_sec *sec = &linker->secs[i];
2844 
2845             sz = emit_btf_ext_data(linker, cur, sec->sec_name, &sec->func_info);
2846             if (sz < 0) {
2847                 err = sz;
2848                 goto out;
2849             }
2850 
2851             cur += sz;
2852         }
2853     }
2854 
2855     if (lines_sz) {
2856         *(__u32 *)cur = line_rec_sz;
2857         cur += sizeof(__u32);
2858 
2859         for (i = 1; i < linker->sec_cnt; i++) {
2860             struct dst_sec *sec = &linker->secs[i];
2861 
2862             sz = emit_btf_ext_data(linker, cur, sec->sec_name, &sec->line_info);
2863             if (sz < 0) {
2864                 err = sz;
2865                 goto out;
2866             }
2867 
2868             cur += sz;
2869         }
2870     }
2871 
2872     if (core_relos_sz) {
2873         *(__u32 *)cur = core_relo_rec_sz;
2874         cur += sizeof(__u32);
2875 
2876         for (i = 1; i < linker->sec_cnt; i++) {
2877             struct dst_sec *sec = &linker->secs[i];
2878 
2879             sz = emit_btf_ext_data(linker, cur, sec->sec_name, &sec->core_relo_info);
2880             if (sz < 0) {
2881                 err = sz;
2882                 goto out;
2883             }
2884 
2885             cur += sz;
2886         }
2887     }
2888 
2889     linker->btf_ext = btf_ext__new(data, total_sz);
2890     err = libbpf_get_error(linker->btf_ext);
2891     if (err) {
2892         linker->btf_ext = NULL;
2893         pr_warn("failed to parse final .BTF.ext data: %d\n", err);
2894         goto out;
2895     }
2896 
2897 out:
2898     free(data);
2899     return err;
2900 }