xref: /openbmc/linux/tools/bpf/bpftool/prog.c (revision 97e6ea6d)
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 	unsigned int i, vlen;
253 	void *value = NULL;
254 	const char *name;
255 	struct btf *btf;
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 	btf = btf__load_from_kernel_by_id(map_info.btf_id);
267 	if (libbpf_get_error(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) {
650 		btf = btf__load_from_kernel_by_id(info->btf_id);
651 		if (libbpf_get_error(btf)) {
652 			p_err("failed to get btf");
653 			return -1;
654 		}
655 	}
656 
657 	func_info = u64_to_ptr(info->func_info);
658 
659 	if (info->nr_line_info) {
660 		prog_linfo = bpf_prog_linfo__new(info);
661 		if (!prog_linfo)
662 			p_info("error in processing bpf_line_info.  continue without it.");
663 	}
664 
665 	if (filepath) {
666 		fd = open(filepath, O_WRONLY | O_CREAT | O_TRUNC, 0600);
667 		if (fd < 0) {
668 			p_err("can't open file %s: %s", filepath,
669 			      strerror(errno));
670 			return -1;
671 		}
672 
673 		n = write(fd, buf, member_len);
674 		close(fd);
675 		if (n != (ssize_t)member_len) {
676 			p_err("error writing output file: %s",
677 			      n < 0 ? strerror(errno) : "short write");
678 			return -1;
679 		}
680 
681 		if (json_output)
682 			jsonw_null(json_wtr);
683 	} else if (mode == DUMP_JITED) {
684 		const char *name = NULL;
685 
686 		if (info->ifindex) {
687 			name = ifindex_to_bfd_params(info->ifindex,
688 						     info->netns_dev,
689 						     info->netns_ino,
690 						     &disasm_opt);
691 			if (!name)
692 				return -1;
693 		}
694 
695 		if (info->nr_jited_func_lens && info->jited_func_lens) {
696 			struct kernel_sym *sym = NULL;
697 			struct bpf_func_info *record;
698 			char sym_name[SYM_MAX_NAME];
699 			unsigned char *img = buf;
700 			__u64 *ksyms = NULL;
701 			__u32 *lens;
702 			__u32 i;
703 			if (info->nr_jited_ksyms) {
704 				kernel_syms_load(&dd);
705 				ksyms = u64_to_ptr(info->jited_ksyms);
706 			}
707 
708 			if (json_output)
709 				jsonw_start_array(json_wtr);
710 
711 			lens = u64_to_ptr(info->jited_func_lens);
712 			for (i = 0; i < info->nr_jited_func_lens; i++) {
713 				if (ksyms) {
714 					sym = kernel_syms_search(&dd, ksyms[i]);
715 					if (sym)
716 						sprintf(sym_name, "%s", sym->name);
717 					else
718 						sprintf(sym_name, "0x%016llx", ksyms[i]);
719 				} else {
720 					strcpy(sym_name, "unknown");
721 				}
722 
723 				if (func_info) {
724 					record = func_info + i * info->func_info_rec_size;
725 					btf_dumper_type_only(btf, record->type_id,
726 							     func_sig,
727 							     sizeof(func_sig));
728 				}
729 
730 				if (json_output) {
731 					jsonw_start_object(json_wtr);
732 					if (func_info && func_sig[0] != '\0') {
733 						jsonw_name(json_wtr, "proto");
734 						jsonw_string(json_wtr, func_sig);
735 					}
736 					jsonw_name(json_wtr, "name");
737 					jsonw_string(json_wtr, sym_name);
738 					jsonw_name(json_wtr, "insns");
739 				} else {
740 					if (func_info && func_sig[0] != '\0')
741 						printf("%s:\n", func_sig);
742 					printf("%s:\n", sym_name);
743 				}
744 
745 				disasm_print_insn(img, lens[i], opcodes,
746 						  name, disasm_opt, btf,
747 						  prog_linfo, ksyms[i], i,
748 						  linum);
749 
750 				img += lens[i];
751 
752 				if (json_output)
753 					jsonw_end_object(json_wtr);
754 				else
755 					printf("\n");
756 			}
757 
758 			if (json_output)
759 				jsonw_end_array(json_wtr);
760 		} else {
761 			disasm_print_insn(buf, member_len, opcodes, name,
762 					  disasm_opt, btf, NULL, 0, 0, false);
763 		}
764 	} else if (visual) {
765 		if (json_output)
766 			jsonw_null(json_wtr);
767 		else
768 			dump_xlated_cfg(buf, member_len);
769 	} else {
770 		kernel_syms_load(&dd);
771 		dd.nr_jited_ksyms = info->nr_jited_ksyms;
772 		dd.jited_ksyms = u64_to_ptr(info->jited_ksyms);
773 		dd.btf = btf;
774 		dd.func_info = func_info;
775 		dd.finfo_rec_size = info->func_info_rec_size;
776 		dd.prog_linfo = prog_linfo;
777 
778 		if (json_output)
779 			dump_xlated_json(&dd, buf, member_len, opcodes,
780 					 linum);
781 		else
782 			dump_xlated_plain(&dd, buf, member_len, opcodes,
783 					  linum);
784 		kernel_syms_destroy(&dd);
785 	}
786 
787 	btf__free(btf);
788 
789 	return 0;
790 }
791 
792 static int do_dump(int argc, char **argv)
793 {
794 	struct bpf_prog_info_linear *info_linear;
795 	char *filepath = NULL;
796 	bool opcodes = false;
797 	bool visual = false;
798 	enum dump_mode mode;
799 	bool linum = false;
800 	int *fds = NULL;
801 	int nb_fds, i = 0;
802 	int err = -1;
803 	__u64 arrays;
804 
805 	if (is_prefix(*argv, "jited")) {
806 		if (disasm_init())
807 			return -1;
808 		mode = DUMP_JITED;
809 	} else if (is_prefix(*argv, "xlated")) {
810 		mode = DUMP_XLATED;
811 	} else {
812 		p_err("expected 'xlated' or 'jited', got: %s", *argv);
813 		return -1;
814 	}
815 	NEXT_ARG();
816 
817 	if (argc < 2)
818 		usage();
819 
820 	fds = malloc(sizeof(int));
821 	if (!fds) {
822 		p_err("mem alloc failed");
823 		return -1;
824 	}
825 	nb_fds = prog_parse_fds(&argc, &argv, &fds);
826 	if (nb_fds < 1)
827 		goto exit_free;
828 
829 	if (is_prefix(*argv, "file")) {
830 		NEXT_ARG();
831 		if (!argc) {
832 			p_err("expected file path");
833 			goto exit_close;
834 		}
835 		if (nb_fds > 1) {
836 			p_err("several programs matched");
837 			goto exit_close;
838 		}
839 
840 		filepath = *argv;
841 		NEXT_ARG();
842 	} else if (is_prefix(*argv, "opcodes")) {
843 		opcodes = true;
844 		NEXT_ARG();
845 	} else if (is_prefix(*argv, "visual")) {
846 		if (nb_fds > 1) {
847 			p_err("several programs matched");
848 			goto exit_close;
849 		}
850 
851 		visual = true;
852 		NEXT_ARG();
853 	} else if (is_prefix(*argv, "linum")) {
854 		linum = true;
855 		NEXT_ARG();
856 	}
857 
858 	if (argc) {
859 		usage();
860 		goto exit_close;
861 	}
862 
863 	if (mode == DUMP_JITED)
864 		arrays = 1UL << BPF_PROG_INFO_JITED_INSNS;
865 	else
866 		arrays = 1UL << BPF_PROG_INFO_XLATED_INSNS;
867 
868 	arrays |= 1UL << BPF_PROG_INFO_JITED_KSYMS;
869 	arrays |= 1UL << BPF_PROG_INFO_JITED_FUNC_LENS;
870 	arrays |= 1UL << BPF_PROG_INFO_FUNC_INFO;
871 	arrays |= 1UL << BPF_PROG_INFO_LINE_INFO;
872 	arrays |= 1UL << BPF_PROG_INFO_JITED_LINE_INFO;
873 
874 	if (json_output && nb_fds > 1)
875 		jsonw_start_array(json_wtr);	/* root array */
876 	for (i = 0; i < nb_fds; i++) {
877 		info_linear = bpf_program__get_prog_info_linear(fds[i], arrays);
878 		if (IS_ERR_OR_NULL(info_linear)) {
879 			p_err("can't get prog info: %s", strerror(errno));
880 			break;
881 		}
882 
883 		if (json_output && nb_fds > 1) {
884 			jsonw_start_object(json_wtr);	/* prog object */
885 			print_prog_header_json(&info_linear->info);
886 			jsonw_name(json_wtr, "insns");
887 		} else if (nb_fds > 1) {
888 			print_prog_header_plain(&info_linear->info);
889 		}
890 
891 		err = prog_dump(&info_linear->info, mode, filepath, opcodes,
892 				visual, linum);
893 
894 		if (json_output && nb_fds > 1)
895 			jsonw_end_object(json_wtr);	/* prog object */
896 		else if (i != nb_fds - 1 && nb_fds > 1)
897 			printf("\n");
898 
899 		free(info_linear);
900 		if (err)
901 			break;
902 		close(fds[i]);
903 	}
904 	if (json_output && nb_fds > 1)
905 		jsonw_end_array(json_wtr);	/* root array */
906 
907 exit_close:
908 	for (; i < nb_fds; i++)
909 		close(fds[i]);
910 exit_free:
911 	free(fds);
912 	return err;
913 }
914 
915 static int do_pin(int argc, char **argv)
916 {
917 	int err;
918 
919 	err = do_pin_any(argc, argv, prog_parse_fd);
920 	if (!err && json_output)
921 		jsonw_null(json_wtr);
922 	return err;
923 }
924 
925 struct map_replace {
926 	int idx;
927 	int fd;
928 	char *name;
929 };
930 
931 static int map_replace_compar(const void *p1, const void *p2)
932 {
933 	const struct map_replace *a = p1, *b = p2;
934 
935 	return a->idx - b->idx;
936 }
937 
938 static int parse_attach_detach_args(int argc, char **argv, int *progfd,
939 				    enum bpf_attach_type *attach_type,
940 				    int *mapfd)
941 {
942 	if (!REQ_ARGS(3))
943 		return -EINVAL;
944 
945 	*progfd = prog_parse_fd(&argc, &argv);
946 	if (*progfd < 0)
947 		return *progfd;
948 
949 	*attach_type = parse_attach_type(*argv);
950 	if (*attach_type == __MAX_BPF_ATTACH_TYPE) {
951 		p_err("invalid attach/detach type");
952 		return -EINVAL;
953 	}
954 
955 	if (*attach_type == BPF_FLOW_DISSECTOR) {
956 		*mapfd = 0;
957 		return 0;
958 	}
959 
960 	NEXT_ARG();
961 	if (!REQ_ARGS(2))
962 		return -EINVAL;
963 
964 	*mapfd = map_parse_fd(&argc, &argv);
965 	if (*mapfd < 0)
966 		return *mapfd;
967 
968 	return 0;
969 }
970 
971 static int do_attach(int argc, char **argv)
972 {
973 	enum bpf_attach_type attach_type;
974 	int err, progfd;
975 	int mapfd;
976 
977 	err = parse_attach_detach_args(argc, argv,
978 				       &progfd, &attach_type, &mapfd);
979 	if (err)
980 		return err;
981 
982 	err = bpf_prog_attach(progfd, mapfd, attach_type, 0);
983 	if (err) {
984 		p_err("failed prog attach to map");
985 		return -EINVAL;
986 	}
987 
988 	if (json_output)
989 		jsonw_null(json_wtr);
990 	return 0;
991 }
992 
993 static int do_detach(int argc, char **argv)
994 {
995 	enum bpf_attach_type attach_type;
996 	int err, progfd;
997 	int mapfd;
998 
999 	err = parse_attach_detach_args(argc, argv,
1000 				       &progfd, &attach_type, &mapfd);
1001 	if (err)
1002 		return err;
1003 
1004 	err = bpf_prog_detach2(progfd, mapfd, attach_type);
1005 	if (err) {
1006 		p_err("failed prog detach from map");
1007 		return -EINVAL;
1008 	}
1009 
1010 	if (json_output)
1011 		jsonw_null(json_wtr);
1012 	return 0;
1013 }
1014 
1015 static int check_single_stdin(char *file_data_in, char *file_ctx_in)
1016 {
1017 	if (file_data_in && file_ctx_in &&
1018 	    !strcmp(file_data_in, "-") && !strcmp(file_ctx_in, "-")) {
1019 		p_err("cannot use standard input for both data_in and ctx_in");
1020 		return -1;
1021 	}
1022 
1023 	return 0;
1024 }
1025 
1026 static int get_run_data(const char *fname, void **data_ptr, unsigned int *size)
1027 {
1028 	size_t block_size = 256;
1029 	size_t buf_size = block_size;
1030 	size_t nb_read = 0;
1031 	void *tmp;
1032 	FILE *f;
1033 
1034 	if (!fname) {
1035 		*data_ptr = NULL;
1036 		*size = 0;
1037 		return 0;
1038 	}
1039 
1040 	if (!strcmp(fname, "-"))
1041 		f = stdin;
1042 	else
1043 		f = fopen(fname, "r");
1044 	if (!f) {
1045 		p_err("failed to open %s: %s", fname, strerror(errno));
1046 		return -1;
1047 	}
1048 
1049 	*data_ptr = malloc(block_size);
1050 	if (!*data_ptr) {
1051 		p_err("failed to allocate memory for data_in/ctx_in: %s",
1052 		      strerror(errno));
1053 		goto err_fclose;
1054 	}
1055 
1056 	while ((nb_read += fread(*data_ptr + nb_read, 1, block_size, f))) {
1057 		if (feof(f))
1058 			break;
1059 		if (ferror(f)) {
1060 			p_err("failed to read data_in/ctx_in from %s: %s",
1061 			      fname, strerror(errno));
1062 			goto err_free;
1063 		}
1064 		if (nb_read > buf_size - block_size) {
1065 			if (buf_size == UINT32_MAX) {
1066 				p_err("data_in/ctx_in is too long (max: %d)",
1067 				      UINT32_MAX);
1068 				goto err_free;
1069 			}
1070 			/* No space for fread()-ing next chunk; realloc() */
1071 			buf_size *= 2;
1072 			tmp = realloc(*data_ptr, buf_size);
1073 			if (!tmp) {
1074 				p_err("failed to reallocate data_in/ctx_in: %s",
1075 				      strerror(errno));
1076 				goto err_free;
1077 			}
1078 			*data_ptr = tmp;
1079 		}
1080 	}
1081 	if (f != stdin)
1082 		fclose(f);
1083 
1084 	*size = nb_read;
1085 	return 0;
1086 
1087 err_free:
1088 	free(*data_ptr);
1089 	*data_ptr = NULL;
1090 err_fclose:
1091 	if (f != stdin)
1092 		fclose(f);
1093 	return -1;
1094 }
1095 
1096 static void hex_print(void *data, unsigned int size, FILE *f)
1097 {
1098 	size_t i, j;
1099 	char c;
1100 
1101 	for (i = 0; i < size; i += 16) {
1102 		/* Row offset */
1103 		fprintf(f, "%07zx\t", i);
1104 
1105 		/* Hexadecimal values */
1106 		for (j = i; j < i + 16 && j < size; j++)
1107 			fprintf(f, "%02x%s", *(uint8_t *)(data + j),
1108 				j % 2 ? " " : "");
1109 		for (; j < i + 16; j++)
1110 			fprintf(f, "  %s", j % 2 ? " " : "");
1111 
1112 		/* ASCII values (if relevant), '.' otherwise */
1113 		fprintf(f, "| ");
1114 		for (j = i; j < i + 16 && j < size; j++) {
1115 			c = *(char *)(data + j);
1116 			if (c < ' ' || c > '~')
1117 				c = '.';
1118 			fprintf(f, "%c%s", c, j == i + 7 ? " " : "");
1119 		}
1120 
1121 		fprintf(f, "\n");
1122 	}
1123 }
1124 
1125 static int
1126 print_run_output(void *data, unsigned int size, const char *fname,
1127 		 const char *json_key)
1128 {
1129 	size_t nb_written;
1130 	FILE *f;
1131 
1132 	if (!fname)
1133 		return 0;
1134 
1135 	if (!strcmp(fname, "-")) {
1136 		f = stdout;
1137 		if (json_output) {
1138 			jsonw_name(json_wtr, json_key);
1139 			print_data_json(data, size);
1140 		} else {
1141 			hex_print(data, size, f);
1142 		}
1143 		return 0;
1144 	}
1145 
1146 	f = fopen(fname, "w");
1147 	if (!f) {
1148 		p_err("failed to open %s: %s", fname, strerror(errno));
1149 		return -1;
1150 	}
1151 
1152 	nb_written = fwrite(data, 1, size, f);
1153 	fclose(f);
1154 	if (nb_written != size) {
1155 		p_err("failed to write output data/ctx: %s", strerror(errno));
1156 		return -1;
1157 	}
1158 
1159 	return 0;
1160 }
1161 
1162 static int alloc_run_data(void **data_ptr, unsigned int size_out)
1163 {
1164 	*data_ptr = calloc(size_out, 1);
1165 	if (!*data_ptr) {
1166 		p_err("failed to allocate memory for output data/ctx: %s",
1167 		      strerror(errno));
1168 		return -1;
1169 	}
1170 
1171 	return 0;
1172 }
1173 
1174 static int do_run(int argc, char **argv)
1175 {
1176 	char *data_fname_in = NULL, *data_fname_out = NULL;
1177 	char *ctx_fname_in = NULL, *ctx_fname_out = NULL;
1178 	struct bpf_prog_test_run_attr test_attr = {0};
1179 	const unsigned int default_size = SZ_32K;
1180 	void *data_in = NULL, *data_out = NULL;
1181 	void *ctx_in = NULL, *ctx_out = NULL;
1182 	unsigned int repeat = 1;
1183 	int fd, err;
1184 
1185 	if (!REQ_ARGS(4))
1186 		return -1;
1187 
1188 	fd = prog_parse_fd(&argc, &argv);
1189 	if (fd < 0)
1190 		return -1;
1191 
1192 	while (argc) {
1193 		if (detect_common_prefix(*argv, "data_in", "data_out",
1194 					 "data_size_out", NULL))
1195 			return -1;
1196 		if (detect_common_prefix(*argv, "ctx_in", "ctx_out",
1197 					 "ctx_size_out", NULL))
1198 			return -1;
1199 
1200 		if (is_prefix(*argv, "data_in")) {
1201 			NEXT_ARG();
1202 			if (!REQ_ARGS(1))
1203 				return -1;
1204 
1205 			data_fname_in = GET_ARG();
1206 			if (check_single_stdin(data_fname_in, ctx_fname_in))
1207 				return -1;
1208 		} else if (is_prefix(*argv, "data_out")) {
1209 			NEXT_ARG();
1210 			if (!REQ_ARGS(1))
1211 				return -1;
1212 
1213 			data_fname_out = GET_ARG();
1214 		} else if (is_prefix(*argv, "data_size_out")) {
1215 			char *endptr;
1216 
1217 			NEXT_ARG();
1218 			if (!REQ_ARGS(1))
1219 				return -1;
1220 
1221 			test_attr.data_size_out = strtoul(*argv, &endptr, 0);
1222 			if (*endptr) {
1223 				p_err("can't parse %s as output data size",
1224 				      *argv);
1225 				return -1;
1226 			}
1227 			NEXT_ARG();
1228 		} else if (is_prefix(*argv, "ctx_in")) {
1229 			NEXT_ARG();
1230 			if (!REQ_ARGS(1))
1231 				return -1;
1232 
1233 			ctx_fname_in = GET_ARG();
1234 			if (check_single_stdin(data_fname_in, ctx_fname_in))
1235 				return -1;
1236 		} else if (is_prefix(*argv, "ctx_out")) {
1237 			NEXT_ARG();
1238 			if (!REQ_ARGS(1))
1239 				return -1;
1240 
1241 			ctx_fname_out = GET_ARG();
1242 		} else if (is_prefix(*argv, "ctx_size_out")) {
1243 			char *endptr;
1244 
1245 			NEXT_ARG();
1246 			if (!REQ_ARGS(1))
1247 				return -1;
1248 
1249 			test_attr.ctx_size_out = strtoul(*argv, &endptr, 0);
1250 			if (*endptr) {
1251 				p_err("can't parse %s as output context size",
1252 				      *argv);
1253 				return -1;
1254 			}
1255 			NEXT_ARG();
1256 		} else if (is_prefix(*argv, "repeat")) {
1257 			char *endptr;
1258 
1259 			NEXT_ARG();
1260 			if (!REQ_ARGS(1))
1261 				return -1;
1262 
1263 			repeat = strtoul(*argv, &endptr, 0);
1264 			if (*endptr) {
1265 				p_err("can't parse %s as repeat number",
1266 				      *argv);
1267 				return -1;
1268 			}
1269 			NEXT_ARG();
1270 		} else {
1271 			p_err("expected no more arguments, 'data_in', 'data_out', 'data_size_out', 'ctx_in', 'ctx_out', 'ctx_size_out' or 'repeat', got: '%s'?",
1272 			      *argv);
1273 			return -1;
1274 		}
1275 	}
1276 
1277 	err = get_run_data(data_fname_in, &data_in, &test_attr.data_size_in);
1278 	if (err)
1279 		return -1;
1280 
1281 	if (data_in) {
1282 		if (!test_attr.data_size_out)
1283 			test_attr.data_size_out = default_size;
1284 		err = alloc_run_data(&data_out, test_attr.data_size_out);
1285 		if (err)
1286 			goto free_data_in;
1287 	}
1288 
1289 	err = get_run_data(ctx_fname_in, &ctx_in, &test_attr.ctx_size_in);
1290 	if (err)
1291 		goto free_data_out;
1292 
1293 	if (ctx_in) {
1294 		if (!test_attr.ctx_size_out)
1295 			test_attr.ctx_size_out = default_size;
1296 		err = alloc_run_data(&ctx_out, test_attr.ctx_size_out);
1297 		if (err)
1298 			goto free_ctx_in;
1299 	}
1300 
1301 	test_attr.prog_fd	= fd;
1302 	test_attr.repeat	= repeat;
1303 	test_attr.data_in	= data_in;
1304 	test_attr.data_out	= data_out;
1305 	test_attr.ctx_in	= ctx_in;
1306 	test_attr.ctx_out	= ctx_out;
1307 
1308 	err = bpf_prog_test_run_xattr(&test_attr);
1309 	if (err) {
1310 		p_err("failed to run program: %s", strerror(errno));
1311 		goto free_ctx_out;
1312 	}
1313 
1314 	err = 0;
1315 
1316 	if (json_output)
1317 		jsonw_start_object(json_wtr);	/* root */
1318 
1319 	/* Do not exit on errors occurring when printing output data/context,
1320 	 * we still want to print return value and duration for program run.
1321 	 */
1322 	if (test_attr.data_size_out)
1323 		err += print_run_output(test_attr.data_out,
1324 					test_attr.data_size_out,
1325 					data_fname_out, "data_out");
1326 	if (test_attr.ctx_size_out)
1327 		err += print_run_output(test_attr.ctx_out,
1328 					test_attr.ctx_size_out,
1329 					ctx_fname_out, "ctx_out");
1330 
1331 	if (json_output) {
1332 		jsonw_uint_field(json_wtr, "retval", test_attr.retval);
1333 		jsonw_uint_field(json_wtr, "duration", test_attr.duration);
1334 		jsonw_end_object(json_wtr);	/* root */
1335 	} else {
1336 		fprintf(stdout, "Return value: %u, duration%s: %uns\n",
1337 			test_attr.retval,
1338 			repeat > 1 ? " (average)" : "", test_attr.duration);
1339 	}
1340 
1341 free_ctx_out:
1342 	free(ctx_out);
1343 free_ctx_in:
1344 	free(ctx_in);
1345 free_data_out:
1346 	free(data_out);
1347 free_data_in:
1348 	free(data_in);
1349 
1350 	return err;
1351 }
1352 
1353 static int
1354 get_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
1355 		      enum bpf_attach_type *expected_attach_type)
1356 {
1357 	libbpf_print_fn_t print_backup;
1358 	int ret;
1359 
1360 	ret = libbpf_prog_type_by_name(name, prog_type, expected_attach_type);
1361 	if (!ret)
1362 		return ret;
1363 
1364 	/* libbpf_prog_type_by_name() failed, let's re-run with debug level */
1365 	print_backup = libbpf_set_print(print_all_levels);
1366 	ret = libbpf_prog_type_by_name(name, prog_type, expected_attach_type);
1367 	libbpf_set_print(print_backup);
1368 
1369 	return ret;
1370 }
1371 
1372 static int load_with_options(int argc, char **argv, bool first_prog_only)
1373 {
1374 	enum bpf_prog_type common_prog_type = BPF_PROG_TYPE_UNSPEC;
1375 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, open_opts,
1376 		.relaxed_maps = relaxed_maps,
1377 	);
1378 	struct bpf_object_load_attr load_attr = { 0 };
1379 	enum bpf_attach_type expected_attach_type;
1380 	struct map_replace *map_replace = NULL;
1381 	struct bpf_program *prog = NULL, *pos;
1382 	unsigned int old_map_fds = 0;
1383 	const char *pinmaps = NULL;
1384 	struct bpf_object *obj;
1385 	struct bpf_map *map;
1386 	const char *pinfile;
1387 	unsigned int i, j;
1388 	__u32 ifindex = 0;
1389 	const char *file;
1390 	int idx, err;
1391 
1392 
1393 	if (!REQ_ARGS(2))
1394 		return -1;
1395 	file = GET_ARG();
1396 	pinfile = GET_ARG();
1397 
1398 	while (argc) {
1399 		if (is_prefix(*argv, "type")) {
1400 			char *type;
1401 
1402 			NEXT_ARG();
1403 
1404 			if (common_prog_type != BPF_PROG_TYPE_UNSPEC) {
1405 				p_err("program type already specified");
1406 				goto err_free_reuse_maps;
1407 			}
1408 			if (!REQ_ARGS(1))
1409 				goto err_free_reuse_maps;
1410 
1411 			/* Put a '/' at the end of type to appease libbpf */
1412 			type = malloc(strlen(*argv) + 2);
1413 			if (!type) {
1414 				p_err("mem alloc failed");
1415 				goto err_free_reuse_maps;
1416 			}
1417 			*type = 0;
1418 			strcat(type, *argv);
1419 			strcat(type, "/");
1420 
1421 			err = get_prog_type_by_name(type, &common_prog_type,
1422 						    &expected_attach_type);
1423 			free(type);
1424 			if (err < 0)
1425 				goto err_free_reuse_maps;
1426 
1427 			NEXT_ARG();
1428 		} else if (is_prefix(*argv, "map")) {
1429 			void *new_map_replace;
1430 			char *endptr, *name;
1431 			int fd;
1432 
1433 			NEXT_ARG();
1434 
1435 			if (!REQ_ARGS(4))
1436 				goto err_free_reuse_maps;
1437 
1438 			if (is_prefix(*argv, "idx")) {
1439 				NEXT_ARG();
1440 
1441 				idx = strtoul(*argv, &endptr, 0);
1442 				if (*endptr) {
1443 					p_err("can't parse %s as IDX", *argv);
1444 					goto err_free_reuse_maps;
1445 				}
1446 				name = NULL;
1447 			} else if (is_prefix(*argv, "name")) {
1448 				NEXT_ARG();
1449 
1450 				name = *argv;
1451 				idx = -1;
1452 			} else {
1453 				p_err("expected 'idx' or 'name', got: '%s'?",
1454 				      *argv);
1455 				goto err_free_reuse_maps;
1456 			}
1457 			NEXT_ARG();
1458 
1459 			fd = map_parse_fd(&argc, &argv);
1460 			if (fd < 0)
1461 				goto err_free_reuse_maps;
1462 
1463 			new_map_replace = reallocarray(map_replace,
1464 						       old_map_fds + 1,
1465 						       sizeof(*map_replace));
1466 			if (!new_map_replace) {
1467 				p_err("mem alloc failed");
1468 				goto err_free_reuse_maps;
1469 			}
1470 			map_replace = new_map_replace;
1471 
1472 			map_replace[old_map_fds].idx = idx;
1473 			map_replace[old_map_fds].name = name;
1474 			map_replace[old_map_fds].fd = fd;
1475 			old_map_fds++;
1476 		} else if (is_prefix(*argv, "dev")) {
1477 			NEXT_ARG();
1478 
1479 			if (ifindex) {
1480 				p_err("offload device already specified");
1481 				goto err_free_reuse_maps;
1482 			}
1483 			if (!REQ_ARGS(1))
1484 				goto err_free_reuse_maps;
1485 
1486 			ifindex = if_nametoindex(*argv);
1487 			if (!ifindex) {
1488 				p_err("unrecognized netdevice '%s': %s",
1489 				      *argv, strerror(errno));
1490 				goto err_free_reuse_maps;
1491 			}
1492 			NEXT_ARG();
1493 		} else if (is_prefix(*argv, "pinmaps")) {
1494 			NEXT_ARG();
1495 
1496 			if (!REQ_ARGS(1))
1497 				goto err_free_reuse_maps;
1498 
1499 			pinmaps = GET_ARG();
1500 		} else {
1501 			p_err("expected no more arguments, 'type', 'map' or 'dev', got: '%s'?",
1502 			      *argv);
1503 			goto err_free_reuse_maps;
1504 		}
1505 	}
1506 
1507 	set_max_rlimit();
1508 
1509 	obj = bpf_object__open_file(file, &open_opts);
1510 	if (libbpf_get_error(obj)) {
1511 		p_err("failed to open object file");
1512 		goto err_free_reuse_maps;
1513 	}
1514 
1515 	bpf_object__for_each_program(pos, obj) {
1516 		enum bpf_prog_type prog_type = common_prog_type;
1517 
1518 		if (prog_type == BPF_PROG_TYPE_UNSPEC) {
1519 			const char *sec_name = bpf_program__section_name(pos);
1520 
1521 			err = get_prog_type_by_name(sec_name, &prog_type,
1522 						    &expected_attach_type);
1523 			if (err < 0)
1524 				goto err_close_obj;
1525 		}
1526 
1527 		bpf_program__set_ifindex(pos, ifindex);
1528 		bpf_program__set_type(pos, prog_type);
1529 		bpf_program__set_expected_attach_type(pos, expected_attach_type);
1530 	}
1531 
1532 	qsort(map_replace, old_map_fds, sizeof(*map_replace),
1533 	      map_replace_compar);
1534 
1535 	/* After the sort maps by name will be first on the list, because they
1536 	 * have idx == -1.  Resolve them.
1537 	 */
1538 	j = 0;
1539 	while (j < old_map_fds && map_replace[j].name) {
1540 		i = 0;
1541 		bpf_object__for_each_map(map, obj) {
1542 			if (!strcmp(bpf_map__name(map), map_replace[j].name)) {
1543 				map_replace[j].idx = i;
1544 				break;
1545 			}
1546 			i++;
1547 		}
1548 		if (map_replace[j].idx == -1) {
1549 			p_err("unable to find map '%s'", map_replace[j].name);
1550 			goto err_close_obj;
1551 		}
1552 		j++;
1553 	}
1554 	/* Resort if any names were resolved */
1555 	if (j)
1556 		qsort(map_replace, old_map_fds, sizeof(*map_replace),
1557 		      map_replace_compar);
1558 
1559 	/* Set ifindex and name reuse */
1560 	j = 0;
1561 	idx = 0;
1562 	bpf_object__for_each_map(map, obj) {
1563 		if (!bpf_map__is_offload_neutral(map))
1564 			bpf_map__set_ifindex(map, ifindex);
1565 
1566 		if (j < old_map_fds && idx == map_replace[j].idx) {
1567 			err = bpf_map__reuse_fd(map, map_replace[j++].fd);
1568 			if (err) {
1569 				p_err("unable to set up map reuse: %d", err);
1570 				goto err_close_obj;
1571 			}
1572 
1573 			/* Next reuse wants to apply to the same map */
1574 			if (j < old_map_fds && map_replace[j].idx == idx) {
1575 				p_err("replacement for map idx %d specified more than once",
1576 				      idx);
1577 				goto err_close_obj;
1578 			}
1579 		}
1580 
1581 		idx++;
1582 	}
1583 	if (j < old_map_fds) {
1584 		p_err("map idx '%d' not used", map_replace[j].idx);
1585 		goto err_close_obj;
1586 	}
1587 
1588 	load_attr.obj = obj;
1589 	if (verifier_logs)
1590 		/* log_level1 + log_level2 + stats, but not stable UAPI */
1591 		load_attr.log_level = 1 + 2 + 4;
1592 
1593 	err = bpf_object__load_xattr(&load_attr);
1594 	if (err) {
1595 		p_err("failed to load object file");
1596 		goto err_close_obj;
1597 	}
1598 
1599 	err = mount_bpffs_for_pin(pinfile);
1600 	if (err)
1601 		goto err_close_obj;
1602 
1603 	if (first_prog_only) {
1604 		prog = bpf_program__next(NULL, obj);
1605 		if (!prog) {
1606 			p_err("object file doesn't contain any bpf program");
1607 			goto err_close_obj;
1608 		}
1609 
1610 		err = bpf_obj_pin(bpf_program__fd(prog), pinfile);
1611 		if (err) {
1612 			p_err("failed to pin program %s",
1613 			      bpf_program__section_name(prog));
1614 			goto err_close_obj;
1615 		}
1616 	} else {
1617 		err = bpf_object__pin_programs(obj, pinfile);
1618 		if (err) {
1619 			p_err("failed to pin all programs");
1620 			goto err_close_obj;
1621 		}
1622 	}
1623 
1624 	if (pinmaps) {
1625 		err = bpf_object__pin_maps(obj, pinmaps);
1626 		if (err) {
1627 			p_err("failed to pin all maps");
1628 			goto err_unpin;
1629 		}
1630 	}
1631 
1632 	if (json_output)
1633 		jsonw_null(json_wtr);
1634 
1635 	bpf_object__close(obj);
1636 	for (i = 0; i < old_map_fds; i++)
1637 		close(map_replace[i].fd);
1638 	free(map_replace);
1639 
1640 	return 0;
1641 
1642 err_unpin:
1643 	if (first_prog_only)
1644 		unlink(pinfile);
1645 	else
1646 		bpf_object__unpin_programs(obj, pinfile);
1647 err_close_obj:
1648 	bpf_object__close(obj);
1649 err_free_reuse_maps:
1650 	for (i = 0; i < old_map_fds; i++)
1651 		close(map_replace[i].fd);
1652 	free(map_replace);
1653 	return -1;
1654 }
1655 
1656 static int count_open_fds(void)
1657 {
1658 	DIR *dp = opendir("/proc/self/fd");
1659 	struct dirent *de;
1660 	int cnt = -3;
1661 
1662 	if (!dp)
1663 		return -1;
1664 
1665 	while ((de = readdir(dp)))
1666 		cnt++;
1667 
1668 	closedir(dp);
1669 	return cnt;
1670 }
1671 
1672 static int try_loader(struct gen_loader_opts *gen)
1673 {
1674 	struct bpf_load_and_run_opts opts = {};
1675 	struct bpf_loader_ctx *ctx;
1676 	int ctx_sz = sizeof(*ctx) + 64 * max(sizeof(struct bpf_map_desc),
1677 					     sizeof(struct bpf_prog_desc));
1678 	int log_buf_sz = (1u << 24) - 1;
1679 	int err, fds_before, fd_delta;
1680 	char *log_buf;
1681 
1682 	ctx = alloca(ctx_sz);
1683 	memset(ctx, 0, ctx_sz);
1684 	ctx->sz = ctx_sz;
1685 	ctx->log_level = 1;
1686 	ctx->log_size = log_buf_sz;
1687 	log_buf = malloc(log_buf_sz);
1688 	if (!log_buf)
1689 		return -ENOMEM;
1690 	ctx->log_buf = (long) log_buf;
1691 	opts.ctx = ctx;
1692 	opts.data = gen->data;
1693 	opts.data_sz = gen->data_sz;
1694 	opts.insns = gen->insns;
1695 	opts.insns_sz = gen->insns_sz;
1696 	fds_before = count_open_fds();
1697 	err = bpf_load_and_run(&opts);
1698 	fd_delta = count_open_fds() - fds_before;
1699 	if (err < 0) {
1700 		fprintf(stderr, "err %d\n%s\n%s", err, opts.errstr, log_buf);
1701 		if (fd_delta)
1702 			fprintf(stderr, "loader prog leaked %d FDs\n",
1703 				fd_delta);
1704 	}
1705 	free(log_buf);
1706 	return err;
1707 }
1708 
1709 static int do_loader(int argc, char **argv)
1710 {
1711 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, open_opts);
1712 	DECLARE_LIBBPF_OPTS(gen_loader_opts, gen);
1713 	struct bpf_object_load_attr load_attr = {};
1714 	struct bpf_object *obj;
1715 	const char *file;
1716 	int err = 0;
1717 
1718 	if (!REQ_ARGS(1))
1719 		return -1;
1720 	file = GET_ARG();
1721 
1722 	obj = bpf_object__open_file(file, &open_opts);
1723 	if (libbpf_get_error(obj)) {
1724 		p_err("failed to open object file");
1725 		goto err_close_obj;
1726 	}
1727 
1728 	err = bpf_object__gen_loader(obj, &gen);
1729 	if (err)
1730 		goto err_close_obj;
1731 
1732 	load_attr.obj = obj;
1733 	if (verifier_logs)
1734 		/* log_level1 + log_level2 + stats, but not stable UAPI */
1735 		load_attr.log_level = 1 + 2 + 4;
1736 
1737 	err = bpf_object__load_xattr(&load_attr);
1738 	if (err) {
1739 		p_err("failed to load object file");
1740 		goto err_close_obj;
1741 	}
1742 
1743 	if (verifier_logs) {
1744 		struct dump_data dd = {};
1745 
1746 		kernel_syms_load(&dd);
1747 		dump_xlated_plain(&dd, (void *)gen.insns, gen.insns_sz, false, false);
1748 		kernel_syms_destroy(&dd);
1749 	}
1750 	err = try_loader(&gen);
1751 err_close_obj:
1752 	bpf_object__close(obj);
1753 	return err;
1754 }
1755 
1756 static int do_load(int argc, char **argv)
1757 {
1758 	if (use_loader)
1759 		return do_loader(argc, argv);
1760 	return load_with_options(argc, argv, true);
1761 }
1762 
1763 static int do_loadall(int argc, char **argv)
1764 {
1765 	return load_with_options(argc, argv, false);
1766 }
1767 
1768 #ifdef BPFTOOL_WITHOUT_SKELETONS
1769 
1770 static int do_profile(int argc, char **argv)
1771 {
1772 	p_err("bpftool prog profile command is not supported. Please build bpftool with clang >= 10.0.0");
1773 	return 0;
1774 }
1775 
1776 #else /* BPFTOOL_WITHOUT_SKELETONS */
1777 
1778 #include "profiler.skel.h"
1779 
1780 struct profile_metric {
1781 	const char *name;
1782 	struct bpf_perf_event_value val;
1783 	struct perf_event_attr attr;
1784 	bool selected;
1785 
1786 	/* calculate ratios like instructions per cycle */
1787 	const int ratio_metric; /* 0 for N/A, 1 for index 0 (cycles) */
1788 	const char *ratio_desc;
1789 	const float ratio_mul;
1790 } metrics[] = {
1791 	{
1792 		.name = "cycles",
1793 		.attr = {
1794 			.type = PERF_TYPE_HARDWARE,
1795 			.config = PERF_COUNT_HW_CPU_CYCLES,
1796 			.exclude_user = 1,
1797 		},
1798 	},
1799 	{
1800 		.name = "instructions",
1801 		.attr = {
1802 			.type = PERF_TYPE_HARDWARE,
1803 			.config = PERF_COUNT_HW_INSTRUCTIONS,
1804 			.exclude_user = 1,
1805 		},
1806 		.ratio_metric = 1,
1807 		.ratio_desc = "insns per cycle",
1808 		.ratio_mul = 1.0,
1809 	},
1810 	{
1811 		.name = "l1d_loads",
1812 		.attr = {
1813 			.type = PERF_TYPE_HW_CACHE,
1814 			.config =
1815 				PERF_COUNT_HW_CACHE_L1D |
1816 				(PERF_COUNT_HW_CACHE_OP_READ << 8) |
1817 				(PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16),
1818 			.exclude_user = 1,
1819 		},
1820 	},
1821 	{
1822 		.name = "llc_misses",
1823 		.attr = {
1824 			.type = PERF_TYPE_HW_CACHE,
1825 			.config =
1826 				PERF_COUNT_HW_CACHE_LL |
1827 				(PERF_COUNT_HW_CACHE_OP_READ << 8) |
1828 				(PERF_COUNT_HW_CACHE_RESULT_MISS << 16),
1829 			.exclude_user = 1
1830 		},
1831 		.ratio_metric = 2,
1832 		.ratio_desc = "LLC misses per million insns",
1833 		.ratio_mul = 1e6,
1834 	},
1835 	{
1836 		.name = "itlb_misses",
1837 		.attr = {
1838 			.type = PERF_TYPE_HW_CACHE,
1839 			.config =
1840 				PERF_COUNT_HW_CACHE_ITLB |
1841 				(PERF_COUNT_HW_CACHE_OP_READ << 8) |
1842 				(PERF_COUNT_HW_CACHE_RESULT_MISS << 16),
1843 			.exclude_user = 1
1844 		},
1845 		.ratio_metric = 2,
1846 		.ratio_desc = "itlb misses per million insns",
1847 		.ratio_mul = 1e6,
1848 	},
1849 	{
1850 		.name = "dtlb_misses",
1851 		.attr = {
1852 			.type = PERF_TYPE_HW_CACHE,
1853 			.config =
1854 				PERF_COUNT_HW_CACHE_DTLB |
1855 				(PERF_COUNT_HW_CACHE_OP_READ << 8) |
1856 				(PERF_COUNT_HW_CACHE_RESULT_MISS << 16),
1857 			.exclude_user = 1
1858 		},
1859 		.ratio_metric = 2,
1860 		.ratio_desc = "dtlb misses per million insns",
1861 		.ratio_mul = 1e6,
1862 	},
1863 };
1864 
1865 static __u64 profile_total_count;
1866 
1867 #define MAX_NUM_PROFILE_METRICS 4
1868 
1869 static int profile_parse_metrics(int argc, char **argv)
1870 {
1871 	unsigned int metric_cnt;
1872 	int selected_cnt = 0;
1873 	unsigned int i;
1874 
1875 	metric_cnt = sizeof(metrics) / sizeof(struct profile_metric);
1876 
1877 	while (argc > 0) {
1878 		for (i = 0; i < metric_cnt; i++) {
1879 			if (is_prefix(argv[0], metrics[i].name)) {
1880 				if (!metrics[i].selected)
1881 					selected_cnt++;
1882 				metrics[i].selected = true;
1883 				break;
1884 			}
1885 		}
1886 		if (i == metric_cnt) {
1887 			p_err("unknown metric %s", argv[0]);
1888 			return -1;
1889 		}
1890 		NEXT_ARG();
1891 	}
1892 	if (selected_cnt > MAX_NUM_PROFILE_METRICS) {
1893 		p_err("too many (%d) metrics, please specify no more than %d metrics at at time",
1894 		      selected_cnt, MAX_NUM_PROFILE_METRICS);
1895 		return -1;
1896 	}
1897 	return selected_cnt;
1898 }
1899 
1900 static void profile_read_values(struct profiler_bpf *obj)
1901 {
1902 	__u32 m, cpu, num_cpu = obj->rodata->num_cpu;
1903 	int reading_map_fd, count_map_fd;
1904 	__u64 counts[num_cpu];
1905 	__u32 key = 0;
1906 	int err;
1907 
1908 	reading_map_fd = bpf_map__fd(obj->maps.accum_readings);
1909 	count_map_fd = bpf_map__fd(obj->maps.counts);
1910 	if (reading_map_fd < 0 || count_map_fd < 0) {
1911 		p_err("failed to get fd for map");
1912 		return;
1913 	}
1914 
1915 	err = bpf_map_lookup_elem(count_map_fd, &key, counts);
1916 	if (err) {
1917 		p_err("failed to read count_map: %s", strerror(errno));
1918 		return;
1919 	}
1920 
1921 	profile_total_count = 0;
1922 	for (cpu = 0; cpu < num_cpu; cpu++)
1923 		profile_total_count += counts[cpu];
1924 
1925 	for (m = 0; m < ARRAY_SIZE(metrics); m++) {
1926 		struct bpf_perf_event_value values[num_cpu];
1927 
1928 		if (!metrics[m].selected)
1929 			continue;
1930 
1931 		err = bpf_map_lookup_elem(reading_map_fd, &key, values);
1932 		if (err) {
1933 			p_err("failed to read reading_map: %s",
1934 			      strerror(errno));
1935 			return;
1936 		}
1937 		for (cpu = 0; cpu < num_cpu; cpu++) {
1938 			metrics[m].val.counter += values[cpu].counter;
1939 			metrics[m].val.enabled += values[cpu].enabled;
1940 			metrics[m].val.running += values[cpu].running;
1941 		}
1942 		key++;
1943 	}
1944 }
1945 
1946 static void profile_print_readings_json(void)
1947 {
1948 	__u32 m;
1949 
1950 	jsonw_start_array(json_wtr);
1951 	for (m = 0; m < ARRAY_SIZE(metrics); m++) {
1952 		if (!metrics[m].selected)
1953 			continue;
1954 		jsonw_start_object(json_wtr);
1955 		jsonw_string_field(json_wtr, "metric", metrics[m].name);
1956 		jsonw_lluint_field(json_wtr, "run_cnt", profile_total_count);
1957 		jsonw_lluint_field(json_wtr, "value", metrics[m].val.counter);
1958 		jsonw_lluint_field(json_wtr, "enabled", metrics[m].val.enabled);
1959 		jsonw_lluint_field(json_wtr, "running", metrics[m].val.running);
1960 
1961 		jsonw_end_object(json_wtr);
1962 	}
1963 	jsonw_end_array(json_wtr);
1964 }
1965 
1966 static void profile_print_readings_plain(void)
1967 {
1968 	__u32 m;
1969 
1970 	printf("\n%18llu %-20s\n", profile_total_count, "run_cnt");
1971 	for (m = 0; m < ARRAY_SIZE(metrics); m++) {
1972 		struct bpf_perf_event_value *val = &metrics[m].val;
1973 		int r;
1974 
1975 		if (!metrics[m].selected)
1976 			continue;
1977 		printf("%18llu %-20s", val->counter, metrics[m].name);
1978 
1979 		r = metrics[m].ratio_metric - 1;
1980 		if (r >= 0 && metrics[r].selected &&
1981 		    metrics[r].val.counter > 0) {
1982 			printf("# %8.2f %-30s",
1983 			       val->counter * metrics[m].ratio_mul /
1984 			       metrics[r].val.counter,
1985 			       metrics[m].ratio_desc);
1986 		} else {
1987 			printf("%-41s", "");
1988 		}
1989 
1990 		if (val->enabled > val->running)
1991 			printf("(%4.2f%%)",
1992 			       val->running * 100.0 / val->enabled);
1993 		printf("\n");
1994 	}
1995 }
1996 
1997 static void profile_print_readings(void)
1998 {
1999 	if (json_output)
2000 		profile_print_readings_json();
2001 	else
2002 		profile_print_readings_plain();
2003 }
2004 
2005 static char *profile_target_name(int tgt_fd)
2006 {
2007 	struct bpf_prog_info_linear *info_linear;
2008 	struct bpf_func_info *func_info;
2009 	const struct btf_type *t;
2010 	struct btf *btf = NULL;
2011 	char *name = NULL;
2012 
2013 	info_linear = bpf_program__get_prog_info_linear(
2014 		tgt_fd, 1UL << BPF_PROG_INFO_FUNC_INFO);
2015 	if (IS_ERR_OR_NULL(info_linear)) {
2016 		p_err("failed to get info_linear for prog FD %d", tgt_fd);
2017 		return NULL;
2018 	}
2019 
2020 	if (info_linear->info.btf_id == 0) {
2021 		p_err("prog FD %d doesn't have valid btf", tgt_fd);
2022 		goto out;
2023 	}
2024 
2025 	btf = btf__load_from_kernel_by_id(info_linear->info.btf_id);
2026 	if (libbpf_get_error(btf)) {
2027 		p_err("failed to load btf for prog FD %d", tgt_fd);
2028 		goto out;
2029 	}
2030 
2031 	func_info = u64_to_ptr(info_linear->info.func_info);
2032 	t = btf__type_by_id(btf, func_info[0].type_id);
2033 	if (!t) {
2034 		p_err("btf %d doesn't have type %d",
2035 		      info_linear->info.btf_id, func_info[0].type_id);
2036 		goto out;
2037 	}
2038 	name = strdup(btf__name_by_offset(btf, t->name_off));
2039 out:
2040 	btf__free(btf);
2041 	free(info_linear);
2042 	return name;
2043 }
2044 
2045 static struct profiler_bpf *profile_obj;
2046 static int profile_tgt_fd = -1;
2047 static char *profile_tgt_name;
2048 static int *profile_perf_events;
2049 static int profile_perf_event_cnt;
2050 
2051 static void profile_close_perf_events(struct profiler_bpf *obj)
2052 {
2053 	int i;
2054 
2055 	for (i = profile_perf_event_cnt - 1; i >= 0; i--)
2056 		close(profile_perf_events[i]);
2057 
2058 	free(profile_perf_events);
2059 	profile_perf_event_cnt = 0;
2060 }
2061 
2062 static int profile_open_perf_events(struct profiler_bpf *obj)
2063 {
2064 	unsigned int cpu, m;
2065 	int map_fd, pmu_fd;
2066 
2067 	profile_perf_events = calloc(
2068 		sizeof(int), obj->rodata->num_cpu * obj->rodata->num_metric);
2069 	if (!profile_perf_events) {
2070 		p_err("failed to allocate memory for perf_event array: %s",
2071 		      strerror(errno));
2072 		return -1;
2073 	}
2074 	map_fd = bpf_map__fd(obj->maps.events);
2075 	if (map_fd < 0) {
2076 		p_err("failed to get fd for events map");
2077 		return -1;
2078 	}
2079 
2080 	for (m = 0; m < ARRAY_SIZE(metrics); m++) {
2081 		if (!metrics[m].selected)
2082 			continue;
2083 		for (cpu = 0; cpu < obj->rodata->num_cpu; cpu++) {
2084 			pmu_fd = syscall(__NR_perf_event_open, &metrics[m].attr,
2085 					 -1/*pid*/, cpu, -1/*group_fd*/, 0);
2086 			if (pmu_fd < 0 ||
2087 			    bpf_map_update_elem(map_fd, &profile_perf_event_cnt,
2088 						&pmu_fd, BPF_ANY) ||
2089 			    ioctl(pmu_fd, PERF_EVENT_IOC_ENABLE, 0)) {
2090 				p_err("failed to create event %s on cpu %d",
2091 				      metrics[m].name, cpu);
2092 				return -1;
2093 			}
2094 			profile_perf_events[profile_perf_event_cnt++] = pmu_fd;
2095 		}
2096 	}
2097 	return 0;
2098 }
2099 
2100 static void profile_print_and_cleanup(void)
2101 {
2102 	profile_close_perf_events(profile_obj);
2103 	profile_read_values(profile_obj);
2104 	profile_print_readings();
2105 	profiler_bpf__destroy(profile_obj);
2106 
2107 	close(profile_tgt_fd);
2108 	free(profile_tgt_name);
2109 }
2110 
2111 static void int_exit(int signo)
2112 {
2113 	profile_print_and_cleanup();
2114 	exit(0);
2115 }
2116 
2117 static int do_profile(int argc, char **argv)
2118 {
2119 	int num_metric, num_cpu, err = -1;
2120 	struct bpf_program *prog;
2121 	unsigned long duration;
2122 	char *endptr;
2123 
2124 	/* we at least need two args for the prog and one metric */
2125 	if (!REQ_ARGS(3))
2126 		return -EINVAL;
2127 
2128 	/* parse target fd */
2129 	profile_tgt_fd = prog_parse_fd(&argc, &argv);
2130 	if (profile_tgt_fd < 0) {
2131 		p_err("failed to parse fd");
2132 		return -1;
2133 	}
2134 
2135 	/* parse profiling optional duration */
2136 	if (argc > 2 && is_prefix(argv[0], "duration")) {
2137 		NEXT_ARG();
2138 		duration = strtoul(*argv, &endptr, 0);
2139 		if (*endptr)
2140 			usage();
2141 		NEXT_ARG();
2142 	} else {
2143 		duration = UINT_MAX;
2144 	}
2145 
2146 	num_metric = profile_parse_metrics(argc, argv);
2147 	if (num_metric <= 0)
2148 		goto out;
2149 
2150 	num_cpu = libbpf_num_possible_cpus();
2151 	if (num_cpu <= 0) {
2152 		p_err("failed to identify number of CPUs");
2153 		goto out;
2154 	}
2155 
2156 	profile_obj = profiler_bpf__open();
2157 	if (!profile_obj) {
2158 		p_err("failed to open and/or load BPF object");
2159 		goto out;
2160 	}
2161 
2162 	profile_obj->rodata->num_cpu = num_cpu;
2163 	profile_obj->rodata->num_metric = num_metric;
2164 
2165 	/* adjust map sizes */
2166 	bpf_map__resize(profile_obj->maps.events, num_metric * num_cpu);
2167 	bpf_map__resize(profile_obj->maps.fentry_readings, num_metric);
2168 	bpf_map__resize(profile_obj->maps.accum_readings, num_metric);
2169 	bpf_map__resize(profile_obj->maps.counts, 1);
2170 
2171 	/* change target name */
2172 	profile_tgt_name = profile_target_name(profile_tgt_fd);
2173 	if (!profile_tgt_name)
2174 		goto out;
2175 
2176 	bpf_object__for_each_program(prog, profile_obj->obj) {
2177 		err = bpf_program__set_attach_target(prog, profile_tgt_fd,
2178 						     profile_tgt_name);
2179 		if (err) {
2180 			p_err("failed to set attach target\n");
2181 			goto out;
2182 		}
2183 	}
2184 
2185 	set_max_rlimit();
2186 	err = profiler_bpf__load(profile_obj);
2187 	if (err) {
2188 		p_err("failed to load profile_obj");
2189 		goto out;
2190 	}
2191 
2192 	err = profile_open_perf_events(profile_obj);
2193 	if (err)
2194 		goto out;
2195 
2196 	err = profiler_bpf__attach(profile_obj);
2197 	if (err) {
2198 		p_err("failed to attach profile_obj");
2199 		goto out;
2200 	}
2201 	signal(SIGINT, int_exit);
2202 
2203 	sleep(duration);
2204 	profile_print_and_cleanup();
2205 	return 0;
2206 
2207 out:
2208 	profile_close_perf_events(profile_obj);
2209 	if (profile_obj)
2210 		profiler_bpf__destroy(profile_obj);
2211 	close(profile_tgt_fd);
2212 	free(profile_tgt_name);
2213 	return err;
2214 }
2215 
2216 #endif /* BPFTOOL_WITHOUT_SKELETONS */
2217 
2218 static int do_help(int argc, char **argv)
2219 {
2220 	if (json_output) {
2221 		jsonw_null(json_wtr);
2222 		return 0;
2223 	}
2224 
2225 	fprintf(stderr,
2226 		"Usage: %1$s %2$s { show | list } [PROG]\n"
2227 		"       %1$s %2$s dump xlated PROG [{ file FILE | opcodes | visual | linum }]\n"
2228 		"       %1$s %2$s dump jited  PROG [{ file FILE | opcodes | linum }]\n"
2229 		"       %1$s %2$s pin   PROG FILE\n"
2230 		"       %1$s %2$s { load | loadall } OBJ  PATH \\\n"
2231 		"                         [type TYPE] [dev NAME] \\\n"
2232 		"                         [map { idx IDX | name NAME } MAP]\\\n"
2233 		"                         [pinmaps MAP_DIR]\n"
2234 		"       %1$s %2$s attach PROG ATTACH_TYPE [MAP]\n"
2235 		"       %1$s %2$s detach PROG ATTACH_TYPE [MAP]\n"
2236 		"       %1$s %2$s run PROG \\\n"
2237 		"                         data_in FILE \\\n"
2238 		"                         [data_out FILE [data_size_out L]] \\\n"
2239 		"                         [ctx_in FILE [ctx_out FILE [ctx_size_out M]]] \\\n"
2240 		"                         [repeat N]\n"
2241 		"       %1$s %2$s profile PROG [duration DURATION] METRICs\n"
2242 		"       %1$s %2$s tracelog\n"
2243 		"       %1$s %2$s help\n"
2244 		"\n"
2245 		"       " HELP_SPEC_MAP "\n"
2246 		"       " HELP_SPEC_PROGRAM "\n"
2247 		"       TYPE := { socket | kprobe | kretprobe | classifier | action |\n"
2248 		"                 tracepoint | raw_tracepoint | xdp | perf_event | cgroup/skb |\n"
2249 		"                 cgroup/sock | cgroup/dev | lwt_in | lwt_out | lwt_xmit |\n"
2250 		"                 lwt_seg6local | sockops | sk_skb | sk_msg | lirc_mode2 |\n"
2251 		"                 sk_reuseport | flow_dissector | cgroup/sysctl |\n"
2252 		"                 cgroup/bind4 | cgroup/bind6 | cgroup/post_bind4 |\n"
2253 		"                 cgroup/post_bind6 | cgroup/connect4 | cgroup/connect6 |\n"
2254 		"                 cgroup/getpeername4 | cgroup/getpeername6 |\n"
2255 		"                 cgroup/getsockname4 | cgroup/getsockname6 | cgroup/sendmsg4 |\n"
2256 		"                 cgroup/sendmsg6 | cgroup/recvmsg4 | cgroup/recvmsg6 |\n"
2257 		"                 cgroup/getsockopt | cgroup/setsockopt | cgroup/sock_release |\n"
2258 		"                 struct_ops | fentry | fexit | freplace | sk_lookup }\n"
2259 		"       ATTACH_TYPE := { msg_verdict | skb_verdict | stream_verdict |\n"
2260 		"                        stream_parser | flow_dissector }\n"
2261 		"       METRIC := { cycles | instructions | l1d_loads | llc_misses | itlb_misses | dtlb_misses }\n"
2262 		"       " HELP_SPEC_OPTIONS " |\n"
2263 		"                    {-f|--bpffs} | {-m|--mapcompat} | {-n|--nomount} |\n"
2264 		"                    {-L|--use-loader} }\n"
2265 		"",
2266 		bin_name, argv[-2]);
2267 
2268 	return 0;
2269 }
2270 
2271 static const struct cmd cmds[] = {
2272 	{ "show",	do_show },
2273 	{ "list",	do_show },
2274 	{ "help",	do_help },
2275 	{ "dump",	do_dump },
2276 	{ "pin",	do_pin },
2277 	{ "load",	do_load },
2278 	{ "loadall",	do_loadall },
2279 	{ "attach",	do_attach },
2280 	{ "detach",	do_detach },
2281 	{ "tracelog",	do_tracelog },
2282 	{ "run",	do_run },
2283 	{ "profile",	do_profile },
2284 	{ 0 }
2285 };
2286 
2287 int do_prog(int argc, char **argv)
2288 {
2289 	return cmd_select(cmds, argc, argv, do_help);
2290 }
2291