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