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