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