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