xref: /openbmc/linux/tools/bpf/bpftool/prog.c (revision 8f184732b60b74a8f8ba0d9a5c248bf611b1ebba)
102ff58dcSJakub Kicinski // SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
202ff58dcSJakub Kicinski /* Copyright (C) 2017-2018 Netronome Systems, Inc. */
371bb428fSJakub Kicinski 
43ff5a4dcSJakub Kicinski #define _GNU_SOURCE
571bb428fSJakub Kicinski #include <errno.h>
671bb428fSJakub Kicinski #include <fcntl.h>
747c09d6aSSong Liu #include <signal.h>
8c9c35995SJakub Kicinski #include <stdarg.h>
971bb428fSJakub Kicinski #include <stdio.h>
1071bb428fSJakub Kicinski #include <stdlib.h>
1171bb428fSJakub Kicinski #include <string.h>
1271bb428fSJakub Kicinski #include <time.h>
1371bb428fSJakub Kicinski #include <unistd.h>
14ba6dd679SJakub Kicinski #include <net/if.h>
1547c09d6aSSong Liu #include <sys/ioctl.h>
1671bb428fSJakub Kicinski #include <sys/types.h>
1771bb428fSJakub Kicinski #include <sys/stat.h>
1847c09d6aSSong Liu #include <sys/syscall.h>
19d510296dSAlexei Starovoitov #include <dirent.h>
2071bb428fSJakub Kicinski 
21c8406848SJakub Kicinski #include <linux/err.h>
2247c09d6aSSong Liu #include <linux/perf_event.h>
23ba95c745SQuentin Monnet #include <linux/sizes.h>
24c8406848SJakub Kicinski 
25229c3b47SToke Høiland-Jørgensen #include <bpf/bpf.h>
26229c3b47SToke Høiland-Jørgensen #include <bpf/btf.h>
27*8f184732SQuentin Monnet #include <bpf/hashmap.h>
28229c3b47SToke Høiland-Jørgensen #include <bpf/libbpf.h>
29d510296dSAlexei Starovoitov #include <bpf/skel_internal.h>
3071bb428fSJakub Kicinski 
31b6c1cedbSJiong Wang #include "cfg.h"
3271bb428fSJakub Kicinski #include "main.h"
3373bb5b4fSJiong Wang #include "xlated_dumper.h"
3471bb428fSJakub Kicinski 
35aff52e68SYiFei Zhu #define BPF_METADATA_PREFIX "bpf_metadata_"
36aff52e68SYiFei Zhu #define BPF_METADATA_PREFIX_LEN (sizeof(BPF_METADATA_PREFIX) - 1)
37aff52e68SYiFei Zhu 
389023497dSTobias Klauser const char * const prog_type_name[] = {
399023497dSTobias Klauser 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
409023497dSTobias Klauser 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
419023497dSTobias Klauser 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
429023497dSTobias Klauser 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
439023497dSTobias Klauser 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
449023497dSTobias Klauser 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
459023497dSTobias Klauser 	[BPF_PROG_TYPE_XDP]			= "xdp",
469023497dSTobias Klauser 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
479023497dSTobias Klauser 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
489023497dSTobias Klauser 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
499023497dSTobias Klauser 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
509023497dSTobias Klauser 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
519023497dSTobias Klauser 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
529023497dSTobias Klauser 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
539023497dSTobias Klauser 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
549023497dSTobias Klauser 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
559023497dSTobias Klauser 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
569023497dSTobias Klauser 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
579023497dSTobias Klauser 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
589023497dSTobias Klauser 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
599023497dSTobias Klauser 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
609023497dSTobias Klauser 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
619023497dSTobias Klauser 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
629023497dSTobias Klauser 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
639023497dSTobias Klauser 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
649023497dSTobias Klauser 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
659023497dSTobias Klauser 	[BPF_PROG_TYPE_TRACING]			= "tracing",
669023497dSTobias Klauser 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
679023497dSTobias Klauser 	[BPF_PROG_TYPE_EXT]			= "ext",
689a97c9d2SQuentin Monnet 	[BPF_PROG_TYPE_LSM]			= "lsm",
6993a3545dSJakub Sitnicki 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
709023497dSTobias Klauser };
719023497dSTobias Klauser 
729023497dSTobias Klauser const size_t prog_type_name_size = ARRAY_SIZE(prog_type_name);
739023497dSTobias Klauser 
74ec202509SPaul Chaignon enum dump_mode {
75ec202509SPaul Chaignon 	DUMP_JITED,
76ec202509SPaul Chaignon 	DUMP_XLATED,
77ec202509SPaul Chaignon };
78ec202509SPaul Chaignon 
79b7d3826cSJohn Fastabend static const char * const attach_type_strings[] = {
80b7d3826cSJohn Fastabend 	[BPF_SK_SKB_STREAM_PARSER] = "stream_parser",
81b7d3826cSJohn Fastabend 	[BPF_SK_SKB_STREAM_VERDICT] = "stream_verdict",
82a7ba4558SCong Wang 	[BPF_SK_SKB_VERDICT] = "skb_verdict",
83b7d3826cSJohn Fastabend 	[BPF_SK_MSG_VERDICT] = "msg_verdict",
84092f0892SStanislav Fomichev 	[BPF_FLOW_DISSECTOR] = "flow_dissector",
85b7d3826cSJohn Fastabend 	[__MAX_BPF_ATTACH_TYPE] = NULL,
86b7d3826cSJohn Fastabend };
87b7d3826cSJohn Fastabend 
88*8f184732SQuentin Monnet static struct hashmap *prog_table;
8946241271SQuentin Monnet 
90c101189bSQuentin Monnet static enum bpf_attach_type parse_attach_type(const char *str)
91b7d3826cSJohn Fastabend {
92b7d3826cSJohn Fastabend 	enum bpf_attach_type type;
93b7d3826cSJohn Fastabend 
94b7d3826cSJohn Fastabend 	for (type = 0; type < __MAX_BPF_ATTACH_TYPE; type++) {
95b7d3826cSJohn Fastabend 		if (attach_type_strings[type] &&
96b7d3826cSJohn Fastabend 		    is_prefix(str, attach_type_strings[type]))
97b7d3826cSJohn Fastabend 			return type;
98b7d3826cSJohn Fastabend 	}
99b7d3826cSJohn Fastabend 
100b7d3826cSJohn Fastabend 	return __MAX_BPF_ATTACH_TYPE;
101b7d3826cSJohn Fastabend }
102b7d3826cSJohn Fastabend 
10371bb428fSJakub Kicinski static void print_boot_time(__u64 nsecs, char *buf, unsigned int size)
10471bb428fSJakub Kicinski {
10571bb428fSJakub Kicinski 	struct timespec real_time_ts, boot_time_ts;
10671bb428fSJakub Kicinski 	time_t wallclock_secs;
10771bb428fSJakub Kicinski 	struct tm load_tm;
10871bb428fSJakub Kicinski 
10971bb428fSJakub Kicinski 	buf[--size] = '\0';
11071bb428fSJakub Kicinski 
11171bb428fSJakub Kicinski 	if (clock_gettime(CLOCK_REALTIME, &real_time_ts) ||
11271bb428fSJakub Kicinski 	    clock_gettime(CLOCK_BOOTTIME, &boot_time_ts)) {
11371bb428fSJakub Kicinski 		perror("Can't read clocks");
11471bb428fSJakub Kicinski 		snprintf(buf, size, "%llu", nsecs / 1000000000);
11571bb428fSJakub Kicinski 		return;
11671bb428fSJakub Kicinski 	}
11771bb428fSJakub Kicinski 
11871bb428fSJakub Kicinski 	wallclock_secs = (real_time_ts.tv_sec - boot_time_ts.tv_sec) +
11907480cbcSJakub Kicinski 		(real_time_ts.tv_nsec - boot_time_ts.tv_nsec + nsecs) /
12007480cbcSJakub Kicinski 		1000000000;
12107480cbcSJakub Kicinski 
12271bb428fSJakub Kicinski 
12371bb428fSJakub Kicinski 	if (!localtime_r(&wallclock_secs, &load_tm)) {
12471bb428fSJakub Kicinski 		snprintf(buf, size, "%llu", nsecs / 1000000000);
12571bb428fSJakub Kicinski 		return;
12671bb428fSJakub Kicinski 	}
12771bb428fSJakub Kicinski 
128a3fe1f6fSQuentin Monnet 	if (json_output)
129a3fe1f6fSQuentin Monnet 		strftime(buf, size, "%s", &load_tm);
130a3fe1f6fSQuentin Monnet 	else
131a3fe1f6fSQuentin Monnet 		strftime(buf, size, "%FT%T%z", &load_tm);
13271bb428fSJakub Kicinski }
13371bb428fSJakub Kicinski 
1346e7e034eSQuentin Monnet static void show_prog_maps(int fd, __u32 num_maps)
13571bb428fSJakub Kicinski {
13671bb428fSJakub Kicinski 	struct bpf_prog_info info = {};
13771bb428fSJakub Kicinski 	__u32 len = sizeof(info);
13871bb428fSJakub Kicinski 	__u32 map_ids[num_maps];
13971bb428fSJakub Kicinski 	unsigned int i;
14071bb428fSJakub Kicinski 	int err;
14171bb428fSJakub Kicinski 
14271bb428fSJakub Kicinski 	info.nr_map_ids = num_maps;
14371bb428fSJakub Kicinski 	info.map_ids = ptr_to_u64(map_ids);
14471bb428fSJakub Kicinski 
14571bb428fSJakub Kicinski 	err = bpf_obj_get_info_by_fd(fd, &info, &len);
14671bb428fSJakub Kicinski 	if (err || !info.nr_map_ids)
14771bb428fSJakub Kicinski 		return;
14871bb428fSJakub Kicinski 
149743cc665SQuentin Monnet 	if (json_output) {
150743cc665SQuentin Monnet 		jsonw_name(json_wtr, "map_ids");
151743cc665SQuentin Monnet 		jsonw_start_array(json_wtr);
152743cc665SQuentin Monnet 		for (i = 0; i < info.nr_map_ids; i++)
153743cc665SQuentin Monnet 			jsonw_uint(json_wtr, map_ids[i]);
154743cc665SQuentin Monnet 		jsonw_end_array(json_wtr);
155743cc665SQuentin Monnet 	} else {
15671bb428fSJakub Kicinski 		printf("  map_ids ");
15771bb428fSJakub Kicinski 		for (i = 0; i < info.nr_map_ids; i++)
15871bb428fSJakub Kicinski 			printf("%u%s", map_ids[i],
15971bb428fSJakub Kicinski 			       i == info.nr_map_ids - 1 ? "" : ",");
16071bb428fSJakub Kicinski 	}
16171bb428fSJakub Kicinski }
16271bb428fSJakub Kicinski 
163aff52e68SYiFei Zhu static void *find_metadata(int prog_fd, struct bpf_map_info *map_info)
164aff52e68SYiFei Zhu {
165aff52e68SYiFei Zhu 	struct bpf_prog_info prog_info;
166aff52e68SYiFei Zhu 	__u32 prog_info_len;
167aff52e68SYiFei Zhu 	__u32 map_info_len;
168aff52e68SYiFei Zhu 	void *value = NULL;
169aff52e68SYiFei Zhu 	__u32 *map_ids;
170aff52e68SYiFei Zhu 	int nr_maps;
171aff52e68SYiFei Zhu 	int key = 0;
172aff52e68SYiFei Zhu 	int map_fd;
173aff52e68SYiFei Zhu 	int ret;
174aff52e68SYiFei Zhu 	__u32 i;
175aff52e68SYiFei Zhu 
176aff52e68SYiFei Zhu 	memset(&prog_info, 0, sizeof(prog_info));
177aff52e68SYiFei Zhu 	prog_info_len = sizeof(prog_info);
178aff52e68SYiFei Zhu 	ret = bpf_obj_get_info_by_fd(prog_fd, &prog_info, &prog_info_len);
179aff52e68SYiFei Zhu 	if (ret)
180aff52e68SYiFei Zhu 		return NULL;
181aff52e68SYiFei Zhu 
182aff52e68SYiFei Zhu 	if (!prog_info.nr_map_ids)
183aff52e68SYiFei Zhu 		return NULL;
184aff52e68SYiFei Zhu 
185aff52e68SYiFei Zhu 	map_ids = calloc(prog_info.nr_map_ids, sizeof(__u32));
186aff52e68SYiFei Zhu 	if (!map_ids)
187aff52e68SYiFei Zhu 		return NULL;
188aff52e68SYiFei Zhu 
189aff52e68SYiFei Zhu 	nr_maps = prog_info.nr_map_ids;
190aff52e68SYiFei Zhu 	memset(&prog_info, 0, sizeof(prog_info));
191aff52e68SYiFei Zhu 	prog_info.nr_map_ids = nr_maps;
192aff52e68SYiFei Zhu 	prog_info.map_ids = ptr_to_u64(map_ids);
193aff52e68SYiFei Zhu 	prog_info_len = sizeof(prog_info);
194aff52e68SYiFei Zhu 
195aff52e68SYiFei Zhu 	ret = bpf_obj_get_info_by_fd(prog_fd, &prog_info, &prog_info_len);
196aff52e68SYiFei Zhu 	if (ret)
197aff52e68SYiFei Zhu 		goto free_map_ids;
198aff52e68SYiFei Zhu 
199aff52e68SYiFei Zhu 	for (i = 0; i < prog_info.nr_map_ids; i++) {
200aff52e68SYiFei Zhu 		map_fd = bpf_map_get_fd_by_id(map_ids[i]);
201aff52e68SYiFei Zhu 		if (map_fd < 0)
202aff52e68SYiFei Zhu 			goto free_map_ids;
203aff52e68SYiFei Zhu 
204aff52e68SYiFei Zhu 		memset(map_info, 0, sizeof(*map_info));
205aff52e68SYiFei Zhu 		map_info_len = sizeof(*map_info);
206aff52e68SYiFei Zhu 		ret = bpf_obj_get_info_by_fd(map_fd, map_info, &map_info_len);
207aff52e68SYiFei Zhu 		if (ret < 0) {
208aff52e68SYiFei Zhu 			close(map_fd);
209aff52e68SYiFei Zhu 			goto free_map_ids;
210aff52e68SYiFei Zhu 		}
211aff52e68SYiFei Zhu 
212aff52e68SYiFei Zhu 		if (map_info->type != BPF_MAP_TYPE_ARRAY ||
213aff52e68SYiFei Zhu 		    map_info->key_size != sizeof(int) ||
214aff52e68SYiFei Zhu 		    map_info->max_entries != 1 ||
215aff52e68SYiFei Zhu 		    !map_info->btf_value_type_id ||
216aff52e68SYiFei Zhu 		    !strstr(map_info->name, ".rodata")) {
217aff52e68SYiFei Zhu 			close(map_fd);
218aff52e68SYiFei Zhu 			continue;
219aff52e68SYiFei Zhu 		}
220aff52e68SYiFei Zhu 
221aff52e68SYiFei Zhu 		value = malloc(map_info->value_size);
222aff52e68SYiFei Zhu 		if (!value) {
223aff52e68SYiFei Zhu 			close(map_fd);
224aff52e68SYiFei Zhu 			goto free_map_ids;
225aff52e68SYiFei Zhu 		}
226aff52e68SYiFei Zhu 
227aff52e68SYiFei Zhu 		if (bpf_map_lookup_elem(map_fd, &key, value)) {
228aff52e68SYiFei Zhu 			close(map_fd);
229aff52e68SYiFei Zhu 			free(value);
230aff52e68SYiFei Zhu 			value = NULL;
231aff52e68SYiFei Zhu 			goto free_map_ids;
232aff52e68SYiFei Zhu 		}
233aff52e68SYiFei Zhu 
234aff52e68SYiFei Zhu 		close(map_fd);
235aff52e68SYiFei Zhu 		break;
236aff52e68SYiFei Zhu 	}
237aff52e68SYiFei Zhu 
238aff52e68SYiFei Zhu free_map_ids:
239aff52e68SYiFei Zhu 	free(map_ids);
240aff52e68SYiFei Zhu 	return value;
241aff52e68SYiFei Zhu }
242aff52e68SYiFei Zhu 
243aff52e68SYiFei Zhu static bool has_metadata_prefix(const char *s)
244aff52e68SYiFei Zhu {
245aff52e68SYiFei Zhu 	return strncmp(s, BPF_METADATA_PREFIX, BPF_METADATA_PREFIX_LEN) == 0;
246aff52e68SYiFei Zhu }
247aff52e68SYiFei Zhu 
248aff52e68SYiFei Zhu static void show_prog_metadata(int fd, __u32 num_maps)
249aff52e68SYiFei Zhu {
250aff52e68SYiFei Zhu 	const struct btf_type *t_datasec, *t_var;
251aff52e68SYiFei Zhu 	struct bpf_map_info map_info;
252aff52e68SYiFei Zhu 	struct btf_var_secinfo *vsi;
253aff52e68SYiFei Zhu 	bool printed_header = false;
254aff52e68SYiFei Zhu 	unsigned int i, vlen;
255aff52e68SYiFei Zhu 	void *value = NULL;
256aff52e68SYiFei Zhu 	const char *name;
25786f4b7f2SQuentin Monnet 	struct btf *btf;
258aff52e68SYiFei Zhu 	int err;
259aff52e68SYiFei Zhu 
260aff52e68SYiFei Zhu 	if (!num_maps)
261aff52e68SYiFei Zhu 		return;
262aff52e68SYiFei Zhu 
263aff52e68SYiFei Zhu 	memset(&map_info, 0, sizeof(map_info));
264aff52e68SYiFei Zhu 	value = find_metadata(fd, &map_info);
265aff52e68SYiFei Zhu 	if (!value)
266aff52e68SYiFei Zhu 		return;
267aff52e68SYiFei Zhu 
26886f4b7f2SQuentin Monnet 	btf = btf__load_from_kernel_by_id(map_info.btf_id);
26986f4b7f2SQuentin Monnet 	if (libbpf_get_error(btf))
270aff52e68SYiFei Zhu 		goto out_free;
271aff52e68SYiFei Zhu 
272aff52e68SYiFei Zhu 	t_datasec = btf__type_by_id(btf, map_info.btf_value_type_id);
273aff52e68SYiFei Zhu 	if (!btf_is_datasec(t_datasec))
274aff52e68SYiFei Zhu 		goto out_free;
275aff52e68SYiFei Zhu 
276aff52e68SYiFei Zhu 	vlen = btf_vlen(t_datasec);
277aff52e68SYiFei Zhu 	vsi = btf_var_secinfos(t_datasec);
278aff52e68SYiFei Zhu 
279aff52e68SYiFei Zhu 	/* We don't proceed to check the kinds of the elements of the DATASEC.
280aff52e68SYiFei Zhu 	 * The verifier enforces them to be BTF_KIND_VAR.
281aff52e68SYiFei Zhu 	 */
282aff52e68SYiFei Zhu 
283aff52e68SYiFei Zhu 	if (json_output) {
284aff52e68SYiFei Zhu 		struct btf_dumper d = {
285aff52e68SYiFei Zhu 			.btf = btf,
286aff52e68SYiFei Zhu 			.jw = json_wtr,
287aff52e68SYiFei Zhu 			.is_plain_text = false,
288aff52e68SYiFei Zhu 		};
289aff52e68SYiFei Zhu 
290aff52e68SYiFei Zhu 		for (i = 0; i < vlen; i++, vsi++) {
291aff52e68SYiFei Zhu 			t_var = btf__type_by_id(btf, vsi->type);
292aff52e68SYiFei Zhu 			name = btf__name_by_offset(btf, t_var->name_off);
293aff52e68SYiFei Zhu 
294aff52e68SYiFei Zhu 			if (!has_metadata_prefix(name))
295aff52e68SYiFei Zhu 				continue;
296aff52e68SYiFei Zhu 
297aff52e68SYiFei Zhu 			if (!printed_header) {
298aff52e68SYiFei Zhu 				jsonw_name(json_wtr, "metadata");
299aff52e68SYiFei Zhu 				jsonw_start_object(json_wtr);
300aff52e68SYiFei Zhu 				printed_header = true;
301aff52e68SYiFei Zhu 			}
302aff52e68SYiFei Zhu 
303aff52e68SYiFei Zhu 			jsonw_name(json_wtr, name + BPF_METADATA_PREFIX_LEN);
304aff52e68SYiFei Zhu 			err = btf_dumper_type(&d, t_var->type, value + vsi->offset);
305aff52e68SYiFei Zhu 			if (err) {
306aff52e68SYiFei Zhu 				p_err("btf dump failed: %d", err);
307aff52e68SYiFei Zhu 				break;
308aff52e68SYiFei Zhu 			}
309aff52e68SYiFei Zhu 		}
310aff52e68SYiFei Zhu 		if (printed_header)
311aff52e68SYiFei Zhu 			jsonw_end_object(json_wtr);
312aff52e68SYiFei Zhu 	} else {
313e89ef634SQuentin Monnet 		json_writer_t *btf_wtr;
314aff52e68SYiFei Zhu 		struct btf_dumper d = {
315aff52e68SYiFei Zhu 			.btf = btf,
316aff52e68SYiFei Zhu 			.is_plain_text = true,
317aff52e68SYiFei Zhu 		};
318aff52e68SYiFei Zhu 
319aff52e68SYiFei Zhu 		for (i = 0; i < vlen; i++, vsi++) {
320aff52e68SYiFei Zhu 			t_var = btf__type_by_id(btf, vsi->type);
321aff52e68SYiFei Zhu 			name = btf__name_by_offset(btf, t_var->name_off);
322aff52e68SYiFei Zhu 
323aff52e68SYiFei Zhu 			if (!has_metadata_prefix(name))
324aff52e68SYiFei Zhu 				continue;
325aff52e68SYiFei Zhu 
326aff52e68SYiFei Zhu 			if (!printed_header) {
327aff52e68SYiFei Zhu 				printf("\tmetadata:");
328e89ef634SQuentin Monnet 
329e89ef634SQuentin Monnet 				btf_wtr = jsonw_new(stdout);
330e89ef634SQuentin Monnet 				if (!btf_wtr) {
331e89ef634SQuentin Monnet 					p_err("jsonw alloc failed");
332e89ef634SQuentin Monnet 					goto out_free;
333e89ef634SQuentin Monnet 				}
334e89ef634SQuentin Monnet 				d.jw = btf_wtr,
335e89ef634SQuentin Monnet 
336aff52e68SYiFei Zhu 				printed_header = true;
337aff52e68SYiFei Zhu 			}
338aff52e68SYiFei Zhu 
339aff52e68SYiFei Zhu 			printf("\n\t\t%s = ", name + BPF_METADATA_PREFIX_LEN);
340aff52e68SYiFei Zhu 
341aff52e68SYiFei Zhu 			jsonw_reset(btf_wtr);
342aff52e68SYiFei Zhu 			err = btf_dumper_type(&d, t_var->type, value + vsi->offset);
343aff52e68SYiFei Zhu 			if (err) {
344aff52e68SYiFei Zhu 				p_err("btf dump failed: %d", err);
345aff52e68SYiFei Zhu 				break;
346aff52e68SYiFei Zhu 			}
347aff52e68SYiFei Zhu 		}
348aff52e68SYiFei Zhu 		if (printed_header)
349aff52e68SYiFei Zhu 			jsonw_destroy(&btf_wtr);
350aff52e68SYiFei Zhu 	}
351aff52e68SYiFei Zhu 
352aff52e68SYiFei Zhu out_free:
353aff52e68SYiFei Zhu 	btf__free(btf);
354aff52e68SYiFei Zhu 	free(value);
355aff52e68SYiFei Zhu }
356aff52e68SYiFei Zhu 
357ec202509SPaul Chaignon static void print_prog_header_json(struct bpf_prog_info *info)
358743cc665SQuentin Monnet {
359743cc665SQuentin Monnet 	jsonw_uint_field(json_wtr, "id", info->id);
360743cc665SQuentin Monnet 	if (info->type < ARRAY_SIZE(prog_type_name))
361743cc665SQuentin Monnet 		jsonw_string_field(json_wtr, "type",
362743cc665SQuentin Monnet 				   prog_type_name[info->type]);
36371bb428fSJakub Kicinski 	else
364743cc665SQuentin Monnet 		jsonw_uint_field(json_wtr, "type", info->type);
36571bb428fSJakub Kicinski 
366743cc665SQuentin Monnet 	if (*info->name)
367743cc665SQuentin Monnet 		jsonw_string_field(json_wtr, "name", info->name);
36871bb428fSJakub Kicinski 
369743cc665SQuentin Monnet 	jsonw_name(json_wtr, "tag");
370743cc665SQuentin Monnet 	jsonw_printf(json_wtr, "\"" BPF_TAG_FMT "\"",
371743cc665SQuentin Monnet 		     info->tag[0], info->tag[1], info->tag[2], info->tag[3],
372743cc665SQuentin Monnet 		     info->tag[4], info->tag[5], info->tag[6], info->tag[7]);
37371bb428fSJakub Kicinski 
3749b984a20SJiri Olsa 	jsonw_bool_field(json_wtr, "gpl_compatible", info->gpl_compatible);
37588ad472bSAlexei Starovoitov 	if (info->run_time_ns) {
37688ad472bSAlexei Starovoitov 		jsonw_uint_field(json_wtr, "run_time_ns", info->run_time_ns);
37788ad472bSAlexei Starovoitov 		jsonw_uint_field(json_wtr, "run_cnt", info->run_cnt);
37888ad472bSAlexei Starovoitov 	}
3799ed9e9baSAlexei Starovoitov 	if (info->recursion_misses)
3809ed9e9baSAlexei Starovoitov 		jsonw_uint_field(json_wtr, "recursion_misses", info->recursion_misses);
381ec202509SPaul Chaignon }
3829b984a20SJiri Olsa 
383ec202509SPaul Chaignon static void print_prog_json(struct bpf_prog_info *info, int fd)
384ec202509SPaul Chaignon {
385ec202509SPaul Chaignon 	char *memlock;
386ec202509SPaul Chaignon 
387ec202509SPaul Chaignon 	jsonw_start_object(json_wtr);
388ec202509SPaul Chaignon 	print_prog_header_json(info);
38952262210SJakub Kicinski 	print_dev_json(info->ifindex, info->netns_dev, info->netns_ino);
39052262210SJakub Kicinski 
391743cc665SQuentin Monnet 	if (info->load_time) {
39271bb428fSJakub Kicinski 		char buf[32];
39371bb428fSJakub Kicinski 
394743cc665SQuentin Monnet 		print_boot_time(info->load_time, buf, sizeof(buf));
39571bb428fSJakub Kicinski 
39671bb428fSJakub Kicinski 		/* Piggy back on load_time, since 0 uid is a valid one */
397a3fe1f6fSQuentin Monnet 		jsonw_name(json_wtr, "loaded_at");
398a3fe1f6fSQuentin Monnet 		jsonw_printf(json_wtr, "%s", buf);
399743cc665SQuentin Monnet 		jsonw_uint_field(json_wtr, "uid", info->created_by_uid);
40071bb428fSJakub Kicinski 	}
40171bb428fSJakub Kicinski 
402743cc665SQuentin Monnet 	jsonw_uint_field(json_wtr, "bytes_xlated", info->xlated_prog_len);
40371bb428fSJakub Kicinski 
404743cc665SQuentin Monnet 	if (info->jited_prog_len) {
405743cc665SQuentin Monnet 		jsonw_bool_field(json_wtr, "jited", true);
406743cc665SQuentin Monnet 		jsonw_uint_field(json_wtr, "bytes_jited", info->jited_prog_len);
407743cc665SQuentin Monnet 	} else {
408743cc665SQuentin Monnet 		jsonw_bool_field(json_wtr, "jited", false);
409743cc665SQuentin Monnet 	}
410743cc665SQuentin Monnet 
411743cc665SQuentin Monnet 	memlock = get_fdinfo(fd, "memlock");
412743cc665SQuentin Monnet 	if (memlock)
413743cc665SQuentin Monnet 		jsonw_int_field(json_wtr, "bytes_memlock", atoi(memlock));
414743cc665SQuentin Monnet 	free(memlock);
415743cc665SQuentin Monnet 
416743cc665SQuentin Monnet 	if (info->nr_map_ids)
417743cc665SQuentin Monnet 		show_prog_maps(fd, info->nr_map_ids);
418743cc665SQuentin Monnet 
419569b0c77SPrashant Bhole 	if (info->btf_id)
420569b0c77SPrashant Bhole 		jsonw_int_field(json_wtr, "btf_id", info->btf_id);
421569b0c77SPrashant Bhole 
422*8f184732SQuentin Monnet 	if (!hashmap__empty(prog_table)) {
423*8f184732SQuentin Monnet 		struct hashmap_entry *entry;
4244990f1f4SPrashant Bhole 
4254990f1f4SPrashant Bhole 		jsonw_name(json_wtr, "pinned");
4264990f1f4SPrashant Bhole 		jsonw_start_array(json_wtr);
427*8f184732SQuentin Monnet 		hashmap__for_each_key_entry(prog_table, entry,
428*8f184732SQuentin Monnet 					    u32_as_hash_field(info->id))
429*8f184732SQuentin Monnet 			jsonw_string(json_wtr, entry->value);
4304990f1f4SPrashant Bhole 		jsonw_end_array(json_wtr);
4314990f1f4SPrashant Bhole 	}
4324990f1f4SPrashant Bhole 
433d53dee3fSAndrii Nakryiko 	emit_obj_refs_json(&refs_table, info->id, json_wtr);
434d53dee3fSAndrii Nakryiko 
435aff52e68SYiFei Zhu 	show_prog_metadata(fd, info->nr_map_ids);
436aff52e68SYiFei Zhu 
437743cc665SQuentin Monnet 	jsonw_end_object(json_wtr);
438743cc665SQuentin Monnet }
439743cc665SQuentin Monnet 
440ec202509SPaul Chaignon static void print_prog_header_plain(struct bpf_prog_info *info)
441743cc665SQuentin Monnet {
442743cc665SQuentin Monnet 	printf("%u: ", info->id);
443743cc665SQuentin Monnet 	if (info->type < ARRAY_SIZE(prog_type_name))
444743cc665SQuentin Monnet 		printf("%s  ", prog_type_name[info->type]);
445743cc665SQuentin Monnet 	else
446743cc665SQuentin Monnet 		printf("type %u  ", info->type);
447743cc665SQuentin Monnet 
448743cc665SQuentin Monnet 	if (*info->name)
449743cc665SQuentin Monnet 		printf("name %s  ", info->name);
450743cc665SQuentin Monnet 
451743cc665SQuentin Monnet 	printf("tag ");
452743cc665SQuentin Monnet 	fprint_hex(stdout, info->tag, BPF_TAG_SIZE, "");
45352262210SJakub Kicinski 	print_dev_plain(info->ifindex, info->netns_dev, info->netns_ino);
4549b984a20SJiri Olsa 	printf("%s", info->gpl_compatible ? "  gpl" : "");
45588ad472bSAlexei Starovoitov 	if (info->run_time_ns)
45688ad472bSAlexei Starovoitov 		printf(" run_time_ns %lld run_cnt %lld",
45788ad472bSAlexei Starovoitov 		       info->run_time_ns, info->run_cnt);
4589ed9e9baSAlexei Starovoitov 	if (info->recursion_misses)
4599ed9e9baSAlexei Starovoitov 		printf(" recursion_misses %lld", info->recursion_misses);
460743cc665SQuentin Monnet 	printf("\n");
461ec202509SPaul Chaignon }
462ec202509SPaul Chaignon 
463ec202509SPaul Chaignon static void print_prog_plain(struct bpf_prog_info *info, int fd)
464ec202509SPaul Chaignon {
465ec202509SPaul Chaignon 	char *memlock;
466ec202509SPaul Chaignon 
467ec202509SPaul Chaignon 	print_prog_header_plain(info);
468743cc665SQuentin Monnet 
469743cc665SQuentin Monnet 	if (info->load_time) {
470743cc665SQuentin Monnet 		char buf[32];
471743cc665SQuentin Monnet 
472743cc665SQuentin Monnet 		print_boot_time(info->load_time, buf, sizeof(buf));
473743cc665SQuentin Monnet 
474743cc665SQuentin Monnet 		/* Piggy back on load_time, since 0 uid is a valid one */
475743cc665SQuentin Monnet 		printf("\tloaded_at %s  uid %u\n", buf, info->created_by_uid);
476743cc665SQuentin Monnet 	}
477743cc665SQuentin Monnet 
478743cc665SQuentin Monnet 	printf("\txlated %uB", info->xlated_prog_len);
479743cc665SQuentin Monnet 
480743cc665SQuentin Monnet 	if (info->jited_prog_len)
481743cc665SQuentin Monnet 		printf("  jited %uB", info->jited_prog_len);
48271bb428fSJakub Kicinski 	else
48371bb428fSJakub Kicinski 		printf("  not jited");
48471bb428fSJakub Kicinski 
48571bb428fSJakub Kicinski 	memlock = get_fdinfo(fd, "memlock");
48671bb428fSJakub Kicinski 	if (memlock)
48771bb428fSJakub Kicinski 		printf("  memlock %sB", memlock);
48871bb428fSJakub Kicinski 	free(memlock);
48971bb428fSJakub Kicinski 
490743cc665SQuentin Monnet 	if (info->nr_map_ids)
491743cc665SQuentin Monnet 		show_prog_maps(fd, info->nr_map_ids);
49271bb428fSJakub Kicinski 
493*8f184732SQuentin Monnet 	if (!hashmap__empty(prog_table)) {
494*8f184732SQuentin Monnet 		struct hashmap_entry *entry;
4954990f1f4SPrashant Bhole 
496*8f184732SQuentin Monnet 		hashmap__for_each_key_entry(prog_table, entry,
497*8f184732SQuentin Monnet 					    u32_as_hash_field(info->id))
498*8f184732SQuentin Monnet 			printf("\n\tpinned %s", (char *)entry->value);
4994990f1f4SPrashant Bhole 	}
5004990f1f4SPrashant Bhole 
501569b0c77SPrashant Bhole 	if (info->btf_id)
502031ebc1aSQuentin Monnet 		printf("\n\tbtf_id %d", info->btf_id);
503569b0c77SPrashant Bhole 
504d53dee3fSAndrii Nakryiko 	emit_obj_refs_plain(&refs_table, info->id, "\n\tpids ");
505d53dee3fSAndrii Nakryiko 
50671bb428fSJakub Kicinski 	printf("\n");
507aff52e68SYiFei Zhu 
508aff52e68SYiFei Zhu 	show_prog_metadata(fd, info->nr_map_ids);
509743cc665SQuentin Monnet }
510743cc665SQuentin Monnet 
511743cc665SQuentin Monnet static int show_prog(int fd)
512743cc665SQuentin Monnet {
513743cc665SQuentin Monnet 	struct bpf_prog_info info = {};
514743cc665SQuentin Monnet 	__u32 len = sizeof(info);
515743cc665SQuentin Monnet 	int err;
516743cc665SQuentin Monnet 
517743cc665SQuentin Monnet 	err = bpf_obj_get_info_by_fd(fd, &info, &len);
518743cc665SQuentin Monnet 	if (err) {
5199a5ab8bfSQuentin Monnet 		p_err("can't get prog info: %s", strerror(errno));
520743cc665SQuentin Monnet 		return -1;
521743cc665SQuentin Monnet 	}
522743cc665SQuentin Monnet 
523743cc665SQuentin Monnet 	if (json_output)
524743cc665SQuentin Monnet 		print_prog_json(&info, fd);
525743cc665SQuentin Monnet 	else
526743cc665SQuentin Monnet 		print_prog_plain(&info, fd);
52771bb428fSJakub Kicinski 
52871bb428fSJakub Kicinski 	return 0;
52971bb428fSJakub Kicinski }
53071bb428fSJakub Kicinski 
531ec202509SPaul Chaignon static int do_show_subset(int argc, char **argv)
532ec202509SPaul Chaignon {
533ec202509SPaul Chaignon 	int *fds = NULL;
534ec202509SPaul Chaignon 	int nb_fds, i;
535ec202509SPaul Chaignon 	int err = -1;
536ec202509SPaul Chaignon 
537ec202509SPaul Chaignon 	fds = malloc(sizeof(int));
538ec202509SPaul Chaignon 	if (!fds) {
539ec202509SPaul Chaignon 		p_err("mem alloc failed");
540ec202509SPaul Chaignon 		return -1;
541ec202509SPaul Chaignon 	}
542ec202509SPaul Chaignon 	nb_fds = prog_parse_fds(&argc, &argv, &fds);
543ec202509SPaul Chaignon 	if (nb_fds < 1)
544ec202509SPaul Chaignon 		goto exit_free;
545ec202509SPaul Chaignon 
546ec202509SPaul Chaignon 	if (json_output && nb_fds > 1)
547ec202509SPaul Chaignon 		jsonw_start_array(json_wtr);	/* root array */
548ec202509SPaul Chaignon 	for (i = 0; i < nb_fds; i++) {
549ec202509SPaul Chaignon 		err = show_prog(fds[i]);
550ec202509SPaul Chaignon 		if (err) {
551ec202509SPaul Chaignon 			for (; i < nb_fds; i++)
552ec202509SPaul Chaignon 				close(fds[i]);
553ec202509SPaul Chaignon 			break;
554ec202509SPaul Chaignon 		}
555ec202509SPaul Chaignon 		close(fds[i]);
556ec202509SPaul Chaignon 	}
557ec202509SPaul Chaignon 	if (json_output && nb_fds > 1)
558ec202509SPaul Chaignon 		jsonw_end_array(json_wtr);	/* root array */
559ec202509SPaul Chaignon 
560ec202509SPaul Chaignon exit_free:
561ec202509SPaul Chaignon 	free(fds);
562ec202509SPaul Chaignon 	return err;
563ec202509SPaul Chaignon }
564ec202509SPaul Chaignon 
56571bb428fSJakub Kicinski static int do_show(int argc, char **argv)
566743cc665SQuentin Monnet {
567743cc665SQuentin Monnet 	__u32 id = 0;
56871bb428fSJakub Kicinski 	int err;
56971bb428fSJakub Kicinski 	int fd;
57071bb428fSJakub Kicinski 
57146241271SQuentin Monnet 	if (show_pinned) {
572*8f184732SQuentin Monnet 		prog_table = hashmap__new(hash_fn_for_key_as_id,
573*8f184732SQuentin Monnet 					  equal_fn_for_key_as_id, NULL);
574*8f184732SQuentin Monnet 		if (!prog_table) {
575*8f184732SQuentin Monnet 			p_err("failed to create hashmap for pinned paths");
576*8f184732SQuentin Monnet 			return -1;
577*8f184732SQuentin Monnet 		}
578*8f184732SQuentin Monnet 		build_pinned_obj_table(prog_table, BPF_OBJ_PROG);
57946241271SQuentin Monnet 	}
580d53dee3fSAndrii Nakryiko 	build_obj_refs_table(&refs_table, BPF_OBJ_PROG);
5814990f1f4SPrashant Bhole 
582ec202509SPaul Chaignon 	if (argc == 2)
583ec202509SPaul Chaignon 		return do_show_subset(argc, argv);
58471bb428fSJakub Kicinski 
58571bb428fSJakub Kicinski 	if (argc)
58671bb428fSJakub Kicinski 		return BAD_ARG();
58771bb428fSJakub Kicinski 
588743cc665SQuentin Monnet 	if (json_output)
589743cc665SQuentin Monnet 		jsonw_start_array(json_wtr);
59071bb428fSJakub Kicinski 	while (true) {
59171bb428fSJakub Kicinski 		err = bpf_prog_get_next_id(id, &id);
59271bb428fSJakub Kicinski 		if (err) {
5931739c26dSQuentin Monnet 			if (errno == ENOENT) {
5941739c26dSQuentin Monnet 				err = 0;
59571bb428fSJakub Kicinski 				break;
5961739c26dSQuentin Monnet 			}
5979a5ab8bfSQuentin Monnet 			p_err("can't get next program: %s%s", strerror(errno),
5989a5ab8bfSQuentin Monnet 			      errno == EINVAL ? " -- kernel too old?" : "");
599743cc665SQuentin Monnet 			err = -1;
600743cc665SQuentin Monnet 			break;
60171bb428fSJakub Kicinski 		}
60271bb428fSJakub Kicinski 
60371bb428fSJakub Kicinski 		fd = bpf_prog_get_fd_by_id(id);
60471bb428fSJakub Kicinski 		if (fd < 0) {
6058207c6ddSJakub Kicinski 			if (errno == ENOENT)
6068207c6ddSJakub Kicinski 				continue;
6079a5ab8bfSQuentin Monnet 			p_err("can't get prog by id (%u): %s",
60871bb428fSJakub Kicinski 			      id, strerror(errno));
609743cc665SQuentin Monnet 			err = -1;
610743cc665SQuentin Monnet 			break;
61171bb428fSJakub Kicinski 		}
61271bb428fSJakub Kicinski 
61371bb428fSJakub Kicinski 		err = show_prog(fd);
61471bb428fSJakub Kicinski 		close(fd);
61571bb428fSJakub Kicinski 		if (err)
616743cc665SQuentin Monnet 			break;
61771bb428fSJakub Kicinski 	}
61871bb428fSJakub Kicinski 
619743cc665SQuentin Monnet 	if (json_output)
620743cc665SQuentin Monnet 		jsonw_end_array(json_wtr);
621743cc665SQuentin Monnet 
622d53dee3fSAndrii Nakryiko 	delete_obj_refs_table(&refs_table);
623d53dee3fSAndrii Nakryiko 
62446241271SQuentin Monnet 	if (show_pinned)
625*8f184732SQuentin Monnet 		delete_pinned_obj_table(prog_table);
62646241271SQuentin Monnet 
627743cc665SQuentin Monnet 	return err;
62871bb428fSJakub Kicinski }
62971bb428fSJakub Kicinski 
630ec202509SPaul Chaignon static int
631ec202509SPaul Chaignon prog_dump(struct bpf_prog_info *info, enum dump_mode mode,
632ec202509SPaul Chaignon 	  char *filepath, bool opcodes, bool visual, bool linum)
63371bb428fSJakub Kicinski {
634b053b439SMartin KaFai Lau 	struct bpf_prog_linfo *prog_linfo = NULL;
6353ddeac67SJakub Kicinski 	const char *disasm_opt = NULL;
6367105e828SDaniel Borkmann 	struct dump_data dd = {};
637cae73f23SSong Liu 	void *func_info = NULL;
638254471e5SYonghong Song 	struct btf *btf = NULL;
639254471e5SYonghong Song 	char func_sig[1024];
64071bb428fSJakub Kicinski 	unsigned char *buf;
641cae73f23SSong Liu 	__u32 member_len;
64271bb428fSJakub Kicinski 	ssize_t n;
64371bb428fSJakub Kicinski 	int fd;
64471bb428fSJakub Kicinski 
645cae73f23SSong Liu 	if (mode == DUMP_JITED) {
6465b79bcdfSToke Høiland-Jørgensen 		if (info->jited_prog_len == 0 || !info->jited_prog_insns) {
6479a5ab8bfSQuentin Monnet 			p_info("no instructions returned");
648ec202509SPaul Chaignon 			return -1;
649f84192eeSSandipan Das 		}
65009f44b75SAndrii Nakryiko 		buf = u64_to_ptr(info->jited_prog_insns);
651cae73f23SSong Liu 		member_len = info->jited_prog_len;
652cae73f23SSong Liu 	} else {	/* DUMP_XLATED */
653d95f1e8bSToke Høiland-Jørgensen 		if (info->xlated_prog_len == 0 || !info->xlated_prog_insns) {
6547105e828SDaniel Borkmann 			p_err("error retrieving insn dump: kernel.kptr_restrict set?");
655ec202509SPaul Chaignon 			return -1;
6567105e828SDaniel Borkmann 		}
65709f44b75SAndrii Nakryiko 		buf = u64_to_ptr(info->xlated_prog_insns);
658cae73f23SSong Liu 		member_len = info->xlated_prog_len;
659cae73f23SSong Liu 	}
6607105e828SDaniel Borkmann 
66186f4b7f2SQuentin Monnet 	if (info->btf_id) {
66286f4b7f2SQuentin Monnet 		btf = btf__load_from_kernel_by_id(info->btf_id);
66386f4b7f2SQuentin Monnet 		if (libbpf_get_error(btf)) {
664254471e5SYonghong Song 			p_err("failed to get btf");
665ec202509SPaul Chaignon 			return -1;
666254471e5SYonghong Song 		}
66786f4b7f2SQuentin Monnet 	}
668254471e5SYonghong Song 
66909f44b75SAndrii Nakryiko 	func_info = u64_to_ptr(info->func_info);
670cae73f23SSong Liu 
671cae73f23SSong Liu 	if (info->nr_line_info) {
672cae73f23SSong Liu 		prog_linfo = bpf_prog_linfo__new(info);
673b053b439SMartin KaFai Lau 		if (!prog_linfo)
67410a5ce98SMartin KaFai Lau 			p_info("error in processing bpf_line_info.  continue without it.");
675b053b439SMartin KaFai Lau 	}
676b053b439SMartin KaFai Lau 
67771bb428fSJakub Kicinski 	if (filepath) {
67871bb428fSJakub Kicinski 		fd = open(filepath, O_WRONLY | O_CREAT | O_TRUNC, 0600);
67971bb428fSJakub Kicinski 		if (fd < 0) {
6809a5ab8bfSQuentin Monnet 			p_err("can't open file %s: %s", filepath,
68171bb428fSJakub Kicinski 			      strerror(errno));
682ec202509SPaul Chaignon 			return -1;
68371bb428fSJakub Kicinski 		}
68471bb428fSJakub Kicinski 
685cae73f23SSong Liu 		n = write(fd, buf, member_len);
68671bb428fSJakub Kicinski 		close(fd);
68709f44b75SAndrii Nakryiko 		if (n != (ssize_t)member_len) {
6889a5ab8bfSQuentin Monnet 			p_err("error writing output file: %s",
68971bb428fSJakub Kicinski 			      n < 0 ? strerror(errno) : "short write");
690ec202509SPaul Chaignon 			return -1;
69171bb428fSJakub Kicinski 		}
69252c84d36SQuentin Monnet 
69352c84d36SQuentin Monnet 		if (json_output)
69452c84d36SQuentin Monnet 			jsonw_null(json_wtr);
695cae73f23SSong Liu 	} else if (mode == DUMP_JITED) {
696e6593596SJiong Wang 		const char *name = NULL;
697e6593596SJiong Wang 
698cae73f23SSong Liu 		if (info->ifindex) {
699cae73f23SSong Liu 			name = ifindex_to_bfd_params(info->ifindex,
700cae73f23SSong Liu 						     info->netns_dev,
701cae73f23SSong Liu 						     info->netns_ino,
7023ddeac67SJakub Kicinski 						     &disasm_opt);
703e6593596SJiong Wang 			if (!name)
704ec202509SPaul Chaignon 				return -1;
705e6593596SJiong Wang 		}
706e6593596SJiong Wang 
707cae73f23SSong Liu 		if (info->nr_jited_func_lens && info->jited_func_lens) {
708f7f62c71SSandipan Das 			struct kernel_sym *sym = NULL;
709254471e5SYonghong Song 			struct bpf_func_info *record;
710f7f62c71SSandipan Das 			char sym_name[SYM_MAX_NAME];
711f7f62c71SSandipan Das 			unsigned char *img = buf;
712f7f62c71SSandipan Das 			__u64 *ksyms = NULL;
713f7f62c71SSandipan Das 			__u32 *lens;
714f7f62c71SSandipan Das 			__u32 i;
715cae73f23SSong Liu 			if (info->nr_jited_ksyms) {
716f7f62c71SSandipan Das 				kernel_syms_load(&dd);
71709f44b75SAndrii Nakryiko 				ksyms = u64_to_ptr(info->jited_ksyms);
718f7f62c71SSandipan Das 			}
719f7f62c71SSandipan Das 
720f7f62c71SSandipan Das 			if (json_output)
721f7f62c71SSandipan Das 				jsonw_start_array(json_wtr);
722f7f62c71SSandipan Das 
72309f44b75SAndrii Nakryiko 			lens = u64_to_ptr(info->jited_func_lens);
724cae73f23SSong Liu 			for (i = 0; i < info->nr_jited_func_lens; i++) {
725f7f62c71SSandipan Das 				if (ksyms) {
726f7f62c71SSandipan Das 					sym = kernel_syms_search(&dd, ksyms[i]);
727f7f62c71SSandipan Das 					if (sym)
728f7f62c71SSandipan Das 						sprintf(sym_name, "%s", sym->name);
729f7f62c71SSandipan Das 					else
730f7f62c71SSandipan Das 						sprintf(sym_name, "0x%016llx", ksyms[i]);
731f7f62c71SSandipan Das 				} else {
732f7f62c71SSandipan Das 					strcpy(sym_name, "unknown");
733f7f62c71SSandipan Das 				}
734f7f62c71SSandipan Das 
735254471e5SYonghong Song 				if (func_info) {
736cae73f23SSong Liu 					record = func_info + i * info->func_info_rec_size;
737254471e5SYonghong Song 					btf_dumper_type_only(btf, record->type_id,
738254471e5SYonghong Song 							     func_sig,
739254471e5SYonghong Song 							     sizeof(func_sig));
740254471e5SYonghong Song 				}
741254471e5SYonghong Song 
742f7f62c71SSandipan Das 				if (json_output) {
743f7f62c71SSandipan Das 					jsonw_start_object(json_wtr);
744254471e5SYonghong Song 					if (func_info && func_sig[0] != '\0') {
745254471e5SYonghong Song 						jsonw_name(json_wtr, "proto");
746254471e5SYonghong Song 						jsonw_string(json_wtr, func_sig);
747254471e5SYonghong Song 					}
748f7f62c71SSandipan Das 					jsonw_name(json_wtr, "name");
749f7f62c71SSandipan Das 					jsonw_string(json_wtr, sym_name);
750f7f62c71SSandipan Das 					jsonw_name(json_wtr, "insns");
751f7f62c71SSandipan Das 				} else {
752254471e5SYonghong Song 					if (func_info && func_sig[0] != '\0')
753254471e5SYonghong Song 						printf("%s:\n", func_sig);
754f7f62c71SSandipan Das 					printf("%s:\n", sym_name);
755f7f62c71SSandipan Das 				}
756f7f62c71SSandipan Das 
757b053b439SMartin KaFai Lau 				disasm_print_insn(img, lens[i], opcodes,
758b053b439SMartin KaFai Lau 						  name, disasm_opt, btf,
759b053b439SMartin KaFai Lau 						  prog_linfo, ksyms[i], i,
760b053b439SMartin KaFai Lau 						  linum);
761b053b439SMartin KaFai Lau 
762f7f62c71SSandipan Das 				img += lens[i];
763f7f62c71SSandipan Das 
764f7f62c71SSandipan Das 				if (json_output)
765f7f62c71SSandipan Das 					jsonw_end_object(json_wtr);
766f7f62c71SSandipan Das 				else
767f7f62c71SSandipan Das 					printf("\n");
768f7f62c71SSandipan Das 			}
769f7f62c71SSandipan Das 
770f7f62c71SSandipan Das 			if (json_output)
771f7f62c71SSandipan Das 				jsonw_end_array(json_wtr);
772f7f62c71SSandipan Das 		} else {
773cae73f23SSong Liu 			disasm_print_insn(buf, member_len, opcodes, name,
774b053b439SMartin KaFai Lau 					  disasm_opt, btf, NULL, 0, 0, false);
775f7f62c71SSandipan Das 		}
776b6c1cedbSJiong Wang 	} else if (visual) {
777b6c1cedbSJiong Wang 		if (json_output)
778b6c1cedbSJiong Wang 			jsonw_null(json_wtr);
779b6c1cedbSJiong Wang 		else
780cae73f23SSong Liu 			dump_xlated_cfg(buf, member_len);
7817105e828SDaniel Borkmann 	} else {
7827105e828SDaniel Borkmann 		kernel_syms_load(&dd);
783cae73f23SSong Liu 		dd.nr_jited_ksyms = info->nr_jited_ksyms;
78409f44b75SAndrii Nakryiko 		dd.jited_ksyms = u64_to_ptr(info->jited_ksyms);
785254471e5SYonghong Song 		dd.btf = btf;
786254471e5SYonghong Song 		dd.func_info = func_info;
787cae73f23SSong Liu 		dd.finfo_rec_size = info->func_info_rec_size;
788b053b439SMartin KaFai Lau 		dd.prog_linfo = prog_linfo;
789f84192eeSSandipan Das 
790f05e2c32SQuentin Monnet 		if (json_output)
791cae73f23SSong Liu 			dump_xlated_json(&dd, buf, member_len, opcodes,
792b053b439SMartin KaFai Lau 					 linum);
793f05e2c32SQuentin Monnet 		else
794cae73f23SSong Liu 			dump_xlated_plain(&dd, buf, member_len, opcodes,
795b053b439SMartin KaFai Lau 					  linum);
7967105e828SDaniel Borkmann 		kernel_syms_destroy(&dd);
7977105e828SDaniel Borkmann 	}
79871bb428fSJakub Kicinski 
799369e955bSQuentin Monnet 	btf__free(btf);
800369e955bSQuentin Monnet 
80171bb428fSJakub Kicinski 	return 0;
802ec202509SPaul Chaignon }
80371bb428fSJakub Kicinski 
804ec202509SPaul Chaignon static int do_dump(int argc, char **argv)
805ec202509SPaul Chaignon {
806ec202509SPaul Chaignon 	struct bpf_prog_info_linear *info_linear;
807ec202509SPaul Chaignon 	char *filepath = NULL;
808ec202509SPaul Chaignon 	bool opcodes = false;
809ec202509SPaul Chaignon 	bool visual = false;
810ec202509SPaul Chaignon 	enum dump_mode mode;
811ec202509SPaul Chaignon 	bool linum = false;
812ec202509SPaul Chaignon 	int *fds = NULL;
813ec202509SPaul Chaignon 	int nb_fds, i = 0;
814ec202509SPaul Chaignon 	int err = -1;
815ec202509SPaul Chaignon 	__u64 arrays;
816ec202509SPaul Chaignon 
817ec202509SPaul Chaignon 	if (is_prefix(*argv, "jited")) {
818ec202509SPaul Chaignon 		if (disasm_init())
81971bb428fSJakub Kicinski 			return -1;
820ec202509SPaul Chaignon 		mode = DUMP_JITED;
821ec202509SPaul Chaignon 	} else if (is_prefix(*argv, "xlated")) {
822ec202509SPaul Chaignon 		mode = DUMP_XLATED;
823ec202509SPaul Chaignon 	} else {
824ec202509SPaul Chaignon 		p_err("expected 'xlated' or 'jited', got: %s", *argv);
825ec202509SPaul Chaignon 		return -1;
826ec202509SPaul Chaignon 	}
827ec202509SPaul Chaignon 	NEXT_ARG();
828ec202509SPaul Chaignon 
829ec202509SPaul Chaignon 	if (argc < 2)
830ec202509SPaul Chaignon 		usage();
831ec202509SPaul Chaignon 
832ec202509SPaul Chaignon 	fds = malloc(sizeof(int));
833ec202509SPaul Chaignon 	if (!fds) {
834ec202509SPaul Chaignon 		p_err("mem alloc failed");
835ec202509SPaul Chaignon 		return -1;
836ec202509SPaul Chaignon 	}
837ec202509SPaul Chaignon 	nb_fds = prog_parse_fds(&argc, &argv, &fds);
838ec202509SPaul Chaignon 	if (nb_fds < 1)
839ec202509SPaul Chaignon 		goto exit_free;
840ec202509SPaul Chaignon 
841ec202509SPaul Chaignon 	if (is_prefix(*argv, "file")) {
842ec202509SPaul Chaignon 		NEXT_ARG();
843ec202509SPaul Chaignon 		if (!argc) {
844ec202509SPaul Chaignon 			p_err("expected file path");
845ec202509SPaul Chaignon 			goto exit_close;
846ec202509SPaul Chaignon 		}
847ec202509SPaul Chaignon 		if (nb_fds > 1) {
848ec202509SPaul Chaignon 			p_err("several programs matched");
849ec202509SPaul Chaignon 			goto exit_close;
850ec202509SPaul Chaignon 		}
851ec202509SPaul Chaignon 
852ec202509SPaul Chaignon 		filepath = *argv;
853ec202509SPaul Chaignon 		NEXT_ARG();
854ec202509SPaul Chaignon 	} else if (is_prefix(*argv, "opcodes")) {
855ec202509SPaul Chaignon 		opcodes = true;
856ec202509SPaul Chaignon 		NEXT_ARG();
857ec202509SPaul Chaignon 	} else if (is_prefix(*argv, "visual")) {
858ec202509SPaul Chaignon 		if (nb_fds > 1) {
859ec202509SPaul Chaignon 			p_err("several programs matched");
860ec202509SPaul Chaignon 			goto exit_close;
861ec202509SPaul Chaignon 		}
862ec202509SPaul Chaignon 
863ec202509SPaul Chaignon 		visual = true;
864ec202509SPaul Chaignon 		NEXT_ARG();
865ec202509SPaul Chaignon 	} else if (is_prefix(*argv, "linum")) {
866ec202509SPaul Chaignon 		linum = true;
867ec202509SPaul Chaignon 		NEXT_ARG();
868ec202509SPaul Chaignon 	}
869ec202509SPaul Chaignon 
870ec202509SPaul Chaignon 	if (argc) {
871ec202509SPaul Chaignon 		usage();
872ec202509SPaul Chaignon 		goto exit_close;
873ec202509SPaul Chaignon 	}
874ec202509SPaul Chaignon 
875ec202509SPaul Chaignon 	if (mode == DUMP_JITED)
876ec202509SPaul Chaignon 		arrays = 1UL << BPF_PROG_INFO_JITED_INSNS;
877ec202509SPaul Chaignon 	else
878ec202509SPaul Chaignon 		arrays = 1UL << BPF_PROG_INFO_XLATED_INSNS;
879ec202509SPaul Chaignon 
880ec202509SPaul Chaignon 	arrays |= 1UL << BPF_PROG_INFO_JITED_KSYMS;
881ec202509SPaul Chaignon 	arrays |= 1UL << BPF_PROG_INFO_JITED_FUNC_LENS;
882ec202509SPaul Chaignon 	arrays |= 1UL << BPF_PROG_INFO_FUNC_INFO;
883ec202509SPaul Chaignon 	arrays |= 1UL << BPF_PROG_INFO_LINE_INFO;
884ec202509SPaul Chaignon 	arrays |= 1UL << BPF_PROG_INFO_JITED_LINE_INFO;
885ec202509SPaul Chaignon 
886ec202509SPaul Chaignon 	if (json_output && nb_fds > 1)
887ec202509SPaul Chaignon 		jsonw_start_array(json_wtr);	/* root array */
888ec202509SPaul Chaignon 	for (i = 0; i < nb_fds; i++) {
889ec202509SPaul Chaignon 		info_linear = bpf_program__get_prog_info_linear(fds[i], arrays);
890ec202509SPaul Chaignon 		if (IS_ERR_OR_NULL(info_linear)) {
891ec202509SPaul Chaignon 			p_err("can't get prog info: %s", strerror(errno));
892ec202509SPaul Chaignon 			break;
893ec202509SPaul Chaignon 		}
894ec202509SPaul Chaignon 
895ec202509SPaul Chaignon 		if (json_output && nb_fds > 1) {
896ec202509SPaul Chaignon 			jsonw_start_object(json_wtr);	/* prog object */
897ec202509SPaul Chaignon 			print_prog_header_json(&info_linear->info);
898ec202509SPaul Chaignon 			jsonw_name(json_wtr, "insns");
899ec202509SPaul Chaignon 		} else if (nb_fds > 1) {
900ec202509SPaul Chaignon 			print_prog_header_plain(&info_linear->info);
901ec202509SPaul Chaignon 		}
902ec202509SPaul Chaignon 
903ec202509SPaul Chaignon 		err = prog_dump(&info_linear->info, mode, filepath, opcodes,
904ec202509SPaul Chaignon 				visual, linum);
905ec202509SPaul Chaignon 
906ec202509SPaul Chaignon 		if (json_output && nb_fds > 1)
907ec202509SPaul Chaignon 			jsonw_end_object(json_wtr);	/* prog object */
908ec202509SPaul Chaignon 		else if (i != nb_fds - 1 && nb_fds > 1)
909ec202509SPaul Chaignon 			printf("\n");
910ec202509SPaul Chaignon 
911ec202509SPaul Chaignon 		free(info_linear);
912ec202509SPaul Chaignon 		if (err)
913ec202509SPaul Chaignon 			break;
914ec202509SPaul Chaignon 		close(fds[i]);
915ec202509SPaul Chaignon 	}
916ec202509SPaul Chaignon 	if (json_output && nb_fds > 1)
917ec202509SPaul Chaignon 		jsonw_end_array(json_wtr);	/* root array */
918ec202509SPaul Chaignon 
919ec202509SPaul Chaignon exit_close:
920ec202509SPaul Chaignon 	for (; i < nb_fds; i++)
921ec202509SPaul Chaignon 		close(fds[i]);
922ec202509SPaul Chaignon exit_free:
923ec202509SPaul Chaignon 	free(fds);
924ec202509SPaul Chaignon 	return err;
92571bb428fSJakub Kicinski }
92671bb428fSJakub Kicinski 
92771bb428fSJakub Kicinski static int do_pin(int argc, char **argv)
92871bb428fSJakub Kicinski {
929004b45c0SQuentin Monnet 	int err;
930004b45c0SQuentin Monnet 
93175a1e792SQuentin Monnet 	err = do_pin_any(argc, argv, prog_parse_fd);
932004b45c0SQuentin Monnet 	if (!err && json_output)
933004b45c0SQuentin Monnet 		jsonw_null(json_wtr);
934004b45c0SQuentin Monnet 	return err;
93571bb428fSJakub Kicinski }
93671bb428fSJakub Kicinski 
9373ff5a4dcSJakub Kicinski struct map_replace {
9383ff5a4dcSJakub Kicinski 	int idx;
9393ff5a4dcSJakub Kicinski 	int fd;
9403ff5a4dcSJakub Kicinski 	char *name;
9413ff5a4dcSJakub Kicinski };
9423ff5a4dcSJakub Kicinski 
943c101189bSQuentin Monnet static int map_replace_compar(const void *p1, const void *p2)
9443ff5a4dcSJakub Kicinski {
9453ff5a4dcSJakub Kicinski 	const struct map_replace *a = p1, *b = p2;
9463ff5a4dcSJakub Kicinski 
9473ff5a4dcSJakub Kicinski 	return a->idx - b->idx;
9483ff5a4dcSJakub Kicinski }
9493ff5a4dcSJakub Kicinski 
950092f0892SStanislav Fomichev static int parse_attach_detach_args(int argc, char **argv, int *progfd,
951092f0892SStanislav Fomichev 				    enum bpf_attach_type *attach_type,
952092f0892SStanislav Fomichev 				    int *mapfd)
953092f0892SStanislav Fomichev {
954092f0892SStanislav Fomichev 	if (!REQ_ARGS(3))
955092f0892SStanislav Fomichev 		return -EINVAL;
956092f0892SStanislav Fomichev 
957092f0892SStanislav Fomichev 	*progfd = prog_parse_fd(&argc, &argv);
958092f0892SStanislav Fomichev 	if (*progfd < 0)
959092f0892SStanislav Fomichev 		return *progfd;
960092f0892SStanislav Fomichev 
961092f0892SStanislav Fomichev 	*attach_type = parse_attach_type(*argv);
962092f0892SStanislav Fomichev 	if (*attach_type == __MAX_BPF_ATTACH_TYPE) {
963092f0892SStanislav Fomichev 		p_err("invalid attach/detach type");
964092f0892SStanislav Fomichev 		return -EINVAL;
965092f0892SStanislav Fomichev 	}
966092f0892SStanislav Fomichev 
967092f0892SStanislav Fomichev 	if (*attach_type == BPF_FLOW_DISSECTOR) {
968f9b7ff0dSLorenz Bauer 		*mapfd = 0;
969092f0892SStanislav Fomichev 		return 0;
970092f0892SStanislav Fomichev 	}
971092f0892SStanislav Fomichev 
972092f0892SStanislav Fomichev 	NEXT_ARG();
973092f0892SStanislav Fomichev 	if (!REQ_ARGS(2))
974092f0892SStanislav Fomichev 		return -EINVAL;
975092f0892SStanislav Fomichev 
976092f0892SStanislav Fomichev 	*mapfd = map_parse_fd(&argc, &argv);
977092f0892SStanislav Fomichev 	if (*mapfd < 0)
978092f0892SStanislav Fomichev 		return *mapfd;
979092f0892SStanislav Fomichev 
980092f0892SStanislav Fomichev 	return 0;
981092f0892SStanislav Fomichev }
982092f0892SStanislav Fomichev 
983b7d3826cSJohn Fastabend static int do_attach(int argc, char **argv)
984b7d3826cSJohn Fastabend {
985b7d3826cSJohn Fastabend 	enum bpf_attach_type attach_type;
986092f0892SStanislav Fomichev 	int err, progfd;
987092f0892SStanislav Fomichev 	int mapfd;
988b7d3826cSJohn Fastabend 
989092f0892SStanislav Fomichev 	err = parse_attach_detach_args(argc, argv,
990092f0892SStanislav Fomichev 				       &progfd, &attach_type, &mapfd);
991092f0892SStanislav Fomichev 	if (err)
992092f0892SStanislav Fomichev 		return err;
993b7d3826cSJohn Fastabend 
994b7d3826cSJohn Fastabend 	err = bpf_prog_attach(progfd, mapfd, attach_type, 0);
995b7d3826cSJohn Fastabend 	if (err) {
996b7d3826cSJohn Fastabend 		p_err("failed prog attach to map");
997b7d3826cSJohn Fastabend 		return -EINVAL;
998b7d3826cSJohn Fastabend 	}
999b7d3826cSJohn Fastabend 
1000b7d3826cSJohn Fastabend 	if (json_output)
1001b7d3826cSJohn Fastabend 		jsonw_null(json_wtr);
1002b7d3826cSJohn Fastabend 	return 0;
1003b7d3826cSJohn Fastabend }
1004b7d3826cSJohn Fastabend 
1005b7d3826cSJohn Fastabend static int do_detach(int argc, char **argv)
1006b7d3826cSJohn Fastabend {
1007b7d3826cSJohn Fastabend 	enum bpf_attach_type attach_type;
1008092f0892SStanislav Fomichev 	int err, progfd;
1009092f0892SStanislav Fomichev 	int mapfd;
1010b7d3826cSJohn Fastabend 
1011092f0892SStanislav Fomichev 	err = parse_attach_detach_args(argc, argv,
1012092f0892SStanislav Fomichev 				       &progfd, &attach_type, &mapfd);
1013092f0892SStanislav Fomichev 	if (err)
1014092f0892SStanislav Fomichev 		return err;
1015b7d3826cSJohn Fastabend 
1016b7d3826cSJohn Fastabend 	err = bpf_prog_detach2(progfd, mapfd, attach_type);
1017b7d3826cSJohn Fastabend 	if (err) {
1018b7d3826cSJohn Fastabend 		p_err("failed prog detach from map");
1019b7d3826cSJohn Fastabend 		return -EINVAL;
1020b7d3826cSJohn Fastabend 	}
1021b7d3826cSJohn Fastabend 
1022b7d3826cSJohn Fastabend 	if (json_output)
1023b7d3826cSJohn Fastabend 		jsonw_null(json_wtr);
1024b7d3826cSJohn Fastabend 	return 0;
1025b7d3826cSJohn Fastabend }
102677380998SStanislav Fomichev 
1027ba95c745SQuentin Monnet static int check_single_stdin(char *file_data_in, char *file_ctx_in)
1028ba95c745SQuentin Monnet {
1029ba95c745SQuentin Monnet 	if (file_data_in && file_ctx_in &&
1030ba95c745SQuentin Monnet 	    !strcmp(file_data_in, "-") && !strcmp(file_ctx_in, "-")) {
1031ba95c745SQuentin Monnet 		p_err("cannot use standard input for both data_in and ctx_in");
1032ba95c745SQuentin Monnet 		return -1;
1033ba95c745SQuentin Monnet 	}
1034ba95c745SQuentin Monnet 
1035ba95c745SQuentin Monnet 	return 0;
1036ba95c745SQuentin Monnet }
1037ba95c745SQuentin Monnet 
1038ba95c745SQuentin Monnet static int get_run_data(const char *fname, void **data_ptr, unsigned int *size)
1039ba95c745SQuentin Monnet {
1040ba95c745SQuentin Monnet 	size_t block_size = 256;
1041ba95c745SQuentin Monnet 	size_t buf_size = block_size;
1042ba95c745SQuentin Monnet 	size_t nb_read = 0;
1043ba95c745SQuentin Monnet 	void *tmp;
1044ba95c745SQuentin Monnet 	FILE *f;
1045ba95c745SQuentin Monnet 
1046ba95c745SQuentin Monnet 	if (!fname) {
1047ba95c745SQuentin Monnet 		*data_ptr = NULL;
1048ba95c745SQuentin Monnet 		*size = 0;
1049ba95c745SQuentin Monnet 		return 0;
1050ba95c745SQuentin Monnet 	}
1051ba95c745SQuentin Monnet 
1052ba95c745SQuentin Monnet 	if (!strcmp(fname, "-"))
1053ba95c745SQuentin Monnet 		f = stdin;
1054ba95c745SQuentin Monnet 	else
1055ba95c745SQuentin Monnet 		f = fopen(fname, "r");
1056ba95c745SQuentin Monnet 	if (!f) {
1057ba95c745SQuentin Monnet 		p_err("failed to open %s: %s", fname, strerror(errno));
1058ba95c745SQuentin Monnet 		return -1;
1059ba95c745SQuentin Monnet 	}
1060ba95c745SQuentin Monnet 
1061ba95c745SQuentin Monnet 	*data_ptr = malloc(block_size);
1062ba95c745SQuentin Monnet 	if (!*data_ptr) {
1063ba95c745SQuentin Monnet 		p_err("failed to allocate memory for data_in/ctx_in: %s",
1064ba95c745SQuentin Monnet 		      strerror(errno));
1065ba95c745SQuentin Monnet 		goto err_fclose;
1066ba95c745SQuentin Monnet 	}
1067ba95c745SQuentin Monnet 
1068ba95c745SQuentin Monnet 	while ((nb_read += fread(*data_ptr + nb_read, 1, block_size, f))) {
1069ba95c745SQuentin Monnet 		if (feof(f))
1070ba95c745SQuentin Monnet 			break;
1071ba95c745SQuentin Monnet 		if (ferror(f)) {
1072ba95c745SQuentin Monnet 			p_err("failed to read data_in/ctx_in from %s: %s",
1073ba95c745SQuentin Monnet 			      fname, strerror(errno));
1074ba95c745SQuentin Monnet 			goto err_free;
1075ba95c745SQuentin Monnet 		}
1076ba95c745SQuentin Monnet 		if (nb_read > buf_size - block_size) {
1077ba95c745SQuentin Monnet 			if (buf_size == UINT32_MAX) {
1078ba95c745SQuentin Monnet 				p_err("data_in/ctx_in is too long (max: %d)",
1079ba95c745SQuentin Monnet 				      UINT32_MAX);
1080ba95c745SQuentin Monnet 				goto err_free;
1081ba95c745SQuentin Monnet 			}
1082ba95c745SQuentin Monnet 			/* No space for fread()-ing next chunk; realloc() */
1083ba95c745SQuentin Monnet 			buf_size *= 2;
1084ba95c745SQuentin Monnet 			tmp = realloc(*data_ptr, buf_size);
1085ba95c745SQuentin Monnet 			if (!tmp) {
1086ba95c745SQuentin Monnet 				p_err("failed to reallocate data_in/ctx_in: %s",
1087ba95c745SQuentin Monnet 				      strerror(errno));
1088ba95c745SQuentin Monnet 				goto err_free;
1089ba95c745SQuentin Monnet 			}
1090ba95c745SQuentin Monnet 			*data_ptr = tmp;
1091ba95c745SQuentin Monnet 		}
1092ba95c745SQuentin Monnet 	}
1093ba95c745SQuentin Monnet 	if (f != stdin)
1094ba95c745SQuentin Monnet 		fclose(f);
1095ba95c745SQuentin Monnet 
1096ba95c745SQuentin Monnet 	*size = nb_read;
1097ba95c745SQuentin Monnet 	return 0;
1098ba95c745SQuentin Monnet 
1099ba95c745SQuentin Monnet err_free:
1100ba95c745SQuentin Monnet 	free(*data_ptr);
1101ba95c745SQuentin Monnet 	*data_ptr = NULL;
1102ba95c745SQuentin Monnet err_fclose:
1103ba95c745SQuentin Monnet 	if (f != stdin)
1104ba95c745SQuentin Monnet 		fclose(f);
1105ba95c745SQuentin Monnet 	return -1;
1106ba95c745SQuentin Monnet }
1107ba95c745SQuentin Monnet 
1108ba95c745SQuentin Monnet static void hex_print(void *data, unsigned int size, FILE *f)
1109ba95c745SQuentin Monnet {
1110ba95c745SQuentin Monnet 	size_t i, j;
1111ba95c745SQuentin Monnet 	char c;
1112ba95c745SQuentin Monnet 
1113ba95c745SQuentin Monnet 	for (i = 0; i < size; i += 16) {
1114ba95c745SQuentin Monnet 		/* Row offset */
1115ba95c745SQuentin Monnet 		fprintf(f, "%07zx\t", i);
1116ba95c745SQuentin Monnet 
1117ba95c745SQuentin Monnet 		/* Hexadecimal values */
1118ba95c745SQuentin Monnet 		for (j = i; j < i + 16 && j < size; j++)
1119ba95c745SQuentin Monnet 			fprintf(f, "%02x%s", *(uint8_t *)(data + j),
1120ba95c745SQuentin Monnet 				j % 2 ? " " : "");
1121ba95c745SQuentin Monnet 		for (; j < i + 16; j++)
1122ba95c745SQuentin Monnet 			fprintf(f, "  %s", j % 2 ? " " : "");
1123ba95c745SQuentin Monnet 
1124ba95c745SQuentin Monnet 		/* ASCII values (if relevant), '.' otherwise */
1125ba95c745SQuentin Monnet 		fprintf(f, "| ");
1126ba95c745SQuentin Monnet 		for (j = i; j < i + 16 && j < size; j++) {
1127ba95c745SQuentin Monnet 			c = *(char *)(data + j);
1128ba95c745SQuentin Monnet 			if (c < ' ' || c > '~')
1129ba95c745SQuentin Monnet 				c = '.';
1130ba95c745SQuentin Monnet 			fprintf(f, "%c%s", c, j == i + 7 ? " " : "");
1131ba95c745SQuentin Monnet 		}
1132ba95c745SQuentin Monnet 
1133ba95c745SQuentin Monnet 		fprintf(f, "\n");
1134ba95c745SQuentin Monnet 	}
1135ba95c745SQuentin Monnet }
1136ba95c745SQuentin Monnet 
1137ba95c745SQuentin Monnet static int
1138ba95c745SQuentin Monnet print_run_output(void *data, unsigned int size, const char *fname,
1139ba95c745SQuentin Monnet 		 const char *json_key)
1140ba95c745SQuentin Monnet {
1141ba95c745SQuentin Monnet 	size_t nb_written;
1142ba95c745SQuentin Monnet 	FILE *f;
1143ba95c745SQuentin Monnet 
1144ba95c745SQuentin Monnet 	if (!fname)
1145ba95c745SQuentin Monnet 		return 0;
1146ba95c745SQuentin Monnet 
1147ba95c745SQuentin Monnet 	if (!strcmp(fname, "-")) {
1148ba95c745SQuentin Monnet 		f = stdout;
1149ba95c745SQuentin Monnet 		if (json_output) {
1150ba95c745SQuentin Monnet 			jsonw_name(json_wtr, json_key);
1151ba95c745SQuentin Monnet 			print_data_json(data, size);
1152ba95c745SQuentin Monnet 		} else {
1153ba95c745SQuentin Monnet 			hex_print(data, size, f);
1154ba95c745SQuentin Monnet 		}
1155ba95c745SQuentin Monnet 		return 0;
1156ba95c745SQuentin Monnet 	}
1157ba95c745SQuentin Monnet 
1158ba95c745SQuentin Monnet 	f = fopen(fname, "w");
1159ba95c745SQuentin Monnet 	if (!f) {
1160ba95c745SQuentin Monnet 		p_err("failed to open %s: %s", fname, strerror(errno));
1161ba95c745SQuentin Monnet 		return -1;
1162ba95c745SQuentin Monnet 	}
1163ba95c745SQuentin Monnet 
1164ba95c745SQuentin Monnet 	nb_written = fwrite(data, 1, size, f);
1165ba95c745SQuentin Monnet 	fclose(f);
1166ba95c745SQuentin Monnet 	if (nb_written != size) {
1167ba95c745SQuentin Monnet 		p_err("failed to write output data/ctx: %s", strerror(errno));
1168ba95c745SQuentin Monnet 		return -1;
1169ba95c745SQuentin Monnet 	}
1170ba95c745SQuentin Monnet 
1171ba95c745SQuentin Monnet 	return 0;
1172ba95c745SQuentin Monnet }
1173ba95c745SQuentin Monnet 
1174ba95c745SQuentin Monnet static int alloc_run_data(void **data_ptr, unsigned int size_out)
1175ba95c745SQuentin Monnet {
1176ba95c745SQuentin Monnet 	*data_ptr = calloc(size_out, 1);
1177ba95c745SQuentin Monnet 	if (!*data_ptr) {
1178ba95c745SQuentin Monnet 		p_err("failed to allocate memory for output data/ctx: %s",
1179ba95c745SQuentin Monnet 		      strerror(errno));
1180ba95c745SQuentin Monnet 		return -1;
1181ba95c745SQuentin Monnet 	}
1182ba95c745SQuentin Monnet 
1183ba95c745SQuentin Monnet 	return 0;
1184ba95c745SQuentin Monnet }
1185ba95c745SQuentin Monnet 
1186ba95c745SQuentin Monnet static int do_run(int argc, char **argv)
1187ba95c745SQuentin Monnet {
1188ba95c745SQuentin Monnet 	char *data_fname_in = NULL, *data_fname_out = NULL;
1189ba95c745SQuentin Monnet 	char *ctx_fname_in = NULL, *ctx_fname_out = NULL;
1190ba95c745SQuentin Monnet 	struct bpf_prog_test_run_attr test_attr = {0};
1191ba95c745SQuentin Monnet 	const unsigned int default_size = SZ_32K;
1192ba95c745SQuentin Monnet 	void *data_in = NULL, *data_out = NULL;
1193ba95c745SQuentin Monnet 	void *ctx_in = NULL, *ctx_out = NULL;
1194ba95c745SQuentin Monnet 	unsigned int repeat = 1;
1195ba95c745SQuentin Monnet 	int fd, err;
1196ba95c745SQuentin Monnet 
1197ba95c745SQuentin Monnet 	if (!REQ_ARGS(4))
1198ba95c745SQuentin Monnet 		return -1;
1199ba95c745SQuentin Monnet 
1200ba95c745SQuentin Monnet 	fd = prog_parse_fd(&argc, &argv);
1201ba95c745SQuentin Monnet 	if (fd < 0)
1202ba95c745SQuentin Monnet 		return -1;
1203ba95c745SQuentin Monnet 
1204ba95c745SQuentin Monnet 	while (argc) {
1205ba95c745SQuentin Monnet 		if (detect_common_prefix(*argv, "data_in", "data_out",
1206ba95c745SQuentin Monnet 					 "data_size_out", NULL))
1207ba95c745SQuentin Monnet 			return -1;
1208ba95c745SQuentin Monnet 		if (detect_common_prefix(*argv, "ctx_in", "ctx_out",
1209ba95c745SQuentin Monnet 					 "ctx_size_out", NULL))
1210ba95c745SQuentin Monnet 			return -1;
1211ba95c745SQuentin Monnet 
1212ba95c745SQuentin Monnet 		if (is_prefix(*argv, "data_in")) {
1213ba95c745SQuentin Monnet 			NEXT_ARG();
1214ba95c745SQuentin Monnet 			if (!REQ_ARGS(1))
1215ba95c745SQuentin Monnet 				return -1;
1216ba95c745SQuentin Monnet 
1217ba95c745SQuentin Monnet 			data_fname_in = GET_ARG();
1218ba95c745SQuentin Monnet 			if (check_single_stdin(data_fname_in, ctx_fname_in))
1219ba95c745SQuentin Monnet 				return -1;
1220ba95c745SQuentin Monnet 		} else if (is_prefix(*argv, "data_out")) {
1221ba95c745SQuentin Monnet 			NEXT_ARG();
1222ba95c745SQuentin Monnet 			if (!REQ_ARGS(1))
1223ba95c745SQuentin Monnet 				return -1;
1224ba95c745SQuentin Monnet 
1225ba95c745SQuentin Monnet 			data_fname_out = GET_ARG();
1226ba95c745SQuentin Monnet 		} else if (is_prefix(*argv, "data_size_out")) {
1227ba95c745SQuentin Monnet 			char *endptr;
1228ba95c745SQuentin Monnet 
1229ba95c745SQuentin Monnet 			NEXT_ARG();
1230ba95c745SQuentin Monnet 			if (!REQ_ARGS(1))
1231ba95c745SQuentin Monnet 				return -1;
1232ba95c745SQuentin Monnet 
1233ba95c745SQuentin Monnet 			test_attr.data_size_out = strtoul(*argv, &endptr, 0);
1234ba95c745SQuentin Monnet 			if (*endptr) {
1235ba95c745SQuentin Monnet 				p_err("can't parse %s as output data size",
1236ba95c745SQuentin Monnet 				      *argv);
1237ba95c745SQuentin Monnet 				return -1;
1238ba95c745SQuentin Monnet 			}
1239ba95c745SQuentin Monnet 			NEXT_ARG();
1240ba95c745SQuentin Monnet 		} else if (is_prefix(*argv, "ctx_in")) {
1241ba95c745SQuentin Monnet 			NEXT_ARG();
1242ba95c745SQuentin Monnet 			if (!REQ_ARGS(1))
1243ba95c745SQuentin Monnet 				return -1;
1244ba95c745SQuentin Monnet 
1245ba95c745SQuentin Monnet 			ctx_fname_in = GET_ARG();
1246ba95c745SQuentin Monnet 			if (check_single_stdin(data_fname_in, ctx_fname_in))
1247ba95c745SQuentin Monnet 				return -1;
1248ba95c745SQuentin Monnet 		} else if (is_prefix(*argv, "ctx_out")) {
1249ba95c745SQuentin Monnet 			NEXT_ARG();
1250ba95c745SQuentin Monnet 			if (!REQ_ARGS(1))
1251ba95c745SQuentin Monnet 				return -1;
1252ba95c745SQuentin Monnet 
1253ba95c745SQuentin Monnet 			ctx_fname_out = GET_ARG();
1254ba95c745SQuentin Monnet 		} else if (is_prefix(*argv, "ctx_size_out")) {
1255ba95c745SQuentin Monnet 			char *endptr;
1256ba95c745SQuentin Monnet 
1257ba95c745SQuentin Monnet 			NEXT_ARG();
1258ba95c745SQuentin Monnet 			if (!REQ_ARGS(1))
1259ba95c745SQuentin Monnet 				return -1;
1260ba95c745SQuentin Monnet 
1261ba95c745SQuentin Monnet 			test_attr.ctx_size_out = strtoul(*argv, &endptr, 0);
1262ba95c745SQuentin Monnet 			if (*endptr) {
1263ba95c745SQuentin Monnet 				p_err("can't parse %s as output context size",
1264ba95c745SQuentin Monnet 				      *argv);
1265ba95c745SQuentin Monnet 				return -1;
1266ba95c745SQuentin Monnet 			}
1267ba95c745SQuentin Monnet 			NEXT_ARG();
1268ba95c745SQuentin Monnet 		} else if (is_prefix(*argv, "repeat")) {
1269ba95c745SQuentin Monnet 			char *endptr;
1270ba95c745SQuentin Monnet 
1271ba95c745SQuentin Monnet 			NEXT_ARG();
1272ba95c745SQuentin Monnet 			if (!REQ_ARGS(1))
1273ba95c745SQuentin Monnet 				return -1;
1274ba95c745SQuentin Monnet 
1275ba95c745SQuentin Monnet 			repeat = strtoul(*argv, &endptr, 0);
1276ba95c745SQuentin Monnet 			if (*endptr) {
1277ba95c745SQuentin Monnet 				p_err("can't parse %s as repeat number",
1278ba95c745SQuentin Monnet 				      *argv);
1279ba95c745SQuentin Monnet 				return -1;
1280ba95c745SQuentin Monnet 			}
1281ba95c745SQuentin Monnet 			NEXT_ARG();
1282ba95c745SQuentin Monnet 		} else {
1283ba95c745SQuentin Monnet 			p_err("expected no more arguments, 'data_in', 'data_out', 'data_size_out', 'ctx_in', 'ctx_out', 'ctx_size_out' or 'repeat', got: '%s'?",
1284ba95c745SQuentin Monnet 			      *argv);
1285ba95c745SQuentin Monnet 			return -1;
1286ba95c745SQuentin Monnet 		}
1287ba95c745SQuentin Monnet 	}
1288ba95c745SQuentin Monnet 
1289ba95c745SQuentin Monnet 	err = get_run_data(data_fname_in, &data_in, &test_attr.data_size_in);
1290ba95c745SQuentin Monnet 	if (err)
1291ba95c745SQuentin Monnet 		return -1;
1292ba95c745SQuentin Monnet 
1293ba95c745SQuentin Monnet 	if (data_in) {
1294ba95c745SQuentin Monnet 		if (!test_attr.data_size_out)
1295ba95c745SQuentin Monnet 			test_attr.data_size_out = default_size;
1296ba95c745SQuentin Monnet 		err = alloc_run_data(&data_out, test_attr.data_size_out);
1297ba95c745SQuentin Monnet 		if (err)
1298ba95c745SQuentin Monnet 			goto free_data_in;
1299ba95c745SQuentin Monnet 	}
1300ba95c745SQuentin Monnet 
1301ba95c745SQuentin Monnet 	err = get_run_data(ctx_fname_in, &ctx_in, &test_attr.ctx_size_in);
1302ba95c745SQuentin Monnet 	if (err)
1303ba95c745SQuentin Monnet 		goto free_data_out;
1304ba95c745SQuentin Monnet 
1305ba95c745SQuentin Monnet 	if (ctx_in) {
1306ba95c745SQuentin Monnet 		if (!test_attr.ctx_size_out)
1307ba95c745SQuentin Monnet 			test_attr.ctx_size_out = default_size;
1308ba95c745SQuentin Monnet 		err = alloc_run_data(&ctx_out, test_attr.ctx_size_out);
1309ba95c745SQuentin Monnet 		if (err)
1310ba95c745SQuentin Monnet 			goto free_ctx_in;
1311ba95c745SQuentin Monnet 	}
1312ba95c745SQuentin Monnet 
1313ba95c745SQuentin Monnet 	test_attr.prog_fd	= fd;
1314ba95c745SQuentin Monnet 	test_attr.repeat	= repeat;
1315ba95c745SQuentin Monnet 	test_attr.data_in	= data_in;
1316ba95c745SQuentin Monnet 	test_attr.data_out	= data_out;
1317ba95c745SQuentin Monnet 	test_attr.ctx_in	= ctx_in;
1318ba95c745SQuentin Monnet 	test_attr.ctx_out	= ctx_out;
1319ba95c745SQuentin Monnet 
1320ba95c745SQuentin Monnet 	err = bpf_prog_test_run_xattr(&test_attr);
1321ba95c745SQuentin Monnet 	if (err) {
1322ba95c745SQuentin Monnet 		p_err("failed to run program: %s", strerror(errno));
1323ba95c745SQuentin Monnet 		goto free_ctx_out;
1324ba95c745SQuentin Monnet 	}
1325ba95c745SQuentin Monnet 
1326ba95c745SQuentin Monnet 	err = 0;
1327ba95c745SQuentin Monnet 
1328ba95c745SQuentin Monnet 	if (json_output)
1329ba95c745SQuentin Monnet 		jsonw_start_object(json_wtr);	/* root */
1330ba95c745SQuentin Monnet 
1331ba95c745SQuentin Monnet 	/* Do not exit on errors occurring when printing output data/context,
1332ba95c745SQuentin Monnet 	 * we still want to print return value and duration for program run.
1333ba95c745SQuentin Monnet 	 */
1334ba95c745SQuentin Monnet 	if (test_attr.data_size_out)
1335ba95c745SQuentin Monnet 		err += print_run_output(test_attr.data_out,
1336ba95c745SQuentin Monnet 					test_attr.data_size_out,
1337ba95c745SQuentin Monnet 					data_fname_out, "data_out");
1338ba95c745SQuentin Monnet 	if (test_attr.ctx_size_out)
1339ba95c745SQuentin Monnet 		err += print_run_output(test_attr.ctx_out,
1340ba95c745SQuentin Monnet 					test_attr.ctx_size_out,
1341ba95c745SQuentin Monnet 					ctx_fname_out, "ctx_out");
1342ba95c745SQuentin Monnet 
1343ba95c745SQuentin Monnet 	if (json_output) {
1344ba95c745SQuentin Monnet 		jsonw_uint_field(json_wtr, "retval", test_attr.retval);
1345ba95c745SQuentin Monnet 		jsonw_uint_field(json_wtr, "duration", test_attr.duration);
1346ba95c745SQuentin Monnet 		jsonw_end_object(json_wtr);	/* root */
1347ba95c745SQuentin Monnet 	} else {
1348ba95c745SQuentin Monnet 		fprintf(stdout, "Return value: %u, duration%s: %uns\n",
1349ba95c745SQuentin Monnet 			test_attr.retval,
1350ba95c745SQuentin Monnet 			repeat > 1 ? " (average)" : "", test_attr.duration);
1351ba95c745SQuentin Monnet 	}
1352ba95c745SQuentin Monnet 
1353ba95c745SQuentin Monnet free_ctx_out:
1354ba95c745SQuentin Monnet 	free(ctx_out);
1355ba95c745SQuentin Monnet free_ctx_in:
1356ba95c745SQuentin Monnet 	free(ctx_in);
1357ba95c745SQuentin Monnet free_data_out:
1358ba95c745SQuentin Monnet 	free(data_out);
1359ba95c745SQuentin Monnet free_data_in:
1360ba95c745SQuentin Monnet 	free(data_in);
1361ba95c745SQuentin Monnet 
1362ba95c745SQuentin Monnet 	return err;
1363ba95c745SQuentin Monnet }
1364ba95c745SQuentin Monnet 
13656ae32b29SQuentin Monnet static int
13666ae32b29SQuentin Monnet get_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
13676ae32b29SQuentin Monnet 		      enum bpf_attach_type *expected_attach_type)
13686ae32b29SQuentin Monnet {
13696ae32b29SQuentin Monnet 	libbpf_print_fn_t print_backup;
13706ae32b29SQuentin Monnet 	int ret;
13716ae32b29SQuentin Monnet 
13726ae32b29SQuentin Monnet 	ret = libbpf_prog_type_by_name(name, prog_type, expected_attach_type);
13736ae32b29SQuentin Monnet 	if (!ret)
13746ae32b29SQuentin Monnet 		return ret;
13756ae32b29SQuentin Monnet 
13766ae32b29SQuentin Monnet 	/* libbpf_prog_type_by_name() failed, let's re-run with debug level */
13776ae32b29SQuentin Monnet 	print_backup = libbpf_set_print(print_all_levels);
13786ae32b29SQuentin Monnet 	ret = libbpf_prog_type_by_name(name, prog_type, expected_attach_type);
13796ae32b29SQuentin Monnet 	libbpf_set_print(print_backup);
13806ae32b29SQuentin Monnet 
13816ae32b29SQuentin Monnet 	return ret;
13826ae32b29SQuentin Monnet }
13836ae32b29SQuentin Monnet 
138477380998SStanislav Fomichev static int load_with_options(int argc, char **argv, bool first_prog_only)
138549a086c2SRoman Gushchin {
138632e3e58eSAndrii Nakryiko 	enum bpf_prog_type common_prog_type = BPF_PROG_TYPE_UNSPEC;
1387e00aca65SAndrii Nakryiko 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, open_opts,
1388e00aca65SAndrii Nakryiko 		.relaxed_maps = relaxed_maps,
1389e00aca65SAndrii Nakryiko 	);
1390e00aca65SAndrii Nakryiko 	struct bpf_object_load_attr load_attr = { 0 };
139155d77807SQuentin Monnet 	enum bpf_attach_type expected_attach_type;
13923ff5a4dcSJakub Kicinski 	struct map_replace *map_replace = NULL;
139377380998SStanislav Fomichev 	struct bpf_program *prog = NULL, *pos;
13943ff5a4dcSJakub Kicinski 	unsigned int old_map_fds = 0;
13953767a94bSStanislav Fomichev 	const char *pinmaps = NULL;
139649a086c2SRoman Gushchin 	struct bpf_object *obj;
1397c8406848SJakub Kicinski 	struct bpf_map *map;
1398c8406848SJakub Kicinski 	const char *pinfile;
13993ff5a4dcSJakub Kicinski 	unsigned int i, j;
1400c8406848SJakub Kicinski 	__u32 ifindex = 0;
140132e3e58eSAndrii Nakryiko 	const char *file;
14023ff5a4dcSJakub Kicinski 	int idx, err;
140349a086c2SRoman Gushchin 
140432e3e58eSAndrii Nakryiko 
14058d1fc3deSJakub Kicinski 	if (!REQ_ARGS(2))
14068d1fc3deSJakub Kicinski 		return -1;
140732e3e58eSAndrii Nakryiko 	file = GET_ARG();
14088d1fc3deSJakub Kicinski 	pinfile = GET_ARG();
140949a086c2SRoman Gushchin 
1410ba6dd679SJakub Kicinski 	while (argc) {
141149f2cba3SJakub Kicinski 		if (is_prefix(*argv, "type")) {
141249f2cba3SJakub Kicinski 			char *type;
141349f2cba3SJakub Kicinski 
141449f2cba3SJakub Kicinski 			NEXT_ARG();
141549f2cba3SJakub Kicinski 
141632e3e58eSAndrii Nakryiko 			if (common_prog_type != BPF_PROG_TYPE_UNSPEC) {
141749f2cba3SJakub Kicinski 				p_err("program type already specified");
14183ff5a4dcSJakub Kicinski 				goto err_free_reuse_maps;
141949f2cba3SJakub Kicinski 			}
142049f2cba3SJakub Kicinski 			if (!REQ_ARGS(1))
14213ff5a4dcSJakub Kicinski 				goto err_free_reuse_maps;
142249f2cba3SJakub Kicinski 
142349f2cba3SJakub Kicinski 			/* Put a '/' at the end of type to appease libbpf */
142449f2cba3SJakub Kicinski 			type = malloc(strlen(*argv) + 2);
142549f2cba3SJakub Kicinski 			if (!type) {
142649f2cba3SJakub Kicinski 				p_err("mem alloc failed");
14273ff5a4dcSJakub Kicinski 				goto err_free_reuse_maps;
142849f2cba3SJakub Kicinski 			}
142949f2cba3SJakub Kicinski 			*type = 0;
143049f2cba3SJakub Kicinski 			strcat(type, *argv);
143149f2cba3SJakub Kicinski 			strcat(type, "/");
143249f2cba3SJakub Kicinski 
14336ae32b29SQuentin Monnet 			err = get_prog_type_by_name(type, &common_prog_type,
1434c8406848SJakub Kicinski 						    &expected_attach_type);
143549f2cba3SJakub Kicinski 			free(type);
1436c76e4c22STaeung Song 			if (err < 0)
14373ff5a4dcSJakub Kicinski 				goto err_free_reuse_maps;
1438c76e4c22STaeung Song 
143949f2cba3SJakub Kicinski 			NEXT_ARG();
14403ff5a4dcSJakub Kicinski 		} else if (is_prefix(*argv, "map")) {
1441dde7011aSJakub Kicinski 			void *new_map_replace;
14423ff5a4dcSJakub Kicinski 			char *endptr, *name;
14433ff5a4dcSJakub Kicinski 			int fd;
14443ff5a4dcSJakub Kicinski 
14453ff5a4dcSJakub Kicinski 			NEXT_ARG();
14463ff5a4dcSJakub Kicinski 
14473ff5a4dcSJakub Kicinski 			if (!REQ_ARGS(4))
14483ff5a4dcSJakub Kicinski 				goto err_free_reuse_maps;
14493ff5a4dcSJakub Kicinski 
14503ff5a4dcSJakub Kicinski 			if (is_prefix(*argv, "idx")) {
14513ff5a4dcSJakub Kicinski 				NEXT_ARG();
14523ff5a4dcSJakub Kicinski 
14533ff5a4dcSJakub Kicinski 				idx = strtoul(*argv, &endptr, 0);
14543ff5a4dcSJakub Kicinski 				if (*endptr) {
14553ff5a4dcSJakub Kicinski 					p_err("can't parse %s as IDX", *argv);
14563ff5a4dcSJakub Kicinski 					goto err_free_reuse_maps;
14573ff5a4dcSJakub Kicinski 				}
14583ff5a4dcSJakub Kicinski 				name = NULL;
14593ff5a4dcSJakub Kicinski 			} else if (is_prefix(*argv, "name")) {
14603ff5a4dcSJakub Kicinski 				NEXT_ARG();
14613ff5a4dcSJakub Kicinski 
14623ff5a4dcSJakub Kicinski 				name = *argv;
14633ff5a4dcSJakub Kicinski 				idx = -1;
14643ff5a4dcSJakub Kicinski 			} else {
14653ff5a4dcSJakub Kicinski 				p_err("expected 'idx' or 'name', got: '%s'?",
14663ff5a4dcSJakub Kicinski 				      *argv);
14673ff5a4dcSJakub Kicinski 				goto err_free_reuse_maps;
14683ff5a4dcSJakub Kicinski 			}
14693ff5a4dcSJakub Kicinski 			NEXT_ARG();
14703ff5a4dcSJakub Kicinski 
14713ff5a4dcSJakub Kicinski 			fd = map_parse_fd(&argc, &argv);
14723ff5a4dcSJakub Kicinski 			if (fd < 0)
14733ff5a4dcSJakub Kicinski 				goto err_free_reuse_maps;
14743ff5a4dcSJakub Kicinski 
1475dde7011aSJakub Kicinski 			new_map_replace = reallocarray(map_replace,
1476dde7011aSJakub Kicinski 						       old_map_fds + 1,
14773ff5a4dcSJakub Kicinski 						       sizeof(*map_replace));
1478dde7011aSJakub Kicinski 			if (!new_map_replace) {
14793ff5a4dcSJakub Kicinski 				p_err("mem alloc failed");
14803ff5a4dcSJakub Kicinski 				goto err_free_reuse_maps;
14813ff5a4dcSJakub Kicinski 			}
1482dde7011aSJakub Kicinski 			map_replace = new_map_replace;
1483dde7011aSJakub Kicinski 
14843ff5a4dcSJakub Kicinski 			map_replace[old_map_fds].idx = idx;
14853ff5a4dcSJakub Kicinski 			map_replace[old_map_fds].name = name;
14863ff5a4dcSJakub Kicinski 			map_replace[old_map_fds].fd = fd;
14873ff5a4dcSJakub Kicinski 			old_map_fds++;
148849f2cba3SJakub Kicinski 		} else if (is_prefix(*argv, "dev")) {
1489ba6dd679SJakub Kicinski 			NEXT_ARG();
1490ba6dd679SJakub Kicinski 
1491c8406848SJakub Kicinski 			if (ifindex) {
1492ba6dd679SJakub Kicinski 				p_err("offload device already specified");
14933ff5a4dcSJakub Kicinski 				goto err_free_reuse_maps;
1494ba6dd679SJakub Kicinski 			}
1495ba6dd679SJakub Kicinski 			if (!REQ_ARGS(1))
14963ff5a4dcSJakub Kicinski 				goto err_free_reuse_maps;
1497ba6dd679SJakub Kicinski 
1498c8406848SJakub Kicinski 			ifindex = if_nametoindex(*argv);
1499c8406848SJakub Kicinski 			if (!ifindex) {
1500ba6dd679SJakub Kicinski 				p_err("unrecognized netdevice '%s': %s",
1501ba6dd679SJakub Kicinski 				      *argv, strerror(errno));
15023ff5a4dcSJakub Kicinski 				goto err_free_reuse_maps;
1503ba6dd679SJakub Kicinski 			}
1504ba6dd679SJakub Kicinski 			NEXT_ARG();
15053767a94bSStanislav Fomichev 		} else if (is_prefix(*argv, "pinmaps")) {
15063767a94bSStanislav Fomichev 			NEXT_ARG();
15073767a94bSStanislav Fomichev 
15083767a94bSStanislav Fomichev 			if (!REQ_ARGS(1))
15093767a94bSStanislav Fomichev 				goto err_free_reuse_maps;
15103767a94bSStanislav Fomichev 
15113767a94bSStanislav Fomichev 			pinmaps = GET_ARG();
1512ba6dd679SJakub Kicinski 		} else {
15133ff5a4dcSJakub Kicinski 			p_err("expected no more arguments, 'type', 'map' or 'dev', got: '%s'?",
1514ba6dd679SJakub Kicinski 			      *argv);
15153ff5a4dcSJakub Kicinski 			goto err_free_reuse_maps;
1516ba6dd679SJakub Kicinski 		}
1517ba6dd679SJakub Kicinski 	}
1518ba6dd679SJakub Kicinski 
1519ac4e0e05SYonghong Song 	set_max_rlimit();
1520ac4e0e05SYonghong Song 
152132e3e58eSAndrii Nakryiko 	obj = bpf_object__open_file(file, &open_opts);
1522d510296dSAlexei Starovoitov 	if (libbpf_get_error(obj)) {
1523c8406848SJakub Kicinski 		p_err("failed to open object file");
15243ff5a4dcSJakub Kicinski 		goto err_free_reuse_maps;
152549a086c2SRoman Gushchin 	}
152649a086c2SRoman Gushchin 
152777380998SStanislav Fomichev 	bpf_object__for_each_program(pos, obj) {
152832e3e58eSAndrii Nakryiko 		enum bpf_prog_type prog_type = common_prog_type;
1529c8406848SJakub Kicinski 
153032e3e58eSAndrii Nakryiko 		if (prog_type == BPF_PROG_TYPE_UNSPEC) {
1531fd17e272SAndrii Nakryiko 			const char *sec_name = bpf_program__section_name(pos);
1532c8406848SJakub Kicinski 
15336ae32b29SQuentin Monnet 			err = get_prog_type_by_name(sec_name, &prog_type,
1534c8406848SJakub Kicinski 						    &expected_attach_type);
1535c76e4c22STaeung Song 			if (err < 0)
1536c8406848SJakub Kicinski 				goto err_close_obj;
1537c8406848SJakub Kicinski 		}
153877380998SStanislav Fomichev 
153977380998SStanislav Fomichev 		bpf_program__set_ifindex(pos, ifindex);
154077380998SStanislav Fomichev 		bpf_program__set_type(pos, prog_type);
154177380998SStanislav Fomichev 		bpf_program__set_expected_attach_type(pos, expected_attach_type);
154277380998SStanislav Fomichev 	}
1543c8406848SJakub Kicinski 
15443ff5a4dcSJakub Kicinski 	qsort(map_replace, old_map_fds, sizeof(*map_replace),
15453ff5a4dcSJakub Kicinski 	      map_replace_compar);
15463ff5a4dcSJakub Kicinski 
15473ff5a4dcSJakub Kicinski 	/* After the sort maps by name will be first on the list, because they
15483ff5a4dcSJakub Kicinski 	 * have idx == -1.  Resolve them.
15493ff5a4dcSJakub Kicinski 	 */
15503ff5a4dcSJakub Kicinski 	j = 0;
15513ff5a4dcSJakub Kicinski 	while (j < old_map_fds && map_replace[j].name) {
15523ff5a4dcSJakub Kicinski 		i = 0;
1553f74a53d9SJakub Kicinski 		bpf_object__for_each_map(map, obj) {
15543ff5a4dcSJakub Kicinski 			if (!strcmp(bpf_map__name(map), map_replace[j].name)) {
15553ff5a4dcSJakub Kicinski 				map_replace[j].idx = i;
15563ff5a4dcSJakub Kicinski 				break;
15573ff5a4dcSJakub Kicinski 			}
15583ff5a4dcSJakub Kicinski 			i++;
15593ff5a4dcSJakub Kicinski 		}
15603ff5a4dcSJakub Kicinski 		if (map_replace[j].idx == -1) {
15613ff5a4dcSJakub Kicinski 			p_err("unable to find map '%s'", map_replace[j].name);
15623ff5a4dcSJakub Kicinski 			goto err_close_obj;
15633ff5a4dcSJakub Kicinski 		}
15643ff5a4dcSJakub Kicinski 		j++;
15653ff5a4dcSJakub Kicinski 	}
15663ff5a4dcSJakub Kicinski 	/* Resort if any names were resolved */
15673ff5a4dcSJakub Kicinski 	if (j)
15683ff5a4dcSJakub Kicinski 		qsort(map_replace, old_map_fds, sizeof(*map_replace),
15693ff5a4dcSJakub Kicinski 		      map_replace_compar);
15703ff5a4dcSJakub Kicinski 
15713ff5a4dcSJakub Kicinski 	/* Set ifindex and name reuse */
15723ff5a4dcSJakub Kicinski 	j = 0;
15733ff5a4dcSJakub Kicinski 	idx = 0;
1574f74a53d9SJakub Kicinski 	bpf_object__for_each_map(map, obj) {
1575c8406848SJakub Kicinski 		if (!bpf_map__is_offload_neutral(map))
1576c8406848SJakub Kicinski 			bpf_map__set_ifindex(map, ifindex);
1577c8406848SJakub Kicinski 
15783ff5a4dcSJakub Kicinski 		if (j < old_map_fds && idx == map_replace[j].idx) {
15793ff5a4dcSJakub Kicinski 			err = bpf_map__reuse_fd(map, map_replace[j++].fd);
15803ff5a4dcSJakub Kicinski 			if (err) {
15813ff5a4dcSJakub Kicinski 				p_err("unable to set up map reuse: %d", err);
15823ff5a4dcSJakub Kicinski 				goto err_close_obj;
15833ff5a4dcSJakub Kicinski 			}
15843ff5a4dcSJakub Kicinski 
15853ff5a4dcSJakub Kicinski 			/* Next reuse wants to apply to the same map */
15863ff5a4dcSJakub Kicinski 			if (j < old_map_fds && map_replace[j].idx == idx) {
15873ff5a4dcSJakub Kicinski 				p_err("replacement for map idx %d specified more than once",
15883ff5a4dcSJakub Kicinski 				      idx);
15893ff5a4dcSJakub Kicinski 				goto err_close_obj;
15903ff5a4dcSJakub Kicinski 			}
15913ff5a4dcSJakub Kicinski 		}
15923ff5a4dcSJakub Kicinski 
15933ff5a4dcSJakub Kicinski 		idx++;
15943ff5a4dcSJakub Kicinski 	}
15953ff5a4dcSJakub Kicinski 	if (j < old_map_fds) {
15963ff5a4dcSJakub Kicinski 		p_err("map idx '%d' not used", map_replace[j].idx);
15973ff5a4dcSJakub Kicinski 		goto err_close_obj;
15983ff5a4dcSJakub Kicinski 	}
15993ff5a4dcSJakub Kicinski 
160055d77807SQuentin Monnet 	load_attr.obj = obj;
160155d77807SQuentin Monnet 	if (verifier_logs)
160255d77807SQuentin Monnet 		/* log_level1 + log_level2 + stats, but not stable UAPI */
160355d77807SQuentin Monnet 		load_attr.log_level = 1 + 2 + 4;
160455d77807SQuentin Monnet 
160555d77807SQuentin Monnet 	err = bpf_object__load_xattr(&load_attr);
1606c8406848SJakub Kicinski 	if (err) {
1607c8406848SJakub Kicinski 		p_err("failed to load object file");
1608c8406848SJakub Kicinski 		goto err_close_obj;
1609c8406848SJakub Kicinski 	}
1610c8406848SJakub Kicinski 
161177380998SStanislav Fomichev 	err = mount_bpffs_for_pin(pinfile);
161277380998SStanislav Fomichev 	if (err)
1613bfee71fbSJakub Kicinski 		goto err_close_obj;
161449a086c2SRoman Gushchin 
161577380998SStanislav Fomichev 	if (first_prog_only) {
16166f2b219bSHengqi Chen 		prog = bpf_object__next_program(obj, NULL);
161777380998SStanislav Fomichev 		if (!prog) {
161877380998SStanislav Fomichev 			p_err("object file doesn't contain any bpf program");
161977380998SStanislav Fomichev 			goto err_close_obj;
162077380998SStanislav Fomichev 		}
162177380998SStanislav Fomichev 
162277380998SStanislav Fomichev 		err = bpf_obj_pin(bpf_program__fd(prog), pinfile);
162377380998SStanislav Fomichev 		if (err) {
162477380998SStanislav Fomichev 			p_err("failed to pin program %s",
1625fd17e272SAndrii Nakryiko 			      bpf_program__section_name(prog));
162677380998SStanislav Fomichev 			goto err_close_obj;
162777380998SStanislav Fomichev 		}
162877380998SStanislav Fomichev 	} else {
162977380998SStanislav Fomichev 		err = bpf_object__pin_programs(obj, pinfile);
163077380998SStanislav Fomichev 		if (err) {
163177380998SStanislav Fomichev 			p_err("failed to pin all programs");
163277380998SStanislav Fomichev 			goto err_close_obj;
163377380998SStanislav Fomichev 		}
163477380998SStanislav Fomichev 	}
163577380998SStanislav Fomichev 
16363767a94bSStanislav Fomichev 	if (pinmaps) {
16373767a94bSStanislav Fomichev 		err = bpf_object__pin_maps(obj, pinmaps);
16383767a94bSStanislav Fomichev 		if (err) {
16393767a94bSStanislav Fomichev 			p_err("failed to pin all maps");
16403767a94bSStanislav Fomichev 			goto err_unpin;
16413767a94bSStanislav Fomichev 		}
16423767a94bSStanislav Fomichev 	}
16433767a94bSStanislav Fomichev 
164449a086c2SRoman Gushchin 	if (json_output)
164549a086c2SRoman Gushchin 		jsonw_null(json_wtr);
164649a086c2SRoman Gushchin 
1647bfee71fbSJakub Kicinski 	bpf_object__close(obj);
16483ff5a4dcSJakub Kicinski 	for (i = 0; i < old_map_fds; i++)
16493ff5a4dcSJakub Kicinski 		close(map_replace[i].fd);
16503ff5a4dcSJakub Kicinski 	free(map_replace);
1651bfee71fbSJakub Kicinski 
165249a086c2SRoman Gushchin 	return 0;
1653bfee71fbSJakub Kicinski 
16543767a94bSStanislav Fomichev err_unpin:
16553767a94bSStanislav Fomichev 	if (first_prog_only)
16563767a94bSStanislav Fomichev 		unlink(pinfile);
16573767a94bSStanislav Fomichev 	else
16583767a94bSStanislav Fomichev 		bpf_object__unpin_programs(obj, pinfile);
1659bfee71fbSJakub Kicinski err_close_obj:
1660bfee71fbSJakub Kicinski 	bpf_object__close(obj);
16613ff5a4dcSJakub Kicinski err_free_reuse_maps:
16623ff5a4dcSJakub Kicinski 	for (i = 0; i < old_map_fds; i++)
16633ff5a4dcSJakub Kicinski 		close(map_replace[i].fd);
16643ff5a4dcSJakub Kicinski 	free(map_replace);
1665bfee71fbSJakub Kicinski 	return -1;
166649a086c2SRoman Gushchin }
166749a086c2SRoman Gushchin 
1668d510296dSAlexei Starovoitov static int count_open_fds(void)
1669d510296dSAlexei Starovoitov {
1670d510296dSAlexei Starovoitov 	DIR *dp = opendir("/proc/self/fd");
1671d510296dSAlexei Starovoitov 	struct dirent *de;
1672d510296dSAlexei Starovoitov 	int cnt = -3;
1673d510296dSAlexei Starovoitov 
1674d510296dSAlexei Starovoitov 	if (!dp)
1675d510296dSAlexei Starovoitov 		return -1;
1676d510296dSAlexei Starovoitov 
1677d510296dSAlexei Starovoitov 	while ((de = readdir(dp)))
1678d510296dSAlexei Starovoitov 		cnt++;
1679d510296dSAlexei Starovoitov 
1680d510296dSAlexei Starovoitov 	closedir(dp);
1681d510296dSAlexei Starovoitov 	return cnt;
1682d510296dSAlexei Starovoitov }
1683d510296dSAlexei Starovoitov 
1684d510296dSAlexei Starovoitov static int try_loader(struct gen_loader_opts *gen)
1685d510296dSAlexei Starovoitov {
1686d510296dSAlexei Starovoitov 	struct bpf_load_and_run_opts opts = {};
1687d510296dSAlexei Starovoitov 	struct bpf_loader_ctx *ctx;
1688d510296dSAlexei Starovoitov 	int ctx_sz = sizeof(*ctx) + 64 * max(sizeof(struct bpf_map_desc),
1689d510296dSAlexei Starovoitov 					     sizeof(struct bpf_prog_desc));
1690d510296dSAlexei Starovoitov 	int log_buf_sz = (1u << 24) - 1;
1691d510296dSAlexei Starovoitov 	int err, fds_before, fd_delta;
1692d510296dSAlexei Starovoitov 	char *log_buf;
1693d510296dSAlexei Starovoitov 
1694d510296dSAlexei Starovoitov 	ctx = alloca(ctx_sz);
1695d510296dSAlexei Starovoitov 	memset(ctx, 0, ctx_sz);
1696d510296dSAlexei Starovoitov 	ctx->sz = ctx_sz;
1697d510296dSAlexei Starovoitov 	ctx->log_level = 1;
1698d510296dSAlexei Starovoitov 	ctx->log_size = log_buf_sz;
1699d510296dSAlexei Starovoitov 	log_buf = malloc(log_buf_sz);
1700d510296dSAlexei Starovoitov 	if (!log_buf)
1701d510296dSAlexei Starovoitov 		return -ENOMEM;
1702d510296dSAlexei Starovoitov 	ctx->log_buf = (long) log_buf;
1703d510296dSAlexei Starovoitov 	opts.ctx = ctx;
1704d510296dSAlexei Starovoitov 	opts.data = gen->data;
1705d510296dSAlexei Starovoitov 	opts.data_sz = gen->data_sz;
1706d510296dSAlexei Starovoitov 	opts.insns = gen->insns;
1707d510296dSAlexei Starovoitov 	opts.insns_sz = gen->insns_sz;
1708d510296dSAlexei Starovoitov 	fds_before = count_open_fds();
1709d510296dSAlexei Starovoitov 	err = bpf_load_and_run(&opts);
1710d510296dSAlexei Starovoitov 	fd_delta = count_open_fds() - fds_before;
1711d510296dSAlexei Starovoitov 	if (err < 0) {
1712d510296dSAlexei Starovoitov 		fprintf(stderr, "err %d\n%s\n%s", err, opts.errstr, log_buf);
1713d510296dSAlexei Starovoitov 		if (fd_delta)
1714d510296dSAlexei Starovoitov 			fprintf(stderr, "loader prog leaked %d FDs\n",
1715d510296dSAlexei Starovoitov 				fd_delta);
1716d510296dSAlexei Starovoitov 	}
1717d510296dSAlexei Starovoitov 	free(log_buf);
1718d510296dSAlexei Starovoitov 	return err;
1719d510296dSAlexei Starovoitov }
1720d510296dSAlexei Starovoitov 
1721d510296dSAlexei Starovoitov static int do_loader(int argc, char **argv)
1722d510296dSAlexei Starovoitov {
1723d510296dSAlexei Starovoitov 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, open_opts);
1724d510296dSAlexei Starovoitov 	DECLARE_LIBBPF_OPTS(gen_loader_opts, gen);
1725d510296dSAlexei Starovoitov 	struct bpf_object_load_attr load_attr = {};
1726d510296dSAlexei Starovoitov 	struct bpf_object *obj;
1727d510296dSAlexei Starovoitov 	const char *file;
1728d510296dSAlexei Starovoitov 	int err = 0;
1729d510296dSAlexei Starovoitov 
1730d510296dSAlexei Starovoitov 	if (!REQ_ARGS(1))
1731d510296dSAlexei Starovoitov 		return -1;
1732d510296dSAlexei Starovoitov 	file = GET_ARG();
1733d510296dSAlexei Starovoitov 
1734d510296dSAlexei Starovoitov 	obj = bpf_object__open_file(file, &open_opts);
1735d510296dSAlexei Starovoitov 	if (libbpf_get_error(obj)) {
1736d510296dSAlexei Starovoitov 		p_err("failed to open object file");
1737d510296dSAlexei Starovoitov 		goto err_close_obj;
1738d510296dSAlexei Starovoitov 	}
1739d510296dSAlexei Starovoitov 
1740d510296dSAlexei Starovoitov 	err = bpf_object__gen_loader(obj, &gen);
1741d510296dSAlexei Starovoitov 	if (err)
1742d510296dSAlexei Starovoitov 		goto err_close_obj;
1743d510296dSAlexei Starovoitov 
1744d510296dSAlexei Starovoitov 	load_attr.obj = obj;
1745d510296dSAlexei Starovoitov 	if (verifier_logs)
1746d510296dSAlexei Starovoitov 		/* log_level1 + log_level2 + stats, but not stable UAPI */
1747d510296dSAlexei Starovoitov 		load_attr.log_level = 1 + 2 + 4;
1748d510296dSAlexei Starovoitov 
1749d510296dSAlexei Starovoitov 	err = bpf_object__load_xattr(&load_attr);
1750d510296dSAlexei Starovoitov 	if (err) {
1751d510296dSAlexei Starovoitov 		p_err("failed to load object file");
1752d510296dSAlexei Starovoitov 		goto err_close_obj;
1753d510296dSAlexei Starovoitov 	}
1754d510296dSAlexei Starovoitov 
1755d510296dSAlexei Starovoitov 	if (verifier_logs) {
1756d510296dSAlexei Starovoitov 		struct dump_data dd = {};
1757d510296dSAlexei Starovoitov 
1758d510296dSAlexei Starovoitov 		kernel_syms_load(&dd);
1759d510296dSAlexei Starovoitov 		dump_xlated_plain(&dd, (void *)gen.insns, gen.insns_sz, false, false);
1760d510296dSAlexei Starovoitov 		kernel_syms_destroy(&dd);
1761d510296dSAlexei Starovoitov 	}
1762d510296dSAlexei Starovoitov 	err = try_loader(&gen);
1763d510296dSAlexei Starovoitov err_close_obj:
1764d510296dSAlexei Starovoitov 	bpf_object__close(obj);
1765d510296dSAlexei Starovoitov 	return err;
1766d510296dSAlexei Starovoitov }
1767d510296dSAlexei Starovoitov 
176877380998SStanislav Fomichev static int do_load(int argc, char **argv)
176977380998SStanislav Fomichev {
1770d510296dSAlexei Starovoitov 	if (use_loader)
1771d510296dSAlexei Starovoitov 		return do_loader(argc, argv);
177277380998SStanislav Fomichev 	return load_with_options(argc, argv, true);
177377380998SStanislav Fomichev }
177477380998SStanislav Fomichev 
177577380998SStanislav Fomichev static int do_loadall(int argc, char **argv)
177677380998SStanislav Fomichev {
177777380998SStanislav Fomichev 	return load_with_options(argc, argv, false);
177877380998SStanislav Fomichev }
177977380998SStanislav Fomichev 
178047c09d6aSSong Liu #ifdef BPFTOOL_WITHOUT_SKELETONS
178147c09d6aSSong Liu 
178247c09d6aSSong Liu static int do_profile(int argc, char **argv)
178347c09d6aSSong Liu {
178414e5728fSSong Liu 	p_err("bpftool prog profile command is not supported. Please build bpftool with clang >= 10.0.0");
178547c09d6aSSong Liu 	return 0;
178647c09d6aSSong Liu }
178747c09d6aSSong Liu 
178847c09d6aSSong Liu #else /* BPFTOOL_WITHOUT_SKELETONS */
178947c09d6aSSong Liu 
179047c09d6aSSong Liu #include "profiler.skel.h"
179147c09d6aSSong Liu 
179247c09d6aSSong Liu struct profile_metric {
179347c09d6aSSong Liu 	const char *name;
179447c09d6aSSong Liu 	struct bpf_perf_event_value val;
179547c09d6aSSong Liu 	struct perf_event_attr attr;
179647c09d6aSSong Liu 	bool selected;
179747c09d6aSSong Liu 
179847c09d6aSSong Liu 	/* calculate ratios like instructions per cycle */
179947c09d6aSSong Liu 	const int ratio_metric; /* 0 for N/A, 1 for index 0 (cycles) */
180047c09d6aSSong Liu 	const char *ratio_desc;
180147c09d6aSSong Liu 	const float ratio_mul;
180247c09d6aSSong Liu } metrics[] = {
180347c09d6aSSong Liu 	{
180447c09d6aSSong Liu 		.name = "cycles",
180547c09d6aSSong Liu 		.attr = {
180647c09d6aSSong Liu 			.type = PERF_TYPE_HARDWARE,
180747c09d6aSSong Liu 			.config = PERF_COUNT_HW_CPU_CYCLES,
180847c09d6aSSong Liu 			.exclude_user = 1,
180947c09d6aSSong Liu 		},
181047c09d6aSSong Liu 	},
181147c09d6aSSong Liu 	{
181247c09d6aSSong Liu 		.name = "instructions",
181347c09d6aSSong Liu 		.attr = {
181447c09d6aSSong Liu 			.type = PERF_TYPE_HARDWARE,
181547c09d6aSSong Liu 			.config = PERF_COUNT_HW_INSTRUCTIONS,
181647c09d6aSSong Liu 			.exclude_user = 1,
181747c09d6aSSong Liu 		},
181847c09d6aSSong Liu 		.ratio_metric = 1,
181947c09d6aSSong Liu 		.ratio_desc = "insns per cycle",
182047c09d6aSSong Liu 		.ratio_mul = 1.0,
182147c09d6aSSong Liu 	},
182247c09d6aSSong Liu 	{
182347c09d6aSSong Liu 		.name = "l1d_loads",
182447c09d6aSSong Liu 		.attr = {
182547c09d6aSSong Liu 			.type = PERF_TYPE_HW_CACHE,
182647c09d6aSSong Liu 			.config =
182747c09d6aSSong Liu 				PERF_COUNT_HW_CACHE_L1D |
182847c09d6aSSong Liu 				(PERF_COUNT_HW_CACHE_OP_READ << 8) |
182947c09d6aSSong Liu 				(PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16),
183047c09d6aSSong Liu 			.exclude_user = 1,
183147c09d6aSSong Liu 		},
183247c09d6aSSong Liu 	},
183347c09d6aSSong Liu 	{
183447c09d6aSSong Liu 		.name = "llc_misses",
183547c09d6aSSong Liu 		.attr = {
183647c09d6aSSong Liu 			.type = PERF_TYPE_HW_CACHE,
183747c09d6aSSong Liu 			.config =
183847c09d6aSSong Liu 				PERF_COUNT_HW_CACHE_LL |
183947c09d6aSSong Liu 				(PERF_COUNT_HW_CACHE_OP_READ << 8) |
184047c09d6aSSong Liu 				(PERF_COUNT_HW_CACHE_RESULT_MISS << 16),
184147c09d6aSSong Liu 			.exclude_user = 1
184247c09d6aSSong Liu 		},
184347c09d6aSSong Liu 		.ratio_metric = 2,
184447c09d6aSSong Liu 		.ratio_desc = "LLC misses per million insns",
184547c09d6aSSong Liu 		.ratio_mul = 1e6,
184647c09d6aSSong Liu 	},
1847450d060eSYonghong Song 	{
1848450d060eSYonghong Song 		.name = "itlb_misses",
1849450d060eSYonghong Song 		.attr = {
1850450d060eSYonghong Song 			.type = PERF_TYPE_HW_CACHE,
1851450d060eSYonghong Song 			.config =
1852450d060eSYonghong Song 				PERF_COUNT_HW_CACHE_ITLB |
1853450d060eSYonghong Song 				(PERF_COUNT_HW_CACHE_OP_READ << 8) |
1854450d060eSYonghong Song 				(PERF_COUNT_HW_CACHE_RESULT_MISS << 16),
1855450d060eSYonghong Song 			.exclude_user = 1
1856450d060eSYonghong Song 		},
1857450d060eSYonghong Song 		.ratio_metric = 2,
1858450d060eSYonghong Song 		.ratio_desc = "itlb misses per million insns",
1859450d060eSYonghong Song 		.ratio_mul = 1e6,
1860450d060eSYonghong Song 	},
1861450d060eSYonghong Song 	{
1862450d060eSYonghong Song 		.name = "dtlb_misses",
1863450d060eSYonghong Song 		.attr = {
1864450d060eSYonghong Song 			.type = PERF_TYPE_HW_CACHE,
1865450d060eSYonghong Song 			.config =
1866450d060eSYonghong Song 				PERF_COUNT_HW_CACHE_DTLB |
1867450d060eSYonghong Song 				(PERF_COUNT_HW_CACHE_OP_READ << 8) |
1868450d060eSYonghong Song 				(PERF_COUNT_HW_CACHE_RESULT_MISS << 16),
1869450d060eSYonghong Song 			.exclude_user = 1
1870450d060eSYonghong Song 		},
1871450d060eSYonghong Song 		.ratio_metric = 2,
1872450d060eSYonghong Song 		.ratio_desc = "dtlb misses per million insns",
1873450d060eSYonghong Song 		.ratio_mul = 1e6,
1874450d060eSYonghong Song 	},
187547c09d6aSSong Liu };
187647c09d6aSSong Liu 
187747c09d6aSSong Liu static __u64 profile_total_count;
187847c09d6aSSong Liu 
187947c09d6aSSong Liu #define MAX_NUM_PROFILE_METRICS 4
188047c09d6aSSong Liu 
188147c09d6aSSong Liu static int profile_parse_metrics(int argc, char **argv)
188247c09d6aSSong Liu {
188347c09d6aSSong Liu 	unsigned int metric_cnt;
188447c09d6aSSong Liu 	int selected_cnt = 0;
188547c09d6aSSong Liu 	unsigned int i;
188647c09d6aSSong Liu 
188747c09d6aSSong Liu 	metric_cnt = sizeof(metrics) / sizeof(struct profile_metric);
188847c09d6aSSong Liu 
188947c09d6aSSong Liu 	while (argc > 0) {
189047c09d6aSSong Liu 		for (i = 0; i < metric_cnt; i++) {
189147c09d6aSSong Liu 			if (is_prefix(argv[0], metrics[i].name)) {
189247c09d6aSSong Liu 				if (!metrics[i].selected)
189347c09d6aSSong Liu 					selected_cnt++;
189447c09d6aSSong Liu 				metrics[i].selected = true;
189547c09d6aSSong Liu 				break;
189647c09d6aSSong Liu 			}
189747c09d6aSSong Liu 		}
189847c09d6aSSong Liu 		if (i == metric_cnt) {
189947c09d6aSSong Liu 			p_err("unknown metric %s", argv[0]);
190047c09d6aSSong Liu 			return -1;
190147c09d6aSSong Liu 		}
190247c09d6aSSong Liu 		NEXT_ARG();
190347c09d6aSSong Liu 	}
190447c09d6aSSong Liu 	if (selected_cnt > MAX_NUM_PROFILE_METRICS) {
190547c09d6aSSong Liu 		p_err("too many (%d) metrics, please specify no more than %d metrics at at time",
190647c09d6aSSong Liu 		      selected_cnt, MAX_NUM_PROFILE_METRICS);
190747c09d6aSSong Liu 		return -1;
190847c09d6aSSong Liu 	}
190947c09d6aSSong Liu 	return selected_cnt;
191047c09d6aSSong Liu }
191147c09d6aSSong Liu 
191247c09d6aSSong Liu static void profile_read_values(struct profiler_bpf *obj)
191347c09d6aSSong Liu {
191447c09d6aSSong Liu 	__u32 m, cpu, num_cpu = obj->rodata->num_cpu;
191547c09d6aSSong Liu 	int reading_map_fd, count_map_fd;
191647c09d6aSSong Liu 	__u64 counts[num_cpu];
191747c09d6aSSong Liu 	__u32 key = 0;
191847c09d6aSSong Liu 	int err;
191947c09d6aSSong Liu 
192047c09d6aSSong Liu 	reading_map_fd = bpf_map__fd(obj->maps.accum_readings);
192147c09d6aSSong Liu 	count_map_fd = bpf_map__fd(obj->maps.counts);
192247c09d6aSSong Liu 	if (reading_map_fd < 0 || count_map_fd < 0) {
192347c09d6aSSong Liu 		p_err("failed to get fd for map");
192447c09d6aSSong Liu 		return;
192547c09d6aSSong Liu 	}
192647c09d6aSSong Liu 
192747c09d6aSSong Liu 	err = bpf_map_lookup_elem(count_map_fd, &key, counts);
192847c09d6aSSong Liu 	if (err) {
192947c09d6aSSong Liu 		p_err("failed to read count_map: %s", strerror(errno));
193047c09d6aSSong Liu 		return;
193147c09d6aSSong Liu 	}
193247c09d6aSSong Liu 
193347c09d6aSSong Liu 	profile_total_count = 0;
193447c09d6aSSong Liu 	for (cpu = 0; cpu < num_cpu; cpu++)
193547c09d6aSSong Liu 		profile_total_count += counts[cpu];
193647c09d6aSSong Liu 
193747c09d6aSSong Liu 	for (m = 0; m < ARRAY_SIZE(metrics); m++) {
193847c09d6aSSong Liu 		struct bpf_perf_event_value values[num_cpu];
193947c09d6aSSong Liu 
194047c09d6aSSong Liu 		if (!metrics[m].selected)
194147c09d6aSSong Liu 			continue;
194247c09d6aSSong Liu 
194347c09d6aSSong Liu 		err = bpf_map_lookup_elem(reading_map_fd, &key, values);
194447c09d6aSSong Liu 		if (err) {
194547c09d6aSSong Liu 			p_err("failed to read reading_map: %s",
194647c09d6aSSong Liu 			      strerror(errno));
194747c09d6aSSong Liu 			return;
194847c09d6aSSong Liu 		}
194947c09d6aSSong Liu 		for (cpu = 0; cpu < num_cpu; cpu++) {
195047c09d6aSSong Liu 			metrics[m].val.counter += values[cpu].counter;
195147c09d6aSSong Liu 			metrics[m].val.enabled += values[cpu].enabled;
195247c09d6aSSong Liu 			metrics[m].val.running += values[cpu].running;
195347c09d6aSSong Liu 		}
195447c09d6aSSong Liu 		key++;
195547c09d6aSSong Liu 	}
195647c09d6aSSong Liu }
195747c09d6aSSong Liu 
195847c09d6aSSong Liu static void profile_print_readings_json(void)
195947c09d6aSSong Liu {
196047c09d6aSSong Liu 	__u32 m;
196147c09d6aSSong Liu 
196247c09d6aSSong Liu 	jsonw_start_array(json_wtr);
196347c09d6aSSong Liu 	for (m = 0; m < ARRAY_SIZE(metrics); m++) {
196447c09d6aSSong Liu 		if (!metrics[m].selected)
196547c09d6aSSong Liu 			continue;
196647c09d6aSSong Liu 		jsonw_start_object(json_wtr);
196747c09d6aSSong Liu 		jsonw_string_field(json_wtr, "metric", metrics[m].name);
196847c09d6aSSong Liu 		jsonw_lluint_field(json_wtr, "run_cnt", profile_total_count);
196947c09d6aSSong Liu 		jsonw_lluint_field(json_wtr, "value", metrics[m].val.counter);
197047c09d6aSSong Liu 		jsonw_lluint_field(json_wtr, "enabled", metrics[m].val.enabled);
197147c09d6aSSong Liu 		jsonw_lluint_field(json_wtr, "running", metrics[m].val.running);
197247c09d6aSSong Liu 
197347c09d6aSSong Liu 		jsonw_end_object(json_wtr);
197447c09d6aSSong Liu 	}
197547c09d6aSSong Liu 	jsonw_end_array(json_wtr);
197647c09d6aSSong Liu }
197747c09d6aSSong Liu 
197847c09d6aSSong Liu static void profile_print_readings_plain(void)
197947c09d6aSSong Liu {
198047c09d6aSSong Liu 	__u32 m;
198147c09d6aSSong Liu 
198247c09d6aSSong Liu 	printf("\n%18llu %-20s\n", profile_total_count, "run_cnt");
198347c09d6aSSong Liu 	for (m = 0; m < ARRAY_SIZE(metrics); m++) {
198447c09d6aSSong Liu 		struct bpf_perf_event_value *val = &metrics[m].val;
198547c09d6aSSong Liu 		int r;
198647c09d6aSSong Liu 
198747c09d6aSSong Liu 		if (!metrics[m].selected)
198847c09d6aSSong Liu 			continue;
198947c09d6aSSong Liu 		printf("%18llu %-20s", val->counter, metrics[m].name);
199047c09d6aSSong Liu 
199147c09d6aSSong Liu 		r = metrics[m].ratio_metric - 1;
199247c09d6aSSong Liu 		if (r >= 0 && metrics[r].selected &&
199347c09d6aSSong Liu 		    metrics[r].val.counter > 0) {
199447c09d6aSSong Liu 			printf("# %8.2f %-30s",
199547c09d6aSSong Liu 			       val->counter * metrics[m].ratio_mul /
199647c09d6aSSong Liu 			       metrics[r].val.counter,
199747c09d6aSSong Liu 			       metrics[m].ratio_desc);
199847c09d6aSSong Liu 		} else {
199947c09d6aSSong Liu 			printf("%-41s", "");
200047c09d6aSSong Liu 		}
200147c09d6aSSong Liu 
200247c09d6aSSong Liu 		if (val->enabled > val->running)
200347c09d6aSSong Liu 			printf("(%4.2f%%)",
200447c09d6aSSong Liu 			       val->running * 100.0 / val->enabled);
200547c09d6aSSong Liu 		printf("\n");
200647c09d6aSSong Liu 	}
200747c09d6aSSong Liu }
200847c09d6aSSong Liu 
200947c09d6aSSong Liu static void profile_print_readings(void)
201047c09d6aSSong Liu {
201147c09d6aSSong Liu 	if (json_output)
201247c09d6aSSong Liu 		profile_print_readings_json();
201347c09d6aSSong Liu 	else
201447c09d6aSSong Liu 		profile_print_readings_plain();
201547c09d6aSSong Liu }
201647c09d6aSSong Liu 
201747c09d6aSSong Liu static char *profile_target_name(int tgt_fd)
201847c09d6aSSong Liu {
201947c09d6aSSong Liu 	struct bpf_prog_info_linear *info_linear;
202047c09d6aSSong Liu 	struct bpf_func_info *func_info;
202147c09d6aSSong Liu 	const struct btf_type *t;
2022369e955bSQuentin Monnet 	struct btf *btf = NULL;
202347c09d6aSSong Liu 	char *name = NULL;
202447c09d6aSSong Liu 
202547c09d6aSSong Liu 	info_linear = bpf_program__get_prog_info_linear(
202647c09d6aSSong Liu 		tgt_fd, 1UL << BPF_PROG_INFO_FUNC_INFO);
202747c09d6aSSong Liu 	if (IS_ERR_OR_NULL(info_linear)) {
202847c09d6aSSong Liu 		p_err("failed to get info_linear for prog FD %d", tgt_fd);
202947c09d6aSSong Liu 		return NULL;
203047c09d6aSSong Liu 	}
203147c09d6aSSong Liu 
203286f4b7f2SQuentin Monnet 	if (info_linear->info.btf_id == 0) {
203347c09d6aSSong Liu 		p_err("prog FD %d doesn't have valid btf", tgt_fd);
203447c09d6aSSong Liu 		goto out;
203547c09d6aSSong Liu 	}
203647c09d6aSSong Liu 
203786f4b7f2SQuentin Monnet 	btf = btf__load_from_kernel_by_id(info_linear->info.btf_id);
203886f4b7f2SQuentin Monnet 	if (libbpf_get_error(btf)) {
203986f4b7f2SQuentin Monnet 		p_err("failed to load btf for prog FD %d", tgt_fd);
204086f4b7f2SQuentin Monnet 		goto out;
204186f4b7f2SQuentin Monnet 	}
204286f4b7f2SQuentin Monnet 
204309f44b75SAndrii Nakryiko 	func_info = u64_to_ptr(info_linear->info.func_info);
204447c09d6aSSong Liu 	t = btf__type_by_id(btf, func_info[0].type_id);
204547c09d6aSSong Liu 	if (!t) {
204647c09d6aSSong Liu 		p_err("btf %d doesn't have type %d",
204747c09d6aSSong Liu 		      info_linear->info.btf_id, func_info[0].type_id);
204847c09d6aSSong Liu 		goto out;
204947c09d6aSSong Liu 	}
205047c09d6aSSong Liu 	name = strdup(btf__name_by_offset(btf, t->name_off));
205147c09d6aSSong Liu out:
2052369e955bSQuentin Monnet 	btf__free(btf);
205347c09d6aSSong Liu 	free(info_linear);
205447c09d6aSSong Liu 	return name;
205547c09d6aSSong Liu }
205647c09d6aSSong Liu 
205747c09d6aSSong Liu static struct profiler_bpf *profile_obj;
205847c09d6aSSong Liu static int profile_tgt_fd = -1;
205947c09d6aSSong Liu static char *profile_tgt_name;
206047c09d6aSSong Liu static int *profile_perf_events;
206147c09d6aSSong Liu static int profile_perf_event_cnt;
206247c09d6aSSong Liu 
206347c09d6aSSong Liu static void profile_close_perf_events(struct profiler_bpf *obj)
206447c09d6aSSong Liu {
206547c09d6aSSong Liu 	int i;
206647c09d6aSSong Liu 
206747c09d6aSSong Liu 	for (i = profile_perf_event_cnt - 1; i >= 0; i--)
206847c09d6aSSong Liu 		close(profile_perf_events[i]);
206947c09d6aSSong Liu 
207047c09d6aSSong Liu 	free(profile_perf_events);
207147c09d6aSSong Liu 	profile_perf_event_cnt = 0;
207247c09d6aSSong Liu }
207347c09d6aSSong Liu 
207447c09d6aSSong Liu static int profile_open_perf_events(struct profiler_bpf *obj)
207547c09d6aSSong Liu {
207647c09d6aSSong Liu 	unsigned int cpu, m;
207747c09d6aSSong Liu 	int map_fd, pmu_fd;
207847c09d6aSSong Liu 
207947c09d6aSSong Liu 	profile_perf_events = calloc(
208047c09d6aSSong Liu 		sizeof(int), obj->rodata->num_cpu * obj->rodata->num_metric);
208147c09d6aSSong Liu 	if (!profile_perf_events) {
208247c09d6aSSong Liu 		p_err("failed to allocate memory for perf_event array: %s",
208347c09d6aSSong Liu 		      strerror(errno));
208447c09d6aSSong Liu 		return -1;
208547c09d6aSSong Liu 	}
208647c09d6aSSong Liu 	map_fd = bpf_map__fd(obj->maps.events);
208747c09d6aSSong Liu 	if (map_fd < 0) {
208847c09d6aSSong Liu 		p_err("failed to get fd for events map");
208947c09d6aSSong Liu 		return -1;
209047c09d6aSSong Liu 	}
209147c09d6aSSong Liu 
209247c09d6aSSong Liu 	for (m = 0; m < ARRAY_SIZE(metrics); m++) {
209347c09d6aSSong Liu 		if (!metrics[m].selected)
209447c09d6aSSong Liu 			continue;
209547c09d6aSSong Liu 		for (cpu = 0; cpu < obj->rodata->num_cpu; cpu++) {
209647c09d6aSSong Liu 			pmu_fd = syscall(__NR_perf_event_open, &metrics[m].attr,
209747c09d6aSSong Liu 					 -1/*pid*/, cpu, -1/*group_fd*/, 0);
209847c09d6aSSong Liu 			if (pmu_fd < 0 ||
209947c09d6aSSong Liu 			    bpf_map_update_elem(map_fd, &profile_perf_event_cnt,
210047c09d6aSSong Liu 						&pmu_fd, BPF_ANY) ||
210147c09d6aSSong Liu 			    ioctl(pmu_fd, PERF_EVENT_IOC_ENABLE, 0)) {
210247c09d6aSSong Liu 				p_err("failed to create event %s on cpu %d",
210347c09d6aSSong Liu 				      metrics[m].name, cpu);
210447c09d6aSSong Liu 				return -1;
210547c09d6aSSong Liu 			}
210647c09d6aSSong Liu 			profile_perf_events[profile_perf_event_cnt++] = pmu_fd;
210747c09d6aSSong Liu 		}
210847c09d6aSSong Liu 	}
210947c09d6aSSong Liu 	return 0;
211047c09d6aSSong Liu }
211147c09d6aSSong Liu 
211247c09d6aSSong Liu static void profile_print_and_cleanup(void)
211347c09d6aSSong Liu {
211447c09d6aSSong Liu 	profile_close_perf_events(profile_obj);
211547c09d6aSSong Liu 	profile_read_values(profile_obj);
211647c09d6aSSong Liu 	profile_print_readings();
211747c09d6aSSong Liu 	profiler_bpf__destroy(profile_obj);
211847c09d6aSSong Liu 
211947c09d6aSSong Liu 	close(profile_tgt_fd);
212047c09d6aSSong Liu 	free(profile_tgt_name);
212147c09d6aSSong Liu }
212247c09d6aSSong Liu 
212347c09d6aSSong Liu static void int_exit(int signo)
212447c09d6aSSong Liu {
212547c09d6aSSong Liu 	profile_print_and_cleanup();
212647c09d6aSSong Liu 	exit(0);
212747c09d6aSSong Liu }
212847c09d6aSSong Liu 
212947c09d6aSSong Liu static int do_profile(int argc, char **argv)
213047c09d6aSSong Liu {
213147c09d6aSSong Liu 	int num_metric, num_cpu, err = -1;
213247c09d6aSSong Liu 	struct bpf_program *prog;
213347c09d6aSSong Liu 	unsigned long duration;
213447c09d6aSSong Liu 	char *endptr;
213547c09d6aSSong Liu 
213647c09d6aSSong Liu 	/* we at least need two args for the prog and one metric */
213747c09d6aSSong Liu 	if (!REQ_ARGS(3))
213847c09d6aSSong Liu 		return -EINVAL;
213947c09d6aSSong Liu 
214047c09d6aSSong Liu 	/* parse target fd */
214147c09d6aSSong Liu 	profile_tgt_fd = prog_parse_fd(&argc, &argv);
214247c09d6aSSong Liu 	if (profile_tgt_fd < 0) {
214347c09d6aSSong Liu 		p_err("failed to parse fd");
214447c09d6aSSong Liu 		return -1;
214547c09d6aSSong Liu 	}
214647c09d6aSSong Liu 
214747c09d6aSSong Liu 	/* parse profiling optional duration */
214847c09d6aSSong Liu 	if (argc > 2 && is_prefix(argv[0], "duration")) {
214947c09d6aSSong Liu 		NEXT_ARG();
215047c09d6aSSong Liu 		duration = strtoul(*argv, &endptr, 0);
215147c09d6aSSong Liu 		if (*endptr)
215247c09d6aSSong Liu 			usage();
215347c09d6aSSong Liu 		NEXT_ARG();
215447c09d6aSSong Liu 	} else {
215547c09d6aSSong Liu 		duration = UINT_MAX;
215647c09d6aSSong Liu 	}
215747c09d6aSSong Liu 
215847c09d6aSSong Liu 	num_metric = profile_parse_metrics(argc, argv);
215947c09d6aSSong Liu 	if (num_metric <= 0)
216047c09d6aSSong Liu 		goto out;
216147c09d6aSSong Liu 
216247c09d6aSSong Liu 	num_cpu = libbpf_num_possible_cpus();
216347c09d6aSSong Liu 	if (num_cpu <= 0) {
216447c09d6aSSong Liu 		p_err("failed to identify number of CPUs");
216547c09d6aSSong Liu 		goto out;
216647c09d6aSSong Liu 	}
216747c09d6aSSong Liu 
216847c09d6aSSong Liu 	profile_obj = profiler_bpf__open();
216947c09d6aSSong Liu 	if (!profile_obj) {
217047c09d6aSSong Liu 		p_err("failed to open and/or load BPF object");
217147c09d6aSSong Liu 		goto out;
217247c09d6aSSong Liu 	}
217347c09d6aSSong Liu 
217447c09d6aSSong Liu 	profile_obj->rodata->num_cpu = num_cpu;
217547c09d6aSSong Liu 	profile_obj->rodata->num_metric = num_metric;
217647c09d6aSSong Liu 
217747c09d6aSSong Liu 	/* adjust map sizes */
217847c09d6aSSong Liu 	bpf_map__resize(profile_obj->maps.events, num_metric * num_cpu);
217947c09d6aSSong Liu 	bpf_map__resize(profile_obj->maps.fentry_readings, num_metric);
218047c09d6aSSong Liu 	bpf_map__resize(profile_obj->maps.accum_readings, num_metric);
218147c09d6aSSong Liu 	bpf_map__resize(profile_obj->maps.counts, 1);
218247c09d6aSSong Liu 
218347c09d6aSSong Liu 	/* change target name */
218447c09d6aSSong Liu 	profile_tgt_name = profile_target_name(profile_tgt_fd);
218547c09d6aSSong Liu 	if (!profile_tgt_name)
218647c09d6aSSong Liu 		goto out;
218747c09d6aSSong Liu 
218847c09d6aSSong Liu 	bpf_object__for_each_program(prog, profile_obj->obj) {
218947c09d6aSSong Liu 		err = bpf_program__set_attach_target(prog, profile_tgt_fd,
219047c09d6aSSong Liu 						     profile_tgt_name);
219147c09d6aSSong Liu 		if (err) {
219247c09d6aSSong Liu 			p_err("failed to set attach target\n");
219347c09d6aSSong Liu 			goto out;
219447c09d6aSSong Liu 		}
219547c09d6aSSong Liu 	}
219647c09d6aSSong Liu 
219747c09d6aSSong Liu 	set_max_rlimit();
219847c09d6aSSong Liu 	err = profiler_bpf__load(profile_obj);
219947c09d6aSSong Liu 	if (err) {
220047c09d6aSSong Liu 		p_err("failed to load profile_obj");
220147c09d6aSSong Liu 		goto out;
220247c09d6aSSong Liu 	}
220347c09d6aSSong Liu 
220447c09d6aSSong Liu 	err = profile_open_perf_events(profile_obj);
220547c09d6aSSong Liu 	if (err)
220647c09d6aSSong Liu 		goto out;
220747c09d6aSSong Liu 
220847c09d6aSSong Liu 	err = profiler_bpf__attach(profile_obj);
220947c09d6aSSong Liu 	if (err) {
221047c09d6aSSong Liu 		p_err("failed to attach profile_obj");
221147c09d6aSSong Liu 		goto out;
221247c09d6aSSong Liu 	}
221347c09d6aSSong Liu 	signal(SIGINT, int_exit);
221447c09d6aSSong Liu 
221547c09d6aSSong Liu 	sleep(duration);
221647c09d6aSSong Liu 	profile_print_and_cleanup();
221747c09d6aSSong Liu 	return 0;
221847c09d6aSSong Liu 
221947c09d6aSSong Liu out:
222047c09d6aSSong Liu 	profile_close_perf_events(profile_obj);
222147c09d6aSSong Liu 	if (profile_obj)
222247c09d6aSSong Liu 		profiler_bpf__destroy(profile_obj);
222347c09d6aSSong Liu 	close(profile_tgt_fd);
222447c09d6aSSong Liu 	free(profile_tgt_name);
222547c09d6aSSong Liu 	return err;
222647c09d6aSSong Liu }
222747c09d6aSSong Liu 
222847c09d6aSSong Liu #endif /* BPFTOOL_WITHOUT_SKELETONS */
222947c09d6aSSong Liu 
223071bb428fSJakub Kicinski static int do_help(int argc, char **argv)
223171bb428fSJakub Kicinski {
2232004b45c0SQuentin Monnet 	if (json_output) {
2233004b45c0SQuentin Monnet 		jsonw_null(json_wtr);
2234004b45c0SQuentin Monnet 		return 0;
2235004b45c0SQuentin Monnet 	}
2236004b45c0SQuentin Monnet 
223771bb428fSJakub Kicinski 	fprintf(stderr,
223890040351SQuentin Monnet 		"Usage: %1$s %2$s { show | list } [PROG]\n"
223990040351SQuentin Monnet 		"       %1$s %2$s dump xlated PROG [{ file FILE | opcodes | visual | linum }]\n"
224090040351SQuentin Monnet 		"       %1$s %2$s dump jited  PROG [{ file FILE | opcodes | linum }]\n"
224190040351SQuentin Monnet 		"       %1$s %2$s pin   PROG FILE\n"
224290040351SQuentin Monnet 		"       %1$s %2$s { load | loadall } OBJ  PATH \\\n"
224377380998SStanislav Fomichev 		"                         [type TYPE] [dev NAME] \\\n"
22443767a94bSStanislav Fomichev 		"                         [map { idx IDX | name NAME } MAP]\\\n"
22453767a94bSStanislav Fomichev 		"                         [pinmaps MAP_DIR]\n"
224690040351SQuentin Monnet 		"       %1$s %2$s attach PROG ATTACH_TYPE [MAP]\n"
224790040351SQuentin Monnet 		"       %1$s %2$s detach PROG ATTACH_TYPE [MAP]\n"
224890040351SQuentin Monnet 		"       %1$s %2$s run PROG \\\n"
2249ba95c745SQuentin Monnet 		"                         data_in FILE \\\n"
2250ba95c745SQuentin Monnet 		"                         [data_out FILE [data_size_out L]] \\\n"
2251ba95c745SQuentin Monnet 		"                         [ctx_in FILE [ctx_out FILE [ctx_size_out M]]] \\\n"
2252ba95c745SQuentin Monnet 		"                         [repeat N]\n"
225390040351SQuentin Monnet 		"       %1$s %2$s profile PROG [duration DURATION] METRICs\n"
225490040351SQuentin Monnet 		"       %1$s %2$s tracelog\n"
225590040351SQuentin Monnet 		"       %1$s %2$s help\n"
225671bb428fSJakub Kicinski 		"\n"
22573ff5a4dcSJakub Kicinski 		"       " HELP_SPEC_MAP "\n"
225871bb428fSJakub Kicinski 		"       " HELP_SPEC_PROGRAM "\n"
225949f2cba3SJakub Kicinski 		"       TYPE := { socket | kprobe | kretprobe | classifier | action |\n"
226049f2cba3SJakub Kicinski 		"                 tracepoint | raw_tracepoint | xdp | perf_event | cgroup/skb |\n"
226149f2cba3SJakub Kicinski 		"                 cgroup/sock | cgroup/dev | lwt_in | lwt_out | lwt_xmit |\n"
226249f2cba3SJakub Kicinski 		"                 lwt_seg6local | sockops | sk_skb | sk_msg | lirc_mode2 |\n"
2263f25377eeSAndrey Ignatov 		"                 sk_reuseport | flow_dissector | cgroup/sysctl |\n"
226449f2cba3SJakub Kicinski 		"                 cgroup/bind4 | cgroup/bind6 | cgroup/post_bind4 |\n"
226549f2cba3SJakub Kicinski 		"                 cgroup/post_bind6 | cgroup/connect4 | cgroup/connect6 |\n"
226605ee19c1SDaniel Borkmann 		"                 cgroup/getpeername4 | cgroup/getpeername6 |\n"
226705ee19c1SDaniel Borkmann 		"                 cgroup/getsockname4 | cgroup/getsockname6 | cgroup/sendmsg4 |\n"
226805ee19c1SDaniel Borkmann 		"                 cgroup/sendmsg6 | cgroup/recvmsg4 | cgroup/recvmsg6 |\n"
2269a8deba85SLiu Jian 		"                 cgroup/getsockopt | cgroup/setsockopt | cgroup/sock_release |\n"
227093a3545dSJakub Sitnicki 		"                 struct_ops | fentry | fexit | freplace | sk_lookup }\n"
2271b544342eSQuentin Monnet 		"       ATTACH_TYPE := { msg_verdict | skb_verdict | stream_verdict |\n"
2272b544342eSQuentin Monnet 		"                        stream_parser | flow_dissector }\n"
2273450d060eSYonghong Song 		"       METRIC := { cycles | instructions | l1d_loads | llc_misses | itlb_misses | dtlb_misses }\n"
2274c07ba629SQuentin Monnet 		"       " HELP_SPEC_OPTIONS " |\n"
22758cc8c635SQuentin Monnet 		"                    {-f|--bpffs} | {-m|--mapcompat} | {-n|--nomount} |\n"
22768cc8c635SQuentin Monnet 		"                    {-L|--use-loader} }\n"
227771bb428fSJakub Kicinski 		"",
227890040351SQuentin Monnet 		bin_name, argv[-2]);
227971bb428fSJakub Kicinski 
228071bb428fSJakub Kicinski 	return 0;
228171bb428fSJakub Kicinski }
228271bb428fSJakub Kicinski 
228371bb428fSJakub Kicinski static const struct cmd cmds[] = {
228471bb428fSJakub Kicinski 	{ "show",	do_show },
22856ebe6dbdSJakub Kicinski 	{ "list",	do_show },
22869f606179SQuentin Monnet 	{ "help",	do_help },
228771bb428fSJakub Kicinski 	{ "dump",	do_dump },
228871bb428fSJakub Kicinski 	{ "pin",	do_pin },
228949a086c2SRoman Gushchin 	{ "load",	do_load },
229077380998SStanislav Fomichev 	{ "loadall",	do_loadall },
2291b7d3826cSJohn Fastabend 	{ "attach",	do_attach },
2292b7d3826cSJohn Fastabend 	{ "detach",	do_detach },
229330da46b5SQuentin Monnet 	{ "tracelog",	do_tracelog },
2294ba95c745SQuentin Monnet 	{ "run",	do_run },
229547c09d6aSSong Liu 	{ "profile",	do_profile },
229671bb428fSJakub Kicinski 	{ 0 }
229771bb428fSJakub Kicinski };
229871bb428fSJakub Kicinski 
229971bb428fSJakub Kicinski int do_prog(int argc, char **argv)
230071bb428fSJakub Kicinski {
230171bb428fSJakub Kicinski 	return cmd_select(cmds, argc, argv, do_help);
230271bb428fSJakub Kicinski }
2303