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