xref: /openbmc/linux/tools/bpf/bpftool/prog.c (revision 8a1e6bb3)
1 // SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
2 /* Copyright (C) 2017-2018 Netronome Systems, Inc. */
3 
4 #define _GNU_SOURCE
5 #include <errno.h>
6 #include <fcntl.h>
7 #include <signal.h>
8 #include <stdarg.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <time.h>
13 #include <unistd.h>
14 #include <net/if.h>
15 #include <sys/ioctl.h>
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #include <sys/syscall.h>
19 #include <dirent.h>
20 
21 #include <linux/err.h>
22 #include <linux/perf_event.h>
23 #include <linux/sizes.h>
24 
25 #include <bpf/bpf.h>
26 #include <bpf/btf.h>
27 #include <bpf/hashmap.h>
28 #include <bpf/libbpf.h>
29 #include <bpf/libbpf_internal.h>
30 #include <bpf/skel_internal.h>
31 
32 #include "cfg.h"
33 #include "main.h"
34 #include "xlated_dumper.h"
35 
36 #define BPF_METADATA_PREFIX "bpf_metadata_"
37 #define BPF_METADATA_PREFIX_LEN (sizeof(BPF_METADATA_PREFIX) - 1)
38 
39 const char * const prog_type_name[] = {
40 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
41 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
42 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
43 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
44 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
45 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
46 	[BPF_PROG_TYPE_XDP]			= "xdp",
47 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
48 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
49 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
50 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
51 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
52 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
53 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
54 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
55 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
56 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
57 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
58 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
59 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
60 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
61 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
62 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
63 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
64 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
65 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
66 	[BPF_PROG_TYPE_TRACING]			= "tracing",
67 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
68 	[BPF_PROG_TYPE_EXT]			= "ext",
69 	[BPF_PROG_TYPE_LSM]			= "lsm",
70 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
71 };
72 
73 const size_t prog_type_name_size = ARRAY_SIZE(prog_type_name);
74 
75 enum dump_mode {
76 	DUMP_JITED,
77 	DUMP_XLATED,
78 };
79 
80 static const char * const attach_type_strings[] = {
81 	[BPF_SK_SKB_STREAM_PARSER] = "stream_parser",
82 	[BPF_SK_SKB_STREAM_VERDICT] = "stream_verdict",
83 	[BPF_SK_SKB_VERDICT] = "skb_verdict",
84 	[BPF_SK_MSG_VERDICT] = "msg_verdict",
85 	[BPF_FLOW_DISSECTOR] = "flow_dissector",
86 	[__MAX_BPF_ATTACH_TYPE] = NULL,
87 };
88 
89 static struct hashmap *prog_table;
90 
91 static enum bpf_attach_type parse_attach_type(const char *str)
92 {
93 	enum bpf_attach_type type;
94 
95 	for (type = 0; type < __MAX_BPF_ATTACH_TYPE; type++) {
96 		if (attach_type_strings[type] &&
97 		    is_prefix(str, attach_type_strings[type]))
98 			return type;
99 	}
100 
101 	return __MAX_BPF_ATTACH_TYPE;
102 }
103 
104 static int prep_prog_info(struct bpf_prog_info *const info, enum dump_mode mode,
105 			  void **info_data, size_t *const info_data_sz)
106 {
107 	struct bpf_prog_info holder = {};
108 	size_t needed = 0;
109 	void *ptr;
110 
111 	if (mode == DUMP_JITED) {
112 		holder.jited_prog_len = info->jited_prog_len;
113 		needed += info->jited_prog_len;
114 	} else {
115 		holder.xlated_prog_len = info->xlated_prog_len;
116 		needed += info->xlated_prog_len;
117 	}
118 
119 	holder.nr_jited_ksyms = info->nr_jited_ksyms;
120 	needed += info->nr_jited_ksyms * sizeof(__u64);
121 
122 	holder.nr_jited_func_lens = info->nr_jited_func_lens;
123 	needed += info->nr_jited_func_lens * sizeof(__u32);
124 
125 	holder.nr_func_info = info->nr_func_info;
126 	holder.func_info_rec_size = info->func_info_rec_size;
127 	needed += info->nr_func_info * info->func_info_rec_size;
128 
129 	holder.nr_line_info = info->nr_line_info;
130 	holder.line_info_rec_size = info->line_info_rec_size;
131 	needed += info->nr_line_info * info->line_info_rec_size;
132 
133 	holder.nr_jited_line_info = info->nr_jited_line_info;
134 	holder.jited_line_info_rec_size = info->jited_line_info_rec_size;
135 	needed += info->nr_jited_line_info * info->jited_line_info_rec_size;
136 
137 	if (needed > *info_data_sz) {
138 		ptr = realloc(*info_data, needed);
139 		if (!ptr)
140 			return -1;
141 
142 		*info_data = ptr;
143 		*info_data_sz = needed;
144 	}
145 	ptr = *info_data;
146 
147 	if (mode == DUMP_JITED) {
148 		holder.jited_prog_insns = ptr_to_u64(ptr);
149 		ptr += holder.jited_prog_len;
150 	} else {
151 		holder.xlated_prog_insns = ptr_to_u64(ptr);
152 		ptr += holder.xlated_prog_len;
153 	}
154 
155 	holder.jited_ksyms = ptr_to_u64(ptr);
156 	ptr += holder.nr_jited_ksyms * sizeof(__u64);
157 
158 	holder.jited_func_lens = ptr_to_u64(ptr);
159 	ptr += holder.nr_jited_func_lens * sizeof(__u32);
160 
161 	holder.func_info = ptr_to_u64(ptr);
162 	ptr += holder.nr_func_info * holder.func_info_rec_size;
163 
164 	holder.line_info = ptr_to_u64(ptr);
165 	ptr += holder.nr_line_info * holder.line_info_rec_size;
166 
167 	holder.jited_line_info = ptr_to_u64(ptr);
168 	ptr += holder.nr_jited_line_info * holder.jited_line_info_rec_size;
169 
170 	*info = holder;
171 	return 0;
172 }
173 
174 static void print_boot_time(__u64 nsecs, char *buf, unsigned int size)
175 {
176 	struct timespec real_time_ts, boot_time_ts;
177 	time_t wallclock_secs;
178 	struct tm load_tm;
179 
180 	buf[--size] = '\0';
181 
182 	if (clock_gettime(CLOCK_REALTIME, &real_time_ts) ||
183 	    clock_gettime(CLOCK_BOOTTIME, &boot_time_ts)) {
184 		perror("Can't read clocks");
185 		snprintf(buf, size, "%llu", nsecs / 1000000000);
186 		return;
187 	}
188 
189 	wallclock_secs = (real_time_ts.tv_sec - boot_time_ts.tv_sec) +
190 		(real_time_ts.tv_nsec - boot_time_ts.tv_nsec + nsecs) /
191 		1000000000;
192 
193 
194 	if (!localtime_r(&wallclock_secs, &load_tm)) {
195 		snprintf(buf, size, "%llu", nsecs / 1000000000);
196 		return;
197 	}
198 
199 	if (json_output)
200 		strftime(buf, size, "%s", &load_tm);
201 	else
202 		strftime(buf, size, "%FT%T%z", &load_tm);
203 }
204 
205 static void show_prog_maps(int fd, __u32 num_maps)
206 {
207 	struct bpf_prog_info info = {};
208 	__u32 len = sizeof(info);
209 	__u32 map_ids[num_maps];
210 	unsigned int i;
211 	int err;
212 
213 	info.nr_map_ids = num_maps;
214 	info.map_ids = ptr_to_u64(map_ids);
215 
216 	err = bpf_obj_get_info_by_fd(fd, &info, &len);
217 	if (err || !info.nr_map_ids)
218 		return;
219 
220 	if (json_output) {
221 		jsonw_name(json_wtr, "map_ids");
222 		jsonw_start_array(json_wtr);
223 		for (i = 0; i < info.nr_map_ids; i++)
224 			jsonw_uint(json_wtr, map_ids[i]);
225 		jsonw_end_array(json_wtr);
226 	} else {
227 		printf("  map_ids ");
228 		for (i = 0; i < info.nr_map_ids; i++)
229 			printf("%u%s", map_ids[i],
230 			       i == info.nr_map_ids - 1 ? "" : ",");
231 	}
232 }
233 
234 static void *find_metadata(int prog_fd, struct bpf_map_info *map_info)
235 {
236 	struct bpf_prog_info prog_info;
237 	__u32 prog_info_len;
238 	__u32 map_info_len;
239 	void *value = NULL;
240 	__u32 *map_ids;
241 	int nr_maps;
242 	int key = 0;
243 	int map_fd;
244 	int ret;
245 	__u32 i;
246 
247 	memset(&prog_info, 0, sizeof(prog_info));
248 	prog_info_len = sizeof(prog_info);
249 	ret = bpf_obj_get_info_by_fd(prog_fd, &prog_info, &prog_info_len);
250 	if (ret)
251 		return NULL;
252 
253 	if (!prog_info.nr_map_ids)
254 		return NULL;
255 
256 	map_ids = calloc(prog_info.nr_map_ids, sizeof(__u32));
257 	if (!map_ids)
258 		return NULL;
259 
260 	nr_maps = prog_info.nr_map_ids;
261 	memset(&prog_info, 0, sizeof(prog_info));
262 	prog_info.nr_map_ids = nr_maps;
263 	prog_info.map_ids = ptr_to_u64(map_ids);
264 	prog_info_len = sizeof(prog_info);
265 
266 	ret = bpf_obj_get_info_by_fd(prog_fd, &prog_info, &prog_info_len);
267 	if (ret)
268 		goto free_map_ids;
269 
270 	for (i = 0; i < prog_info.nr_map_ids; i++) {
271 		map_fd = bpf_map_get_fd_by_id(map_ids[i]);
272 		if (map_fd < 0)
273 			goto free_map_ids;
274 
275 		memset(map_info, 0, sizeof(*map_info));
276 		map_info_len = sizeof(*map_info);
277 		ret = bpf_obj_get_info_by_fd(map_fd, map_info, &map_info_len);
278 		if (ret < 0) {
279 			close(map_fd);
280 			goto free_map_ids;
281 		}
282 
283 		if (map_info->type != BPF_MAP_TYPE_ARRAY ||
284 		    map_info->key_size != sizeof(int) ||
285 		    map_info->max_entries != 1 ||
286 		    !map_info->btf_value_type_id ||
287 		    !strstr(map_info->name, ".rodata")) {
288 			close(map_fd);
289 			continue;
290 		}
291 
292 		value = malloc(map_info->value_size);
293 		if (!value) {
294 			close(map_fd);
295 			goto free_map_ids;
296 		}
297 
298 		if (bpf_map_lookup_elem(map_fd, &key, value)) {
299 			close(map_fd);
300 			free(value);
301 			value = NULL;
302 			goto free_map_ids;
303 		}
304 
305 		close(map_fd);
306 		break;
307 	}
308 
309 free_map_ids:
310 	free(map_ids);
311 	return value;
312 }
313 
314 static bool has_metadata_prefix(const char *s)
315 {
316 	return strncmp(s, BPF_METADATA_PREFIX, BPF_METADATA_PREFIX_LEN) == 0;
317 }
318 
319 static void show_prog_metadata(int fd, __u32 num_maps)
320 {
321 	const struct btf_type *t_datasec, *t_var;
322 	struct bpf_map_info map_info;
323 	struct btf_var_secinfo *vsi;
324 	bool printed_header = false;
325 	unsigned int i, vlen;
326 	void *value = NULL;
327 	const char *name;
328 	struct btf *btf;
329 	int err;
330 
331 	if (!num_maps)
332 		return;
333 
334 	memset(&map_info, 0, sizeof(map_info));
335 	value = find_metadata(fd, &map_info);
336 	if (!value)
337 		return;
338 
339 	btf = btf__load_from_kernel_by_id(map_info.btf_id);
340 	if (libbpf_get_error(btf))
341 		goto out_free;
342 
343 	t_datasec = btf__type_by_id(btf, map_info.btf_value_type_id);
344 	if (!btf_is_datasec(t_datasec))
345 		goto out_free;
346 
347 	vlen = btf_vlen(t_datasec);
348 	vsi = btf_var_secinfos(t_datasec);
349 
350 	/* We don't proceed to check the kinds of the elements of the DATASEC.
351 	 * The verifier enforces them to be BTF_KIND_VAR.
352 	 */
353 
354 	if (json_output) {
355 		struct btf_dumper d = {
356 			.btf = btf,
357 			.jw = json_wtr,
358 			.is_plain_text = false,
359 		};
360 
361 		for (i = 0; i < vlen; i++, vsi++) {
362 			t_var = btf__type_by_id(btf, vsi->type);
363 			name = btf__name_by_offset(btf, t_var->name_off);
364 
365 			if (!has_metadata_prefix(name))
366 				continue;
367 
368 			if (!printed_header) {
369 				jsonw_name(json_wtr, "metadata");
370 				jsonw_start_object(json_wtr);
371 				printed_header = true;
372 			}
373 
374 			jsonw_name(json_wtr, name + BPF_METADATA_PREFIX_LEN);
375 			err = btf_dumper_type(&d, t_var->type, value + vsi->offset);
376 			if (err) {
377 				p_err("btf dump failed: %d", err);
378 				break;
379 			}
380 		}
381 		if (printed_header)
382 			jsonw_end_object(json_wtr);
383 	} else {
384 		json_writer_t *btf_wtr;
385 		struct btf_dumper d = {
386 			.btf = btf,
387 			.is_plain_text = true,
388 		};
389 
390 		for (i = 0; i < vlen; i++, vsi++) {
391 			t_var = btf__type_by_id(btf, vsi->type);
392 			name = btf__name_by_offset(btf, t_var->name_off);
393 
394 			if (!has_metadata_prefix(name))
395 				continue;
396 
397 			if (!printed_header) {
398 				printf("\tmetadata:");
399 
400 				btf_wtr = jsonw_new(stdout);
401 				if (!btf_wtr) {
402 					p_err("jsonw alloc failed");
403 					goto out_free;
404 				}
405 				d.jw = btf_wtr,
406 
407 				printed_header = true;
408 			}
409 
410 			printf("\n\t\t%s = ", name + BPF_METADATA_PREFIX_LEN);
411 
412 			jsonw_reset(btf_wtr);
413 			err = btf_dumper_type(&d, t_var->type, value + vsi->offset);
414 			if (err) {
415 				p_err("btf dump failed: %d", err);
416 				break;
417 			}
418 		}
419 		if (printed_header)
420 			jsonw_destroy(&btf_wtr);
421 	}
422 
423 out_free:
424 	btf__free(btf);
425 	free(value);
426 }
427 
428 static void print_prog_header_json(struct bpf_prog_info *info, int fd)
429 {
430 	char prog_name[MAX_PROG_FULL_NAME];
431 
432 	jsonw_uint_field(json_wtr, "id", info->id);
433 	if (info->type < ARRAY_SIZE(prog_type_name))
434 		jsonw_string_field(json_wtr, "type",
435 				   prog_type_name[info->type]);
436 	else
437 		jsonw_uint_field(json_wtr, "type", info->type);
438 
439 	if (*info->name) {
440 		get_prog_full_name(info, fd, prog_name, sizeof(prog_name));
441 		jsonw_string_field(json_wtr, "name", prog_name);
442 	}
443 
444 	jsonw_name(json_wtr, "tag");
445 	jsonw_printf(json_wtr, "\"" BPF_TAG_FMT "\"",
446 		     info->tag[0], info->tag[1], info->tag[2], info->tag[3],
447 		     info->tag[4], info->tag[5], info->tag[6], info->tag[7]);
448 
449 	jsonw_bool_field(json_wtr, "gpl_compatible", info->gpl_compatible);
450 	if (info->run_time_ns) {
451 		jsonw_uint_field(json_wtr, "run_time_ns", info->run_time_ns);
452 		jsonw_uint_field(json_wtr, "run_cnt", info->run_cnt);
453 	}
454 	if (info->recursion_misses)
455 		jsonw_uint_field(json_wtr, "recursion_misses", info->recursion_misses);
456 }
457 
458 static void print_prog_json(struct bpf_prog_info *info, int fd)
459 {
460 	char *memlock;
461 
462 	jsonw_start_object(json_wtr);
463 	print_prog_header_json(info, fd);
464 	print_dev_json(info->ifindex, info->netns_dev, info->netns_ino);
465 
466 	if (info->load_time) {
467 		char buf[32];
468 
469 		print_boot_time(info->load_time, buf, sizeof(buf));
470 
471 		/* Piggy back on load_time, since 0 uid is a valid one */
472 		jsonw_name(json_wtr, "loaded_at");
473 		jsonw_printf(json_wtr, "%s", buf);
474 		jsonw_uint_field(json_wtr, "uid", info->created_by_uid);
475 	}
476 
477 	jsonw_uint_field(json_wtr, "bytes_xlated", info->xlated_prog_len);
478 
479 	if (info->jited_prog_len) {
480 		jsonw_bool_field(json_wtr, "jited", true);
481 		jsonw_uint_field(json_wtr, "bytes_jited", info->jited_prog_len);
482 	} else {
483 		jsonw_bool_field(json_wtr, "jited", false);
484 	}
485 
486 	memlock = get_fdinfo(fd, "memlock");
487 	if (memlock)
488 		jsonw_int_field(json_wtr, "bytes_memlock", atoll(memlock));
489 	free(memlock);
490 
491 	if (info->nr_map_ids)
492 		show_prog_maps(fd, info->nr_map_ids);
493 
494 	if (info->btf_id)
495 		jsonw_int_field(json_wtr, "btf_id", info->btf_id);
496 
497 	if (!hashmap__empty(prog_table)) {
498 		struct hashmap_entry *entry;
499 
500 		jsonw_name(json_wtr, "pinned");
501 		jsonw_start_array(json_wtr);
502 		hashmap__for_each_key_entry(prog_table, entry,
503 					    u32_as_hash_field(info->id))
504 			jsonw_string(json_wtr, entry->value);
505 		jsonw_end_array(json_wtr);
506 	}
507 
508 	emit_obj_refs_json(refs_table, info->id, json_wtr);
509 
510 	show_prog_metadata(fd, info->nr_map_ids);
511 
512 	jsonw_end_object(json_wtr);
513 }
514 
515 static void print_prog_header_plain(struct bpf_prog_info *info, int fd)
516 {
517 	char prog_name[MAX_PROG_FULL_NAME];
518 
519 	printf("%u: ", info->id);
520 	if (info->type < ARRAY_SIZE(prog_type_name))
521 		printf("%s  ", prog_type_name[info->type]);
522 	else
523 		printf("type %u  ", info->type);
524 
525 	if (*info->name) {
526 		get_prog_full_name(info, fd, prog_name, sizeof(prog_name));
527 		printf("name %s  ", prog_name);
528 	}
529 
530 	printf("tag ");
531 	fprint_hex(stdout, info->tag, BPF_TAG_SIZE, "");
532 	print_dev_plain(info->ifindex, info->netns_dev, info->netns_ino);
533 	printf("%s", info->gpl_compatible ? "  gpl" : "");
534 	if (info->run_time_ns)
535 		printf(" run_time_ns %lld run_cnt %lld",
536 		       info->run_time_ns, info->run_cnt);
537 	if (info->recursion_misses)
538 		printf(" recursion_misses %lld", info->recursion_misses);
539 	printf("\n");
540 }
541 
542 static void print_prog_plain(struct bpf_prog_info *info, int fd)
543 {
544 	char *memlock;
545 
546 	print_prog_header_plain(info, fd);
547 
548 	if (info->load_time) {
549 		char buf[32];
550 
551 		print_boot_time(info->load_time, buf, sizeof(buf));
552 
553 		/* Piggy back on load_time, since 0 uid is a valid one */
554 		printf("\tloaded_at %s  uid %u\n", buf, info->created_by_uid);
555 	}
556 
557 	printf("\txlated %uB", info->xlated_prog_len);
558 
559 	if (info->jited_prog_len)
560 		printf("  jited %uB", info->jited_prog_len);
561 	else
562 		printf("  not jited");
563 
564 	memlock = get_fdinfo(fd, "memlock");
565 	if (memlock)
566 		printf("  memlock %sB", memlock);
567 	free(memlock);
568 
569 	if (info->nr_map_ids)
570 		show_prog_maps(fd, info->nr_map_ids);
571 
572 	if (!hashmap__empty(prog_table)) {
573 		struct hashmap_entry *entry;
574 
575 		hashmap__for_each_key_entry(prog_table, entry,
576 					    u32_as_hash_field(info->id))
577 			printf("\n\tpinned %s", (char *)entry->value);
578 	}
579 
580 	if (info->btf_id)
581 		printf("\n\tbtf_id %d", info->btf_id);
582 
583 	emit_obj_refs_plain(refs_table, info->id, "\n\tpids ");
584 
585 	printf("\n");
586 
587 	show_prog_metadata(fd, info->nr_map_ids);
588 }
589 
590 static int show_prog(int fd)
591 {
592 	struct bpf_prog_info info = {};
593 	__u32 len = sizeof(info);
594 	int err;
595 
596 	err = bpf_obj_get_info_by_fd(fd, &info, &len);
597 	if (err) {
598 		p_err("can't get prog info: %s", strerror(errno));
599 		return -1;
600 	}
601 
602 	if (json_output)
603 		print_prog_json(&info, fd);
604 	else
605 		print_prog_plain(&info, fd);
606 
607 	return 0;
608 }
609 
610 static int do_show_subset(int argc, char **argv)
611 {
612 	int *fds = NULL;
613 	int nb_fds, i;
614 	int err = -1;
615 
616 	fds = malloc(sizeof(int));
617 	if (!fds) {
618 		p_err("mem alloc failed");
619 		return -1;
620 	}
621 	nb_fds = prog_parse_fds(&argc, &argv, &fds);
622 	if (nb_fds < 1)
623 		goto exit_free;
624 
625 	if (json_output && nb_fds > 1)
626 		jsonw_start_array(json_wtr);	/* root array */
627 	for (i = 0; i < nb_fds; i++) {
628 		err = show_prog(fds[i]);
629 		if (err) {
630 			for (; i < nb_fds; i++)
631 				close(fds[i]);
632 			break;
633 		}
634 		close(fds[i]);
635 	}
636 	if (json_output && nb_fds > 1)
637 		jsonw_end_array(json_wtr);	/* root array */
638 
639 exit_free:
640 	free(fds);
641 	return err;
642 }
643 
644 static int do_show(int argc, char **argv)
645 {
646 	__u32 id = 0;
647 	int err;
648 	int fd;
649 
650 	if (show_pinned) {
651 		prog_table = hashmap__new(hash_fn_for_key_as_id,
652 					  equal_fn_for_key_as_id, NULL);
653 		if (IS_ERR(prog_table)) {
654 			p_err("failed to create hashmap for pinned paths");
655 			return -1;
656 		}
657 		build_pinned_obj_table(prog_table, BPF_OBJ_PROG);
658 	}
659 	build_obj_refs_table(&refs_table, BPF_OBJ_PROG);
660 
661 	if (argc == 2)
662 		return do_show_subset(argc, argv);
663 
664 	if (argc)
665 		return BAD_ARG();
666 
667 	if (json_output)
668 		jsonw_start_array(json_wtr);
669 	while (true) {
670 		err = bpf_prog_get_next_id(id, &id);
671 		if (err) {
672 			if (errno == ENOENT) {
673 				err = 0;
674 				break;
675 			}
676 			p_err("can't get next program: %s%s", strerror(errno),
677 			      errno == EINVAL ? " -- kernel too old?" : "");
678 			err = -1;
679 			break;
680 		}
681 
682 		fd = bpf_prog_get_fd_by_id(id);
683 		if (fd < 0) {
684 			if (errno == ENOENT)
685 				continue;
686 			p_err("can't get prog by id (%u): %s",
687 			      id, strerror(errno));
688 			err = -1;
689 			break;
690 		}
691 
692 		err = show_prog(fd);
693 		close(fd);
694 		if (err)
695 			break;
696 	}
697 
698 	if (json_output)
699 		jsonw_end_array(json_wtr);
700 
701 	delete_obj_refs_table(refs_table);
702 
703 	if (show_pinned)
704 		delete_pinned_obj_table(prog_table);
705 
706 	return err;
707 }
708 
709 static int
710 prog_dump(struct bpf_prog_info *info, enum dump_mode mode,
711 	  char *filepath, bool opcodes, bool visual, bool linum)
712 {
713 	struct bpf_prog_linfo *prog_linfo = NULL;
714 	const char *disasm_opt = NULL;
715 	struct dump_data dd = {};
716 	void *func_info = NULL;
717 	struct btf *btf = NULL;
718 	char func_sig[1024];
719 	unsigned char *buf;
720 	__u32 member_len;
721 	int fd, err = -1;
722 	ssize_t n;
723 
724 	if (mode == DUMP_JITED) {
725 		if (info->jited_prog_len == 0 || !info->jited_prog_insns) {
726 			p_info("no instructions returned");
727 			return -1;
728 		}
729 		buf = u64_to_ptr(info->jited_prog_insns);
730 		member_len = info->jited_prog_len;
731 	} else {	/* DUMP_XLATED */
732 		if (info->xlated_prog_len == 0 || !info->xlated_prog_insns) {
733 			p_err("error retrieving insn dump: kernel.kptr_restrict set?");
734 			return -1;
735 		}
736 		buf = u64_to_ptr(info->xlated_prog_insns);
737 		member_len = info->xlated_prog_len;
738 	}
739 
740 	if (info->btf_id) {
741 		btf = btf__load_from_kernel_by_id(info->btf_id);
742 		if (libbpf_get_error(btf)) {
743 			p_err("failed to get btf");
744 			return -1;
745 		}
746 	}
747 
748 	func_info = u64_to_ptr(info->func_info);
749 
750 	if (info->nr_line_info) {
751 		prog_linfo = bpf_prog_linfo__new(info);
752 		if (!prog_linfo)
753 			p_info("error in processing bpf_line_info.  continue without it.");
754 	}
755 
756 	if (filepath) {
757 		fd = open(filepath, O_WRONLY | O_CREAT | O_TRUNC, 0600);
758 		if (fd < 0) {
759 			p_err("can't open file %s: %s", filepath,
760 			      strerror(errno));
761 			goto exit_free;
762 		}
763 
764 		n = write(fd, buf, member_len);
765 		close(fd);
766 		if (n != (ssize_t)member_len) {
767 			p_err("error writing output file: %s",
768 			      n < 0 ? strerror(errno) : "short write");
769 			goto exit_free;
770 		}
771 
772 		if (json_output)
773 			jsonw_null(json_wtr);
774 	} else if (mode == DUMP_JITED) {
775 		const char *name = NULL;
776 
777 		if (info->ifindex) {
778 			name = ifindex_to_bfd_params(info->ifindex,
779 						     info->netns_dev,
780 						     info->netns_ino,
781 						     &disasm_opt);
782 			if (!name)
783 				goto exit_free;
784 		}
785 
786 		if (info->nr_jited_func_lens && info->jited_func_lens) {
787 			struct kernel_sym *sym = NULL;
788 			struct bpf_func_info *record;
789 			char sym_name[SYM_MAX_NAME];
790 			unsigned char *img = buf;
791 			__u64 *ksyms = NULL;
792 			__u32 *lens;
793 			__u32 i;
794 			if (info->nr_jited_ksyms) {
795 				kernel_syms_load(&dd);
796 				ksyms = u64_to_ptr(info->jited_ksyms);
797 			}
798 
799 			if (json_output)
800 				jsonw_start_array(json_wtr);
801 
802 			lens = u64_to_ptr(info->jited_func_lens);
803 			for (i = 0; i < info->nr_jited_func_lens; i++) {
804 				if (ksyms) {
805 					sym = kernel_syms_search(&dd, ksyms[i]);
806 					if (sym)
807 						sprintf(sym_name, "%s", sym->name);
808 					else
809 						sprintf(sym_name, "0x%016llx", ksyms[i]);
810 				} else {
811 					strcpy(sym_name, "unknown");
812 				}
813 
814 				if (func_info) {
815 					record = func_info + i * info->func_info_rec_size;
816 					btf_dumper_type_only(btf, record->type_id,
817 							     func_sig,
818 							     sizeof(func_sig));
819 				}
820 
821 				if (json_output) {
822 					jsonw_start_object(json_wtr);
823 					if (func_info && func_sig[0] != '\0') {
824 						jsonw_name(json_wtr, "proto");
825 						jsonw_string(json_wtr, func_sig);
826 					}
827 					jsonw_name(json_wtr, "name");
828 					jsonw_string(json_wtr, sym_name);
829 					jsonw_name(json_wtr, "insns");
830 				} else {
831 					if (func_info && func_sig[0] != '\0')
832 						printf("%s:\n", func_sig);
833 					printf("%s:\n", sym_name);
834 				}
835 
836 				disasm_print_insn(img, lens[i], opcodes,
837 						  name, disasm_opt, btf,
838 						  prog_linfo, ksyms[i], i,
839 						  linum);
840 
841 				img += lens[i];
842 
843 				if (json_output)
844 					jsonw_end_object(json_wtr);
845 				else
846 					printf("\n");
847 			}
848 
849 			if (json_output)
850 				jsonw_end_array(json_wtr);
851 		} else {
852 			disasm_print_insn(buf, member_len, opcodes, name,
853 					  disasm_opt, btf, NULL, 0, 0, false);
854 		}
855 	} else if (visual) {
856 		if (json_output)
857 			jsonw_null(json_wtr);
858 		else
859 			dump_xlated_cfg(buf, member_len);
860 	} else {
861 		kernel_syms_load(&dd);
862 		dd.nr_jited_ksyms = info->nr_jited_ksyms;
863 		dd.jited_ksyms = u64_to_ptr(info->jited_ksyms);
864 		dd.btf = btf;
865 		dd.func_info = func_info;
866 		dd.finfo_rec_size = info->func_info_rec_size;
867 		dd.prog_linfo = prog_linfo;
868 
869 		if (json_output)
870 			dump_xlated_json(&dd, buf, member_len, opcodes,
871 					 linum);
872 		else
873 			dump_xlated_plain(&dd, buf, member_len, opcodes,
874 					  linum);
875 		kernel_syms_destroy(&dd);
876 	}
877 
878 	err = 0;
879 
880 exit_free:
881 	btf__free(btf);
882 	bpf_prog_linfo__free(prog_linfo);
883 	return err;
884 }
885 
886 static int do_dump(int argc, char **argv)
887 {
888 	struct bpf_prog_info info;
889 	__u32 info_len = sizeof(info);
890 	size_t info_data_sz = 0;
891 	void *info_data = NULL;
892 	char *filepath = NULL;
893 	bool opcodes = false;
894 	bool visual = false;
895 	enum dump_mode mode;
896 	bool linum = false;
897 	int nb_fds, i = 0;
898 	int *fds = NULL;
899 	int err = -1;
900 
901 	if (is_prefix(*argv, "jited")) {
902 		if (disasm_init())
903 			return -1;
904 		mode = DUMP_JITED;
905 	} else if (is_prefix(*argv, "xlated")) {
906 		mode = DUMP_XLATED;
907 	} else {
908 		p_err("expected 'xlated' or 'jited', got: %s", *argv);
909 		return -1;
910 	}
911 	NEXT_ARG();
912 
913 	if (argc < 2)
914 		usage();
915 
916 	fds = malloc(sizeof(int));
917 	if (!fds) {
918 		p_err("mem alloc failed");
919 		return -1;
920 	}
921 	nb_fds = prog_parse_fds(&argc, &argv, &fds);
922 	if (nb_fds < 1)
923 		goto exit_free;
924 
925 	if (is_prefix(*argv, "file")) {
926 		NEXT_ARG();
927 		if (!argc) {
928 			p_err("expected file path");
929 			goto exit_close;
930 		}
931 		if (nb_fds > 1) {
932 			p_err("several programs matched");
933 			goto exit_close;
934 		}
935 
936 		filepath = *argv;
937 		NEXT_ARG();
938 	} else if (is_prefix(*argv, "opcodes")) {
939 		opcodes = true;
940 		NEXT_ARG();
941 	} else if (is_prefix(*argv, "visual")) {
942 		if (nb_fds > 1) {
943 			p_err("several programs matched");
944 			goto exit_close;
945 		}
946 
947 		visual = true;
948 		NEXT_ARG();
949 	} else if (is_prefix(*argv, "linum")) {
950 		linum = true;
951 		NEXT_ARG();
952 	}
953 
954 	if (argc) {
955 		usage();
956 		goto exit_close;
957 	}
958 
959 	if (json_output && nb_fds > 1)
960 		jsonw_start_array(json_wtr);	/* root array */
961 	for (i = 0; i < nb_fds; i++) {
962 		memset(&info, 0, sizeof(info));
963 
964 		err = bpf_obj_get_info_by_fd(fds[i], &info, &info_len);
965 		if (err) {
966 			p_err("can't get prog info: %s", strerror(errno));
967 			break;
968 		}
969 
970 		err = prep_prog_info(&info, mode, &info_data, &info_data_sz);
971 		if (err) {
972 			p_err("can't grow prog info_data");
973 			break;
974 		}
975 
976 		err = bpf_obj_get_info_by_fd(fds[i], &info, &info_len);
977 		if (err) {
978 			p_err("can't get prog info: %s", strerror(errno));
979 			break;
980 		}
981 
982 		if (json_output && nb_fds > 1) {
983 			jsonw_start_object(json_wtr);	/* prog object */
984 			print_prog_header_json(&info, fds[i]);
985 			jsonw_name(json_wtr, "insns");
986 		} else if (nb_fds > 1) {
987 			print_prog_header_plain(&info, fds[i]);
988 		}
989 
990 		err = prog_dump(&info, mode, filepath, opcodes, visual, linum);
991 
992 		if (json_output && nb_fds > 1)
993 			jsonw_end_object(json_wtr);	/* prog object */
994 		else if (i != nb_fds - 1 && nb_fds > 1)
995 			printf("\n");
996 
997 		if (err)
998 			break;
999 		close(fds[i]);
1000 	}
1001 	if (json_output && nb_fds > 1)
1002 		jsonw_end_array(json_wtr);	/* root array */
1003 
1004 exit_close:
1005 	for (; i < nb_fds; i++)
1006 		close(fds[i]);
1007 exit_free:
1008 	free(info_data);
1009 	free(fds);
1010 	return err;
1011 }
1012 
1013 static int do_pin(int argc, char **argv)
1014 {
1015 	int err;
1016 
1017 	err = do_pin_any(argc, argv, prog_parse_fd);
1018 	if (!err && json_output)
1019 		jsonw_null(json_wtr);
1020 	return err;
1021 }
1022 
1023 struct map_replace {
1024 	int idx;
1025 	int fd;
1026 	char *name;
1027 };
1028 
1029 static int map_replace_compar(const void *p1, const void *p2)
1030 {
1031 	const struct map_replace *a = p1, *b = p2;
1032 
1033 	return a->idx - b->idx;
1034 }
1035 
1036 static int parse_attach_detach_args(int argc, char **argv, int *progfd,
1037 				    enum bpf_attach_type *attach_type,
1038 				    int *mapfd)
1039 {
1040 	if (!REQ_ARGS(3))
1041 		return -EINVAL;
1042 
1043 	*progfd = prog_parse_fd(&argc, &argv);
1044 	if (*progfd < 0)
1045 		return *progfd;
1046 
1047 	*attach_type = parse_attach_type(*argv);
1048 	if (*attach_type == __MAX_BPF_ATTACH_TYPE) {
1049 		p_err("invalid attach/detach type");
1050 		return -EINVAL;
1051 	}
1052 
1053 	if (*attach_type == BPF_FLOW_DISSECTOR) {
1054 		*mapfd = 0;
1055 		return 0;
1056 	}
1057 
1058 	NEXT_ARG();
1059 	if (!REQ_ARGS(2))
1060 		return -EINVAL;
1061 
1062 	*mapfd = map_parse_fd(&argc, &argv);
1063 	if (*mapfd < 0)
1064 		return *mapfd;
1065 
1066 	return 0;
1067 }
1068 
1069 static int do_attach(int argc, char **argv)
1070 {
1071 	enum bpf_attach_type attach_type;
1072 	int err, progfd;
1073 	int mapfd;
1074 
1075 	err = parse_attach_detach_args(argc, argv,
1076 				       &progfd, &attach_type, &mapfd);
1077 	if (err)
1078 		return err;
1079 
1080 	err = bpf_prog_attach(progfd, mapfd, attach_type, 0);
1081 	if (err) {
1082 		p_err("failed prog attach to map");
1083 		return -EINVAL;
1084 	}
1085 
1086 	if (json_output)
1087 		jsonw_null(json_wtr);
1088 	return 0;
1089 }
1090 
1091 static int do_detach(int argc, char **argv)
1092 {
1093 	enum bpf_attach_type attach_type;
1094 	int err, progfd;
1095 	int mapfd;
1096 
1097 	err = parse_attach_detach_args(argc, argv,
1098 				       &progfd, &attach_type, &mapfd);
1099 	if (err)
1100 		return err;
1101 
1102 	err = bpf_prog_detach2(progfd, mapfd, attach_type);
1103 	if (err) {
1104 		p_err("failed prog detach from map");
1105 		return -EINVAL;
1106 	}
1107 
1108 	if (json_output)
1109 		jsonw_null(json_wtr);
1110 	return 0;
1111 }
1112 
1113 static int check_single_stdin(char *file_data_in, char *file_ctx_in)
1114 {
1115 	if (file_data_in && file_ctx_in &&
1116 	    !strcmp(file_data_in, "-") && !strcmp(file_ctx_in, "-")) {
1117 		p_err("cannot use standard input for both data_in and ctx_in");
1118 		return -1;
1119 	}
1120 
1121 	return 0;
1122 }
1123 
1124 static int get_run_data(const char *fname, void **data_ptr, unsigned int *size)
1125 {
1126 	size_t block_size = 256;
1127 	size_t buf_size = block_size;
1128 	size_t nb_read = 0;
1129 	void *tmp;
1130 	FILE *f;
1131 
1132 	if (!fname) {
1133 		*data_ptr = NULL;
1134 		*size = 0;
1135 		return 0;
1136 	}
1137 
1138 	if (!strcmp(fname, "-"))
1139 		f = stdin;
1140 	else
1141 		f = fopen(fname, "r");
1142 	if (!f) {
1143 		p_err("failed to open %s: %s", fname, strerror(errno));
1144 		return -1;
1145 	}
1146 
1147 	*data_ptr = malloc(block_size);
1148 	if (!*data_ptr) {
1149 		p_err("failed to allocate memory for data_in/ctx_in: %s",
1150 		      strerror(errno));
1151 		goto err_fclose;
1152 	}
1153 
1154 	while ((nb_read += fread(*data_ptr + nb_read, 1, block_size, f))) {
1155 		if (feof(f))
1156 			break;
1157 		if (ferror(f)) {
1158 			p_err("failed to read data_in/ctx_in from %s: %s",
1159 			      fname, strerror(errno));
1160 			goto err_free;
1161 		}
1162 		if (nb_read > buf_size - block_size) {
1163 			if (buf_size == UINT32_MAX) {
1164 				p_err("data_in/ctx_in is too long (max: %d)",
1165 				      UINT32_MAX);
1166 				goto err_free;
1167 			}
1168 			/* No space for fread()-ing next chunk; realloc() */
1169 			buf_size *= 2;
1170 			tmp = realloc(*data_ptr, buf_size);
1171 			if (!tmp) {
1172 				p_err("failed to reallocate data_in/ctx_in: %s",
1173 				      strerror(errno));
1174 				goto err_free;
1175 			}
1176 			*data_ptr = tmp;
1177 		}
1178 	}
1179 	if (f != stdin)
1180 		fclose(f);
1181 
1182 	*size = nb_read;
1183 	return 0;
1184 
1185 err_free:
1186 	free(*data_ptr);
1187 	*data_ptr = NULL;
1188 err_fclose:
1189 	if (f != stdin)
1190 		fclose(f);
1191 	return -1;
1192 }
1193 
1194 static void hex_print(void *data, unsigned int size, FILE *f)
1195 {
1196 	size_t i, j;
1197 	char c;
1198 
1199 	for (i = 0; i < size; i += 16) {
1200 		/* Row offset */
1201 		fprintf(f, "%07zx\t", i);
1202 
1203 		/* Hexadecimal values */
1204 		for (j = i; j < i + 16 && j < size; j++)
1205 			fprintf(f, "%02x%s", *(uint8_t *)(data + j),
1206 				j % 2 ? " " : "");
1207 		for (; j < i + 16; j++)
1208 			fprintf(f, "  %s", j % 2 ? " " : "");
1209 
1210 		/* ASCII values (if relevant), '.' otherwise */
1211 		fprintf(f, "| ");
1212 		for (j = i; j < i + 16 && j < size; j++) {
1213 			c = *(char *)(data + j);
1214 			if (c < ' ' || c > '~')
1215 				c = '.';
1216 			fprintf(f, "%c%s", c, j == i + 7 ? " " : "");
1217 		}
1218 
1219 		fprintf(f, "\n");
1220 	}
1221 }
1222 
1223 static int
1224 print_run_output(void *data, unsigned int size, const char *fname,
1225 		 const char *json_key)
1226 {
1227 	size_t nb_written;
1228 	FILE *f;
1229 
1230 	if (!fname)
1231 		return 0;
1232 
1233 	if (!strcmp(fname, "-")) {
1234 		f = stdout;
1235 		if (json_output) {
1236 			jsonw_name(json_wtr, json_key);
1237 			print_data_json(data, size);
1238 		} else {
1239 			hex_print(data, size, f);
1240 		}
1241 		return 0;
1242 	}
1243 
1244 	f = fopen(fname, "w");
1245 	if (!f) {
1246 		p_err("failed to open %s: %s", fname, strerror(errno));
1247 		return -1;
1248 	}
1249 
1250 	nb_written = fwrite(data, 1, size, f);
1251 	fclose(f);
1252 	if (nb_written != size) {
1253 		p_err("failed to write output data/ctx: %s", strerror(errno));
1254 		return -1;
1255 	}
1256 
1257 	return 0;
1258 }
1259 
1260 static int alloc_run_data(void **data_ptr, unsigned int size_out)
1261 {
1262 	*data_ptr = calloc(size_out, 1);
1263 	if (!*data_ptr) {
1264 		p_err("failed to allocate memory for output data/ctx: %s",
1265 		      strerror(errno));
1266 		return -1;
1267 	}
1268 
1269 	return 0;
1270 }
1271 
1272 static int do_run(int argc, char **argv)
1273 {
1274 	char *data_fname_in = NULL, *data_fname_out = NULL;
1275 	char *ctx_fname_in = NULL, *ctx_fname_out = NULL;
1276 	const unsigned int default_size = SZ_32K;
1277 	void *data_in = NULL, *data_out = NULL;
1278 	void *ctx_in = NULL, *ctx_out = NULL;
1279 	unsigned int repeat = 1;
1280 	int fd, err;
1281 	LIBBPF_OPTS(bpf_test_run_opts, test_attr);
1282 
1283 	if (!REQ_ARGS(4))
1284 		return -1;
1285 
1286 	fd = prog_parse_fd(&argc, &argv);
1287 	if (fd < 0)
1288 		return -1;
1289 
1290 	while (argc) {
1291 		if (detect_common_prefix(*argv, "data_in", "data_out",
1292 					 "data_size_out", NULL))
1293 			return -1;
1294 		if (detect_common_prefix(*argv, "ctx_in", "ctx_out",
1295 					 "ctx_size_out", NULL))
1296 			return -1;
1297 
1298 		if (is_prefix(*argv, "data_in")) {
1299 			NEXT_ARG();
1300 			if (!REQ_ARGS(1))
1301 				return -1;
1302 
1303 			data_fname_in = GET_ARG();
1304 			if (check_single_stdin(data_fname_in, ctx_fname_in))
1305 				return -1;
1306 		} else if (is_prefix(*argv, "data_out")) {
1307 			NEXT_ARG();
1308 			if (!REQ_ARGS(1))
1309 				return -1;
1310 
1311 			data_fname_out = GET_ARG();
1312 		} else if (is_prefix(*argv, "data_size_out")) {
1313 			char *endptr;
1314 
1315 			NEXT_ARG();
1316 			if (!REQ_ARGS(1))
1317 				return -1;
1318 
1319 			test_attr.data_size_out = strtoul(*argv, &endptr, 0);
1320 			if (*endptr) {
1321 				p_err("can't parse %s as output data size",
1322 				      *argv);
1323 				return -1;
1324 			}
1325 			NEXT_ARG();
1326 		} else if (is_prefix(*argv, "ctx_in")) {
1327 			NEXT_ARG();
1328 			if (!REQ_ARGS(1))
1329 				return -1;
1330 
1331 			ctx_fname_in = GET_ARG();
1332 			if (check_single_stdin(data_fname_in, ctx_fname_in))
1333 				return -1;
1334 		} else if (is_prefix(*argv, "ctx_out")) {
1335 			NEXT_ARG();
1336 			if (!REQ_ARGS(1))
1337 				return -1;
1338 
1339 			ctx_fname_out = GET_ARG();
1340 		} else if (is_prefix(*argv, "ctx_size_out")) {
1341 			char *endptr;
1342 
1343 			NEXT_ARG();
1344 			if (!REQ_ARGS(1))
1345 				return -1;
1346 
1347 			test_attr.ctx_size_out = strtoul(*argv, &endptr, 0);
1348 			if (*endptr) {
1349 				p_err("can't parse %s as output context size",
1350 				      *argv);
1351 				return -1;
1352 			}
1353 			NEXT_ARG();
1354 		} else if (is_prefix(*argv, "repeat")) {
1355 			char *endptr;
1356 
1357 			NEXT_ARG();
1358 			if (!REQ_ARGS(1))
1359 				return -1;
1360 
1361 			repeat = strtoul(*argv, &endptr, 0);
1362 			if (*endptr) {
1363 				p_err("can't parse %s as repeat number",
1364 				      *argv);
1365 				return -1;
1366 			}
1367 			NEXT_ARG();
1368 		} else {
1369 			p_err("expected no more arguments, 'data_in', 'data_out', 'data_size_out', 'ctx_in', 'ctx_out', 'ctx_size_out' or 'repeat', got: '%s'?",
1370 			      *argv);
1371 			return -1;
1372 		}
1373 	}
1374 
1375 	err = get_run_data(data_fname_in, &data_in, &test_attr.data_size_in);
1376 	if (err)
1377 		return -1;
1378 
1379 	if (data_in) {
1380 		if (!test_attr.data_size_out)
1381 			test_attr.data_size_out = default_size;
1382 		err = alloc_run_data(&data_out, test_attr.data_size_out);
1383 		if (err)
1384 			goto free_data_in;
1385 	}
1386 
1387 	err = get_run_data(ctx_fname_in, &ctx_in, &test_attr.ctx_size_in);
1388 	if (err)
1389 		goto free_data_out;
1390 
1391 	if (ctx_in) {
1392 		if (!test_attr.ctx_size_out)
1393 			test_attr.ctx_size_out = default_size;
1394 		err = alloc_run_data(&ctx_out, test_attr.ctx_size_out);
1395 		if (err)
1396 			goto free_ctx_in;
1397 	}
1398 
1399 	test_attr.repeat	= repeat;
1400 	test_attr.data_in	= data_in;
1401 	test_attr.data_out	= data_out;
1402 	test_attr.ctx_in	= ctx_in;
1403 	test_attr.ctx_out	= ctx_out;
1404 
1405 	err = bpf_prog_test_run_opts(fd, &test_attr);
1406 	if (err) {
1407 		p_err("failed to run program: %s", strerror(errno));
1408 		goto free_ctx_out;
1409 	}
1410 
1411 	err = 0;
1412 
1413 	if (json_output)
1414 		jsonw_start_object(json_wtr);	/* root */
1415 
1416 	/* Do not exit on errors occurring when printing output data/context,
1417 	 * we still want to print return value and duration for program run.
1418 	 */
1419 	if (test_attr.data_size_out)
1420 		err += print_run_output(test_attr.data_out,
1421 					test_attr.data_size_out,
1422 					data_fname_out, "data_out");
1423 	if (test_attr.ctx_size_out)
1424 		err += print_run_output(test_attr.ctx_out,
1425 					test_attr.ctx_size_out,
1426 					ctx_fname_out, "ctx_out");
1427 
1428 	if (json_output) {
1429 		jsonw_uint_field(json_wtr, "retval", test_attr.retval);
1430 		jsonw_uint_field(json_wtr, "duration", test_attr.duration);
1431 		jsonw_end_object(json_wtr);	/* root */
1432 	} else {
1433 		fprintf(stdout, "Return value: %u, duration%s: %uns\n",
1434 			test_attr.retval,
1435 			repeat > 1 ? " (average)" : "", test_attr.duration);
1436 	}
1437 
1438 free_ctx_out:
1439 	free(ctx_out);
1440 free_ctx_in:
1441 	free(ctx_in);
1442 free_data_out:
1443 	free(data_out);
1444 free_data_in:
1445 	free(data_in);
1446 
1447 	return err;
1448 }
1449 
1450 static int
1451 get_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
1452 		      enum bpf_attach_type *expected_attach_type)
1453 {
1454 	libbpf_print_fn_t print_backup;
1455 	int ret;
1456 
1457 	ret = libbpf_prog_type_by_name(name, prog_type, expected_attach_type);
1458 	if (!ret)
1459 		return ret;
1460 
1461 	/* libbpf_prog_type_by_name() failed, let's re-run with debug level */
1462 	print_backup = libbpf_set_print(print_all_levels);
1463 	ret = libbpf_prog_type_by_name(name, prog_type, expected_attach_type);
1464 	libbpf_set_print(print_backup);
1465 
1466 	return ret;
1467 }
1468 
1469 static int load_with_options(int argc, char **argv, bool first_prog_only)
1470 {
1471 	enum bpf_prog_type common_prog_type = BPF_PROG_TYPE_UNSPEC;
1472 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, open_opts,
1473 		.relaxed_maps = relaxed_maps,
1474 	);
1475 	enum bpf_attach_type expected_attach_type;
1476 	struct map_replace *map_replace = NULL;
1477 	struct bpf_program *prog = NULL, *pos;
1478 	unsigned int old_map_fds = 0;
1479 	const char *pinmaps = NULL;
1480 	struct bpf_object *obj;
1481 	struct bpf_map *map;
1482 	const char *pinfile;
1483 	unsigned int i, j;
1484 	__u32 ifindex = 0;
1485 	const char *file;
1486 	int idx, err;
1487 
1488 
1489 	if (!REQ_ARGS(2))
1490 		return -1;
1491 	file = GET_ARG();
1492 	pinfile = GET_ARG();
1493 
1494 	while (argc) {
1495 		if (is_prefix(*argv, "type")) {
1496 			NEXT_ARG();
1497 
1498 			if (common_prog_type != BPF_PROG_TYPE_UNSPEC) {
1499 				p_err("program type already specified");
1500 				goto err_free_reuse_maps;
1501 			}
1502 			if (!REQ_ARGS(1))
1503 				goto err_free_reuse_maps;
1504 
1505 			err = libbpf_prog_type_by_name(*argv, &common_prog_type,
1506 						       &expected_attach_type);
1507 			if (err < 0) {
1508 				/* Put a '/' at the end of type to appease libbpf */
1509 				char *type = malloc(strlen(*argv) + 2);
1510 
1511 				if (!type) {
1512 					p_err("mem alloc failed");
1513 					goto err_free_reuse_maps;
1514 				}
1515 				*type = 0;
1516 				strcat(type, *argv);
1517 				strcat(type, "/");
1518 
1519 				err = get_prog_type_by_name(type, &common_prog_type,
1520 							    &expected_attach_type);
1521 				free(type);
1522 				if (err < 0)
1523 					goto err_free_reuse_maps;
1524 			}
1525 
1526 			NEXT_ARG();
1527 		} else if (is_prefix(*argv, "map")) {
1528 			void *new_map_replace;
1529 			char *endptr, *name;
1530 			int fd;
1531 
1532 			NEXT_ARG();
1533 
1534 			if (!REQ_ARGS(4))
1535 				goto err_free_reuse_maps;
1536 
1537 			if (is_prefix(*argv, "idx")) {
1538 				NEXT_ARG();
1539 
1540 				idx = strtoul(*argv, &endptr, 0);
1541 				if (*endptr) {
1542 					p_err("can't parse %s as IDX", *argv);
1543 					goto err_free_reuse_maps;
1544 				}
1545 				name = NULL;
1546 			} else if (is_prefix(*argv, "name")) {
1547 				NEXT_ARG();
1548 
1549 				name = *argv;
1550 				idx = -1;
1551 			} else {
1552 				p_err("expected 'idx' or 'name', got: '%s'?",
1553 				      *argv);
1554 				goto err_free_reuse_maps;
1555 			}
1556 			NEXT_ARG();
1557 
1558 			fd = map_parse_fd(&argc, &argv);
1559 			if (fd < 0)
1560 				goto err_free_reuse_maps;
1561 
1562 			new_map_replace = libbpf_reallocarray(map_replace,
1563 							      old_map_fds + 1,
1564 							      sizeof(*map_replace));
1565 			if (!new_map_replace) {
1566 				p_err("mem alloc failed");
1567 				goto err_free_reuse_maps;
1568 			}
1569 			map_replace = new_map_replace;
1570 
1571 			map_replace[old_map_fds].idx = idx;
1572 			map_replace[old_map_fds].name = name;
1573 			map_replace[old_map_fds].fd = fd;
1574 			old_map_fds++;
1575 		} else if (is_prefix(*argv, "dev")) {
1576 			NEXT_ARG();
1577 
1578 			if (ifindex) {
1579 				p_err("offload device already specified");
1580 				goto err_free_reuse_maps;
1581 			}
1582 			if (!REQ_ARGS(1))
1583 				goto err_free_reuse_maps;
1584 
1585 			ifindex = if_nametoindex(*argv);
1586 			if (!ifindex) {
1587 				p_err("unrecognized netdevice '%s': %s",
1588 				      *argv, strerror(errno));
1589 				goto err_free_reuse_maps;
1590 			}
1591 			NEXT_ARG();
1592 		} else if (is_prefix(*argv, "pinmaps")) {
1593 			NEXT_ARG();
1594 
1595 			if (!REQ_ARGS(1))
1596 				goto err_free_reuse_maps;
1597 
1598 			pinmaps = GET_ARG();
1599 		} else {
1600 			p_err("expected no more arguments, 'type', 'map' or 'dev', got: '%s'?",
1601 			      *argv);
1602 			goto err_free_reuse_maps;
1603 		}
1604 	}
1605 
1606 	set_max_rlimit();
1607 
1608 	if (verifier_logs)
1609 		/* log_level1 + log_level2 + stats, but not stable UAPI */
1610 		open_opts.kernel_log_level = 1 + 2 + 4;
1611 
1612 	obj = bpf_object__open_file(file, &open_opts);
1613 	if (libbpf_get_error(obj)) {
1614 		p_err("failed to open object file");
1615 		goto err_free_reuse_maps;
1616 	}
1617 
1618 	bpf_object__for_each_program(pos, obj) {
1619 		enum bpf_prog_type prog_type = common_prog_type;
1620 
1621 		if (prog_type == BPF_PROG_TYPE_UNSPEC) {
1622 			const char *sec_name = bpf_program__section_name(pos);
1623 
1624 			err = get_prog_type_by_name(sec_name, &prog_type,
1625 						    &expected_attach_type);
1626 			if (err < 0)
1627 				goto err_close_obj;
1628 		}
1629 
1630 		bpf_program__set_ifindex(pos, ifindex);
1631 		bpf_program__set_type(pos, prog_type);
1632 		bpf_program__set_expected_attach_type(pos, expected_attach_type);
1633 	}
1634 
1635 	qsort(map_replace, old_map_fds, sizeof(*map_replace),
1636 	      map_replace_compar);
1637 
1638 	/* After the sort maps by name will be first on the list, because they
1639 	 * have idx == -1.  Resolve them.
1640 	 */
1641 	j = 0;
1642 	while (j < old_map_fds && map_replace[j].name) {
1643 		i = 0;
1644 		bpf_object__for_each_map(map, obj) {
1645 			if (!strcmp(bpf_map__name(map), map_replace[j].name)) {
1646 				map_replace[j].idx = i;
1647 				break;
1648 			}
1649 			i++;
1650 		}
1651 		if (map_replace[j].idx == -1) {
1652 			p_err("unable to find map '%s'", map_replace[j].name);
1653 			goto err_close_obj;
1654 		}
1655 		j++;
1656 	}
1657 	/* Resort if any names were resolved */
1658 	if (j)
1659 		qsort(map_replace, old_map_fds, sizeof(*map_replace),
1660 		      map_replace_compar);
1661 
1662 	/* Set ifindex and name reuse */
1663 	j = 0;
1664 	idx = 0;
1665 	bpf_object__for_each_map(map, obj) {
1666 		if (bpf_map__type(map) != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
1667 			bpf_map__set_ifindex(map, ifindex);
1668 
1669 		if (j < old_map_fds && idx == map_replace[j].idx) {
1670 			err = bpf_map__reuse_fd(map, map_replace[j++].fd);
1671 			if (err) {
1672 				p_err("unable to set up map reuse: %d", err);
1673 				goto err_close_obj;
1674 			}
1675 
1676 			/* Next reuse wants to apply to the same map */
1677 			if (j < old_map_fds && map_replace[j].idx == idx) {
1678 				p_err("replacement for map idx %d specified more than once",
1679 				      idx);
1680 				goto err_close_obj;
1681 			}
1682 		}
1683 
1684 		idx++;
1685 	}
1686 	if (j < old_map_fds) {
1687 		p_err("map idx '%d' not used", map_replace[j].idx);
1688 		goto err_close_obj;
1689 	}
1690 
1691 	err = bpf_object__load(obj);
1692 	if (err) {
1693 		p_err("failed to load object file");
1694 		goto err_close_obj;
1695 	}
1696 
1697 	err = mount_bpffs_for_pin(pinfile);
1698 	if (err)
1699 		goto err_close_obj;
1700 
1701 	if (first_prog_only) {
1702 		prog = bpf_object__next_program(obj, NULL);
1703 		if (!prog) {
1704 			p_err("object file doesn't contain any bpf program");
1705 			goto err_close_obj;
1706 		}
1707 
1708 		err = bpf_obj_pin(bpf_program__fd(prog), pinfile);
1709 		if (err) {
1710 			p_err("failed to pin program %s",
1711 			      bpf_program__section_name(prog));
1712 			goto err_close_obj;
1713 		}
1714 	} else {
1715 		err = bpf_object__pin_programs(obj, pinfile);
1716 		if (err) {
1717 			p_err("failed to pin all programs");
1718 			goto err_close_obj;
1719 		}
1720 	}
1721 
1722 	if (pinmaps) {
1723 		err = bpf_object__pin_maps(obj, pinmaps);
1724 		if (err) {
1725 			p_err("failed to pin all maps");
1726 			goto err_unpin;
1727 		}
1728 	}
1729 
1730 	if (json_output)
1731 		jsonw_null(json_wtr);
1732 
1733 	bpf_object__close(obj);
1734 	for (i = 0; i < old_map_fds; i++)
1735 		close(map_replace[i].fd);
1736 	free(map_replace);
1737 
1738 	return 0;
1739 
1740 err_unpin:
1741 	if (first_prog_only)
1742 		unlink(pinfile);
1743 	else
1744 		bpf_object__unpin_programs(obj, pinfile);
1745 err_close_obj:
1746 	if (!legacy_libbpf) {
1747 		p_info("Warning: bpftool is now running in libbpf strict mode and has more stringent requirements about BPF programs.\n"
1748 		       "If it used to work for this object file but now doesn't, see --legacy option for more details.\n");
1749 	}
1750 
1751 	bpf_object__close(obj);
1752 err_free_reuse_maps:
1753 	for (i = 0; i < old_map_fds; i++)
1754 		close(map_replace[i].fd);
1755 	free(map_replace);
1756 	return -1;
1757 }
1758 
1759 static int count_open_fds(void)
1760 {
1761 	DIR *dp = opendir("/proc/self/fd");
1762 	struct dirent *de;
1763 	int cnt = -3;
1764 
1765 	if (!dp)
1766 		return -1;
1767 
1768 	while ((de = readdir(dp)))
1769 		cnt++;
1770 
1771 	closedir(dp);
1772 	return cnt;
1773 }
1774 
1775 static int try_loader(struct gen_loader_opts *gen)
1776 {
1777 	struct bpf_load_and_run_opts opts = {};
1778 	struct bpf_loader_ctx *ctx;
1779 	int ctx_sz = sizeof(*ctx) + 64 * max(sizeof(struct bpf_map_desc),
1780 					     sizeof(struct bpf_prog_desc));
1781 	int log_buf_sz = (1u << 24) - 1;
1782 	int err, fds_before, fd_delta;
1783 	char *log_buf = NULL;
1784 
1785 	ctx = alloca(ctx_sz);
1786 	memset(ctx, 0, ctx_sz);
1787 	ctx->sz = ctx_sz;
1788 	if (verifier_logs) {
1789 		ctx->log_level = 1 + 2 + 4;
1790 		ctx->log_size = log_buf_sz;
1791 		log_buf = malloc(log_buf_sz);
1792 		if (!log_buf)
1793 			return -ENOMEM;
1794 		ctx->log_buf = (long) log_buf;
1795 	}
1796 	opts.ctx = ctx;
1797 	opts.data = gen->data;
1798 	opts.data_sz = gen->data_sz;
1799 	opts.insns = gen->insns;
1800 	opts.insns_sz = gen->insns_sz;
1801 	fds_before = count_open_fds();
1802 	err = bpf_load_and_run(&opts);
1803 	fd_delta = count_open_fds() - fds_before;
1804 	if (err < 0 || verifier_logs) {
1805 		fprintf(stderr, "err %d\n%s\n%s", err, opts.errstr, log_buf);
1806 		if (fd_delta && err < 0)
1807 			fprintf(stderr, "loader prog leaked %d FDs\n",
1808 				fd_delta);
1809 	}
1810 	free(log_buf);
1811 	return err;
1812 }
1813 
1814 static int do_loader(int argc, char **argv)
1815 {
1816 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, open_opts);
1817 	DECLARE_LIBBPF_OPTS(gen_loader_opts, gen);
1818 	struct bpf_object *obj;
1819 	const char *file;
1820 	int err = 0;
1821 
1822 	if (!REQ_ARGS(1))
1823 		return -1;
1824 	file = GET_ARG();
1825 
1826 	if (verifier_logs)
1827 		/* log_level1 + log_level2 + stats, but not stable UAPI */
1828 		open_opts.kernel_log_level = 1 + 2 + 4;
1829 
1830 	obj = bpf_object__open_file(file, &open_opts);
1831 	if (libbpf_get_error(obj)) {
1832 		p_err("failed to open object file");
1833 		goto err_close_obj;
1834 	}
1835 
1836 	err = bpf_object__gen_loader(obj, &gen);
1837 	if (err)
1838 		goto err_close_obj;
1839 
1840 	err = bpf_object__load(obj);
1841 	if (err) {
1842 		p_err("failed to load object file");
1843 		goto err_close_obj;
1844 	}
1845 
1846 	if (verifier_logs) {
1847 		struct dump_data dd = {};
1848 
1849 		kernel_syms_load(&dd);
1850 		dump_xlated_plain(&dd, (void *)gen.insns, gen.insns_sz, false, false);
1851 		kernel_syms_destroy(&dd);
1852 	}
1853 	err = try_loader(&gen);
1854 err_close_obj:
1855 	bpf_object__close(obj);
1856 	return err;
1857 }
1858 
1859 static int do_load(int argc, char **argv)
1860 {
1861 	if (use_loader)
1862 		return do_loader(argc, argv);
1863 	return load_with_options(argc, argv, true);
1864 }
1865 
1866 static int do_loadall(int argc, char **argv)
1867 {
1868 	return load_with_options(argc, argv, false);
1869 }
1870 
1871 #ifdef BPFTOOL_WITHOUT_SKELETONS
1872 
1873 static int do_profile(int argc, char **argv)
1874 {
1875 	p_err("bpftool prog profile command is not supported. Please build bpftool with clang >= 10.0.0");
1876 	return 0;
1877 }
1878 
1879 #else /* BPFTOOL_WITHOUT_SKELETONS */
1880 
1881 #include "profiler.skel.h"
1882 
1883 struct profile_metric {
1884 	const char *name;
1885 	struct bpf_perf_event_value val;
1886 	struct perf_event_attr attr;
1887 	bool selected;
1888 
1889 	/* calculate ratios like instructions per cycle */
1890 	const int ratio_metric; /* 0 for N/A, 1 for index 0 (cycles) */
1891 	const char *ratio_desc;
1892 	const float ratio_mul;
1893 } metrics[] = {
1894 	{
1895 		.name = "cycles",
1896 		.attr = {
1897 			.type = PERF_TYPE_HARDWARE,
1898 			.config = PERF_COUNT_HW_CPU_CYCLES,
1899 			.exclude_user = 1,
1900 		},
1901 	},
1902 	{
1903 		.name = "instructions",
1904 		.attr = {
1905 			.type = PERF_TYPE_HARDWARE,
1906 			.config = PERF_COUNT_HW_INSTRUCTIONS,
1907 			.exclude_user = 1,
1908 		},
1909 		.ratio_metric = 1,
1910 		.ratio_desc = "insns per cycle",
1911 		.ratio_mul = 1.0,
1912 	},
1913 	{
1914 		.name = "l1d_loads",
1915 		.attr = {
1916 			.type = PERF_TYPE_HW_CACHE,
1917 			.config =
1918 				PERF_COUNT_HW_CACHE_L1D |
1919 				(PERF_COUNT_HW_CACHE_OP_READ << 8) |
1920 				(PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16),
1921 			.exclude_user = 1,
1922 		},
1923 	},
1924 	{
1925 		.name = "llc_misses",
1926 		.attr = {
1927 			.type = PERF_TYPE_HW_CACHE,
1928 			.config =
1929 				PERF_COUNT_HW_CACHE_LL |
1930 				(PERF_COUNT_HW_CACHE_OP_READ << 8) |
1931 				(PERF_COUNT_HW_CACHE_RESULT_MISS << 16),
1932 			.exclude_user = 1
1933 		},
1934 		.ratio_metric = 2,
1935 		.ratio_desc = "LLC misses per million insns",
1936 		.ratio_mul = 1e6,
1937 	},
1938 	{
1939 		.name = "itlb_misses",
1940 		.attr = {
1941 			.type = PERF_TYPE_HW_CACHE,
1942 			.config =
1943 				PERF_COUNT_HW_CACHE_ITLB |
1944 				(PERF_COUNT_HW_CACHE_OP_READ << 8) |
1945 				(PERF_COUNT_HW_CACHE_RESULT_MISS << 16),
1946 			.exclude_user = 1
1947 		},
1948 		.ratio_metric = 2,
1949 		.ratio_desc = "itlb misses per million insns",
1950 		.ratio_mul = 1e6,
1951 	},
1952 	{
1953 		.name = "dtlb_misses",
1954 		.attr = {
1955 			.type = PERF_TYPE_HW_CACHE,
1956 			.config =
1957 				PERF_COUNT_HW_CACHE_DTLB |
1958 				(PERF_COUNT_HW_CACHE_OP_READ << 8) |
1959 				(PERF_COUNT_HW_CACHE_RESULT_MISS << 16),
1960 			.exclude_user = 1
1961 		},
1962 		.ratio_metric = 2,
1963 		.ratio_desc = "dtlb misses per million insns",
1964 		.ratio_mul = 1e6,
1965 	},
1966 };
1967 
1968 static __u64 profile_total_count;
1969 
1970 #define MAX_NUM_PROFILE_METRICS 4
1971 
1972 static int profile_parse_metrics(int argc, char **argv)
1973 {
1974 	unsigned int metric_cnt;
1975 	int selected_cnt = 0;
1976 	unsigned int i;
1977 
1978 	metric_cnt = sizeof(metrics) / sizeof(struct profile_metric);
1979 
1980 	while (argc > 0) {
1981 		for (i = 0; i < metric_cnt; i++) {
1982 			if (is_prefix(argv[0], metrics[i].name)) {
1983 				if (!metrics[i].selected)
1984 					selected_cnt++;
1985 				metrics[i].selected = true;
1986 				break;
1987 			}
1988 		}
1989 		if (i == metric_cnt) {
1990 			p_err("unknown metric %s", argv[0]);
1991 			return -1;
1992 		}
1993 		NEXT_ARG();
1994 	}
1995 	if (selected_cnt > MAX_NUM_PROFILE_METRICS) {
1996 		p_err("too many (%d) metrics, please specify no more than %d metrics at at time",
1997 		      selected_cnt, MAX_NUM_PROFILE_METRICS);
1998 		return -1;
1999 	}
2000 	return selected_cnt;
2001 }
2002 
2003 static void profile_read_values(struct profiler_bpf *obj)
2004 {
2005 	__u32 m, cpu, num_cpu = obj->rodata->num_cpu;
2006 	int reading_map_fd, count_map_fd;
2007 	__u64 counts[num_cpu];
2008 	__u32 key = 0;
2009 	int err;
2010 
2011 	reading_map_fd = bpf_map__fd(obj->maps.accum_readings);
2012 	count_map_fd = bpf_map__fd(obj->maps.counts);
2013 	if (reading_map_fd < 0 || count_map_fd < 0) {
2014 		p_err("failed to get fd for map");
2015 		return;
2016 	}
2017 
2018 	err = bpf_map_lookup_elem(count_map_fd, &key, counts);
2019 	if (err) {
2020 		p_err("failed to read count_map: %s", strerror(errno));
2021 		return;
2022 	}
2023 
2024 	profile_total_count = 0;
2025 	for (cpu = 0; cpu < num_cpu; cpu++)
2026 		profile_total_count += counts[cpu];
2027 
2028 	for (m = 0; m < ARRAY_SIZE(metrics); m++) {
2029 		struct bpf_perf_event_value values[num_cpu];
2030 
2031 		if (!metrics[m].selected)
2032 			continue;
2033 
2034 		err = bpf_map_lookup_elem(reading_map_fd, &key, values);
2035 		if (err) {
2036 			p_err("failed to read reading_map: %s",
2037 			      strerror(errno));
2038 			return;
2039 		}
2040 		for (cpu = 0; cpu < num_cpu; cpu++) {
2041 			metrics[m].val.counter += values[cpu].counter;
2042 			metrics[m].val.enabled += values[cpu].enabled;
2043 			metrics[m].val.running += values[cpu].running;
2044 		}
2045 		key++;
2046 	}
2047 }
2048 
2049 static void profile_print_readings_json(void)
2050 {
2051 	__u32 m;
2052 
2053 	jsonw_start_array(json_wtr);
2054 	for (m = 0; m < ARRAY_SIZE(metrics); m++) {
2055 		if (!metrics[m].selected)
2056 			continue;
2057 		jsonw_start_object(json_wtr);
2058 		jsonw_string_field(json_wtr, "metric", metrics[m].name);
2059 		jsonw_lluint_field(json_wtr, "run_cnt", profile_total_count);
2060 		jsonw_lluint_field(json_wtr, "value", metrics[m].val.counter);
2061 		jsonw_lluint_field(json_wtr, "enabled", metrics[m].val.enabled);
2062 		jsonw_lluint_field(json_wtr, "running", metrics[m].val.running);
2063 
2064 		jsonw_end_object(json_wtr);
2065 	}
2066 	jsonw_end_array(json_wtr);
2067 }
2068 
2069 static void profile_print_readings_plain(void)
2070 {
2071 	__u32 m;
2072 
2073 	printf("\n%18llu %-20s\n", profile_total_count, "run_cnt");
2074 	for (m = 0; m < ARRAY_SIZE(metrics); m++) {
2075 		struct bpf_perf_event_value *val = &metrics[m].val;
2076 		int r;
2077 
2078 		if (!metrics[m].selected)
2079 			continue;
2080 		printf("%18llu %-20s", val->counter, metrics[m].name);
2081 
2082 		r = metrics[m].ratio_metric - 1;
2083 		if (r >= 0 && metrics[r].selected &&
2084 		    metrics[r].val.counter > 0) {
2085 			printf("# %8.2f %-30s",
2086 			       val->counter * metrics[m].ratio_mul /
2087 			       metrics[r].val.counter,
2088 			       metrics[m].ratio_desc);
2089 		} else {
2090 			printf("%-41s", "");
2091 		}
2092 
2093 		if (val->enabled > val->running)
2094 			printf("(%4.2f%%)",
2095 			       val->running * 100.0 / val->enabled);
2096 		printf("\n");
2097 	}
2098 }
2099 
2100 static void profile_print_readings(void)
2101 {
2102 	if (json_output)
2103 		profile_print_readings_json();
2104 	else
2105 		profile_print_readings_plain();
2106 }
2107 
2108 static char *profile_target_name(int tgt_fd)
2109 {
2110 	struct bpf_func_info func_info;
2111 	struct bpf_prog_info info = {};
2112 	__u32 info_len = sizeof(info);
2113 	const struct btf_type *t;
2114 	__u32 func_info_rec_size;
2115 	struct btf *btf = NULL;
2116 	char *name = NULL;
2117 	int err;
2118 
2119 	err = bpf_obj_get_info_by_fd(tgt_fd, &info, &info_len);
2120 	if (err) {
2121 		p_err("failed to bpf_obj_get_info_by_fd for prog FD %d", tgt_fd);
2122 		goto out;
2123 	}
2124 
2125 	if (info.btf_id == 0) {
2126 		p_err("prog FD %d doesn't have valid btf", tgt_fd);
2127 		goto out;
2128 	}
2129 
2130 	func_info_rec_size = info.func_info_rec_size;
2131 	if (info.nr_func_info == 0) {
2132 		p_err("bpf_obj_get_info_by_fd for prog FD %d found 0 func_info", tgt_fd);
2133 		goto out;
2134 	}
2135 
2136 	memset(&info, 0, sizeof(info));
2137 	info.nr_func_info = 1;
2138 	info.func_info_rec_size = func_info_rec_size;
2139 	info.func_info = ptr_to_u64(&func_info);
2140 
2141 	err = bpf_obj_get_info_by_fd(tgt_fd, &info, &info_len);
2142 	if (err) {
2143 		p_err("failed to get func_info for prog FD %d", tgt_fd);
2144 		goto out;
2145 	}
2146 
2147 	btf = btf__load_from_kernel_by_id(info.btf_id);
2148 	if (libbpf_get_error(btf)) {
2149 		p_err("failed to load btf for prog FD %d", tgt_fd);
2150 		goto out;
2151 	}
2152 
2153 	t = btf__type_by_id(btf, func_info.type_id);
2154 	if (!t) {
2155 		p_err("btf %d doesn't have type %d",
2156 		      info.btf_id, func_info.type_id);
2157 		goto out;
2158 	}
2159 	name = strdup(btf__name_by_offset(btf, t->name_off));
2160 out:
2161 	btf__free(btf);
2162 	return name;
2163 }
2164 
2165 static struct profiler_bpf *profile_obj;
2166 static int profile_tgt_fd = -1;
2167 static char *profile_tgt_name;
2168 static int *profile_perf_events;
2169 static int profile_perf_event_cnt;
2170 
2171 static void profile_close_perf_events(struct profiler_bpf *obj)
2172 {
2173 	int i;
2174 
2175 	for (i = profile_perf_event_cnt - 1; i >= 0; i--)
2176 		close(profile_perf_events[i]);
2177 
2178 	free(profile_perf_events);
2179 	profile_perf_event_cnt = 0;
2180 }
2181 
2182 static int profile_open_perf_events(struct profiler_bpf *obj)
2183 {
2184 	unsigned int cpu, m;
2185 	int map_fd, pmu_fd;
2186 
2187 	profile_perf_events = calloc(
2188 		sizeof(int), obj->rodata->num_cpu * obj->rodata->num_metric);
2189 	if (!profile_perf_events) {
2190 		p_err("failed to allocate memory for perf_event array: %s",
2191 		      strerror(errno));
2192 		return -1;
2193 	}
2194 	map_fd = bpf_map__fd(obj->maps.events);
2195 	if (map_fd < 0) {
2196 		p_err("failed to get fd for events map");
2197 		return -1;
2198 	}
2199 
2200 	for (m = 0; m < ARRAY_SIZE(metrics); m++) {
2201 		if (!metrics[m].selected)
2202 			continue;
2203 		for (cpu = 0; cpu < obj->rodata->num_cpu; cpu++) {
2204 			pmu_fd = syscall(__NR_perf_event_open, &metrics[m].attr,
2205 					 -1/*pid*/, cpu, -1/*group_fd*/, 0);
2206 			if (pmu_fd < 0 ||
2207 			    bpf_map_update_elem(map_fd, &profile_perf_event_cnt,
2208 						&pmu_fd, BPF_ANY) ||
2209 			    ioctl(pmu_fd, PERF_EVENT_IOC_ENABLE, 0)) {
2210 				p_err("failed to create event %s on cpu %d",
2211 				      metrics[m].name, cpu);
2212 				return -1;
2213 			}
2214 			profile_perf_events[profile_perf_event_cnt++] = pmu_fd;
2215 		}
2216 	}
2217 	return 0;
2218 }
2219 
2220 static void profile_print_and_cleanup(void)
2221 {
2222 	profile_close_perf_events(profile_obj);
2223 	profile_read_values(profile_obj);
2224 	profile_print_readings();
2225 	profiler_bpf__destroy(profile_obj);
2226 
2227 	close(profile_tgt_fd);
2228 	free(profile_tgt_name);
2229 }
2230 
2231 static void int_exit(int signo)
2232 {
2233 	profile_print_and_cleanup();
2234 	exit(0);
2235 }
2236 
2237 static int do_profile(int argc, char **argv)
2238 {
2239 	int num_metric, num_cpu, err = -1;
2240 	struct bpf_program *prog;
2241 	unsigned long duration;
2242 	char *endptr;
2243 
2244 	/* we at least need two args for the prog and one metric */
2245 	if (!REQ_ARGS(3))
2246 		return -EINVAL;
2247 
2248 	/* parse target fd */
2249 	profile_tgt_fd = prog_parse_fd(&argc, &argv);
2250 	if (profile_tgt_fd < 0) {
2251 		p_err("failed to parse fd");
2252 		return -1;
2253 	}
2254 
2255 	/* parse profiling optional duration */
2256 	if (argc > 2 && is_prefix(argv[0], "duration")) {
2257 		NEXT_ARG();
2258 		duration = strtoul(*argv, &endptr, 0);
2259 		if (*endptr)
2260 			usage();
2261 		NEXT_ARG();
2262 	} else {
2263 		duration = UINT_MAX;
2264 	}
2265 
2266 	num_metric = profile_parse_metrics(argc, argv);
2267 	if (num_metric <= 0)
2268 		goto out;
2269 
2270 	num_cpu = libbpf_num_possible_cpus();
2271 	if (num_cpu <= 0) {
2272 		p_err("failed to identify number of CPUs");
2273 		goto out;
2274 	}
2275 
2276 	profile_obj = profiler_bpf__open();
2277 	if (!profile_obj) {
2278 		p_err("failed to open and/or load BPF object");
2279 		goto out;
2280 	}
2281 
2282 	profile_obj->rodata->num_cpu = num_cpu;
2283 	profile_obj->rodata->num_metric = num_metric;
2284 
2285 	/* adjust map sizes */
2286 	bpf_map__set_max_entries(profile_obj->maps.events, num_metric * num_cpu);
2287 	bpf_map__set_max_entries(profile_obj->maps.fentry_readings, num_metric);
2288 	bpf_map__set_max_entries(profile_obj->maps.accum_readings, num_metric);
2289 	bpf_map__set_max_entries(profile_obj->maps.counts, 1);
2290 
2291 	/* change target name */
2292 	profile_tgt_name = profile_target_name(profile_tgt_fd);
2293 	if (!profile_tgt_name)
2294 		goto out;
2295 
2296 	bpf_object__for_each_program(prog, profile_obj->obj) {
2297 		err = bpf_program__set_attach_target(prog, profile_tgt_fd,
2298 						     profile_tgt_name);
2299 		if (err) {
2300 			p_err("failed to set attach target\n");
2301 			goto out;
2302 		}
2303 	}
2304 
2305 	set_max_rlimit();
2306 	err = profiler_bpf__load(profile_obj);
2307 	if (err) {
2308 		p_err("failed to load profile_obj");
2309 		goto out;
2310 	}
2311 
2312 	err = profile_open_perf_events(profile_obj);
2313 	if (err)
2314 		goto out;
2315 
2316 	err = profiler_bpf__attach(profile_obj);
2317 	if (err) {
2318 		p_err("failed to attach profile_obj");
2319 		goto out;
2320 	}
2321 	signal(SIGINT, int_exit);
2322 
2323 	sleep(duration);
2324 	profile_print_and_cleanup();
2325 	return 0;
2326 
2327 out:
2328 	profile_close_perf_events(profile_obj);
2329 	if (profile_obj)
2330 		profiler_bpf__destroy(profile_obj);
2331 	close(profile_tgt_fd);
2332 	free(profile_tgt_name);
2333 	return err;
2334 }
2335 
2336 #endif /* BPFTOOL_WITHOUT_SKELETONS */
2337 
2338 static int do_help(int argc, char **argv)
2339 {
2340 	if (json_output) {
2341 		jsonw_null(json_wtr);
2342 		return 0;
2343 	}
2344 
2345 	fprintf(stderr,
2346 		"Usage: %1$s %2$s { show | list } [PROG]\n"
2347 		"       %1$s %2$s dump xlated PROG [{ file FILE | opcodes | visual | linum }]\n"
2348 		"       %1$s %2$s dump jited  PROG [{ file FILE | opcodes | linum }]\n"
2349 		"       %1$s %2$s pin   PROG FILE\n"
2350 		"       %1$s %2$s { load | loadall } OBJ  PATH \\\n"
2351 		"                         [type TYPE] [dev NAME] \\\n"
2352 		"                         [map { idx IDX | name NAME } MAP]\\\n"
2353 		"                         [pinmaps MAP_DIR]\n"
2354 		"       %1$s %2$s attach PROG ATTACH_TYPE [MAP]\n"
2355 		"       %1$s %2$s detach PROG ATTACH_TYPE [MAP]\n"
2356 		"       %1$s %2$s run PROG \\\n"
2357 		"                         data_in FILE \\\n"
2358 		"                         [data_out FILE [data_size_out L]] \\\n"
2359 		"                         [ctx_in FILE [ctx_out FILE [ctx_size_out M]]] \\\n"
2360 		"                         [repeat N]\n"
2361 		"       %1$s %2$s profile PROG [duration DURATION] METRICs\n"
2362 		"       %1$s %2$s tracelog\n"
2363 		"       %1$s %2$s help\n"
2364 		"\n"
2365 		"       " HELP_SPEC_MAP "\n"
2366 		"       " HELP_SPEC_PROGRAM "\n"
2367 		"       TYPE := { socket | kprobe | kretprobe | classifier | action |\n"
2368 		"                 tracepoint | raw_tracepoint | xdp | perf_event | cgroup/skb |\n"
2369 		"                 cgroup/sock | cgroup/dev | lwt_in | lwt_out | lwt_xmit |\n"
2370 		"                 lwt_seg6local | sockops | sk_skb | sk_msg | lirc_mode2 |\n"
2371 		"                 sk_reuseport | flow_dissector | cgroup/sysctl |\n"
2372 		"                 cgroup/bind4 | cgroup/bind6 | cgroup/post_bind4 |\n"
2373 		"                 cgroup/post_bind6 | cgroup/connect4 | cgroup/connect6 |\n"
2374 		"                 cgroup/getpeername4 | cgroup/getpeername6 |\n"
2375 		"                 cgroup/getsockname4 | cgroup/getsockname6 | cgroup/sendmsg4 |\n"
2376 		"                 cgroup/sendmsg6 | cgroup/recvmsg4 | cgroup/recvmsg6 |\n"
2377 		"                 cgroup/getsockopt | cgroup/setsockopt | cgroup/sock_release |\n"
2378 		"                 struct_ops | fentry | fexit | freplace | sk_lookup }\n"
2379 		"       ATTACH_TYPE := { msg_verdict | skb_verdict | stream_verdict |\n"
2380 		"                        stream_parser | flow_dissector }\n"
2381 		"       METRIC := { cycles | instructions | l1d_loads | llc_misses | itlb_misses | dtlb_misses }\n"
2382 		"       " HELP_SPEC_OPTIONS " |\n"
2383 		"                    {-f|--bpffs} | {-m|--mapcompat} | {-n|--nomount} |\n"
2384 		"                    {-L|--use-loader} }\n"
2385 		"",
2386 		bin_name, argv[-2]);
2387 
2388 	return 0;
2389 }
2390 
2391 static const struct cmd cmds[] = {
2392 	{ "show",	do_show },
2393 	{ "list",	do_show },
2394 	{ "help",	do_help },
2395 	{ "dump",	do_dump },
2396 	{ "pin",	do_pin },
2397 	{ "load",	do_load },
2398 	{ "loadall",	do_loadall },
2399 	{ "attach",	do_attach },
2400 	{ "detach",	do_detach },
2401 	{ "tracelog",	do_tracelog },
2402 	{ "run",	do_run },
2403 	{ "profile",	do_profile },
2404 	{ 0 }
2405 };
2406 
2407 int do_prog(int argc, char **argv)
2408 {
2409 	return cmd_select(cmds, argc, argv, do_help);
2410 }
2411