xref: /linux/tools/bpf/bpftool/gen.c (revision a6a6a98094116b60e5523a571d9443c53325f5b1)
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 		struct %1$s {						    \n\
1276 			struct bpf_object_skeleton *skeleton;		    \n\
1277 			struct bpf_object *obj;				    \n\
1278 		",
1279 		obj_name, header_guard
1280 		);
1281 	}
1282 
1283 	if (map_cnt) {
1284 		printf("\tstruct {\n");
1285 		bpf_object__for_each_map(map, obj) {
1286 			if (!get_map_ident(map, ident, sizeof(ident)))
1287 				continue;
1288 			if (use_loader)
1289 				printf("\t\tstruct bpf_map_desc %s;\n", ident);
1290 			else
1291 				printf("\t\tstruct bpf_map *%s;\n", ident);
1292 		}
1293 		printf("\t} maps;\n");
1294 	}
1295 
1296 	btf = bpf_object__btf(obj);
1297 	err = gen_st_ops_shadow(obj_name, btf, obj);
1298 	if (err)
1299 		goto out;
1300 
1301 	if (prog_cnt) {
1302 		printf("\tstruct {\n");
1303 		bpf_object__for_each_program(prog, obj) {
1304 			if (use_loader)
1305 				printf("\t\tstruct bpf_prog_desc %s;\n",
1306 				       bpf_program__name(prog));
1307 			else
1308 				printf("\t\tstruct bpf_program *%s;\n",
1309 				       bpf_program__name(prog));
1310 		}
1311 		printf("\t} progs;\n");
1312 	}
1313 
1314 	if (prog_cnt + attach_map_cnt) {
1315 		printf("\tstruct {\n");
1316 		bpf_object__for_each_program(prog, obj) {
1317 			if (use_loader)
1318 				printf("\t\tint %s_fd;\n",
1319 				       bpf_program__name(prog));
1320 			else
1321 				printf("\t\tstruct bpf_link *%s;\n",
1322 				       bpf_program__name(prog));
1323 		}
1324 
1325 		bpf_object__for_each_map(map, obj) {
1326 			if (!get_map_ident(map, ident, sizeof(ident)))
1327 				continue;
1328 			if (bpf_map__type(map) != BPF_MAP_TYPE_STRUCT_OPS)
1329 				continue;
1330 
1331 			if (use_loader)
1332 				printf("t\tint %s_fd;\n", ident);
1333 			else
1334 				printf("\t\tstruct bpf_link *%s;\n", ident);
1335 		}
1336 
1337 		printf("\t} links;\n");
1338 	}
1339 
1340 	if (btf) {
1341 		err = codegen_datasecs(obj, obj_name);
1342 		if (err)
1343 			goto out;
1344 	}
1345 	if (use_loader) {
1346 		err = gen_trace(obj, obj_name, header_guard);
1347 		goto out;
1348 	}
1349 
1350 	codegen("\
1351 		\n\
1352 									    \n\
1353 		#ifdef __cplusplus					    \n\
1354 			static inline struct %1$s *open(const struct bpf_object_open_opts *opts = nullptr);\n\
1355 			static inline struct %1$s *open_and_load();	    \n\
1356 			static inline int load(struct %1$s *skel);	    \n\
1357 			static inline int attach(struct %1$s *skel);	    \n\
1358 			static inline void detach(struct %1$s *skel);	    \n\
1359 			static inline void destroy(struct %1$s *skel);	    \n\
1360 			static inline const void *elf_bytes(size_t *sz);    \n\
1361 		#endif /* __cplusplus */				    \n\
1362 		};							    \n\
1363 									    \n\
1364 		static void						    \n\
1365 		%1$s__destroy(struct %1$s *obj)				    \n\
1366 		{							    \n\
1367 			if (!obj)					    \n\
1368 				return;					    \n\
1369 			if (obj->skeleton)				    \n\
1370 				bpf_object__destroy_skeleton(obj->skeleton);\n\
1371 			free(obj);					    \n\
1372 		}							    \n\
1373 									    \n\
1374 		static inline int					    \n\
1375 		%1$s__create_skeleton(struct %1$s *obj);		    \n\
1376 									    \n\
1377 		static inline struct %1$s *				    \n\
1378 		%1$s__open_opts(const struct bpf_object_open_opts *opts)    \n\
1379 		{							    \n\
1380 			struct %1$s *obj;				    \n\
1381 			int err;					    \n\
1382 									    \n\
1383 			obj = (struct %1$s *)calloc(1, sizeof(*obj));	    \n\
1384 			if (!obj) {					    \n\
1385 				errno = ENOMEM;				    \n\
1386 				return NULL;				    \n\
1387 			}						    \n\
1388 									    \n\
1389 			err = %1$s__create_skeleton(obj);		    \n\
1390 			if (err)					    \n\
1391 				goto err_out;				    \n\
1392 									    \n\
1393 			err = bpf_object__open_skeleton(obj->skeleton, opts);\n\
1394 			if (err)					    \n\
1395 				goto err_out;				    \n\
1396 									    \n\
1397 		", obj_name);
1398 
1399 	gen_st_ops_shadow_init(btf, obj);
1400 
1401 	codegen("\
1402 		\n\
1403 			return obj;					    \n\
1404 		err_out:						    \n\
1405 			%1$s__destroy(obj);				    \n\
1406 			errno = -err;					    \n\
1407 			return NULL;					    \n\
1408 		}							    \n\
1409 									    \n\
1410 		static inline struct %1$s *				    \n\
1411 		%1$s__open(void)					    \n\
1412 		{							    \n\
1413 			return %1$s__open_opts(NULL);			    \n\
1414 		}							    \n\
1415 									    \n\
1416 		static inline int					    \n\
1417 		%1$s__load(struct %1$s *obj)				    \n\
1418 		{							    \n\
1419 			return bpf_object__load_skeleton(obj->skeleton);    \n\
1420 		}							    \n\
1421 									    \n\
1422 		static inline struct %1$s *				    \n\
1423 		%1$s__open_and_load(void)				    \n\
1424 		{							    \n\
1425 			struct %1$s *obj;				    \n\
1426 			int err;					    \n\
1427 									    \n\
1428 			obj = %1$s__open();				    \n\
1429 			if (!obj)					    \n\
1430 				return NULL;				    \n\
1431 			err = %1$s__load(obj);				    \n\
1432 			if (err) {					    \n\
1433 				%1$s__destroy(obj);			    \n\
1434 				errno = -err;				    \n\
1435 				return NULL;				    \n\
1436 			}						    \n\
1437 			return obj;					    \n\
1438 		}							    \n\
1439 									    \n\
1440 		static inline int					    \n\
1441 		%1$s__attach(struct %1$s *obj)				    \n\
1442 		{							    \n\
1443 			return bpf_object__attach_skeleton(obj->skeleton);  \n\
1444 		}							    \n\
1445 									    \n\
1446 		static inline void					    \n\
1447 		%1$s__detach(struct %1$s *obj)				    \n\
1448 		{							    \n\
1449 			bpf_object__detach_skeleton(obj->skeleton);	    \n\
1450 		}							    \n\
1451 		",
1452 		obj_name
1453 	);
1454 
1455 	codegen("\
1456 		\n\
1457 									    \n\
1458 		static inline const void *%1$s__elf_bytes(size_t *sz);	    \n\
1459 									    \n\
1460 		static inline int					    \n\
1461 		%1$s__create_skeleton(struct %1$s *obj)			    \n\
1462 		{							    \n\
1463 			struct bpf_object_skeleton *s;			    \n\
1464 			int err;					    \n\
1465 									    \n\
1466 			s = (struct bpf_object_skeleton *)calloc(1, sizeof(*s));\n\
1467 			if (!s)	{					    \n\
1468 				err = -ENOMEM;				    \n\
1469 				goto err;				    \n\
1470 			}						    \n\
1471 									    \n\
1472 			s->sz = sizeof(*s);				    \n\
1473 			s->name = \"%1$s\";				    \n\
1474 			s->obj = &obj->obj;				    \n\
1475 		",
1476 		obj_name
1477 	);
1478 
1479 	codegen_maps_skeleton(obj, map_cnt, true /*mmaped*/, true /*links*/);
1480 	codegen_progs_skeleton(obj, prog_cnt, true /*populate_links*/);
1481 
1482 	codegen("\
1483 		\n\
1484 									    \n\
1485 			s->data = %1$s__elf_bytes(&s->data_sz);		    \n\
1486 									    \n\
1487 			obj->skeleton = s;				    \n\
1488 			return 0;					    \n\
1489 		err:							    \n\
1490 			bpf_object__destroy_skeleton(s);		    \n\
1491 			return err;					    \n\
1492 		}							    \n\
1493 									    \n\
1494 		static inline const void *%1$s__elf_bytes(size_t *sz)	    \n\
1495 		{							    \n\
1496 			static const char data[] __attribute__((__aligned__(8))) = \"\\\n\
1497 		",
1498 		obj_name
1499 	);
1500 
1501 	/* embed contents of BPF object file */
1502 	print_hex(obj_data, file_sz);
1503 
1504 	codegen("\
1505 		\n\
1506 		\";							    \n\
1507 									    \n\
1508 			*sz = sizeof(data) - 1;				    \n\
1509 			return (const void *)data;			    \n\
1510 		}							    \n\
1511 									    \n\
1512 		#ifdef __cplusplus					    \n\
1513 		struct %1$s *%1$s::open(const struct bpf_object_open_opts *opts) { return %1$s__open_opts(opts); }\n\
1514 		struct %1$s *%1$s::open_and_load() { return %1$s__open_and_load(); }	\n\
1515 		int %1$s::load(struct %1$s *skel) { return %1$s__load(skel); }		\n\
1516 		int %1$s::attach(struct %1$s *skel) { return %1$s__attach(skel); }	\n\
1517 		void %1$s::detach(struct %1$s *skel) { %1$s__detach(skel); }		\n\
1518 		void %1$s::destroy(struct %1$s *skel) { %1$s__destroy(skel); }		\n\
1519 		const void *%1$s::elf_bytes(size_t *sz) { return %1$s__elf_bytes(sz); } \n\
1520 		#endif /* __cplusplus */				    \n\
1521 									    \n\
1522 		",
1523 		obj_name);
1524 
1525 	codegen_asserts(obj, obj_name);
1526 
1527 	codegen("\
1528 		\n\
1529 									    \n\
1530 		#endif /* %1$s */					    \n\
1531 		",
1532 		header_guard);
1533 	err = 0;
1534 out:
1535 	bpf_object__close(obj);
1536 	if (obj_data)
1537 		munmap(obj_data, mmap_sz);
1538 	close(fd);
1539 	return err;
1540 }
1541 
1542 /* Subskeletons are like skeletons, except they don't own the bpf_object,
1543  * associated maps, links, etc. Instead, they know about the existence of
1544  * variables, maps, programs and are able to find their locations
1545  * _at runtime_ from an already loaded bpf_object.
1546  *
1547  * This allows for library-like BPF objects to have userspace counterparts
1548  * with access to their own items without having to know anything about the
1549  * final BPF object that the library was linked into.
1550  */
1551 static int do_subskeleton(int argc, char **argv)
1552 {
1553 	char header_guard[MAX_OBJ_NAME_LEN + sizeof("__SUBSKEL_H__")];
1554 	size_t i, len, file_sz, map_cnt = 0, prog_cnt = 0, mmap_sz, var_cnt = 0, var_idx = 0;
1555 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts);
1556 	char obj_name[MAX_OBJ_NAME_LEN] = "", *obj_data;
1557 	struct bpf_object *obj = NULL;
1558 	const char *file, *var_name;
1559 	char ident[256];
1560 	int fd, err = -1, map_type_id;
1561 	const struct bpf_map *map;
1562 	struct bpf_program *prog;
1563 	struct btf *btf;
1564 	const struct btf_type *map_type, *var_type;
1565 	const struct btf_var_secinfo *var;
1566 	struct stat st;
1567 
1568 	if (!REQ_ARGS(1)) {
1569 		usage();
1570 		return -1;
1571 	}
1572 	file = GET_ARG();
1573 
1574 	while (argc) {
1575 		if (!REQ_ARGS(2))
1576 			return -1;
1577 
1578 		if (is_prefix(*argv, "name")) {
1579 			NEXT_ARG();
1580 
1581 			if (obj_name[0] != '\0') {
1582 				p_err("object name already specified");
1583 				return -1;
1584 			}
1585 
1586 			strncpy(obj_name, *argv, MAX_OBJ_NAME_LEN - 1);
1587 			obj_name[MAX_OBJ_NAME_LEN - 1] = '\0';
1588 		} else {
1589 			p_err("unknown arg %s", *argv);
1590 			return -1;
1591 		}
1592 
1593 		NEXT_ARG();
1594 	}
1595 
1596 	if (argc) {
1597 		p_err("extra unknown arguments");
1598 		return -1;
1599 	}
1600 
1601 	if (use_loader) {
1602 		p_err("cannot use loader for subskeletons");
1603 		return -1;
1604 	}
1605 
1606 	if (stat(file, &st)) {
1607 		p_err("failed to stat() %s: %s", file, strerror(errno));
1608 		return -1;
1609 	}
1610 	file_sz = st.st_size;
1611 	mmap_sz = roundup(file_sz, sysconf(_SC_PAGE_SIZE));
1612 	fd = open(file, O_RDONLY);
1613 	if (fd < 0) {
1614 		p_err("failed to open() %s: %s", file, strerror(errno));
1615 		return -1;
1616 	}
1617 	obj_data = mmap(NULL, mmap_sz, PROT_READ, MAP_PRIVATE, fd, 0);
1618 	if (obj_data == MAP_FAILED) {
1619 		obj_data = NULL;
1620 		p_err("failed to mmap() %s: %s", file, strerror(errno));
1621 		goto out;
1622 	}
1623 	if (obj_name[0] == '\0')
1624 		get_obj_name(obj_name, file);
1625 
1626 	/* The empty object name allows us to use bpf_map__name and produce
1627 	 * ELF section names out of it. (".data" instead of "obj.data")
1628 	 */
1629 	opts.object_name = "";
1630 	obj = bpf_object__open_mem(obj_data, file_sz, &opts);
1631 	if (!obj) {
1632 		char err_buf[256];
1633 
1634 		libbpf_strerror(errno, err_buf, sizeof(err_buf));
1635 		p_err("failed to open BPF object file: %s", err_buf);
1636 		obj = NULL;
1637 		goto out;
1638 	}
1639 
1640 	btf = bpf_object__btf(obj);
1641 	if (!btf) {
1642 		err = -1;
1643 		p_err("need btf type information for %s", obj_name);
1644 		goto out;
1645 	}
1646 
1647 	bpf_object__for_each_program(prog, obj) {
1648 		prog_cnt++;
1649 	}
1650 
1651 	/* First, count how many variables we have to find.
1652 	 * We need this in advance so the subskel can allocate the right
1653 	 * amount of storage.
1654 	 */
1655 	bpf_object__for_each_map(map, obj) {
1656 		if (!get_map_ident(map, ident, sizeof(ident)))
1657 			continue;
1658 
1659 		/* Also count all maps that have a name */
1660 		map_cnt++;
1661 
1662 		if (!is_mmapable_map(map, ident, sizeof(ident)))
1663 			continue;
1664 
1665 		map_type_id = bpf_map__btf_value_type_id(map);
1666 		if (map_type_id <= 0) {
1667 			err = map_type_id;
1668 			goto out;
1669 		}
1670 		map_type = btf__type_by_id(btf, map_type_id);
1671 
1672 		var = btf_var_secinfos(map_type);
1673 		len = btf_vlen(map_type);
1674 		for (i = 0; i < len; i++, var++) {
1675 			var_type = btf__type_by_id(btf, var->type);
1676 
1677 			if (btf_var(var_type)->linkage == BTF_VAR_STATIC)
1678 				continue;
1679 
1680 			var_cnt++;
1681 		}
1682 	}
1683 
1684 	get_header_guard(header_guard, obj_name, "SUBSKEL_H");
1685 	codegen("\
1686 	\n\
1687 	/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */	    \n\
1688 									    \n\
1689 	/* THIS FILE IS AUTOGENERATED! */				    \n\
1690 	#ifndef %2$s							    \n\
1691 	#define %2$s							    \n\
1692 									    \n\
1693 	#include <errno.h>						    \n\
1694 	#include <stdlib.h>						    \n\
1695 	#include <bpf/libbpf.h>						    \n\
1696 									    \n\
1697 	struct %1$s {							    \n\
1698 		struct bpf_object *obj;					    \n\
1699 		struct bpf_object_subskeleton *subskel;			    \n\
1700 	", obj_name, header_guard);
1701 
1702 	if (map_cnt) {
1703 		printf("\tstruct {\n");
1704 		bpf_object__for_each_map(map, obj) {
1705 			if (!get_map_ident(map, ident, sizeof(ident)))
1706 				continue;
1707 			printf("\t\tstruct bpf_map *%s;\n", ident);
1708 		}
1709 		printf("\t} maps;\n");
1710 	}
1711 
1712 	err = gen_st_ops_shadow(obj_name, btf, obj);
1713 	if (err)
1714 		goto out;
1715 
1716 	if (prog_cnt) {
1717 		printf("\tstruct {\n");
1718 		bpf_object__for_each_program(prog, obj) {
1719 			printf("\t\tstruct bpf_program *%s;\n",
1720 				bpf_program__name(prog));
1721 		}
1722 		printf("\t} progs;\n");
1723 	}
1724 
1725 	err = codegen_subskel_datasecs(obj, obj_name);
1726 	if (err)
1727 		goto out;
1728 
1729 	/* emit code that will allocate enough storage for all symbols */
1730 	codegen("\
1731 		\n\
1732 									    \n\
1733 		#ifdef __cplusplus					    \n\
1734 			static inline struct %1$s *open(const struct bpf_object *src);\n\
1735 			static inline void destroy(struct %1$s *skel);	    \n\
1736 		#endif /* __cplusplus */				    \n\
1737 		};							    \n\
1738 									    \n\
1739 		static inline void					    \n\
1740 		%1$s__destroy(struct %1$s *skel)			    \n\
1741 		{							    \n\
1742 			if (!skel)					    \n\
1743 				return;					    \n\
1744 			if (skel->subskel)				    \n\
1745 				bpf_object__destroy_subskeleton(skel->subskel);\n\
1746 			free(skel);					    \n\
1747 		}							    \n\
1748 									    \n\
1749 		static inline struct %1$s *				    \n\
1750 		%1$s__open(const struct bpf_object *src)		    \n\
1751 		{							    \n\
1752 			struct %1$s *obj;				    \n\
1753 			struct bpf_object_subskeleton *s;		    \n\
1754 			int err;					    \n\
1755 									    \n\
1756 			obj = (struct %1$s *)calloc(1, sizeof(*obj));	    \n\
1757 			if (!obj) {					    \n\
1758 				err = -ENOMEM;				    \n\
1759 				goto err;				    \n\
1760 			}						    \n\
1761 			s = (struct bpf_object_subskeleton *)calloc(1, sizeof(*s));\n\
1762 			if (!s) {					    \n\
1763 				err = -ENOMEM;				    \n\
1764 				goto err;				    \n\
1765 			}						    \n\
1766 			s->sz = sizeof(*s);				    \n\
1767 			s->obj = src;					    \n\
1768 			s->var_skel_sz = sizeof(*s->vars);		    \n\
1769 			obj->subskel = s;				    \n\
1770 									    \n\
1771 			/* vars */					    \n\
1772 			s->var_cnt = %2$d;				    \n\
1773 			s->vars = (struct bpf_var_skeleton *)calloc(%2$d, sizeof(*s->vars));\n\
1774 			if (!s->vars) {					    \n\
1775 				err = -ENOMEM;				    \n\
1776 				goto err;				    \n\
1777 			}						    \n\
1778 		",
1779 		obj_name, var_cnt
1780 	);
1781 
1782 	/* walk through each symbol and emit the runtime representation */
1783 	bpf_object__for_each_map(map, obj) {
1784 		if (!is_mmapable_map(map, ident, sizeof(ident)))
1785 			continue;
1786 
1787 		map_type_id = bpf_map__btf_value_type_id(map);
1788 		if (map_type_id <= 0)
1789 			/* skip over internal maps with no type*/
1790 			continue;
1791 
1792 		map_type = btf__type_by_id(btf, map_type_id);
1793 		var = btf_var_secinfos(map_type);
1794 		len = btf_vlen(map_type);
1795 		for (i = 0; i < len; i++, var++) {
1796 			var_type = btf__type_by_id(btf, var->type);
1797 			var_name = btf__name_by_offset(btf, var_type->name_off);
1798 
1799 			if (btf_var(var_type)->linkage == BTF_VAR_STATIC)
1800 				continue;
1801 
1802 			/* Note that we use the dot prefix in .data as the
1803 			 * field access operator i.e. maps%s becomes maps.data
1804 			 */
1805 			codegen("\
1806 			\n\
1807 									    \n\
1808 				s->vars[%3$d].name = \"%1$s\";		    \n\
1809 				s->vars[%3$d].map = &obj->maps.%2$s;	    \n\
1810 				s->vars[%3$d].addr = (void **) &obj->%2$s.%1$s;\n\
1811 			", var_name, ident, var_idx);
1812 
1813 			var_idx++;
1814 		}
1815 	}
1816 
1817 	codegen_maps_skeleton(obj, map_cnt, false /*mmaped*/, false /*links*/);
1818 	codegen_progs_skeleton(obj, prog_cnt, false /*links*/);
1819 
1820 	codegen("\
1821 		\n\
1822 									    \n\
1823 			err = bpf_object__open_subskeleton(s);		    \n\
1824 			if (err)					    \n\
1825 				goto err;				    \n\
1826 									    \n\
1827 		");
1828 
1829 	gen_st_ops_shadow_init(btf, obj);
1830 
1831 	codegen("\
1832 		\n\
1833 			return obj;					    \n\
1834 		err:							    \n\
1835 			%1$s__destroy(obj);				    \n\
1836 			errno = -err;					    \n\
1837 			return NULL;					    \n\
1838 		}							    \n\
1839 									    \n\
1840 		#ifdef __cplusplus					    \n\
1841 		struct %1$s *%1$s::open(const struct bpf_object *src) { return %1$s__open(src); }\n\
1842 		void %1$s::destroy(struct %1$s *skel) { %1$s__destroy(skel); }\n\
1843 		#endif /* __cplusplus */				    \n\
1844 									    \n\
1845 		#endif /* %2$s */					    \n\
1846 		",
1847 		obj_name, header_guard);
1848 	err = 0;
1849 out:
1850 	bpf_object__close(obj);
1851 	if (obj_data)
1852 		munmap(obj_data, mmap_sz);
1853 	close(fd);
1854 	return err;
1855 }
1856 
1857 static int do_object(int argc, char **argv)
1858 {
1859 	struct bpf_linker *linker;
1860 	const char *output_file, *file;
1861 	int err = 0;
1862 
1863 	if (!REQ_ARGS(2)) {
1864 		usage();
1865 		return -1;
1866 	}
1867 
1868 	output_file = GET_ARG();
1869 
1870 	linker = bpf_linker__new(output_file, NULL);
1871 	if (!linker) {
1872 		p_err("failed to create BPF linker instance");
1873 		return -1;
1874 	}
1875 
1876 	while (argc) {
1877 		file = GET_ARG();
1878 
1879 		err = bpf_linker__add_file(linker, file, NULL);
1880 		if (err) {
1881 			p_err("failed to link '%s': %s (%d)", file, strerror(errno), errno);
1882 			goto out;
1883 		}
1884 	}
1885 
1886 	err = bpf_linker__finalize(linker);
1887 	if (err) {
1888 		p_err("failed to finalize ELF file: %s (%d)", strerror(errno), errno);
1889 		goto out;
1890 	}
1891 
1892 	err = 0;
1893 out:
1894 	bpf_linker__free(linker);
1895 	return err;
1896 }
1897 
1898 static int do_help(int argc, char **argv)
1899 {
1900 	if (json_output) {
1901 		jsonw_null(json_wtr);
1902 		return 0;
1903 	}
1904 
1905 	fprintf(stderr,
1906 		"Usage: %1$s %2$s object OUTPUT_FILE INPUT_FILE [INPUT_FILE...]\n"
1907 		"       %1$s %2$s skeleton FILE [name OBJECT_NAME]\n"
1908 		"       %1$s %2$s subskeleton FILE [name OBJECT_NAME]\n"
1909 		"       %1$s %2$s min_core_btf INPUT OUTPUT OBJECT [OBJECT...]\n"
1910 		"       %1$s %2$s help\n"
1911 		"\n"
1912 		"       " HELP_SPEC_OPTIONS " |\n"
1913 		"                    {-L|--use-loader} }\n"
1914 		"",
1915 		bin_name, "gen");
1916 
1917 	return 0;
1918 }
1919 
1920 static int btf_save_raw(const struct btf *btf, const char *path)
1921 {
1922 	const void *data;
1923 	FILE *f = NULL;
1924 	__u32 data_sz;
1925 	int err = 0;
1926 
1927 	data = btf__raw_data(btf, &data_sz);
1928 	if (!data)
1929 		return -ENOMEM;
1930 
1931 	f = fopen(path, "wb");
1932 	if (!f)
1933 		return -errno;
1934 
1935 	if (fwrite(data, 1, data_sz, f) != data_sz)
1936 		err = -errno;
1937 
1938 	fclose(f);
1939 	return err;
1940 }
1941 
1942 struct btfgen_info {
1943 	struct btf *src_btf;
1944 	struct btf *marked_btf; /* btf structure used to mark used types */
1945 };
1946 
1947 static size_t btfgen_hash_fn(long key, void *ctx)
1948 {
1949 	return key;
1950 }
1951 
1952 static bool btfgen_equal_fn(long k1, long k2, void *ctx)
1953 {
1954 	return k1 == k2;
1955 }
1956 
1957 static void btfgen_free_info(struct btfgen_info *info)
1958 {
1959 	if (!info)
1960 		return;
1961 
1962 	btf__free(info->src_btf);
1963 	btf__free(info->marked_btf);
1964 
1965 	free(info);
1966 }
1967 
1968 static struct btfgen_info *
1969 btfgen_new_info(const char *targ_btf_path)
1970 {
1971 	struct btfgen_info *info;
1972 	int err;
1973 
1974 	info = calloc(1, sizeof(*info));
1975 	if (!info)
1976 		return NULL;
1977 
1978 	info->src_btf = btf__parse(targ_btf_path, NULL);
1979 	if (!info->src_btf) {
1980 		err = -errno;
1981 		p_err("failed parsing '%s' BTF file: %s", targ_btf_path, strerror(errno));
1982 		goto err_out;
1983 	}
1984 
1985 	info->marked_btf = btf__parse(targ_btf_path, NULL);
1986 	if (!info->marked_btf) {
1987 		err = -errno;
1988 		p_err("failed parsing '%s' BTF file: %s", targ_btf_path, strerror(errno));
1989 		goto err_out;
1990 	}
1991 
1992 	return info;
1993 
1994 err_out:
1995 	btfgen_free_info(info);
1996 	errno = -err;
1997 	return NULL;
1998 }
1999 
2000 #define MARKED UINT32_MAX
2001 
2002 static void btfgen_mark_member(struct btfgen_info *info, int type_id, int idx)
2003 {
2004 	const struct btf_type *t = btf__type_by_id(info->marked_btf, type_id);
2005 	struct btf_member *m = btf_members(t) + idx;
2006 
2007 	m->name_off = MARKED;
2008 }
2009 
2010 static int
2011 btfgen_mark_type(struct btfgen_info *info, unsigned int type_id, bool follow_pointers)
2012 {
2013 	const struct btf_type *btf_type = btf__type_by_id(info->src_btf, type_id);
2014 	struct btf_type *cloned_type;
2015 	struct btf_param *param;
2016 	struct btf_array *array;
2017 	int err, i;
2018 
2019 	if (type_id == 0)
2020 		return 0;
2021 
2022 	/* mark type on cloned BTF as used */
2023 	cloned_type = (struct btf_type *) btf__type_by_id(info->marked_btf, type_id);
2024 	cloned_type->name_off = MARKED;
2025 
2026 	/* recursively mark other types needed by it */
2027 	switch (btf_kind(btf_type)) {
2028 	case BTF_KIND_UNKN:
2029 	case BTF_KIND_INT:
2030 	case BTF_KIND_FLOAT:
2031 	case BTF_KIND_ENUM:
2032 	case BTF_KIND_ENUM64:
2033 	case BTF_KIND_STRUCT:
2034 	case BTF_KIND_UNION:
2035 		break;
2036 	case BTF_KIND_PTR:
2037 		if (follow_pointers) {
2038 			err = btfgen_mark_type(info, btf_type->type, follow_pointers);
2039 			if (err)
2040 				return err;
2041 		}
2042 		break;
2043 	case BTF_KIND_CONST:
2044 	case BTF_KIND_RESTRICT:
2045 	case BTF_KIND_VOLATILE:
2046 	case BTF_KIND_TYPEDEF:
2047 		err = btfgen_mark_type(info, btf_type->type, follow_pointers);
2048 		if (err)
2049 			return err;
2050 		break;
2051 	case BTF_KIND_ARRAY:
2052 		array = btf_array(btf_type);
2053 
2054 		/* mark array type */
2055 		err = btfgen_mark_type(info, array->type, follow_pointers);
2056 		/* mark array's index type */
2057 		err = err ? : btfgen_mark_type(info, array->index_type, follow_pointers);
2058 		if (err)
2059 			return err;
2060 		break;
2061 	case BTF_KIND_FUNC_PROTO:
2062 		/* mark ret type */
2063 		err = btfgen_mark_type(info, btf_type->type, follow_pointers);
2064 		if (err)
2065 			return err;
2066 
2067 		/* mark parameters types */
2068 		param = btf_params(btf_type);
2069 		for (i = 0; i < btf_vlen(btf_type); i++) {
2070 			err = btfgen_mark_type(info, param->type, follow_pointers);
2071 			if (err)
2072 				return err;
2073 			param++;
2074 		}
2075 		break;
2076 	/* tells if some other type needs to be handled */
2077 	default:
2078 		p_err("unsupported kind: %s (%d)", btf_kind_str(btf_type), type_id);
2079 		return -EINVAL;
2080 	}
2081 
2082 	return 0;
2083 }
2084 
2085 static int btfgen_record_field_relo(struct btfgen_info *info, struct bpf_core_spec *targ_spec)
2086 {
2087 	struct btf *btf = info->src_btf;
2088 	const struct btf_type *btf_type;
2089 	struct btf_member *btf_member;
2090 	struct btf_array *array;
2091 	unsigned int type_id = targ_spec->root_type_id;
2092 	int idx, err;
2093 
2094 	/* mark root type */
2095 	btf_type = btf__type_by_id(btf, type_id);
2096 	err = btfgen_mark_type(info, type_id, false);
2097 	if (err)
2098 		return err;
2099 
2100 	/* mark types for complex types (arrays, unions, structures) */
2101 	for (int i = 1; i < targ_spec->raw_len; i++) {
2102 		/* skip typedefs and mods */
2103 		while (btf_is_mod(btf_type) || btf_is_typedef(btf_type)) {
2104 			type_id = btf_type->type;
2105 			btf_type = btf__type_by_id(btf, type_id);
2106 		}
2107 
2108 		switch (btf_kind(btf_type)) {
2109 		case BTF_KIND_STRUCT:
2110 		case BTF_KIND_UNION:
2111 			idx = targ_spec->raw_spec[i];
2112 			btf_member = btf_members(btf_type) + idx;
2113 
2114 			/* mark member */
2115 			btfgen_mark_member(info, type_id, idx);
2116 
2117 			/* mark member's type */
2118 			type_id = btf_member->type;
2119 			btf_type = btf__type_by_id(btf, type_id);
2120 			err = btfgen_mark_type(info, type_id, false);
2121 			if (err)
2122 				return err;
2123 			break;
2124 		case BTF_KIND_ARRAY:
2125 			array = btf_array(btf_type);
2126 			type_id = array->type;
2127 			btf_type = btf__type_by_id(btf, type_id);
2128 			break;
2129 		default:
2130 			p_err("unsupported kind: %s (%d)",
2131 			      btf_kind_str(btf_type), btf_type->type);
2132 			return -EINVAL;
2133 		}
2134 	}
2135 
2136 	return 0;
2137 }
2138 
2139 /* Mark types, members, and member types. Compared to btfgen_record_field_relo,
2140  * this function does not rely on the target spec for inferring members, but
2141  * uses the associated BTF.
2142  *
2143  * The `behind_ptr` argument is used to stop marking of composite types reached
2144  * through a pointer. This way, we can keep BTF size in check while providing
2145  * reasonable match semantics.
2146  */
2147 static int btfgen_mark_type_match(struct btfgen_info *info, __u32 type_id, bool behind_ptr)
2148 {
2149 	const struct btf_type *btf_type;
2150 	struct btf *btf = info->src_btf;
2151 	struct btf_type *cloned_type;
2152 	int i, err;
2153 
2154 	if (type_id == 0)
2155 		return 0;
2156 
2157 	btf_type = btf__type_by_id(btf, type_id);
2158 	/* mark type on cloned BTF as used */
2159 	cloned_type = (struct btf_type *)btf__type_by_id(info->marked_btf, type_id);
2160 	cloned_type->name_off = MARKED;
2161 
2162 	switch (btf_kind(btf_type)) {
2163 	case BTF_KIND_UNKN:
2164 	case BTF_KIND_INT:
2165 	case BTF_KIND_FLOAT:
2166 	case BTF_KIND_ENUM:
2167 	case BTF_KIND_ENUM64:
2168 		break;
2169 	case BTF_KIND_STRUCT:
2170 	case BTF_KIND_UNION: {
2171 		struct btf_member *m = btf_members(btf_type);
2172 		__u16 vlen = btf_vlen(btf_type);
2173 
2174 		if (behind_ptr)
2175 			break;
2176 
2177 		for (i = 0; i < vlen; i++, m++) {
2178 			/* mark member */
2179 			btfgen_mark_member(info, type_id, i);
2180 
2181 			/* mark member's type */
2182 			err = btfgen_mark_type_match(info, m->type, false);
2183 			if (err)
2184 				return err;
2185 		}
2186 		break;
2187 	}
2188 	case BTF_KIND_CONST:
2189 	case BTF_KIND_FWD:
2190 	case BTF_KIND_RESTRICT:
2191 	case BTF_KIND_TYPEDEF:
2192 	case BTF_KIND_VOLATILE:
2193 		return btfgen_mark_type_match(info, btf_type->type, behind_ptr);
2194 	case BTF_KIND_PTR:
2195 		return btfgen_mark_type_match(info, btf_type->type, true);
2196 	case BTF_KIND_ARRAY: {
2197 		struct btf_array *array;
2198 
2199 		array = btf_array(btf_type);
2200 		/* mark array type */
2201 		err = btfgen_mark_type_match(info, array->type, false);
2202 		/* mark array's index type */
2203 		err = err ? : btfgen_mark_type_match(info, array->index_type, false);
2204 		if (err)
2205 			return err;
2206 		break;
2207 	}
2208 	case BTF_KIND_FUNC_PROTO: {
2209 		__u16 vlen = btf_vlen(btf_type);
2210 		struct btf_param *param;
2211 
2212 		/* mark ret type */
2213 		err = btfgen_mark_type_match(info, btf_type->type, false);
2214 		if (err)
2215 			return err;
2216 
2217 		/* mark parameters types */
2218 		param = btf_params(btf_type);
2219 		for (i = 0; i < vlen; i++) {
2220 			err = btfgen_mark_type_match(info, param->type, false);
2221 			if (err)
2222 				return err;
2223 			param++;
2224 		}
2225 		break;
2226 	}
2227 	/* tells if some other type needs to be handled */
2228 	default:
2229 		p_err("unsupported kind: %s (%d)", btf_kind_str(btf_type), type_id);
2230 		return -EINVAL;
2231 	}
2232 
2233 	return 0;
2234 }
2235 
2236 /* Mark types, members, and member types. Compared to btfgen_record_field_relo,
2237  * this function does not rely on the target spec for inferring members, but
2238  * uses the associated BTF.
2239  */
2240 static int btfgen_record_type_match_relo(struct btfgen_info *info, struct bpf_core_spec *targ_spec)
2241 {
2242 	return btfgen_mark_type_match(info, targ_spec->root_type_id, false);
2243 }
2244 
2245 static int btfgen_record_type_relo(struct btfgen_info *info, struct bpf_core_spec *targ_spec)
2246 {
2247 	return btfgen_mark_type(info, targ_spec->root_type_id, true);
2248 }
2249 
2250 static int btfgen_record_enumval_relo(struct btfgen_info *info, struct bpf_core_spec *targ_spec)
2251 {
2252 	return btfgen_mark_type(info, targ_spec->root_type_id, false);
2253 }
2254 
2255 static int btfgen_record_reloc(struct btfgen_info *info, struct bpf_core_spec *res)
2256 {
2257 	switch (res->relo_kind) {
2258 	case BPF_CORE_FIELD_BYTE_OFFSET:
2259 	case BPF_CORE_FIELD_BYTE_SIZE:
2260 	case BPF_CORE_FIELD_EXISTS:
2261 	case BPF_CORE_FIELD_SIGNED:
2262 	case BPF_CORE_FIELD_LSHIFT_U64:
2263 	case BPF_CORE_FIELD_RSHIFT_U64:
2264 		return btfgen_record_field_relo(info, res);
2265 	case BPF_CORE_TYPE_ID_LOCAL: /* BPF_CORE_TYPE_ID_LOCAL doesn't require kernel BTF */
2266 		return 0;
2267 	case BPF_CORE_TYPE_ID_TARGET:
2268 	case BPF_CORE_TYPE_EXISTS:
2269 	case BPF_CORE_TYPE_SIZE:
2270 		return btfgen_record_type_relo(info, res);
2271 	case BPF_CORE_TYPE_MATCHES:
2272 		return btfgen_record_type_match_relo(info, res);
2273 	case BPF_CORE_ENUMVAL_EXISTS:
2274 	case BPF_CORE_ENUMVAL_VALUE:
2275 		return btfgen_record_enumval_relo(info, res);
2276 	default:
2277 		return -EINVAL;
2278 	}
2279 }
2280 
2281 static struct bpf_core_cand_list *
2282 btfgen_find_cands(const struct btf *local_btf, const struct btf *targ_btf, __u32 local_id)
2283 {
2284 	const struct btf_type *local_type;
2285 	struct bpf_core_cand_list *cands = NULL;
2286 	struct bpf_core_cand local_cand = {};
2287 	size_t local_essent_len;
2288 	const char *local_name;
2289 	int err;
2290 
2291 	local_cand.btf = local_btf;
2292 	local_cand.id = local_id;
2293 
2294 	local_type = btf__type_by_id(local_btf, local_id);
2295 	if (!local_type) {
2296 		err = -EINVAL;
2297 		goto err_out;
2298 	}
2299 
2300 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
2301 	if (!local_name) {
2302 		err = -EINVAL;
2303 		goto err_out;
2304 	}
2305 	local_essent_len = bpf_core_essential_name_len(local_name);
2306 
2307 	cands = calloc(1, sizeof(*cands));
2308 	if (!cands)
2309 		return NULL;
2310 
2311 	err = bpf_core_add_cands(&local_cand, local_essent_len, targ_btf, "vmlinux", 1, cands);
2312 	if (err)
2313 		goto err_out;
2314 
2315 	return cands;
2316 
2317 err_out:
2318 	bpf_core_free_cands(cands);
2319 	errno = -err;
2320 	return NULL;
2321 }
2322 
2323 /* Record relocation information for a single BPF object */
2324 static int btfgen_record_obj(struct btfgen_info *info, const char *obj_path)
2325 {
2326 	const struct btf_ext_info_sec *sec;
2327 	const struct bpf_core_relo *relo;
2328 	const struct btf_ext_info *seg;
2329 	struct hashmap_entry *entry;
2330 	struct hashmap *cand_cache = NULL;
2331 	struct btf_ext *btf_ext = NULL;
2332 	unsigned int relo_idx;
2333 	struct btf *btf = NULL;
2334 	size_t i;
2335 	int err;
2336 
2337 	btf = btf__parse(obj_path, &btf_ext);
2338 	if (!btf) {
2339 		err = -errno;
2340 		p_err("failed to parse BPF object '%s': %s", obj_path, strerror(errno));
2341 		return err;
2342 	}
2343 
2344 	if (!btf_ext) {
2345 		p_err("failed to parse BPF object '%s': section %s not found",
2346 		      obj_path, BTF_EXT_ELF_SEC);
2347 		err = -EINVAL;
2348 		goto out;
2349 	}
2350 
2351 	if (btf_ext->core_relo_info.len == 0) {
2352 		err = 0;
2353 		goto out;
2354 	}
2355 
2356 	cand_cache = hashmap__new(btfgen_hash_fn, btfgen_equal_fn, NULL);
2357 	if (IS_ERR(cand_cache)) {
2358 		err = PTR_ERR(cand_cache);
2359 		goto out;
2360 	}
2361 
2362 	seg = &btf_ext->core_relo_info;
2363 	for_each_btf_ext_sec(seg, sec) {
2364 		for_each_btf_ext_rec(seg, sec, relo_idx, relo) {
2365 			struct bpf_core_spec specs_scratch[3] = {};
2366 			struct bpf_core_relo_res targ_res = {};
2367 			struct bpf_core_cand_list *cands = NULL;
2368 			const char *sec_name = btf__name_by_offset(btf, sec->sec_name_off);
2369 
2370 			if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
2371 			    !hashmap__find(cand_cache, relo->type_id, &cands)) {
2372 				cands = btfgen_find_cands(btf, info->src_btf, relo->type_id);
2373 				if (!cands) {
2374 					err = -errno;
2375 					goto out;
2376 				}
2377 
2378 				err = hashmap__set(cand_cache, relo->type_id, cands,
2379 						   NULL, NULL);
2380 				if (err)
2381 					goto out;
2382 			}
2383 
2384 			err = bpf_core_calc_relo_insn(sec_name, relo, relo_idx, btf, cands,
2385 						      specs_scratch, &targ_res);
2386 			if (err)
2387 				goto out;
2388 
2389 			/* specs_scratch[2] is the target spec */
2390 			err = btfgen_record_reloc(info, &specs_scratch[2]);
2391 			if (err)
2392 				goto out;
2393 		}
2394 	}
2395 
2396 out:
2397 	btf__free(btf);
2398 	btf_ext__free(btf_ext);
2399 
2400 	if (!IS_ERR_OR_NULL(cand_cache)) {
2401 		hashmap__for_each_entry(cand_cache, entry, i) {
2402 			bpf_core_free_cands(entry->pvalue);
2403 		}
2404 		hashmap__free(cand_cache);
2405 	}
2406 
2407 	return err;
2408 }
2409 
2410 /* Generate BTF from relocation information previously recorded */
2411 static struct btf *btfgen_get_btf(struct btfgen_info *info)
2412 {
2413 	struct btf *btf_new = NULL;
2414 	unsigned int *ids = NULL;
2415 	unsigned int i, n = btf__type_cnt(info->marked_btf);
2416 	int err = 0;
2417 
2418 	btf_new = btf__new_empty();
2419 	if (!btf_new) {
2420 		err = -errno;
2421 		goto err_out;
2422 	}
2423 
2424 	ids = calloc(n, sizeof(*ids));
2425 	if (!ids) {
2426 		err = -errno;
2427 		goto err_out;
2428 	}
2429 
2430 	/* first pass: add all marked types to btf_new and add their new ids to the ids map */
2431 	for (i = 1; i < n; i++) {
2432 		const struct btf_type *cloned_type, *type;
2433 		const char *name;
2434 		int new_id;
2435 
2436 		cloned_type = btf__type_by_id(info->marked_btf, i);
2437 
2438 		if (cloned_type->name_off != MARKED)
2439 			continue;
2440 
2441 		type = btf__type_by_id(info->src_btf, i);
2442 
2443 		/* add members for struct and union */
2444 		if (btf_is_composite(type)) {
2445 			struct btf_member *cloned_m, *m;
2446 			unsigned short vlen;
2447 			int idx_src;
2448 
2449 			name = btf__str_by_offset(info->src_btf, type->name_off);
2450 
2451 			if (btf_is_struct(type))
2452 				err = btf__add_struct(btf_new, name, type->size);
2453 			else
2454 				err = btf__add_union(btf_new, name, type->size);
2455 
2456 			if (err < 0)
2457 				goto err_out;
2458 			new_id = err;
2459 
2460 			cloned_m = btf_members(cloned_type);
2461 			m = btf_members(type);
2462 			vlen = btf_vlen(cloned_type);
2463 			for (idx_src = 0; idx_src < vlen; idx_src++, cloned_m++, m++) {
2464 				/* add only members that are marked as used */
2465 				if (cloned_m->name_off != MARKED)
2466 					continue;
2467 
2468 				name = btf__str_by_offset(info->src_btf, m->name_off);
2469 				err = btf__add_field(btf_new, name, m->type,
2470 						     btf_member_bit_offset(cloned_type, idx_src),
2471 						     btf_member_bitfield_size(cloned_type, idx_src));
2472 				if (err < 0)
2473 					goto err_out;
2474 			}
2475 		} else {
2476 			err = btf__add_type(btf_new, info->src_btf, type);
2477 			if (err < 0)
2478 				goto err_out;
2479 			new_id = err;
2480 		}
2481 
2482 		/* add ID mapping */
2483 		ids[i] = new_id;
2484 	}
2485 
2486 	/* second pass: fix up type ids */
2487 	for (i = 1; i < btf__type_cnt(btf_new); i++) {
2488 		struct btf_type *btf_type = (struct btf_type *) btf__type_by_id(btf_new, i);
2489 		struct btf_field_iter it;
2490 		__u32 *type_id;
2491 
2492 		err = btf_field_iter_init(&it, btf_type, BTF_FIELD_ITER_IDS);
2493 		if (err)
2494 			goto err_out;
2495 
2496 		while ((type_id = btf_field_iter_next(&it)))
2497 			*type_id = ids[*type_id];
2498 	}
2499 
2500 	free(ids);
2501 	return btf_new;
2502 
2503 err_out:
2504 	btf__free(btf_new);
2505 	free(ids);
2506 	errno = -err;
2507 	return NULL;
2508 }
2509 
2510 /* Create minimized BTF file for a set of BPF objects.
2511  *
2512  * The BTFGen algorithm is divided in two main parts: (1) collect the
2513  * BTF types that are involved in relocations and (2) generate the BTF
2514  * object using the collected types.
2515  *
2516  * In order to collect the types involved in the relocations, we parse
2517  * the BTF and BTF.ext sections of the BPF objects and use
2518  * bpf_core_calc_relo_insn() to get the target specification, this
2519  * indicates how the types and fields are used in a relocation.
2520  *
2521  * Types are recorded in different ways according to the kind of the
2522  * relocation. For field-based relocations only the members that are
2523  * actually used are saved in order to reduce the size of the generated
2524  * BTF file. For type-based relocations empty struct / unions are
2525  * generated and for enum-based relocations the whole type is saved.
2526  *
2527  * The second part of the algorithm generates the BTF object. It creates
2528  * an empty BTF object and fills it with the types recorded in the
2529  * previous step. This function takes care of only adding the structure
2530  * and union members that were marked as used and it also fixes up the
2531  * type IDs on the generated BTF object.
2532  */
2533 static int minimize_btf(const char *src_btf, const char *dst_btf, const char *objspaths[])
2534 {
2535 	struct btfgen_info *info;
2536 	struct btf *btf_new = NULL;
2537 	int err, i;
2538 
2539 	info = btfgen_new_info(src_btf);
2540 	if (!info) {
2541 		err = -errno;
2542 		p_err("failed to allocate info structure: %s", strerror(errno));
2543 		goto out;
2544 	}
2545 
2546 	for (i = 0; objspaths[i] != NULL; i++) {
2547 		err = btfgen_record_obj(info, objspaths[i]);
2548 		if (err) {
2549 			p_err("error recording relocations for %s: %s", objspaths[i],
2550 			      strerror(errno));
2551 			goto out;
2552 		}
2553 	}
2554 
2555 	btf_new = btfgen_get_btf(info);
2556 	if (!btf_new) {
2557 		err = -errno;
2558 		p_err("error generating BTF: %s", strerror(errno));
2559 		goto out;
2560 	}
2561 
2562 	err = btf_save_raw(btf_new, dst_btf);
2563 	if (err) {
2564 		p_err("error saving btf file: %s", strerror(errno));
2565 		goto out;
2566 	}
2567 
2568 out:
2569 	btf__free(btf_new);
2570 	btfgen_free_info(info);
2571 
2572 	return err;
2573 }
2574 
2575 static int do_min_core_btf(int argc, char **argv)
2576 {
2577 	const char *input, *output, **objs;
2578 	int i, err;
2579 
2580 	if (!REQ_ARGS(3)) {
2581 		usage();
2582 		return -1;
2583 	}
2584 
2585 	input = GET_ARG();
2586 	output = GET_ARG();
2587 
2588 	objs = (const char **) calloc(argc + 1, sizeof(*objs));
2589 	if (!objs) {
2590 		p_err("failed to allocate array for object names");
2591 		return -ENOMEM;
2592 	}
2593 
2594 	i = 0;
2595 	while (argc)
2596 		objs[i++] = GET_ARG();
2597 
2598 	err = minimize_btf(input, output, objs);
2599 	free(objs);
2600 	return err;
2601 }
2602 
2603 static const struct cmd cmds[] = {
2604 	{ "object",		do_object },
2605 	{ "skeleton",		do_skeleton },
2606 	{ "subskeleton",	do_subskeleton },
2607 	{ "min_core_btf",	do_min_core_btf},
2608 	{ "help",		do_help },
2609 	{ 0 }
2610 };
2611 
2612 int do_gen(int argc, char **argv)
2613 {
2614 	return cmd_select(cmds, argc, argv, do_help);
2615 }
2616