xref: /linux/tools/perf/builtin-inject.c (revision 67f8bc848ee31831336bd478e57d2f993551902e)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * builtin-inject.c
4  *
5  * Builtin inject command: Examine the live mode (stdin) event stream
6  * and repipe it to stdout while optionally injecting additional
7  * events into it.
8  */
9 #include "builtin.h"
10 
11 #include "util/aslr.h"
12 #include "util/color.h"
13 #include "util/dso.h"
14 #include "util/vdso.h"
15 #include "util/evlist.h"
16 #include "util/evsel.h"
17 #include "util/map.h"
18 #include "util/session.h"
19 #include "util/tool.h"
20 #include "util/debug.h"
21 #include "util/build-id.h"
22 #include "util/data.h"
23 #include "util/auxtrace.h"
24 #include "util/jit.h"
25 #include "util/string2.h"
26 #include "util/symbol.h"
27 #include "util/synthetic-events.h"
28 #include "util/pmus.h"
29 #include "util/thread.h"
30 #include "util/namespaces.h"
31 #include "util/unwind.h"
32 #include "util/util.h"
33 #include "util/tsc.h"
34 
35 #include <internal/lib.h>
36 
37 #include <linux/err.h>
38 #include <subcmd/parse-options.h>
39 #include <uapi/linux/mman.h> /* To get things like MAP_HUGETLB even on older libc headers */
40 
41 #include <linux/list.h>
42 #include <linux/string.h>
43 #include <linux/zalloc.h>
44 #include <linux/hash.h>
45 #include <ctype.h>
46 #include <errno.h>
47 #include <signal.h>
48 #include <inttypes.h>
49 
50 struct guest_event {
51 	struct perf_sample		sample;
52 	union perf_event		*event;
53 	char				*event_buf;
54 };
55 
56 struct guest_id {
57 	/* hlist_node must be first, see free_hlist() */
58 	struct hlist_node		node;
59 	u64				id;
60 	u64				host_id;
61 	u32				vcpu;
62 };
63 
64 struct guest_tid {
65 	/* hlist_node must be first, see free_hlist() */
66 	struct hlist_node		node;
67 	/* Thread ID of QEMU thread */
68 	u32				tid;
69 	u32				vcpu;
70 };
71 
72 struct guest_vcpu {
73 	/* Current host CPU */
74 	u32				cpu;
75 	/* Thread ID of QEMU thread */
76 	u32				tid;
77 };
78 
79 struct guest_session {
80 	char				*perf_data_file;
81 	u32				machine_pid;
82 	u64				time_offset;
83 	double				time_scale;
84 	struct perf_tool		tool;
85 	struct perf_data		data;
86 	struct perf_session		*session;
87 	char				*tmp_file_name;
88 	int				tmp_fd;
89 	struct perf_tsc_conversion	host_tc;
90 	struct perf_tsc_conversion	guest_tc;
91 	bool				copy_kcore_dir;
92 	bool				have_tc;
93 	bool				fetched;
94 	bool				ready;
95 	u16				dflt_id_hdr_size;
96 	u64				dflt_id;
97 	u64				highest_id;
98 	/* Array of guest_vcpu */
99 	struct guest_vcpu		*vcpu;
100 	size_t				vcpu_cnt;
101 	/* Hash table for guest_id */
102 	struct hlist_head		heads[PERF_EVLIST__HLIST_SIZE];
103 	/* Hash table for guest_tid */
104 	struct hlist_head		tids[PERF_EVLIST__HLIST_SIZE];
105 	/* Place to stash next guest event */
106 	struct guest_event		ev;
107 };
108 
109 enum build_id_rewrite_style {
110 	BID_RWS__NONE = 0,
111 	BID_RWS__INJECT_HEADER_LAZY,
112 	BID_RWS__INJECT_HEADER_ALL,
113 	BID_RWS__MMAP2_BUILDID_ALL,
114 	BID_RWS__MMAP2_BUILDID_LAZY,
115 };
116 
117 struct perf_inject {
118 	struct perf_tool	tool;
119 	struct perf_session	*session;
120 	enum build_id_rewrite_style build_id_style;
121 	bool			sched_stat;
122 	bool			have_auxtrace;
123 	bool			strip;
124 	bool			jit_mode;
125 	bool			in_place_update;
126 	bool			in_place_update_dry_run;
127 	bool			copy_kcore_dir;
128 	bool			convert_callchain;
129 	bool			aslr;
130 	const char		*input_name;
131 	struct perf_data	output;
132 	u64			bytes_written;
133 	u64			aux_id;
134 	struct list_head	samples;
135 	struct itrace_synth_opts itrace_synth_opts;
136 	char			*event_copy;
137 	struct perf_file_section secs[HEADER_FEAT_BITS];
138 	struct guest_session	guest_session;
139 	struct strlist		*known_build_ids;
140 	struct evsel		*mmap_evsel;
141 	struct ip_callchain	*raw_callchain;
142 };
143 
144 struct event_entry {
145 	struct list_head node;
146 	u32		 tid;
147 	union perf_event event[];
148 };
149 
150 static int tool__inject_build_id(const struct perf_tool *tool,
151 				 struct perf_sample *sample,
152 				 struct machine *machine,
153 				 __u16 misc,
154 				 const char *filename,
155 				 struct dso *dso, u32 flags);
156 static int tool__inject_mmap2_build_id(const struct perf_tool *tool,
157 				      struct perf_sample *sample,
158 				      struct machine *machine,
159 				      __u16 misc,
160 				      __u32 pid, __u32 tid,
161 				      __u64 start, __u64 len, __u64 pgoff,
162 				      struct dso *dso,
163 				      __u32 prot, __u32 flags,
164 				      const char *filename);
165 
166 static int output_bytes(struct perf_inject *inject, void *buf, size_t sz)
167 {
168 	ssize_t size;
169 
170 	size = perf_data__write(&inject->output, buf, sz);
171 	if (size < 0)
172 		return -errno;
173 
174 	inject->bytes_written += size;
175 	return 0;
176 }
177 
178 static int perf_event__repipe_synth(const struct perf_tool *tool,
179 				    union perf_event *event)
180 
181 {
182 	struct perf_inject *inject = container_of(tool, struct perf_inject,
183 						  tool);
184 
185 	return output_bytes(inject, event, event->header.size);
186 }
187 
188 static int perf_event__repipe_oe_synth(const struct perf_tool *tool,
189 				       union perf_event *event,
190 				       struct ordered_events *oe __maybe_unused)
191 {
192 	return perf_event__repipe_synth(tool, event);
193 }
194 
195 #ifdef HAVE_JITDUMP
196 static int perf_event__drop_oe(const struct perf_tool *tool __maybe_unused,
197 			       union perf_event *event __maybe_unused,
198 			       struct ordered_events *oe __maybe_unused)
199 {
200 	return 0;
201 }
202 #endif
203 
204 static int perf_event__repipe_op2_synth(const struct perf_tool *tool,
205 					struct perf_session *session __maybe_unused,
206 					union perf_event *event)
207 {
208 	return perf_event__repipe_synth(tool, event);
209 }
210 
211 static int perf_event__repipe_op4_synth(const struct perf_tool *tool,
212 					struct perf_session *session __maybe_unused,
213 					union perf_event *event,
214 					u64 data __maybe_unused,
215 					const char *str __maybe_unused)
216 {
217 	return perf_event__repipe_synth(tool, event);
218 }
219 
220 static int perf_event__repipe_synth_cb(const struct perf_tool *tool,
221 				       union perf_event *event,
222 				       struct perf_sample *sample __maybe_unused,
223 				       struct machine *machine __maybe_unused)
224 {
225 	return perf_event__repipe_synth(tool, event);
226 }
227 
228 static int perf_event__repipe_attr(const struct perf_tool *tool,
229 				   union perf_event *event,
230 				   struct evlist **pevlist)
231 {
232 	struct perf_inject *inject = container_of(tool, struct perf_inject,
233 						  tool);
234 	struct perf_event_attr attr;
235 	u32 raw_attr_size, attr_size;
236 	size_t n_ids;
237 	u64 *ids;
238 	int ret;
239 
240 	union perf_event *aslr_event = NULL;
241 
242 	ret = perf_event__process_attr(tool, event, pevlist);
243 	if (ret)
244 		return ret;
245 
246 	if (inject->aslr) {
247 		aslr_event = malloc(event->header.size);
248 		if (!aslr_event)
249 			return -ENOMEM;
250 		memcpy(aslr_event, event, event->header.size);
251 		aslr_tool__strip_attr_event(aslr_event, *pevlist);
252 		event = aslr_event;
253 	}
254 
255 	/* If the output isn't a pipe then the attributes will be written as part of the header. */
256 	if (!inject->output.is_pipe) {
257 		ret = 0;
258 		goto out;
259 	}
260 
261 	if (!inject->itrace_synth_opts.set) {
262 		ret = perf_event__repipe_synth(tool, event);
263 		goto out;
264 	}
265 
266 	if (event->header.size < sizeof(struct perf_event_header) + PERF_ATTR_SIZE_VER0) {
267 		pr_err("Attribute event size %u is too small\n", event->header.size);
268 		ret = -EINVAL;
269 		goto out;
270 	}
271 
272 	/*
273 	 * ABI0 pipe/inject events have attr.size == 0; default to
274 	 * PERF_ATTR_SIZE_VER0 (the ABI0 footprint) for the bounded
275 	 * copy and ID array position.  Same pattern as
276 	 * perf_event__process_attr() in header.c.
277 	 */
278 	raw_attr_size = event->attr.attr.size;
279 	attr_size = raw_attr_size ?: PERF_ATTR_SIZE_VER0;
280 
281 	if (raw_attr_size && (raw_attr_size < PERF_ATTR_SIZE_VER0 ||
282 			      raw_attr_size > event->header.size - sizeof(event->header))) {
283 		pr_err("Attribute event size %u is too small for attr.size %u\n",
284 		       event->header.size, raw_attr_size);
285 		ret = -EINVAL;
286 		goto out;
287 	}
288 
289 	memset(&attr, 0, sizeof(attr));
290 	memcpy(&attr, &event->attr.attr,
291 	       min_t(size_t, sizeof(attr), attr_size));
292 
293 	n_ids = event->header.size - sizeof(event->header) - attr_size;
294 	n_ids /= sizeof(u64);
295 	ids = (void *)&event->attr.attr + attr_size;
296 
297 	attr.size = sizeof(struct perf_event_attr);
298 	attr.sample_type &= ~PERF_SAMPLE_AUX;
299 
300 
301 	if (inject->itrace_synth_opts.add_last_branch) {
302 		attr.sample_type |= PERF_SAMPLE_BRANCH_STACK;
303 		attr.branch_sample_type |= PERF_SAMPLE_BRANCH_HW_INDEX;
304 	}
305 	ret = perf_event__synthesize_attr(tool, &attr, (u32)n_ids, ids,
306 					   perf_event__repipe_synth_cb);
307 out:
308 	free(aslr_event);
309 	return ret;
310 }
311 
312 static int perf_event__repipe_event_update(const struct perf_tool *tool,
313 					   union perf_event *event,
314 					   struct evlist **pevlist __maybe_unused)
315 {
316 	return perf_event__repipe_synth(tool, event);
317 }
318 
319 static int copy_bytes(struct perf_inject *inject, struct perf_data *data, off_t size)
320 {
321 	char buf[4096];
322 	ssize_t ssz;
323 	int ret;
324 
325 	while (size > 0) {
326 		ssz = perf_data__read(data, buf, min(size, (off_t)sizeof(buf)));
327 		if (ssz < 0)
328 			return -errno;
329 		ret = output_bytes(inject, buf, ssz);
330 		if (ret)
331 			return ret;
332 		size -= ssz;
333 	}
334 
335 	return 0;
336 }
337 
338 static s64 perf_event__repipe_auxtrace(const struct perf_tool *tool,
339 				       struct perf_session *session,
340 				       union perf_event *event)
341 {
342 	struct perf_inject *inject = container_of(tool, struct perf_inject, tool);
343 	int ret;
344 
345 	inject->have_auxtrace = true;
346 
347 	if (!inject->output.is_pipe) {
348 		off_t offset = perf_data__seek(&inject->output, 0, SEEK_CUR);
349 
350 		if (offset == -1)
351 			return -errno;
352 		ret = auxtrace_index__auxtrace_event(&session->auxtrace_index,
353 						     event, offset);
354 		if (ret < 0)
355 			return ret;
356 	}
357 
358 	if (perf_data__is_pipe(session->data) || !session->one_mmap) {
359 		ret = output_bytes(inject, event, event->header.size);
360 		if (ret < 0)
361 			return ret;
362 		ret = copy_bytes(inject, session->data,
363 				 event->auxtrace.size);
364 	} else {
365 		ret = output_bytes(inject, event,
366 				   event->header.size + event->auxtrace.size);
367 	}
368 	if (ret < 0)
369 		return ret;
370 
371 	return event->auxtrace.size;
372 }
373 
374 static int perf_event__repipe(const struct perf_tool *tool,
375 			      union perf_event *event,
376 			      struct perf_sample *sample __maybe_unused,
377 			      struct machine *machine __maybe_unused)
378 {
379 	return perf_event__repipe_synth(tool, event);
380 }
381 
382 static int perf_event__drop(const struct perf_tool *tool __maybe_unused,
383 			    union perf_event *event __maybe_unused,
384 			    struct perf_sample *sample __maybe_unused,
385 			    struct machine *machine __maybe_unused)
386 {
387 	return 0;
388 }
389 
390 static int perf_event__drop_aux(const struct perf_tool *tool,
391 				union perf_event *event __maybe_unused,
392 				struct perf_sample *sample,
393 				struct machine *machine __maybe_unused)
394 {
395 	struct perf_inject *inject = container_of(tool, struct perf_inject, tool);
396 
397 	if (!inject->aux_id)
398 		inject->aux_id = sample->id;
399 
400 	return 0;
401 }
402 
403 static union perf_event *
404 perf_inject__cut_auxtrace_sample(struct perf_inject *inject,
405 				 union perf_event *event,
406 				 struct perf_sample *sample)
407 {
408 	size_t sz1 = sample->aux_sample.data - (void *)event - sizeof(u64);
409 	size_t sz2 = event->header.size - sample->aux_sample.size - (sz1 + sizeof(u64));
410 	union perf_event *ev;
411 
412 	if (inject->event_copy == NULL) {
413 		inject->event_copy = malloc(PERF_SAMPLE_MAX_SIZE);
414 		if (!inject->event_copy)
415 			return ERR_PTR(-ENOMEM);
416 	}
417 	ev = (union perf_event *)inject->event_copy;
418 	if (sz1 > event->header.size || sz2 > event->header.size ||
419 	    sz1 + sz2 > event->header.size ||
420 	    sz1 < sizeof(struct perf_event_header))
421 		return event;
422 
423 	memcpy(ev, event, sz1);
424 	memcpy((void *)ev + sz1, (void *)event + event->header.size - sz2, sz2);
425 	ev->header.size = sz1 + sz2;
426 
427 	return ev;
428 }
429 
430 typedef int (*inject_handler)(const struct perf_tool *tool,
431 			      union perf_event *event,
432 			      struct perf_sample *sample,
433 			      struct machine *machine);
434 
435 static int perf_event__repipe_sample(const struct perf_tool *tool,
436 				     union perf_event *event,
437 				     struct perf_sample *sample,
438 				     struct machine *machine)
439 {
440 	struct perf_inject *inject = container_of(tool, struct perf_inject, tool);
441 	struct evsel *evsel = sample->evsel;
442 
443 	if (evsel == NULL)
444 		return perf_event__repipe_synth(tool, event);
445 
446 	if (evsel->handler) {
447 		inject_handler f = evsel->handler;
448 		return f(tool, event, sample, machine);
449 	}
450 
451 	build_id__mark_dso_hit(tool, event, sample, machine);
452 
453 	if (inject->itrace_synth_opts.set &&
454 	    (inject->itrace_synth_opts.last_branch ||
455 	     inject->itrace_synth_opts.add_last_branch)) {
456 		union perf_event *event_copy = (void *)inject->event_copy;
457 		struct branch_stack dummy_bs = { .nr = 0, .hw_idx = 0 };
458 		int err;
459 		size_t sz;
460 		u64 orig_type = evsel->core.attr.sample_type;
461 		u64 orig_branch_type = evsel->core.attr.branch_sample_type;
462 
463 		struct branch_stack *orig_bs = sample->branch_stack;
464 
465 		if (event_copy == NULL) {
466 			inject->event_copy = malloc(PERF_SAMPLE_MAX_SIZE);
467 			if (!inject->event_copy)
468 				return -ENOMEM;
469 
470 			event_copy = (void *)inject->event_copy;
471 		}
472 
473 		if (!sample->branch_stack)
474 			sample->branch_stack = &dummy_bs;
475 
476 		if (inject->itrace_synth_opts.add_last_branch) {
477 			/* Temporarily add in type bits for synthesis. */
478 			evsel->core.attr.sample_type |= PERF_SAMPLE_BRANCH_STACK;
479 			evsel->core.attr.branch_sample_type |= PERF_SAMPLE_BRANCH_HW_INDEX;
480 		}
481 		evsel->core.attr.sample_type &= ~PERF_SAMPLE_AUX;
482 
483 		sz = perf_event__sample_event_size(sample, evsel->core.attr.sample_type,
484 						   evsel->core.attr.read_format,
485 						   evsel->core.attr.branch_sample_type);
486 
487 		if (sz >= PERF_SAMPLE_MAX_SIZE) {
488 			pr_err("Sample size %zu exceeds max size %d\n", sz, PERF_SAMPLE_MAX_SIZE);
489 			evsel->core.attr.sample_type = orig_type;
490 			evsel->core.attr.branch_sample_type = orig_branch_type;
491 			sample->branch_stack = orig_bs;
492 			return -EFAULT;
493 		}
494 
495 		event_copy->header.type = PERF_RECORD_SAMPLE;
496 		event_copy->header.misc = event->header.misc;
497 		event_copy->header.size = sz;
498 
499 		err = perf_event__synthesize_sample(event_copy, evsel->core.attr.sample_type,
500 						    evsel->core.attr.read_format,
501 						    evsel->core.attr.branch_sample_type, sample);
502 
503 		evsel->core.attr.sample_type = orig_type;
504 		evsel->core.attr.branch_sample_type = orig_branch_type;
505 		sample->branch_stack = orig_bs;
506 
507 		if (err) {
508 			pr_err("Failed to synthesize sample\n");
509 			return err;
510 		}
511 		event = event_copy;
512 	} else if (inject->itrace_synth_opts.set &&
513 		   (evsel->core.attr.sample_type & PERF_SAMPLE_AUX)) {
514 		event = perf_inject__cut_auxtrace_sample(inject, event, sample);
515 		if (IS_ERR(event))
516 			return PTR_ERR(event);
517 	}
518 
519 	return perf_event__repipe_synth(tool, event);
520 }
521 
522 static int perf_event__convert_sample_callchain(const struct perf_tool *tool,
523 						union perf_event *event,
524 						struct perf_sample *sample,
525 						struct machine *machine)
526 {
527 	struct perf_inject *inject = container_of(tool, struct perf_inject, tool);
528 	struct evsel *evsel = sample->evsel;
529 	struct callchain_cursor *cursor = get_tls_callchain_cursor();
530 	union perf_event *event_copy = (void *)inject->event_copy;
531 	struct callchain_cursor_node *node;
532 	struct thread *thread;
533 	u64 sample_type = evsel->core.attr.sample_type;
534 	size_t sz;
535 	u64 i, k;
536 	int ret;
537 
538 	if (event_copy == NULL) {
539 		inject->event_copy = malloc(PERF_SAMPLE_MAX_SIZE);
540 		if (!inject->event_copy)
541 			return -ENOMEM;
542 
543 		event_copy = (void *)inject->event_copy;
544 	}
545 
546 	if (cursor == NULL)
547 		return -ENOMEM;
548 
549 	callchain_cursor_reset(cursor);
550 
551 	thread = machine__find_thread(machine, sample->tid, sample->pid);
552 	if (thread == NULL)
553 		goto out;
554 
555 	/* this will parse DWARF using stack and register data */
556 	ret = thread__resolve_callchain(thread, cursor, sample,
557 					/*parent=*/NULL, /*root_al=*/NULL,
558 					PERF_MAX_STACK_DEPTH);
559 	thread__put(thread);
560 	if (ret != 0)
561 		goto out;
562 
563 	/* copy kernel callchain and context entries */
564 	for (i = 0; i < sample->callchain->nr; i++) {
565 		inject->raw_callchain->ips[i] = sample->callchain->ips[i];
566 		if (sample->callchain->ips[i] == PERF_CONTEXT_USER) {
567 			i++;
568 			break;
569 		}
570 	}
571 	if (i == 0 || inject->raw_callchain->ips[i - 1] != PERF_CONTEXT_USER)
572 		inject->raw_callchain->ips[i++] = PERF_CONTEXT_USER;
573 
574 	node = cursor->first;
575 	for (k = 0; k < cursor->nr && i < PERF_MAX_STACK_DEPTH; k++) {
576 		if (!(machine->single_address_space &&
577 		      machine__kernel_ip(machine, node->ip)) &&
578 		    !(node->ms.sym && symbol__inlined(node->ms.sym))) {
579 			inject->raw_callchain->ips[i++] = node->ip;
580 		}
581 
582 		node = node->next;
583 	}
584 
585 	inject->raw_callchain->nr = i;
586 	sample->callchain = inject->raw_callchain;
587 
588 out:
589 	memcpy(event_copy, event, sizeof(event->header));
590 
591 	/* remove sample_type {STACK,REGS}_USER for synthesize */
592 	sample_type &= ~(PERF_SAMPLE_STACK_USER | PERF_SAMPLE_REGS_USER);
593 
594 	sz = perf_event__sample_event_size(sample, sample_type,
595 					   evsel->core.attr.read_format,
596 					   evsel->core.attr.branch_sample_type);
597 	if (sz >= PERF_SAMPLE_MAX_SIZE) {
598 		pr_err("Sample size %zu exceeds max size %d\n", sz, PERF_SAMPLE_MAX_SIZE);
599 		return -EFAULT;
600 	}
601 	event_copy->header.size = sz;
602 
603 	ret = perf_event__synthesize_sample(event_copy, sample_type,
604 					    evsel->core.attr.read_format,
605 					    evsel->core.attr.branch_sample_type, sample);
606 	if (ret) {
607 		pr_err("Failed to synthesize sample\n");
608 		return ret;
609 	}
610 	return perf_event__repipe_synth(tool, event_copy);
611 }
612 
613 static struct dso *findnew_dso(int pid, int tid, const char *filename,
614 			       const struct dso_id *id, struct machine *machine)
615 {
616 	struct thread *thread;
617 	struct nsinfo *nsi = NULL;
618 	struct nsinfo *nnsi;
619 	struct dso *dso;
620 	bool vdso;
621 
622 	thread = machine__findnew_thread(machine, pid, tid);
623 	if (thread == NULL) {
624 		pr_err("cannot find or create a task %d/%d.\n", tid, pid);
625 		return NULL;
626 	}
627 
628 	vdso = is_vdso_map(filename);
629 	nsi = nsinfo__get(thread__nsinfo(thread));
630 
631 	if (vdso) {
632 		/* The vdso maps are always on the host and not the
633 		 * container.  Ensure that we don't use setns to look
634 		 * them up.
635 		 */
636 		nnsi = nsinfo__copy(nsi);
637 		if (nnsi) {
638 			nsinfo__put(nsi);
639 			nsinfo__clear_need_setns(nnsi);
640 			nsi = nnsi;
641 		}
642 		dso = machine__findnew_vdso(machine, thread);
643 	} else {
644 		dso = machine__findnew_dso_id(machine, filename, id);
645 	}
646 
647 	if (dso) {
648 		mutex_lock(dso__lock(dso));
649 		dso__set_nsinfo(dso, nsi);
650 		mutex_unlock(dso__lock(dso));
651 	} else
652 		nsinfo__put(nsi);
653 
654 	thread__put(thread);
655 	return dso;
656 }
657 
658 /*
659  * The evsel used for the sample ID for mmap events. Typically stashed when
660  * processing mmap events. If not stashed, search the evlist for the first mmap
661  * gathering event.
662  */
663 static struct evsel *inject__mmap_evsel(struct perf_inject *inject)
664 {
665 	struct evsel *pos;
666 
667 	if (inject->mmap_evsel)
668 		return inject->mmap_evsel;
669 
670 	evlist__for_each_entry(inject->session->evlist, pos) {
671 		if (pos->core.attr.mmap) {
672 			inject->mmap_evsel = pos;
673 			return pos;
674 		}
675 	}
676 	pr_err("No mmap events found\n");
677 	return NULL;
678 }
679 
680 static int perf_event__repipe_common_mmap(const struct perf_tool *tool,
681 					  union perf_event *event,
682 					  struct perf_sample *sample,
683 					  struct machine *machine,
684 					  __u32 pid, __u32 tid,
685 					  __u64 start, __u64 len, __u64 pgoff,
686 					  __u32 flags, __u32 prot,
687 					  const char *filename,
688 					  const struct dso_id *dso_id,
689 					  int (*perf_event_process)(const struct perf_tool *tool,
690 								    union perf_event *event,
691 								    struct perf_sample *sample,
692 								    struct machine *machine))
693 {
694 	struct perf_inject *inject = container_of(tool, struct perf_inject, tool);
695 	struct dso *dso = NULL;
696 	bool dso_sought = false;
697 
698 #ifdef HAVE_JITDUMP
699 	if (inject->jit_mode) {
700 		u64 n = 0;
701 		int ret;
702 
703 		/* If jit marker, then inject jit mmaps and generate ELF images. */
704 		ret = jit_process(inject->session, &inject->output, machine,
705 				  filename, pid, tid, &n);
706 		if (ret < 0)
707 			return ret;
708 		if (ret) {
709 			inject->bytes_written += n;
710 			return 0;
711 		}
712 	}
713 #endif
714 	if (event->header.misc & PERF_RECORD_MISC_MMAP_BUILD_ID) {
715 		dso = findnew_dso(pid, tid, filename, dso_id, machine);
716 		dso_sought = true;
717 		if (dso) {
718 			/* mark it not to inject build-id */
719 			dso__set_hit(dso);
720 		}
721 	}
722 	if (inject->build_id_style == BID_RWS__INJECT_HEADER_ALL) {
723 		if (!dso_sought) {
724 			dso = findnew_dso(pid, tid, filename, dso_id, machine);
725 			dso_sought = true;
726 		}
727 
728 		if (dso && !dso__hit(dso)) {
729 			if (!sample->evsel) {
730 				sample->evsel = evlist__event2evsel(inject->session->evlist, event);
731 				if (sample->evsel)
732 					evsel__get(sample->evsel);
733 			}
734 
735 			if (sample->evsel) {
736 				dso__set_hit(dso);
737 				tool__inject_build_id(tool, sample, machine,
738 						      /*misc=*/sample->cpumode,
739 						      filename, dso, flags);
740 			}
741 		}
742 	} else {
743 		int err;
744 
745 		/*
746 		 * Remember the evsel for lazy build id generation. It is used
747 		 * for the sample id header type.
748 		 */
749 		if ((inject->build_id_style == BID_RWS__INJECT_HEADER_LAZY ||
750 		     inject->build_id_style == BID_RWS__MMAP2_BUILDID_LAZY) &&
751 		    !inject->mmap_evsel)
752 			inject->mmap_evsel = evlist__event2evsel(inject->session->evlist, event);
753 
754 		/* Create the thread, map, etc. Not done for the unordered inject all case. */
755 		err = perf_event_process(tool, event, sample, machine);
756 
757 		if (err) {
758 			dso__put(dso);
759 			return err;
760 		}
761 	}
762 	if ((inject->build_id_style == BID_RWS__MMAP2_BUILDID_ALL) &&
763 	    !(event->header.misc & PERF_RECORD_MISC_MMAP_BUILD_ID)) {
764 		struct evsel *saved_evsel = sample->evsel;
765 
766 		sample->evsel = evlist__event2evsel(inject->session->evlist, event);
767 		if (sample->evsel && !dso_sought) {
768 			dso = findnew_dso(pid, tid, filename, dso_id, machine);
769 			dso_sought = true;
770 		}
771 		if (sample->evsel && dso &&
772 		    !tool__inject_mmap2_build_id(tool, sample, machine,
773 						 sample->cpumode | PERF_RECORD_MISC_MMAP_BUILD_ID,
774 						 pid, tid, start, len, pgoff,
775 						 dso,
776 						 prot, flags,
777 						 filename)) {
778 			/* Injected mmap2 so no need to repipe. */
779 			sample->evsel = saved_evsel;
780 			dso__put(dso);
781 			return 0;
782 		}
783 		sample->evsel = saved_evsel;
784 	}
785 	dso__put(dso);
786 	if (inject->build_id_style == BID_RWS__MMAP2_BUILDID_LAZY)
787 		return 0;
788 
789 	return perf_event__repipe(tool, event, sample, machine);
790 }
791 
792 static int perf_event__repipe_mmap(const struct perf_tool *tool,
793 				union perf_event *event,
794 				struct perf_sample *sample,
795 				struct machine *machine)
796 {
797 	return perf_event__repipe_common_mmap(
798 		tool, event, sample, machine,
799 		event->mmap.pid, event->mmap.tid,
800 		event->mmap.start, event->mmap.len, event->mmap.pgoff,
801 		/*flags=*/0, PROT_EXEC,
802 		event->mmap.filename, /*dso_id=*/NULL,
803 		perf_event__process_mmap);
804 }
805 
806 static int perf_event__repipe_mmap2(const struct perf_tool *tool,
807 				union perf_event *event,
808 				struct perf_sample *sample,
809 				struct machine *machine)
810 {
811 	struct dso_id id = dso_id_empty;
812 
813 	if (event->header.misc & PERF_RECORD_MISC_MMAP_BUILD_ID) {
814 		build_id__init(&id.build_id, event->mmap2.build_id, event->mmap2.build_id_size);
815 	} else {
816 		id.maj = event->mmap2.maj;
817 		id.min = event->mmap2.min;
818 		id.ino = event->mmap2.ino;
819 		id.ino_generation = event->mmap2.ino_generation;
820 		id.mmap2_valid = true;
821 		id.mmap2_ino_generation_valid = true;
822 	}
823 
824 	return perf_event__repipe_common_mmap(
825 		tool, event, sample, machine,
826 		event->mmap2.pid, event->mmap2.tid,
827 		event->mmap2.start, event->mmap2.len, event->mmap2.pgoff,
828 		event->mmap2.flags, event->mmap2.prot,
829 		event->mmap2.filename, &id,
830 		perf_event__process_mmap2);
831 }
832 
833 static int perf_event__repipe_fork(const struct perf_tool *tool,
834 				   union perf_event *event,
835 				   struct perf_sample *sample,
836 				   struct machine *machine)
837 {
838 	int err;
839 
840 	err = perf_event__process_fork(tool, event, sample, machine);
841 	perf_event__repipe(tool, event, sample, machine);
842 
843 	return err;
844 }
845 
846 static int perf_event__repipe_comm(const struct perf_tool *tool,
847 				   union perf_event *event,
848 				   struct perf_sample *sample,
849 				   struct machine *machine)
850 {
851 	int err;
852 
853 	err = perf_event__process_comm(tool, event, sample, machine);
854 	perf_event__repipe(tool, event, sample, machine);
855 
856 	return err;
857 }
858 
859 static int perf_event__repipe_namespaces(const struct perf_tool *tool,
860 					 union perf_event *event,
861 					 struct perf_sample *sample,
862 					 struct machine *machine)
863 {
864 	int err = perf_event__process_namespaces(tool, event, sample, machine);
865 
866 	perf_event__repipe(tool, event, sample, machine);
867 
868 	return err;
869 }
870 
871 static int perf_event__repipe_exit(const struct perf_tool *tool,
872 				   union perf_event *event,
873 				   struct perf_sample *sample,
874 				   struct machine *machine)
875 {
876 	int err;
877 
878 	err = perf_event__process_exit(tool, event, sample, machine);
879 	perf_event__repipe(tool, event, sample, machine);
880 
881 	return err;
882 }
883 
884 #ifdef HAVE_LIBTRACEEVENT
885 static int perf_event__repipe_tracing_data(const struct perf_tool *tool,
886 					   struct perf_session *session,
887 					   union perf_event *event)
888 {
889 	perf_event__repipe_synth(tool, event);
890 
891 	return perf_event__process_tracing_data(tool, session, event);
892 }
893 #endif
894 
895 static int dso__read_build_id(struct dso *dso)
896 {
897 	struct nscookie nsc;
898 	struct build_id bid = { .size = 0, };
899 
900 	if (dso__has_build_id(dso))
901 		return 0;
902 
903 	mutex_lock(dso__lock(dso));
904 	nsinfo__mountns_enter(dso__nsinfo(dso), &nsc);
905 	if (filename__read_build_id(dso__long_name(dso), &bid) > 0)
906 		dso__set_build_id(dso, &bid);
907 	else if (dso__nsinfo(dso)) {
908 		char *new_name = dso__filename_with_chroot(dso, dso__long_name(dso));
909 
910 		if (new_name && filename__read_build_id(new_name, &bid) > 0)
911 			dso__set_build_id(dso, &bid);
912 		free(new_name);
913 	}
914 	nsinfo__mountns_exit(&nsc);
915 	mutex_unlock(dso__lock(dso));
916 
917 	return dso__has_build_id(dso) ? 0 : -1;
918 }
919 
920 static struct strlist *perf_inject__parse_known_build_ids(
921 	const char *known_build_ids_string)
922 {
923 	struct str_node *pos, *tmp;
924 	struct strlist *known_build_ids;
925 	int bid_len;
926 
927 	known_build_ids = strlist__new(known_build_ids_string, NULL);
928 	if (known_build_ids == NULL)
929 		return NULL;
930 	strlist__for_each_entry_safe(pos, tmp, known_build_ids) {
931 		const char *build_id, *dso_name;
932 
933 		build_id = skip_spaces(pos->s);
934 		dso_name = strchr(build_id, ' ');
935 		if (dso_name == NULL) {
936 			strlist__remove(known_build_ids, pos);
937 			continue;
938 		}
939 		bid_len = dso_name - pos->s;
940 		dso_name = skip_spaces(dso_name);
941 		if (bid_len % 2 != 0 || bid_len >= SBUILD_ID_SIZE) {
942 			strlist__remove(known_build_ids, pos);
943 			continue;
944 		}
945 		for (int ix = 0; 2 * ix + 1 < bid_len; ++ix) {
946 			if (!isxdigit(build_id[2 * ix]) ||
947 			    !isxdigit(build_id[2 * ix + 1])) {
948 				strlist__remove(known_build_ids, pos);
949 				break;
950 			}
951 		}
952 	}
953 	return known_build_ids;
954 }
955 
956 static bool perf_inject__lookup_known_build_id(struct perf_inject *inject,
957 					       struct dso *dso)
958 {
959 	struct str_node *pos;
960 
961 	strlist__for_each_entry(pos, inject->known_build_ids) {
962 		struct build_id bid;
963 		const char *build_id, *dso_name;
964 		size_t bid_len;
965 
966 		build_id = skip_spaces(pos->s);
967 		dso_name = strchr(build_id, ' ');
968 		bid_len = dso_name - pos->s;
969 		if (bid_len > sizeof(bid.data))
970 			bid_len = sizeof(bid.data);
971 		dso_name = skip_spaces(dso_name);
972 		if (strcmp(dso__long_name(dso), dso_name))
973 			continue;
974 		for (size_t ix = 0; 2 * ix + 1 < bid_len; ++ix) {
975 			bid.data[ix] = (hex(build_id[2 * ix]) << 4 |
976 					hex(build_id[2 * ix + 1]));
977 		}
978 		bid.size = bid_len / 2;
979 		dso__set_build_id(dso, &bid);
980 		return true;
981 	}
982 	return false;
983 }
984 
985 static int tool__inject_build_id(const struct perf_tool *tool,
986 				 struct perf_sample *sample,
987 				 struct machine *machine,
988 				 __u16 misc,
989 				 const char *filename,
990 				 struct dso *dso, u32 flags)
991 {
992 	struct perf_inject *inject = container_of(tool, struct perf_inject, tool);
993 	int err;
994 
995 	if (is_anon_memory(filename) || flags & MAP_HUGETLB)
996 		return 0;
997 	if (is_no_dso_memory(filename))
998 		return 0;
999 
1000 	if (inject->known_build_ids != NULL &&
1001 	    perf_inject__lookup_known_build_id(inject, dso))
1002 		return 1;
1003 
1004 	if (dso__read_build_id(dso) < 0) {
1005 		pr_debug("no build_id found for %s\n", filename);
1006 		return -1;
1007 	}
1008 
1009 	err = perf_event__synthesize_build_id(tool, sample, machine,
1010 					      perf_event__repipe,
1011 					      misc, dso__bid(dso),
1012 					      filename);
1013 	if (err) {
1014 		pr_err("Can't synthesize build_id event for %s\n", filename);
1015 		return -1;
1016 	}
1017 
1018 	return 0;
1019 }
1020 
1021 static int tool__inject_mmap2_build_id(const struct perf_tool *tool,
1022 				       struct perf_sample *sample,
1023 				       struct machine *machine,
1024 				       __u16 misc,
1025 				       __u32 pid, __u32 tid,
1026 				       __u64 start, __u64 len, __u64 pgoff,
1027 				       struct dso *dso,
1028 				       __u32 prot, __u32 flags,
1029 				       const char *filename)
1030 {
1031 	int err;
1032 
1033 	/* Return to repipe anonymous maps. */
1034 	if (is_anon_memory(filename) || flags & MAP_HUGETLB)
1035 		return 1;
1036 	if (is_no_dso_memory(filename))
1037 		return 1;
1038 
1039 	if (dso__read_build_id(dso)) {
1040 		pr_debug("no build_id found for %s\n", filename);
1041 		return -1;
1042 	}
1043 
1044 	err = perf_event__synthesize_mmap2_build_id(tool, sample, machine,
1045 						    perf_event__repipe,
1046 						    misc, pid, tid,
1047 						    start, len, pgoff,
1048 						    dso__bid(dso),
1049 						    prot, flags,
1050 						    filename);
1051 	if (err) {
1052 		pr_err("Can't synthesize build_id event for %s\n", filename);
1053 		return -1;
1054 	}
1055 	return 0;
1056 }
1057 
1058 static int mark_dso_hit(const struct perf_inject *inject,
1059 			const struct perf_tool *tool,
1060 			struct perf_sample *sample,
1061 			struct machine *machine,
1062 			struct evsel *mmap_evsel,
1063 			struct map *map, bool sample_in_dso)
1064 {
1065 	struct dso *dso;
1066 	u16 misc = sample->cpumode;
1067 
1068 	if (!map)
1069 		return 0;
1070 
1071 	if (!sample_in_dso) {
1072 		u16 guest_mask = PERF_RECORD_MISC_GUEST_KERNEL |
1073 			PERF_RECORD_MISC_GUEST_USER;
1074 
1075 		if ((misc & guest_mask) != 0) {
1076 			misc &= PERF_RECORD_MISC_HYPERVISOR;
1077 			misc |= __map__is_kernel(map)
1078 				? PERF_RECORD_MISC_GUEST_KERNEL
1079 				: PERF_RECORD_MISC_GUEST_USER;
1080 		} else {
1081 			misc &= PERF_RECORD_MISC_HYPERVISOR;
1082 			misc |= __map__is_kernel(map)
1083 				? PERF_RECORD_MISC_KERNEL
1084 				: PERF_RECORD_MISC_USER;
1085 		}
1086 	}
1087 	dso = map__dso(map);
1088 	if (inject->build_id_style == BID_RWS__INJECT_HEADER_LAZY) {
1089 		if (dso && !dso__hit(dso)) {
1090 			/*
1091 			 * The sample is just read for identifiers which we want
1092 			 * to match the for the event of the sample.
1093 			 */
1094 			dso__set_hit(dso);
1095 			tool__inject_build_id(tool, sample, machine,
1096 					     misc, dso__long_name(dso), dso,
1097 					     map__flags(map));
1098 		}
1099 	} else if (inject->build_id_style == BID_RWS__MMAP2_BUILDID_LAZY) {
1100 		if (!map__hit(map)) {
1101 			const struct build_id null_bid = { .size = 0 };
1102 			const struct build_id *bid = dso ? dso__bid(dso) : &null_bid;
1103 			const char *filename = dso ? dso__long_name(dso) : "";
1104 			struct evsel *saved_evsel = sample->evsel;
1105 
1106 			map__set_hit(map);
1107 			/* Creating a new mmap2 event which has an evsel for the mmap event. */
1108 			sample->evsel = mmap_evsel;
1109 			perf_event__synthesize_mmap2_build_id(tool, sample, machine,
1110 								perf_event__repipe,
1111 								misc,
1112 								sample->pid, sample->tid,
1113 								map__start(map),
1114 								map__end(map) - map__start(map),
1115 								map__pgoff(map),
1116 								bid,
1117 								map__prot(map),
1118 								map__flags(map),
1119 								filename);
1120 			sample->evsel = saved_evsel;
1121 		}
1122 	}
1123 	return 0;
1124 }
1125 
1126 struct mark_dso_hit_args {
1127 	const struct perf_inject *inject;
1128 	const struct perf_tool *tool;
1129 	struct perf_sample *sample;
1130 	struct machine *machine;
1131 	struct evsel *mmap_evsel;
1132 };
1133 
1134 static int mark_dso_hit_callback(struct callchain_cursor_node *node, void *data)
1135 {
1136 	struct mark_dso_hit_args *args = data;
1137 	struct map *map = node->ms.map;
1138 
1139 	return mark_dso_hit(args->inject, args->tool, args->sample, args->machine,
1140 			    args->mmap_evsel, map, /*sample_in_dso=*/false);
1141 }
1142 
1143 static int perf_event__inject_buildid(const struct perf_tool *tool, union perf_event *event,
1144 				      struct perf_sample *sample, struct machine *machine)
1145 {
1146 	struct addr_location al;
1147 	struct thread *thread;
1148 	struct perf_inject *inject = container_of(tool, struct perf_inject, tool);
1149 	struct mark_dso_hit_args args = {
1150 		.inject = inject,
1151 		.tool = tool,
1152 		/*
1153 		 * Use the parsed sample data of the sample event, which will
1154 		 * have a later timestamp than the mmap event.
1155 		 */
1156 		.sample = sample,
1157 		.machine = machine,
1158 		.mmap_evsel = inject__mmap_evsel(inject),
1159 	};
1160 
1161 	addr_location__init(&al);
1162 	thread = machine__findnew_thread(machine, sample->pid, sample->tid);
1163 	if (thread == NULL) {
1164 		pr_err("problem processing %d event, skipping it.\n",
1165 		       event->header.type);
1166 		goto repipe;
1167 	}
1168 
1169 	if (thread__find_map(thread, sample->cpumode, sample->ip, &al)) {
1170 		mark_dso_hit(inject, tool, sample, machine, args.mmap_evsel, al.map,
1171 			     /*sample_in_dso=*/true);
1172 	}
1173 
1174 	sample__for_each_callchain_node(thread, sample, PERF_MAX_STACK_DEPTH,
1175 					/*symbols=*/false, mark_dso_hit_callback, &args);
1176 	thread__put(thread);
1177 repipe:
1178 	perf_event__repipe(tool, event, sample, machine);
1179 	addr_location__exit(&al);
1180 	return 0;
1181 }
1182 
1183 static int perf_inject__sched_process_exit(const struct perf_tool *tool,
1184 					   union perf_event *event __maybe_unused,
1185 					   struct perf_sample *sample,
1186 					   struct machine *machine __maybe_unused)
1187 {
1188 	struct perf_inject *inject = container_of(tool, struct perf_inject, tool);
1189 	struct event_entry *ent;
1190 
1191 	list_for_each_entry(ent, &inject->samples, node) {
1192 		if (sample->tid == ent->tid) {
1193 			list_del_init(&ent->node);
1194 			free(ent);
1195 			break;
1196 		}
1197 	}
1198 
1199 	return 0;
1200 }
1201 
1202 static int perf_inject__sched_switch(const struct perf_tool *tool,
1203 				     union perf_event *event,
1204 				     struct perf_sample *sample,
1205 				     struct machine *machine)
1206 {
1207 	struct perf_inject *inject = container_of(tool, struct perf_inject, tool);
1208 	struct event_entry *ent;
1209 
1210 	perf_inject__sched_process_exit(tool, event, sample, machine);
1211 
1212 	ent = malloc(event->header.size + sizeof(struct event_entry));
1213 	if (ent == NULL) {
1214 		color_fprintf(stderr, PERF_COLOR_RED,
1215 			     "Not enough memory to process sched switch event!");
1216 		return -1;
1217 	}
1218 
1219 	ent->tid = sample->tid;
1220 	memcpy(&ent->event, event, event->header.size);
1221 	list_add(&ent->node, &inject->samples);
1222 	return 0;
1223 }
1224 
1225 #ifdef HAVE_LIBTRACEEVENT
1226 static int perf_inject__sched_stat(const struct perf_tool *tool,
1227 				   union perf_event *event __maybe_unused,
1228 				   struct perf_sample *sample,
1229 				   struct machine *machine)
1230 {
1231 	struct event_entry *ent;
1232 	union perf_event *event_sw;
1233 	struct perf_sample sample_sw;
1234 	struct perf_inject *inject = container_of(tool, struct perf_inject, tool);
1235 	struct evsel *evsel = sample->evsel;
1236 	u32 pid = perf_sample__intval(sample, "pid");
1237 	int ret;
1238 
1239 	list_for_each_entry(ent, &inject->samples, node) {
1240 		if (pid == ent->tid)
1241 			goto found;
1242 	}
1243 
1244 	return 0;
1245 found:
1246 	event_sw = &ent->event[0];
1247 	evsel__parse_sample(evsel, event_sw, &sample_sw);
1248 
1249 	sample_sw.period = sample->period;
1250 	sample_sw.time	 = sample->time;
1251 	perf_event__synthesize_sample(event_sw, evsel->core.attr.sample_type,
1252 				      evsel->core.attr.read_format,
1253 				      evsel->core.attr.branch_sample_type, &sample_sw);
1254 	build_id__mark_dso_hit(tool, event_sw, &sample_sw, machine);
1255 	ret = perf_event__repipe(tool, event_sw, &sample_sw, machine);
1256 	perf_sample__exit(&sample_sw);
1257 	return ret;
1258 }
1259 #endif
1260 
1261 static struct guest_vcpu *guest_session__vcpu(struct guest_session *gs, u32 vcpu)
1262 {
1263 	if (realloc_array_as_needed(gs->vcpu, gs->vcpu_cnt, vcpu, NULL))
1264 		return NULL;
1265 	return &gs->vcpu[vcpu];
1266 }
1267 
1268 static int guest_session__output_bytes(struct guest_session *gs, void *buf, size_t sz)
1269 {
1270 	ssize_t ret = writen(gs->tmp_fd, buf, sz);
1271 
1272 	return ret < 0 ? ret : 0;
1273 }
1274 
1275 static int guest_session__repipe(const struct perf_tool *tool,
1276 				 union perf_event *event,
1277 				 struct perf_sample *sample __maybe_unused,
1278 				 struct machine *machine __maybe_unused)
1279 {
1280 	struct guest_session *gs = container_of(tool, struct guest_session, tool);
1281 
1282 	return guest_session__output_bytes(gs, event, event->header.size);
1283 }
1284 
1285 static int guest_session__map_tid(struct guest_session *gs, u32 tid, u32 vcpu)
1286 {
1287 	struct guest_tid *guest_tid = zalloc(sizeof(*guest_tid));
1288 	int hash;
1289 
1290 	if (!guest_tid)
1291 		return -ENOMEM;
1292 
1293 	guest_tid->tid = tid;
1294 	guest_tid->vcpu = vcpu;
1295 	hash = hash_32(guest_tid->tid, PERF_EVLIST__HLIST_BITS);
1296 	hlist_add_head(&guest_tid->node, &gs->tids[hash]);
1297 
1298 	return 0;
1299 }
1300 
1301 static int host_peek_vm_comms_cb(struct perf_session *session __maybe_unused,
1302 				 union perf_event *event,
1303 				 u64 offset __maybe_unused, void *data)
1304 {
1305 	struct guest_session *gs = data;
1306 	unsigned int vcpu;
1307 	struct guest_vcpu *guest_vcpu;
1308 	int ret;
1309 
1310 	if (event->header.type != PERF_RECORD_COMM ||
1311 	    event->comm.pid != gs->machine_pid)
1312 		return 0;
1313 
1314 	/*
1315 	 * QEMU option -name debug-threads=on, causes thread names formatted as
1316 	 * below, although it is not an ABI. Also libvirt seems to use this by
1317 	 * default. Here we rely on it to tell us which thread is which VCPU.
1318 	 */
1319 	ret = sscanf(event->comm.comm, "CPU %u/KVM", &vcpu);
1320 	if (ret <= 0)
1321 		return ret;
1322 	pr_debug("Found VCPU: tid %u comm %s vcpu %u\n",
1323 		 event->comm.tid, event->comm.comm, vcpu);
1324 	if (vcpu > INT_MAX) {
1325 		pr_err("Invalid VCPU %u\n", vcpu);
1326 		return -EINVAL;
1327 	}
1328 	guest_vcpu = guest_session__vcpu(gs, vcpu);
1329 	if (!guest_vcpu)
1330 		return -ENOMEM;
1331 	if (guest_vcpu->tid && guest_vcpu->tid != event->comm.tid) {
1332 		pr_err("Fatal error: Two threads found with the same VCPU\n");
1333 		return -EINVAL;
1334 	}
1335 	guest_vcpu->tid = event->comm.tid;
1336 
1337 	return guest_session__map_tid(gs, event->comm.tid, vcpu);
1338 }
1339 
1340 static int host_peek_vm_comms(struct perf_session *session, struct guest_session *gs)
1341 {
1342 	return perf_session__peek_events(session, session->header.data_offset,
1343 					 session->header.data_size,
1344 					 host_peek_vm_comms_cb, gs);
1345 }
1346 
1347 static bool evlist__is_id_used(struct evlist *evlist, u64 id)
1348 {
1349 	return evlist__id2sid(evlist, id);
1350 }
1351 
1352 static u64 guest_session__allocate_new_id(struct guest_session *gs, struct evlist *host_evlist)
1353 {
1354 	do {
1355 		gs->highest_id += 1;
1356 	} while (!gs->highest_id || evlist__is_id_used(host_evlist, gs->highest_id));
1357 
1358 	return gs->highest_id;
1359 }
1360 
1361 static int guest_session__map_id(struct guest_session *gs, u64 id, u64 host_id, u32 vcpu)
1362 {
1363 	struct guest_id *guest_id = zalloc(sizeof(*guest_id));
1364 	int hash;
1365 
1366 	if (!guest_id)
1367 		return -ENOMEM;
1368 
1369 	guest_id->id = id;
1370 	guest_id->host_id = host_id;
1371 	guest_id->vcpu = vcpu;
1372 	hash = hash_64(guest_id->id, PERF_EVLIST__HLIST_BITS);
1373 	hlist_add_head(&guest_id->node, &gs->heads[hash]);
1374 
1375 	return 0;
1376 }
1377 
1378 static u64 evlist__find_highest_id(struct evlist *evlist)
1379 {
1380 	struct evsel *evsel;
1381 	u64 highest_id = 1;
1382 
1383 	evlist__for_each_entry(evlist, evsel) {
1384 		u32 j;
1385 
1386 		for (j = 0; j < evsel->core.ids; j++) {
1387 			u64 id = evsel->core.id[j];
1388 
1389 			if (id > highest_id)
1390 				highest_id = id;
1391 		}
1392 	}
1393 
1394 	return highest_id;
1395 }
1396 
1397 static int guest_session__map_ids(struct guest_session *gs, struct evlist *host_evlist)
1398 {
1399 	struct evlist *evlist = gs->session->evlist;
1400 	struct evsel *evsel;
1401 	int ret;
1402 
1403 	evlist__for_each_entry(evlist, evsel) {
1404 		u32 j;
1405 
1406 		for (j = 0; j < evsel->core.ids; j++) {
1407 			struct perf_sample_id *sid;
1408 			u64 host_id;
1409 			u64 id;
1410 
1411 			id = evsel->core.id[j];
1412 			sid = evlist__id2sid(evlist, id);
1413 			if (!sid || sid->cpu.cpu == -1)
1414 				continue;
1415 			host_id = guest_session__allocate_new_id(gs, host_evlist);
1416 			ret = guest_session__map_id(gs, id, host_id, sid->cpu.cpu);
1417 			if (ret)
1418 				return ret;
1419 		}
1420 	}
1421 
1422 	return 0;
1423 }
1424 
1425 static struct guest_id *guest_session__lookup_id(struct guest_session *gs, u64 id)
1426 {
1427 	struct hlist_head *head;
1428 	struct guest_id *guest_id;
1429 	int hash;
1430 
1431 	hash = hash_64(id, PERF_EVLIST__HLIST_BITS);
1432 	head = &gs->heads[hash];
1433 
1434 	hlist_for_each_entry(guest_id, head, node)
1435 		if (guest_id->id == id)
1436 			return guest_id;
1437 
1438 	return NULL;
1439 }
1440 
1441 static int process_attr(const struct perf_tool *tool, union perf_event *event,
1442 			struct perf_sample *sample __maybe_unused,
1443 			struct machine *machine __maybe_unused)
1444 {
1445 	struct perf_inject *inject = container_of(tool, struct perf_inject, tool);
1446 
1447 	return perf_event__process_attr(tool, event, &inject->session->evlist);
1448 }
1449 
1450 static int guest_session__add_attr(struct guest_session *gs, struct evsel *evsel)
1451 {
1452 	struct perf_inject *inject = container_of(gs, struct perf_inject, guest_session);
1453 	struct perf_event_attr attr = evsel->core.attr;
1454 	u64 *id_array;
1455 	u32 *vcpu_array;
1456 	int ret = -ENOMEM;
1457 	u32 i;
1458 
1459 	id_array = calloc(evsel->core.ids, sizeof(*id_array));
1460 	if (!id_array)
1461 		return -ENOMEM;
1462 
1463 	vcpu_array = calloc(evsel->core.ids, sizeof(*vcpu_array));
1464 	if (!vcpu_array)
1465 		goto out;
1466 
1467 	for (i = 0; i < evsel->core.ids; i++) {
1468 		u64 id = evsel->core.id[i];
1469 		struct guest_id *guest_id = guest_session__lookup_id(gs, id);
1470 
1471 		if (!guest_id) {
1472 			pr_err("Failed to find guest id %"PRIu64"\n", id);
1473 			ret = -EINVAL;
1474 			goto out;
1475 		}
1476 		id_array[i] = guest_id->host_id;
1477 		vcpu_array[i] = guest_id->vcpu;
1478 	}
1479 
1480 	attr.sample_type |= PERF_SAMPLE_IDENTIFIER;
1481 	attr.exclude_host = 1;
1482 	attr.exclude_guest = 0;
1483 
1484 	ret = perf_event__synthesize_attr(&inject->tool, &attr, evsel->core.ids,
1485 					  id_array, process_attr);
1486 	if (ret)
1487 		pr_err("Failed to add guest attr.\n");
1488 
1489 	for (i = 0; i < evsel->core.ids; i++) {
1490 		struct perf_sample_id *sid;
1491 		u32 vcpu = vcpu_array[i];
1492 
1493 		sid = evlist__id2sid(inject->session->evlist, id_array[i]);
1494 		/* Guest event is per-thread from the host point of view */
1495 		sid->cpu.cpu = -1;
1496 		sid->tid = gs->vcpu[vcpu].tid;
1497 		sid->machine_pid = gs->machine_pid;
1498 		sid->vcpu.cpu = vcpu;
1499 	}
1500 out:
1501 	free(vcpu_array);
1502 	free(id_array);
1503 	return ret;
1504 }
1505 
1506 static int guest_session__add_attrs(struct guest_session *gs)
1507 {
1508 	struct evlist *evlist = gs->session->evlist;
1509 	struct evsel *evsel;
1510 	int ret;
1511 
1512 	evlist__for_each_entry(evlist, evsel) {
1513 		ret = guest_session__add_attr(gs, evsel);
1514 		if (ret)
1515 			return ret;
1516 	}
1517 
1518 	return 0;
1519 }
1520 
1521 static int synthesize_id_index(struct perf_inject *inject, size_t new_cnt)
1522 {
1523 	struct perf_session *session = inject->session;
1524 	struct evlist *evlist = session->evlist;
1525 	struct machine *machine = &session->machines.host;
1526 	size_t from = evlist__nr_entries(evlist) - new_cnt;
1527 
1528 	return __perf_event__synthesize_id_index(&inject->tool, perf_event__repipe,
1529 						 evlist, machine, from);
1530 }
1531 
1532 static struct guest_tid *guest_session__lookup_tid(struct guest_session *gs, u32 tid)
1533 {
1534 	struct hlist_head *head;
1535 	struct guest_tid *guest_tid;
1536 	int hash;
1537 
1538 	hash = hash_32(tid, PERF_EVLIST__HLIST_BITS);
1539 	head = &gs->tids[hash];
1540 
1541 	hlist_for_each_entry(guest_tid, head, node)
1542 		if (guest_tid->tid == tid)
1543 			return guest_tid;
1544 
1545 	return NULL;
1546 }
1547 
1548 static bool dso__is_in_kernel_space(struct dso *dso)
1549 {
1550 	if (dso__is_vdso(dso))
1551 		return false;
1552 
1553 	return dso__is_kcore(dso) ||
1554 	       dso__kernel(dso) ||
1555 	       is_kernel_module(dso__long_name(dso), PERF_RECORD_MISC_CPUMODE_UNKNOWN);
1556 }
1557 
1558 static u64 evlist__first_id(struct evlist *evlist)
1559 {
1560 	struct evsel *evsel;
1561 
1562 	evlist__for_each_entry(evlist, evsel) {
1563 		if (evsel->core.ids)
1564 			return evsel->core.id[0];
1565 	}
1566 	return 0;
1567 }
1568 
1569 static int process_build_id(const struct perf_tool *tool,
1570 			    union perf_event *event,
1571 			    struct perf_sample *sample __maybe_unused,
1572 			    struct machine *machine __maybe_unused)
1573 {
1574 	struct perf_inject *inject = container_of(tool, struct perf_inject, tool);
1575 
1576 	return perf_event__process_build_id(tool, inject->session, event);
1577 }
1578 
1579 static int synthesize_build_id(struct perf_inject *inject, struct dso *dso, pid_t machine_pid)
1580 {
1581 	struct machine *machine = perf_session__findnew_machine(inject->session, machine_pid);
1582 	struct perf_sample synth_sample = {
1583 		.evsel	   = inject__mmap_evsel(inject),
1584 		.pid	   = -1,
1585 		.tid	   = -1,
1586 		.time	   = -1,
1587 		.stream_id = -1,
1588 		.cpu	   = -1,
1589 		.period	   = 1,
1590 		.cpumode   = dso__is_in_kernel_space(dso)
1591 		? PERF_RECORD_MISC_GUEST_KERNEL
1592 		: PERF_RECORD_MISC_GUEST_USER,
1593 	};
1594 
1595 	if (!machine)
1596 		return -ENOMEM;
1597 
1598 	dso__set_hit(dso);
1599 
1600 	return perf_event__synthesize_build_id(&inject->tool, &synth_sample, machine,
1601 					       process_build_id,
1602 					       /*misc=*/synth_sample.cpumode,
1603 					       dso__bid(dso), dso__long_name(dso));
1604 }
1605 
1606 static int guest_session__add_build_ids_cb(struct dso *dso, void *data)
1607 {
1608 	struct guest_session *gs = data;
1609 	struct perf_inject *inject = container_of(gs, struct perf_inject, guest_session);
1610 
1611 	if (!dso__has_build_id(dso))
1612 		return 0;
1613 
1614 	return synthesize_build_id(inject, dso, gs->machine_pid);
1615 
1616 }
1617 
1618 static int guest_session__add_build_ids(struct guest_session *gs)
1619 {
1620 	struct perf_inject *inject = container_of(gs, struct perf_inject, guest_session);
1621 
1622 	/* Build IDs will be put in the Build ID feature section */
1623 	perf_header__set_feat(&inject->session->header, HEADER_BUILD_ID);
1624 
1625 	return dsos__for_each_dso(&gs->session->machines.host.dsos,
1626 				  guest_session__add_build_ids_cb,
1627 				  gs);
1628 }
1629 
1630 static int guest_session__ksymbol_event(const struct perf_tool *tool,
1631 					union perf_event *event,
1632 					struct perf_sample *sample __maybe_unused,
1633 					struct machine *machine __maybe_unused)
1634 {
1635 	struct guest_session *gs = container_of(tool, struct guest_session, tool);
1636 
1637 	/* Only support out-of-line i.e. no BPF support */
1638 	if (event->ksymbol.ksym_type != PERF_RECORD_KSYMBOL_TYPE_OOL)
1639 		return 0;
1640 
1641 	return guest_session__output_bytes(gs, event, event->header.size);
1642 }
1643 
1644 static int guest_session__start(struct guest_session *gs, const char *name, bool force)
1645 {
1646 	char tmp_file_name[] = "/tmp/perf-inject-guest_session-XXXXXX";
1647 	struct perf_session *session;
1648 	int ret;
1649 
1650 	/* Only these events will be injected */
1651 	gs->tool.mmap		= guest_session__repipe;
1652 	gs->tool.mmap2		= guest_session__repipe;
1653 	gs->tool.comm		= guest_session__repipe;
1654 	gs->tool.fork		= guest_session__repipe;
1655 	gs->tool.exit		= guest_session__repipe;
1656 	gs->tool.lost		= guest_session__repipe;
1657 	gs->tool.context_switch	= guest_session__repipe;
1658 	gs->tool.ksymbol	= guest_session__ksymbol_event;
1659 	gs->tool.text_poke	= guest_session__repipe;
1660 	/*
1661 	 * Processing a build ID creates a struct dso with that build ID. Later,
1662 	 * all guest dsos are iterated and the build IDs processed into the host
1663 	 * session where they will be output to the Build ID feature section
1664 	 * when the perf.data file header is written.
1665 	 */
1666 	gs->tool.build_id	= perf_event__process_build_id;
1667 	/* Process the id index to know what VCPU an ID belongs to */
1668 	gs->tool.id_index	= perf_event__process_id_index;
1669 
1670 	gs->tool.ordered_events	= true;
1671 	gs->tool.ordering_requires_timestamps = true;
1672 
1673 	gs->data.path	= name;
1674 	gs->data.force	= force;
1675 	gs->data.mode	= PERF_DATA_MODE_READ;
1676 
1677 	session = perf_session__new(&gs->data, &gs->tool);
1678 	if (IS_ERR(session))
1679 		return PTR_ERR(session);
1680 	gs->session = session;
1681 
1682 	/*
1683 	 * Initial events have zero'd ID samples. Get default ID sample size
1684 	 * used for removing them.
1685 	 */
1686 	gs->dflt_id_hdr_size = session->machines.host.id_hdr_size;
1687 	/* And default ID for adding back a host-compatible ID sample */
1688 	gs->dflt_id = evlist__first_id(session->evlist);
1689 	if (!gs->dflt_id) {
1690 		pr_err("Guest data has no sample IDs");
1691 		return -EINVAL;
1692 	}
1693 
1694 	/* Temporary file for guest events */
1695 	gs->tmp_file_name = strdup(tmp_file_name);
1696 	if (!gs->tmp_file_name)
1697 		return -ENOMEM;
1698 	gs->tmp_fd = mkstemp(gs->tmp_file_name);
1699 	if (gs->tmp_fd < 0)
1700 		return -errno;
1701 
1702 	if (zstd_init(&gs->session->zstd_data, 0) < 0)
1703 		pr_warning("Guest session decompression initialization failed.\n");
1704 
1705 	/*
1706 	 * perf does not support processing 2 sessions simultaneously, so output
1707 	 * guest events to a temporary file.
1708 	 */
1709 	ret = perf_session__process_events(gs->session);
1710 	if (ret)
1711 		return ret;
1712 
1713 	if (lseek(gs->tmp_fd, 0, SEEK_SET))
1714 		return -errno;
1715 
1716 	return 0;
1717 }
1718 
1719 /* Free hlist nodes assuming hlist_node is the first member of hlist entries */
1720 static void free_hlist(struct hlist_head *heads, size_t hlist_sz)
1721 {
1722 	struct hlist_node *pos, *n;
1723 	size_t i;
1724 
1725 	for (i = 0; i < hlist_sz; ++i) {
1726 		hlist_for_each_safe(pos, n, &heads[i]) {
1727 			hlist_del(pos);
1728 			free(pos);
1729 		}
1730 	}
1731 }
1732 
1733 static void guest_session__exit(struct guest_session *gs)
1734 {
1735 	if (gs->session) {
1736 		perf_session__delete(gs->session);
1737 		free_hlist(gs->heads, PERF_EVLIST__HLIST_SIZE);
1738 		free_hlist(gs->tids, PERF_EVLIST__HLIST_SIZE);
1739 	}
1740 	if (gs->tmp_file_name) {
1741 		if (gs->tmp_fd >= 0)
1742 			close(gs->tmp_fd);
1743 		unlink(gs->tmp_file_name);
1744 		zfree(&gs->tmp_file_name);
1745 	}
1746 	zfree(&gs->vcpu);
1747 	zfree(&gs->perf_data_file);
1748 }
1749 
1750 static void get_tsc_conv(struct perf_tsc_conversion *tc, struct perf_record_time_conv *time_conv)
1751 {
1752 	tc->time_shift		= time_conv->time_shift;
1753 	tc->time_mult		= time_conv->time_mult;
1754 	tc->time_zero		= time_conv->time_zero;
1755 	tc->time_cycles		= time_conv->time_cycles;
1756 	tc->time_mask		= time_conv->time_mask;
1757 	tc->cap_user_time_zero	= time_conv->cap_user_time_zero;
1758 	tc->cap_user_time_short	= time_conv->cap_user_time_short;
1759 }
1760 
1761 static void guest_session__get_tc(struct guest_session *gs)
1762 {
1763 	struct perf_inject *inject = container_of(gs, struct perf_inject, guest_session);
1764 
1765 	get_tsc_conv(&gs->host_tc, &inject->session->time_conv);
1766 	get_tsc_conv(&gs->guest_tc, &gs->session->time_conv);
1767 }
1768 
1769 static void guest_session__convert_time(struct guest_session *gs, u64 guest_time, u64 *host_time)
1770 {
1771 	u64 tsc;
1772 
1773 	if (!guest_time) {
1774 		*host_time = 0;
1775 		return;
1776 	}
1777 
1778 	if (gs->guest_tc.cap_user_time_zero)
1779 		tsc = perf_time_to_tsc(guest_time, &gs->guest_tc);
1780 	else
1781 		tsc = guest_time;
1782 
1783 	/*
1784 	 * This is the correct order of operations for x86 if the TSC Offset and
1785 	 * Multiplier values are used.
1786 	 */
1787 	tsc -= gs->time_offset;
1788 	tsc /= gs->time_scale;
1789 
1790 	if (gs->host_tc.cap_user_time_zero)
1791 		*host_time = tsc_to_perf_time(tsc, &gs->host_tc);
1792 	else
1793 		*host_time = tsc;
1794 }
1795 
1796 static int guest_session__fetch(struct guest_session *gs)
1797 {
1798 	void *buf;
1799 	struct perf_event_header *hdr;
1800 	size_t hdr_sz = sizeof(*hdr);
1801 	ssize_t ret;
1802 
1803 	perf_sample__init(&gs->ev.sample, /*all=*/false);
1804 	buf = gs->ev.event_buf;
1805 	if (!buf) {
1806 		buf = malloc(PERF_SAMPLE_MAX_SIZE);
1807 		if (!buf)
1808 			return -ENOMEM;
1809 		gs->ev.event_buf = buf;
1810 	}
1811 	hdr = buf;
1812 	ret = readn(gs->tmp_fd, buf, hdr_sz);
1813 	if (ret < 0)
1814 		return ret;
1815 
1816 	if (!ret) {
1817 		/* Zero size means EOF */
1818 		hdr->size = 0;
1819 		return 0;
1820 	}
1821 
1822 	buf += hdr_sz;
1823 
1824 	ret = readn(gs->tmp_fd, buf, hdr->size - hdr_sz);
1825 	if (ret < 0)
1826 		return ret;
1827 
1828 	gs->ev.event = (union perf_event *)gs->ev.event_buf;
1829 	gs->ev.sample.time = 0;
1830 
1831 	if (hdr->type >= PERF_RECORD_USER_TYPE_START) {
1832 		pr_err("Unexpected type fetching guest event");
1833 		return 0;
1834 	}
1835 
1836 	ret = evlist__parse_sample(gs->session->evlist, gs->ev.event, &gs->ev.sample);
1837 	if (ret) {
1838 		pr_err("Parse failed fetching guest event");
1839 		return ret;
1840 	}
1841 
1842 	if (!gs->have_tc) {
1843 		guest_session__get_tc(gs);
1844 		gs->have_tc = true;
1845 	}
1846 
1847 	guest_session__convert_time(gs, gs->ev.sample.time, &gs->ev.sample.time);
1848 
1849 	return 0;
1850 }
1851 
1852 static int evlist__append_id_sample(struct evlist *evlist, union perf_event *ev,
1853 				    const struct perf_sample *sample)
1854 {
1855 	struct evsel *evsel;
1856 	void *array;
1857 	int ret;
1858 
1859 	evsel = evlist__id2evsel(evlist, sample->id);
1860 	array = ev;
1861 
1862 	if (!evsel) {
1863 		pr_err("No evsel for id %"PRIu64"\n", sample->id);
1864 		return -EINVAL;
1865 	}
1866 
1867 	array += ev->header.size;
1868 	ret = perf_event__synthesize_id_sample(array, evsel->core.attr.sample_type, sample);
1869 	if (ret < 0)
1870 		return ret;
1871 
1872 	if (ret & 7) {
1873 		pr_err("Bad id sample size %d\n", ret);
1874 		return -EINVAL;
1875 	}
1876 
1877 	ev->header.size += ret;
1878 
1879 	return 0;
1880 }
1881 
1882 static int guest_session__inject_events(struct guest_session *gs, u64 timestamp)
1883 {
1884 	struct perf_inject *inject = container_of(gs, struct perf_inject, guest_session);
1885 	int ret;
1886 
1887 	if (!gs->ready)
1888 		return 0;
1889 
1890 	while (1) {
1891 		struct perf_sample *sample;
1892 		struct guest_id *guest_id;
1893 		union perf_event *ev;
1894 		u16 id_hdr_size;
1895 		u8 cpumode;
1896 		u64 id;
1897 
1898 		if (!gs->fetched) {
1899 			ret = guest_session__fetch(gs);
1900 			if (ret)
1901 				break;
1902 			gs->fetched = true;
1903 		}
1904 
1905 		ev = gs->ev.event;
1906 		sample = &gs->ev.sample;
1907 
1908 		if (!ev->header.size) {
1909 			/* EOF */
1910 			perf_sample__exit(&gs->ev.sample);
1911 			gs->fetched = false;
1912 			ret = 0;
1913 			break;
1914 		}
1915 		if (sample->time > timestamp) {
1916 			ret = 0;
1917 			break;
1918 		}
1919 
1920 		/* Change cpumode to guest */
1921 		cpumode = ev->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
1922 		if (cpumode & PERF_RECORD_MISC_USER)
1923 			cpumode = PERF_RECORD_MISC_GUEST_USER;
1924 		else
1925 			cpumode = PERF_RECORD_MISC_GUEST_KERNEL;
1926 		ev->header.misc &= ~PERF_RECORD_MISC_CPUMODE_MASK;
1927 		ev->header.misc |= cpumode;
1928 
1929 		id = sample->id;
1930 		if (!id) {
1931 			id = gs->dflt_id;
1932 			id_hdr_size = gs->dflt_id_hdr_size;
1933 		} else {
1934 			struct evsel *evsel = evlist__id2evsel(gs->session->evlist, id);
1935 
1936 			id_hdr_size = evsel__id_hdr_size(evsel);
1937 		}
1938 
1939 		if (id_hdr_size & 7) {
1940 			pr_err("Bad id_hdr_size %u\n", id_hdr_size);
1941 			ret = -EINVAL;
1942 			break;
1943 		}
1944 
1945 		if (ev->header.size & 7) {
1946 			pr_err("Bad event size %u\n", ev->header.size);
1947 			ret = -EINVAL;
1948 			break;
1949 		}
1950 
1951 		/* Remove guest id sample */
1952 		ev->header.size -= id_hdr_size;
1953 
1954 		if (ev->header.size & 7) {
1955 			pr_err("Bad raw event size %u\n", ev->header.size);
1956 			ret = -EINVAL;
1957 			break;
1958 		}
1959 
1960 		guest_id = guest_session__lookup_id(gs, id);
1961 		if (!guest_id) {
1962 			pr_err("Guest event with unknown id %llu\n",
1963 			       (unsigned long long)id);
1964 			ret = -EINVAL;
1965 			break;
1966 		}
1967 
1968 		/* Change to host ID to avoid conflicting ID values */
1969 		sample->id = guest_id->host_id;
1970 		sample->stream_id = guest_id->host_id;
1971 
1972 		if (sample->cpu != (u32)-1) {
1973 			if (sample->cpu >= gs->vcpu_cnt) {
1974 				pr_err("Guest event with unknown VCPU %u\n",
1975 				       sample->cpu);
1976 				return -EINVAL;
1977 			}
1978 			/* Change to host CPU instead of guest VCPU */
1979 			sample->cpu = gs->vcpu[sample->cpu].cpu;
1980 		}
1981 
1982 		/* New id sample with new ID and CPU */
1983 		ret = evlist__append_id_sample(inject->session->evlist, ev, sample);
1984 		if (ret)
1985 			break;
1986 
1987 		if (ev->header.size & 7) {
1988 			pr_err("Bad new event size %u\n", ev->header.size);
1989 			ret = -EINVAL;
1990 			break;
1991 		}
1992 
1993 		ret = output_bytes(inject, ev, ev->header.size);
1994 		if (ret)
1995 			break;
1996 
1997 		/* Reset for next guest session event fetch. */
1998 		perf_sample__exit(sample);
1999 		gs->fetched = false;
2000 	}
2001 	if (ret && gs->fetched) {
2002 		/* Clear saved sample state on error. */
2003 		perf_sample__exit(&gs->ev.sample);
2004 		gs->fetched = false;
2005 	}
2006 	return ret;
2007 }
2008 
2009 static int guest_session__flush_events(struct guest_session *gs)
2010 {
2011 	return guest_session__inject_events(gs, -1);
2012 }
2013 
2014 static int host__repipe(const struct perf_tool *tool,
2015 			union perf_event *event,
2016 			struct perf_sample *sample,
2017 			struct machine *machine)
2018 {
2019 	struct perf_inject *inject = container_of(tool, struct perf_inject, tool);
2020 	int ret;
2021 
2022 	ret = guest_session__inject_events(&inject->guest_session, sample->time);
2023 	if (ret)
2024 		return ret;
2025 
2026 	return perf_event__repipe(tool, event, sample, machine);
2027 }
2028 
2029 static int host__finished_init(const struct perf_tool *tool, struct perf_session *session,
2030 			       union perf_event *event)
2031 {
2032 	struct perf_inject *inject = container_of(tool, struct perf_inject, tool);
2033 	struct guest_session *gs = &inject->guest_session;
2034 	int ret;
2035 
2036 	/*
2037 	 * Peek through host COMM events to find QEMU threads and the VCPU they
2038 	 * are running.
2039 	 */
2040 	ret = host_peek_vm_comms(session, gs);
2041 	if (ret)
2042 		return ret;
2043 
2044 	if (!gs->vcpu_cnt) {
2045 		pr_err("No VCPU threads found for pid %u\n", gs->machine_pid);
2046 		return -EINVAL;
2047 	}
2048 
2049 	/*
2050 	 * Allocate new (unused) host sample IDs and map them to the guest IDs.
2051 	 */
2052 	gs->highest_id = evlist__find_highest_id(session->evlist);
2053 	ret = guest_session__map_ids(gs, session->evlist);
2054 	if (ret)
2055 		return ret;
2056 
2057 	ret = guest_session__add_attrs(gs);
2058 	if (ret)
2059 		return ret;
2060 
2061 	ret = synthesize_id_index(inject, evlist__nr_entries(gs->session->evlist));
2062 	if (ret) {
2063 		pr_err("Failed to synthesize id_index\n");
2064 		return ret;
2065 	}
2066 
2067 	ret = guest_session__add_build_ids(gs);
2068 	if (ret) {
2069 		pr_err("Failed to add guest build IDs\n");
2070 		return ret;
2071 	}
2072 
2073 	gs->ready = true;
2074 
2075 	ret = guest_session__inject_events(gs, 0);
2076 	if (ret)
2077 		return ret;
2078 
2079 	return perf_event__repipe_op2_synth(tool, session, event);
2080 }
2081 
2082 /*
2083  * Obey finished-round ordering. The FINISHED_ROUND event is first processed
2084  * which flushes host events to file up until the last flush time. Then inject
2085  * guest events up to the same time. Finally write out the FINISHED_ROUND event
2086  * itself.
2087  */
2088 static int host__finished_round(const struct perf_tool *tool,
2089 				union perf_event *event,
2090 				struct ordered_events *oe)
2091 {
2092 	struct perf_inject *inject = container_of(tool, struct perf_inject, tool);
2093 	int ret = perf_event__process_finished_round(tool, event, oe);
2094 	u64 timestamp = ordered_events__last_flush_time(oe);
2095 
2096 	if (ret)
2097 		return ret;
2098 
2099 	ret = guest_session__inject_events(&inject->guest_session, timestamp);
2100 	if (ret)
2101 		return ret;
2102 
2103 	return perf_event__repipe_oe_synth(tool, event, oe);
2104 }
2105 
2106 static int host__context_switch(const struct perf_tool *tool,
2107 				union perf_event *event,
2108 				struct perf_sample *sample,
2109 				struct machine *machine)
2110 {
2111 	struct perf_inject *inject = container_of(tool, struct perf_inject, tool);
2112 	bool out = event->header.misc & PERF_RECORD_MISC_SWITCH_OUT;
2113 	struct guest_session *gs = &inject->guest_session;
2114 	u32 pid = event->context_switch.next_prev_pid;
2115 	u32 tid = event->context_switch.next_prev_tid;
2116 	struct guest_tid *guest_tid;
2117 	u32 vcpu;
2118 
2119 	if (out || pid != gs->machine_pid)
2120 		goto out;
2121 
2122 	guest_tid = guest_session__lookup_tid(gs, tid);
2123 	if (!guest_tid)
2124 		goto out;
2125 
2126 	if (sample->cpu == (u32)-1) {
2127 		pr_err("Switch event does not have CPU\n");
2128 		return -EINVAL;
2129 	}
2130 
2131 	vcpu = guest_tid->vcpu;
2132 	if (vcpu >= gs->vcpu_cnt)
2133 		return -EINVAL;
2134 
2135 	/* Guest is switching in, record which CPU the VCPU is now running on */
2136 	gs->vcpu[vcpu].cpu = sample->cpu;
2137 out:
2138 	return host__repipe(tool, event, sample, machine);
2139 }
2140 
2141 static void sig_handler(int sig __maybe_unused)
2142 {
2143 	session_done = 1;
2144 }
2145 
2146 static int evsel__check_stype(struct evsel *evsel, u64 sample_type, const char *sample_msg)
2147 {
2148 	struct perf_event_attr *attr = &evsel->core.attr;
2149 	const char *name = evsel__name(evsel);
2150 
2151 	if (!(attr->sample_type & sample_type)) {
2152 		pr_err("Samples for %s event do not have %s attribute set.",
2153 			name, sample_msg);
2154 		return -EINVAL;
2155 	}
2156 
2157 	return 0;
2158 }
2159 
2160 static int drop_sample(const struct perf_tool *tool __maybe_unused,
2161 		       union perf_event *event __maybe_unused,
2162 		       struct perf_sample *sample __maybe_unused,
2163 		       struct machine *machine __maybe_unused)
2164 {
2165 	return 0;
2166 }
2167 
2168 static void strip_init(struct perf_inject *inject)
2169 {
2170 	struct evlist *evlist = inject->session->evlist;
2171 	struct evsel *evsel;
2172 
2173 	inject->tool.context_switch = perf_event__drop;
2174 
2175 	evlist__for_each_entry(evlist, evsel)
2176 		evsel->handler = drop_sample;
2177 }
2178 
2179 static int parse_vm_time_correlation(const struct option *opt, const char *str, int unset)
2180 {
2181 	struct perf_inject *inject = opt->value;
2182 	const char *args;
2183 	char *dry_run;
2184 
2185 	if (unset)
2186 		return 0;
2187 
2188 	inject->itrace_synth_opts.set = true;
2189 	inject->itrace_synth_opts.vm_time_correlation = true;
2190 	inject->in_place_update = true;
2191 
2192 	if (!str)
2193 		return 0;
2194 
2195 	dry_run = skip_spaces(str);
2196 	if (!strncmp(dry_run, "dry-run", strlen("dry-run"))) {
2197 		inject->itrace_synth_opts.vm_tm_corr_dry_run = true;
2198 		inject->in_place_update_dry_run = true;
2199 		args = dry_run + strlen("dry-run");
2200 	} else {
2201 		args = str;
2202 	}
2203 
2204 	inject->itrace_synth_opts.vm_tm_corr_args = strdup(args);
2205 
2206 	return inject->itrace_synth_opts.vm_tm_corr_args ? 0 : -ENOMEM;
2207 }
2208 
2209 static int parse_guest_data(const struct option *opt, const char *str, int unset)
2210 {
2211 	struct perf_inject *inject = opt->value;
2212 	struct guest_session *gs = &inject->guest_session;
2213 	char *tok;
2214 	char *s;
2215 
2216 	if (unset)
2217 		return 0;
2218 
2219 	if (!str)
2220 		goto bad_args;
2221 
2222 	s = strdup(str);
2223 	if (!s)
2224 		return -ENOMEM;
2225 
2226 	gs->perf_data_file = strsep(&s, ",");
2227 	if (!gs->perf_data_file)
2228 		goto bad_args;
2229 
2230 	gs->copy_kcore_dir = has_kcore_dir(gs->perf_data_file);
2231 	if (gs->copy_kcore_dir)
2232 		inject->output.is_dir = true;
2233 
2234 	tok = strsep(&s, ",");
2235 	if (!tok)
2236 		goto bad_args;
2237 	gs->machine_pid = strtoul(tok, NULL, 0);
2238 	if (!inject->guest_session.machine_pid)
2239 		goto bad_args;
2240 
2241 	gs->time_scale = 1;
2242 
2243 	tok = strsep(&s, ",");
2244 	if (!tok)
2245 		goto out;
2246 	gs->time_offset = strtoull(tok, NULL, 0);
2247 
2248 	tok = strsep(&s, ",");
2249 	if (!tok)
2250 		goto out;
2251 	gs->time_scale = strtod(tok, NULL);
2252 	if (!gs->time_scale)
2253 		goto bad_args;
2254 out:
2255 	return 0;
2256 
2257 bad_args:
2258 	pr_err("--guest-data option requires guest perf.data file name, "
2259 	       "guest machine PID, and optionally guest timestamp offset, "
2260 	       "and guest timestamp scale factor, separated by commas.\n");
2261 	return -1;
2262 }
2263 
2264 static int save_section_info_cb(struct perf_file_section *section,
2265 				struct perf_header *ph __maybe_unused,
2266 				int feat, int fd __maybe_unused, void *data)
2267 {
2268 	struct perf_inject *inject = data;
2269 
2270 	inject->secs[feat] = *section;
2271 	return 0;
2272 }
2273 
2274 static int save_section_info(struct perf_inject *inject)
2275 {
2276 	struct perf_header *header = &inject->session->header;
2277 	int fd = perf_data__fd(inject->session->data);
2278 
2279 	return perf_header__process_sections(header, fd, inject, save_section_info_cb);
2280 }
2281 
2282 static bool keep_feat(struct perf_inject *inject, int feat)
2283 {
2284 	switch (feat) {
2285 	/* Keep original information that describes the machine or software */
2286 	case HEADER_TRACING_DATA:
2287 	case HEADER_HOSTNAME:
2288 	case HEADER_OSRELEASE:
2289 	case HEADER_VERSION:
2290 	case HEADER_ARCH:
2291 	case HEADER_NRCPUS:
2292 	case HEADER_CPUDESC:
2293 	case HEADER_CPUID:
2294 	case HEADER_TOTAL_MEM:
2295 	case HEADER_CPU_TOPOLOGY:
2296 	case HEADER_NUMA_TOPOLOGY:
2297 	case HEADER_PMU_MAPPINGS:
2298 	case HEADER_CACHE:
2299 	case HEADER_MEM_TOPOLOGY:
2300 	case HEADER_CLOCKID:
2301 	case HEADER_BPF_PROG_INFO:
2302 	case HEADER_BPF_BTF:
2303 	case HEADER_CPU_PMU_CAPS:
2304 	case HEADER_CLOCK_DATA:
2305 	case HEADER_HYBRID_TOPOLOGY:
2306 	case HEADER_PMU_CAPS:
2307 	case HEADER_CPU_DOMAIN_INFO:
2308 	case HEADER_CLN_SIZE:
2309 		return true;
2310 	/* Information that can be updated */
2311 	case HEADER_BUILD_ID:
2312 		return inject->build_id_style == BID_RWS__NONE;
2313 	case HEADER_CMDLINE:
2314 	case HEADER_EVENT_DESC:
2315 	case HEADER_BRANCH_STACK:
2316 	case HEADER_GROUP_DESC:
2317 	case HEADER_AUXTRACE:
2318 	case HEADER_STAT:
2319 	case HEADER_SAMPLE_TIME:
2320 	case HEADER_DIR_FORMAT:
2321 	case HEADER_COMPRESSED:
2322 	default:
2323 		return false;
2324 	};
2325 }
2326 
2327 static int read_file(int fd, u64 offs, void *buf, size_t sz)
2328 {
2329 	ssize_t ret = preadn(fd, buf, sz, offs);
2330 
2331 	if (ret < 0)
2332 		return -errno;
2333 	if ((size_t)ret != sz)
2334 		return -EINVAL;
2335 	return 0;
2336 }
2337 
2338 static int feat_copy(struct perf_inject *inject, int feat, struct feat_writer *fw)
2339 {
2340 	int fd = perf_data__fd(inject->session->data);
2341 	u64 offs = inject->secs[feat].offset;
2342 	size_t sz = inject->secs[feat].size;
2343 	void *buf = malloc(sz);
2344 	int ret;
2345 
2346 	if (!buf)
2347 		return -ENOMEM;
2348 
2349 	ret = read_file(fd, offs, buf, sz);
2350 	if (ret)
2351 		goto out_free;
2352 
2353 	ret = fw->write(fw, buf, sz);
2354 out_free:
2355 	free(buf);
2356 	return ret;
2357 }
2358 
2359 struct inject_fc {
2360 	struct feat_copier fc;
2361 	struct perf_inject *inject;
2362 };
2363 
2364 static int feat_copy_cb(struct feat_copier *fc, int feat, struct feat_writer *fw)
2365 {
2366 	struct inject_fc *inj_fc = container_of(fc, struct inject_fc, fc);
2367 	struct perf_inject *inject = inj_fc->inject;
2368 	int ret;
2369 
2370 	if (!inject->secs[feat].offset ||
2371 	    !keep_feat(inject, feat))
2372 		return 0;
2373 
2374 	ret = feat_copy(inject, feat, fw);
2375 	if (ret < 0)
2376 		return ret;
2377 
2378 	return 1; /* Feature section copied */
2379 }
2380 
2381 static int copy_kcore_dir(struct perf_inject *inject)
2382 {
2383 	char *cmd;
2384 	int ret;
2385 
2386 	ret = asprintf(&cmd, "cp -r -n %s/kcore_dir* %s >/dev/null 2>&1",
2387 		       inject->input_name, inject->output.path);
2388 	if (ret < 0)
2389 		return ret;
2390 	pr_debug("%s\n", cmd);
2391 	ret = system(cmd);
2392 	free(cmd);
2393 	return ret;
2394 }
2395 
2396 static int guest_session__copy_kcore_dir(struct guest_session *gs)
2397 {
2398 	struct perf_inject *inject = container_of(gs, struct perf_inject, guest_session);
2399 	char *cmd;
2400 	int ret;
2401 
2402 	ret = asprintf(&cmd, "cp -r -n %s/kcore_dir %s/kcore_dir__%u >/dev/null 2>&1",
2403 		       gs->perf_data_file, inject->output.path, gs->machine_pid);
2404 	if (ret < 0)
2405 		return ret;
2406 	pr_debug("%s\n", cmd);
2407 	ret = system(cmd);
2408 	free(cmd);
2409 	return ret;
2410 }
2411 
2412 static int output_fd(struct perf_inject *inject)
2413 {
2414 	return inject->in_place_update ? -1 : perf_data__fd(&inject->output);
2415 }
2416 
2417 static int __cmd_inject(struct perf_inject *inject)
2418 {
2419 	int ret = -EINVAL;
2420 	struct guest_session *gs = &inject->guest_session;
2421 	struct perf_session *session = inject->session;
2422 	int fd = output_fd(inject);
2423 	u64 output_data_offset = perf_session__data_offset(session->evlist);
2424 	/*
2425 	 * Pipe input hasn't loaded the attributes and will handle them as
2426 	 * events. So that the attributes don't overlap the data, write the
2427 	 * attributes after the data.
2428 	 */
2429 	bool write_attrs_after_data = !inject->output.is_pipe && inject->session->data->is_pipe;
2430 
2431 	signal(SIGINT, sig_handler);
2432 
2433 	if (inject->build_id_style != BID_RWS__NONE || inject->sched_stat ||
2434 	    inject->itrace_synth_opts.set) {
2435 		inject->tool.mmap	  = perf_event__repipe_mmap;
2436 		inject->tool.mmap2	  = perf_event__repipe_mmap2;
2437 		inject->tool.fork	  = perf_event__repipe_fork;
2438 #ifdef HAVE_LIBTRACEEVENT
2439 		inject->tool.tracing_data = perf_event__repipe_tracing_data;
2440 #endif
2441 	}
2442 
2443 	if (inject->build_id_style == BID_RWS__INJECT_HEADER_LAZY ||
2444 	    inject->build_id_style == BID_RWS__MMAP2_BUILDID_LAZY) {
2445 		inject->tool.sample = perf_event__inject_buildid;
2446 	} else if (inject->sched_stat) {
2447 		struct evsel *evsel;
2448 
2449 		evlist__for_each_entry(session->evlist, evsel) {
2450 			const char *name = evsel__name(evsel);
2451 
2452 			if (!strcmp(name, "sched:sched_switch")) {
2453 				if (evsel__check_stype(evsel, PERF_SAMPLE_TID, "TID"))
2454 					return -EINVAL;
2455 
2456 				evsel->handler = perf_inject__sched_switch;
2457 			} else if (!strcmp(name, "sched:sched_process_exit"))
2458 				evsel->handler = perf_inject__sched_process_exit;
2459 #ifdef HAVE_LIBTRACEEVENT
2460 			else if (!strncmp(name, "sched:sched_stat_", 17))
2461 				evsel->handler = perf_inject__sched_stat;
2462 #endif
2463 		}
2464 	} else if (inject->itrace_synth_opts.vm_time_correlation) {
2465 		session->itrace_synth_opts = &inject->itrace_synth_opts;
2466 		memset(&inject->tool, 0, sizeof(inject->tool));
2467 		inject->tool.id_index	    = perf_event__process_id_index;
2468 		inject->tool.auxtrace_info  = perf_event__process_auxtrace_info;
2469 		inject->tool.auxtrace	    = perf_event__process_auxtrace;
2470 		inject->tool.auxtrace_error = perf_event__process_auxtrace_error;
2471 		inject->tool.ordered_events = true;
2472 		inject->tool.ordering_requires_timestamps = true;
2473 	} else if (inject->itrace_synth_opts.set) {
2474 		session->itrace_synth_opts = &inject->itrace_synth_opts;
2475 		inject->itrace_synth_opts.inject = true;
2476 		inject->tool.comm	    = perf_event__repipe_comm;
2477 		inject->tool.namespaces	    = perf_event__repipe_namespaces;
2478 		inject->tool.exit	    = perf_event__repipe_exit;
2479 		inject->tool.id_index	    = perf_event__process_id_index;
2480 		inject->tool.auxtrace_info  = perf_event__process_auxtrace_info;
2481 		inject->tool.auxtrace	    = perf_event__process_auxtrace;
2482 		inject->tool.aux	    = perf_event__drop_aux;
2483 		inject->tool.itrace_start   = perf_event__drop_aux;
2484 		inject->tool.aux_output_hw_id = perf_event__drop_aux;
2485 		inject->tool.ordered_events = true;
2486 		inject->tool.ordering_requires_timestamps = true;
2487 		/* Allow space in the header for new attributes */
2488 		output_data_offset = roundup(8192 + session->header.data_offset, 4096);
2489 		if (inject->strip)
2490 			strip_init(inject);
2491 	} else if (gs->perf_data_file) {
2492 		char *name = gs->perf_data_file;
2493 
2494 		/*
2495 		 * Not strictly necessary, but keep these events in order wrt
2496 		 * guest events.
2497 		 */
2498 		inject->tool.mmap		= host__repipe;
2499 		inject->tool.mmap2		= host__repipe;
2500 		inject->tool.comm		= host__repipe;
2501 		inject->tool.fork		= host__repipe;
2502 		inject->tool.exit		= host__repipe;
2503 		inject->tool.lost		= host__repipe;
2504 		inject->tool.context_switch	= host__repipe;
2505 		inject->tool.ksymbol		= host__repipe;
2506 		inject->tool.text_poke		= host__repipe;
2507 		/*
2508 		 * Once the host session has initialized, set up sample ID
2509 		 * mapping and feed in guest attrs, build IDs and initial
2510 		 * events.
2511 		 */
2512 		inject->tool.finished_init	= host__finished_init;
2513 		/* Obey finished round ordering */
2514 		inject->tool.finished_round	= host__finished_round;
2515 		/* Keep track of which CPU a VCPU is runnng on */
2516 		inject->tool.context_switch	= host__context_switch;
2517 		/*
2518 		 * Must order events to be able to obey finished round
2519 		 * ordering.
2520 		 */
2521 		inject->tool.ordered_events	= true;
2522 		inject->tool.ordering_requires_timestamps = true;
2523 		/* Set up a separate session to process guest perf.data file */
2524 		ret = guest_session__start(gs, name, session->data->force);
2525 		if (ret) {
2526 			pr_err("Failed to process %s, error %d\n", name, ret);
2527 			return ret;
2528 		}
2529 		/* Allow space in the header for guest attributes */
2530 		output_data_offset += gs->session->header.data_offset;
2531 		output_data_offset = roundup(output_data_offset, 4096);
2532 	} else if (inject->convert_callchain) {
2533 		inject->tool.sample	= perf_event__convert_sample_callchain;
2534 		inject->tool.fork	= perf_event__repipe_fork;
2535 		inject->tool.comm	= perf_event__repipe_comm;
2536 		inject->tool.exit	= perf_event__repipe_exit;
2537 		inject->tool.mmap	= perf_event__repipe_mmap;
2538 		inject->tool.mmap2	= perf_event__repipe_mmap2;
2539 		inject->tool.ordered_events = true;
2540 		inject->tool.ordering_requires_timestamps = true;
2541 	}
2542 
2543 	if (!inject->itrace_synth_opts.set)
2544 		auxtrace_index__free(&session->auxtrace_index);
2545 
2546 	if (!inject->output.is_pipe && !inject->in_place_update)
2547 		lseek(fd, output_data_offset, SEEK_SET);
2548 
2549 	ret = perf_session__process_events(session);
2550 	if (ret)
2551 		return ret;
2552 
2553 	if (gs->session) {
2554 		/*
2555 		 * Remaining guest events have later timestamps. Flush them
2556 		 * out to file.
2557 		 */
2558 		ret = guest_session__flush_events(gs);
2559 		if (ret) {
2560 			pr_err("Failed to flush guest events\n");
2561 			return ret;
2562 		}
2563 	}
2564 
2565 	if (!inject->output.is_pipe && !inject->in_place_update) {
2566 		struct inject_fc inj_fc = {
2567 			.fc.copy = feat_copy_cb,
2568 			.inject = inject,
2569 		};
2570 
2571 		if (inject->build_id_style == BID_RWS__INJECT_HEADER_LAZY ||
2572 		    inject->build_id_style == BID_RWS__INJECT_HEADER_ALL)
2573 			perf_header__set_feat(&session->header, HEADER_BUILD_ID);
2574 		/*
2575 		 * Keep all buildids when there is unprocessed AUX data because
2576 		 * it is not known which ones the AUX trace hits.
2577 		 */
2578 		if (perf_header__has_feat(&session->header, HEADER_BUILD_ID) &&
2579 		    inject->have_auxtrace && !inject->itrace_synth_opts.set)
2580 			perf_session__dsos_hit_all(session);
2581 		/*
2582 		 * The AUX areas have been removed and replaced with
2583 		 * synthesized hardware events, so clear the feature flag.
2584 		 */
2585 		if (inject->itrace_synth_opts.set) {
2586 			struct evsel *evsel;
2587 
2588 			perf_header__clear_feat(&session->header,
2589 						HEADER_AUXTRACE);
2590 
2591 			evlist__for_each_entry(session->evlist, evsel) {
2592 				evsel->core.attr.sample_type &= ~PERF_SAMPLE_AUX;
2593 			}
2594 
2595 			if (inject->itrace_synth_opts.add_last_branch) {
2596 				perf_header__set_feat(&session->header,
2597 						      HEADER_BRANCH_STACK);
2598 
2599 				evlist__for_each_entry(session->evlist, evsel) {
2600 					evsel->core.attr.sample_type |= PERF_SAMPLE_BRANCH_STACK;
2601 					if (evsel->core.attr.size < PERF_ATTR_SIZE_VER2)
2602 						evsel->core.attr.size = PERF_ATTR_SIZE_VER2;
2603 					evsel->core.attr.branch_sample_type |=
2604 						PERF_SAMPLE_BRANCH_HW_INDEX;
2605 				}
2606 			}
2607 		}
2608 
2609 		/*
2610 		 * The converted data file won't have stack and registers.
2611 		 * Update the perf_event_attr to remove them before writing.
2612 		 */
2613 		if (inject->convert_callchain) {
2614 			struct evsel *evsel;
2615 
2616 			evlist__for_each_entry(session->evlist, evsel) {
2617 				evsel__reset_sample_bit(evsel, REGS_USER);
2618 				evsel__reset_sample_bit(evsel, STACK_USER);
2619 				evsel->core.attr.sample_regs_user = 0;
2620 				evsel->core.attr.sample_stack_user = 0;
2621 				evsel->core.attr.exclude_callchain_user = 0;
2622 			}
2623 		}
2624 
2625 		if (inject->aslr)
2626 			aslr_tool__strip_evlist(inject->session->tool, session->evlist);
2627 
2628 		session->header.data_offset = output_data_offset;
2629 		session->header.data_size = inject->bytes_written;
2630 		perf_session__inject_header(session, session->evlist, fd, &inj_fc.fc,
2631 					    write_attrs_after_data);
2632 
2633 		if (inject->copy_kcore_dir) {
2634 			ret = copy_kcore_dir(inject);
2635 			if (ret) {
2636 				pr_err("Failed to copy kcore\n");
2637 				return ret;
2638 			}
2639 		}
2640 		if (gs->copy_kcore_dir) {
2641 			ret = guest_session__copy_kcore_dir(gs);
2642 			if (ret) {
2643 				pr_err("Failed to copy guest kcore\n");
2644 				return ret;
2645 			}
2646 		}
2647 	}
2648 
2649 	return ret;
2650 }
2651 
2652 static bool evsel__has_dwarf_callchain(struct evsel *evsel)
2653 {
2654 	struct perf_event_attr *attr = &evsel->core.attr;
2655 	const u64 dwarf_callchain_flags =
2656 		PERF_SAMPLE_STACK_USER | PERF_SAMPLE_REGS_USER | PERF_SAMPLE_CALLCHAIN;
2657 
2658 	if (!attr->exclude_callchain_user)
2659 		return false;
2660 
2661 	return (attr->sample_type & dwarf_callchain_flags) == dwarf_callchain_flags;
2662 }
2663 
2664 int cmd_inject(int argc, const char **argv)
2665 {
2666 	struct perf_inject inject = {
2667 		.input_name  = "-",
2668 		.samples = LIST_HEAD_INIT(inject.samples),
2669 		.output = {
2670 			.path = "-",
2671 			.mode = PERF_DATA_MODE_WRITE,
2672 			.file.use_stdio = true,
2673 		},
2674 	};
2675 	struct perf_data data = {
2676 		.mode = PERF_DATA_MODE_READ,
2677 		.file.use_stdio = true,
2678 	};
2679 	int ret;
2680 	const char *known_build_ids = NULL;
2681 	bool build_ids = false;
2682 	bool build_id_all = false;
2683 	bool mmap2_build_ids = false;
2684 	bool mmap2_build_id_all = false;
2685 
2686 	struct option options[] = {
2687 		OPT_BOOLEAN('b', "build-ids", &build_ids,
2688 			    "Inject build-ids into the output stream"),
2689 		OPT_BOOLEAN(0, "buildid-all", &build_id_all,
2690 			    "Inject build-ids of all DSOs into the output stream"),
2691 		OPT_BOOLEAN('B', "mmap2-buildids", &mmap2_build_ids,
2692 			    "Drop unused mmap events, make others mmap2 with build IDs"),
2693 		OPT_BOOLEAN(0, "mmap2-buildid-all", &mmap2_build_id_all,
2694 			    "Rewrite all mmap events as mmap2 events with build IDs"),
2695 		OPT_STRING(0, "known-build-ids", &known_build_ids,
2696 			   "buildid path [,buildid path...]",
2697 			   "build-ids to use for given paths"),
2698 		OPT_STRING('i', "input", &inject.input_name, "file",
2699 			   "input file name"),
2700 		OPT_STRING('o', "output", &inject.output.path, "file",
2701 			   "output file name"),
2702 		OPT_BOOLEAN('s', "sched-stat", &inject.sched_stat,
2703 			    "Merge sched-stat and sched-switch for getting events "
2704 			    "where and how long tasks slept"),
2705 #ifdef HAVE_JITDUMP
2706 		OPT_BOOLEAN('j', "jit", &inject.jit_mode, "merge jitdump files into perf.data file"),
2707 #endif
2708 		OPT_INCR('v', "verbose", &verbose,
2709 			 "be more verbose (show build ids, etc)"),
2710 		OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
2711 			   "file", "vmlinux pathname"),
2712 		OPT_BOOLEAN(0, "ignore-vmlinux", &symbol_conf.ignore_vmlinux,
2713 			    "don't load vmlinux even if found"),
2714 		OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name, "file",
2715 			   "kallsyms pathname"),
2716 		OPT_BOOLEAN('f', "force", &data.force, "don't complain, do it"),
2717 		OPT_CALLBACK_OPTARG(0, "itrace", &inject.itrace_synth_opts,
2718 				    NULL, "opts", "Instruction Tracing options\n"
2719 				    ITRACE_HELP,
2720 				    itrace_parse_synth_opts),
2721 		OPT_BOOLEAN(0, "strip", &inject.strip,
2722 			    "strip non-synthesized events (use with --itrace)"),
2723 		OPT_CALLBACK_OPTARG(0, "vm-time-correlation", &inject, NULL, "opts",
2724 				    "correlate time between VM guests and the host",
2725 				    parse_vm_time_correlation),
2726 		OPT_CALLBACK_OPTARG(0, "guest-data", &inject, NULL, "opts",
2727 				    "inject events from a guest perf.data file",
2728 				    parse_guest_data),
2729 		OPT_STRING(0, "guestmount", &symbol_conf.guestmount, "directory",
2730 			   "guest mount directory under which every guest os"
2731 			   " instance has a subdir"),
2732 		OPT_CALLBACK(0, "unwind-style", NULL, "unwind style",
2733 			     "unwind styles (libdw,libunwind)",
2734 			     unwind__option),
2735 		OPT_BOOLEAN(0, "convert-callchain", &inject.convert_callchain,
2736 			    "Generate callchains using DWARF and drop register/stack data"),
2737 		OPT_BOOLEAN(0, "aslr", &inject.aslr,
2738 			    "Remap virtual memory addresses similar to ASLR"),
2739 		OPT_END()
2740 	};
2741 	const char * const inject_usage[] = {
2742 		"perf inject [<options>]",
2743 		NULL
2744 	};
2745 	bool ordered_events;
2746 	struct perf_tool *tool = &inject.tool;
2747 
2748 	if (!inject.itrace_synth_opts.set) {
2749 		/* Disable eager loading of kernel symbols that adds overhead to perf inject. */
2750 		symbol_conf.lazy_load_kernel_maps = true;
2751 	}
2752 
2753 #ifndef HAVE_JITDUMP
2754 	set_option_nobuild(options, 'j', "jit", "NO_LIBELF=1", true);
2755 #endif
2756 #ifndef HAVE_LIBDW_SUPPORT
2757 	set_option_nobuild(options, 0, "convert-callchain", "NO_LIBDW=1", true);
2758 #endif
2759 	argc = parse_options(argc, argv, options, inject_usage, 0);
2760 
2761 	/*
2762 	 * Any (unrecognized) arguments left?
2763 	 */
2764 	if (argc)
2765 		usage_with_options(inject_usage, options);
2766 
2767 	if (inject.aslr && inject.convert_callchain) {
2768 		pr_err("Error: --aslr and --convert-callchain are mutually exclusive features.\n");
2769 		return -EINVAL;
2770 	}
2771 
2772 	if (inject.strip && !inject.itrace_synth_opts.set) {
2773 		pr_err("--strip option requires --itrace option\n");
2774 		return -1;
2775 	}
2776 
2777 	if (symbol__validate_sym_arguments())
2778 		return -1;
2779 
2780 	if (inject.in_place_update) {
2781 		if (!strcmp(inject.input_name, "-")) {
2782 			pr_err("Input file name required for in-place updating\n");
2783 			return -1;
2784 		}
2785 		if (strcmp(inject.output.path, "-")) {
2786 			pr_err("Output file name must not be specified for in-place updating\n");
2787 			return -1;
2788 		}
2789 		if (!data.force && !inject.in_place_update_dry_run) {
2790 			pr_err("The input file would be updated in place, "
2791 				"the --force option is required.\n");
2792 			return -1;
2793 		}
2794 		if (!inject.in_place_update_dry_run)
2795 			data.in_place_update = true;
2796 	} else {
2797 		if (strcmp(inject.output.path, "-") && !inject.strip &&
2798 		    has_kcore_dir(inject.input_name)) {
2799 			inject.output.is_dir = true;
2800 			inject.copy_kcore_dir = true;
2801 		}
2802 		if (perf_data__open(&inject.output)) {
2803 			perror("failed to create output file");
2804 			return -1;
2805 		}
2806 	}
2807 	if (mmap2_build_ids)
2808 		inject.build_id_style = BID_RWS__MMAP2_BUILDID_LAZY;
2809 	if (mmap2_build_id_all)
2810 		inject.build_id_style = BID_RWS__MMAP2_BUILDID_ALL;
2811 	if (build_ids)
2812 		inject.build_id_style = BID_RWS__INJECT_HEADER_LAZY;
2813 	if (build_id_all)
2814 		inject.build_id_style = BID_RWS__INJECT_HEADER_ALL;
2815 
2816 	data.path = inject.input_name;
2817 
2818 	ordered_events = inject.jit_mode || inject.sched_stat ||
2819 		inject.build_id_style == BID_RWS__INJECT_HEADER_LAZY ||
2820 		inject.build_id_style == BID_RWS__MMAP2_BUILDID_LAZY;
2821 	perf_tool__init(&inject.tool, ordered_events);
2822 	inject.tool.sample		= perf_event__repipe_sample;
2823 	inject.tool.read		= perf_event__repipe_sample;
2824 	inject.tool.mmap		= perf_event__repipe;
2825 	inject.tool.mmap2		= perf_event__repipe;
2826 	inject.tool.comm		= perf_event__repipe;
2827 	inject.tool.namespaces		= perf_event__repipe;
2828 	inject.tool.cgroup		= perf_event__repipe;
2829 	inject.tool.fork		= perf_event__repipe;
2830 	inject.tool.exit		= perf_event__repipe;
2831 	inject.tool.lost		= perf_event__repipe;
2832 	inject.tool.lost_samples	= perf_event__repipe;
2833 	inject.tool.aux			= perf_event__repipe;
2834 	inject.tool.itrace_start	= perf_event__repipe;
2835 	inject.tool.aux_output_hw_id	= perf_event__repipe;
2836 	inject.tool.context_switch	= perf_event__repipe;
2837 	inject.tool.throttle		= perf_event__repipe;
2838 	inject.tool.unthrottle		= perf_event__repipe;
2839 	inject.tool.ksymbol		= perf_event__repipe;
2840 	inject.tool.bpf			= perf_event__repipe;
2841 	inject.tool.text_poke		= perf_event__repipe;
2842 	inject.tool.attr		= perf_event__repipe_attr;
2843 	inject.tool.event_update	= perf_event__repipe_event_update;
2844 	inject.tool.tracing_data	= perf_event__repipe_op2_synth;
2845 	inject.tool.finished_round	= perf_event__repipe_oe_synth;
2846 	inject.tool.build_id		= perf_event__repipe_op2_synth;
2847 	inject.tool.id_index		= perf_event__repipe_op2_synth;
2848 	inject.tool.auxtrace_info	= perf_event__repipe_op2_synth;
2849 	inject.tool.auxtrace_error	= perf_event__repipe_op2_synth;
2850 	inject.tool.time_conv		= perf_event__repipe_op2_synth;
2851 	inject.tool.thread_map		= perf_event__repipe_op2_synth;
2852 	inject.tool.cpu_map		= perf_event__repipe_op2_synth;
2853 	inject.tool.stat_config		= perf_event__repipe_op2_synth;
2854 	inject.tool.stat		= perf_event__repipe_op2_synth;
2855 	inject.tool.stat_round		= perf_event__repipe_op2_synth;
2856 	inject.tool.feature		= perf_event__repipe_op2_synth;
2857 	inject.tool.finished_init	= perf_event__repipe_op2_synth;
2858 	inject.tool.compressed		= perf_event__repipe_op4_synth;
2859 	inject.tool.auxtrace		= perf_event__repipe_auxtrace;
2860 	inject.tool.bpf_metadata	= perf_event__repipe_op2_synth;
2861 	inject.tool.schedstat_cpu	= perf_event__repipe_op2_synth;
2862 	inject.tool.schedstat_domain	= perf_event__repipe_op2_synth;
2863 	inject.tool.dont_split_sample_group = true;
2864 	inject.tool.merge_deferred_callchains = false;
2865 	if (inject.aslr) {
2866 		tool = aslr_tool__new(&inject.tool);
2867 		if (!tool) {
2868 			ret = -ENOMEM;
2869 			goto out_close_output;
2870 		}
2871 	}
2872 	inject.session = __perf_session__new(&data, tool,
2873 					     /*trace_event_repipe=*/inject.output.is_pipe,
2874 					     /*host_env=*/NULL);
2875 
2876 	if (IS_ERR(inject.session)) {
2877 		ret = PTR_ERR(inject.session);
2878 		if (inject.aslr)
2879 			aslr_tool__delete(tool);
2880 		goto out_close_output;
2881 	}
2882 
2883 	if (zstd_init(&(inject.session->zstd_data), 0) < 0)
2884 		pr_warning("Decompression initialization failed.\n");
2885 
2886 	if (inject.aslr) {
2887 		struct evsel *evsel;
2888 
2889 		evlist__for_each_entry(inject.session->evlist, evsel) {
2890 			ret = aslr_tool__cache_orig_attrs(tool, evsel);
2891 			if (ret) {
2892 				pr_err("Failed to cache original attributes: %d\n", ret);
2893 				goto out_delete;
2894 			}
2895 		}
2896 	}
2897 
2898 	/* Save original section info before feature bits change */
2899 	ret = save_section_info(&inject);
2900 	if (ret)
2901 		goto out_delete;
2902 
2903 	if (inject.output.is_pipe) {
2904 		ret = perf_header__write_pipe(perf_data__fd(&inject.output));
2905 		if (ret < 0) {
2906 			pr_err("Couldn't write a new pipe header.\n");
2907 			goto out_delete;
2908 		}
2909 
2910 		/*
2911 		 * If the input is already a pipe then the features and
2912 		 * attributes don't need synthesizing, they will be present in
2913 		 * the input.
2914 		 */
2915 		if (!data.is_pipe) {
2916 			if (inject.aslr)
2917 				aslr_tool__strip_evlist(tool, inject.session->evlist);
2918 
2919 			ret = perf_event__synthesize_for_pipe(&inject.tool,
2920 							      inject.session,
2921 							      &inject.output,
2922 							      perf_event__repipe);
2923 
2924 			if (inject.aslr)
2925 				aslr_tool__restore_evlist(tool, inject.session->evlist);
2926 
2927 			if (ret < 0)
2928 				goto out_delete;
2929 		}
2930 	}
2931 
2932 	if (inject.build_id_style == BID_RWS__INJECT_HEADER_LAZY ||
2933 	    inject.build_id_style == BID_RWS__MMAP2_BUILDID_LAZY) {
2934 		/*
2935 		 * to make sure the mmap records are ordered correctly
2936 		 * and so that the correct especially due to jitted code
2937 		 * mmaps. We cannot generate the buildid hit list and
2938 		 * inject the jit mmaps at the same time for now.
2939 		 */
2940 		inject.tool.ordering_requires_timestamps = true;
2941 	}
2942 	if (inject.build_id_style != BID_RWS__NONE && known_build_ids != NULL) {
2943 		inject.known_build_ids =
2944 			perf_inject__parse_known_build_ids(known_build_ids);
2945 
2946 		if (inject.known_build_ids == NULL) {
2947 			pr_err("Couldn't parse known build ids.\n");
2948 			goto out_delete;
2949 		}
2950 	}
2951 
2952 	if (inject.convert_callchain) {
2953 		struct evsel *evsel;
2954 
2955 		if (inject.output.is_pipe || inject.session->data->is_pipe) {
2956 			pr_err("--convert-callchain cannot work with pipe\n");
2957 			goto out_delete;
2958 		}
2959 
2960 		evlist__for_each_entry(inject.session->evlist, evsel) {
2961 			if (!evsel__has_dwarf_callchain(evsel) && !evsel__is_dummy_event(evsel)) {
2962 				pr_err("--convert-callchain requires DWARF call graph.\n");
2963 				goto out_delete;
2964 			}
2965 		}
2966 
2967 		inject.raw_callchain = calloc(PERF_MAX_STACK_DEPTH, sizeof(u64));
2968 		if (inject.raw_callchain == NULL) {
2969 			pr_err("callchain allocation failed\n");
2970 			goto out_delete;
2971 		}
2972 	}
2973 
2974 #ifdef HAVE_JITDUMP
2975 	if (inject.jit_mode) {
2976 		inject.tool.mmap2	   = perf_event__repipe_mmap2;
2977 		inject.tool.mmap	   = perf_event__repipe_mmap;
2978 		inject.tool.ordering_requires_timestamps = true;
2979 		/*
2980 		 * JIT MMAP injection injects all MMAP events in one go, so it
2981 		 * does not obey finished_round semantics.
2982 		 */
2983 		inject.tool.finished_round = perf_event__drop_oe;
2984 	}
2985 #endif
2986 	ret = symbol__init(perf_session__env(inject.session));
2987 	if (ret < 0)
2988 		goto out_delete;
2989 
2990 	ret = __cmd_inject(&inject);
2991 
2992 	guest_session__exit(&inject.guest_session);
2993 
2994 out_delete:
2995 	strlist__delete(inject.known_build_ids);
2996 	zstd_fini(&(inject.session->zstd_data));
2997 	perf_session__delete(inject.session);
2998 	if (inject.aslr)
2999 		aslr_tool__delete(tool);
3000 out_close_output:
3001 	if (!inject.in_place_update)
3002 		perf_data__close(&inject.output);
3003 	free(inject.itrace_synth_opts.vm_tm_corr_args);
3004 	free(inject.event_copy);
3005 	free(inject.guest_session.ev.event_buf);
3006 	free(inject.raw_callchain);
3007 	return ret;
3008 }
3009