xref: /linux/tools/bpf/bpftool/gen.c (revision 5763790965eb3414148720f030b20fd5ccc438ca)
1 // SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
2 /* Copyright (C) 2019 Facebook */
3 
4 #ifndef _GNU_SOURCE
5 #define _GNU_SOURCE
6 #endif
7 #include <ctype.h>
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <libgen.h>
11 #include <linux/err.h>
12 #include <stdbool.h>
13 #include <stdio.h>
14 #include <string.h>
15 #include <unistd.h>
16 #include <bpf/bpf.h>
17 #include <bpf/libbpf.h>
18 #include <bpf/libbpf_internal.h>
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <sys/mman.h>
22 #include <bpf/btf.h>
23 
24 #include "json_writer.h"
25 #include "main.h"
26 
27 #define MAX_OBJ_NAME_LEN 64
28 
29 static void sanitize_identifier(char *name)
30 {
31 	int i;
32 
33 	for (i = 0; name[i]; i++)
34 		if (!isalnum(name[i]) && name[i] != '_')
35 			name[i] = '_';
36 }
37 
38 static bool str_has_prefix(const char *str, const char *prefix)
39 {
40 	return strncmp(str, prefix, strlen(prefix)) == 0;
41 }
42 
43 static bool str_has_suffix(const char *str, const char *suffix)
44 {
45 	size_t i, n1 = strlen(str), n2 = strlen(suffix);
46 
47 	if (n1 < n2)
48 		return false;
49 
50 	for (i = 0; i < n2; i++) {
51 		if (str[n1 - i - 1] != suffix[n2 - i - 1])
52 			return false;
53 	}
54 
55 	return true;
56 }
57 
58 static const struct btf_type *
59 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
60 {
61 	const struct btf_type *t;
62 
63 	t = skip_mods_and_typedefs(btf, id, NULL);
64 	if (!btf_is_ptr(t))
65 		return NULL;
66 
67 	t = skip_mods_and_typedefs(btf, t->type, res_id);
68 
69 	return btf_is_func_proto(t) ? t : NULL;
70 }
71 
72 static void get_obj_name(char *name, const char *file)
73 {
74 	char file_copy[PATH_MAX];
75 
76 	/* Using basename() POSIX version to be more portable. */
77 	strncpy(file_copy, file, PATH_MAX - 1)[PATH_MAX - 1] = '\0';
78 	strncpy(name, basename(file_copy), MAX_OBJ_NAME_LEN - 1)[MAX_OBJ_NAME_LEN - 1] = '\0';
79 	if (str_has_suffix(name, ".o"))
80 		name[strlen(name) - 2] = '\0';
81 	sanitize_identifier(name);
82 }
83 
84 static void get_header_guard(char *guard, const char *obj_name, const char *suffix)
85 {
86 	int i;
87 
88 	sprintf(guard, "__%s_%s__", obj_name, suffix);
89 	for (i = 0; guard[i]; i++)
90 		guard[i] = toupper(guard[i]);
91 }
92 
93 static bool get_map_ident(const struct bpf_map *map, char *buf, size_t buf_sz)
94 {
95 	static const char *sfxs[] = { ".data", ".rodata", ".bss", ".kconfig" };
96 	const char *name = bpf_map__name(map);
97 	int i, n;
98 
99 	if (!bpf_map__is_internal(map)) {
100 		snprintf(buf, buf_sz, "%s", name);
101 		return true;
102 	}
103 
104 	for  (i = 0, n = ARRAY_SIZE(sfxs); i < n; i++) {
105 		const char *sfx = sfxs[i], *p;
106 
107 		p = strstr(name, sfx);
108 		if (p) {
109 			snprintf(buf, buf_sz, "%s", p + 1);
110 			sanitize_identifier(buf);
111 			return true;
112 		}
113 	}
114 
115 	return false;
116 }
117 
118 static bool get_datasec_ident(const char *sec_name, char *buf, size_t buf_sz)
119 {
120 	static const char *pfxs[] = { ".data", ".rodata", ".bss", ".kconfig" };
121 	int i, n;
122 
123 	/* recognize hard coded LLVM section name */
124 	if (strcmp(sec_name, ".addr_space.1") == 0) {
125 		/* this is the name to use in skeleton */
126 		snprintf(buf, buf_sz, "arena");
127 		return true;
128 	}
129 	for  (i = 0, n = ARRAY_SIZE(pfxs); i < n; i++) {
130 		const char *pfx = pfxs[i];
131 
132 		if (str_has_prefix(sec_name, pfx)) {
133 			snprintf(buf, buf_sz, "%s", sec_name + 1);
134 			sanitize_identifier(buf);
135 			return true;
136 		}
137 	}
138 
139 	return false;
140 }
141 
142 static void codegen_btf_dump_printf(void *ctx, const char *fmt, va_list args)
143 {
144 	vprintf(fmt, args);
145 }
146 
147 static int codegen_datasec_def(struct bpf_object *obj,
148 			       struct btf *btf,
149 			       struct btf_dump *d,
150 			       const struct btf_type *sec,
151 			       const char *obj_name)
152 {
153 	const char *sec_name = btf__name_by_offset(btf, sec->name_off);
154 	const struct btf_var_secinfo *sec_var = btf_var_secinfos(sec);
155 	int i, err, off = 0, pad_cnt = 0, vlen = btf_vlen(sec);
156 	char var_ident[256], sec_ident[256];
157 	bool strip_mods = false;
158 
159 	if (!get_datasec_ident(sec_name, sec_ident, sizeof(sec_ident)))
160 		return 0;
161 
162 	if (strcmp(sec_name, ".kconfig") != 0)
163 		strip_mods = true;
164 
165 	printf("	struct %s__%s {\n", obj_name, sec_ident);
166 	for (i = 0; i < vlen; i++, sec_var++) {
167 		const struct btf_type *var = btf__type_by_id(btf, sec_var->type);
168 		const char *var_name = btf__name_by_offset(btf, var->name_off);
169 		DECLARE_LIBBPF_OPTS(btf_dump_emit_type_decl_opts, opts,
170 			.field_name = var_ident,
171 			.indent_level = 2,
172 			.strip_mods = strip_mods,
173 		);
174 		int need_off = sec_var->offset, align_off, align;
175 		__u32 var_type_id = var->type;
176 
177 		/* static variables are not exposed through BPF skeleton */
178 		if (btf_var(var)->linkage == BTF_VAR_STATIC)
179 			continue;
180 
181 		if (off > need_off) {
182 			p_err("Something is wrong for %s's variable #%d: need offset %d, already at %d.\n",
183 			      sec_name, i, need_off, off);
184 			return -EINVAL;
185 		}
186 
187 		align = btf__align_of(btf, var->type);
188 		if (align <= 0) {
189 			p_err("Failed to determine alignment of variable '%s': %d",
190 			      var_name, align);
191 			return -EINVAL;
192 		}
193 		/* Assume 32-bit architectures when generating data section
194 		 * struct memory layout. Given bpftool can't know which target
195 		 * host architecture it's emitting skeleton for, we need to be
196 		 * conservative and assume 32-bit one to ensure enough padding
197 		 * bytes are generated for pointer and long types. This will
198 		 * still work correctly for 64-bit architectures, because in
199 		 * the worst case we'll generate unnecessary padding field,
200 		 * which on 64-bit architectures is not strictly necessary and
201 		 * would be handled by natural 8-byte alignment. But it still
202 		 * will be a correct memory layout, based on recorded offsets
203 		 * in BTF.
204 		 */
205 		if (align > 4)
206 			align = 4;
207 
208 		align_off = (off + align - 1) / align * align;
209 		if (align_off != need_off) {
210 			printf("\t\tchar __pad%d[%d];\n",
211 			       pad_cnt, need_off - off);
212 			pad_cnt++;
213 		}
214 
215 		/* sanitize variable name, e.g., for static vars inside
216 		 * a function, it's name is '<function name>.<variable name>',
217 		 * which we'll turn into a '<function name>_<variable name>'
218 		 */
219 		var_ident[0] = '\0';
220 		strncat(var_ident, var_name, sizeof(var_ident) - 1);
221 		sanitize_identifier(var_ident);
222 
223 		printf("\t\t");
224 		err = btf_dump__emit_type_decl(d, var_type_id, &opts);
225 		if (err)
226 			return err;
227 		printf(";\n");
228 
229 		off = sec_var->offset + sec_var->size;
230 	}
231 	printf("	} *%s;\n", sec_ident);
232 	return 0;
233 }
234 
235 static const struct btf_type *find_type_for_map(struct btf *btf, const char *map_ident)
236 {
237 	int n = btf__type_cnt(btf), i;
238 	char sec_ident[256];
239 
240 	for (i = 1; i < n; i++) {
241 		const struct btf_type *t = btf__type_by_id(btf, i);
242 		const char *name;
243 
244 		if (!btf_is_datasec(t))
245 			continue;
246 
247 		name = btf__str_by_offset(btf, t->name_off);
248 		if (!get_datasec_ident(name, sec_ident, sizeof(sec_ident)))
249 			continue;
250 
251 		if (strcmp(sec_ident, map_ident) == 0)
252 			return t;
253 	}
254 	return NULL;
255 }
256 
257 static bool is_mmapable_map(const struct bpf_map *map, char *buf, size_t sz)
258 {
259 	size_t tmp_sz;
260 
261 	if (bpf_map__type(map) == BPF_MAP_TYPE_ARENA && bpf_map__initial_value(map, &tmp_sz)) {
262 		snprintf(buf, sz, "arena");
263 		return true;
264 	}
265 
266 	if (!bpf_map__is_internal(map) || !(bpf_map__map_flags(map) & BPF_F_MMAPABLE))
267 		return false;
268 
269 	if (!get_map_ident(map, buf, sz))
270 		return false;
271 
272 	return true;
273 }
274 
275 static int codegen_datasecs(struct bpf_object *obj, const char *obj_name)
276 {
277 	struct btf *btf = bpf_object__btf(obj);
278 	struct btf_dump *d;
279 	struct bpf_map *map;
280 	const struct btf_type *sec;
281 	char map_ident[256];
282 	int err = 0;
283 
284 	d = btf_dump__new(btf, codegen_btf_dump_printf, NULL, NULL);
285 	if (!d)
286 		return -errno;
287 
288 	bpf_object__for_each_map(map, obj) {
289 		/* only generate definitions for memory-mapped internal maps */
290 		if (!is_mmapable_map(map, map_ident, sizeof(map_ident)))
291 			continue;
292 
293 		sec = find_type_for_map(btf, map_ident);
294 
295 		/* In some cases (e.g., sections like .rodata.cst16 containing
296 		 * compiler allocated string constants only) there will be
297 		 * special internal maps with no corresponding DATASEC BTF
298 		 * type. In such case, generate empty structs for each such
299 		 * map. It will still be memory-mapped and its contents
300 		 * accessible from user-space through BPF skeleton.
301 		 */
302 		if (!sec) {
303 			printf("	struct %s__%s {\n", obj_name, map_ident);
304 			printf("	} *%s;\n", map_ident);
305 		} else {
306 			err = codegen_datasec_def(obj, btf, d, sec, obj_name);
307 			if (err)
308 				goto out;
309 		}
310 	}
311 
312 
313 out:
314 	btf_dump__free(d);
315 	return err;
316 }
317 
318 static bool btf_is_ptr_to_func_proto(const struct btf *btf,
319 				     const struct btf_type *v)
320 {
321 	return btf_is_ptr(v) && btf_is_func_proto(btf__type_by_id(btf, v->type));
322 }
323 
324 static int codegen_subskel_datasecs(struct bpf_object *obj, const char *obj_name)
325 {
326 	struct btf *btf = bpf_object__btf(obj);
327 	struct btf_dump *d;
328 	struct bpf_map *map;
329 	const struct btf_type *sec, *var;
330 	const struct btf_var_secinfo *sec_var;
331 	int i, err = 0, vlen;
332 	char map_ident[256], sec_ident[256];
333 	bool strip_mods = false, needs_typeof = false;
334 	const char *sec_name, *var_name;
335 	__u32 var_type_id;
336 
337 	d = btf_dump__new(btf, codegen_btf_dump_printf, NULL, NULL);
338 	if (!d)
339 		return -errno;
340 
341 	bpf_object__for_each_map(map, obj) {
342 		/* only generate definitions for memory-mapped internal maps */
343 		if (!is_mmapable_map(map, map_ident, sizeof(map_ident)))
344 			continue;
345 
346 		sec = find_type_for_map(btf, map_ident);
347 		if (!sec)
348 			continue;
349 
350 		sec_name = btf__name_by_offset(btf, sec->name_off);
351 		if (!get_datasec_ident(sec_name, sec_ident, sizeof(sec_ident)))
352 			continue;
353 
354 		strip_mods = strcmp(sec_name, ".kconfig") != 0;
355 		printf("	struct %s__%s {\n", obj_name, sec_ident);
356 
357 		sec_var = btf_var_secinfos(sec);
358 		vlen = btf_vlen(sec);
359 		for (i = 0; i < vlen; i++, sec_var++) {
360 			DECLARE_LIBBPF_OPTS(btf_dump_emit_type_decl_opts, opts,
361 				.indent_level = 2,
362 				.strip_mods = strip_mods,
363 				/* we'll print the name separately */
364 				.field_name = "",
365 			);
366 
367 			var = btf__type_by_id(btf, sec_var->type);
368 			var_name = btf__name_by_offset(btf, var->name_off);
369 			var_type_id = var->type;
370 
371 			/* static variables are not exposed through BPF skeleton */
372 			if (btf_var(var)->linkage == BTF_VAR_STATIC)
373 				continue;
374 
375 			/* The datasec member has KIND_VAR but we want the
376 			 * underlying type of the variable (e.g. KIND_INT).
377 			 */
378 			var = skip_mods_and_typedefs(btf, var->type, NULL);
379 
380 			printf("\t\t");
381 			/* Func and array members require special handling.
382 			 * Instead of producing `typename *var`, they produce
383 			 * `typeof(typename) *var`. This allows us to keep a
384 			 * similar syntax where the identifier is just prefixed
385 			 * by *, allowing us to ignore C declaration minutiae.
386 			 */
387 			needs_typeof = btf_is_array(var) || btf_is_ptr_to_func_proto(btf, var);
388 			if (needs_typeof)
389 				printf("__typeof__(");
390 
391 			err = btf_dump__emit_type_decl(d, var_type_id, &opts);
392 			if (err)
393 				goto out;
394 
395 			if (needs_typeof)
396 				printf(")");
397 
398 			printf(" *%s;\n", var_name);
399 		}
400 		printf("	} %s;\n", sec_ident);
401 	}
402 
403 out:
404 	btf_dump__free(d);
405 	return err;
406 }
407 
408 static void codegen(const char *template, ...)
409 {
410 	const char *src, *end;
411 	int skip_tabs = 0, n;
412 	char *s, *dst;
413 	va_list args;
414 	char c;
415 
416 	n = strlen(template);
417 	s = malloc(n + 1);
418 	if (!s)
419 		exit(-1);
420 	src = template;
421 	dst = s;
422 
423 	/* find out "baseline" indentation to skip */
424 	while ((c = *src++)) {
425 		if (c == '\t') {
426 			skip_tabs++;
427 		} else if (c == '\n') {
428 			break;
429 		} else {
430 			p_err("unrecognized character at pos %td in template '%s': '%c'",
431 			      src - template - 1, template, c);
432 			free(s);
433 			exit(-1);
434 		}
435 	}
436 
437 	while (*src) {
438 		/* skip baseline indentation tabs */
439 		for (n = skip_tabs; n > 0; n--, src++) {
440 			if (*src != '\t') {
441 				p_err("not enough tabs at pos %td in template '%s'",
442 				      src - template - 1, template);
443 				free(s);
444 				exit(-1);
445 			}
446 		}
447 		/* trim trailing whitespace */
448 		end = strchrnul(src, '\n');
449 		for (n = end - src; n > 0 && isspace(src[n - 1]); n--)
450 			;
451 		memcpy(dst, src, n);
452 		dst += n;
453 		if (*end)
454 			*dst++ = '\n';
455 		src = *end ? end + 1 : end;
456 	}
457 	*dst++ = '\0';
458 
459 	/* print out using adjusted template */
460 	va_start(args, template);
461 	n = vprintf(s, args);
462 	va_end(args);
463 
464 	free(s);
465 }
466 
467 static void print_hex(const char *data, int data_sz)
468 {
469 	int i, len;
470 
471 	for (i = 0, len = 0; i < data_sz; i++) {
472 		int w = data[i] ? 4 : 2;
473 
474 		len += w;
475 		if (len > 78) {
476 			printf("\\\n");
477 			len = w;
478 		}
479 		if (!data[i])
480 			printf("\\0");
481 		else
482 			printf("\\x%02x", (unsigned char)data[i]);
483 	}
484 }
485 
486 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
487 {
488 	long page_sz = sysconf(_SC_PAGE_SIZE);
489 	size_t map_sz;
490 
491 	map_sz = (size_t)roundup(bpf_map__value_size(map), 8) * bpf_map__max_entries(map);
492 	map_sz = roundup(map_sz, page_sz);
493 	return map_sz;
494 }
495 
496 /* Emit type size asserts for all top-level fields in memory-mapped internal maps. */
497 static void codegen_asserts(struct bpf_object *obj, const char *obj_name)
498 {
499 	struct btf *btf = bpf_object__btf(obj);
500 	struct bpf_map *map;
501 	struct btf_var_secinfo *sec_var;
502 	int i, vlen;
503 	const struct btf_type *sec;
504 	char map_ident[256], var_ident[256];
505 
506 	if (!btf)
507 		return;
508 
509 	codegen("\
510 		\n\
511 		__attribute__((unused)) static void			    \n\
512 		%1$s__assert(struct %1$s *s __attribute__((unused)))	    \n\
513 		{							    \n\
514 		#ifdef __cplusplus					    \n\
515 		#define _Static_assert static_assert			    \n\
516 		#endif							    \n\
517 		", obj_name);
518 
519 	bpf_object__for_each_map(map, obj) {
520 		if (!is_mmapable_map(map, map_ident, sizeof(map_ident)))
521 			continue;
522 
523 		sec = find_type_for_map(btf, map_ident);
524 		if (!sec) {
525 			/* best effort, couldn't find the type for this map */
526 			continue;
527 		}
528 
529 		sec_var = btf_var_secinfos(sec);
530 		vlen =  btf_vlen(sec);
531 
532 		for (i = 0; i < vlen; i++, sec_var++) {
533 			const struct btf_type *var = btf__type_by_id(btf, sec_var->type);
534 			const char *var_name = btf__name_by_offset(btf, var->name_off);
535 			long var_size;
536 
537 			/* static variables are not exposed through BPF skeleton */
538 			if (btf_var(var)->linkage == BTF_VAR_STATIC)
539 				continue;
540 
541 			var_size = btf__resolve_size(btf, var->type);
542 			if (var_size < 0)
543 				continue;
544 
545 			var_ident[0] = '\0';
546 			strncat(var_ident, var_name, sizeof(var_ident) - 1);
547 			sanitize_identifier(var_ident);
548 
549 			printf("\t_Static_assert(sizeof(s->%s->%s) == %ld, \"unexpected size of '%s'\");\n",
550 			       map_ident, var_ident, var_size, var_ident);
551 		}
552 	}
553 	codegen("\
554 		\n\
555 		#ifdef __cplusplus					    \n\
556 		#undef _Static_assert					    \n\
557 		#endif							    \n\
558 		}							    \n\
559 		");
560 }
561 
562 static void codegen_attach_detach(struct bpf_object *obj, const char *obj_name)
563 {
564 	struct bpf_program *prog;
565 
566 	bpf_object__for_each_program(prog, obj) {
567 		const char *tp_name;
568 
569 		codegen("\
570 			\n\
571 			\n\
572 			static inline int					    \n\
573 			%1$s__%2$s__attach(struct %1$s *skel)			    \n\
574 			{							    \n\
575 				int prog_fd = skel->progs.%2$s.prog_fd;		    \n\
576 			", obj_name, bpf_program__name(prog));
577 
578 		switch (bpf_program__type(prog)) {
579 		case BPF_PROG_TYPE_RAW_TRACEPOINT:
580 			tp_name = strchr(bpf_program__section_name(prog), '/') + 1;
581 			printf("\tint fd = skel_raw_tracepoint_open(\"%s\", prog_fd);\n", tp_name);
582 			break;
583 		case BPF_PROG_TYPE_TRACING:
584 		case BPF_PROG_TYPE_LSM:
585 			if (bpf_program__expected_attach_type(prog) == BPF_TRACE_ITER)
586 				printf("\tint fd = skel_link_create(prog_fd, 0, BPF_TRACE_ITER);\n");
587 			else
588 				printf("\tint fd = skel_raw_tracepoint_open(NULL, prog_fd);\n");
589 			break;
590 		default:
591 			printf("\tint fd = ((void)prog_fd, 0); /* auto-attach not supported */\n");
592 			break;
593 		}
594 		codegen("\
595 			\n\
596 										    \n\
597 				if (fd > 0)					    \n\
598 					skel->links.%1$s_fd = fd;		    \n\
599 				return fd;					    \n\
600 			}							    \n\
601 			", bpf_program__name(prog));
602 	}
603 
604 	codegen("\
605 		\n\
606 									    \n\
607 		static inline int					    \n\
608 		%1$s__attach(struct %1$s *skel)				    \n\
609 		{							    \n\
610 			int ret = 0;					    \n\
611 									    \n\
612 		", obj_name);
613 
614 	bpf_object__for_each_program(prog, obj) {
615 		codegen("\
616 			\n\
617 				ret = ret < 0 ? ret : %1$s__%2$s__attach(skel);   \n\
618 			", obj_name, bpf_program__name(prog));
619 	}
620 
621 	codegen("\
622 		\n\
623 			return ret < 0 ? ret : 0;			    \n\
624 		}							    \n\
625 									    \n\
626 		static inline void					    \n\
627 		%1$s__detach(struct %1$s *skel)				    \n\
628 		{							    \n\
629 		", obj_name);
630 
631 	bpf_object__for_each_program(prog, obj) {
632 		codegen("\
633 			\n\
634 				skel_closenz(skel->links.%1$s_fd);	    \n\
635 			", bpf_program__name(prog));
636 	}
637 
638 	codegen("\
639 		\n\
640 		}							    \n\
641 		");
642 }
643 
644 static void codegen_destroy(struct bpf_object *obj, const char *obj_name)
645 {
646 	struct bpf_program *prog;
647 	struct bpf_map *map;
648 	char ident[256];
649 
650 	codegen("\
651 		\n\
652 		static void						    \n\
653 		%1$s__destroy(struct %1$s *skel)			    \n\
654 		{							    \n\
655 			if (!skel)					    \n\
656 				return;					    \n\
657 			%1$s__detach(skel);				    \n\
658 		",
659 		obj_name);
660 
661 	bpf_object__for_each_program(prog, obj) {
662 		codegen("\
663 			\n\
664 				skel_closenz(skel->progs.%1$s.prog_fd);	    \n\
665 			", bpf_program__name(prog));
666 	}
667 
668 	bpf_object__for_each_map(map, obj) {
669 		if (!get_map_ident(map, ident, sizeof(ident)))
670 			continue;
671 		if (bpf_map__is_internal(map) &&
672 		    (bpf_map__map_flags(map) & BPF_F_MMAPABLE))
673 			printf("\tskel_free_map_data(skel->%1$s, skel->maps.%1$s.initial_value, %2$zu);\n",
674 			       ident, bpf_map_mmap_sz(map));
675 		codegen("\
676 			\n\
677 				skel_closenz(skel->maps.%1$s.map_fd);	    \n\
678 			", ident);
679 	}
680 	codegen("\
681 		\n\
682 			skel_free(skel);				    \n\
683 		}							    \n\
684 		",
685 		obj_name);
686 }
687 
688 static int gen_trace(struct bpf_object *obj, const char *obj_name, const char *header_guard)
689 {
690 	DECLARE_LIBBPF_OPTS(gen_loader_opts, opts);
691 	struct bpf_load_and_run_opts sopts = {};
692 	char sig_buf[MAX_SIG_SIZE];
693 	__u8 prog_sha[SHA256_DIGEST_LENGTH];
694 	struct bpf_map *map;
695 
696 	char ident[256];
697 	int err = 0;
698 
699 	if (sign_progs)
700 		opts.gen_hash = true;
701 
702 	err = bpf_object__gen_loader(obj, &opts);
703 	if (err)
704 		return err;
705 
706 	err = bpf_object__load(obj);
707 	if (err) {
708 		p_err("failed to load object file");
709 		goto out;
710 	}
711 
712 	/* If there was no error during load then gen_loader_opts
713 	 * are populated with the loader program.
714 	 */
715 
716 	/* finish generating 'struct skel' */
717 	codegen("\
718 		\n\
719 		};							    \n\
720 		", obj_name);
721 
722 
723 	codegen_attach_detach(obj, obj_name);
724 
725 	codegen_destroy(obj, obj_name);
726 
727 	codegen("\
728 		\n\
729 		static inline struct %1$s *				    \n\
730 		%1$s__open(void)					    \n\
731 		{							    \n\
732 			struct %1$s *skel;				    \n\
733 									    \n\
734 			skel = (struct %1$s *)skel_alloc(sizeof(*skel));    \n\
735 			if (!skel)					    \n\
736 				goto cleanup;				    \n\
737 			skel->ctx.sz = (char *)&skel->links - (char *)skel; \n\
738 		",
739 		obj_name, opts.data_sz);
740 	bpf_object__for_each_map(map, obj) {
741 		const void *mmap_data = NULL;
742 		size_t mmap_size = 0;
743 
744 		if (!is_mmapable_map(map, ident, sizeof(ident)))
745 			continue;
746 
747 		codegen("\
748 		\n\
749 			{						    \n\
750 				static const char data[] __attribute__((__aligned__(8))) = \"\\\n\
751 		");
752 		mmap_data = bpf_map__initial_value(map, &mmap_size);
753 		print_hex(mmap_data, mmap_size);
754 		codegen("\
755 		\n\
756 		\";							    \n\
757 									    \n\
758 				skel->%1$s = (__typeof__(skel->%1$s))skel_prep_map_data((void *)data, %2$zd,\n\
759 								sizeof(data) - 1);\n\
760 				if (!skel->%1$s)			    \n\
761 					goto cleanup;			    \n\
762 				skel->maps.%1$s.initial_value = (__u64) (long) skel->%1$s;\n\
763 			}						    \n\
764 			", ident, bpf_map_mmap_sz(map));
765 	}
766 	codegen("\
767 		\n\
768 			return skel;					    \n\
769 		cleanup:						    \n\
770 			%1$s__destroy(skel);				    \n\
771 			return NULL;					    \n\
772 		}							    \n\
773 									    \n\
774 		static inline int					    \n\
775 		%1$s__load(struct %1$s *skel)				    \n\
776 		{							    \n\
777 			struct bpf_load_and_run_opts opts = {};		    \n\
778 			int err;					    \n\
779 			static const char opts_data[] __attribute__((__aligned__(8))) = \"\\\n\
780 		",
781 		obj_name);
782 	print_hex(opts.data, opts.data_sz);
783 	codegen("\
784 		\n\
785 		\";							    \n\
786 			static const char opts_insn[] __attribute__((__aligned__(8))) = \"\\\n\
787 		");
788 	print_hex(opts.insns, opts.insns_sz);
789 	codegen("\
790 		\n\
791 		\";\n");
792 
793 	if (sign_progs) {
794 		sopts.insns = opts.insns;
795 		sopts.insns_sz = opts.insns_sz;
796 		sopts.data = opts.data;
797 		sopts.data_sz = opts.data_sz;
798 		sopts.excl_prog_hash = prog_sha;
799 		sopts.excl_prog_hash_sz = sizeof(prog_sha);
800 		sopts.signature = sig_buf;
801 		sopts.signature_sz = MAX_SIG_SIZE;
802 
803 		err = bpftool_prog_sign(&sopts);
804 		if (err < 0) {
805 			p_err("failed to sign program");
806 			goto out;
807 		}
808 
809 		codegen("\
810 		\n\
811 			static const char opts_sig[] __attribute__((__aligned__(8))) = \"\\\n\
812 		");
813 		print_hex((const void *)sig_buf, sopts.signature_sz);
814 		codegen("\
815 		\n\
816 		\";\n");
817 
818 		codegen("\
819 		\n\
820 			static const char opts_excl_hash[] __attribute__((__aligned__(8))) = \"\\\n\
821 		");
822 		print_hex((const void *)prog_sha, sizeof(prog_sha));
823 		codegen("\
824 		\n\
825 		\";\n");
826 
827 		codegen("\
828 		\n\
829 			opts.signature = (void *)opts_sig;			\n\
830 			opts.signature_sz = sizeof(opts_sig) - 1;		\n\
831 			opts.excl_prog_hash = (void *)opts_excl_hash;		\n\
832 			opts.excl_prog_hash_sz = sizeof(opts_excl_hash) - 1;	\n\
833 			opts.keyring_id = skel->keyring_id;			\n\
834 		");
835 	}
836 
837 	codegen("\
838 		\n\
839 			opts.ctx = (struct bpf_loader_ctx *)skel;	    \n\
840 			opts.data_sz = sizeof(opts_data) - 1;		    \n\
841 			opts.data = (void *)opts_data;			    \n\
842 			opts.insns_sz = sizeof(opts_insn) - 1;		    \n\
843 			opts.insns = (void *)opts_insn;			    \n\
844 									    \n\
845 			err = bpf_load_and_run(&opts);			    \n\
846 			if (err < 0)					    \n\
847 				return err;				    \n\
848 		");
849 	bpf_object__for_each_map(map, obj) {
850 		const char *mmap_flags;
851 
852 		if (!is_mmapable_map(map, ident, sizeof(ident)))
853 			continue;
854 
855 		if (bpf_map__map_flags(map) & BPF_F_RDONLY_PROG)
856 			mmap_flags = "PROT_READ";
857 		else
858 			mmap_flags = "PROT_READ | PROT_WRITE";
859 
860 		codegen("\
861 		\n\
862 			skel->%1$s = (__typeof__(skel->%1$s))skel_finalize_map_data(&skel->maps.%1$s.initial_value,\n\
863 							%2$zd, %3$s, skel->maps.%1$s.map_fd);\n\
864 			if (!skel->%1$s)				    \n\
865 				return -ENOMEM;				    \n\
866 			",
867 		       ident, bpf_map_mmap_sz(map), mmap_flags);
868 	}
869 	codegen("\
870 		\n\
871 			return 0;					    \n\
872 		}							    \n\
873 									    \n\
874 		static inline struct %1$s *				    \n\
875 		%1$s__open_and_load(void)				    \n\
876 		{							    \n\
877 			struct %1$s *skel;				    \n\
878 									    \n\
879 			skel = %1$s__open();				    \n\
880 			if (!skel)					    \n\
881 				return NULL;				    \n\
882 			if (%1$s__load(skel)) {				    \n\
883 				%1$s__destroy(skel);			    \n\
884 				return NULL;				    \n\
885 			}						    \n\
886 			return skel;					    \n\
887 		}							    \n\
888 									    \n\
889 		", obj_name);
890 
891 	codegen_asserts(obj, obj_name);
892 
893 	codegen("\
894 		\n\
895 									    \n\
896 		#endif /* %s */						    \n\
897 		",
898 		header_guard);
899 	err = 0;
900 out:
901 	return err;
902 }
903 
904 static void
905 codegen_maps_skeleton(struct bpf_object *obj, size_t map_cnt, bool mmaped, bool populate_links)
906 {
907 	struct bpf_map *map;
908 	char ident[256];
909 	size_t i, map_sz;
910 
911 	if (!map_cnt)
912 		return;
913 
914 	/* for backward compatibility with old libbpf versions that don't
915 	 * handle new BPF skeleton with new struct bpf_map_skeleton definition
916 	 * that includes link field, avoid specifying new increased size,
917 	 * unless we absolutely have to (i.e., if there are struct_ops maps
918 	 * present)
919 	 */
920 	map_sz = offsetof(struct bpf_map_skeleton, link);
921 	if (populate_links) {
922 		bpf_object__for_each_map(map, obj) {
923 			if (bpf_map__type(map) == BPF_MAP_TYPE_STRUCT_OPS) {
924 				map_sz = sizeof(struct bpf_map_skeleton);
925 				break;
926 			}
927 		}
928 	}
929 
930 	codegen("\
931 		\n\
932 								    \n\
933 			/* maps */				    \n\
934 			s->map_cnt = %zu;			    \n\
935 			s->map_skel_sz = %zu;			    \n\
936 			s->maps = (struct bpf_map_skeleton *)calloc(s->map_cnt,\n\
937 					sizeof(*s->maps) > %zu ? sizeof(*s->maps) : %zu);\n\
938 			if (!s->maps) {				    \n\
939 				err = -ENOMEM;			    \n\
940 				goto err;			    \n\
941 			}					    \n\
942 		",
943 		map_cnt, map_sz, map_sz, map_sz
944 	);
945 	i = 0;
946 	bpf_object__for_each_map(map, obj) {
947 		if (!get_map_ident(map, ident, sizeof(ident)))
948 			continue;
949 
950 		codegen("\
951 			\n\
952 								    \n\
953 				map = (struct bpf_map_skeleton *)((char *)s->maps + %zu * s->map_skel_sz);\n\
954 				map->name = \"%s\";		    \n\
955 				map->map = &obj->maps.%s;	    \n\
956 			",
957 			i, bpf_map__name(map), ident);
958 		/* memory-mapped internal maps */
959 		if (mmaped && is_mmapable_map(map, ident, sizeof(ident))) {
960 			printf("\tmap->mmaped = (void **)&obj->%s;\n", ident);
961 		}
962 
963 		if (populate_links && bpf_map__type(map) == BPF_MAP_TYPE_STRUCT_OPS) {
964 			codegen("\
965 				\n\
966 					map->link = &obj->links.%s; \n\
967 				", ident);
968 		}
969 		i++;
970 	}
971 }
972 
973 static void
974 codegen_progs_skeleton(struct bpf_object *obj, size_t prog_cnt, bool populate_links)
975 {
976 	struct bpf_program *prog;
977 	int i;
978 
979 	if (!prog_cnt)
980 		return;
981 
982 	codegen("\
983 		\n\
984 									\n\
985 			/* programs */				    \n\
986 			s->prog_cnt = %zu;			    \n\
987 			s->prog_skel_sz = sizeof(*s->progs);	    \n\
988 			s->progs = (struct bpf_prog_skeleton *)calloc(s->prog_cnt, s->prog_skel_sz);\n\
989 			if (!s->progs) {			    \n\
990 				err = -ENOMEM;			    \n\
991 				goto err;			    \n\
992 			}					    \n\
993 		",
994 		prog_cnt
995 	);
996 	i = 0;
997 	bpf_object__for_each_program(prog, obj) {
998 		codegen("\
999 			\n\
1000 									\n\
1001 				s->progs[%1$zu].name = \"%2$s\";    \n\
1002 				s->progs[%1$zu].prog = &obj->progs.%2$s;\n\
1003 			",
1004 			i, bpf_program__name(prog));
1005 
1006 		if (populate_links) {
1007 			codegen("\
1008 				\n\
1009 					s->progs[%1$zu].link = &obj->links.%2$s;\n\
1010 				",
1011 				i, bpf_program__name(prog));
1012 		}
1013 		i++;
1014 	}
1015 }
1016 
1017 static int walk_st_ops_shadow_vars(struct btf *btf, const char *ident,
1018 				   const struct btf_type *map_type, __u32 map_type_id)
1019 {
1020 	LIBBPF_OPTS(btf_dump_emit_type_decl_opts, opts, .indent_level = 3);
1021 	const struct btf_type *member_type;
1022 	__u32 offset, next_offset = 0;
1023 	const struct btf_member *m;
1024 	struct btf_dump *d = NULL;
1025 	const char *member_name;
1026 	__u32 member_type_id;
1027 	int i, err = 0, n;
1028 	int size;
1029 
1030 	d = btf_dump__new(btf, codegen_btf_dump_printf, NULL, NULL);
1031 	if (!d)
1032 		return -errno;
1033 
1034 	n = btf_vlen(map_type);
1035 	for (i = 0, m = btf_members(map_type); i < n; i++, m++) {
1036 		member_type = skip_mods_and_typedefs(btf, m->type, &member_type_id);
1037 		member_name = btf__name_by_offset(btf, m->name_off);
1038 
1039 		offset = m->offset / 8;
1040 		if (next_offset < offset)
1041 			printf("\t\t\tchar __padding_%d[%u];\n", i, offset - next_offset);
1042 
1043 		switch (btf_kind(member_type)) {
1044 		case BTF_KIND_INT:
1045 		case BTF_KIND_FLOAT:
1046 		case BTF_KIND_ENUM:
1047 		case BTF_KIND_ENUM64:
1048 			/* scalar type */
1049 			printf("\t\t\t");
1050 			opts.field_name = member_name;
1051 			err = btf_dump__emit_type_decl(d, member_type_id, &opts);
1052 			if (err) {
1053 				p_err("Failed to emit type declaration for %s: %d", member_name, err);
1054 				goto out;
1055 			}
1056 			printf(";\n");
1057 
1058 			size = btf__resolve_size(btf, member_type_id);
1059 			if (size < 0) {
1060 				p_err("Failed to resolve size of %s: %d\n", member_name, size);
1061 				err = size;
1062 				goto out;
1063 			}
1064 
1065 			next_offset = offset + size;
1066 			break;
1067 
1068 		case BTF_KIND_PTR:
1069 			if (resolve_func_ptr(btf, m->type, NULL)) {
1070 				/* Function pointer */
1071 				printf("\t\t\tstruct bpf_program *%s;\n", member_name);
1072 
1073 				next_offset = offset + sizeof(void *);
1074 				break;
1075 			}
1076 			/* All pointer types are unsupported except for
1077 			 * function pointers.
1078 			 */
1079 			fallthrough;
1080 
1081 		default:
1082 			/* Unsupported types
1083 			 *
1084 			 * Types other than scalar types and function
1085 			 * pointers are currently not supported in order to
1086 			 * prevent conflicts in the generated code caused
1087 			 * by multiple definitions. For instance, if the
1088 			 * struct type FOO is used in a struct_ops map,
1089 			 * bpftool has to generate definitions for FOO,
1090 			 * which may result in conflicts if FOO is defined
1091 			 * in different skeleton files.
1092 			 */
1093 			size = btf__resolve_size(btf, member_type_id);
1094 			if (size < 0) {
1095 				p_err("Failed to resolve size of %s: %d\n", member_name, size);
1096 				err = size;
1097 				goto out;
1098 			}
1099 			printf("\t\t\tchar __unsupported_%d[%d];\n", i, size);
1100 
1101 			next_offset = offset + size;
1102 			break;
1103 		}
1104 	}
1105 
1106 	/* Cannot fail since it must be a struct type */
1107 	size = btf__resolve_size(btf, map_type_id);
1108 	if (next_offset < (__u32)size)
1109 		printf("\t\t\tchar __padding_end[%u];\n", size - next_offset);
1110 
1111 out:
1112 	btf_dump__free(d);
1113 
1114 	return err;
1115 }
1116 
1117 /* Generate the pointer of the shadow type for a struct_ops map.
1118  *
1119  * This function adds a pointer of the shadow type for a struct_ops map.
1120  * The members of a struct_ops map can be exported through a pointer to a
1121  * shadow type. The user can access these members through the pointer.
1122  *
1123  * A shadow type includes not all members, only members of some types.
1124  * They are scalar types and function pointers. The function pointers are
1125  * translated to the pointer of the struct bpf_program. The scalar types
1126  * are translated to the original type without any modifiers.
1127  *
1128  * Unsupported types will be translated to a char array to occupy the same
1129  * space as the original field, being renamed as __unsupported_*.  The user
1130  * should treat these fields as opaque data.
1131  */
1132 static int gen_st_ops_shadow_type(const char *obj_name, struct btf *btf, const char *ident,
1133 				  const struct bpf_map *map)
1134 {
1135 	const struct btf_type *map_type;
1136 	const char *type_name;
1137 	__u32 map_type_id;
1138 	int err;
1139 
1140 	map_type_id = bpf_map__btf_value_type_id(map);
1141 	if (map_type_id == 0)
1142 		return -EINVAL;
1143 	map_type = btf__type_by_id(btf, map_type_id);
1144 	if (!map_type)
1145 		return -EINVAL;
1146 
1147 	type_name = btf__name_by_offset(btf, map_type->name_off);
1148 
1149 	printf("\t\tstruct %s__%s__%s {\n", obj_name, ident, type_name);
1150 
1151 	err = walk_st_ops_shadow_vars(btf, ident, map_type, map_type_id);
1152 	if (err)
1153 		return err;
1154 
1155 	printf("\t\t} *%s;\n", ident);
1156 
1157 	return 0;
1158 }
1159 
1160 static int gen_st_ops_shadow(const char *obj_name, struct btf *btf, struct bpf_object *obj)
1161 {
1162 	int err, st_ops_cnt = 0;
1163 	struct bpf_map *map;
1164 	char ident[256];
1165 
1166 	if (!btf)
1167 		return 0;
1168 
1169 	/* Generate the pointers to shadow types of
1170 	 * struct_ops maps.
1171 	 */
1172 	bpf_object__for_each_map(map, obj) {
1173 		if (bpf_map__type(map) != BPF_MAP_TYPE_STRUCT_OPS)
1174 			continue;
1175 		if (!get_map_ident(map, ident, sizeof(ident)))
1176 			continue;
1177 
1178 		if (st_ops_cnt == 0) /* first struct_ops map */
1179 			printf("\tstruct {\n");
1180 		st_ops_cnt++;
1181 
1182 		err = gen_st_ops_shadow_type(obj_name, btf, ident, map);
1183 		if (err)
1184 			return err;
1185 	}
1186 
1187 	if (st_ops_cnt)
1188 		printf("\t} struct_ops;\n");
1189 
1190 	return 0;
1191 }
1192 
1193 /* Generate the code to initialize the pointers of shadow types. */
1194 static void gen_st_ops_shadow_init(struct btf *btf, struct bpf_object *obj)
1195 {
1196 	struct bpf_map *map;
1197 	char ident[256];
1198 
1199 	if (!btf)
1200 		return;
1201 
1202 	/* Initialize the pointers to_ops shadow types of
1203 	 * struct_ops maps.
1204 	 */
1205 	bpf_object__for_each_map(map, obj) {
1206 		if (bpf_map__type(map) != BPF_MAP_TYPE_STRUCT_OPS)
1207 			continue;
1208 		if (!get_map_ident(map, ident, sizeof(ident)))
1209 			continue;
1210 		codegen("\
1211 			\n\
1212 				obj->struct_ops.%1$s = (__typeof__(obj->struct_ops.%1$s))\n\
1213 					bpf_map__initial_value(obj->maps.%1$s, NULL);\n\
1214 			\n\
1215 			", ident);
1216 	}
1217 }
1218 
1219 static int do_skeleton(int argc, char **argv)
1220 {
1221 	char header_guard[MAX_OBJ_NAME_LEN + sizeof("__SKEL_H__")];
1222 	size_t map_cnt = 0, prog_cnt = 0, attach_map_cnt = 0, file_sz, mmap_sz;
1223 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts);
1224 	char obj_name[MAX_OBJ_NAME_LEN] = "", *obj_data;
1225 	struct bpf_object *obj = NULL;
1226 	const char *file;
1227 	char ident[256];
1228 	struct bpf_program *prog;
1229 	int fd, err = -1;
1230 	struct bpf_map *map;
1231 	struct btf *btf;
1232 	struct stat st;
1233 
1234 	if (!REQ_ARGS(1)) {
1235 		usage();
1236 		return -1;
1237 	}
1238 	file = GET_ARG();
1239 
1240 	while (argc) {
1241 		if (!REQ_ARGS(2))
1242 			return -1;
1243 
1244 		if (is_prefix(*argv, "name")) {
1245 			NEXT_ARG();
1246 
1247 			if (obj_name[0] != '\0') {
1248 				p_err("object name already specified");
1249 				return -1;
1250 			}
1251 
1252 			strncpy(obj_name, *argv, MAX_OBJ_NAME_LEN - 1);
1253 			obj_name[MAX_OBJ_NAME_LEN - 1] = '\0';
1254 		} else {
1255 			p_err("unknown arg %s", *argv);
1256 			return -1;
1257 		}
1258 
1259 		NEXT_ARG();
1260 	}
1261 
1262 	if (argc) {
1263 		p_err("extra unknown arguments");
1264 		return -1;
1265 	}
1266 
1267 	if (stat(file, &st)) {
1268 		p_err("failed to stat() %s: %s", file, strerror(errno));
1269 		return -1;
1270 	}
1271 	file_sz = st.st_size;
1272 	mmap_sz = roundup(file_sz, sysconf(_SC_PAGE_SIZE));
1273 	fd = open(file, O_RDONLY);
1274 	if (fd < 0) {
1275 		p_err("failed to open() %s: %s", file, strerror(errno));
1276 		return -1;
1277 	}
1278 	obj_data = mmap(NULL, mmap_sz, PROT_READ, MAP_PRIVATE, fd, 0);
1279 	if (obj_data == MAP_FAILED) {
1280 		obj_data = NULL;
1281 		p_err("failed to mmap() %s: %s", file, strerror(errno));
1282 		goto out;
1283 	}
1284 	if (obj_name[0] == '\0')
1285 		get_obj_name(obj_name, file);
1286 	opts.object_name = obj_name;
1287 	if (verifier_logs)
1288 		/* log_level1 + log_level2 + stats, but not stable UAPI */
1289 		opts.kernel_log_level = 1 + 2 + 4;
1290 	obj = bpf_object__open_mem(obj_data, file_sz, &opts);
1291 	if (!obj) {
1292 		char err_buf[256];
1293 
1294 		err = -errno;
1295 		libbpf_strerror(err, err_buf, sizeof(err_buf));
1296 		p_err("failed to open BPF object file: %s", err_buf);
1297 		goto out_obj;
1298 	}
1299 
1300 	bpf_object__for_each_map(map, obj) {
1301 		if (!get_map_ident(map, ident, sizeof(ident))) {
1302 			p_err("ignoring unrecognized internal map '%s'...",
1303 			      bpf_map__name(map));
1304 			continue;
1305 		}
1306 
1307 		if (bpf_map__type(map) == BPF_MAP_TYPE_STRUCT_OPS)
1308 			attach_map_cnt++;
1309 
1310 		map_cnt++;
1311 	}
1312 	bpf_object__for_each_program(prog, obj) {
1313 		prog_cnt++;
1314 	}
1315 
1316 	get_header_guard(header_guard, obj_name, "SKEL_H");
1317 	if (use_loader) {
1318 		codegen("\
1319 		\n\
1320 		/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */   \n\
1321 		/* THIS FILE IS AUTOGENERATED BY BPFTOOL! */		    \n\
1322 		#ifndef %2$s						    \n\
1323 		#define %2$s						    \n\
1324 									    \n\
1325 		#include <bpf/skel_internal.h>				    \n\
1326 									    \n\
1327 		struct %1$s {						    \n\
1328 			struct bpf_loader_ctx ctx;			    \n\
1329 		",
1330 		obj_name, header_guard
1331 		);
1332 	} else {
1333 		codegen("\
1334 		\n\
1335 		/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */   \n\
1336 									    \n\
1337 		/* THIS FILE IS AUTOGENERATED BY BPFTOOL! */		    \n\
1338 		#ifndef %2$s						    \n\
1339 		#define %2$s						    \n\
1340 									    \n\
1341 		#include <errno.h>					    \n\
1342 		#include <stdlib.h>					    \n\
1343 		#include <bpf/libbpf.h>					    \n\
1344 									    \n\
1345 		#define BPF_SKEL_SUPPORTS_MAP_AUTO_ATTACH 1		    \n\
1346 									    \n\
1347 		struct %1$s {						    \n\
1348 			struct bpf_object_skeleton *skeleton;		    \n\
1349 			struct bpf_object *obj;				    \n\
1350 		",
1351 		obj_name, header_guard
1352 		);
1353 	}
1354 
1355 	if (map_cnt) {
1356 		printf("\tstruct {\n");
1357 		bpf_object__for_each_map(map, obj) {
1358 			if (!get_map_ident(map, ident, sizeof(ident)))
1359 				continue;
1360 			if (use_loader)
1361 				printf("\t\tstruct bpf_map_desc %s;\n", ident);
1362 			else
1363 				printf("\t\tstruct bpf_map *%s;\n", ident);
1364 		}
1365 		printf("\t} maps;\n");
1366 	}
1367 
1368 	btf = bpf_object__btf(obj);
1369 	err = gen_st_ops_shadow(obj_name, btf, obj);
1370 	if (err)
1371 		goto out;
1372 
1373 	if (prog_cnt) {
1374 		printf("\tstruct {\n");
1375 		bpf_object__for_each_program(prog, obj) {
1376 			if (use_loader)
1377 				printf("\t\tstruct bpf_prog_desc %s;\n",
1378 				       bpf_program__name(prog));
1379 			else
1380 				printf("\t\tstruct bpf_program *%s;\n",
1381 				       bpf_program__name(prog));
1382 		}
1383 		printf("\t} progs;\n");
1384 	}
1385 
1386 	if (prog_cnt + attach_map_cnt) {
1387 		printf("\tstruct {\n");
1388 		bpf_object__for_each_program(prog, obj) {
1389 			if (use_loader)
1390 				printf("\t\tint %s_fd;\n",
1391 				       bpf_program__name(prog));
1392 			else
1393 				printf("\t\tstruct bpf_link *%s;\n",
1394 				       bpf_program__name(prog));
1395 		}
1396 
1397 		bpf_object__for_each_map(map, obj) {
1398 			if (!get_map_ident(map, ident, sizeof(ident)))
1399 				continue;
1400 			if (bpf_map__type(map) != BPF_MAP_TYPE_STRUCT_OPS)
1401 				continue;
1402 
1403 			if (use_loader)
1404 				printf("\t\tint %s_fd;\n", ident);
1405 			else
1406 				printf("\t\tstruct bpf_link *%s;\n", ident);
1407 		}
1408 
1409 		printf("\t} links;\n");
1410 	}
1411 
1412 	if (sign_progs) {
1413 		codegen("\
1414 		\n\
1415 			__s32 keyring_id;				   \n\
1416 		");
1417 	}
1418 
1419 	if (btf) {
1420 		err = codegen_datasecs(obj, obj_name);
1421 		if (err)
1422 			goto out;
1423 	}
1424 	if (use_loader) {
1425 		err = gen_trace(obj, obj_name, header_guard);
1426 		goto out;
1427 	}
1428 
1429 	codegen("\
1430 		\n\
1431 									    \n\
1432 		#ifdef __cplusplus					    \n\
1433 			static inline struct %1$s *open(const struct bpf_object_open_opts *opts = nullptr);\n\
1434 			static inline struct %1$s *open_and_load();	    \n\
1435 			static inline int load(struct %1$s *skel);	    \n\
1436 			static inline int attach(struct %1$s *skel);	    \n\
1437 			static inline void detach(struct %1$s *skel);	    \n\
1438 			static inline void destroy(struct %1$s *skel);	    \n\
1439 			static inline const void *elf_bytes(size_t *sz);    \n\
1440 		#endif /* __cplusplus */				    \n\
1441 		};							    \n\
1442 									    \n\
1443 		static void						    \n\
1444 		%1$s__destroy(struct %1$s *obj)				    \n\
1445 		{							    \n\
1446 			if (!obj)					    \n\
1447 				return;					    \n\
1448 			if (obj->skeleton)				    \n\
1449 				bpf_object__destroy_skeleton(obj->skeleton);\n\
1450 			free(obj);					    \n\
1451 		}							    \n\
1452 									    \n\
1453 		static inline int					    \n\
1454 		%1$s__create_skeleton(struct %1$s *obj);		    \n\
1455 									    \n\
1456 		static inline struct %1$s *				    \n\
1457 		%1$s__open_opts(const struct bpf_object_open_opts *opts)    \n\
1458 		{							    \n\
1459 			struct %1$s *obj;				    \n\
1460 			int err;					    \n\
1461 									    \n\
1462 			obj = (struct %1$s *)calloc(1, sizeof(*obj));	    \n\
1463 			if (!obj) {					    \n\
1464 				errno = ENOMEM;				    \n\
1465 				return NULL;				    \n\
1466 			}						    \n\
1467 									    \n\
1468 			err = %1$s__create_skeleton(obj);		    \n\
1469 			if (err)					    \n\
1470 				goto err_out;				    \n\
1471 									    \n\
1472 			err = bpf_object__open_skeleton(obj->skeleton, opts);\n\
1473 			if (err)					    \n\
1474 				goto err_out;				    \n\
1475 									    \n\
1476 		", obj_name);
1477 
1478 	gen_st_ops_shadow_init(btf, obj);
1479 
1480 	codegen("\
1481 		\n\
1482 			return obj;					    \n\
1483 		err_out:						    \n\
1484 			%1$s__destroy(obj);				    \n\
1485 			errno = -err;					    \n\
1486 			return NULL;					    \n\
1487 		}							    \n\
1488 									    \n\
1489 		static inline struct %1$s *				    \n\
1490 		%1$s__open(void)					    \n\
1491 		{							    \n\
1492 			return %1$s__open_opts(NULL);			    \n\
1493 		}							    \n\
1494 									    \n\
1495 		static inline int					    \n\
1496 		%1$s__load(struct %1$s *obj)				    \n\
1497 		{							    \n\
1498 			return bpf_object__load_skeleton(obj->skeleton);    \n\
1499 		}							    \n\
1500 									    \n\
1501 		static inline struct %1$s *				    \n\
1502 		%1$s__open_and_load(void)				    \n\
1503 		{							    \n\
1504 			struct %1$s *obj;				    \n\
1505 			int err;					    \n\
1506 									    \n\
1507 			obj = %1$s__open();				    \n\
1508 			if (!obj)					    \n\
1509 				return NULL;				    \n\
1510 			err = %1$s__load(obj);				    \n\
1511 			if (err) {					    \n\
1512 				%1$s__destroy(obj);			    \n\
1513 				errno = -err;				    \n\
1514 				return NULL;				    \n\
1515 			}						    \n\
1516 			return obj;					    \n\
1517 		}							    \n\
1518 									    \n\
1519 		static inline int					    \n\
1520 		%1$s__attach(struct %1$s *obj)				    \n\
1521 		{							    \n\
1522 			return bpf_object__attach_skeleton(obj->skeleton);  \n\
1523 		}							    \n\
1524 									    \n\
1525 		static inline void					    \n\
1526 		%1$s__detach(struct %1$s *obj)				    \n\
1527 		{							    \n\
1528 			bpf_object__detach_skeleton(obj->skeleton);	    \n\
1529 		}							    \n\
1530 		",
1531 		obj_name
1532 	);
1533 
1534 	codegen("\
1535 		\n\
1536 									    \n\
1537 		static inline const void *%1$s__elf_bytes(size_t *sz);	    \n\
1538 									    \n\
1539 		static inline int					    \n\
1540 		%1$s__create_skeleton(struct %1$s *obj)			    \n\
1541 		{							    \n\
1542 			struct bpf_object_skeleton *s;			    \n\
1543 			struct bpf_map_skeleton *map __attribute__((unused));\n\
1544 			int err;					    \n\
1545 									    \n\
1546 			s = (struct bpf_object_skeleton *)calloc(1, sizeof(*s));\n\
1547 			if (!s)	{					    \n\
1548 				err = -ENOMEM;				    \n\
1549 				goto err;				    \n\
1550 			}						    \n\
1551 									    \n\
1552 			s->sz = sizeof(*s);				    \n\
1553 			s->name = \"%1$s\";				    \n\
1554 			s->obj = &obj->obj;				    \n\
1555 		",
1556 		obj_name
1557 	);
1558 
1559 	codegen_maps_skeleton(obj, map_cnt, true /*mmaped*/, true /*links*/);
1560 	codegen_progs_skeleton(obj, prog_cnt, true /*populate_links*/);
1561 
1562 	codegen("\
1563 		\n\
1564 									    \n\
1565 			s->data = %1$s__elf_bytes(&s->data_sz);		    \n\
1566 									    \n\
1567 			obj->skeleton = s;				    \n\
1568 			return 0;					    \n\
1569 		err:							    \n\
1570 			bpf_object__destroy_skeleton(s);		    \n\
1571 			return err;					    \n\
1572 		}							    \n\
1573 									    \n\
1574 		static inline const void *%1$s__elf_bytes(size_t *sz)	    \n\
1575 		{							    \n\
1576 			static const char data[] __attribute__((__aligned__(8))) = \"\\\n\
1577 		",
1578 		obj_name
1579 	);
1580 
1581 	/* embed contents of BPF object file */
1582 	print_hex(obj_data, file_sz);
1583 
1584 	codegen("\
1585 		\n\
1586 		\";							    \n\
1587 									    \n\
1588 			*sz = sizeof(data) - 1;				    \n\
1589 			return (const void *)data;			    \n\
1590 		}							    \n\
1591 									    \n\
1592 		#ifdef __cplusplus					    \n\
1593 		struct %1$s *%1$s::open(const struct bpf_object_open_opts *opts) { return %1$s__open_opts(opts); }\n\
1594 		struct %1$s *%1$s::open_and_load() { return %1$s__open_and_load(); }	\n\
1595 		int %1$s::load(struct %1$s *skel) { return %1$s__load(skel); }		\n\
1596 		int %1$s::attach(struct %1$s *skel) { return %1$s__attach(skel); }	\n\
1597 		void %1$s::detach(struct %1$s *skel) { %1$s__detach(skel); }		\n\
1598 		void %1$s::destroy(struct %1$s *skel) { %1$s__destroy(skel); }		\n\
1599 		const void *%1$s::elf_bytes(size_t *sz) { return %1$s__elf_bytes(sz); } \n\
1600 		#endif /* __cplusplus */				    \n\
1601 									    \n\
1602 		",
1603 		obj_name);
1604 
1605 	codegen_asserts(obj, obj_name);
1606 
1607 	codegen("\
1608 		\n\
1609 									    \n\
1610 		#endif /* %1$s */					    \n\
1611 		",
1612 		header_guard);
1613 	err = 0;
1614 out:
1615 	bpf_object__close(obj);
1616 out_obj:
1617 	if (obj_data)
1618 		munmap(obj_data, mmap_sz);
1619 	close(fd);
1620 	return err;
1621 }
1622 
1623 /* Subskeletons are like skeletons, except they don't own the bpf_object,
1624  * associated maps, links, etc. Instead, they know about the existence of
1625  * variables, maps, programs and are able to find their locations
1626  * _at runtime_ from an already loaded bpf_object.
1627  *
1628  * This allows for library-like BPF objects to have userspace counterparts
1629  * with access to their own items without having to know anything about the
1630  * final BPF object that the library was linked into.
1631  */
1632 static int do_subskeleton(int argc, char **argv)
1633 {
1634 	char header_guard[MAX_OBJ_NAME_LEN + sizeof("__SUBSKEL_H__")];
1635 	size_t i, len, file_sz, map_cnt = 0, prog_cnt = 0, mmap_sz, var_cnt = 0, var_idx = 0;
1636 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts);
1637 	char obj_name[MAX_OBJ_NAME_LEN] = "", *obj_data;
1638 	struct bpf_object *obj = NULL;
1639 	const char *file, *var_name;
1640 	char ident[256];
1641 	int fd, err = -1, map_type_id;
1642 	const struct bpf_map *map;
1643 	struct bpf_program *prog;
1644 	struct btf *btf;
1645 	const struct btf_type *map_type, *var_type;
1646 	const struct btf_var_secinfo *var;
1647 	struct stat st;
1648 
1649 	if (!REQ_ARGS(1)) {
1650 		usage();
1651 		return -1;
1652 	}
1653 	file = GET_ARG();
1654 
1655 	while (argc) {
1656 		if (!REQ_ARGS(2))
1657 			return -1;
1658 
1659 		if (is_prefix(*argv, "name")) {
1660 			NEXT_ARG();
1661 
1662 			if (obj_name[0] != '\0') {
1663 				p_err("object name already specified");
1664 				return -1;
1665 			}
1666 
1667 			strncpy(obj_name, *argv, MAX_OBJ_NAME_LEN - 1);
1668 			obj_name[MAX_OBJ_NAME_LEN - 1] = '\0';
1669 		} else {
1670 			p_err("unknown arg %s", *argv);
1671 			return -1;
1672 		}
1673 
1674 		NEXT_ARG();
1675 	}
1676 
1677 	if (argc) {
1678 		p_err("extra unknown arguments");
1679 		return -1;
1680 	}
1681 
1682 	if (use_loader) {
1683 		p_err("cannot use loader for subskeletons");
1684 		return -1;
1685 	}
1686 
1687 	if (stat(file, &st)) {
1688 		p_err("failed to stat() %s: %s", file, strerror(errno));
1689 		return -1;
1690 	}
1691 	file_sz = st.st_size;
1692 	mmap_sz = roundup(file_sz, sysconf(_SC_PAGE_SIZE));
1693 	fd = open(file, O_RDONLY);
1694 	if (fd < 0) {
1695 		p_err("failed to open() %s: %s", file, strerror(errno));
1696 		return -1;
1697 	}
1698 	obj_data = mmap(NULL, mmap_sz, PROT_READ, MAP_PRIVATE, fd, 0);
1699 	if (obj_data == MAP_FAILED) {
1700 		obj_data = NULL;
1701 		p_err("failed to mmap() %s: %s", file, strerror(errno));
1702 		goto out;
1703 	}
1704 	if (obj_name[0] == '\0')
1705 		get_obj_name(obj_name, file);
1706 
1707 	/* The empty object name allows us to use bpf_map__name and produce
1708 	 * ELF section names out of it. (".data" instead of "obj.data")
1709 	 */
1710 	opts.object_name = "";
1711 	obj = bpf_object__open_mem(obj_data, file_sz, &opts);
1712 	if (!obj) {
1713 		char err_buf[256];
1714 
1715 		libbpf_strerror(errno, err_buf, sizeof(err_buf));
1716 		p_err("failed to open BPF object file: %s", err_buf);
1717 		obj = NULL;
1718 		goto out;
1719 	}
1720 
1721 	btf = bpf_object__btf(obj);
1722 	if (!btf) {
1723 		err = -1;
1724 		p_err("need btf type information for %s", obj_name);
1725 		goto out;
1726 	}
1727 
1728 	bpf_object__for_each_program(prog, obj) {
1729 		prog_cnt++;
1730 	}
1731 
1732 	/* First, count how many variables we have to find.
1733 	 * We need this in advance so the subskel can allocate the right
1734 	 * amount of storage.
1735 	 */
1736 	bpf_object__for_each_map(map, obj) {
1737 		if (!get_map_ident(map, ident, sizeof(ident)))
1738 			continue;
1739 
1740 		/* Also count all maps that have a name */
1741 		map_cnt++;
1742 
1743 		if (!is_mmapable_map(map, ident, sizeof(ident)))
1744 			continue;
1745 
1746 		map_type_id = bpf_map__btf_value_type_id(map);
1747 		if (map_type_id <= 0) {
1748 			err = map_type_id;
1749 			goto out;
1750 		}
1751 		map_type = btf__type_by_id(btf, map_type_id);
1752 
1753 		var = btf_var_secinfos(map_type);
1754 		len = btf_vlen(map_type);
1755 		for (i = 0; i < len; i++, var++) {
1756 			var_type = btf__type_by_id(btf, var->type);
1757 
1758 			if (btf_var(var_type)->linkage == BTF_VAR_STATIC)
1759 				continue;
1760 
1761 			var_cnt++;
1762 		}
1763 	}
1764 
1765 	get_header_guard(header_guard, obj_name, "SUBSKEL_H");
1766 	codegen("\
1767 	\n\
1768 	/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */	    \n\
1769 									    \n\
1770 	/* THIS FILE IS AUTOGENERATED! */				    \n\
1771 	#ifndef %2$s							    \n\
1772 	#define %2$s							    \n\
1773 									    \n\
1774 	#include <errno.h>						    \n\
1775 	#include <stdlib.h>						    \n\
1776 	#include <bpf/libbpf.h>						    \n\
1777 									    \n\
1778 	struct %1$s {							    \n\
1779 		struct bpf_object *obj;					    \n\
1780 		struct bpf_object_subskeleton *subskel;			    \n\
1781 	", obj_name, header_guard);
1782 
1783 	if (map_cnt) {
1784 		printf("\tstruct {\n");
1785 		bpf_object__for_each_map(map, obj) {
1786 			if (!get_map_ident(map, ident, sizeof(ident)))
1787 				continue;
1788 			printf("\t\tstruct bpf_map *%s;\n", ident);
1789 		}
1790 		printf("\t} maps;\n");
1791 	}
1792 
1793 	err = gen_st_ops_shadow(obj_name, btf, obj);
1794 	if (err)
1795 		goto out;
1796 
1797 	if (prog_cnt) {
1798 		printf("\tstruct {\n");
1799 		bpf_object__for_each_program(prog, obj) {
1800 			printf("\t\tstruct bpf_program *%s;\n",
1801 				bpf_program__name(prog));
1802 		}
1803 		printf("\t} progs;\n");
1804 	}
1805 
1806 	err = codegen_subskel_datasecs(obj, obj_name);
1807 	if (err)
1808 		goto out;
1809 
1810 	/* emit code that will allocate enough storage for all symbols */
1811 	codegen("\
1812 		\n\
1813 									    \n\
1814 		#ifdef __cplusplus					    \n\
1815 			static inline struct %1$s *open(const struct bpf_object *src);\n\
1816 			static inline void destroy(struct %1$s *skel);	    \n\
1817 		#endif /* __cplusplus */				    \n\
1818 		};							    \n\
1819 									    \n\
1820 		static inline void					    \n\
1821 		%1$s__destroy(struct %1$s *skel)			    \n\
1822 		{							    \n\
1823 			if (!skel)					    \n\
1824 				return;					    \n\
1825 			if (skel->subskel)				    \n\
1826 				bpf_object__destroy_subskeleton(skel->subskel);\n\
1827 			free(skel);					    \n\
1828 		}							    \n\
1829 									    \n\
1830 		static inline struct %1$s *				    \n\
1831 		%1$s__open(const struct bpf_object *src)		    \n\
1832 		{							    \n\
1833 			struct %1$s *obj;				    \n\
1834 			struct bpf_object_subskeleton *s;		    \n\
1835 			struct bpf_map_skeleton *map __attribute__((unused));\n\
1836 			int err;					    \n\
1837 									    \n\
1838 			obj = (struct %1$s *)calloc(1, sizeof(*obj));	    \n\
1839 			if (!obj) {					    \n\
1840 				err = -ENOMEM;				    \n\
1841 				goto err;				    \n\
1842 			}						    \n\
1843 			s = (struct bpf_object_subskeleton *)calloc(1, sizeof(*s));\n\
1844 			if (!s) {					    \n\
1845 				err = -ENOMEM;				    \n\
1846 				goto err;				    \n\
1847 			}						    \n\
1848 			s->sz = sizeof(*s);				    \n\
1849 			s->obj = src;					    \n\
1850 			s->var_skel_sz = sizeof(*s->vars);		    \n\
1851 			obj->subskel = s;				    \n\
1852 									    \n\
1853 			/* vars */					    \n\
1854 			s->var_cnt = %2$d;				    \n\
1855 			s->vars = (struct bpf_var_skeleton *)calloc(%2$d, sizeof(*s->vars));\n\
1856 			if (!s->vars) {					    \n\
1857 				err = -ENOMEM;				    \n\
1858 				goto err;				    \n\
1859 			}						    \n\
1860 		",
1861 		obj_name, var_cnt
1862 	);
1863 
1864 	/* walk through each symbol and emit the runtime representation */
1865 	bpf_object__for_each_map(map, obj) {
1866 		if (!is_mmapable_map(map, ident, sizeof(ident)))
1867 			continue;
1868 
1869 		map_type_id = bpf_map__btf_value_type_id(map);
1870 		if (map_type_id <= 0)
1871 			/* skip over internal maps with no type*/
1872 			continue;
1873 
1874 		map_type = btf__type_by_id(btf, map_type_id);
1875 		var = btf_var_secinfos(map_type);
1876 		len = btf_vlen(map_type);
1877 		for (i = 0; i < len; i++, var++) {
1878 			var_type = btf__type_by_id(btf, var->type);
1879 			var_name = btf__name_by_offset(btf, var_type->name_off);
1880 
1881 			if (btf_var(var_type)->linkage == BTF_VAR_STATIC)
1882 				continue;
1883 
1884 			/* Note that we use the dot prefix in .data as the
1885 			 * field access operator i.e. maps%s becomes maps.data
1886 			 */
1887 			codegen("\
1888 			\n\
1889 									    \n\
1890 				s->vars[%3$d].name = \"%1$s\";		    \n\
1891 				s->vars[%3$d].map = &obj->maps.%2$s;	    \n\
1892 				s->vars[%3$d].addr = (void **) &obj->%2$s.%1$s;\n\
1893 			", var_name, ident, var_idx);
1894 
1895 			var_idx++;
1896 		}
1897 	}
1898 
1899 	codegen_maps_skeleton(obj, map_cnt, false /*mmaped*/, false /*links*/);
1900 	codegen_progs_skeleton(obj, prog_cnt, false /*links*/);
1901 
1902 	codegen("\
1903 		\n\
1904 									    \n\
1905 			err = bpf_object__open_subskeleton(s);		    \n\
1906 			if (err)					    \n\
1907 				goto err;				    \n\
1908 									    \n\
1909 		");
1910 
1911 	gen_st_ops_shadow_init(btf, obj);
1912 
1913 	codegen("\
1914 		\n\
1915 			return obj;					    \n\
1916 		err:							    \n\
1917 			%1$s__destroy(obj);				    \n\
1918 			errno = -err;					    \n\
1919 			return NULL;					    \n\
1920 		}							    \n\
1921 									    \n\
1922 		#ifdef __cplusplus					    \n\
1923 		struct %1$s *%1$s::open(const struct bpf_object *src) { return %1$s__open(src); }\n\
1924 		void %1$s::destroy(struct %1$s *skel) { %1$s__destroy(skel); }\n\
1925 		#endif /* __cplusplus */				    \n\
1926 									    \n\
1927 		#endif /* %2$s */					    \n\
1928 		",
1929 		obj_name, header_guard);
1930 	err = 0;
1931 out:
1932 	bpf_object__close(obj);
1933 	if (obj_data)
1934 		munmap(obj_data, mmap_sz);
1935 	close(fd);
1936 	return err;
1937 }
1938 
1939 static int do_object(int argc, char **argv)
1940 {
1941 	struct bpf_linker *linker;
1942 	const char *output_file, *file;
1943 	int err = 0;
1944 
1945 	if (!REQ_ARGS(2)) {
1946 		usage();
1947 		return -1;
1948 	}
1949 
1950 	output_file = GET_ARG();
1951 
1952 	linker = bpf_linker__new(output_file, NULL);
1953 	if (!linker) {
1954 		p_err("failed to create BPF linker instance");
1955 		return -1;
1956 	}
1957 
1958 	while (argc) {
1959 		file = GET_ARG();
1960 
1961 		err = bpf_linker__add_file(linker, file, NULL);
1962 		if (err) {
1963 			p_err("failed to link '%s': %s (%d)", file, strerror(errno), errno);
1964 			goto out;
1965 		}
1966 	}
1967 
1968 	err = bpf_linker__finalize(linker);
1969 	if (err) {
1970 		p_err("failed to finalize ELF file: %s (%d)", strerror(errno), errno);
1971 		goto out;
1972 	}
1973 
1974 	err = 0;
1975 out:
1976 	bpf_linker__free(linker);
1977 	return err;
1978 }
1979 
1980 static int do_help(int argc, char **argv)
1981 {
1982 	if (json_output) {
1983 		jsonw_null(json_wtr);
1984 		return 0;
1985 	}
1986 
1987 	fprintf(stderr,
1988 		"Usage: %1$s %2$s object OUTPUT_FILE INPUT_FILE [INPUT_FILE...]\n"
1989 		"       %1$s %2$s skeleton FILE [name OBJECT_NAME]\n"
1990 		"       %1$s %2$s subskeleton FILE [name OBJECT_NAME]\n"
1991 		"       %1$s %2$s min_core_btf INPUT OUTPUT OBJECT [OBJECT...]\n"
1992 		"       %1$s %2$s help\n"
1993 		"\n"
1994 		"       " HELP_SPEC_OPTIONS " |\n"
1995 		"                    {-L|--use-loader} | [ {-S|--sign } {-k} <private_key.pem> {-i} <certificate.x509> ]}\n"
1996 		"",
1997 		bin_name, "gen");
1998 
1999 	return 0;
2000 }
2001 
2002 static int btf_save_raw(const struct btf *btf, const char *path)
2003 {
2004 	const void *data;
2005 	FILE *f = NULL;
2006 	__u32 data_sz;
2007 	int err = 0;
2008 
2009 	data = btf__raw_data(btf, &data_sz);
2010 	if (!data)
2011 		return -ENOMEM;
2012 
2013 	f = fopen(path, "wb");
2014 	if (!f)
2015 		return -errno;
2016 
2017 	if (fwrite(data, 1, data_sz, f) != data_sz)
2018 		err = -errno;
2019 
2020 	fclose(f);
2021 	return err;
2022 }
2023 
2024 struct btfgen_info {
2025 	struct btf *src_btf;
2026 	struct btf *marked_btf; /* btf structure used to mark used types */
2027 };
2028 
2029 static size_t btfgen_hash_fn(long key, void *ctx)
2030 {
2031 	return key;
2032 }
2033 
2034 static bool btfgen_equal_fn(long k1, long k2, void *ctx)
2035 {
2036 	return k1 == k2;
2037 }
2038 
2039 static void btfgen_free_info(struct btfgen_info *info)
2040 {
2041 	if (!info)
2042 		return;
2043 
2044 	btf__free(info->src_btf);
2045 	btf__free(info->marked_btf);
2046 
2047 	free(info);
2048 }
2049 
2050 static struct btfgen_info *
2051 btfgen_new_info(const char *targ_btf_path)
2052 {
2053 	struct btfgen_info *info;
2054 	int err;
2055 
2056 	info = calloc(1, sizeof(*info));
2057 	if (!info)
2058 		return NULL;
2059 
2060 	info->src_btf = btf__parse(targ_btf_path, NULL);
2061 	if (!info->src_btf) {
2062 		err = -errno;
2063 		p_err("failed parsing '%s' BTF file: %s", targ_btf_path, strerror(errno));
2064 		goto err_out;
2065 	}
2066 
2067 	info->marked_btf = btf__parse(targ_btf_path, NULL);
2068 	if (!info->marked_btf) {
2069 		err = -errno;
2070 		p_err("failed parsing '%s' BTF file: %s", targ_btf_path, strerror(errno));
2071 		goto err_out;
2072 	}
2073 
2074 	return info;
2075 
2076 err_out:
2077 	btfgen_free_info(info);
2078 	errno = -err;
2079 	return NULL;
2080 }
2081 
2082 #define MARKED UINT32_MAX
2083 
2084 static void btfgen_mark_member(struct btfgen_info *info, int type_id, int idx)
2085 {
2086 	const struct btf_type *t = btf__type_by_id(info->marked_btf, type_id);
2087 	struct btf_member *m = btf_members(t) + idx;
2088 
2089 	m->name_off = MARKED;
2090 }
2091 
2092 static int
2093 btfgen_mark_type(struct btfgen_info *info, unsigned int type_id, bool follow_pointers)
2094 {
2095 	const struct btf_type *btf_type = btf__type_by_id(info->src_btf, type_id);
2096 	struct btf_type *cloned_type;
2097 	struct btf_param *param;
2098 	struct btf_array *array;
2099 	__u32 i;
2100 	int err;
2101 
2102 	if (type_id == 0)
2103 		return 0;
2104 
2105 	/* mark type on cloned BTF as used */
2106 	cloned_type = (struct btf_type *) btf__type_by_id(info->marked_btf, type_id);
2107 	cloned_type->name_off = MARKED;
2108 
2109 	/* recursively mark other types needed by it */
2110 	switch (btf_kind(btf_type)) {
2111 	case BTF_KIND_UNKN:
2112 	case BTF_KIND_INT:
2113 	case BTF_KIND_FLOAT:
2114 	case BTF_KIND_ENUM:
2115 	case BTF_KIND_ENUM64:
2116 	case BTF_KIND_STRUCT:
2117 	case BTF_KIND_UNION:
2118 		break;
2119 	case BTF_KIND_PTR:
2120 		if (follow_pointers) {
2121 			err = btfgen_mark_type(info, btf_type->type, follow_pointers);
2122 			if (err)
2123 				return err;
2124 		}
2125 		break;
2126 	case BTF_KIND_CONST:
2127 	case BTF_KIND_RESTRICT:
2128 	case BTF_KIND_VOLATILE:
2129 	case BTF_KIND_TYPEDEF:
2130 		err = btfgen_mark_type(info, btf_type->type, follow_pointers);
2131 		if (err)
2132 			return err;
2133 		break;
2134 	case BTF_KIND_ARRAY:
2135 		array = btf_array(btf_type);
2136 
2137 		/* mark array type */
2138 		err = btfgen_mark_type(info, array->type, follow_pointers);
2139 		/* mark array's index type */
2140 		err = err ? : btfgen_mark_type(info, array->index_type, follow_pointers);
2141 		if (err)
2142 			return err;
2143 		break;
2144 	case BTF_KIND_FUNC_PROTO:
2145 		/* mark ret type */
2146 		err = btfgen_mark_type(info, btf_type->type, follow_pointers);
2147 		if (err)
2148 			return err;
2149 
2150 		/* mark parameters types */
2151 		param = btf_params(btf_type);
2152 		for (i = 0; i < btf_vlen(btf_type); i++) {
2153 			err = btfgen_mark_type(info, param->type, follow_pointers);
2154 			if (err)
2155 				return err;
2156 			param++;
2157 		}
2158 		break;
2159 	/* tells if some other type needs to be handled */
2160 	default:
2161 		p_err("unsupported kind: %s (%u)", btf_kind_str(btf_type), type_id);
2162 		return -EINVAL;
2163 	}
2164 
2165 	return 0;
2166 }
2167 
2168 static int btfgen_record_field_relo(struct btfgen_info *info, struct bpf_core_spec *targ_spec)
2169 {
2170 	struct btf *btf = info->src_btf;
2171 	const struct btf_type *btf_type;
2172 	struct btf_member *btf_member;
2173 	struct btf_array *array;
2174 	unsigned int type_id = targ_spec->root_type_id;
2175 	int idx, err;
2176 
2177 	/* mark root type */
2178 	btf_type = btf__type_by_id(btf, type_id);
2179 	err = btfgen_mark_type(info, type_id, false);
2180 	if (err)
2181 		return err;
2182 
2183 	/* mark types for complex types (arrays, unions, structures) */
2184 	for (int i = 1; i < targ_spec->raw_len; i++) {
2185 		/* skip typedefs and mods */
2186 		while (btf_is_mod(btf_type) || btf_is_typedef(btf_type)) {
2187 			type_id = btf_type->type;
2188 			btf_type = btf__type_by_id(btf, type_id);
2189 		}
2190 
2191 		switch (btf_kind(btf_type)) {
2192 		case BTF_KIND_STRUCT:
2193 		case BTF_KIND_UNION:
2194 			idx = targ_spec->raw_spec[i];
2195 			btf_member = btf_members(btf_type) + idx;
2196 
2197 			/* mark member */
2198 			btfgen_mark_member(info, type_id, idx);
2199 
2200 			/* mark member's type */
2201 			type_id = btf_member->type;
2202 			btf_type = btf__type_by_id(btf, type_id);
2203 			err = btfgen_mark_type(info, type_id, false);
2204 			if (err)
2205 				return err;
2206 			break;
2207 		case BTF_KIND_ARRAY:
2208 			array = btf_array(btf_type);
2209 			type_id = array->type;
2210 			btf_type = btf__type_by_id(btf, type_id);
2211 			break;
2212 		default:
2213 			p_err("unsupported kind: %s (%u)",
2214 			      btf_kind_str(btf_type), btf_type->type);
2215 			return -EINVAL;
2216 		}
2217 	}
2218 
2219 	return 0;
2220 }
2221 
2222 /* Mark types, members, and member types. Compared to btfgen_record_field_relo,
2223  * this function does not rely on the target spec for inferring members, but
2224  * uses the associated BTF.
2225  *
2226  * The `behind_ptr` argument is used to stop marking of composite types reached
2227  * through a pointer. This way, we can keep BTF size in check while providing
2228  * reasonable match semantics.
2229  */
2230 static int btfgen_mark_type_match(struct btfgen_info *info, __u32 type_id, bool behind_ptr)
2231 {
2232 	const struct btf_type *btf_type;
2233 	struct btf *btf = info->src_btf;
2234 	struct btf_type *cloned_type;
2235 	int err;
2236 	__u32 i;
2237 
2238 	if (type_id == 0)
2239 		return 0;
2240 
2241 	btf_type = btf__type_by_id(btf, type_id);
2242 	/* mark type on cloned BTF as used */
2243 	cloned_type = (struct btf_type *)btf__type_by_id(info->marked_btf, type_id);
2244 	cloned_type->name_off = MARKED;
2245 
2246 	switch (btf_kind(btf_type)) {
2247 	case BTF_KIND_UNKN:
2248 	case BTF_KIND_INT:
2249 	case BTF_KIND_FLOAT:
2250 	case BTF_KIND_ENUM:
2251 	case BTF_KIND_ENUM64:
2252 		break;
2253 	case BTF_KIND_STRUCT:
2254 	case BTF_KIND_UNION: {
2255 		struct btf_member *m = btf_members(btf_type);
2256 		__u32 vlen = btf_vlen(btf_type);
2257 
2258 		if (behind_ptr)
2259 			break;
2260 
2261 		for (i = 0; i < vlen; i++, m++) {
2262 			/* mark member */
2263 			btfgen_mark_member(info, type_id, i);
2264 
2265 			/* mark member's type */
2266 			err = btfgen_mark_type_match(info, m->type, false);
2267 			if (err)
2268 				return err;
2269 		}
2270 		break;
2271 	}
2272 	case BTF_KIND_CONST:
2273 	case BTF_KIND_FWD:
2274 	case BTF_KIND_RESTRICT:
2275 	case BTF_KIND_TYPEDEF:
2276 	case BTF_KIND_VOLATILE:
2277 		return btfgen_mark_type_match(info, btf_type->type, behind_ptr);
2278 	case BTF_KIND_PTR:
2279 		return btfgen_mark_type_match(info, btf_type->type, true);
2280 	case BTF_KIND_ARRAY: {
2281 		struct btf_array *array;
2282 
2283 		array = btf_array(btf_type);
2284 		/* mark array type */
2285 		err = btfgen_mark_type_match(info, array->type, false);
2286 		/* mark array's index type */
2287 		err = err ? : btfgen_mark_type_match(info, array->index_type, false);
2288 		if (err)
2289 			return err;
2290 		break;
2291 	}
2292 	case BTF_KIND_FUNC_PROTO: {
2293 		__u32 vlen = btf_vlen(btf_type);
2294 		struct btf_param *param;
2295 
2296 		/* mark ret type */
2297 		err = btfgen_mark_type_match(info, btf_type->type, false);
2298 		if (err)
2299 			return err;
2300 
2301 		/* mark parameters types */
2302 		param = btf_params(btf_type);
2303 		for (i = 0; i < vlen; i++) {
2304 			err = btfgen_mark_type_match(info, param->type, false);
2305 			if (err)
2306 				return err;
2307 			param++;
2308 		}
2309 		break;
2310 	}
2311 	/* tells if some other type needs to be handled */
2312 	default:
2313 		p_err("unsupported kind: %s (%u)", btf_kind_str(btf_type), type_id);
2314 		return -EINVAL;
2315 	}
2316 
2317 	return 0;
2318 }
2319 
2320 /* Mark types, members, and member types. Compared to btfgen_record_field_relo,
2321  * this function does not rely on the target spec for inferring members, but
2322  * uses the associated BTF.
2323  */
2324 static int btfgen_record_type_match_relo(struct btfgen_info *info, struct bpf_core_spec *targ_spec)
2325 {
2326 	return btfgen_mark_type_match(info, targ_spec->root_type_id, false);
2327 }
2328 
2329 static int btfgen_record_type_relo(struct btfgen_info *info, struct bpf_core_spec *targ_spec)
2330 {
2331 	return btfgen_mark_type(info, targ_spec->root_type_id, true);
2332 }
2333 
2334 static int btfgen_record_enumval_relo(struct btfgen_info *info, struct bpf_core_spec *targ_spec)
2335 {
2336 	return btfgen_mark_type(info, targ_spec->root_type_id, false);
2337 }
2338 
2339 static int btfgen_record_reloc(struct btfgen_info *info, struct bpf_core_spec *res)
2340 {
2341 	switch (res->relo_kind) {
2342 	case BPF_CORE_FIELD_BYTE_OFFSET:
2343 	case BPF_CORE_FIELD_BYTE_SIZE:
2344 	case BPF_CORE_FIELD_EXISTS:
2345 	case BPF_CORE_FIELD_SIGNED:
2346 	case BPF_CORE_FIELD_LSHIFT_U64:
2347 	case BPF_CORE_FIELD_RSHIFT_U64:
2348 		return btfgen_record_field_relo(info, res);
2349 	case BPF_CORE_TYPE_ID_LOCAL: /* BPF_CORE_TYPE_ID_LOCAL doesn't require kernel BTF */
2350 		return 0;
2351 	case BPF_CORE_TYPE_ID_TARGET:
2352 	case BPF_CORE_TYPE_EXISTS:
2353 	case BPF_CORE_TYPE_SIZE:
2354 		return btfgen_record_type_relo(info, res);
2355 	case BPF_CORE_TYPE_MATCHES:
2356 		return btfgen_record_type_match_relo(info, res);
2357 	case BPF_CORE_ENUMVAL_EXISTS:
2358 	case BPF_CORE_ENUMVAL_VALUE:
2359 		return btfgen_record_enumval_relo(info, res);
2360 	default:
2361 		return -EINVAL;
2362 	}
2363 }
2364 
2365 static struct bpf_core_cand_list *
2366 btfgen_find_cands(const struct btf *local_btf, const struct btf *targ_btf, __u32 local_id)
2367 {
2368 	const struct btf_type *local_type;
2369 	struct bpf_core_cand_list *cands = NULL;
2370 	struct bpf_core_cand local_cand = {};
2371 	size_t local_essent_len;
2372 	const char *local_name;
2373 	int err;
2374 
2375 	local_cand.btf = local_btf;
2376 	local_cand.id = local_id;
2377 
2378 	local_type = btf__type_by_id(local_btf, local_id);
2379 	if (!local_type) {
2380 		err = -EINVAL;
2381 		goto err_out;
2382 	}
2383 
2384 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
2385 	if (!local_name) {
2386 		err = -EINVAL;
2387 		goto err_out;
2388 	}
2389 	local_essent_len = bpf_core_essential_name_len(local_name);
2390 
2391 	cands = calloc(1, sizeof(*cands));
2392 	if (!cands)
2393 		return NULL;
2394 
2395 	err = bpf_core_add_cands(&local_cand, local_essent_len, targ_btf, "vmlinux", 1, cands);
2396 	if (err)
2397 		goto err_out;
2398 
2399 	return cands;
2400 
2401 err_out:
2402 	bpf_core_free_cands(cands);
2403 	errno = -err;
2404 	return NULL;
2405 }
2406 
2407 /* Record relocation information for a single BPF object */
2408 static int btfgen_record_obj(struct btfgen_info *info, const char *obj_path)
2409 {
2410 	const struct btf_ext_info_sec *sec;
2411 	const struct bpf_core_relo *relo;
2412 	const struct btf_ext_info *seg;
2413 	struct hashmap_entry *entry;
2414 	struct hashmap *cand_cache = NULL;
2415 	struct btf_ext *btf_ext = NULL;
2416 	unsigned int relo_idx;
2417 	struct btf *btf = NULL;
2418 	size_t i;
2419 	int err;
2420 
2421 	btf = btf__parse(obj_path, &btf_ext);
2422 	if (!btf) {
2423 		err = -errno;
2424 		p_err("failed to parse BPF object '%s': %s", obj_path, strerror(errno));
2425 		return err;
2426 	}
2427 
2428 	if (!btf_ext) {
2429 		p_err("failed to parse BPF object '%s': section %s not found",
2430 		      obj_path, BTF_EXT_ELF_SEC);
2431 		err = -EINVAL;
2432 		goto out;
2433 	}
2434 
2435 	if (btf_ext->core_relo_info.len == 0) {
2436 		err = 0;
2437 		goto out;
2438 	}
2439 
2440 	cand_cache = hashmap__new(btfgen_hash_fn, btfgen_equal_fn, NULL);
2441 	if (IS_ERR(cand_cache)) {
2442 		err = PTR_ERR(cand_cache);
2443 		goto out;
2444 	}
2445 
2446 	seg = &btf_ext->core_relo_info;
2447 	for_each_btf_ext_sec(seg, sec) {
2448 		for_each_btf_ext_rec(seg, sec, relo_idx, relo) {
2449 			struct bpf_core_spec specs_scratch[3] = {};
2450 			struct bpf_core_relo_res targ_res = {};
2451 			struct bpf_core_cand_list *cands = NULL;
2452 			const char *sec_name = btf__name_by_offset(btf, sec->sec_name_off);
2453 
2454 			if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
2455 			    !hashmap__find(cand_cache, relo->type_id, &cands)) {
2456 				cands = btfgen_find_cands(btf, info->src_btf, relo->type_id);
2457 				if (!cands) {
2458 					err = -errno;
2459 					goto out;
2460 				}
2461 
2462 				err = hashmap__set(cand_cache, relo->type_id, cands,
2463 						   NULL, NULL);
2464 				if (err)
2465 					goto out;
2466 			}
2467 
2468 			err = bpf_core_calc_relo_insn(sec_name, relo, relo_idx, btf, cands,
2469 						      specs_scratch, &targ_res);
2470 			if (err)
2471 				goto out;
2472 
2473 			/* specs_scratch[2] is the target spec */
2474 			err = btfgen_record_reloc(info, &specs_scratch[2]);
2475 			if (err)
2476 				goto out;
2477 		}
2478 	}
2479 
2480 out:
2481 	btf__free(btf);
2482 	btf_ext__free(btf_ext);
2483 
2484 	if (!IS_ERR_OR_NULL(cand_cache)) {
2485 		hashmap__for_each_entry(cand_cache, entry, i) {
2486 			bpf_core_free_cands(entry->pvalue);
2487 		}
2488 		hashmap__free(cand_cache);
2489 	}
2490 
2491 	return err;
2492 }
2493 
2494 /* Generate BTF from relocation information previously recorded */
2495 static struct btf *btfgen_get_btf(struct btfgen_info *info)
2496 {
2497 	struct btf *btf_new = NULL;
2498 	unsigned int *ids = NULL;
2499 	unsigned int n = btf__type_cnt(info->marked_btf);
2500 	int err = 0;
2501 	__u32 i;
2502 
2503 	btf_new = btf__new_empty();
2504 	if (!btf_new) {
2505 		err = -errno;
2506 		goto err_out;
2507 	}
2508 
2509 	ids = calloc(n, sizeof(*ids));
2510 	if (!ids) {
2511 		err = -errno;
2512 		goto err_out;
2513 	}
2514 
2515 	/* first pass: add all marked types to btf_new and add their new ids to the ids map */
2516 	for (i = 1; i < n; i++) {
2517 		const struct btf_type *cloned_type, *type;
2518 		const char *name;
2519 		int new_id;
2520 
2521 		cloned_type = btf__type_by_id(info->marked_btf, i);
2522 
2523 		if (cloned_type->name_off != MARKED)
2524 			continue;
2525 
2526 		type = btf__type_by_id(info->src_btf, i);
2527 
2528 		/* add members for struct and union */
2529 		if (btf_is_composite(type)) {
2530 			struct btf_member *cloned_m, *m;
2531 			__u32 vlen, idx_src;
2532 
2533 			name = btf__str_by_offset(info->src_btf, type->name_off);
2534 
2535 			if (btf_is_struct(type))
2536 				err = btf__add_struct(btf_new, name, type->size);
2537 			else
2538 				err = btf__add_union(btf_new, name, type->size);
2539 
2540 			if (err < 0)
2541 				goto err_out;
2542 			new_id = err;
2543 
2544 			cloned_m = btf_members(cloned_type);
2545 			m = btf_members(type);
2546 			vlen = btf_vlen(cloned_type);
2547 			for (idx_src = 0; idx_src < vlen; idx_src++, cloned_m++, m++) {
2548 				/* add only members that are marked as used */
2549 				if (cloned_m->name_off != MARKED)
2550 					continue;
2551 
2552 				name = btf__str_by_offset(info->src_btf, m->name_off);
2553 				err = btf__add_field(btf_new, name, m->type,
2554 						     btf_member_bit_offset(cloned_type, idx_src),
2555 						     btf_member_bitfield_size(cloned_type, idx_src));
2556 				if (err < 0)
2557 					goto err_out;
2558 			}
2559 		} else {
2560 			err = btf__add_type(btf_new, info->src_btf, type);
2561 			if (err < 0)
2562 				goto err_out;
2563 			new_id = err;
2564 		}
2565 
2566 		/* add ID mapping */
2567 		ids[i] = new_id;
2568 	}
2569 
2570 	/* second pass: fix up type ids */
2571 	for (i = 1; i < btf__type_cnt(btf_new); i++) {
2572 		struct btf_type *btf_type = (struct btf_type *) btf__type_by_id(btf_new, i);
2573 		struct btf_field_iter it;
2574 		__u32 *type_id;
2575 
2576 		err = btf_field_iter_init(&it, btf_type, BTF_FIELD_ITER_IDS);
2577 		if (err)
2578 			goto err_out;
2579 
2580 		while ((type_id = btf_field_iter_next(&it)))
2581 			*type_id = ids[*type_id];
2582 	}
2583 
2584 	free(ids);
2585 	return btf_new;
2586 
2587 err_out:
2588 	btf__free(btf_new);
2589 	free(ids);
2590 	errno = -err;
2591 	return NULL;
2592 }
2593 
2594 /* Create minimized BTF file for a set of BPF objects.
2595  *
2596  * The BTFGen algorithm is divided in two main parts: (1) collect the
2597  * BTF types that are involved in relocations and (2) generate the BTF
2598  * object using the collected types.
2599  *
2600  * In order to collect the types involved in the relocations, we parse
2601  * the BTF and BTF.ext sections of the BPF objects and use
2602  * bpf_core_calc_relo_insn() to get the target specification, this
2603  * indicates how the types and fields are used in a relocation.
2604  *
2605  * Types are recorded in different ways according to the kind of the
2606  * relocation. For field-based relocations only the members that are
2607  * actually used are saved in order to reduce the size of the generated
2608  * BTF file. For type-based relocations empty struct / unions are
2609  * generated and for enum-based relocations the whole type is saved.
2610  *
2611  * The second part of the algorithm generates the BTF object. It creates
2612  * an empty BTF object and fills it with the types recorded in the
2613  * previous step. This function takes care of only adding the structure
2614  * and union members that were marked as used and it also fixes up the
2615  * type IDs on the generated BTF object.
2616  */
2617 static int minimize_btf(const char *src_btf, const char *dst_btf, const char *objspaths[])
2618 {
2619 	struct btfgen_info *info;
2620 	struct btf *btf_new = NULL;
2621 	int err, i;
2622 
2623 	info = btfgen_new_info(src_btf);
2624 	if (!info) {
2625 		err = -errno;
2626 		p_err("failed to allocate info structure: %s", strerror(errno));
2627 		goto out;
2628 	}
2629 
2630 	for (i = 0; objspaths[i] != NULL; i++) {
2631 		err = btfgen_record_obj(info, objspaths[i]);
2632 		if (err) {
2633 			p_err("error recording relocations for %s: %s", objspaths[i],
2634 			      strerror(errno));
2635 			goto out;
2636 		}
2637 	}
2638 
2639 	btf_new = btfgen_get_btf(info);
2640 	if (!btf_new) {
2641 		err = -errno;
2642 		p_err("error generating BTF: %s", strerror(errno));
2643 		goto out;
2644 	}
2645 
2646 	err = btf_save_raw(btf_new, dst_btf);
2647 	if (err) {
2648 		p_err("error saving btf file: %s", strerror(errno));
2649 		goto out;
2650 	}
2651 
2652 out:
2653 	btf__free(btf_new);
2654 	btfgen_free_info(info);
2655 
2656 	return err;
2657 }
2658 
2659 static int do_min_core_btf(int argc, char **argv)
2660 {
2661 	const char *input, *output, **objs;
2662 	int i, err;
2663 
2664 	if (!REQ_ARGS(3)) {
2665 		usage();
2666 		return -1;
2667 	}
2668 
2669 	input = GET_ARG();
2670 	output = GET_ARG();
2671 
2672 	objs = (const char **) calloc(argc + 1, sizeof(*objs));
2673 	if (!objs) {
2674 		p_err("failed to allocate array for object names");
2675 		return -ENOMEM;
2676 	}
2677 
2678 	i = 0;
2679 	while (argc)
2680 		objs[i++] = GET_ARG();
2681 
2682 	err = minimize_btf(input, output, objs);
2683 	free(objs);
2684 	return err;
2685 }
2686 
2687 static const struct cmd cmds[] = {
2688 	{ "object",		do_object },
2689 	{ "skeleton",		do_skeleton },
2690 	{ "subskeleton",	do_subskeleton },
2691 	{ "min_core_btf",	do_min_core_btf},
2692 	{ "help",		do_help },
2693 	{ 0 }
2694 };
2695 
2696 int do_gen(int argc, char **argv)
2697 {
2698 	return cmd_select(cmds, argc, argv, do_help);
2699 }
2700