xref: /linux/tools/bpf/bpftool/gen.c (revision 39daa09d34ada1bc7227d68def63e0a2105b5496)
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$zd);\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_map *map;
692 	char ident[256];
693 	int err = 0;
694 
695 	err = bpf_object__gen_loader(obj, &opts);
696 	if (err)
697 		return err;
698 
699 	err = bpf_object__load(obj);
700 	if (err) {
701 		p_err("failed to load object file");
702 		goto out;
703 	}
704 	/* If there was no error during load then gen_loader_opts
705 	 * are populated with the loader program.
706 	 */
707 
708 	/* finish generating 'struct skel' */
709 	codegen("\
710 		\n\
711 		};							    \n\
712 		", obj_name);
713 
714 
715 	codegen_attach_detach(obj, obj_name);
716 
717 	codegen_destroy(obj, obj_name);
718 
719 	codegen("\
720 		\n\
721 		static inline struct %1$s *				    \n\
722 		%1$s__open(void)					    \n\
723 		{							    \n\
724 			struct %1$s *skel;				    \n\
725 									    \n\
726 			skel = skel_alloc(sizeof(*skel));		    \n\
727 			if (!skel)					    \n\
728 				goto cleanup;				    \n\
729 			skel->ctx.sz = (void *)&skel->links - (void *)skel; \n\
730 		",
731 		obj_name, opts.data_sz);
732 	bpf_object__for_each_map(map, obj) {
733 		const void *mmap_data = NULL;
734 		size_t mmap_size = 0;
735 
736 		if (!is_mmapable_map(map, ident, sizeof(ident)))
737 			continue;
738 
739 		codegen("\
740 		\n\
741 			{						    \n\
742 				static const char data[] __attribute__((__aligned__(8))) = \"\\\n\
743 		");
744 		mmap_data = bpf_map__initial_value(map, &mmap_size);
745 		print_hex(mmap_data, mmap_size);
746 		codegen("\
747 		\n\
748 		\";							    \n\
749 									    \n\
750 				skel->%1$s = skel_prep_map_data((void *)data, %2$zd,\n\
751 								sizeof(data) - 1);\n\
752 				if (!skel->%1$s)			    \n\
753 					goto cleanup;			    \n\
754 				skel->maps.%1$s.initial_value = (__u64) (long) skel->%1$s;\n\
755 			}						    \n\
756 			", ident, bpf_map_mmap_sz(map));
757 	}
758 	codegen("\
759 		\n\
760 			return skel;					    \n\
761 		cleanup:						    \n\
762 			%1$s__destroy(skel);				    \n\
763 			return NULL;					    \n\
764 		}							    \n\
765 									    \n\
766 		static inline int					    \n\
767 		%1$s__load(struct %1$s *skel)				    \n\
768 		{							    \n\
769 			struct bpf_load_and_run_opts opts = {};		    \n\
770 			int err;					    \n\
771 			static const char opts_data[] __attribute__((__aligned__(8))) = \"\\\n\
772 		",
773 		obj_name);
774 	print_hex(opts.data, opts.data_sz);
775 	codegen("\
776 		\n\
777 		\";							    \n\
778 			static const char opts_insn[] __attribute__((__aligned__(8))) = \"\\\n\
779 		");
780 	print_hex(opts.insns, opts.insns_sz);
781 	codegen("\
782 		\n\
783 		\";							    \n\
784 									    \n\
785 			opts.ctx = (struct bpf_loader_ctx *)skel;	    \n\
786 			opts.data_sz = sizeof(opts_data) - 1;		    \n\
787 			opts.data = (void *)opts_data;			    \n\
788 			opts.insns_sz = sizeof(opts_insn) - 1;		    \n\
789 			opts.insns = (void *)opts_insn;			    \n\
790 									    \n\
791 			err = bpf_load_and_run(&opts);			    \n\
792 			if (err < 0)					    \n\
793 				return err;				    \n\
794 		");
795 	bpf_object__for_each_map(map, obj) {
796 		const char *mmap_flags;
797 
798 		if (!is_mmapable_map(map, ident, sizeof(ident)))
799 			continue;
800 
801 		if (bpf_map__map_flags(map) & BPF_F_RDONLY_PROG)
802 			mmap_flags = "PROT_READ";
803 		else
804 			mmap_flags = "PROT_READ | PROT_WRITE";
805 
806 		codegen("\
807 		\n\
808 			skel->%1$s = skel_finalize_map_data(&skel->maps.%1$s.initial_value,  \n\
809 							%2$zd, %3$s, skel->maps.%1$s.map_fd);\n\
810 			if (!skel->%1$s)				    \n\
811 				return -ENOMEM;				    \n\
812 			",
813 		       ident, bpf_map_mmap_sz(map), mmap_flags);
814 	}
815 	codegen("\
816 		\n\
817 			return 0;					    \n\
818 		}							    \n\
819 									    \n\
820 		static inline struct %1$s *				    \n\
821 		%1$s__open_and_load(void)				    \n\
822 		{							    \n\
823 			struct %1$s *skel;				    \n\
824 									    \n\
825 			skel = %1$s__open();				    \n\
826 			if (!skel)					    \n\
827 				return NULL;				    \n\
828 			if (%1$s__load(skel)) {				    \n\
829 				%1$s__destroy(skel);			    \n\
830 				return NULL;				    \n\
831 			}						    \n\
832 			return skel;					    \n\
833 		}							    \n\
834 									    \n\
835 		", obj_name);
836 
837 	codegen_asserts(obj, obj_name);
838 
839 	codegen("\
840 		\n\
841 									    \n\
842 		#endif /* %s */						    \n\
843 		",
844 		header_guard);
845 	err = 0;
846 out:
847 	return err;
848 }
849 
850 static void
851 codegen_maps_skeleton(struct bpf_object *obj, size_t map_cnt, bool mmaped, bool populate_links)
852 {
853 	struct bpf_map *map;
854 	char ident[256];
855 	size_t i;
856 
857 	if (!map_cnt)
858 		return;
859 
860 	codegen("\
861 		\n\
862 									\n\
863 			/* maps */				    \n\
864 			s->map_cnt = %zu;			    \n\
865 			s->map_skel_sz = sizeof(*s->maps);	    \n\
866 			s->maps = (struct bpf_map_skeleton *)calloc(s->map_cnt, s->map_skel_sz);\n\
867 			if (!s->maps) {				    \n\
868 				err = -ENOMEM;			    \n\
869 				goto err;			    \n\
870 			}					    \n\
871 		",
872 		map_cnt
873 	);
874 	i = 0;
875 	bpf_object__for_each_map(map, obj) {
876 		if (!get_map_ident(map, ident, sizeof(ident)))
877 			continue;
878 
879 		codegen("\
880 			\n\
881 									\n\
882 				s->maps[%zu].name = \"%s\";	    \n\
883 				s->maps[%zu].map = &obj->maps.%s;   \n\
884 			",
885 			i, bpf_map__name(map), i, ident);
886 		/* memory-mapped internal maps */
887 		if (mmaped && is_mmapable_map(map, ident, sizeof(ident))) {
888 			printf("\ts->maps[%zu].mmaped = (void **)&obj->%s;\n",
889 				i, ident);
890 		}
891 
892 		if (populate_links && bpf_map__type(map) == BPF_MAP_TYPE_STRUCT_OPS) {
893 			codegen("\
894 				\n\
895 					s->maps[%zu].link = &obj->links.%s;\n\
896 				",
897 				i, ident);
898 		}
899 		i++;
900 	}
901 }
902 
903 static void
904 codegen_progs_skeleton(struct bpf_object *obj, size_t prog_cnt, bool populate_links)
905 {
906 	struct bpf_program *prog;
907 	int i;
908 
909 	if (!prog_cnt)
910 		return;
911 
912 	codegen("\
913 		\n\
914 									\n\
915 			/* programs */				    \n\
916 			s->prog_cnt = %zu;			    \n\
917 			s->prog_skel_sz = sizeof(*s->progs);	    \n\
918 			s->progs = (struct bpf_prog_skeleton *)calloc(s->prog_cnt, s->prog_skel_sz);\n\
919 			if (!s->progs) {			    \n\
920 				err = -ENOMEM;			    \n\
921 				goto err;			    \n\
922 			}					    \n\
923 		",
924 		prog_cnt
925 	);
926 	i = 0;
927 	bpf_object__for_each_program(prog, obj) {
928 		codegen("\
929 			\n\
930 									\n\
931 				s->progs[%1$zu].name = \"%2$s\";    \n\
932 				s->progs[%1$zu].prog = &obj->progs.%2$s;\n\
933 			",
934 			i, bpf_program__name(prog));
935 
936 		if (populate_links) {
937 			codegen("\
938 				\n\
939 					s->progs[%1$zu].link = &obj->links.%2$s;\n\
940 				",
941 				i, bpf_program__name(prog));
942 		}
943 		i++;
944 	}
945 }
946 
947 static int walk_st_ops_shadow_vars(struct btf *btf, const char *ident,
948 				   const struct btf_type *map_type, __u32 map_type_id)
949 {
950 	LIBBPF_OPTS(btf_dump_emit_type_decl_opts, opts, .indent_level = 3);
951 	const struct btf_type *member_type;
952 	__u32 offset, next_offset = 0;
953 	const struct btf_member *m;
954 	struct btf_dump *d = NULL;
955 	const char *member_name;
956 	__u32 member_type_id;
957 	int i, err = 0, n;
958 	int size;
959 
960 	d = btf_dump__new(btf, codegen_btf_dump_printf, NULL, NULL);
961 	if (!d)
962 		return -errno;
963 
964 	n = btf_vlen(map_type);
965 	for (i = 0, m = btf_members(map_type); i < n; i++, m++) {
966 		member_type = skip_mods_and_typedefs(btf, m->type, &member_type_id);
967 		member_name = btf__name_by_offset(btf, m->name_off);
968 
969 		offset = m->offset / 8;
970 		if (next_offset < offset)
971 			printf("\t\t\tchar __padding_%d[%d];\n", i, offset - next_offset);
972 
973 		switch (btf_kind(member_type)) {
974 		case BTF_KIND_INT:
975 		case BTF_KIND_FLOAT:
976 		case BTF_KIND_ENUM:
977 		case BTF_KIND_ENUM64:
978 			/* scalar type */
979 			printf("\t\t\t");
980 			opts.field_name = member_name;
981 			err = btf_dump__emit_type_decl(d, member_type_id, &opts);
982 			if (err) {
983 				p_err("Failed to emit type declaration for %s: %d", member_name, err);
984 				goto out;
985 			}
986 			printf(";\n");
987 
988 			size = btf__resolve_size(btf, member_type_id);
989 			if (size < 0) {
990 				p_err("Failed to resolve size of %s: %d\n", member_name, size);
991 				err = size;
992 				goto out;
993 			}
994 
995 			next_offset = offset + size;
996 			break;
997 
998 		case BTF_KIND_PTR:
999 			if (resolve_func_ptr(btf, m->type, NULL)) {
1000 				/* Function pointer */
1001 				printf("\t\t\tstruct bpf_program *%s;\n", member_name);
1002 
1003 				next_offset = offset + sizeof(void *);
1004 				break;
1005 			}
1006 			/* All pointer types are unsupported except for
1007 			 * function pointers.
1008 			 */
1009 			fallthrough;
1010 
1011 		default:
1012 			/* Unsupported types
1013 			 *
1014 			 * Types other than scalar types and function
1015 			 * pointers are currently not supported in order to
1016 			 * prevent conflicts in the generated code caused
1017 			 * by multiple definitions. For instance, if the
1018 			 * struct type FOO is used in a struct_ops map,
1019 			 * bpftool has to generate definitions for FOO,
1020 			 * which may result in conflicts if FOO is defined
1021 			 * in different skeleton files.
1022 			 */
1023 			size = btf__resolve_size(btf, member_type_id);
1024 			if (size < 0) {
1025 				p_err("Failed to resolve size of %s: %d\n", member_name, size);
1026 				err = size;
1027 				goto out;
1028 			}
1029 			printf("\t\t\tchar __unsupported_%d[%d];\n", i, size);
1030 
1031 			next_offset = offset + size;
1032 			break;
1033 		}
1034 	}
1035 
1036 	/* Cannot fail since it must be a struct type */
1037 	size = btf__resolve_size(btf, map_type_id);
1038 	if (next_offset < (__u32)size)
1039 		printf("\t\t\tchar __padding_end[%d];\n", size - next_offset);
1040 
1041 out:
1042 	btf_dump__free(d);
1043 
1044 	return err;
1045 }
1046 
1047 /* Generate the pointer of the shadow type for a struct_ops map.
1048  *
1049  * This function adds a pointer of the shadow type for a struct_ops map.
1050  * The members of a struct_ops map can be exported through a pointer to a
1051  * shadow type. The user can access these members through the pointer.
1052  *
1053  * A shadow type includes not all members, only members of some types.
1054  * They are scalar types and function pointers. The function pointers are
1055  * translated to the pointer of the struct bpf_program. The scalar types
1056  * are translated to the original type without any modifiers.
1057  *
1058  * Unsupported types will be translated to a char array to occupy the same
1059  * space as the original field, being renamed as __unsupported_*.  The user
1060  * should treat these fields as opaque data.
1061  */
1062 static int gen_st_ops_shadow_type(const char *obj_name, struct btf *btf, const char *ident,
1063 				  const struct bpf_map *map)
1064 {
1065 	const struct btf_type *map_type;
1066 	const char *type_name;
1067 	__u32 map_type_id;
1068 	int err;
1069 
1070 	map_type_id = bpf_map__btf_value_type_id(map);
1071 	if (map_type_id == 0)
1072 		return -EINVAL;
1073 	map_type = btf__type_by_id(btf, map_type_id);
1074 	if (!map_type)
1075 		return -EINVAL;
1076 
1077 	type_name = btf__name_by_offset(btf, map_type->name_off);
1078 
1079 	printf("\t\tstruct %s__%s__%s {\n", obj_name, ident, type_name);
1080 
1081 	err = walk_st_ops_shadow_vars(btf, ident, map_type, map_type_id);
1082 	if (err)
1083 		return err;
1084 
1085 	printf("\t\t} *%s;\n", ident);
1086 
1087 	return 0;
1088 }
1089 
1090 static int gen_st_ops_shadow(const char *obj_name, struct btf *btf, struct bpf_object *obj)
1091 {
1092 	int err, st_ops_cnt = 0;
1093 	struct bpf_map *map;
1094 	char ident[256];
1095 
1096 	if (!btf)
1097 		return 0;
1098 
1099 	/* Generate the pointers to shadow types of
1100 	 * struct_ops maps.
1101 	 */
1102 	bpf_object__for_each_map(map, obj) {
1103 		if (bpf_map__type(map) != BPF_MAP_TYPE_STRUCT_OPS)
1104 			continue;
1105 		if (!get_map_ident(map, ident, sizeof(ident)))
1106 			continue;
1107 
1108 		if (st_ops_cnt == 0) /* first struct_ops map */
1109 			printf("\tstruct {\n");
1110 		st_ops_cnt++;
1111 
1112 		err = gen_st_ops_shadow_type(obj_name, btf, ident, map);
1113 		if (err)
1114 			return err;
1115 	}
1116 
1117 	if (st_ops_cnt)
1118 		printf("\t} struct_ops;\n");
1119 
1120 	return 0;
1121 }
1122 
1123 /* Generate the code to initialize the pointers of shadow types. */
1124 static void gen_st_ops_shadow_init(struct btf *btf, struct bpf_object *obj)
1125 {
1126 	struct bpf_map *map;
1127 	char ident[256];
1128 
1129 	if (!btf)
1130 		return;
1131 
1132 	/* Initialize the pointers to_ops shadow types of
1133 	 * struct_ops maps.
1134 	 */
1135 	bpf_object__for_each_map(map, obj) {
1136 		if (bpf_map__type(map) != BPF_MAP_TYPE_STRUCT_OPS)
1137 			continue;
1138 		if (!get_map_ident(map, ident, sizeof(ident)))
1139 			continue;
1140 		codegen("\
1141 			\n\
1142 				obj->struct_ops.%1$s = (__typeof__(obj->struct_ops.%1$s))\n\
1143 					bpf_map__initial_value(obj->maps.%1$s, NULL);\n\
1144 			\n\
1145 			", ident);
1146 	}
1147 }
1148 
1149 static int do_skeleton(int argc, char **argv)
1150 {
1151 	char header_guard[MAX_OBJ_NAME_LEN + sizeof("__SKEL_H__")];
1152 	size_t map_cnt = 0, prog_cnt = 0, attach_map_cnt = 0, file_sz, mmap_sz;
1153 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts);
1154 	char obj_name[MAX_OBJ_NAME_LEN] = "", *obj_data;
1155 	struct bpf_object *obj = NULL;
1156 	const char *file;
1157 	char ident[256];
1158 	struct bpf_program *prog;
1159 	int fd, err = -1;
1160 	struct bpf_map *map;
1161 	struct btf *btf;
1162 	struct stat st;
1163 
1164 	if (!REQ_ARGS(1)) {
1165 		usage();
1166 		return -1;
1167 	}
1168 	file = GET_ARG();
1169 
1170 	while (argc) {
1171 		if (!REQ_ARGS(2))
1172 			return -1;
1173 
1174 		if (is_prefix(*argv, "name")) {
1175 			NEXT_ARG();
1176 
1177 			if (obj_name[0] != '\0') {
1178 				p_err("object name already specified");
1179 				return -1;
1180 			}
1181 
1182 			strncpy(obj_name, *argv, MAX_OBJ_NAME_LEN - 1);
1183 			obj_name[MAX_OBJ_NAME_LEN - 1] = '\0';
1184 		} else {
1185 			p_err("unknown arg %s", *argv);
1186 			return -1;
1187 		}
1188 
1189 		NEXT_ARG();
1190 	}
1191 
1192 	if (argc) {
1193 		p_err("extra unknown arguments");
1194 		return -1;
1195 	}
1196 
1197 	if (stat(file, &st)) {
1198 		p_err("failed to stat() %s: %s", file, strerror(errno));
1199 		return -1;
1200 	}
1201 	file_sz = st.st_size;
1202 	mmap_sz = roundup(file_sz, sysconf(_SC_PAGE_SIZE));
1203 	fd = open(file, O_RDONLY);
1204 	if (fd < 0) {
1205 		p_err("failed to open() %s: %s", file, strerror(errno));
1206 		return -1;
1207 	}
1208 	obj_data = mmap(NULL, mmap_sz, PROT_READ, MAP_PRIVATE, fd, 0);
1209 	if (obj_data == MAP_FAILED) {
1210 		obj_data = NULL;
1211 		p_err("failed to mmap() %s: %s", file, strerror(errno));
1212 		goto out;
1213 	}
1214 	if (obj_name[0] == '\0')
1215 		get_obj_name(obj_name, file);
1216 	opts.object_name = obj_name;
1217 	if (verifier_logs)
1218 		/* log_level1 + log_level2 + stats, but not stable UAPI */
1219 		opts.kernel_log_level = 1 + 2 + 4;
1220 	obj = bpf_object__open_mem(obj_data, file_sz, &opts);
1221 	if (!obj) {
1222 		char err_buf[256];
1223 
1224 		err = -errno;
1225 		libbpf_strerror(err, err_buf, sizeof(err_buf));
1226 		p_err("failed to open BPF object file: %s", err_buf);
1227 		goto out;
1228 	}
1229 
1230 	bpf_object__for_each_map(map, obj) {
1231 		if (!get_map_ident(map, ident, sizeof(ident))) {
1232 			p_err("ignoring unrecognized internal map '%s'...",
1233 			      bpf_map__name(map));
1234 			continue;
1235 		}
1236 
1237 		if (bpf_map__type(map) == BPF_MAP_TYPE_STRUCT_OPS)
1238 			attach_map_cnt++;
1239 
1240 		map_cnt++;
1241 	}
1242 	bpf_object__for_each_program(prog, obj) {
1243 		prog_cnt++;
1244 	}
1245 
1246 	get_header_guard(header_guard, obj_name, "SKEL_H");
1247 	if (use_loader) {
1248 		codegen("\
1249 		\n\
1250 		/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */   \n\
1251 		/* THIS FILE IS AUTOGENERATED BY BPFTOOL! */		    \n\
1252 		#ifndef %2$s						    \n\
1253 		#define %2$s						    \n\
1254 									    \n\
1255 		#include <bpf/skel_internal.h>				    \n\
1256 									    \n\
1257 		struct %1$s {						    \n\
1258 			struct bpf_loader_ctx ctx;			    \n\
1259 		",
1260 		obj_name, header_guard
1261 		);
1262 	} else {
1263 		codegen("\
1264 		\n\
1265 		/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */   \n\
1266 									    \n\
1267 		/* THIS FILE IS AUTOGENERATED BY BPFTOOL! */		    \n\
1268 		#ifndef %2$s						    \n\
1269 		#define %2$s						    \n\
1270 									    \n\
1271 		#include <errno.h>					    \n\
1272 		#include <stdlib.h>					    \n\
1273 		#include <bpf/libbpf.h>					    \n\
1274 									    \n\
1275 		#define BPF_SKEL_SUPPORTS_MAP_AUTO_ATTACH 1		    \n\
1276 									    \n\
1277 		struct %1$s {						    \n\
1278 			struct bpf_object_skeleton *skeleton;		    \n\
1279 			struct bpf_object *obj;				    \n\
1280 		",
1281 		obj_name, header_guard
1282 		);
1283 	}
1284 
1285 	if (map_cnt) {
1286 		printf("\tstruct {\n");
1287 		bpf_object__for_each_map(map, obj) {
1288 			if (!get_map_ident(map, ident, sizeof(ident)))
1289 				continue;
1290 			if (use_loader)
1291 				printf("\t\tstruct bpf_map_desc %s;\n", ident);
1292 			else
1293 				printf("\t\tstruct bpf_map *%s;\n", ident);
1294 		}
1295 		printf("\t} maps;\n");
1296 	}
1297 
1298 	btf = bpf_object__btf(obj);
1299 	err = gen_st_ops_shadow(obj_name, btf, obj);
1300 	if (err)
1301 		goto out;
1302 
1303 	if (prog_cnt) {
1304 		printf("\tstruct {\n");
1305 		bpf_object__for_each_program(prog, obj) {
1306 			if (use_loader)
1307 				printf("\t\tstruct bpf_prog_desc %s;\n",
1308 				       bpf_program__name(prog));
1309 			else
1310 				printf("\t\tstruct bpf_program *%s;\n",
1311 				       bpf_program__name(prog));
1312 		}
1313 		printf("\t} progs;\n");
1314 	}
1315 
1316 	if (prog_cnt + attach_map_cnt) {
1317 		printf("\tstruct {\n");
1318 		bpf_object__for_each_program(prog, obj) {
1319 			if (use_loader)
1320 				printf("\t\tint %s_fd;\n",
1321 				       bpf_program__name(prog));
1322 			else
1323 				printf("\t\tstruct bpf_link *%s;\n",
1324 				       bpf_program__name(prog));
1325 		}
1326 
1327 		bpf_object__for_each_map(map, obj) {
1328 			if (!get_map_ident(map, ident, sizeof(ident)))
1329 				continue;
1330 			if (bpf_map__type(map) != BPF_MAP_TYPE_STRUCT_OPS)
1331 				continue;
1332 
1333 			if (use_loader)
1334 				printf("t\tint %s_fd;\n", ident);
1335 			else
1336 				printf("\t\tstruct bpf_link *%s;\n", ident);
1337 		}
1338 
1339 		printf("\t} links;\n");
1340 	}
1341 
1342 	if (btf) {
1343 		err = codegen_datasecs(obj, obj_name);
1344 		if (err)
1345 			goto out;
1346 	}
1347 	if (use_loader) {
1348 		err = gen_trace(obj, obj_name, header_guard);
1349 		goto out;
1350 	}
1351 
1352 	codegen("\
1353 		\n\
1354 									    \n\
1355 		#ifdef __cplusplus					    \n\
1356 			static inline struct %1$s *open(const struct bpf_object_open_opts *opts = nullptr);\n\
1357 			static inline struct %1$s *open_and_load();	    \n\
1358 			static inline int load(struct %1$s *skel);	    \n\
1359 			static inline int attach(struct %1$s *skel);	    \n\
1360 			static inline void detach(struct %1$s *skel);	    \n\
1361 			static inline void destroy(struct %1$s *skel);	    \n\
1362 			static inline const void *elf_bytes(size_t *sz);    \n\
1363 		#endif /* __cplusplus */				    \n\
1364 		};							    \n\
1365 									    \n\
1366 		static void						    \n\
1367 		%1$s__destroy(struct %1$s *obj)				    \n\
1368 		{							    \n\
1369 			if (!obj)					    \n\
1370 				return;					    \n\
1371 			if (obj->skeleton)				    \n\
1372 				bpf_object__destroy_skeleton(obj->skeleton);\n\
1373 			free(obj);					    \n\
1374 		}							    \n\
1375 									    \n\
1376 		static inline int					    \n\
1377 		%1$s__create_skeleton(struct %1$s *obj);		    \n\
1378 									    \n\
1379 		static inline struct %1$s *				    \n\
1380 		%1$s__open_opts(const struct bpf_object_open_opts *opts)    \n\
1381 		{							    \n\
1382 			struct %1$s *obj;				    \n\
1383 			int err;					    \n\
1384 									    \n\
1385 			obj = (struct %1$s *)calloc(1, sizeof(*obj));	    \n\
1386 			if (!obj) {					    \n\
1387 				errno = ENOMEM;				    \n\
1388 				return NULL;				    \n\
1389 			}						    \n\
1390 									    \n\
1391 			err = %1$s__create_skeleton(obj);		    \n\
1392 			if (err)					    \n\
1393 				goto err_out;				    \n\
1394 									    \n\
1395 			err = bpf_object__open_skeleton(obj->skeleton, opts);\n\
1396 			if (err)					    \n\
1397 				goto err_out;				    \n\
1398 									    \n\
1399 		", obj_name);
1400 
1401 	gen_st_ops_shadow_init(btf, obj);
1402 
1403 	codegen("\
1404 		\n\
1405 			return obj;					    \n\
1406 		err_out:						    \n\
1407 			%1$s__destroy(obj);				    \n\
1408 			errno = -err;					    \n\
1409 			return NULL;					    \n\
1410 		}							    \n\
1411 									    \n\
1412 		static inline struct %1$s *				    \n\
1413 		%1$s__open(void)					    \n\
1414 		{							    \n\
1415 			return %1$s__open_opts(NULL);			    \n\
1416 		}							    \n\
1417 									    \n\
1418 		static inline int					    \n\
1419 		%1$s__load(struct %1$s *obj)				    \n\
1420 		{							    \n\
1421 			return bpf_object__load_skeleton(obj->skeleton);    \n\
1422 		}							    \n\
1423 									    \n\
1424 		static inline struct %1$s *				    \n\
1425 		%1$s__open_and_load(void)				    \n\
1426 		{							    \n\
1427 			struct %1$s *obj;				    \n\
1428 			int err;					    \n\
1429 									    \n\
1430 			obj = %1$s__open();				    \n\
1431 			if (!obj)					    \n\
1432 				return NULL;				    \n\
1433 			err = %1$s__load(obj);				    \n\
1434 			if (err) {					    \n\
1435 				%1$s__destroy(obj);			    \n\
1436 				errno = -err;				    \n\
1437 				return NULL;				    \n\
1438 			}						    \n\
1439 			return obj;					    \n\
1440 		}							    \n\
1441 									    \n\
1442 		static inline int					    \n\
1443 		%1$s__attach(struct %1$s *obj)				    \n\
1444 		{							    \n\
1445 			return bpf_object__attach_skeleton(obj->skeleton);  \n\
1446 		}							    \n\
1447 									    \n\
1448 		static inline void					    \n\
1449 		%1$s__detach(struct %1$s *obj)				    \n\
1450 		{							    \n\
1451 			bpf_object__detach_skeleton(obj->skeleton);	    \n\
1452 		}							    \n\
1453 		",
1454 		obj_name
1455 	);
1456 
1457 	codegen("\
1458 		\n\
1459 									    \n\
1460 		static inline const void *%1$s__elf_bytes(size_t *sz);	    \n\
1461 									    \n\
1462 		static inline int					    \n\
1463 		%1$s__create_skeleton(struct %1$s *obj)			    \n\
1464 		{							    \n\
1465 			struct bpf_object_skeleton *s;			    \n\
1466 			int err;					    \n\
1467 									    \n\
1468 			s = (struct bpf_object_skeleton *)calloc(1, sizeof(*s));\n\
1469 			if (!s)	{					    \n\
1470 				err = -ENOMEM;				    \n\
1471 				goto err;				    \n\
1472 			}						    \n\
1473 									    \n\
1474 			s->sz = sizeof(*s);				    \n\
1475 			s->name = \"%1$s\";				    \n\
1476 			s->obj = &obj->obj;				    \n\
1477 		",
1478 		obj_name
1479 	);
1480 
1481 	codegen_maps_skeleton(obj, map_cnt, true /*mmaped*/, true /*links*/);
1482 	codegen_progs_skeleton(obj, prog_cnt, true /*populate_links*/);
1483 
1484 	codegen("\
1485 		\n\
1486 									    \n\
1487 			s->data = %1$s__elf_bytes(&s->data_sz);		    \n\
1488 									    \n\
1489 			obj->skeleton = s;				    \n\
1490 			return 0;					    \n\
1491 		err:							    \n\
1492 			bpf_object__destroy_skeleton(s);		    \n\
1493 			return err;					    \n\
1494 		}							    \n\
1495 									    \n\
1496 		static inline const void *%1$s__elf_bytes(size_t *sz)	    \n\
1497 		{							    \n\
1498 			static const char data[] __attribute__((__aligned__(8))) = \"\\\n\
1499 		",
1500 		obj_name
1501 	);
1502 
1503 	/* embed contents of BPF object file */
1504 	print_hex(obj_data, file_sz);
1505 
1506 	codegen("\
1507 		\n\
1508 		\";							    \n\
1509 									    \n\
1510 			*sz = sizeof(data) - 1;				    \n\
1511 			return (const void *)data;			    \n\
1512 		}							    \n\
1513 									    \n\
1514 		#ifdef __cplusplus					    \n\
1515 		struct %1$s *%1$s::open(const struct bpf_object_open_opts *opts) { return %1$s__open_opts(opts); }\n\
1516 		struct %1$s *%1$s::open_and_load() { return %1$s__open_and_load(); }	\n\
1517 		int %1$s::load(struct %1$s *skel) { return %1$s__load(skel); }		\n\
1518 		int %1$s::attach(struct %1$s *skel) { return %1$s__attach(skel); }	\n\
1519 		void %1$s::detach(struct %1$s *skel) { %1$s__detach(skel); }		\n\
1520 		void %1$s::destroy(struct %1$s *skel) { %1$s__destroy(skel); }		\n\
1521 		const void *%1$s::elf_bytes(size_t *sz) { return %1$s__elf_bytes(sz); } \n\
1522 		#endif /* __cplusplus */				    \n\
1523 									    \n\
1524 		",
1525 		obj_name);
1526 
1527 	codegen_asserts(obj, obj_name);
1528 
1529 	codegen("\
1530 		\n\
1531 									    \n\
1532 		#endif /* %1$s */					    \n\
1533 		",
1534 		header_guard);
1535 	err = 0;
1536 out:
1537 	bpf_object__close(obj);
1538 	if (obj_data)
1539 		munmap(obj_data, mmap_sz);
1540 	close(fd);
1541 	return err;
1542 }
1543 
1544 /* Subskeletons are like skeletons, except they don't own the bpf_object,
1545  * associated maps, links, etc. Instead, they know about the existence of
1546  * variables, maps, programs and are able to find their locations
1547  * _at runtime_ from an already loaded bpf_object.
1548  *
1549  * This allows for library-like BPF objects to have userspace counterparts
1550  * with access to their own items without having to know anything about the
1551  * final BPF object that the library was linked into.
1552  */
1553 static int do_subskeleton(int argc, char **argv)
1554 {
1555 	char header_guard[MAX_OBJ_NAME_LEN + sizeof("__SUBSKEL_H__")];
1556 	size_t i, len, file_sz, map_cnt = 0, prog_cnt = 0, mmap_sz, var_cnt = 0, var_idx = 0;
1557 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts);
1558 	char obj_name[MAX_OBJ_NAME_LEN] = "", *obj_data;
1559 	struct bpf_object *obj = NULL;
1560 	const char *file, *var_name;
1561 	char ident[256];
1562 	int fd, err = -1, map_type_id;
1563 	const struct bpf_map *map;
1564 	struct bpf_program *prog;
1565 	struct btf *btf;
1566 	const struct btf_type *map_type, *var_type;
1567 	const struct btf_var_secinfo *var;
1568 	struct stat st;
1569 
1570 	if (!REQ_ARGS(1)) {
1571 		usage();
1572 		return -1;
1573 	}
1574 	file = GET_ARG();
1575 
1576 	while (argc) {
1577 		if (!REQ_ARGS(2))
1578 			return -1;
1579 
1580 		if (is_prefix(*argv, "name")) {
1581 			NEXT_ARG();
1582 
1583 			if (obj_name[0] != '\0') {
1584 				p_err("object name already specified");
1585 				return -1;
1586 			}
1587 
1588 			strncpy(obj_name, *argv, MAX_OBJ_NAME_LEN - 1);
1589 			obj_name[MAX_OBJ_NAME_LEN - 1] = '\0';
1590 		} else {
1591 			p_err("unknown arg %s", *argv);
1592 			return -1;
1593 		}
1594 
1595 		NEXT_ARG();
1596 	}
1597 
1598 	if (argc) {
1599 		p_err("extra unknown arguments");
1600 		return -1;
1601 	}
1602 
1603 	if (use_loader) {
1604 		p_err("cannot use loader for subskeletons");
1605 		return -1;
1606 	}
1607 
1608 	if (stat(file, &st)) {
1609 		p_err("failed to stat() %s: %s", file, strerror(errno));
1610 		return -1;
1611 	}
1612 	file_sz = st.st_size;
1613 	mmap_sz = roundup(file_sz, sysconf(_SC_PAGE_SIZE));
1614 	fd = open(file, O_RDONLY);
1615 	if (fd < 0) {
1616 		p_err("failed to open() %s: %s", file, strerror(errno));
1617 		return -1;
1618 	}
1619 	obj_data = mmap(NULL, mmap_sz, PROT_READ, MAP_PRIVATE, fd, 0);
1620 	if (obj_data == MAP_FAILED) {
1621 		obj_data = NULL;
1622 		p_err("failed to mmap() %s: %s", file, strerror(errno));
1623 		goto out;
1624 	}
1625 	if (obj_name[0] == '\0')
1626 		get_obj_name(obj_name, file);
1627 
1628 	/* The empty object name allows us to use bpf_map__name and produce
1629 	 * ELF section names out of it. (".data" instead of "obj.data")
1630 	 */
1631 	opts.object_name = "";
1632 	obj = bpf_object__open_mem(obj_data, file_sz, &opts);
1633 	if (!obj) {
1634 		char err_buf[256];
1635 
1636 		libbpf_strerror(errno, err_buf, sizeof(err_buf));
1637 		p_err("failed to open BPF object file: %s", err_buf);
1638 		obj = NULL;
1639 		goto out;
1640 	}
1641 
1642 	btf = bpf_object__btf(obj);
1643 	if (!btf) {
1644 		err = -1;
1645 		p_err("need btf type information for %s", obj_name);
1646 		goto out;
1647 	}
1648 
1649 	bpf_object__for_each_program(prog, obj) {
1650 		prog_cnt++;
1651 	}
1652 
1653 	/* First, count how many variables we have to find.
1654 	 * We need this in advance so the subskel can allocate the right
1655 	 * amount of storage.
1656 	 */
1657 	bpf_object__for_each_map(map, obj) {
1658 		if (!get_map_ident(map, ident, sizeof(ident)))
1659 			continue;
1660 
1661 		/* Also count all maps that have a name */
1662 		map_cnt++;
1663 
1664 		if (!is_mmapable_map(map, ident, sizeof(ident)))
1665 			continue;
1666 
1667 		map_type_id = bpf_map__btf_value_type_id(map);
1668 		if (map_type_id <= 0) {
1669 			err = map_type_id;
1670 			goto out;
1671 		}
1672 		map_type = btf__type_by_id(btf, map_type_id);
1673 
1674 		var = btf_var_secinfos(map_type);
1675 		len = btf_vlen(map_type);
1676 		for (i = 0; i < len; i++, var++) {
1677 			var_type = btf__type_by_id(btf, var->type);
1678 
1679 			if (btf_var(var_type)->linkage == BTF_VAR_STATIC)
1680 				continue;
1681 
1682 			var_cnt++;
1683 		}
1684 	}
1685 
1686 	get_header_guard(header_guard, obj_name, "SUBSKEL_H");
1687 	codegen("\
1688 	\n\
1689 	/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */	    \n\
1690 									    \n\
1691 	/* THIS FILE IS AUTOGENERATED! */				    \n\
1692 	#ifndef %2$s							    \n\
1693 	#define %2$s							    \n\
1694 									    \n\
1695 	#include <errno.h>						    \n\
1696 	#include <stdlib.h>						    \n\
1697 	#include <bpf/libbpf.h>						    \n\
1698 									    \n\
1699 	struct %1$s {							    \n\
1700 		struct bpf_object *obj;					    \n\
1701 		struct bpf_object_subskeleton *subskel;			    \n\
1702 	", obj_name, header_guard);
1703 
1704 	if (map_cnt) {
1705 		printf("\tstruct {\n");
1706 		bpf_object__for_each_map(map, obj) {
1707 			if (!get_map_ident(map, ident, sizeof(ident)))
1708 				continue;
1709 			printf("\t\tstruct bpf_map *%s;\n", ident);
1710 		}
1711 		printf("\t} maps;\n");
1712 	}
1713 
1714 	err = gen_st_ops_shadow(obj_name, btf, obj);
1715 	if (err)
1716 		goto out;
1717 
1718 	if (prog_cnt) {
1719 		printf("\tstruct {\n");
1720 		bpf_object__for_each_program(prog, obj) {
1721 			printf("\t\tstruct bpf_program *%s;\n",
1722 				bpf_program__name(prog));
1723 		}
1724 		printf("\t} progs;\n");
1725 	}
1726 
1727 	err = codegen_subskel_datasecs(obj, obj_name);
1728 	if (err)
1729 		goto out;
1730 
1731 	/* emit code that will allocate enough storage for all symbols */
1732 	codegen("\
1733 		\n\
1734 									    \n\
1735 		#ifdef __cplusplus					    \n\
1736 			static inline struct %1$s *open(const struct bpf_object *src);\n\
1737 			static inline void destroy(struct %1$s *skel);	    \n\
1738 		#endif /* __cplusplus */				    \n\
1739 		};							    \n\
1740 									    \n\
1741 		static inline void					    \n\
1742 		%1$s__destroy(struct %1$s *skel)			    \n\
1743 		{							    \n\
1744 			if (!skel)					    \n\
1745 				return;					    \n\
1746 			if (skel->subskel)				    \n\
1747 				bpf_object__destroy_subskeleton(skel->subskel);\n\
1748 			free(skel);					    \n\
1749 		}							    \n\
1750 									    \n\
1751 		static inline struct %1$s *				    \n\
1752 		%1$s__open(const struct bpf_object *src)		    \n\
1753 		{							    \n\
1754 			struct %1$s *obj;				    \n\
1755 			struct bpf_object_subskeleton *s;		    \n\
1756 			int err;					    \n\
1757 									    \n\
1758 			obj = (struct %1$s *)calloc(1, sizeof(*obj));	    \n\
1759 			if (!obj) {					    \n\
1760 				err = -ENOMEM;				    \n\
1761 				goto err;				    \n\
1762 			}						    \n\
1763 			s = (struct bpf_object_subskeleton *)calloc(1, sizeof(*s));\n\
1764 			if (!s) {					    \n\
1765 				err = -ENOMEM;				    \n\
1766 				goto err;				    \n\
1767 			}						    \n\
1768 			s->sz = sizeof(*s);				    \n\
1769 			s->obj = src;					    \n\
1770 			s->var_skel_sz = sizeof(*s->vars);		    \n\
1771 			obj->subskel = s;				    \n\
1772 									    \n\
1773 			/* vars */					    \n\
1774 			s->var_cnt = %2$d;				    \n\
1775 			s->vars = (struct bpf_var_skeleton *)calloc(%2$d, sizeof(*s->vars));\n\
1776 			if (!s->vars) {					    \n\
1777 				err = -ENOMEM;				    \n\
1778 				goto err;				    \n\
1779 			}						    \n\
1780 		",
1781 		obj_name, var_cnt
1782 	);
1783 
1784 	/* walk through each symbol and emit the runtime representation */
1785 	bpf_object__for_each_map(map, obj) {
1786 		if (!is_mmapable_map(map, ident, sizeof(ident)))
1787 			continue;
1788 
1789 		map_type_id = bpf_map__btf_value_type_id(map);
1790 		if (map_type_id <= 0)
1791 			/* skip over internal maps with no type*/
1792 			continue;
1793 
1794 		map_type = btf__type_by_id(btf, map_type_id);
1795 		var = btf_var_secinfos(map_type);
1796 		len = btf_vlen(map_type);
1797 		for (i = 0; i < len; i++, var++) {
1798 			var_type = btf__type_by_id(btf, var->type);
1799 			var_name = btf__name_by_offset(btf, var_type->name_off);
1800 
1801 			if (btf_var(var_type)->linkage == BTF_VAR_STATIC)
1802 				continue;
1803 
1804 			/* Note that we use the dot prefix in .data as the
1805 			 * field access operator i.e. maps%s becomes maps.data
1806 			 */
1807 			codegen("\
1808 			\n\
1809 									    \n\
1810 				s->vars[%3$d].name = \"%1$s\";		    \n\
1811 				s->vars[%3$d].map = &obj->maps.%2$s;	    \n\
1812 				s->vars[%3$d].addr = (void **) &obj->%2$s.%1$s;\n\
1813 			", var_name, ident, var_idx);
1814 
1815 			var_idx++;
1816 		}
1817 	}
1818 
1819 	codegen_maps_skeleton(obj, map_cnt, false /*mmaped*/, false /*links*/);
1820 	codegen_progs_skeleton(obj, prog_cnt, false /*links*/);
1821 
1822 	codegen("\
1823 		\n\
1824 									    \n\
1825 			err = bpf_object__open_subskeleton(s);		    \n\
1826 			if (err)					    \n\
1827 				goto err;				    \n\
1828 									    \n\
1829 		");
1830 
1831 	gen_st_ops_shadow_init(btf, obj);
1832 
1833 	codegen("\
1834 		\n\
1835 			return obj;					    \n\
1836 		err:							    \n\
1837 			%1$s__destroy(obj);				    \n\
1838 			errno = -err;					    \n\
1839 			return NULL;					    \n\
1840 		}							    \n\
1841 									    \n\
1842 		#ifdef __cplusplus					    \n\
1843 		struct %1$s *%1$s::open(const struct bpf_object *src) { return %1$s__open(src); }\n\
1844 		void %1$s::destroy(struct %1$s *skel) { %1$s__destroy(skel); }\n\
1845 		#endif /* __cplusplus */				    \n\
1846 									    \n\
1847 		#endif /* %2$s */					    \n\
1848 		",
1849 		obj_name, header_guard);
1850 	err = 0;
1851 out:
1852 	bpf_object__close(obj);
1853 	if (obj_data)
1854 		munmap(obj_data, mmap_sz);
1855 	close(fd);
1856 	return err;
1857 }
1858 
1859 static int do_object(int argc, char **argv)
1860 {
1861 	struct bpf_linker *linker;
1862 	const char *output_file, *file;
1863 	int err = 0;
1864 
1865 	if (!REQ_ARGS(2)) {
1866 		usage();
1867 		return -1;
1868 	}
1869 
1870 	output_file = GET_ARG();
1871 
1872 	linker = bpf_linker__new(output_file, NULL);
1873 	if (!linker) {
1874 		p_err("failed to create BPF linker instance");
1875 		return -1;
1876 	}
1877 
1878 	while (argc) {
1879 		file = GET_ARG();
1880 
1881 		err = bpf_linker__add_file(linker, file, NULL);
1882 		if (err) {
1883 			p_err("failed to link '%s': %s (%d)", file, strerror(errno), errno);
1884 			goto out;
1885 		}
1886 	}
1887 
1888 	err = bpf_linker__finalize(linker);
1889 	if (err) {
1890 		p_err("failed to finalize ELF file: %s (%d)", strerror(errno), errno);
1891 		goto out;
1892 	}
1893 
1894 	err = 0;
1895 out:
1896 	bpf_linker__free(linker);
1897 	return err;
1898 }
1899 
1900 static int do_help(int argc, char **argv)
1901 {
1902 	if (json_output) {
1903 		jsonw_null(json_wtr);
1904 		return 0;
1905 	}
1906 
1907 	fprintf(stderr,
1908 		"Usage: %1$s %2$s object OUTPUT_FILE INPUT_FILE [INPUT_FILE...]\n"
1909 		"       %1$s %2$s skeleton FILE [name OBJECT_NAME]\n"
1910 		"       %1$s %2$s subskeleton FILE [name OBJECT_NAME]\n"
1911 		"       %1$s %2$s min_core_btf INPUT OUTPUT OBJECT [OBJECT...]\n"
1912 		"       %1$s %2$s help\n"
1913 		"\n"
1914 		"       " HELP_SPEC_OPTIONS " |\n"
1915 		"                    {-L|--use-loader} }\n"
1916 		"",
1917 		bin_name, "gen");
1918 
1919 	return 0;
1920 }
1921 
1922 static int btf_save_raw(const struct btf *btf, const char *path)
1923 {
1924 	const void *data;
1925 	FILE *f = NULL;
1926 	__u32 data_sz;
1927 	int err = 0;
1928 
1929 	data = btf__raw_data(btf, &data_sz);
1930 	if (!data)
1931 		return -ENOMEM;
1932 
1933 	f = fopen(path, "wb");
1934 	if (!f)
1935 		return -errno;
1936 
1937 	if (fwrite(data, 1, data_sz, f) != data_sz)
1938 		err = -errno;
1939 
1940 	fclose(f);
1941 	return err;
1942 }
1943 
1944 struct btfgen_info {
1945 	struct btf *src_btf;
1946 	struct btf *marked_btf; /* btf structure used to mark used types */
1947 };
1948 
1949 static size_t btfgen_hash_fn(long key, void *ctx)
1950 {
1951 	return key;
1952 }
1953 
1954 static bool btfgen_equal_fn(long k1, long k2, void *ctx)
1955 {
1956 	return k1 == k2;
1957 }
1958 
1959 static void btfgen_free_info(struct btfgen_info *info)
1960 {
1961 	if (!info)
1962 		return;
1963 
1964 	btf__free(info->src_btf);
1965 	btf__free(info->marked_btf);
1966 
1967 	free(info);
1968 }
1969 
1970 static struct btfgen_info *
1971 btfgen_new_info(const char *targ_btf_path)
1972 {
1973 	struct btfgen_info *info;
1974 	int err;
1975 
1976 	info = calloc(1, sizeof(*info));
1977 	if (!info)
1978 		return NULL;
1979 
1980 	info->src_btf = btf__parse(targ_btf_path, NULL);
1981 	if (!info->src_btf) {
1982 		err = -errno;
1983 		p_err("failed parsing '%s' BTF file: %s", targ_btf_path, strerror(errno));
1984 		goto err_out;
1985 	}
1986 
1987 	info->marked_btf = btf__parse(targ_btf_path, NULL);
1988 	if (!info->marked_btf) {
1989 		err = -errno;
1990 		p_err("failed parsing '%s' BTF file: %s", targ_btf_path, strerror(errno));
1991 		goto err_out;
1992 	}
1993 
1994 	return info;
1995 
1996 err_out:
1997 	btfgen_free_info(info);
1998 	errno = -err;
1999 	return NULL;
2000 }
2001 
2002 #define MARKED UINT32_MAX
2003 
2004 static void btfgen_mark_member(struct btfgen_info *info, int type_id, int idx)
2005 {
2006 	const struct btf_type *t = btf__type_by_id(info->marked_btf, type_id);
2007 	struct btf_member *m = btf_members(t) + idx;
2008 
2009 	m->name_off = MARKED;
2010 }
2011 
2012 static int
2013 btfgen_mark_type(struct btfgen_info *info, unsigned int type_id, bool follow_pointers)
2014 {
2015 	const struct btf_type *btf_type = btf__type_by_id(info->src_btf, type_id);
2016 	struct btf_type *cloned_type;
2017 	struct btf_param *param;
2018 	struct btf_array *array;
2019 	int err, i;
2020 
2021 	if (type_id == 0)
2022 		return 0;
2023 
2024 	/* mark type on cloned BTF as used */
2025 	cloned_type = (struct btf_type *) btf__type_by_id(info->marked_btf, type_id);
2026 	cloned_type->name_off = MARKED;
2027 
2028 	/* recursively mark other types needed by it */
2029 	switch (btf_kind(btf_type)) {
2030 	case BTF_KIND_UNKN:
2031 	case BTF_KIND_INT:
2032 	case BTF_KIND_FLOAT:
2033 	case BTF_KIND_ENUM:
2034 	case BTF_KIND_ENUM64:
2035 	case BTF_KIND_STRUCT:
2036 	case BTF_KIND_UNION:
2037 		break;
2038 	case BTF_KIND_PTR:
2039 		if (follow_pointers) {
2040 			err = btfgen_mark_type(info, btf_type->type, follow_pointers);
2041 			if (err)
2042 				return err;
2043 		}
2044 		break;
2045 	case BTF_KIND_CONST:
2046 	case BTF_KIND_RESTRICT:
2047 	case BTF_KIND_VOLATILE:
2048 	case BTF_KIND_TYPEDEF:
2049 		err = btfgen_mark_type(info, btf_type->type, follow_pointers);
2050 		if (err)
2051 			return err;
2052 		break;
2053 	case BTF_KIND_ARRAY:
2054 		array = btf_array(btf_type);
2055 
2056 		/* mark array type */
2057 		err = btfgen_mark_type(info, array->type, follow_pointers);
2058 		/* mark array's index type */
2059 		err = err ? : btfgen_mark_type(info, array->index_type, follow_pointers);
2060 		if (err)
2061 			return err;
2062 		break;
2063 	case BTF_KIND_FUNC_PROTO:
2064 		/* mark ret type */
2065 		err = btfgen_mark_type(info, btf_type->type, follow_pointers);
2066 		if (err)
2067 			return err;
2068 
2069 		/* mark parameters types */
2070 		param = btf_params(btf_type);
2071 		for (i = 0; i < btf_vlen(btf_type); i++) {
2072 			err = btfgen_mark_type(info, param->type, follow_pointers);
2073 			if (err)
2074 				return err;
2075 			param++;
2076 		}
2077 		break;
2078 	/* tells if some other type needs to be handled */
2079 	default:
2080 		p_err("unsupported kind: %s (%d)", btf_kind_str(btf_type), type_id);
2081 		return -EINVAL;
2082 	}
2083 
2084 	return 0;
2085 }
2086 
2087 static int btfgen_record_field_relo(struct btfgen_info *info, struct bpf_core_spec *targ_spec)
2088 {
2089 	struct btf *btf = info->src_btf;
2090 	const struct btf_type *btf_type;
2091 	struct btf_member *btf_member;
2092 	struct btf_array *array;
2093 	unsigned int type_id = targ_spec->root_type_id;
2094 	int idx, err;
2095 
2096 	/* mark root type */
2097 	btf_type = btf__type_by_id(btf, type_id);
2098 	err = btfgen_mark_type(info, type_id, false);
2099 	if (err)
2100 		return err;
2101 
2102 	/* mark types for complex types (arrays, unions, structures) */
2103 	for (int i = 1; i < targ_spec->raw_len; i++) {
2104 		/* skip typedefs and mods */
2105 		while (btf_is_mod(btf_type) || btf_is_typedef(btf_type)) {
2106 			type_id = btf_type->type;
2107 			btf_type = btf__type_by_id(btf, type_id);
2108 		}
2109 
2110 		switch (btf_kind(btf_type)) {
2111 		case BTF_KIND_STRUCT:
2112 		case BTF_KIND_UNION:
2113 			idx = targ_spec->raw_spec[i];
2114 			btf_member = btf_members(btf_type) + idx;
2115 
2116 			/* mark member */
2117 			btfgen_mark_member(info, type_id, idx);
2118 
2119 			/* mark member's type */
2120 			type_id = btf_member->type;
2121 			btf_type = btf__type_by_id(btf, type_id);
2122 			err = btfgen_mark_type(info, type_id, false);
2123 			if (err)
2124 				return err;
2125 			break;
2126 		case BTF_KIND_ARRAY:
2127 			array = btf_array(btf_type);
2128 			type_id = array->type;
2129 			btf_type = btf__type_by_id(btf, type_id);
2130 			break;
2131 		default:
2132 			p_err("unsupported kind: %s (%d)",
2133 			      btf_kind_str(btf_type), btf_type->type);
2134 			return -EINVAL;
2135 		}
2136 	}
2137 
2138 	return 0;
2139 }
2140 
2141 /* Mark types, members, and member types. Compared to btfgen_record_field_relo,
2142  * this function does not rely on the target spec for inferring members, but
2143  * uses the associated BTF.
2144  *
2145  * The `behind_ptr` argument is used to stop marking of composite types reached
2146  * through a pointer. This way, we can keep BTF size in check while providing
2147  * reasonable match semantics.
2148  */
2149 static int btfgen_mark_type_match(struct btfgen_info *info, __u32 type_id, bool behind_ptr)
2150 {
2151 	const struct btf_type *btf_type;
2152 	struct btf *btf = info->src_btf;
2153 	struct btf_type *cloned_type;
2154 	int i, err;
2155 
2156 	if (type_id == 0)
2157 		return 0;
2158 
2159 	btf_type = btf__type_by_id(btf, type_id);
2160 	/* mark type on cloned BTF as used */
2161 	cloned_type = (struct btf_type *)btf__type_by_id(info->marked_btf, type_id);
2162 	cloned_type->name_off = MARKED;
2163 
2164 	switch (btf_kind(btf_type)) {
2165 	case BTF_KIND_UNKN:
2166 	case BTF_KIND_INT:
2167 	case BTF_KIND_FLOAT:
2168 	case BTF_KIND_ENUM:
2169 	case BTF_KIND_ENUM64:
2170 		break;
2171 	case BTF_KIND_STRUCT:
2172 	case BTF_KIND_UNION: {
2173 		struct btf_member *m = btf_members(btf_type);
2174 		__u16 vlen = btf_vlen(btf_type);
2175 
2176 		if (behind_ptr)
2177 			break;
2178 
2179 		for (i = 0; i < vlen; i++, m++) {
2180 			/* mark member */
2181 			btfgen_mark_member(info, type_id, i);
2182 
2183 			/* mark member's type */
2184 			err = btfgen_mark_type_match(info, m->type, false);
2185 			if (err)
2186 				return err;
2187 		}
2188 		break;
2189 	}
2190 	case BTF_KIND_CONST:
2191 	case BTF_KIND_FWD:
2192 	case BTF_KIND_RESTRICT:
2193 	case BTF_KIND_TYPEDEF:
2194 	case BTF_KIND_VOLATILE:
2195 		return btfgen_mark_type_match(info, btf_type->type, behind_ptr);
2196 	case BTF_KIND_PTR:
2197 		return btfgen_mark_type_match(info, btf_type->type, true);
2198 	case BTF_KIND_ARRAY: {
2199 		struct btf_array *array;
2200 
2201 		array = btf_array(btf_type);
2202 		/* mark array type */
2203 		err = btfgen_mark_type_match(info, array->type, false);
2204 		/* mark array's index type */
2205 		err = err ? : btfgen_mark_type_match(info, array->index_type, false);
2206 		if (err)
2207 			return err;
2208 		break;
2209 	}
2210 	case BTF_KIND_FUNC_PROTO: {
2211 		__u16 vlen = btf_vlen(btf_type);
2212 		struct btf_param *param;
2213 
2214 		/* mark ret type */
2215 		err = btfgen_mark_type_match(info, btf_type->type, false);
2216 		if (err)
2217 			return err;
2218 
2219 		/* mark parameters types */
2220 		param = btf_params(btf_type);
2221 		for (i = 0; i < vlen; i++) {
2222 			err = btfgen_mark_type_match(info, param->type, false);
2223 			if (err)
2224 				return err;
2225 			param++;
2226 		}
2227 		break;
2228 	}
2229 	/* tells if some other type needs to be handled */
2230 	default:
2231 		p_err("unsupported kind: %s (%d)", btf_kind_str(btf_type), type_id);
2232 		return -EINVAL;
2233 	}
2234 
2235 	return 0;
2236 }
2237 
2238 /* Mark types, members, and member types. Compared to btfgen_record_field_relo,
2239  * this function does not rely on the target spec for inferring members, but
2240  * uses the associated BTF.
2241  */
2242 static int btfgen_record_type_match_relo(struct btfgen_info *info, struct bpf_core_spec *targ_spec)
2243 {
2244 	return btfgen_mark_type_match(info, targ_spec->root_type_id, false);
2245 }
2246 
2247 static int btfgen_record_type_relo(struct btfgen_info *info, struct bpf_core_spec *targ_spec)
2248 {
2249 	return btfgen_mark_type(info, targ_spec->root_type_id, true);
2250 }
2251 
2252 static int btfgen_record_enumval_relo(struct btfgen_info *info, struct bpf_core_spec *targ_spec)
2253 {
2254 	return btfgen_mark_type(info, targ_spec->root_type_id, false);
2255 }
2256 
2257 static int btfgen_record_reloc(struct btfgen_info *info, struct bpf_core_spec *res)
2258 {
2259 	switch (res->relo_kind) {
2260 	case BPF_CORE_FIELD_BYTE_OFFSET:
2261 	case BPF_CORE_FIELD_BYTE_SIZE:
2262 	case BPF_CORE_FIELD_EXISTS:
2263 	case BPF_CORE_FIELD_SIGNED:
2264 	case BPF_CORE_FIELD_LSHIFT_U64:
2265 	case BPF_CORE_FIELD_RSHIFT_U64:
2266 		return btfgen_record_field_relo(info, res);
2267 	case BPF_CORE_TYPE_ID_LOCAL: /* BPF_CORE_TYPE_ID_LOCAL doesn't require kernel BTF */
2268 		return 0;
2269 	case BPF_CORE_TYPE_ID_TARGET:
2270 	case BPF_CORE_TYPE_EXISTS:
2271 	case BPF_CORE_TYPE_SIZE:
2272 		return btfgen_record_type_relo(info, res);
2273 	case BPF_CORE_TYPE_MATCHES:
2274 		return btfgen_record_type_match_relo(info, res);
2275 	case BPF_CORE_ENUMVAL_EXISTS:
2276 	case BPF_CORE_ENUMVAL_VALUE:
2277 		return btfgen_record_enumval_relo(info, res);
2278 	default:
2279 		return -EINVAL;
2280 	}
2281 }
2282 
2283 static struct bpf_core_cand_list *
2284 btfgen_find_cands(const struct btf *local_btf, const struct btf *targ_btf, __u32 local_id)
2285 {
2286 	const struct btf_type *local_type;
2287 	struct bpf_core_cand_list *cands = NULL;
2288 	struct bpf_core_cand local_cand = {};
2289 	size_t local_essent_len;
2290 	const char *local_name;
2291 	int err;
2292 
2293 	local_cand.btf = local_btf;
2294 	local_cand.id = local_id;
2295 
2296 	local_type = btf__type_by_id(local_btf, local_id);
2297 	if (!local_type) {
2298 		err = -EINVAL;
2299 		goto err_out;
2300 	}
2301 
2302 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
2303 	if (!local_name) {
2304 		err = -EINVAL;
2305 		goto err_out;
2306 	}
2307 	local_essent_len = bpf_core_essential_name_len(local_name);
2308 
2309 	cands = calloc(1, sizeof(*cands));
2310 	if (!cands)
2311 		return NULL;
2312 
2313 	err = bpf_core_add_cands(&local_cand, local_essent_len, targ_btf, "vmlinux", 1, cands);
2314 	if (err)
2315 		goto err_out;
2316 
2317 	return cands;
2318 
2319 err_out:
2320 	bpf_core_free_cands(cands);
2321 	errno = -err;
2322 	return NULL;
2323 }
2324 
2325 /* Record relocation information for a single BPF object */
2326 static int btfgen_record_obj(struct btfgen_info *info, const char *obj_path)
2327 {
2328 	const struct btf_ext_info_sec *sec;
2329 	const struct bpf_core_relo *relo;
2330 	const struct btf_ext_info *seg;
2331 	struct hashmap_entry *entry;
2332 	struct hashmap *cand_cache = NULL;
2333 	struct btf_ext *btf_ext = NULL;
2334 	unsigned int relo_idx;
2335 	struct btf *btf = NULL;
2336 	size_t i;
2337 	int err;
2338 
2339 	btf = btf__parse(obj_path, &btf_ext);
2340 	if (!btf) {
2341 		err = -errno;
2342 		p_err("failed to parse BPF object '%s': %s", obj_path, strerror(errno));
2343 		return err;
2344 	}
2345 
2346 	if (!btf_ext) {
2347 		p_err("failed to parse BPF object '%s': section %s not found",
2348 		      obj_path, BTF_EXT_ELF_SEC);
2349 		err = -EINVAL;
2350 		goto out;
2351 	}
2352 
2353 	if (btf_ext->core_relo_info.len == 0) {
2354 		err = 0;
2355 		goto out;
2356 	}
2357 
2358 	cand_cache = hashmap__new(btfgen_hash_fn, btfgen_equal_fn, NULL);
2359 	if (IS_ERR(cand_cache)) {
2360 		err = PTR_ERR(cand_cache);
2361 		goto out;
2362 	}
2363 
2364 	seg = &btf_ext->core_relo_info;
2365 	for_each_btf_ext_sec(seg, sec) {
2366 		for_each_btf_ext_rec(seg, sec, relo_idx, relo) {
2367 			struct bpf_core_spec specs_scratch[3] = {};
2368 			struct bpf_core_relo_res targ_res = {};
2369 			struct bpf_core_cand_list *cands = NULL;
2370 			const char *sec_name = btf__name_by_offset(btf, sec->sec_name_off);
2371 
2372 			if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
2373 			    !hashmap__find(cand_cache, relo->type_id, &cands)) {
2374 				cands = btfgen_find_cands(btf, info->src_btf, relo->type_id);
2375 				if (!cands) {
2376 					err = -errno;
2377 					goto out;
2378 				}
2379 
2380 				err = hashmap__set(cand_cache, relo->type_id, cands,
2381 						   NULL, NULL);
2382 				if (err)
2383 					goto out;
2384 			}
2385 
2386 			err = bpf_core_calc_relo_insn(sec_name, relo, relo_idx, btf, cands,
2387 						      specs_scratch, &targ_res);
2388 			if (err)
2389 				goto out;
2390 
2391 			/* specs_scratch[2] is the target spec */
2392 			err = btfgen_record_reloc(info, &specs_scratch[2]);
2393 			if (err)
2394 				goto out;
2395 		}
2396 	}
2397 
2398 out:
2399 	btf__free(btf);
2400 	btf_ext__free(btf_ext);
2401 
2402 	if (!IS_ERR_OR_NULL(cand_cache)) {
2403 		hashmap__for_each_entry(cand_cache, entry, i) {
2404 			bpf_core_free_cands(entry->pvalue);
2405 		}
2406 		hashmap__free(cand_cache);
2407 	}
2408 
2409 	return err;
2410 }
2411 
2412 /* Generate BTF from relocation information previously recorded */
2413 static struct btf *btfgen_get_btf(struct btfgen_info *info)
2414 {
2415 	struct btf *btf_new = NULL;
2416 	unsigned int *ids = NULL;
2417 	unsigned int i, n = btf__type_cnt(info->marked_btf);
2418 	int err = 0;
2419 
2420 	btf_new = btf__new_empty();
2421 	if (!btf_new) {
2422 		err = -errno;
2423 		goto err_out;
2424 	}
2425 
2426 	ids = calloc(n, sizeof(*ids));
2427 	if (!ids) {
2428 		err = -errno;
2429 		goto err_out;
2430 	}
2431 
2432 	/* first pass: add all marked types to btf_new and add their new ids to the ids map */
2433 	for (i = 1; i < n; i++) {
2434 		const struct btf_type *cloned_type, *type;
2435 		const char *name;
2436 		int new_id;
2437 
2438 		cloned_type = btf__type_by_id(info->marked_btf, i);
2439 
2440 		if (cloned_type->name_off != MARKED)
2441 			continue;
2442 
2443 		type = btf__type_by_id(info->src_btf, i);
2444 
2445 		/* add members for struct and union */
2446 		if (btf_is_composite(type)) {
2447 			struct btf_member *cloned_m, *m;
2448 			unsigned short vlen;
2449 			int idx_src;
2450 
2451 			name = btf__str_by_offset(info->src_btf, type->name_off);
2452 
2453 			if (btf_is_struct(type))
2454 				err = btf__add_struct(btf_new, name, type->size);
2455 			else
2456 				err = btf__add_union(btf_new, name, type->size);
2457 
2458 			if (err < 0)
2459 				goto err_out;
2460 			new_id = err;
2461 
2462 			cloned_m = btf_members(cloned_type);
2463 			m = btf_members(type);
2464 			vlen = btf_vlen(cloned_type);
2465 			for (idx_src = 0; idx_src < vlen; idx_src++, cloned_m++, m++) {
2466 				/* add only members that are marked as used */
2467 				if (cloned_m->name_off != MARKED)
2468 					continue;
2469 
2470 				name = btf__str_by_offset(info->src_btf, m->name_off);
2471 				err = btf__add_field(btf_new, name, m->type,
2472 						     btf_member_bit_offset(cloned_type, idx_src),
2473 						     btf_member_bitfield_size(cloned_type, idx_src));
2474 				if (err < 0)
2475 					goto err_out;
2476 			}
2477 		} else {
2478 			err = btf__add_type(btf_new, info->src_btf, type);
2479 			if (err < 0)
2480 				goto err_out;
2481 			new_id = err;
2482 		}
2483 
2484 		/* add ID mapping */
2485 		ids[i] = new_id;
2486 	}
2487 
2488 	/* second pass: fix up type ids */
2489 	for (i = 1; i < btf__type_cnt(btf_new); i++) {
2490 		struct btf_type *btf_type = (struct btf_type *) btf__type_by_id(btf_new, i);
2491 		struct btf_field_iter it;
2492 		__u32 *type_id;
2493 
2494 		err = btf_field_iter_init(&it, btf_type, BTF_FIELD_ITER_IDS);
2495 		if (err)
2496 			goto err_out;
2497 
2498 		while ((type_id = btf_field_iter_next(&it)))
2499 			*type_id = ids[*type_id];
2500 	}
2501 
2502 	free(ids);
2503 	return btf_new;
2504 
2505 err_out:
2506 	btf__free(btf_new);
2507 	free(ids);
2508 	errno = -err;
2509 	return NULL;
2510 }
2511 
2512 /* Create minimized BTF file for a set of BPF objects.
2513  *
2514  * The BTFGen algorithm is divided in two main parts: (1) collect the
2515  * BTF types that are involved in relocations and (2) generate the BTF
2516  * object using the collected types.
2517  *
2518  * In order to collect the types involved in the relocations, we parse
2519  * the BTF and BTF.ext sections of the BPF objects and use
2520  * bpf_core_calc_relo_insn() to get the target specification, this
2521  * indicates how the types and fields are used in a relocation.
2522  *
2523  * Types are recorded in different ways according to the kind of the
2524  * relocation. For field-based relocations only the members that are
2525  * actually used are saved in order to reduce the size of the generated
2526  * BTF file. For type-based relocations empty struct / unions are
2527  * generated and for enum-based relocations the whole type is saved.
2528  *
2529  * The second part of the algorithm generates the BTF object. It creates
2530  * an empty BTF object and fills it with the types recorded in the
2531  * previous step. This function takes care of only adding the structure
2532  * and union members that were marked as used and it also fixes up the
2533  * type IDs on the generated BTF object.
2534  */
2535 static int minimize_btf(const char *src_btf, const char *dst_btf, const char *objspaths[])
2536 {
2537 	struct btfgen_info *info;
2538 	struct btf *btf_new = NULL;
2539 	int err, i;
2540 
2541 	info = btfgen_new_info(src_btf);
2542 	if (!info) {
2543 		err = -errno;
2544 		p_err("failed to allocate info structure: %s", strerror(errno));
2545 		goto out;
2546 	}
2547 
2548 	for (i = 0; objspaths[i] != NULL; i++) {
2549 		err = btfgen_record_obj(info, objspaths[i]);
2550 		if (err) {
2551 			p_err("error recording relocations for %s: %s", objspaths[i],
2552 			      strerror(errno));
2553 			goto out;
2554 		}
2555 	}
2556 
2557 	btf_new = btfgen_get_btf(info);
2558 	if (!btf_new) {
2559 		err = -errno;
2560 		p_err("error generating BTF: %s", strerror(errno));
2561 		goto out;
2562 	}
2563 
2564 	err = btf_save_raw(btf_new, dst_btf);
2565 	if (err) {
2566 		p_err("error saving btf file: %s", strerror(errno));
2567 		goto out;
2568 	}
2569 
2570 out:
2571 	btf__free(btf_new);
2572 	btfgen_free_info(info);
2573 
2574 	return err;
2575 }
2576 
2577 static int do_min_core_btf(int argc, char **argv)
2578 {
2579 	const char *input, *output, **objs;
2580 	int i, err;
2581 
2582 	if (!REQ_ARGS(3)) {
2583 		usage();
2584 		return -1;
2585 	}
2586 
2587 	input = GET_ARG();
2588 	output = GET_ARG();
2589 
2590 	objs = (const char **) calloc(argc + 1, sizeof(*objs));
2591 	if (!objs) {
2592 		p_err("failed to allocate array for object names");
2593 		return -ENOMEM;
2594 	}
2595 
2596 	i = 0;
2597 	while (argc)
2598 		objs[i++] = GET_ARG();
2599 
2600 	err = minimize_btf(input, output, objs);
2601 	free(objs);
2602 	return err;
2603 }
2604 
2605 static const struct cmd cmds[] = {
2606 	{ "object",		do_object },
2607 	{ "skeleton",		do_skeleton },
2608 	{ "subskeleton",	do_subskeleton },
2609 	{ "min_core_btf",	do_min_core_btf},
2610 	{ "help",		do_help },
2611 	{ 0 }
2612 };
2613 
2614 int do_gen(int argc, char **argv)
2615 {
2616 	return cmd_select(cmds, argc, argv, do_help);
2617 }
2618