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