xref: /linux/tools/bpf/bpftool/btf.c (revision ed30aef3c864f99111e16d4ea5cf29488d99a278)
1 // SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
2 /* Copyright (C) 2019 Facebook */
3 
4 #include <errno.h>
5 #include <fcntl.h>
6 #include <linux/err.h>
7 #include <stdbool.h>
8 #include <stdio.h>
9 #include <string.h>
10 #include <unistd.h>
11 #include <bpf/bpf.h>
12 #include <bpf/btf.h>
13 #include <bpf/libbpf.h>
14 #include <linux/btf.h>
15 #include <linux/hashtable.h>
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 
19 #include "json_writer.h"
20 #include "main.h"
21 
22 static const char * const btf_kind_str[NR_BTF_KINDS] = {
23 	[BTF_KIND_UNKN]		= "UNKNOWN",
24 	[BTF_KIND_INT]		= "INT",
25 	[BTF_KIND_PTR]		= "PTR",
26 	[BTF_KIND_ARRAY]	= "ARRAY",
27 	[BTF_KIND_STRUCT]	= "STRUCT",
28 	[BTF_KIND_UNION]	= "UNION",
29 	[BTF_KIND_ENUM]		= "ENUM",
30 	[BTF_KIND_FWD]		= "FWD",
31 	[BTF_KIND_TYPEDEF]	= "TYPEDEF",
32 	[BTF_KIND_VOLATILE]	= "VOLATILE",
33 	[BTF_KIND_CONST]	= "CONST",
34 	[BTF_KIND_RESTRICT]	= "RESTRICT",
35 	[BTF_KIND_FUNC]		= "FUNC",
36 	[BTF_KIND_FUNC_PROTO]	= "FUNC_PROTO",
37 	[BTF_KIND_VAR]		= "VAR",
38 	[BTF_KIND_DATASEC]	= "DATASEC",
39 };
40 
41 struct btf_attach_table {
42 	DECLARE_HASHTABLE(table, 16);
43 };
44 
45 struct btf_attach_point {
46 	__u32 obj_id;
47 	__u32 btf_id;
48 	struct hlist_node hash;
49 };
50 
51 static const char *btf_int_enc_str(__u8 encoding)
52 {
53 	switch (encoding) {
54 	case 0:
55 		return "(none)";
56 	case BTF_INT_SIGNED:
57 		return "SIGNED";
58 	case BTF_INT_CHAR:
59 		return "CHAR";
60 	case BTF_INT_BOOL:
61 		return "BOOL";
62 	default:
63 		return "UNKN";
64 	}
65 }
66 
67 static const char *btf_var_linkage_str(__u32 linkage)
68 {
69 	switch (linkage) {
70 	case BTF_VAR_STATIC:
71 		return "static";
72 	case BTF_VAR_GLOBAL_ALLOCATED:
73 		return "global-alloc";
74 	default:
75 		return "(unknown)";
76 	}
77 }
78 
79 static const char *btf_func_linkage_str(const struct btf_type *t)
80 {
81 	switch (btf_vlen(t)) {
82 	case BTF_FUNC_STATIC:
83 		return "static";
84 	case BTF_FUNC_GLOBAL:
85 		return "global";
86 	case BTF_FUNC_EXTERN:
87 		return "extern";
88 	default:
89 		return "(unknown)";
90 	}
91 }
92 
93 static const char *btf_str(const struct btf *btf, __u32 off)
94 {
95 	if (!off)
96 		return "(anon)";
97 	return btf__name_by_offset(btf, off) ? : "(invalid)";
98 }
99 
100 static int dump_btf_type(const struct btf *btf, __u32 id,
101 			 const struct btf_type *t)
102 {
103 	json_writer_t *w = json_wtr;
104 	int kind, safe_kind;
105 
106 	kind = BTF_INFO_KIND(t->info);
107 	safe_kind = kind <= BTF_KIND_MAX ? kind : BTF_KIND_UNKN;
108 
109 	if (json_output) {
110 		jsonw_start_object(w);
111 		jsonw_uint_field(w, "id", id);
112 		jsonw_string_field(w, "kind", btf_kind_str[safe_kind]);
113 		jsonw_string_field(w, "name", btf_str(btf, t->name_off));
114 	} else {
115 		printf("[%u] %s '%s'", id, btf_kind_str[safe_kind],
116 		       btf_str(btf, t->name_off));
117 	}
118 
119 	switch (BTF_INFO_KIND(t->info)) {
120 	case BTF_KIND_INT: {
121 		__u32 v = *(__u32 *)(t + 1);
122 		const char *enc;
123 
124 		enc = btf_int_enc_str(BTF_INT_ENCODING(v));
125 
126 		if (json_output) {
127 			jsonw_uint_field(w, "size", t->size);
128 			jsonw_uint_field(w, "bits_offset", BTF_INT_OFFSET(v));
129 			jsonw_uint_field(w, "nr_bits", BTF_INT_BITS(v));
130 			jsonw_string_field(w, "encoding", enc);
131 		} else {
132 			printf(" size=%u bits_offset=%u nr_bits=%u encoding=%s",
133 			       t->size, BTF_INT_OFFSET(v), BTF_INT_BITS(v),
134 			       enc);
135 		}
136 		break;
137 	}
138 	case BTF_KIND_PTR:
139 	case BTF_KIND_CONST:
140 	case BTF_KIND_VOLATILE:
141 	case BTF_KIND_RESTRICT:
142 	case BTF_KIND_TYPEDEF:
143 		if (json_output)
144 			jsonw_uint_field(w, "type_id", t->type);
145 		else
146 			printf(" type_id=%u", t->type);
147 		break;
148 	case BTF_KIND_ARRAY: {
149 		const struct btf_array *arr = (const void *)(t + 1);
150 
151 		if (json_output) {
152 			jsonw_uint_field(w, "type_id", arr->type);
153 			jsonw_uint_field(w, "index_type_id", arr->index_type);
154 			jsonw_uint_field(w, "nr_elems", arr->nelems);
155 		} else {
156 			printf(" type_id=%u index_type_id=%u nr_elems=%u",
157 			       arr->type, arr->index_type, arr->nelems);
158 		}
159 		break;
160 	}
161 	case BTF_KIND_STRUCT:
162 	case BTF_KIND_UNION: {
163 		const struct btf_member *m = (const void *)(t + 1);
164 		__u16 vlen = BTF_INFO_VLEN(t->info);
165 		int i;
166 
167 		if (json_output) {
168 			jsonw_uint_field(w, "size", t->size);
169 			jsonw_uint_field(w, "vlen", vlen);
170 			jsonw_name(w, "members");
171 			jsonw_start_array(w);
172 		} else {
173 			printf(" size=%u vlen=%u", t->size, vlen);
174 		}
175 		for (i = 0; i < vlen; i++, m++) {
176 			const char *name = btf_str(btf, m->name_off);
177 			__u32 bit_off, bit_sz;
178 
179 			if (BTF_INFO_KFLAG(t->info)) {
180 				bit_off = BTF_MEMBER_BIT_OFFSET(m->offset);
181 				bit_sz = BTF_MEMBER_BITFIELD_SIZE(m->offset);
182 			} else {
183 				bit_off = m->offset;
184 				bit_sz = 0;
185 			}
186 
187 			if (json_output) {
188 				jsonw_start_object(w);
189 				jsonw_string_field(w, "name", name);
190 				jsonw_uint_field(w, "type_id", m->type);
191 				jsonw_uint_field(w, "bits_offset", bit_off);
192 				if (bit_sz) {
193 					jsonw_uint_field(w, "bitfield_size",
194 							 bit_sz);
195 				}
196 				jsonw_end_object(w);
197 			} else {
198 				printf("\n\t'%s' type_id=%u bits_offset=%u",
199 				       name, m->type, bit_off);
200 				if (bit_sz)
201 					printf(" bitfield_size=%u", bit_sz);
202 			}
203 		}
204 		if (json_output)
205 			jsonw_end_array(w);
206 		break;
207 	}
208 	case BTF_KIND_ENUM: {
209 		const struct btf_enum *v = (const void *)(t + 1);
210 		__u16 vlen = BTF_INFO_VLEN(t->info);
211 		int i;
212 
213 		if (json_output) {
214 			jsonw_uint_field(w, "size", t->size);
215 			jsonw_uint_field(w, "vlen", vlen);
216 			jsonw_name(w, "values");
217 			jsonw_start_array(w);
218 		} else {
219 			printf(" size=%u vlen=%u", t->size, vlen);
220 		}
221 		for (i = 0; i < vlen; i++, v++) {
222 			const char *name = btf_str(btf, v->name_off);
223 
224 			if (json_output) {
225 				jsonw_start_object(w);
226 				jsonw_string_field(w, "name", name);
227 				jsonw_uint_field(w, "val", v->val);
228 				jsonw_end_object(w);
229 			} else {
230 				printf("\n\t'%s' val=%u", name, v->val);
231 			}
232 		}
233 		if (json_output)
234 			jsonw_end_array(w);
235 		break;
236 	}
237 	case BTF_KIND_FWD: {
238 		const char *fwd_kind = BTF_INFO_KFLAG(t->info) ? "union"
239 							       : "struct";
240 
241 		if (json_output)
242 			jsonw_string_field(w, "fwd_kind", fwd_kind);
243 		else
244 			printf(" fwd_kind=%s", fwd_kind);
245 		break;
246 	}
247 	case BTF_KIND_FUNC: {
248 		const char *linkage = btf_func_linkage_str(t);
249 
250 		if (json_output) {
251 			jsonw_uint_field(w, "type_id", t->type);
252 			jsonw_string_field(w, "linkage", linkage);
253 		} else {
254 			printf(" type_id=%u linkage=%s", t->type, linkage);
255 		}
256 		break;
257 	}
258 	case BTF_KIND_FUNC_PROTO: {
259 		const struct btf_param *p = (const void *)(t + 1);
260 		__u16 vlen = BTF_INFO_VLEN(t->info);
261 		int i;
262 
263 		if (json_output) {
264 			jsonw_uint_field(w, "ret_type_id", t->type);
265 			jsonw_uint_field(w, "vlen", vlen);
266 			jsonw_name(w, "params");
267 			jsonw_start_array(w);
268 		} else {
269 			printf(" ret_type_id=%u vlen=%u", t->type, vlen);
270 		}
271 		for (i = 0; i < vlen; i++, p++) {
272 			const char *name = btf_str(btf, p->name_off);
273 
274 			if (json_output) {
275 				jsonw_start_object(w);
276 				jsonw_string_field(w, "name", name);
277 				jsonw_uint_field(w, "type_id", p->type);
278 				jsonw_end_object(w);
279 			} else {
280 				printf("\n\t'%s' type_id=%u", name, p->type);
281 			}
282 		}
283 		if (json_output)
284 			jsonw_end_array(w);
285 		break;
286 	}
287 	case BTF_KIND_VAR: {
288 		const struct btf_var *v = (const void *)(t + 1);
289 		const char *linkage;
290 
291 		linkage = btf_var_linkage_str(v->linkage);
292 
293 		if (json_output) {
294 			jsonw_uint_field(w, "type_id", t->type);
295 			jsonw_string_field(w, "linkage", linkage);
296 		} else {
297 			printf(" type_id=%u, linkage=%s", t->type, linkage);
298 		}
299 		break;
300 	}
301 	case BTF_KIND_DATASEC: {
302 		const struct btf_var_secinfo *v = (const void *)(t+1);
303 		__u16 vlen = BTF_INFO_VLEN(t->info);
304 		int i;
305 
306 		if (json_output) {
307 			jsonw_uint_field(w, "size", t->size);
308 			jsonw_uint_field(w, "vlen", vlen);
309 			jsonw_name(w, "vars");
310 			jsonw_start_array(w);
311 		} else {
312 			printf(" size=%u vlen=%u", t->size, vlen);
313 		}
314 		for (i = 0; i < vlen; i++, v++) {
315 			if (json_output) {
316 				jsonw_start_object(w);
317 				jsonw_uint_field(w, "type_id", v->type);
318 				jsonw_uint_field(w, "offset", v->offset);
319 				jsonw_uint_field(w, "size", v->size);
320 				jsonw_end_object(w);
321 			} else {
322 				printf("\n\ttype_id=%u offset=%u size=%u",
323 				       v->type, v->offset, v->size);
324 			}
325 		}
326 		if (json_output)
327 			jsonw_end_array(w);
328 		break;
329 	}
330 	default:
331 		break;
332 	}
333 
334 	if (json_output)
335 		jsonw_end_object(json_wtr);
336 	else
337 		printf("\n");
338 
339 	return 0;
340 }
341 
342 static int dump_btf_raw(const struct btf *btf,
343 			__u32 *root_type_ids, int root_type_cnt)
344 {
345 	const struct btf_type *t;
346 	int i;
347 
348 	if (json_output) {
349 		jsonw_start_object(json_wtr);
350 		jsonw_name(json_wtr, "types");
351 		jsonw_start_array(json_wtr);
352 	}
353 
354 	if (root_type_cnt) {
355 		for (i = 0; i < root_type_cnt; i++) {
356 			t = btf__type_by_id(btf, root_type_ids[i]);
357 			dump_btf_type(btf, root_type_ids[i], t);
358 		}
359 	} else {
360 		int cnt = btf__get_nr_types(btf);
361 		int start_id = 1;
362 
363 		if (base_btf)
364 			start_id = btf__get_nr_types(base_btf) + 1;
365 
366 		for (i = start_id; i <= cnt; i++) {
367 			t = btf__type_by_id(btf, i);
368 			dump_btf_type(btf, i, t);
369 		}
370 	}
371 
372 	if (json_output) {
373 		jsonw_end_array(json_wtr);
374 		jsonw_end_object(json_wtr);
375 	}
376 	return 0;
377 }
378 
379 static void __printf(2, 0) btf_dump_printf(void *ctx,
380 					   const char *fmt, va_list args)
381 {
382 	vfprintf(stdout, fmt, args);
383 }
384 
385 static int dump_btf_c(const struct btf *btf,
386 		      __u32 *root_type_ids, int root_type_cnt)
387 {
388 	struct btf_dump *d;
389 	int err = 0, i;
390 
391 	d = btf_dump__new(btf, NULL, NULL, btf_dump_printf);
392 	if (IS_ERR(d))
393 		return PTR_ERR(d);
394 
395 	printf("#ifndef __VMLINUX_H__\n");
396 	printf("#define __VMLINUX_H__\n");
397 	printf("\n");
398 	printf("#ifndef BPF_NO_PRESERVE_ACCESS_INDEX\n");
399 	printf("#pragma clang attribute push (__attribute__((preserve_access_index)), apply_to = record)\n");
400 	printf("#endif\n\n");
401 
402 	if (root_type_cnt) {
403 		for (i = 0; i < root_type_cnt; i++) {
404 			err = btf_dump__dump_type(d, root_type_ids[i]);
405 			if (err)
406 				goto done;
407 		}
408 	} else {
409 		int cnt = btf__get_nr_types(btf);
410 
411 		for (i = 1; i <= cnt; i++) {
412 			err = btf_dump__dump_type(d, i);
413 			if (err)
414 				goto done;
415 		}
416 	}
417 
418 	printf("#ifndef BPF_NO_PRESERVE_ACCESS_INDEX\n");
419 	printf("#pragma clang attribute pop\n");
420 	printf("#endif\n");
421 	printf("\n");
422 	printf("#endif /* __VMLINUX_H__ */\n");
423 
424 done:
425 	btf_dump__free(d);
426 	return err;
427 }
428 
429 static int do_dump(int argc, char **argv)
430 {
431 	struct btf *btf = NULL;
432 	__u32 root_type_ids[2];
433 	int root_type_cnt = 0;
434 	bool dump_c = false;
435 	__u32 btf_id = -1;
436 	const char *src;
437 	int fd = -1;
438 	int err;
439 
440 	if (!REQ_ARGS(2)) {
441 		usage();
442 		return -1;
443 	}
444 	src = GET_ARG();
445 	if (is_prefix(src, "map")) {
446 		struct bpf_map_info info = {};
447 		__u32 len = sizeof(info);
448 
449 		if (!REQ_ARGS(2)) {
450 			usage();
451 			return -1;
452 		}
453 
454 		fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
455 		if (fd < 0)
456 			return -1;
457 
458 		btf_id = info.btf_id;
459 		if (argc && is_prefix(*argv, "key")) {
460 			root_type_ids[root_type_cnt++] = info.btf_key_type_id;
461 			NEXT_ARG();
462 		} else if (argc && is_prefix(*argv, "value")) {
463 			root_type_ids[root_type_cnt++] = info.btf_value_type_id;
464 			NEXT_ARG();
465 		} else if (argc && is_prefix(*argv, "all")) {
466 			NEXT_ARG();
467 		} else if (argc && is_prefix(*argv, "kv")) {
468 			root_type_ids[root_type_cnt++] = info.btf_key_type_id;
469 			root_type_ids[root_type_cnt++] = info.btf_value_type_id;
470 			NEXT_ARG();
471 		} else {
472 			root_type_ids[root_type_cnt++] = info.btf_key_type_id;
473 			root_type_ids[root_type_cnt++] = info.btf_value_type_id;
474 		}
475 	} else if (is_prefix(src, "prog")) {
476 		struct bpf_prog_info info = {};
477 		__u32 len = sizeof(info);
478 
479 		if (!REQ_ARGS(2)) {
480 			usage();
481 			return -1;
482 		}
483 
484 		fd = prog_parse_fd(&argc, &argv);
485 		if (fd < 0)
486 			return -1;
487 
488 		err = bpf_obj_get_info_by_fd(fd, &info, &len);
489 		if (err) {
490 			p_err("can't get prog info: %s", strerror(errno));
491 			goto done;
492 		}
493 
494 		btf_id = info.btf_id;
495 	} else if (is_prefix(src, "id")) {
496 		char *endptr;
497 
498 		btf_id = strtoul(*argv, &endptr, 0);
499 		if (*endptr) {
500 			p_err("can't parse %s as ID", *argv);
501 			return -1;
502 		}
503 		NEXT_ARG();
504 	} else if (is_prefix(src, "file")) {
505 		btf = btf__parse_split(*argv, base_btf);
506 		if (IS_ERR(btf)) {
507 			err = -PTR_ERR(btf);
508 			btf = NULL;
509 			p_err("failed to load BTF from %s: %s",
510 			      *argv, strerror(err));
511 			goto done;
512 		}
513 		NEXT_ARG();
514 	} else {
515 		err = -1;
516 		p_err("unrecognized BTF source specifier: '%s'", src);
517 		goto done;
518 	}
519 
520 	while (argc) {
521 		if (is_prefix(*argv, "format")) {
522 			NEXT_ARG();
523 			if (argc < 1) {
524 				p_err("expecting value for 'format' option\n");
525 				goto done;
526 			}
527 			if (strcmp(*argv, "c") == 0) {
528 				dump_c = true;
529 			} else if (strcmp(*argv, "raw") == 0) {
530 				dump_c = false;
531 			} else {
532 				p_err("unrecognized format specifier: '%s', possible values: raw, c",
533 				      *argv);
534 				goto done;
535 			}
536 			NEXT_ARG();
537 		} else {
538 			p_err("unrecognized option: '%s'", *argv);
539 			goto done;
540 		}
541 	}
542 
543 	if (!btf) {
544 		err = btf__get_from_id(btf_id, &btf);
545 		if (err) {
546 			p_err("get btf by id (%u): %s", btf_id, strerror(err));
547 			goto done;
548 		}
549 		if (!btf) {
550 			err = -ENOENT;
551 			p_err("can't find btf with ID (%u)", btf_id);
552 			goto done;
553 		}
554 	}
555 
556 	if (dump_c) {
557 		if (json_output) {
558 			p_err("JSON output for C-syntax dump is not supported");
559 			err = -ENOTSUP;
560 			goto done;
561 		}
562 		err = dump_btf_c(btf, root_type_ids, root_type_cnt);
563 	} else {
564 		err = dump_btf_raw(btf, root_type_ids, root_type_cnt);
565 	}
566 
567 done:
568 	close(fd);
569 	btf__free(btf);
570 	return err;
571 }
572 
573 static int btf_parse_fd(int *argc, char ***argv)
574 {
575 	unsigned int id;
576 	char *endptr;
577 	int fd;
578 
579 	if (!is_prefix(*argv[0], "id")) {
580 		p_err("expected 'id', got: '%s'?", **argv);
581 		return -1;
582 	}
583 	NEXT_ARGP();
584 
585 	id = strtoul(**argv, &endptr, 0);
586 	if (*endptr) {
587 		p_err("can't parse %s as ID", **argv);
588 		return -1;
589 	}
590 	NEXT_ARGP();
591 
592 	fd = bpf_btf_get_fd_by_id(id);
593 	if (fd < 0)
594 		p_err("can't get BTF object by id (%u): %s",
595 		      id, strerror(errno));
596 
597 	return fd;
598 }
599 
600 static void delete_btf_table(struct btf_attach_table *tab)
601 {
602 	struct btf_attach_point *obj;
603 	struct hlist_node *tmp;
604 
605 	unsigned int bkt;
606 
607 	hash_for_each_safe(tab->table, bkt, tmp, obj, hash) {
608 		hash_del(&obj->hash);
609 		free(obj);
610 	}
611 }
612 
613 static int
614 build_btf_type_table(struct btf_attach_table *tab, enum bpf_obj_type type,
615 		     void *info, __u32 *len)
616 {
617 	static const char * const names[] = {
618 		[BPF_OBJ_UNKNOWN]	= "unknown",
619 		[BPF_OBJ_PROG]		= "prog",
620 		[BPF_OBJ_MAP]		= "map",
621 	};
622 	struct btf_attach_point *obj_node;
623 	__u32 btf_id, id = 0;
624 	int err;
625 	int fd;
626 
627 	while (true) {
628 		switch (type) {
629 		case BPF_OBJ_PROG:
630 			err = bpf_prog_get_next_id(id, &id);
631 			break;
632 		case BPF_OBJ_MAP:
633 			err = bpf_map_get_next_id(id, &id);
634 			break;
635 		default:
636 			err = -1;
637 			p_err("unexpected object type: %d", type);
638 			goto err_free;
639 		}
640 		if (err) {
641 			if (errno == ENOENT) {
642 				err = 0;
643 				break;
644 			}
645 			p_err("can't get next %s: %s%s", names[type],
646 			      strerror(errno),
647 			      errno == EINVAL ? " -- kernel too old?" : "");
648 			goto err_free;
649 		}
650 
651 		switch (type) {
652 		case BPF_OBJ_PROG:
653 			fd = bpf_prog_get_fd_by_id(id);
654 			break;
655 		case BPF_OBJ_MAP:
656 			fd = bpf_map_get_fd_by_id(id);
657 			break;
658 		default:
659 			err = -1;
660 			p_err("unexpected object type: %d", type);
661 			goto err_free;
662 		}
663 		if (fd < 0) {
664 			if (errno == ENOENT)
665 				continue;
666 			p_err("can't get %s by id (%u): %s", names[type], id,
667 			      strerror(errno));
668 			err = -1;
669 			goto err_free;
670 		}
671 
672 		memset(info, 0, *len);
673 		err = bpf_obj_get_info_by_fd(fd, info, len);
674 		close(fd);
675 		if (err) {
676 			p_err("can't get %s info: %s", names[type],
677 			      strerror(errno));
678 			goto err_free;
679 		}
680 
681 		switch (type) {
682 		case BPF_OBJ_PROG:
683 			btf_id = ((struct bpf_prog_info *)info)->btf_id;
684 			break;
685 		case BPF_OBJ_MAP:
686 			btf_id = ((struct bpf_map_info *)info)->btf_id;
687 			break;
688 		default:
689 			err = -1;
690 			p_err("unexpected object type: %d", type);
691 			goto err_free;
692 		}
693 		if (!btf_id)
694 			continue;
695 
696 		obj_node = calloc(1, sizeof(*obj_node));
697 		if (!obj_node) {
698 			p_err("failed to allocate memory: %s", strerror(errno));
699 			goto err_free;
700 		}
701 
702 		obj_node->obj_id = id;
703 		obj_node->btf_id = btf_id;
704 		hash_add(tab->table, &obj_node->hash, obj_node->btf_id);
705 	}
706 
707 	return 0;
708 
709 err_free:
710 	delete_btf_table(tab);
711 	return err;
712 }
713 
714 static int
715 build_btf_tables(struct btf_attach_table *btf_prog_table,
716 		 struct btf_attach_table *btf_map_table)
717 {
718 	struct bpf_prog_info prog_info;
719 	__u32 prog_len = sizeof(prog_info);
720 	struct bpf_map_info map_info;
721 	__u32 map_len = sizeof(map_info);
722 	int err = 0;
723 
724 	err = build_btf_type_table(btf_prog_table, BPF_OBJ_PROG, &prog_info,
725 				   &prog_len);
726 	if (err)
727 		return err;
728 
729 	err = build_btf_type_table(btf_map_table, BPF_OBJ_MAP, &map_info,
730 				   &map_len);
731 	if (err) {
732 		delete_btf_table(btf_prog_table);
733 		return err;
734 	}
735 
736 	return 0;
737 }
738 
739 static void
740 show_btf_plain(struct bpf_btf_info *info, int fd,
741 	       struct btf_attach_table *btf_prog_table,
742 	       struct btf_attach_table *btf_map_table)
743 {
744 	struct btf_attach_point *obj;
745 	const char *name = u64_to_ptr(info->name);
746 	int n;
747 
748 	printf("%u: ", info->id);
749 	if (info->kernel_btf)
750 		printf("name [%s]  ", name);
751 	else if (name && name[0])
752 		printf("name %s  ", name);
753 	printf("size %uB", info->btf_size);
754 
755 	n = 0;
756 	hash_for_each_possible(btf_prog_table->table, obj, hash, info->id) {
757 		if (obj->btf_id == info->id)
758 			printf("%s%u", n++ == 0 ? "  prog_ids " : ",",
759 			       obj->obj_id);
760 	}
761 
762 	n = 0;
763 	hash_for_each_possible(btf_map_table->table, obj, hash, info->id) {
764 		if (obj->btf_id == info->id)
765 			printf("%s%u", n++ == 0 ? "  map_ids " : ",",
766 			       obj->obj_id);
767 	}
768 	emit_obj_refs_plain(&refs_table, info->id, "\n\tpids ");
769 
770 	printf("\n");
771 }
772 
773 static void
774 show_btf_json(struct bpf_btf_info *info, int fd,
775 	      struct btf_attach_table *btf_prog_table,
776 	      struct btf_attach_table *btf_map_table)
777 {
778 	struct btf_attach_point *obj;
779 	const char *name = u64_to_ptr(info->name);
780 
781 	jsonw_start_object(json_wtr);	/* btf object */
782 	jsonw_uint_field(json_wtr, "id", info->id);
783 	jsonw_uint_field(json_wtr, "size", info->btf_size);
784 
785 	jsonw_name(json_wtr, "prog_ids");
786 	jsonw_start_array(json_wtr);	/* prog_ids */
787 	hash_for_each_possible(btf_prog_table->table, obj, hash,
788 			       info->id) {
789 		if (obj->btf_id == info->id)
790 			jsonw_uint(json_wtr, obj->obj_id);
791 	}
792 	jsonw_end_array(json_wtr);	/* prog_ids */
793 
794 	jsonw_name(json_wtr, "map_ids");
795 	jsonw_start_array(json_wtr);	/* map_ids */
796 	hash_for_each_possible(btf_map_table->table, obj, hash,
797 			       info->id) {
798 		if (obj->btf_id == info->id)
799 			jsonw_uint(json_wtr, obj->obj_id);
800 	}
801 	jsonw_end_array(json_wtr);	/* map_ids */
802 
803 	emit_obj_refs_json(&refs_table, info->id, json_wtr); /* pids */
804 
805 	jsonw_bool_field(json_wtr, "kernel", info->kernel_btf);
806 
807 	if (name && name[0])
808 		jsonw_string_field(json_wtr, "name", name);
809 
810 	jsonw_end_object(json_wtr);	/* btf object */
811 }
812 
813 static int
814 show_btf(int fd, struct btf_attach_table *btf_prog_table,
815 	 struct btf_attach_table *btf_map_table)
816 {
817 	struct bpf_btf_info info;
818 	__u32 len = sizeof(info);
819 	char name[64];
820 	int err;
821 
822 	memset(&info, 0, sizeof(info));
823 	err = bpf_obj_get_info_by_fd(fd, &info, &len);
824 	if (err) {
825 		p_err("can't get BTF object info: %s", strerror(errno));
826 		return -1;
827 	}
828 	/* if kernel support emitting BTF object name, pass name pointer */
829 	if (info.name_len) {
830 		memset(&info, 0, sizeof(info));
831 		info.name_len = sizeof(name);
832 		info.name = ptr_to_u64(name);
833 		len = sizeof(info);
834 
835 		err = bpf_obj_get_info_by_fd(fd, &info, &len);
836 		if (err) {
837 			p_err("can't get BTF object info: %s", strerror(errno));
838 			return -1;
839 		}
840 	}
841 
842 	if (json_output)
843 		show_btf_json(&info, fd, btf_prog_table, btf_map_table);
844 	else
845 		show_btf_plain(&info, fd, btf_prog_table, btf_map_table);
846 
847 	return 0;
848 }
849 
850 static int do_show(int argc, char **argv)
851 {
852 	struct btf_attach_table btf_prog_table;
853 	struct btf_attach_table btf_map_table;
854 	int err, fd = -1;
855 	__u32 id = 0;
856 
857 	if (argc == 2) {
858 		fd = btf_parse_fd(&argc, &argv);
859 		if (fd < 0)
860 			return -1;
861 	}
862 
863 	if (argc) {
864 		if (fd >= 0)
865 			close(fd);
866 		return BAD_ARG();
867 	}
868 
869 	hash_init(btf_prog_table.table);
870 	hash_init(btf_map_table.table);
871 	err = build_btf_tables(&btf_prog_table, &btf_map_table);
872 	if (err) {
873 		if (fd >= 0)
874 			close(fd);
875 		return err;
876 	}
877 	build_obj_refs_table(&refs_table, BPF_OBJ_BTF);
878 
879 	if (fd >= 0) {
880 		err = show_btf(fd, &btf_prog_table, &btf_map_table);
881 		close(fd);
882 		goto exit_free;
883 	}
884 
885 	if (json_output)
886 		jsonw_start_array(json_wtr);	/* root array */
887 
888 	while (true) {
889 		err = bpf_btf_get_next_id(id, &id);
890 		if (err) {
891 			if (errno == ENOENT) {
892 				err = 0;
893 				break;
894 			}
895 			p_err("can't get next BTF object: %s%s",
896 			      strerror(errno),
897 			      errno == EINVAL ? " -- kernel too old?" : "");
898 			err = -1;
899 			break;
900 		}
901 
902 		fd = bpf_btf_get_fd_by_id(id);
903 		if (fd < 0) {
904 			if (errno == ENOENT)
905 				continue;
906 			p_err("can't get BTF object by id (%u): %s",
907 			      id, strerror(errno));
908 			err = -1;
909 			break;
910 		}
911 
912 		err = show_btf(fd, &btf_prog_table, &btf_map_table);
913 		close(fd);
914 		if (err)
915 			break;
916 	}
917 
918 	if (json_output)
919 		jsonw_end_array(json_wtr);	/* root array */
920 
921 exit_free:
922 	delete_btf_table(&btf_prog_table);
923 	delete_btf_table(&btf_map_table);
924 	delete_obj_refs_table(&refs_table);
925 
926 	return err;
927 }
928 
929 static int do_help(int argc, char **argv)
930 {
931 	if (json_output) {
932 		jsonw_null(json_wtr);
933 		return 0;
934 	}
935 
936 	fprintf(stderr,
937 		"Usage: %1$s %2$s { show | list } [id BTF_ID]\n"
938 		"       %1$s %2$s dump BTF_SRC [format FORMAT]\n"
939 		"       %1$s %2$s help\n"
940 		"\n"
941 		"       BTF_SRC := { id BTF_ID | prog PROG | map MAP [{key | value | kv | all}] | file FILE }\n"
942 		"       FORMAT  := { raw | c }\n"
943 		"       " HELP_SPEC_MAP "\n"
944 		"       " HELP_SPEC_PROGRAM "\n"
945 		"       " HELP_SPEC_OPTIONS "\n"
946 		"",
947 		bin_name, "btf");
948 
949 	return 0;
950 }
951 
952 static const struct cmd cmds[] = {
953 	{ "show",	do_show },
954 	{ "list",	do_show },
955 	{ "help",	do_help },
956 	{ "dump",	do_dump },
957 	{ 0 }
958 };
959 
960 int do_btf(int argc, char **argv)
961 {
962 	return cmd_select(cmds, argc, argv, do_help);
963 }
964