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