xref: /linux/tools/perf/util/bpf-event.c (revision 8dc364fa484df22d301a16148d1b356931d0cbb0)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <errno.h>
3 #include <stddef.h>
4 #include <stdint.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <bpf/bpf.h>
9 #include <bpf/btf.h>
10 #include <bpf/libbpf.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/err.h>
14 #include <linux/perf_event.h>
15 #include <linux/string.h>
16 #include <linux/zalloc.h>
17 #include <internal/lib.h>
18 #include <perf/event.h>
19 #include <symbol/kallsyms.h>
20 #include "bpf-event.h"
21 #include "bpf-utils.h"
22 #include "debug.h"
23 #include "dso.h"
24 #include "symbol.h"
25 #include "machine.h"
26 #include "env.h"
27 #include "session.h"
28 #include "map.h"
29 #include "evlist.h"
30 #include "record.h"
31 #include "util/synthetic-events.h"
32 
33 static int snprintf_hex(char *buf, size_t size, unsigned char *data, size_t len)
34 {
35 	int ret = 0;
36 	size_t i;
37 
38 	for (i = 0; i < len; i++)
39 		ret += snprintf(buf + ret, size - ret, "%02x", data[i]);
40 	return ret;
41 }
42 
43 static int machine__process_bpf_event_load(struct machine *machine,
44 					   union perf_event *event,
45 					   struct perf_sample *sample __maybe_unused)
46 {
47 	struct bpf_prog_info_node *info_node;
48 	struct perf_env *env = machine->env;
49 	struct perf_bpil *info_linear;
50 	int id = event->bpf.id;
51 	unsigned int i;
52 
53 	/* perf-record, no need to handle bpf-event */
54 	if (env == NULL)
55 		return 0;
56 
57 	info_node = perf_env__find_bpf_prog_info(env, id);
58 	if (!info_node)
59 		return 0;
60 	info_linear = info_node->info_linear;
61 
62 	for (i = 0; i < info_linear->info.nr_jited_ksyms; i++) {
63 		u64 *addrs = (u64 *)(uintptr_t)(info_linear->info.jited_ksyms);
64 		u64 addr = addrs[i];
65 		struct map *map = maps__find(machine__kernel_maps(machine), addr);
66 
67 		if (map) {
68 			struct dso *dso = map__dso(map);
69 
70 			dso__set_binary_type(dso, DSO_BINARY_TYPE__BPF_PROG_INFO);
71 			dso__bpf_prog(dso)->id = id;
72 			dso__bpf_prog(dso)->sub_id = i;
73 			dso__bpf_prog(dso)->env = env;
74 			map__put(map);
75 		}
76 	}
77 	return 0;
78 }
79 
80 int machine__process_bpf(struct machine *machine, union perf_event *event,
81 			 struct perf_sample *sample)
82 {
83 	if (dump_trace)
84 		perf_event__fprintf_bpf(event, stdout);
85 
86 	switch (event->bpf.type) {
87 	case PERF_BPF_EVENT_PROG_LOAD:
88 		return machine__process_bpf_event_load(machine, event, sample);
89 
90 	case PERF_BPF_EVENT_PROG_UNLOAD:
91 		/*
92 		 * Do not free bpf_prog_info and btf of the program here,
93 		 * as annotation still need them. They will be freed at
94 		 * the end of the session.
95 		 */
96 		break;
97 	default:
98 		pr_debug("unexpected bpf event type of %d\n", event->bpf.type);
99 		break;
100 	}
101 	return 0;
102 }
103 
104 static int perf_env__fetch_btf(struct perf_env *env,
105 			       u32 btf_id,
106 			       struct btf *btf)
107 {
108 	struct btf_node *node;
109 	u32 data_size;
110 	const void *data;
111 
112 	data = btf__raw_data(btf, &data_size);
113 
114 	node = malloc(data_size + sizeof(struct btf_node));
115 	if (!node)
116 		return -1;
117 
118 	node->id = btf_id;
119 	node->data_size = data_size;
120 	memcpy(node->data, data, data_size);
121 
122 	if (!perf_env__insert_btf(env, node)) {
123 		/* Insertion failed because of a duplicate. */
124 		free(node);
125 		return -1;
126 	}
127 	return 0;
128 }
129 
130 static int synthesize_bpf_prog_name(char *buf, int size,
131 				    struct bpf_prog_info *info,
132 				    struct btf *btf,
133 				    u32 sub_id)
134 {
135 	u8 (*prog_tags)[BPF_TAG_SIZE] = (void *)(uintptr_t)(info->prog_tags);
136 	void *func_infos = (void *)(uintptr_t)(info->func_info);
137 	u32 sub_prog_cnt = info->nr_jited_ksyms;
138 	const struct bpf_func_info *finfo;
139 	const char *short_name = NULL;
140 	const struct btf_type *t;
141 	int name_len;
142 
143 	name_len = snprintf(buf, size, "bpf_prog_");
144 	name_len += snprintf_hex(buf + name_len, size - name_len,
145 				 prog_tags[sub_id], BPF_TAG_SIZE);
146 	if (btf) {
147 		finfo = func_infos + sub_id * info->func_info_rec_size;
148 		t = btf__type_by_id(btf, finfo->type_id);
149 		short_name = btf__name_by_offset(btf, t->name_off);
150 	} else if (sub_id == 0 && sub_prog_cnt == 1) {
151 		/* no subprog */
152 		if (info->name[0])
153 			short_name = info->name;
154 	} else
155 		short_name = "F";
156 	if (short_name)
157 		name_len += snprintf(buf + name_len, size - name_len,
158 				     "_%s", short_name);
159 	return name_len;
160 }
161 
162 #ifdef HAVE_LIBBPF_STRINGS_SUPPORT
163 
164 #define BPF_METADATA_PREFIX "bpf_metadata_"
165 #define BPF_METADATA_PREFIX_LEN (sizeof(BPF_METADATA_PREFIX) - 1)
166 
167 static bool name_has_bpf_metadata_prefix(const char **s)
168 {
169 	if (strncmp(*s, BPF_METADATA_PREFIX, BPF_METADATA_PREFIX_LEN) != 0)
170 		return false;
171 	*s += BPF_METADATA_PREFIX_LEN;
172 	return true;
173 }
174 
175 struct bpf_metadata_map {
176 	struct btf *btf;
177 	const struct btf_type *datasec;
178 	void *rodata;
179 	size_t rodata_size;
180 	unsigned int num_vars;
181 };
182 
183 static int bpf_metadata_read_map_data(__u32 map_id, struct bpf_metadata_map *map)
184 {
185 	int map_fd;
186 	struct bpf_map_info map_info;
187 	__u32 map_info_len;
188 	int key;
189 	struct btf *btf;
190 	const struct btf_type *datasec;
191 	struct btf_var_secinfo *vsi;
192 	unsigned int vlen, vars;
193 	void *rodata;
194 
195 	map_fd = bpf_map_get_fd_by_id(map_id);
196 	if (map_fd < 0)
197 		return -1;
198 
199 	memset(&map_info, 0, sizeof(map_info));
200 	map_info_len = sizeof(map_info);
201 	if (bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len) < 0)
202 		goto out_close;
203 
204 	/* If it's not an .rodata map, don't bother. */
205 	if (map_info.type != BPF_MAP_TYPE_ARRAY ||
206 	    map_info.key_size != sizeof(int) ||
207 	    map_info.max_entries != 1 ||
208 	    !map_info.btf_value_type_id ||
209 	    !strstr(map_info.name, ".rodata")) {
210 		goto out_close;
211 	}
212 
213 	btf = btf__load_from_kernel_by_id(map_info.btf_id);
214 	if (!btf)
215 		goto out_close;
216 	datasec = btf__type_by_id(btf, map_info.btf_value_type_id);
217 	if (!btf_is_datasec(datasec))
218 		goto out_free_btf;
219 
220 	/*
221 	 * If there aren't any variables with the "bpf_metadata_" prefix,
222 	 * don't bother.
223 	 */
224 	vlen = btf_vlen(datasec);
225 	vsi = btf_var_secinfos(datasec);
226 	vars = 0;
227 	for (unsigned int i = 0; i < vlen; i++, vsi++) {
228 		const struct btf_type *t_var = btf__type_by_id(btf, vsi->type);
229 		const char *name = btf__name_by_offset(btf, t_var->name_off);
230 
231 		if (name_has_bpf_metadata_prefix(&name))
232 			vars++;
233 	}
234 	if (vars == 0)
235 		goto out_free_btf;
236 
237 	rodata = zalloc(map_info.value_size);
238 	if (!rodata)
239 		goto out_free_btf;
240 	key = 0;
241 	if (bpf_map_lookup_elem(map_fd, &key, rodata)) {
242 		free(rodata);
243 		goto out_free_btf;
244 	}
245 	close(map_fd);
246 
247 	map->btf = btf;
248 	map->datasec = datasec;
249 	map->rodata = rodata;
250 	map->rodata_size = map_info.value_size;
251 	map->num_vars = vars;
252 	return 0;
253 
254 out_free_btf:
255 	btf__free(btf);
256 out_close:
257 	close(map_fd);
258 	return -1;
259 }
260 
261 struct format_btf_ctx {
262 	char *buf;
263 	size_t buf_size;
264 	size_t buf_idx;
265 };
266 
267 static void format_btf_cb(void *arg, const char *fmt, va_list ap)
268 {
269 	int n;
270 	struct format_btf_ctx *ctx = (struct format_btf_ctx *)arg;
271 
272 	n = vsnprintf(ctx->buf + ctx->buf_idx, ctx->buf_size - ctx->buf_idx,
273 		      fmt, ap);
274 	ctx->buf_idx += n;
275 	if (ctx->buf_idx >= ctx->buf_size)
276 		ctx->buf_idx = ctx->buf_size;
277 }
278 
279 static void format_btf_variable(struct btf *btf, char *buf, size_t buf_size,
280 				const struct btf_type *t, const void *btf_data)
281 {
282 	struct format_btf_ctx ctx = {
283 		.buf = buf,
284 		.buf_idx = 0,
285 		.buf_size = buf_size,
286 	};
287 	const struct btf_dump_type_data_opts opts = {
288 		.sz = sizeof(struct btf_dump_type_data_opts),
289 		.skip_names = 1,
290 		.compact = 1,
291 #if LIBBPF_CURRENT_VERSION_GEQ(1, 7)
292 		.emit_strings = 1,
293 #endif
294 	};
295 	struct btf_dump *d;
296 	size_t btf_size;
297 
298 	d = btf_dump__new(btf, format_btf_cb, &ctx, NULL);
299 	btf_size = btf__resolve_size(btf, t->type);
300 	btf_dump__dump_type_data(d, t->type, btf_data, btf_size, &opts);
301 	btf_dump__free(d);
302 }
303 
304 static void bpf_metadata_fill_event(struct bpf_metadata_map *map,
305 				    struct perf_record_bpf_metadata *bpf_metadata_event)
306 {
307 	struct btf_var_secinfo *vsi;
308 	unsigned int i, vlen;
309 
310 	memset(bpf_metadata_event->prog_name, 0, BPF_PROG_NAME_LEN);
311 	vlen = btf_vlen(map->datasec);
312 	vsi = btf_var_secinfos(map->datasec);
313 
314 	for (i = 0; i < vlen; i++, vsi++) {
315 		const struct btf_type *t_var = btf__type_by_id(map->btf,
316 							       vsi->type);
317 		const char *name = btf__name_by_offset(map->btf,
318 						       t_var->name_off);
319 		const __u64 nr_entries = bpf_metadata_event->nr_entries;
320 		struct perf_record_bpf_metadata_entry *entry;
321 
322 		if (!name_has_bpf_metadata_prefix(&name))
323 			continue;
324 
325 		if (nr_entries >= (__u64)map->num_vars)
326 			break;
327 
328 		entry = &bpf_metadata_event->entries[nr_entries];
329 		memset(entry, 0, sizeof(*entry));
330 		snprintf(entry->key, BPF_METADATA_KEY_LEN, "%s", name);
331 		format_btf_variable(map->btf, entry->value,
332 				    BPF_METADATA_VALUE_LEN, t_var,
333 				    map->rodata + vsi->offset);
334 		bpf_metadata_event->nr_entries++;
335 	}
336 }
337 
338 static void bpf_metadata_free_map_data(struct bpf_metadata_map *map)
339 {
340 	btf__free(map->btf);
341 	free(map->rodata);
342 }
343 
344 static struct bpf_metadata *bpf_metadata_alloc(__u32 nr_prog_tags,
345 					       __u32 nr_variables)
346 {
347 	struct bpf_metadata *metadata;
348 	size_t event_size;
349 
350 	metadata = zalloc(sizeof(struct bpf_metadata));
351 	if (!metadata)
352 		return NULL;
353 
354 	metadata->prog_names = zalloc(nr_prog_tags * sizeof(char *));
355 	if (!metadata->prog_names) {
356 		bpf_metadata_free(metadata);
357 		return NULL;
358 	}
359 	for (__u32 prog_index = 0; prog_index < nr_prog_tags; prog_index++) {
360 		metadata->prog_names[prog_index] = zalloc(BPF_PROG_NAME_LEN);
361 		if (!metadata->prog_names[prog_index]) {
362 			bpf_metadata_free(metadata);
363 			return NULL;
364 		}
365 		metadata->nr_prog_names++;
366 	}
367 
368 	event_size = sizeof(metadata->event->bpf_metadata) +
369 	    nr_variables * sizeof(metadata->event->bpf_metadata.entries[0]);
370 	metadata->event = zalloc(event_size);
371 	if (!metadata->event) {
372 		bpf_metadata_free(metadata);
373 		return NULL;
374 	}
375 	metadata->event->bpf_metadata = (struct perf_record_bpf_metadata) {
376 		.header = {
377 			.type = PERF_RECORD_BPF_METADATA,
378 			.size = event_size,
379 		},
380 		.nr_entries = 0,
381 	};
382 
383 	return metadata;
384 }
385 
386 static struct bpf_metadata *bpf_metadata_create(struct bpf_prog_info *info)
387 {
388 	struct bpf_metadata *metadata;
389 	const __u32 *map_ids = (__u32 *)(uintptr_t)info->map_ids;
390 
391 	for (__u32 map_index = 0; map_index < info->nr_map_ids; map_index++) {
392 		struct bpf_metadata_map map;
393 
394 		if (bpf_metadata_read_map_data(map_ids[map_index], &map) != 0)
395 			continue;
396 
397 		metadata = bpf_metadata_alloc(info->nr_prog_tags, map.num_vars);
398 		if (!metadata)
399 			continue;
400 
401 		bpf_metadata_fill_event(&map, &metadata->event->bpf_metadata);
402 
403 		for (__u32 index = 0; index < info->nr_prog_tags; index++) {
404 			synthesize_bpf_prog_name(metadata->prog_names[index],
405 						 BPF_PROG_NAME_LEN, info,
406 						 map.btf, index);
407 		}
408 
409 		bpf_metadata_free_map_data(&map);
410 
411 		return metadata;
412 	}
413 
414 	return NULL;
415 }
416 
417 static int synthesize_perf_record_bpf_metadata(const struct bpf_metadata *metadata,
418 					       const struct perf_tool *tool,
419 					       perf_event__handler_t process,
420 					       struct machine *machine)
421 {
422 	const size_t event_size = metadata->event->header.size;
423 	union perf_event *event;
424 	int err = 0;
425 
426 	event = zalloc(event_size + machine->id_hdr_size);
427 	if (!event)
428 		return -1;
429 	memcpy(event, metadata->event, event_size);
430 	memset((void *)event + event->header.size, 0, machine->id_hdr_size);
431 	event->header.size += machine->id_hdr_size;
432 	for (__u32 index = 0; index < metadata->nr_prog_names; index++) {
433 		memcpy(event->bpf_metadata.prog_name,
434 		       metadata->prog_names[index], BPF_PROG_NAME_LEN);
435 		err = perf_tool__process_synth_event(tool, event, machine,
436 						     process);
437 		if (err != 0)
438 			break;
439 	}
440 
441 	free(event);
442 	return err;
443 }
444 
445 void bpf_metadata_free(struct bpf_metadata *metadata)
446 {
447 	if (metadata == NULL)
448 		return;
449 	for (__u32 index = 0; index < metadata->nr_prog_names; index++)
450 		free(metadata->prog_names[index]);
451 	free(metadata->prog_names);
452 	free(metadata->event);
453 	free(metadata);
454 }
455 
456 #else /* HAVE_LIBBPF_STRINGS_SUPPORT */
457 
458 static struct bpf_metadata *bpf_metadata_create(struct bpf_prog_info *info __maybe_unused)
459 {
460 	return NULL;
461 }
462 
463 static int synthesize_perf_record_bpf_metadata(const struct bpf_metadata *metadata __maybe_unused,
464 					       const struct perf_tool *tool __maybe_unused,
465 					       perf_event__handler_t process __maybe_unused,
466 					       struct machine *machine __maybe_unused)
467 {
468 	return 0;
469 }
470 
471 void bpf_metadata_free(struct bpf_metadata *metadata __maybe_unused)
472 {
473 }
474 
475 #endif /* HAVE_LIBBPF_STRINGS_SUPPORT */
476 
477 struct bpf_metadata_final_ctx {
478 	const struct perf_tool *tool;
479 	perf_event__handler_t process;
480 	struct machine *machine;
481 };
482 
483 static void synthesize_final_bpf_metadata_cb(struct bpf_prog_info_node *node,
484 					     void *data)
485 {
486 	struct bpf_metadata_final_ctx *ctx = (struct bpf_metadata_final_ctx *)data;
487 	struct bpf_metadata *metadata = node->metadata;
488 	int err;
489 
490 	if (metadata == NULL)
491 		return;
492 	err = synthesize_perf_record_bpf_metadata(metadata, ctx->tool,
493 						  ctx->process, ctx->machine);
494 	if (err != 0) {
495 		const char *prog_name = metadata->prog_names[0];
496 
497 		if (prog_name != NULL)
498 			pr_warning("Couldn't synthesize final BPF metadata for %s.\n", prog_name);
499 		else
500 			pr_warning("Couldn't synthesize final BPF metadata.\n");
501 	}
502 	bpf_metadata_free(metadata);
503 	node->metadata = NULL;
504 }
505 
506 void perf_event__synthesize_final_bpf_metadata(struct perf_session *session,
507 					       perf_event__handler_t process)
508 {
509 	struct perf_env *env = &session->header.env;
510 	struct bpf_metadata_final_ctx ctx = {
511 		.tool = session->tool,
512 		.process = process,
513 		.machine = &session->machines.host,
514 	};
515 
516 	perf_env__iterate_bpf_prog_info(env, synthesize_final_bpf_metadata_cb,
517 					&ctx);
518 }
519 
520 /*
521  * Synthesize PERF_RECORD_KSYMBOL and PERF_RECORD_BPF_EVENT for one bpf
522  * program. One PERF_RECORD_BPF_EVENT is generated for the program. And
523  * one PERF_RECORD_KSYMBOL is generated for each sub program.
524  *
525  * Returns:
526  *    0 for success;
527  *   -1 for failures;
528  *   -2 for lack of kernel support.
529  */
530 static int perf_event__synthesize_one_bpf_prog(struct perf_session *session,
531 					       perf_event__handler_t process,
532 					       struct machine *machine,
533 					       int fd,
534 					       union perf_event *event,
535 					       struct record_opts *opts)
536 {
537 	struct perf_record_ksymbol *ksymbol_event = &event->ksymbol;
538 	struct perf_record_bpf_event *bpf_event = &event->bpf;
539 	const struct perf_tool *tool = session->tool;
540 	struct bpf_prog_info_node *info_node;
541 	struct perf_bpil *info_linear;
542 	struct bpf_metadata *metadata;
543 	struct bpf_prog_info *info;
544 	struct btf *btf = NULL;
545 	struct perf_env *env;
546 	u32 sub_prog_cnt, i;
547 	int err = 0;
548 	u64 arrays;
549 
550 	/*
551 	 * for perf-record and perf-report use header.env;
552 	 * otherwise, use global perf_env.
553 	 */
554 	env = perf_session__env(session);
555 
556 	arrays = 1UL << PERF_BPIL_JITED_KSYMS;
557 	arrays |= 1UL << PERF_BPIL_JITED_FUNC_LENS;
558 	arrays |= 1UL << PERF_BPIL_FUNC_INFO;
559 	arrays |= 1UL << PERF_BPIL_PROG_TAGS;
560 	arrays |= 1UL << PERF_BPIL_JITED_INSNS;
561 	arrays |= 1UL << PERF_BPIL_LINE_INFO;
562 	arrays |= 1UL << PERF_BPIL_JITED_LINE_INFO;
563 	arrays |= 1UL << PERF_BPIL_MAP_IDS;
564 
565 	info_linear = get_bpf_prog_info_linear(fd, arrays);
566 	if (IS_ERR_OR_NULL(info_linear)) {
567 		info_linear = NULL;
568 		pr_debug("%s: failed to get BPF program info. aborting\n", __func__);
569 		return -1;
570 	}
571 
572 	if (info_linear->info_len < offsetof(struct bpf_prog_info, prog_tags)) {
573 		free(info_linear);
574 		pr_debug("%s: the kernel is too old, aborting\n", __func__);
575 		return -2;
576 	}
577 
578 	info = &info_linear->info;
579 	if (!info->jited_ksyms) {
580 		free(info_linear);
581 		return -1;
582 	}
583 
584 	/* number of ksyms, func_lengths, and tags should match */
585 	sub_prog_cnt = info->nr_jited_ksyms;
586 	if (sub_prog_cnt != info->nr_prog_tags ||
587 	    sub_prog_cnt != info->nr_jited_func_lens) {
588 		free(info_linear);
589 		return -1;
590 	}
591 
592 	/* check BTF func info support */
593 	if (info->btf_id && info->nr_func_info && info->func_info_rec_size) {
594 		/* btf func info number should be same as sub_prog_cnt */
595 		if (sub_prog_cnt != info->nr_func_info) {
596 			pr_debug("%s: mismatch in BPF sub program count and BTF function info count, aborting\n", __func__);
597 			free(info_linear);
598 			return -1;
599 		}
600 		btf = btf__load_from_kernel_by_id(info->btf_id);
601 		if (libbpf_get_error(btf)) {
602 			pr_debug("%s: failed to get BTF of id %u, aborting\n", __func__, info->btf_id);
603 			err = -1;
604 			goto out;
605 		}
606 		perf_env__fetch_btf(env, info->btf_id, btf);
607 	}
608 
609 	/* Synthesize PERF_RECORD_KSYMBOL */
610 	for (i = 0; i < sub_prog_cnt; i++) {
611 		__u32 *prog_lens = (__u32 *)(uintptr_t)(info->jited_func_lens);
612 		__u64 *prog_addrs = (__u64 *)(uintptr_t)(info->jited_ksyms);
613 		int name_len;
614 
615 		*ksymbol_event = (struct perf_record_ksymbol) {
616 			.header = {
617 				.type = PERF_RECORD_KSYMBOL,
618 				.size = offsetof(struct perf_record_ksymbol, name),
619 			},
620 			.addr = prog_addrs[i],
621 			.len = prog_lens[i],
622 			.ksym_type = PERF_RECORD_KSYMBOL_TYPE_BPF,
623 			.flags = 0,
624 		};
625 
626 		name_len = synthesize_bpf_prog_name(ksymbol_event->name,
627 						    KSYM_NAME_LEN, info, btf, i);
628 		ksymbol_event->header.size += PERF_ALIGN(name_len + 1,
629 							 sizeof(u64));
630 
631 		memset((void *)event + event->header.size, 0, machine->id_hdr_size);
632 		event->header.size += machine->id_hdr_size;
633 		err = perf_tool__process_synth_event(tool, event,
634 						     machine, process);
635 	}
636 
637 	if (!opts->no_bpf_event) {
638 		/* Synthesize PERF_RECORD_BPF_EVENT */
639 		*bpf_event = (struct perf_record_bpf_event) {
640 			.header = {
641 				.type = PERF_RECORD_BPF_EVENT,
642 				.size = sizeof(struct perf_record_bpf_event),
643 			},
644 			.type = PERF_BPF_EVENT_PROG_LOAD,
645 			.flags = 0,
646 			.id = info->id,
647 		};
648 		memcpy(bpf_event->tag, info->tag, BPF_TAG_SIZE);
649 		memset((void *)event + event->header.size, 0, machine->id_hdr_size);
650 		event->header.size += machine->id_hdr_size;
651 
652 		/* save bpf_prog_info to env */
653 		info_node = malloc(sizeof(struct bpf_prog_info_node));
654 		if (!info_node) {
655 			err = -1;
656 			goto out;
657 		}
658 
659 		info_node->info_linear = info_linear;
660 		info_node->metadata = NULL;
661 		if (!perf_env__insert_bpf_prog_info(env, info_node)) {
662 			/*
663 			 * Insert failed, likely because of a duplicate event
664 			 * made by the sideband thread. Ignore synthesizing the
665 			 * metadata.
666 			 */
667 			free(info_node);
668 			goto out;
669 		}
670 		/* info_linear is now owned by info_node and shouldn't be freed below. */
671 		info_linear = NULL;
672 
673 		/*
674 		 * process after saving bpf_prog_info to env, so that
675 		 * required information is ready for look up
676 		 */
677 		err = perf_tool__process_synth_event(tool, event,
678 						     machine, process);
679 
680 		/* Synthesize PERF_RECORD_BPF_METADATA */
681 		metadata = bpf_metadata_create(info);
682 		if (metadata != NULL) {
683 			err = synthesize_perf_record_bpf_metadata(metadata,
684 								  tool, process,
685 								  machine);
686 			bpf_metadata_free(metadata);
687 		}
688 	}
689 
690 out:
691 	free(info_linear);
692 	btf__free(btf);
693 	return err ? -1 : 0;
694 }
695 
696 struct kallsyms_parse {
697 	union perf_event	*event;
698 	perf_event__handler_t	 process;
699 	struct machine		*machine;
700 	const struct perf_tool	*tool;
701 };
702 
703 static int
704 process_bpf_image(char *name, u64 addr, struct kallsyms_parse *data)
705 {
706 	struct machine *machine = data->machine;
707 	union perf_event *event = data->event;
708 	struct perf_record_ksymbol *ksymbol;
709 	int len;
710 
711 	ksymbol = &event->ksymbol;
712 
713 	*ksymbol = (struct perf_record_ksymbol) {
714 		.header = {
715 			.type = PERF_RECORD_KSYMBOL,
716 			.size = offsetof(struct perf_record_ksymbol, name),
717 		},
718 		.addr      = addr,
719 		.len       = page_size,
720 		.ksym_type = PERF_RECORD_KSYMBOL_TYPE_BPF,
721 		.flags     = 0,
722 	};
723 
724 	len = scnprintf(ksymbol->name, KSYM_NAME_LEN, "%s", name);
725 	ksymbol->header.size += PERF_ALIGN(len + 1, sizeof(u64));
726 	memset((void *) event + event->header.size, 0, machine->id_hdr_size);
727 	event->header.size += machine->id_hdr_size;
728 
729 	return perf_tool__process_synth_event(data->tool, event, machine,
730 					      data->process);
731 }
732 
733 static int
734 kallsyms_process_symbol(void *data, const char *_name,
735 			char type __maybe_unused, u64 start)
736 {
737 	char disp[KSYM_NAME_LEN];
738 	char *module, *name;
739 	unsigned long id;
740 	int err = 0;
741 
742 	module = strchr(_name, '\t');
743 	if (!module)
744 		return 0;
745 
746 	/* We are going after [bpf] module ... */
747 	if (strcmp(module + 1, "[bpf]"))
748 		return 0;
749 
750 	name = memdup(_name, (module - _name) + 1);
751 	if (!name)
752 		return -ENOMEM;
753 
754 	name[module - _name] = 0;
755 
756 	/* .. and only for trampolines and dispatchers */
757 	if ((sscanf(name, "bpf_trampoline_%lu", &id) == 1) ||
758 	    (sscanf(name, "bpf_dispatcher_%s", disp) == 1))
759 		err = process_bpf_image(name, start, data);
760 
761 	free(name);
762 	return err;
763 }
764 
765 int perf_event__synthesize_bpf_events(struct perf_session *session,
766 				      perf_event__handler_t process,
767 				      struct machine *machine,
768 				      struct record_opts *opts)
769 {
770 	const char *kallsyms_filename = "/proc/kallsyms";
771 	struct kallsyms_parse arg;
772 	union perf_event *event;
773 	__u32 id = 0;
774 	int err;
775 	int fd;
776 
777 	if (opts->no_bpf_event)
778 		return 0;
779 
780 	event = malloc(sizeof(event->bpf) + KSYM_NAME_LEN + machine->id_hdr_size);
781 	if (!event)
782 		return -1;
783 
784 	/* Synthesize all the bpf programs in system. */
785 	while (true) {
786 		err = bpf_prog_get_next_id(id, &id);
787 		if (err) {
788 			if (errno == ENOENT) {
789 				err = 0;
790 				break;
791 			}
792 			pr_debug("%s: can't get next program: %s%s\n",
793 				 __func__, strerror(errno),
794 				 errno == EINVAL ? " -- kernel too old?" : "");
795 			/* don't report error on old kernel or EPERM  */
796 			err = (errno == EINVAL || errno == EPERM) ? 0 : -1;
797 			break;
798 		}
799 		fd = bpf_prog_get_fd_by_id(id);
800 		if (fd < 0) {
801 			pr_debug("%s: failed to get fd for prog_id %u\n",
802 				 __func__, id);
803 			continue;
804 		}
805 
806 		err = perf_event__synthesize_one_bpf_prog(session, process,
807 							  machine, fd,
808 							  event, opts);
809 		close(fd);
810 		if (err) {
811 			/* do not return error for old kernel */
812 			if (err == -2)
813 				err = 0;
814 			break;
815 		}
816 	}
817 
818 	/* Synthesize all the bpf images - trampolines/dispatchers. */
819 	if (symbol_conf.kallsyms_name != NULL)
820 		kallsyms_filename = symbol_conf.kallsyms_name;
821 
822 	arg = (struct kallsyms_parse) {
823 		.event   = event,
824 		.process = process,
825 		.machine = machine,
826 		.tool    = session->tool,
827 	};
828 
829 	if (kallsyms__parse(kallsyms_filename, &arg, kallsyms_process_symbol)) {
830 		pr_err("%s: failed to synthesize bpf images: %s\n",
831 		       __func__, strerror(errno));
832 	}
833 
834 	free(event);
835 	return err;
836 }
837 
838 static int perf_env__add_bpf_info(struct perf_env *env, u32 id)
839 {
840 	struct bpf_prog_info_node *info_node;
841 	struct perf_bpil *info_linear;
842 	struct btf *btf = NULL;
843 	u64 arrays;
844 	u32 btf_id;
845 	int fd, err = 0;
846 
847 	fd = bpf_prog_get_fd_by_id(id);
848 	if (fd < 0)
849 		return -EINVAL;
850 
851 	arrays = 1UL << PERF_BPIL_JITED_KSYMS;
852 	arrays |= 1UL << PERF_BPIL_JITED_FUNC_LENS;
853 	arrays |= 1UL << PERF_BPIL_FUNC_INFO;
854 	arrays |= 1UL << PERF_BPIL_PROG_TAGS;
855 	arrays |= 1UL << PERF_BPIL_JITED_INSNS;
856 	arrays |= 1UL << PERF_BPIL_LINE_INFO;
857 	arrays |= 1UL << PERF_BPIL_JITED_LINE_INFO;
858 	arrays |= 1UL << PERF_BPIL_MAP_IDS;
859 
860 	info_linear = get_bpf_prog_info_linear(fd, arrays);
861 	if (IS_ERR_OR_NULL(info_linear)) {
862 		pr_debug("%s: failed to get BPF program info. aborting\n", __func__);
863 		err = PTR_ERR(info_linear);
864 		goto out;
865 	}
866 
867 	btf_id = info_linear->info.btf_id;
868 
869 	info_node = malloc(sizeof(struct bpf_prog_info_node));
870 	if (info_node) {
871 		info_node->info_linear = info_linear;
872 		info_node->metadata = bpf_metadata_create(&info_linear->info);
873 		if (!perf_env__insert_bpf_prog_info(env, info_node)) {
874 			pr_debug("%s: duplicate add bpf info request for id %u\n",
875 				 __func__, btf_id);
876 			free(info_linear);
877 			free(info_node);
878 			goto out;
879 		}
880 	} else {
881 		free(info_linear);
882 		err = -ENOMEM;
883 		goto out;
884 	}
885 
886 	if (btf_id == 0)
887 		goto out;
888 
889 	btf = btf__load_from_kernel_by_id(btf_id);
890 	if (!btf) {
891 		err = -errno;
892 		pr_debug("%s: failed to get BTF of id %u %d\n", __func__, btf_id, err);
893 	} else {
894 		perf_env__fetch_btf(env, btf_id, btf);
895 	}
896 
897 out:
898 	btf__free(btf);
899 	close(fd);
900 	return err;
901 }
902 
903 static int bpf_event__sb_cb(union perf_event *event, void *data)
904 {
905 	struct perf_env *env = data;
906 	int ret = 0;
907 
908 	if (event->header.type != PERF_RECORD_BPF_EVENT)
909 		return -1;
910 
911 	switch (event->bpf.type) {
912 	case PERF_BPF_EVENT_PROG_LOAD:
913 		ret = perf_env__add_bpf_info(env, event->bpf.id);
914 
915 	case PERF_BPF_EVENT_PROG_UNLOAD:
916 		/*
917 		 * Do not free bpf_prog_info and btf of the program here,
918 		 * as annotation still need them. They will be freed at
919 		 * the end of the session.
920 		 */
921 		break;
922 	default:
923 		pr_debug("unexpected bpf event type of %d\n", event->bpf.type);
924 		break;
925 	}
926 
927 	return ret;
928 }
929 
930 int evlist__add_bpf_sb_event(struct evlist *evlist, struct perf_env *env)
931 {
932 	struct perf_event_attr attr = {
933 		.type	          = PERF_TYPE_SOFTWARE,
934 		.config           = PERF_COUNT_SW_DUMMY,
935 		.sample_id_all    = 1,
936 		.watermark        = 1,
937 		.bpf_event        = 1,
938 		.size	   = sizeof(attr), /* to capture ABI version */
939 	};
940 
941 	/*
942 	 * Older gcc versions don't support designated initializers, like above,
943 	 * for unnamed union members, such as the following:
944 	 */
945 	attr.wakeup_watermark = 1;
946 
947 	return evlist__add_sb_event(evlist, &attr, bpf_event__sb_cb, env);
948 }
949 
950 void __bpf_event__print_bpf_prog_info(struct bpf_prog_info *info,
951 				      struct perf_env *env,
952 				      FILE *fp)
953 {
954 	__u32 *prog_lens = (__u32 *)(uintptr_t)(info->jited_func_lens);
955 	__u64 *prog_addrs = (__u64 *)(uintptr_t)(info->jited_ksyms);
956 	char name[KSYM_NAME_LEN];
957 	struct btf *btf = NULL;
958 	u32 sub_prog_cnt, i;
959 
960 	sub_prog_cnt = info->nr_jited_ksyms;
961 	if (sub_prog_cnt != info->nr_prog_tags ||
962 	    sub_prog_cnt != info->nr_jited_func_lens)
963 		return;
964 
965 	if (info->btf_id) {
966 		struct btf_node *node;
967 
968 		node = __perf_env__find_btf(env, info->btf_id);
969 		if (node)
970 			btf = btf__new((__u8 *)(node->data),
971 				       node->data_size);
972 	}
973 
974 	if (sub_prog_cnt == 1) {
975 		synthesize_bpf_prog_name(name, KSYM_NAME_LEN, info, btf, 0);
976 		fprintf(fp, "# bpf_prog_info %u: %s addr 0x%llx size %u\n",
977 			info->id, name, prog_addrs[0], prog_lens[0]);
978 		goto out;
979 	}
980 
981 	fprintf(fp, "# bpf_prog_info %u:\n", info->id);
982 	for (i = 0; i < sub_prog_cnt; i++) {
983 		synthesize_bpf_prog_name(name, KSYM_NAME_LEN, info, btf, i);
984 
985 		fprintf(fp, "# \tsub_prog %u: %s addr 0x%llx size %u\n",
986 			i, name, prog_addrs[i], prog_lens[i]);
987 	}
988 out:
989 	btf__free(btf);
990 }
991