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