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