xref: /linux/tools/bpf/bpftool/prog.c (revision 06b9cce42634a50f2840777a66553b02320db5ef)
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 	const unsigned int default_size = SZ_32K;
1276 	void *data_in = NULL, *data_out = NULL;
1277 	void *ctx_in = NULL, *ctx_out = NULL;
1278 	unsigned int repeat = 1;
1279 	int fd, err;
1280 	LIBBPF_OPTS(bpf_test_run_opts, test_attr);
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.repeat	= repeat;
1399 	test_attr.data_in	= data_in;
1400 	test_attr.data_out	= data_out;
1401 	test_attr.ctx_in	= ctx_in;
1402 	test_attr.ctx_out	= ctx_out;
1403 
1404 	err = bpf_prog_test_run_opts(fd, &test_attr);
1405 	if (err) {
1406 		p_err("failed to run program: %s", strerror(errno));
1407 		goto free_ctx_out;
1408 	}
1409 
1410 	err = 0;
1411 
1412 	if (json_output)
1413 		jsonw_start_object(json_wtr);	/* root */
1414 
1415 	/* Do not exit on errors occurring when printing output data/context,
1416 	 * we still want to print return value and duration for program run.
1417 	 */
1418 	if (test_attr.data_size_out)
1419 		err += print_run_output(test_attr.data_out,
1420 					test_attr.data_size_out,
1421 					data_fname_out, "data_out");
1422 	if (test_attr.ctx_size_out)
1423 		err += print_run_output(test_attr.ctx_out,
1424 					test_attr.ctx_size_out,
1425 					ctx_fname_out, "ctx_out");
1426 
1427 	if (json_output) {
1428 		jsonw_uint_field(json_wtr, "retval", test_attr.retval);
1429 		jsonw_uint_field(json_wtr, "duration", test_attr.duration);
1430 		jsonw_end_object(json_wtr);	/* root */
1431 	} else {
1432 		fprintf(stdout, "Return value: %u, duration%s: %uns\n",
1433 			test_attr.retval,
1434 			repeat > 1 ? " (average)" : "", test_attr.duration);
1435 	}
1436 
1437 free_ctx_out:
1438 	free(ctx_out);
1439 free_ctx_in:
1440 	free(ctx_in);
1441 free_data_out:
1442 	free(data_out);
1443 free_data_in:
1444 	free(data_in);
1445 
1446 	return err;
1447 }
1448 
1449 static int
1450 get_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
1451 		      enum bpf_attach_type *expected_attach_type)
1452 {
1453 	libbpf_print_fn_t print_backup;
1454 	int ret;
1455 
1456 	ret = libbpf_prog_type_by_name(name, prog_type, expected_attach_type);
1457 	if (!ret)
1458 		return ret;
1459 
1460 	/* libbpf_prog_type_by_name() failed, let's re-run with debug level */
1461 	print_backup = libbpf_set_print(print_all_levels);
1462 	ret = libbpf_prog_type_by_name(name, prog_type, expected_attach_type);
1463 	libbpf_set_print(print_backup);
1464 
1465 	return ret;
1466 }
1467 
1468 static int load_with_options(int argc, char **argv, bool first_prog_only)
1469 {
1470 	enum bpf_prog_type common_prog_type = BPF_PROG_TYPE_UNSPEC;
1471 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, open_opts,
1472 		.relaxed_maps = relaxed_maps,
1473 	);
1474 	enum bpf_attach_type expected_attach_type;
1475 	struct map_replace *map_replace = NULL;
1476 	struct bpf_program *prog = NULL, *pos;
1477 	unsigned int old_map_fds = 0;
1478 	const char *pinmaps = NULL;
1479 	struct bpf_object *obj;
1480 	struct bpf_map *map;
1481 	const char *pinfile;
1482 	unsigned int i, j;
1483 	__u32 ifindex = 0;
1484 	const char *file;
1485 	int idx, err;
1486 
1487 
1488 	if (!REQ_ARGS(2))
1489 		return -1;
1490 	file = GET_ARG();
1491 	pinfile = GET_ARG();
1492 
1493 	while (argc) {
1494 		if (is_prefix(*argv, "type")) {
1495 			NEXT_ARG();
1496 
1497 			if (common_prog_type != BPF_PROG_TYPE_UNSPEC) {
1498 				p_err("program type already specified");
1499 				goto err_free_reuse_maps;
1500 			}
1501 			if (!REQ_ARGS(1))
1502 				goto err_free_reuse_maps;
1503 
1504 			err = libbpf_prog_type_by_name(*argv, &common_prog_type,
1505 						       &expected_attach_type);
1506 			if (err < 0) {
1507 				/* Put a '/' at the end of type to appease libbpf */
1508 				char *type = malloc(strlen(*argv) + 2);
1509 
1510 				if (!type) {
1511 					p_err("mem alloc failed");
1512 					goto err_free_reuse_maps;
1513 				}
1514 				*type = 0;
1515 				strcat(type, *argv);
1516 				strcat(type, "/");
1517 
1518 				err = get_prog_type_by_name(type, &common_prog_type,
1519 							    &expected_attach_type);
1520 				free(type);
1521 				if (err < 0)
1522 					goto err_free_reuse_maps;
1523 			}
1524 
1525 			NEXT_ARG();
1526 		} else if (is_prefix(*argv, "map")) {
1527 			void *new_map_replace;
1528 			char *endptr, *name;
1529 			int fd;
1530 
1531 			NEXT_ARG();
1532 
1533 			if (!REQ_ARGS(4))
1534 				goto err_free_reuse_maps;
1535 
1536 			if (is_prefix(*argv, "idx")) {
1537 				NEXT_ARG();
1538 
1539 				idx = strtoul(*argv, &endptr, 0);
1540 				if (*endptr) {
1541 					p_err("can't parse %s as IDX", *argv);
1542 					goto err_free_reuse_maps;
1543 				}
1544 				name = NULL;
1545 			} else if (is_prefix(*argv, "name")) {
1546 				NEXT_ARG();
1547 
1548 				name = *argv;
1549 				idx = -1;
1550 			} else {
1551 				p_err("expected 'idx' or 'name', got: '%s'?",
1552 				      *argv);
1553 				goto err_free_reuse_maps;
1554 			}
1555 			NEXT_ARG();
1556 
1557 			fd = map_parse_fd(&argc, &argv);
1558 			if (fd < 0)
1559 				goto err_free_reuse_maps;
1560 
1561 			new_map_replace = reallocarray(map_replace,
1562 						       old_map_fds + 1,
1563 						       sizeof(*map_replace));
1564 			if (!new_map_replace) {
1565 				p_err("mem alloc failed");
1566 				goto err_free_reuse_maps;
1567 			}
1568 			map_replace = new_map_replace;
1569 
1570 			map_replace[old_map_fds].idx = idx;
1571 			map_replace[old_map_fds].name = name;
1572 			map_replace[old_map_fds].fd = fd;
1573 			old_map_fds++;
1574 		} else if (is_prefix(*argv, "dev")) {
1575 			NEXT_ARG();
1576 
1577 			if (ifindex) {
1578 				p_err("offload device already specified");
1579 				goto err_free_reuse_maps;
1580 			}
1581 			if (!REQ_ARGS(1))
1582 				goto err_free_reuse_maps;
1583 
1584 			ifindex = if_nametoindex(*argv);
1585 			if (!ifindex) {
1586 				p_err("unrecognized netdevice '%s': %s",
1587 				      *argv, strerror(errno));
1588 				goto err_free_reuse_maps;
1589 			}
1590 			NEXT_ARG();
1591 		} else if (is_prefix(*argv, "pinmaps")) {
1592 			NEXT_ARG();
1593 
1594 			if (!REQ_ARGS(1))
1595 				goto err_free_reuse_maps;
1596 
1597 			pinmaps = GET_ARG();
1598 		} else {
1599 			p_err("expected no more arguments, 'type', 'map' or 'dev', got: '%s'?",
1600 			      *argv);
1601 			goto err_free_reuse_maps;
1602 		}
1603 	}
1604 
1605 	set_max_rlimit();
1606 
1607 	if (verifier_logs)
1608 		/* log_level1 + log_level2 + stats, but not stable UAPI */
1609 		open_opts.kernel_log_level = 1 + 2 + 4;
1610 
1611 	obj = bpf_object__open_file(file, &open_opts);
1612 	if (libbpf_get_error(obj)) {
1613 		p_err("failed to open object file");
1614 		goto err_free_reuse_maps;
1615 	}
1616 
1617 	bpf_object__for_each_program(pos, obj) {
1618 		enum bpf_prog_type prog_type = common_prog_type;
1619 
1620 		if (prog_type == BPF_PROG_TYPE_UNSPEC) {
1621 			const char *sec_name = bpf_program__section_name(pos);
1622 
1623 			err = get_prog_type_by_name(sec_name, &prog_type,
1624 						    &expected_attach_type);
1625 			if (err < 0)
1626 				goto err_close_obj;
1627 		}
1628 
1629 		bpf_program__set_ifindex(pos, ifindex);
1630 		bpf_program__set_type(pos, prog_type);
1631 		bpf_program__set_expected_attach_type(pos, expected_attach_type);
1632 	}
1633 
1634 	qsort(map_replace, old_map_fds, sizeof(*map_replace),
1635 	      map_replace_compar);
1636 
1637 	/* After the sort maps by name will be first on the list, because they
1638 	 * have idx == -1.  Resolve them.
1639 	 */
1640 	j = 0;
1641 	while (j < old_map_fds && map_replace[j].name) {
1642 		i = 0;
1643 		bpf_object__for_each_map(map, obj) {
1644 			if (!strcmp(bpf_map__name(map), map_replace[j].name)) {
1645 				map_replace[j].idx = i;
1646 				break;
1647 			}
1648 			i++;
1649 		}
1650 		if (map_replace[j].idx == -1) {
1651 			p_err("unable to find map '%s'", map_replace[j].name);
1652 			goto err_close_obj;
1653 		}
1654 		j++;
1655 	}
1656 	/* Resort if any names were resolved */
1657 	if (j)
1658 		qsort(map_replace, old_map_fds, sizeof(*map_replace),
1659 		      map_replace_compar);
1660 
1661 	/* Set ifindex and name reuse */
1662 	j = 0;
1663 	idx = 0;
1664 	bpf_object__for_each_map(map, obj) {
1665 		if (bpf_map__type(map) != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
1666 			bpf_map__set_ifindex(map, ifindex);
1667 
1668 		if (j < old_map_fds && idx == map_replace[j].idx) {
1669 			err = bpf_map__reuse_fd(map, map_replace[j++].fd);
1670 			if (err) {
1671 				p_err("unable to set up map reuse: %d", err);
1672 				goto err_close_obj;
1673 			}
1674 
1675 			/* Next reuse wants to apply to the same map */
1676 			if (j < old_map_fds && map_replace[j].idx == idx) {
1677 				p_err("replacement for map idx %d specified more than once",
1678 				      idx);
1679 				goto err_close_obj;
1680 			}
1681 		}
1682 
1683 		idx++;
1684 	}
1685 	if (j < old_map_fds) {
1686 		p_err("map idx '%d' not used", map_replace[j].idx);
1687 		goto err_close_obj;
1688 	}
1689 
1690 	err = bpf_object__load(obj);
1691 	if (err) {
1692 		p_err("failed to load object file");
1693 		goto err_close_obj;
1694 	}
1695 
1696 	err = mount_bpffs_for_pin(pinfile);
1697 	if (err)
1698 		goto err_close_obj;
1699 
1700 	if (first_prog_only) {
1701 		prog = bpf_object__next_program(obj, NULL);
1702 		if (!prog) {
1703 			p_err("object file doesn't contain any bpf program");
1704 			goto err_close_obj;
1705 		}
1706 
1707 		err = bpf_obj_pin(bpf_program__fd(prog), pinfile);
1708 		if (err) {
1709 			p_err("failed to pin program %s",
1710 			      bpf_program__section_name(prog));
1711 			goto err_close_obj;
1712 		}
1713 	} else {
1714 		err = bpf_object__pin_programs(obj, pinfile);
1715 		if (err) {
1716 			p_err("failed to pin all programs");
1717 			goto err_close_obj;
1718 		}
1719 	}
1720 
1721 	if (pinmaps) {
1722 		err = bpf_object__pin_maps(obj, pinmaps);
1723 		if (err) {
1724 			p_err("failed to pin all maps");
1725 			goto err_unpin;
1726 		}
1727 	}
1728 
1729 	if (json_output)
1730 		jsonw_null(json_wtr);
1731 
1732 	bpf_object__close(obj);
1733 	for (i = 0; i < old_map_fds; i++)
1734 		close(map_replace[i].fd);
1735 	free(map_replace);
1736 
1737 	return 0;
1738 
1739 err_unpin:
1740 	if (first_prog_only)
1741 		unlink(pinfile);
1742 	else
1743 		bpf_object__unpin_programs(obj, pinfile);
1744 err_close_obj:
1745 	if (!legacy_libbpf) {
1746 		p_info("Warning: bpftool is now running in libbpf strict mode and has more stringent requirements about BPF programs.\n"
1747 		       "If it used to work for this object file but now doesn't, see --legacy option for more details.\n");
1748 	}
1749 
1750 	bpf_object__close(obj);
1751 err_free_reuse_maps:
1752 	for (i = 0; i < old_map_fds; i++)
1753 		close(map_replace[i].fd);
1754 	free(map_replace);
1755 	return -1;
1756 }
1757 
1758 static int count_open_fds(void)
1759 {
1760 	DIR *dp = opendir("/proc/self/fd");
1761 	struct dirent *de;
1762 	int cnt = -3;
1763 
1764 	if (!dp)
1765 		return -1;
1766 
1767 	while ((de = readdir(dp)))
1768 		cnt++;
1769 
1770 	closedir(dp);
1771 	return cnt;
1772 }
1773 
1774 static int try_loader(struct gen_loader_opts *gen)
1775 {
1776 	struct bpf_load_and_run_opts opts = {};
1777 	struct bpf_loader_ctx *ctx;
1778 	int ctx_sz = sizeof(*ctx) + 64 * max(sizeof(struct bpf_map_desc),
1779 					     sizeof(struct bpf_prog_desc));
1780 	int log_buf_sz = (1u << 24) - 1;
1781 	int err, fds_before, fd_delta;
1782 	char *log_buf = NULL;
1783 
1784 	ctx = alloca(ctx_sz);
1785 	memset(ctx, 0, ctx_sz);
1786 	ctx->sz = ctx_sz;
1787 	if (verifier_logs) {
1788 		ctx->log_level = 1 + 2 + 4;
1789 		ctx->log_size = log_buf_sz;
1790 		log_buf = malloc(log_buf_sz);
1791 		if (!log_buf)
1792 			return -ENOMEM;
1793 		ctx->log_buf = (long) log_buf;
1794 	}
1795 	opts.ctx = ctx;
1796 	opts.data = gen->data;
1797 	opts.data_sz = gen->data_sz;
1798 	opts.insns = gen->insns;
1799 	opts.insns_sz = gen->insns_sz;
1800 	fds_before = count_open_fds();
1801 	err = bpf_load_and_run(&opts);
1802 	fd_delta = count_open_fds() - fds_before;
1803 	if (err < 0 || verifier_logs) {
1804 		fprintf(stderr, "err %d\n%s\n%s", err, opts.errstr, log_buf);
1805 		if (fd_delta && err < 0)
1806 			fprintf(stderr, "loader prog leaked %d FDs\n",
1807 				fd_delta);
1808 	}
1809 	free(log_buf);
1810 	return err;
1811 }
1812 
1813 static int do_loader(int argc, char **argv)
1814 {
1815 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, open_opts);
1816 	DECLARE_LIBBPF_OPTS(gen_loader_opts, gen);
1817 	struct bpf_object *obj;
1818 	const char *file;
1819 	int err = 0;
1820 
1821 	if (!REQ_ARGS(1))
1822 		return -1;
1823 	file = GET_ARG();
1824 
1825 	if (verifier_logs)
1826 		/* log_level1 + log_level2 + stats, but not stable UAPI */
1827 		open_opts.kernel_log_level = 1 + 2 + 4;
1828 
1829 	obj = bpf_object__open_file(file, &open_opts);
1830 	if (libbpf_get_error(obj)) {
1831 		p_err("failed to open object file");
1832 		goto err_close_obj;
1833 	}
1834 
1835 	err = bpf_object__gen_loader(obj, &gen);
1836 	if (err)
1837 		goto err_close_obj;
1838 
1839 	err = bpf_object__load(obj);
1840 	if (err) {
1841 		p_err("failed to load object file");
1842 		goto err_close_obj;
1843 	}
1844 
1845 	if (verifier_logs) {
1846 		struct dump_data dd = {};
1847 
1848 		kernel_syms_load(&dd);
1849 		dump_xlated_plain(&dd, (void *)gen.insns, gen.insns_sz, false, false);
1850 		kernel_syms_destroy(&dd);
1851 	}
1852 	err = try_loader(&gen);
1853 err_close_obj:
1854 	bpf_object__close(obj);
1855 	return err;
1856 }
1857 
1858 static int do_load(int argc, char **argv)
1859 {
1860 	if (use_loader)
1861 		return do_loader(argc, argv);
1862 	return load_with_options(argc, argv, true);
1863 }
1864 
1865 static int do_loadall(int argc, char **argv)
1866 {
1867 	return load_with_options(argc, argv, false);
1868 }
1869 
1870 #ifdef BPFTOOL_WITHOUT_SKELETONS
1871 
1872 static int do_profile(int argc, char **argv)
1873 {
1874 	p_err("bpftool prog profile command is not supported. Please build bpftool with clang >= 10.0.0");
1875 	return 0;
1876 }
1877 
1878 #else /* BPFTOOL_WITHOUT_SKELETONS */
1879 
1880 #include "profiler.skel.h"
1881 
1882 struct profile_metric {
1883 	const char *name;
1884 	struct bpf_perf_event_value val;
1885 	struct perf_event_attr attr;
1886 	bool selected;
1887 
1888 	/* calculate ratios like instructions per cycle */
1889 	const int ratio_metric; /* 0 for N/A, 1 for index 0 (cycles) */
1890 	const char *ratio_desc;
1891 	const float ratio_mul;
1892 } metrics[] = {
1893 	{
1894 		.name = "cycles",
1895 		.attr = {
1896 			.type = PERF_TYPE_HARDWARE,
1897 			.config = PERF_COUNT_HW_CPU_CYCLES,
1898 			.exclude_user = 1,
1899 		},
1900 	},
1901 	{
1902 		.name = "instructions",
1903 		.attr = {
1904 			.type = PERF_TYPE_HARDWARE,
1905 			.config = PERF_COUNT_HW_INSTRUCTIONS,
1906 			.exclude_user = 1,
1907 		},
1908 		.ratio_metric = 1,
1909 		.ratio_desc = "insns per cycle",
1910 		.ratio_mul = 1.0,
1911 	},
1912 	{
1913 		.name = "l1d_loads",
1914 		.attr = {
1915 			.type = PERF_TYPE_HW_CACHE,
1916 			.config =
1917 				PERF_COUNT_HW_CACHE_L1D |
1918 				(PERF_COUNT_HW_CACHE_OP_READ << 8) |
1919 				(PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16),
1920 			.exclude_user = 1,
1921 		},
1922 	},
1923 	{
1924 		.name = "llc_misses",
1925 		.attr = {
1926 			.type = PERF_TYPE_HW_CACHE,
1927 			.config =
1928 				PERF_COUNT_HW_CACHE_LL |
1929 				(PERF_COUNT_HW_CACHE_OP_READ << 8) |
1930 				(PERF_COUNT_HW_CACHE_RESULT_MISS << 16),
1931 			.exclude_user = 1
1932 		},
1933 		.ratio_metric = 2,
1934 		.ratio_desc = "LLC misses per million insns",
1935 		.ratio_mul = 1e6,
1936 	},
1937 	{
1938 		.name = "itlb_misses",
1939 		.attr = {
1940 			.type = PERF_TYPE_HW_CACHE,
1941 			.config =
1942 				PERF_COUNT_HW_CACHE_ITLB |
1943 				(PERF_COUNT_HW_CACHE_OP_READ << 8) |
1944 				(PERF_COUNT_HW_CACHE_RESULT_MISS << 16),
1945 			.exclude_user = 1
1946 		},
1947 		.ratio_metric = 2,
1948 		.ratio_desc = "itlb misses per million insns",
1949 		.ratio_mul = 1e6,
1950 	},
1951 	{
1952 		.name = "dtlb_misses",
1953 		.attr = {
1954 			.type = PERF_TYPE_HW_CACHE,
1955 			.config =
1956 				PERF_COUNT_HW_CACHE_DTLB |
1957 				(PERF_COUNT_HW_CACHE_OP_READ << 8) |
1958 				(PERF_COUNT_HW_CACHE_RESULT_MISS << 16),
1959 			.exclude_user = 1
1960 		},
1961 		.ratio_metric = 2,
1962 		.ratio_desc = "dtlb misses per million insns",
1963 		.ratio_mul = 1e6,
1964 	},
1965 };
1966 
1967 static __u64 profile_total_count;
1968 
1969 #define MAX_NUM_PROFILE_METRICS 4
1970 
1971 static int profile_parse_metrics(int argc, char **argv)
1972 {
1973 	unsigned int metric_cnt;
1974 	int selected_cnt = 0;
1975 	unsigned int i;
1976 
1977 	metric_cnt = sizeof(metrics) / sizeof(struct profile_metric);
1978 
1979 	while (argc > 0) {
1980 		for (i = 0; i < metric_cnt; i++) {
1981 			if (is_prefix(argv[0], metrics[i].name)) {
1982 				if (!metrics[i].selected)
1983 					selected_cnt++;
1984 				metrics[i].selected = true;
1985 				break;
1986 			}
1987 		}
1988 		if (i == metric_cnt) {
1989 			p_err("unknown metric %s", argv[0]);
1990 			return -1;
1991 		}
1992 		NEXT_ARG();
1993 	}
1994 	if (selected_cnt > MAX_NUM_PROFILE_METRICS) {
1995 		p_err("too many (%d) metrics, please specify no more than %d metrics at at time",
1996 		      selected_cnt, MAX_NUM_PROFILE_METRICS);
1997 		return -1;
1998 	}
1999 	return selected_cnt;
2000 }
2001 
2002 static void profile_read_values(struct profiler_bpf *obj)
2003 {
2004 	__u32 m, cpu, num_cpu = obj->rodata->num_cpu;
2005 	int reading_map_fd, count_map_fd;
2006 	__u64 counts[num_cpu];
2007 	__u32 key = 0;
2008 	int err;
2009 
2010 	reading_map_fd = bpf_map__fd(obj->maps.accum_readings);
2011 	count_map_fd = bpf_map__fd(obj->maps.counts);
2012 	if (reading_map_fd < 0 || count_map_fd < 0) {
2013 		p_err("failed to get fd for map");
2014 		return;
2015 	}
2016 
2017 	err = bpf_map_lookup_elem(count_map_fd, &key, counts);
2018 	if (err) {
2019 		p_err("failed to read count_map: %s", strerror(errno));
2020 		return;
2021 	}
2022 
2023 	profile_total_count = 0;
2024 	for (cpu = 0; cpu < num_cpu; cpu++)
2025 		profile_total_count += counts[cpu];
2026 
2027 	for (m = 0; m < ARRAY_SIZE(metrics); m++) {
2028 		struct bpf_perf_event_value values[num_cpu];
2029 
2030 		if (!metrics[m].selected)
2031 			continue;
2032 
2033 		err = bpf_map_lookup_elem(reading_map_fd, &key, values);
2034 		if (err) {
2035 			p_err("failed to read reading_map: %s",
2036 			      strerror(errno));
2037 			return;
2038 		}
2039 		for (cpu = 0; cpu < num_cpu; cpu++) {
2040 			metrics[m].val.counter += values[cpu].counter;
2041 			metrics[m].val.enabled += values[cpu].enabled;
2042 			metrics[m].val.running += values[cpu].running;
2043 		}
2044 		key++;
2045 	}
2046 }
2047 
2048 static void profile_print_readings_json(void)
2049 {
2050 	__u32 m;
2051 
2052 	jsonw_start_array(json_wtr);
2053 	for (m = 0; m < ARRAY_SIZE(metrics); m++) {
2054 		if (!metrics[m].selected)
2055 			continue;
2056 		jsonw_start_object(json_wtr);
2057 		jsonw_string_field(json_wtr, "metric", metrics[m].name);
2058 		jsonw_lluint_field(json_wtr, "run_cnt", profile_total_count);
2059 		jsonw_lluint_field(json_wtr, "value", metrics[m].val.counter);
2060 		jsonw_lluint_field(json_wtr, "enabled", metrics[m].val.enabled);
2061 		jsonw_lluint_field(json_wtr, "running", metrics[m].val.running);
2062 
2063 		jsonw_end_object(json_wtr);
2064 	}
2065 	jsonw_end_array(json_wtr);
2066 }
2067 
2068 static void profile_print_readings_plain(void)
2069 {
2070 	__u32 m;
2071 
2072 	printf("\n%18llu %-20s\n", profile_total_count, "run_cnt");
2073 	for (m = 0; m < ARRAY_SIZE(metrics); m++) {
2074 		struct bpf_perf_event_value *val = &metrics[m].val;
2075 		int r;
2076 
2077 		if (!metrics[m].selected)
2078 			continue;
2079 		printf("%18llu %-20s", val->counter, metrics[m].name);
2080 
2081 		r = metrics[m].ratio_metric - 1;
2082 		if (r >= 0 && metrics[r].selected &&
2083 		    metrics[r].val.counter > 0) {
2084 			printf("# %8.2f %-30s",
2085 			       val->counter * metrics[m].ratio_mul /
2086 			       metrics[r].val.counter,
2087 			       metrics[m].ratio_desc);
2088 		} else {
2089 			printf("%-41s", "");
2090 		}
2091 
2092 		if (val->enabled > val->running)
2093 			printf("(%4.2f%%)",
2094 			       val->running * 100.0 / val->enabled);
2095 		printf("\n");
2096 	}
2097 }
2098 
2099 static void profile_print_readings(void)
2100 {
2101 	if (json_output)
2102 		profile_print_readings_json();
2103 	else
2104 		profile_print_readings_plain();
2105 }
2106 
2107 static char *profile_target_name(int tgt_fd)
2108 {
2109 	struct bpf_func_info func_info;
2110 	struct bpf_prog_info info = {};
2111 	__u32 info_len = sizeof(info);
2112 	const struct btf_type *t;
2113 	__u32 func_info_rec_size;
2114 	struct btf *btf = NULL;
2115 	char *name = NULL;
2116 	int err;
2117 
2118 	err = bpf_obj_get_info_by_fd(tgt_fd, &info, &info_len);
2119 	if (err) {
2120 		p_err("failed to bpf_obj_get_info_by_fd for prog FD %d", tgt_fd);
2121 		goto out;
2122 	}
2123 
2124 	if (info.btf_id == 0) {
2125 		p_err("prog FD %d doesn't have valid btf", tgt_fd);
2126 		goto out;
2127 	}
2128 
2129 	func_info_rec_size = info.func_info_rec_size;
2130 	if (info.nr_func_info == 0) {
2131 		p_err("bpf_obj_get_info_by_fd for prog FD %d found 0 func_info", tgt_fd);
2132 		goto out;
2133 	}
2134 
2135 	memset(&info, 0, sizeof(info));
2136 	info.nr_func_info = 1;
2137 	info.func_info_rec_size = func_info_rec_size;
2138 	info.func_info = ptr_to_u64(&func_info);
2139 
2140 	err = bpf_obj_get_info_by_fd(tgt_fd, &info, &info_len);
2141 	if (err) {
2142 		p_err("failed to get func_info for prog FD %d", tgt_fd);
2143 		goto out;
2144 	}
2145 
2146 	btf = btf__load_from_kernel_by_id(info.btf_id);
2147 	if (libbpf_get_error(btf)) {
2148 		p_err("failed to load btf for prog FD %d", tgt_fd);
2149 		goto out;
2150 	}
2151 
2152 	t = btf__type_by_id(btf, func_info.type_id);
2153 	if (!t) {
2154 		p_err("btf %d doesn't have type %d",
2155 		      info.btf_id, func_info.type_id);
2156 		goto out;
2157 	}
2158 	name = strdup(btf__name_by_offset(btf, t->name_off));
2159 out:
2160 	btf__free(btf);
2161 	return name;
2162 }
2163 
2164 static struct profiler_bpf *profile_obj;
2165 static int profile_tgt_fd = -1;
2166 static char *profile_tgt_name;
2167 static int *profile_perf_events;
2168 static int profile_perf_event_cnt;
2169 
2170 static void profile_close_perf_events(struct profiler_bpf *obj)
2171 {
2172 	int i;
2173 
2174 	for (i = profile_perf_event_cnt - 1; i >= 0; i--)
2175 		close(profile_perf_events[i]);
2176 
2177 	free(profile_perf_events);
2178 	profile_perf_event_cnt = 0;
2179 }
2180 
2181 static int profile_open_perf_events(struct profiler_bpf *obj)
2182 {
2183 	unsigned int cpu, m;
2184 	int map_fd, pmu_fd;
2185 
2186 	profile_perf_events = calloc(
2187 		sizeof(int), obj->rodata->num_cpu * obj->rodata->num_metric);
2188 	if (!profile_perf_events) {
2189 		p_err("failed to allocate memory for perf_event array: %s",
2190 		      strerror(errno));
2191 		return -1;
2192 	}
2193 	map_fd = bpf_map__fd(obj->maps.events);
2194 	if (map_fd < 0) {
2195 		p_err("failed to get fd for events map");
2196 		return -1;
2197 	}
2198 
2199 	for (m = 0; m < ARRAY_SIZE(metrics); m++) {
2200 		if (!metrics[m].selected)
2201 			continue;
2202 		for (cpu = 0; cpu < obj->rodata->num_cpu; cpu++) {
2203 			pmu_fd = syscall(__NR_perf_event_open, &metrics[m].attr,
2204 					 -1/*pid*/, cpu, -1/*group_fd*/, 0);
2205 			if (pmu_fd < 0 ||
2206 			    bpf_map_update_elem(map_fd, &profile_perf_event_cnt,
2207 						&pmu_fd, BPF_ANY) ||
2208 			    ioctl(pmu_fd, PERF_EVENT_IOC_ENABLE, 0)) {
2209 				p_err("failed to create event %s on cpu %d",
2210 				      metrics[m].name, cpu);
2211 				return -1;
2212 			}
2213 			profile_perf_events[profile_perf_event_cnt++] = pmu_fd;
2214 		}
2215 	}
2216 	return 0;
2217 }
2218 
2219 static void profile_print_and_cleanup(void)
2220 {
2221 	profile_close_perf_events(profile_obj);
2222 	profile_read_values(profile_obj);
2223 	profile_print_readings();
2224 	profiler_bpf__destroy(profile_obj);
2225 
2226 	close(profile_tgt_fd);
2227 	free(profile_tgt_name);
2228 }
2229 
2230 static void int_exit(int signo)
2231 {
2232 	profile_print_and_cleanup();
2233 	exit(0);
2234 }
2235 
2236 static int do_profile(int argc, char **argv)
2237 {
2238 	int num_metric, num_cpu, err = -1;
2239 	struct bpf_program *prog;
2240 	unsigned long duration;
2241 	char *endptr;
2242 
2243 	/* we at least need two args for the prog and one metric */
2244 	if (!REQ_ARGS(3))
2245 		return -EINVAL;
2246 
2247 	/* parse target fd */
2248 	profile_tgt_fd = prog_parse_fd(&argc, &argv);
2249 	if (profile_tgt_fd < 0) {
2250 		p_err("failed to parse fd");
2251 		return -1;
2252 	}
2253 
2254 	/* parse profiling optional duration */
2255 	if (argc > 2 && is_prefix(argv[0], "duration")) {
2256 		NEXT_ARG();
2257 		duration = strtoul(*argv, &endptr, 0);
2258 		if (*endptr)
2259 			usage();
2260 		NEXT_ARG();
2261 	} else {
2262 		duration = UINT_MAX;
2263 	}
2264 
2265 	num_metric = profile_parse_metrics(argc, argv);
2266 	if (num_metric <= 0)
2267 		goto out;
2268 
2269 	num_cpu = libbpf_num_possible_cpus();
2270 	if (num_cpu <= 0) {
2271 		p_err("failed to identify number of CPUs");
2272 		goto out;
2273 	}
2274 
2275 	profile_obj = profiler_bpf__open();
2276 	if (!profile_obj) {
2277 		p_err("failed to open and/or load BPF object");
2278 		goto out;
2279 	}
2280 
2281 	profile_obj->rodata->num_cpu = num_cpu;
2282 	profile_obj->rodata->num_metric = num_metric;
2283 
2284 	/* adjust map sizes */
2285 	bpf_map__set_max_entries(profile_obj->maps.events, num_metric * num_cpu);
2286 	bpf_map__set_max_entries(profile_obj->maps.fentry_readings, num_metric);
2287 	bpf_map__set_max_entries(profile_obj->maps.accum_readings, num_metric);
2288 	bpf_map__set_max_entries(profile_obj->maps.counts, 1);
2289 
2290 	/* change target name */
2291 	profile_tgt_name = profile_target_name(profile_tgt_fd);
2292 	if (!profile_tgt_name)
2293 		goto out;
2294 
2295 	bpf_object__for_each_program(prog, profile_obj->obj) {
2296 		err = bpf_program__set_attach_target(prog, profile_tgt_fd,
2297 						     profile_tgt_name);
2298 		if (err) {
2299 			p_err("failed to set attach target\n");
2300 			goto out;
2301 		}
2302 	}
2303 
2304 	set_max_rlimit();
2305 	err = profiler_bpf__load(profile_obj);
2306 	if (err) {
2307 		p_err("failed to load profile_obj");
2308 		goto out;
2309 	}
2310 
2311 	err = profile_open_perf_events(profile_obj);
2312 	if (err)
2313 		goto out;
2314 
2315 	err = profiler_bpf__attach(profile_obj);
2316 	if (err) {
2317 		p_err("failed to attach profile_obj");
2318 		goto out;
2319 	}
2320 	signal(SIGINT, int_exit);
2321 
2322 	sleep(duration);
2323 	profile_print_and_cleanup();
2324 	return 0;
2325 
2326 out:
2327 	profile_close_perf_events(profile_obj);
2328 	if (profile_obj)
2329 		profiler_bpf__destroy(profile_obj);
2330 	close(profile_tgt_fd);
2331 	free(profile_tgt_name);
2332 	return err;
2333 }
2334 
2335 #endif /* BPFTOOL_WITHOUT_SKELETONS */
2336 
2337 static int do_help(int argc, char **argv)
2338 {
2339 	if (json_output) {
2340 		jsonw_null(json_wtr);
2341 		return 0;
2342 	}
2343 
2344 	fprintf(stderr,
2345 		"Usage: %1$s %2$s { show | list } [PROG]\n"
2346 		"       %1$s %2$s dump xlated PROG [{ file FILE | opcodes | visual | linum }]\n"
2347 		"       %1$s %2$s dump jited  PROG [{ file FILE | opcodes | linum }]\n"
2348 		"       %1$s %2$s pin   PROG FILE\n"
2349 		"       %1$s %2$s { load | loadall } OBJ  PATH \\\n"
2350 		"                         [type TYPE] [dev NAME] \\\n"
2351 		"                         [map { idx IDX | name NAME } MAP]\\\n"
2352 		"                         [pinmaps MAP_DIR]\n"
2353 		"       %1$s %2$s attach PROG ATTACH_TYPE [MAP]\n"
2354 		"       %1$s %2$s detach PROG ATTACH_TYPE [MAP]\n"
2355 		"       %1$s %2$s run PROG \\\n"
2356 		"                         data_in FILE \\\n"
2357 		"                         [data_out FILE [data_size_out L]] \\\n"
2358 		"                         [ctx_in FILE [ctx_out FILE [ctx_size_out M]]] \\\n"
2359 		"                         [repeat N]\n"
2360 		"       %1$s %2$s profile PROG [duration DURATION] METRICs\n"
2361 		"       %1$s %2$s tracelog\n"
2362 		"       %1$s %2$s help\n"
2363 		"\n"
2364 		"       " HELP_SPEC_MAP "\n"
2365 		"       " HELP_SPEC_PROGRAM "\n"
2366 		"       TYPE := { socket | kprobe | kretprobe | classifier | action |\n"
2367 		"                 tracepoint | raw_tracepoint | xdp | perf_event | cgroup/skb |\n"
2368 		"                 cgroup/sock | cgroup/dev | lwt_in | lwt_out | lwt_xmit |\n"
2369 		"                 lwt_seg6local | sockops | sk_skb | sk_msg | lirc_mode2 |\n"
2370 		"                 sk_reuseport | flow_dissector | cgroup/sysctl |\n"
2371 		"                 cgroup/bind4 | cgroup/bind6 | cgroup/post_bind4 |\n"
2372 		"                 cgroup/post_bind6 | cgroup/connect4 | cgroup/connect6 |\n"
2373 		"                 cgroup/getpeername4 | cgroup/getpeername6 |\n"
2374 		"                 cgroup/getsockname4 | cgroup/getsockname6 | cgroup/sendmsg4 |\n"
2375 		"                 cgroup/sendmsg6 | cgroup/recvmsg4 | cgroup/recvmsg6 |\n"
2376 		"                 cgroup/getsockopt | cgroup/setsockopt | cgroup/sock_release |\n"
2377 		"                 struct_ops | fentry | fexit | freplace | sk_lookup }\n"
2378 		"       ATTACH_TYPE := { msg_verdict | skb_verdict | stream_verdict |\n"
2379 		"                        stream_parser | flow_dissector }\n"
2380 		"       METRIC := { cycles | instructions | l1d_loads | llc_misses | itlb_misses | dtlb_misses }\n"
2381 		"       " HELP_SPEC_OPTIONS " |\n"
2382 		"                    {-f|--bpffs} | {-m|--mapcompat} | {-n|--nomount} |\n"
2383 		"                    {-L|--use-loader} }\n"
2384 		"",
2385 		bin_name, argv[-2]);
2386 
2387 	return 0;
2388 }
2389 
2390 static const struct cmd cmds[] = {
2391 	{ "show",	do_show },
2392 	{ "list",	do_show },
2393 	{ "help",	do_help },
2394 	{ "dump",	do_dump },
2395 	{ "pin",	do_pin },
2396 	{ "load",	do_load },
2397 	{ "loadall",	do_loadall },
2398 	{ "attach",	do_attach },
2399 	{ "detach",	do_detach },
2400 	{ "tracelog",	do_tracelog },
2401 	{ "run",	do_run },
2402 	{ "profile",	do_profile },
2403 	{ 0 }
2404 };
2405 
2406 int do_prog(int argc, char **argv)
2407 {
2408 	return cmd_select(cmds, argc, argv, do_help);
2409 }
2410