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