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