1 // SPDX-License-Identifier: GPL-2.0-only
2 
3 #include "util/cgroup.h"
4 #include "util/data.h"
5 #include "util/debug.h"
6 #include "util/dso.h"
7 #include "util/event.h"
8 #include "util/evlist.h"
9 #include "util/machine.h"
10 #include "util/map.h"
11 #include "util/map_symbol.h"
12 #include "util/branch.h"
13 #include "util/memswap.h"
14 #include "util/namespaces.h"
15 #include "util/session.h"
16 #include "util/stat.h"
17 #include "util/symbol.h"
18 #include "util/synthetic-events.h"
19 #include "util/target.h"
20 #include "util/time-utils.h"
21 #include <linux/bitops.h>
22 #include <linux/kernel.h>
23 #include <linux/string.h>
24 #include <linux/zalloc.h>
25 #include <linux/perf_event.h>
26 #include <asm/bug.h>
27 #include <perf/evsel.h>
28 #include <perf/cpumap.h>
29 #include <internal/lib.h> // page_size
30 #include <internal/threadmap.h>
31 #include <perf/threadmap.h>
32 #include <symbol/kallsyms.h>
33 #include <dirent.h>
34 #include <errno.h>
35 #include <inttypes.h>
36 #include <stdio.h>
37 #include <string.h>
38 #include <uapi/linux/mman.h> /* To get things like MAP_HUGETLB even on older libc headers */
39 #include <api/fs/fs.h>
40 #include <api/io.h>
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 #include <fcntl.h>
44 #include <unistd.h>
45 
46 #define DEFAULT_PROC_MAP_PARSE_TIMEOUT 500
47 
48 unsigned int proc_map_timeout = DEFAULT_PROC_MAP_PARSE_TIMEOUT;
49 
50 int perf_tool__process_synth_event(struct perf_tool *tool,
51 				   union perf_event *event,
52 				   struct machine *machine,
53 				   perf_event__handler_t process)
54 {
55 	struct perf_sample synth_sample = {
56 		.pid	   = -1,
57 		.tid	   = -1,
58 		.time	   = -1,
59 		.stream_id = -1,
60 		.cpu	   = -1,
61 		.period	   = 1,
62 		.cpumode   = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK,
63 	};
64 
65 	return process(tool, event, &synth_sample, machine);
66 };
67 
68 /*
69  * Assumes that the first 4095 bytes of /proc/pid/stat contains
70  * the comm, tgid and ppid.
71  */
72 static int perf_event__get_comm_ids(pid_t pid, pid_t tid, char *comm, size_t len,
73 				    pid_t *tgid, pid_t *ppid, bool *kernel)
74 {
75 	char bf[4096];
76 	int fd;
77 	size_t size = 0;
78 	ssize_t n;
79 	char *name, *tgids, *ppids, *vmpeak, *threads;
80 
81 	*tgid = -1;
82 	*ppid = -1;
83 
84 	if (pid)
85 		snprintf(bf, sizeof(bf), "/proc/%d/task/%d/status", pid, tid);
86 	else
87 		snprintf(bf, sizeof(bf), "/proc/%d/status", tid);
88 
89 	fd = open(bf, O_RDONLY);
90 	if (fd < 0) {
91 		pr_debug("couldn't open %s\n", bf);
92 		return -1;
93 	}
94 
95 	n = read(fd, bf, sizeof(bf) - 1);
96 	close(fd);
97 	if (n <= 0) {
98 		pr_warning("Couldn't get COMM, tigd and ppid for pid %d\n",
99 			   tid);
100 		return -1;
101 	}
102 	bf[n] = '\0';
103 
104 	name = strstr(bf, "Name:");
105 	tgids = strstr(name ?: bf, "Tgid:");
106 	ppids = strstr(tgids ?: bf, "PPid:");
107 	vmpeak = strstr(ppids ?: bf, "VmPeak:");
108 
109 	if (vmpeak)
110 		threads = NULL;
111 	else
112 		threads = strstr(ppids ?: bf, "Threads:");
113 
114 	if (name) {
115 		char *nl;
116 
117 		name = skip_spaces(name + 5);  /* strlen("Name:") */
118 		nl = strchr(name, '\n');
119 		if (nl)
120 			*nl = '\0';
121 
122 		size = strlen(name);
123 		if (size >= len)
124 			size = len - 1;
125 		memcpy(comm, name, size);
126 		comm[size] = '\0';
127 	} else {
128 		pr_debug("Name: string not found for pid %d\n", tid);
129 	}
130 
131 	if (tgids) {
132 		tgids += 5;  /* strlen("Tgid:") */
133 		*tgid = atoi(tgids);
134 	} else {
135 		pr_debug("Tgid: string not found for pid %d\n", tid);
136 	}
137 
138 	if (ppids) {
139 		ppids += 5;  /* strlen("PPid:") */
140 		*ppid = atoi(ppids);
141 	} else {
142 		pr_debug("PPid: string not found for pid %d\n", tid);
143 	}
144 
145 	if (!vmpeak && threads)
146 		*kernel = true;
147 	else
148 		*kernel = false;
149 
150 	return 0;
151 }
152 
153 static int perf_event__prepare_comm(union perf_event *event, pid_t pid, pid_t tid,
154 				    struct machine *machine,
155 				    pid_t *tgid, pid_t *ppid, bool *kernel)
156 {
157 	size_t size;
158 
159 	*ppid = -1;
160 
161 	memset(&event->comm, 0, sizeof(event->comm));
162 
163 	if (machine__is_host(machine)) {
164 		if (perf_event__get_comm_ids(pid, tid, event->comm.comm,
165 					     sizeof(event->comm.comm),
166 					     tgid, ppid, kernel) != 0) {
167 			return -1;
168 		}
169 	} else {
170 		*tgid = machine->pid;
171 	}
172 
173 	if (*tgid < 0)
174 		return -1;
175 
176 	event->comm.pid = *tgid;
177 	event->comm.header.type = PERF_RECORD_COMM;
178 
179 	size = strlen(event->comm.comm) + 1;
180 	size = PERF_ALIGN(size, sizeof(u64));
181 	memset(event->comm.comm + size, 0, machine->id_hdr_size);
182 	event->comm.header.size = (sizeof(event->comm) -
183 				(sizeof(event->comm.comm) - size) +
184 				machine->id_hdr_size);
185 	event->comm.tid = tid;
186 
187 	return 0;
188 }
189 
190 pid_t perf_event__synthesize_comm(struct perf_tool *tool,
191 					 union perf_event *event, pid_t pid,
192 					 perf_event__handler_t process,
193 					 struct machine *machine)
194 {
195 	pid_t tgid, ppid;
196 	bool kernel_thread;
197 
198 	if (perf_event__prepare_comm(event, 0, pid, machine, &tgid, &ppid,
199 				     &kernel_thread) != 0)
200 		return -1;
201 
202 	if (perf_tool__process_synth_event(tool, event, machine, process) != 0)
203 		return -1;
204 
205 	return tgid;
206 }
207 
208 static void perf_event__get_ns_link_info(pid_t pid, const char *ns,
209 					 struct perf_ns_link_info *ns_link_info)
210 {
211 	struct stat64 st;
212 	char proc_ns[128];
213 
214 	sprintf(proc_ns, "/proc/%u/ns/%s", pid, ns);
215 	if (stat64(proc_ns, &st) == 0) {
216 		ns_link_info->dev = st.st_dev;
217 		ns_link_info->ino = st.st_ino;
218 	}
219 }
220 
221 int perf_event__synthesize_namespaces(struct perf_tool *tool,
222 				      union perf_event *event,
223 				      pid_t pid, pid_t tgid,
224 				      perf_event__handler_t process,
225 				      struct machine *machine)
226 {
227 	u32 idx;
228 	struct perf_ns_link_info *ns_link_info;
229 
230 	if (!tool || !tool->namespace_events)
231 		return 0;
232 
233 	memset(&event->namespaces, 0, (sizeof(event->namespaces) +
234 	       (NR_NAMESPACES * sizeof(struct perf_ns_link_info)) +
235 	       machine->id_hdr_size));
236 
237 	event->namespaces.pid = tgid;
238 	event->namespaces.tid = pid;
239 
240 	event->namespaces.nr_namespaces = NR_NAMESPACES;
241 
242 	ns_link_info = event->namespaces.link_info;
243 
244 	for (idx = 0; idx < event->namespaces.nr_namespaces; idx++)
245 		perf_event__get_ns_link_info(pid, perf_ns__name(idx),
246 					     &ns_link_info[idx]);
247 
248 	event->namespaces.header.type = PERF_RECORD_NAMESPACES;
249 
250 	event->namespaces.header.size = (sizeof(event->namespaces) +
251 			(NR_NAMESPACES * sizeof(struct perf_ns_link_info)) +
252 			machine->id_hdr_size);
253 
254 	if (perf_tool__process_synth_event(tool, event, machine, process) != 0)
255 		return -1;
256 
257 	return 0;
258 }
259 
260 static int perf_event__synthesize_fork(struct perf_tool *tool,
261 				       union perf_event *event,
262 				       pid_t pid, pid_t tgid, pid_t ppid,
263 				       perf_event__handler_t process,
264 				       struct machine *machine)
265 {
266 	memset(&event->fork, 0, sizeof(event->fork) + machine->id_hdr_size);
267 
268 	/*
269 	 * for main thread set parent to ppid from status file. For other
270 	 * threads set parent pid to main thread. ie., assume main thread
271 	 * spawns all threads in a process
272 	*/
273 	if (tgid == pid) {
274 		event->fork.ppid = ppid;
275 		event->fork.ptid = ppid;
276 	} else {
277 		event->fork.ppid = tgid;
278 		event->fork.ptid = tgid;
279 	}
280 	event->fork.pid  = tgid;
281 	event->fork.tid  = pid;
282 	event->fork.header.type = PERF_RECORD_FORK;
283 	event->fork.header.misc = PERF_RECORD_MISC_FORK_EXEC;
284 
285 	event->fork.header.size = (sizeof(event->fork) + machine->id_hdr_size);
286 
287 	if (perf_tool__process_synth_event(tool, event, machine, process) != 0)
288 		return -1;
289 
290 	return 0;
291 }
292 
293 static bool read_proc_maps_line(struct io *io, __u64 *start, __u64 *end,
294 				u32 *prot, u32 *flags, __u64 *offset,
295 				u32 *maj, u32 *min,
296 				__u64 *inode,
297 				ssize_t pathname_size, char *pathname)
298 {
299 	__u64 temp;
300 	int ch;
301 	char *start_pathname = pathname;
302 
303 	if (io__get_hex(io, start) != '-')
304 		return false;
305 	if (io__get_hex(io, end) != ' ')
306 		return false;
307 
308 	/* map protection and flags bits */
309 	*prot = 0;
310 	ch = io__get_char(io);
311 	if (ch == 'r')
312 		*prot |= PROT_READ;
313 	else if (ch != '-')
314 		return false;
315 	ch = io__get_char(io);
316 	if (ch == 'w')
317 		*prot |= PROT_WRITE;
318 	else if (ch != '-')
319 		return false;
320 	ch = io__get_char(io);
321 	if (ch == 'x')
322 		*prot |= PROT_EXEC;
323 	else if (ch != '-')
324 		return false;
325 	ch = io__get_char(io);
326 	if (ch == 's')
327 		*flags = MAP_SHARED;
328 	else if (ch == 'p')
329 		*flags = MAP_PRIVATE;
330 	else
331 		return false;
332 	if (io__get_char(io) != ' ')
333 		return false;
334 
335 	if (io__get_hex(io, offset) != ' ')
336 		return false;
337 
338 	if (io__get_hex(io, &temp) != ':')
339 		return false;
340 	*maj = temp;
341 	if (io__get_hex(io, &temp) != ' ')
342 		return false;
343 	*min = temp;
344 
345 	ch = io__get_dec(io, inode);
346 	if (ch != ' ') {
347 		*pathname = '\0';
348 		return ch == '\n';
349 	}
350 	do {
351 		ch = io__get_char(io);
352 	} while (ch == ' ');
353 	while (true) {
354 		if (ch < 0)
355 			return false;
356 		if (ch == '\0' || ch == '\n' ||
357 		    (pathname + 1 - start_pathname) >= pathname_size) {
358 			*pathname = '\0';
359 			return true;
360 		}
361 		*pathname++ = ch;
362 		ch = io__get_char(io);
363 	}
364 }
365 
366 static void perf_record_mmap2__read_build_id(struct perf_record_mmap2 *event,
367 					     bool is_kernel)
368 {
369 	struct build_id bid;
370 	int rc;
371 
372 	if (is_kernel)
373 		rc = sysfs__read_build_id("/sys/kernel/notes", &bid);
374 	else
375 		rc = filename__read_build_id(event->filename, &bid) > 0 ? 0 : -1;
376 
377 	if (rc == 0) {
378 		memcpy(event->build_id, bid.data, sizeof(bid.data));
379 		event->build_id_size = (u8) bid.size;
380 		event->header.misc |= PERF_RECORD_MISC_MMAP_BUILD_ID;
381 		event->__reserved_1 = 0;
382 		event->__reserved_2 = 0;
383 	} else {
384 		if (event->filename[0] == '/') {
385 			pr_debug2("Failed to read build ID for %s\n",
386 				  event->filename);
387 		}
388 	}
389 }
390 
391 int perf_event__synthesize_mmap_events(struct perf_tool *tool,
392 				       union perf_event *event,
393 				       pid_t pid, pid_t tgid,
394 				       perf_event__handler_t process,
395 				       struct machine *machine,
396 				       bool mmap_data)
397 {
398 	unsigned long long t;
399 	char bf[BUFSIZ];
400 	struct io io;
401 	bool truncation = false;
402 	unsigned long long timeout = proc_map_timeout * 1000000ULL;
403 	int rc = 0;
404 	const char *hugetlbfs_mnt = hugetlbfs__mountpoint();
405 	int hugetlbfs_mnt_len = hugetlbfs_mnt ? strlen(hugetlbfs_mnt) : 0;
406 
407 	if (machine__is_default_guest(machine))
408 		return 0;
409 
410 	snprintf(bf, sizeof(bf), "%s/proc/%d/task/%d/maps",
411 		machine->root_dir, pid, pid);
412 
413 	io.fd = open(bf, O_RDONLY, 0);
414 	if (io.fd < 0) {
415 		/*
416 		 * We raced with a task exiting - just return:
417 		 */
418 		pr_debug("couldn't open %s\n", bf);
419 		return -1;
420 	}
421 	io__init(&io, io.fd, bf, sizeof(bf));
422 
423 	event->header.type = PERF_RECORD_MMAP2;
424 	t = rdclock();
425 
426 	while (!io.eof) {
427 		static const char anonstr[] = "//anon";
428 		size_t size, aligned_size;
429 
430 		/* ensure null termination since stack will be reused. */
431 		event->mmap2.filename[0] = '\0';
432 
433 		/* 00400000-0040c000 r-xp 00000000 fd:01 41038  /bin/cat */
434 		if (!read_proc_maps_line(&io,
435 					&event->mmap2.start,
436 					&event->mmap2.len,
437 					&event->mmap2.prot,
438 					&event->mmap2.flags,
439 					&event->mmap2.pgoff,
440 					&event->mmap2.maj,
441 					&event->mmap2.min,
442 					&event->mmap2.ino,
443 					sizeof(event->mmap2.filename),
444 					event->mmap2.filename))
445 			continue;
446 
447 		if ((rdclock() - t) > timeout) {
448 			pr_warning("Reading %s/proc/%d/task/%d/maps time out. "
449 				   "You may want to increase "
450 				   "the time limit by --proc-map-timeout\n",
451 				   machine->root_dir, pid, pid);
452 			truncation = true;
453 			goto out;
454 		}
455 
456 		event->mmap2.ino_generation = 0;
457 
458 		/*
459 		 * Just like the kernel, see __perf_event_mmap in kernel/perf_event.c
460 		 */
461 		if (machine__is_host(machine))
462 			event->header.misc = PERF_RECORD_MISC_USER;
463 		else
464 			event->header.misc = PERF_RECORD_MISC_GUEST_USER;
465 
466 		if ((event->mmap2.prot & PROT_EXEC) == 0) {
467 			if (!mmap_data || (event->mmap2.prot & PROT_READ) == 0)
468 				continue;
469 
470 			event->header.misc |= PERF_RECORD_MISC_MMAP_DATA;
471 		}
472 
473 out:
474 		if (truncation)
475 			event->header.misc |= PERF_RECORD_MISC_PROC_MAP_PARSE_TIMEOUT;
476 
477 		if (!strcmp(event->mmap2.filename, ""))
478 			strcpy(event->mmap2.filename, anonstr);
479 
480 		if (hugetlbfs_mnt_len &&
481 		    !strncmp(event->mmap2.filename, hugetlbfs_mnt,
482 			     hugetlbfs_mnt_len)) {
483 			strcpy(event->mmap2.filename, anonstr);
484 			event->mmap2.flags |= MAP_HUGETLB;
485 		}
486 
487 		size = strlen(event->mmap2.filename) + 1;
488 		aligned_size = PERF_ALIGN(size, sizeof(u64));
489 		event->mmap2.len -= event->mmap.start;
490 		event->mmap2.header.size = (sizeof(event->mmap2) -
491 					(sizeof(event->mmap2.filename) - aligned_size));
492 		memset(event->mmap2.filename + size, 0, machine->id_hdr_size +
493 			(aligned_size - size));
494 		event->mmap2.header.size += machine->id_hdr_size;
495 		event->mmap2.pid = tgid;
496 		event->mmap2.tid = pid;
497 
498 		if (symbol_conf.buildid_mmap2)
499 			perf_record_mmap2__read_build_id(&event->mmap2, false);
500 
501 		if (perf_tool__process_synth_event(tool, event, machine, process) != 0) {
502 			rc = -1;
503 			break;
504 		}
505 
506 		if (truncation)
507 			break;
508 	}
509 
510 	close(io.fd);
511 	return rc;
512 }
513 
514 #ifdef HAVE_FILE_HANDLE
515 static int perf_event__synthesize_cgroup(struct perf_tool *tool,
516 					 union perf_event *event,
517 					 char *path, size_t mount_len,
518 					 perf_event__handler_t process,
519 					 struct machine *machine)
520 {
521 	size_t event_size = sizeof(event->cgroup) - sizeof(event->cgroup.path);
522 	size_t path_len = strlen(path) - mount_len + 1;
523 	struct {
524 		struct file_handle fh;
525 		uint64_t cgroup_id;
526 	} handle;
527 	int mount_id;
528 
529 	while (path_len % sizeof(u64))
530 		path[mount_len + path_len++] = '\0';
531 
532 	memset(&event->cgroup, 0, event_size);
533 
534 	event->cgroup.header.type = PERF_RECORD_CGROUP;
535 	event->cgroup.header.size = event_size + path_len + machine->id_hdr_size;
536 
537 	handle.fh.handle_bytes = sizeof(handle.cgroup_id);
538 	if (name_to_handle_at(AT_FDCWD, path, &handle.fh, &mount_id, 0) < 0) {
539 		pr_debug("stat failed: %s\n", path);
540 		return -1;
541 	}
542 
543 	event->cgroup.id = handle.cgroup_id;
544 	strncpy(event->cgroup.path, path + mount_len, path_len);
545 	memset(event->cgroup.path + path_len, 0, machine->id_hdr_size);
546 
547 	if (perf_tool__process_synth_event(tool, event, machine, process) < 0) {
548 		pr_debug("process synth event failed\n");
549 		return -1;
550 	}
551 
552 	return 0;
553 }
554 
555 static int perf_event__walk_cgroup_tree(struct perf_tool *tool,
556 					union perf_event *event,
557 					char *path, size_t mount_len,
558 					perf_event__handler_t process,
559 					struct machine *machine)
560 {
561 	size_t pos = strlen(path);
562 	DIR *d;
563 	struct dirent *dent;
564 	int ret = 0;
565 
566 	if (perf_event__synthesize_cgroup(tool, event, path, mount_len,
567 					  process, machine) < 0)
568 		return -1;
569 
570 	d = opendir(path);
571 	if (d == NULL) {
572 		pr_debug("failed to open directory: %s\n", path);
573 		return -1;
574 	}
575 
576 	while ((dent = readdir(d)) != NULL) {
577 		if (dent->d_type != DT_DIR)
578 			continue;
579 		if (!strcmp(dent->d_name, ".") ||
580 		    !strcmp(dent->d_name, ".."))
581 			continue;
582 
583 		/* any sane path should be less than PATH_MAX */
584 		if (strlen(path) + strlen(dent->d_name) + 1 >= PATH_MAX)
585 			continue;
586 
587 		if (path[pos - 1] != '/')
588 			strcat(path, "/");
589 		strcat(path, dent->d_name);
590 
591 		ret = perf_event__walk_cgroup_tree(tool, event, path,
592 						   mount_len, process, machine);
593 		if (ret < 0)
594 			break;
595 
596 		path[pos] = '\0';
597 	}
598 
599 	closedir(d);
600 	return ret;
601 }
602 
603 int perf_event__synthesize_cgroups(struct perf_tool *tool,
604 				   perf_event__handler_t process,
605 				   struct machine *machine)
606 {
607 	union perf_event event;
608 	char cgrp_root[PATH_MAX];
609 	size_t mount_len;  /* length of mount point in the path */
610 
611 	if (!tool || !tool->cgroup_events)
612 		return 0;
613 
614 	if (cgroupfs_find_mountpoint(cgrp_root, PATH_MAX, "perf_event") < 0) {
615 		pr_debug("cannot find cgroup mount point\n");
616 		return -1;
617 	}
618 
619 	mount_len = strlen(cgrp_root);
620 	/* make sure the path starts with a slash (after mount point) */
621 	strcat(cgrp_root, "/");
622 
623 	if (perf_event__walk_cgroup_tree(tool, &event, cgrp_root, mount_len,
624 					 process, machine) < 0)
625 		return -1;
626 
627 	return 0;
628 }
629 #else
630 int perf_event__synthesize_cgroups(struct perf_tool *tool __maybe_unused,
631 				   perf_event__handler_t process __maybe_unused,
632 				   struct machine *machine __maybe_unused)
633 {
634 	return -1;
635 }
636 #endif
637 
638 int perf_event__synthesize_modules(struct perf_tool *tool, perf_event__handler_t process,
639 				   struct machine *machine)
640 {
641 	int rc = 0;
642 	struct map *pos;
643 	struct maps *maps = machine__kernel_maps(machine);
644 	union perf_event *event;
645 	size_t size = symbol_conf.buildid_mmap2 ?
646 			sizeof(event->mmap2) : sizeof(event->mmap);
647 
648 	event = zalloc(size + machine->id_hdr_size);
649 	if (event == NULL) {
650 		pr_debug("Not enough memory synthesizing mmap event "
651 			 "for kernel modules\n");
652 		return -1;
653 	}
654 
655 	/*
656 	 * kernel uses 0 for user space maps, see kernel/perf_event.c
657 	 * __perf_event_mmap
658 	 */
659 	if (machine__is_host(machine))
660 		event->header.misc = PERF_RECORD_MISC_KERNEL;
661 	else
662 		event->header.misc = PERF_RECORD_MISC_GUEST_KERNEL;
663 
664 	maps__for_each_entry(maps, pos) {
665 		if (!__map__is_kmodule(pos))
666 			continue;
667 
668 		if (symbol_conf.buildid_mmap2) {
669 			size = PERF_ALIGN(pos->dso->long_name_len + 1, sizeof(u64));
670 			event->mmap2.header.type = PERF_RECORD_MMAP2;
671 			event->mmap2.header.size = (sizeof(event->mmap2) -
672 						(sizeof(event->mmap2.filename) - size));
673 			memset(event->mmap2.filename + size, 0, machine->id_hdr_size);
674 			event->mmap2.header.size += machine->id_hdr_size;
675 			event->mmap2.start = pos->start;
676 			event->mmap2.len   = pos->end - pos->start;
677 			event->mmap2.pid   = machine->pid;
678 
679 			memcpy(event->mmap2.filename, pos->dso->long_name,
680 			       pos->dso->long_name_len + 1);
681 
682 			perf_record_mmap2__read_build_id(&event->mmap2, false);
683 		} else {
684 			size = PERF_ALIGN(pos->dso->long_name_len + 1, sizeof(u64));
685 			event->mmap.header.type = PERF_RECORD_MMAP;
686 			event->mmap.header.size = (sizeof(event->mmap) -
687 						(sizeof(event->mmap.filename) - size));
688 			memset(event->mmap.filename + size, 0, machine->id_hdr_size);
689 			event->mmap.header.size += machine->id_hdr_size;
690 			event->mmap.start = pos->start;
691 			event->mmap.len   = pos->end - pos->start;
692 			event->mmap.pid   = machine->pid;
693 
694 			memcpy(event->mmap.filename, pos->dso->long_name,
695 			       pos->dso->long_name_len + 1);
696 		}
697 
698 		if (perf_tool__process_synth_event(tool, event, machine, process) != 0) {
699 			rc = -1;
700 			break;
701 		}
702 	}
703 
704 	free(event);
705 	return rc;
706 }
707 
708 static int filter_task(const struct dirent *dirent)
709 {
710 	return isdigit(dirent->d_name[0]);
711 }
712 
713 static int __event__synthesize_thread(union perf_event *comm_event,
714 				      union perf_event *mmap_event,
715 				      union perf_event *fork_event,
716 				      union perf_event *namespaces_event,
717 				      pid_t pid, int full, perf_event__handler_t process,
718 				      struct perf_tool *tool, struct machine *machine,
719 				      bool needs_mmap, bool mmap_data)
720 {
721 	char filename[PATH_MAX];
722 	struct dirent **dirent;
723 	pid_t tgid, ppid;
724 	int rc = 0;
725 	int i, n;
726 
727 	/* special case: only send one comm event using passed in pid */
728 	if (!full) {
729 		tgid = perf_event__synthesize_comm(tool, comm_event, pid,
730 						   process, machine);
731 
732 		if (tgid == -1)
733 			return -1;
734 
735 		if (perf_event__synthesize_namespaces(tool, namespaces_event, pid,
736 						      tgid, process, machine) < 0)
737 			return -1;
738 
739 		/*
740 		 * send mmap only for thread group leader
741 		 * see thread__init_maps()
742 		 */
743 		if (pid == tgid && needs_mmap &&
744 		    perf_event__synthesize_mmap_events(tool, mmap_event, pid, tgid,
745 						       process, machine, mmap_data))
746 			return -1;
747 
748 		return 0;
749 	}
750 
751 	if (machine__is_default_guest(machine))
752 		return 0;
753 
754 	snprintf(filename, sizeof(filename), "%s/proc/%d/task",
755 		 machine->root_dir, pid);
756 
757 	n = scandir(filename, &dirent, filter_task, NULL);
758 	if (n < 0)
759 		return n;
760 
761 	for (i = 0; i < n; i++) {
762 		char *end;
763 		pid_t _pid;
764 		bool kernel_thread = false;
765 
766 		_pid = strtol(dirent[i]->d_name, &end, 10);
767 		if (*end)
768 			continue;
769 
770 		/* some threads may exit just after scan, ignore it */
771 		if (perf_event__prepare_comm(comm_event, pid, _pid, machine,
772 					     &tgid, &ppid, &kernel_thread) != 0)
773 			continue;
774 
775 		rc = -1;
776 		if (perf_event__synthesize_fork(tool, fork_event, _pid, tgid,
777 						ppid, process, machine) < 0)
778 			break;
779 
780 		if (perf_event__synthesize_namespaces(tool, namespaces_event, _pid,
781 						      tgid, process, machine) < 0)
782 			break;
783 
784 		/*
785 		 * Send the prepared comm event
786 		 */
787 		if (perf_tool__process_synth_event(tool, comm_event, machine, process) != 0)
788 			break;
789 
790 		rc = 0;
791 		if (_pid == pid && !kernel_thread && needs_mmap) {
792 			/* process the parent's maps too */
793 			rc = perf_event__synthesize_mmap_events(tool, mmap_event, pid, tgid,
794 						process, machine, mmap_data);
795 			if (rc)
796 				break;
797 		}
798 	}
799 
800 	for (i = 0; i < n; i++)
801 		zfree(&dirent[i]);
802 	free(dirent);
803 
804 	return rc;
805 }
806 
807 int perf_event__synthesize_thread_map(struct perf_tool *tool,
808 				      struct perf_thread_map *threads,
809 				      perf_event__handler_t process,
810 				      struct machine *machine,
811 				      bool needs_mmap, bool mmap_data)
812 {
813 	union perf_event *comm_event, *mmap_event, *fork_event;
814 	union perf_event *namespaces_event;
815 	int err = -1, thread, j;
816 
817 	comm_event = malloc(sizeof(comm_event->comm) + machine->id_hdr_size);
818 	if (comm_event == NULL)
819 		goto out;
820 
821 	mmap_event = malloc(sizeof(mmap_event->mmap2) + machine->id_hdr_size);
822 	if (mmap_event == NULL)
823 		goto out_free_comm;
824 
825 	fork_event = malloc(sizeof(fork_event->fork) + machine->id_hdr_size);
826 	if (fork_event == NULL)
827 		goto out_free_mmap;
828 
829 	namespaces_event = malloc(sizeof(namespaces_event->namespaces) +
830 				  (NR_NAMESPACES * sizeof(struct perf_ns_link_info)) +
831 				  machine->id_hdr_size);
832 	if (namespaces_event == NULL)
833 		goto out_free_fork;
834 
835 	err = 0;
836 	for (thread = 0; thread < threads->nr; ++thread) {
837 		if (__event__synthesize_thread(comm_event, mmap_event,
838 					       fork_event, namespaces_event,
839 					       perf_thread_map__pid(threads, thread), 0,
840 					       process, tool, machine,
841 					       needs_mmap, mmap_data)) {
842 			err = -1;
843 			break;
844 		}
845 
846 		/*
847 		 * comm.pid is set to thread group id by
848 		 * perf_event__synthesize_comm
849 		 */
850 		if ((int) comm_event->comm.pid != perf_thread_map__pid(threads, thread)) {
851 			bool need_leader = true;
852 
853 			/* is thread group leader in thread_map? */
854 			for (j = 0; j < threads->nr; ++j) {
855 				if ((int) comm_event->comm.pid == perf_thread_map__pid(threads, j)) {
856 					need_leader = false;
857 					break;
858 				}
859 			}
860 
861 			/* if not, generate events for it */
862 			if (need_leader &&
863 			    __event__synthesize_thread(comm_event, mmap_event,
864 						       fork_event, namespaces_event,
865 						       comm_event->comm.pid, 0,
866 						       process, tool, machine,
867 						       needs_mmap, mmap_data)) {
868 				err = -1;
869 				break;
870 			}
871 		}
872 	}
873 	free(namespaces_event);
874 out_free_fork:
875 	free(fork_event);
876 out_free_mmap:
877 	free(mmap_event);
878 out_free_comm:
879 	free(comm_event);
880 out:
881 	return err;
882 }
883 
884 static int __perf_event__synthesize_threads(struct perf_tool *tool,
885 					    perf_event__handler_t process,
886 					    struct machine *machine,
887 					    bool needs_mmap,
888 					    bool mmap_data,
889 					    struct dirent **dirent,
890 					    int start,
891 					    int num)
892 {
893 	union perf_event *comm_event, *mmap_event, *fork_event;
894 	union perf_event *namespaces_event;
895 	int err = -1;
896 	char *end;
897 	pid_t pid;
898 	int i;
899 
900 	comm_event = malloc(sizeof(comm_event->comm) + machine->id_hdr_size);
901 	if (comm_event == NULL)
902 		goto out;
903 
904 	mmap_event = malloc(sizeof(mmap_event->mmap2) + machine->id_hdr_size);
905 	if (mmap_event == NULL)
906 		goto out_free_comm;
907 
908 	fork_event = malloc(sizeof(fork_event->fork) + machine->id_hdr_size);
909 	if (fork_event == NULL)
910 		goto out_free_mmap;
911 
912 	namespaces_event = malloc(sizeof(namespaces_event->namespaces) +
913 				  (NR_NAMESPACES * sizeof(struct perf_ns_link_info)) +
914 				  machine->id_hdr_size);
915 	if (namespaces_event == NULL)
916 		goto out_free_fork;
917 
918 	for (i = start; i < start + num; i++) {
919 		if (!isdigit(dirent[i]->d_name[0]))
920 			continue;
921 
922 		pid = (pid_t)strtol(dirent[i]->d_name, &end, 10);
923 		/* only interested in proper numerical dirents */
924 		if (*end)
925 			continue;
926 		/*
927 		 * We may race with exiting thread, so don't stop just because
928 		 * one thread couldn't be synthesized.
929 		 */
930 		__event__synthesize_thread(comm_event, mmap_event, fork_event,
931 					   namespaces_event, pid, 1, process,
932 					   tool, machine, needs_mmap, mmap_data);
933 	}
934 	err = 0;
935 
936 	free(namespaces_event);
937 out_free_fork:
938 	free(fork_event);
939 out_free_mmap:
940 	free(mmap_event);
941 out_free_comm:
942 	free(comm_event);
943 out:
944 	return err;
945 }
946 
947 struct synthesize_threads_arg {
948 	struct perf_tool *tool;
949 	perf_event__handler_t process;
950 	struct machine *machine;
951 	bool needs_mmap;
952 	bool mmap_data;
953 	struct dirent **dirent;
954 	int num;
955 	int start;
956 };
957 
958 static void *synthesize_threads_worker(void *arg)
959 {
960 	struct synthesize_threads_arg *args = arg;
961 
962 	__perf_event__synthesize_threads(args->tool, args->process,
963 					 args->machine,
964 					 args->needs_mmap, args->mmap_data,
965 					 args->dirent,
966 					 args->start, args->num);
967 	return NULL;
968 }
969 
970 int perf_event__synthesize_threads(struct perf_tool *tool,
971 				   perf_event__handler_t process,
972 				   struct machine *machine,
973 				   bool needs_mmap, bool mmap_data,
974 				   unsigned int nr_threads_synthesize)
975 {
976 	struct synthesize_threads_arg *args = NULL;
977 	pthread_t *synthesize_threads = NULL;
978 	char proc_path[PATH_MAX];
979 	struct dirent **dirent;
980 	int num_per_thread;
981 	int m, n, i, j;
982 	int thread_nr;
983 	int base = 0;
984 	int err = -1;
985 
986 
987 	if (machine__is_default_guest(machine))
988 		return 0;
989 
990 	snprintf(proc_path, sizeof(proc_path), "%s/proc", machine->root_dir);
991 	n = scandir(proc_path, &dirent, filter_task, NULL);
992 	if (n < 0)
993 		return err;
994 
995 	if (nr_threads_synthesize == UINT_MAX)
996 		thread_nr = sysconf(_SC_NPROCESSORS_ONLN);
997 	else
998 		thread_nr = nr_threads_synthesize;
999 
1000 	if (thread_nr <= 1) {
1001 		err = __perf_event__synthesize_threads(tool, process,
1002 						       machine,
1003 						       needs_mmap, mmap_data,
1004 						       dirent, base, n);
1005 		goto free_dirent;
1006 	}
1007 	if (thread_nr > n)
1008 		thread_nr = n;
1009 
1010 	synthesize_threads = calloc(sizeof(pthread_t), thread_nr);
1011 	if (synthesize_threads == NULL)
1012 		goto free_dirent;
1013 
1014 	args = calloc(sizeof(*args), thread_nr);
1015 	if (args == NULL)
1016 		goto free_threads;
1017 
1018 	num_per_thread = n / thread_nr;
1019 	m = n % thread_nr;
1020 	for (i = 0; i < thread_nr; i++) {
1021 		args[i].tool = tool;
1022 		args[i].process = process;
1023 		args[i].machine = machine;
1024 		args[i].needs_mmap = needs_mmap;
1025 		args[i].mmap_data = mmap_data;
1026 		args[i].dirent = dirent;
1027 	}
1028 	for (i = 0; i < m; i++) {
1029 		args[i].num = num_per_thread + 1;
1030 		args[i].start = i * args[i].num;
1031 	}
1032 	if (i != 0)
1033 		base = args[i-1].start + args[i-1].num;
1034 	for (j = i; j < thread_nr; j++) {
1035 		args[j].num = num_per_thread;
1036 		args[j].start = base + (j - i) * args[i].num;
1037 	}
1038 
1039 	for (i = 0; i < thread_nr; i++) {
1040 		if (pthread_create(&synthesize_threads[i], NULL,
1041 				   synthesize_threads_worker, &args[i]))
1042 			goto out_join;
1043 	}
1044 	err = 0;
1045 out_join:
1046 	for (i = 0; i < thread_nr; i++)
1047 		pthread_join(synthesize_threads[i], NULL);
1048 	free(args);
1049 free_threads:
1050 	free(synthesize_threads);
1051 free_dirent:
1052 	for (i = 0; i < n; i++)
1053 		zfree(&dirent[i]);
1054 	free(dirent);
1055 
1056 	return err;
1057 }
1058 
1059 int __weak perf_event__synthesize_extra_kmaps(struct perf_tool *tool __maybe_unused,
1060 					      perf_event__handler_t process __maybe_unused,
1061 					      struct machine *machine __maybe_unused)
1062 {
1063 	return 0;
1064 }
1065 
1066 static int __perf_event__synthesize_kernel_mmap(struct perf_tool *tool,
1067 						perf_event__handler_t process,
1068 						struct machine *machine)
1069 {
1070 	union perf_event *event;
1071 	size_t size = symbol_conf.buildid_mmap2 ?
1072 			sizeof(event->mmap2) : sizeof(event->mmap);
1073 	struct map *map = machine__kernel_map(machine);
1074 	struct kmap *kmap;
1075 	int err;
1076 
1077 	if (map == NULL)
1078 		return -1;
1079 
1080 	kmap = map__kmap(map);
1081 	if (!kmap->ref_reloc_sym)
1082 		return -1;
1083 
1084 	/*
1085 	 * We should get this from /sys/kernel/sections/.text, but till that is
1086 	 * available use this, and after it is use this as a fallback for older
1087 	 * kernels.
1088 	 */
1089 	event = zalloc(size + machine->id_hdr_size);
1090 	if (event == NULL) {
1091 		pr_debug("Not enough memory synthesizing mmap event "
1092 			 "for kernel modules\n");
1093 		return -1;
1094 	}
1095 
1096 	if (machine__is_host(machine)) {
1097 		/*
1098 		 * kernel uses PERF_RECORD_MISC_USER for user space maps,
1099 		 * see kernel/perf_event.c __perf_event_mmap
1100 		 */
1101 		event->header.misc = PERF_RECORD_MISC_KERNEL;
1102 	} else {
1103 		event->header.misc = PERF_RECORD_MISC_GUEST_KERNEL;
1104 	}
1105 
1106 	if (symbol_conf.buildid_mmap2) {
1107 		size = snprintf(event->mmap2.filename, sizeof(event->mmap2.filename),
1108 				"%s%s", machine->mmap_name, kmap->ref_reloc_sym->name) + 1;
1109 		size = PERF_ALIGN(size, sizeof(u64));
1110 		event->mmap2.header.type = PERF_RECORD_MMAP2;
1111 		event->mmap2.header.size = (sizeof(event->mmap2) -
1112 				(sizeof(event->mmap2.filename) - size) + machine->id_hdr_size);
1113 		event->mmap2.pgoff = kmap->ref_reloc_sym->addr;
1114 		event->mmap2.start = map->start;
1115 		event->mmap2.len   = map->end - event->mmap.start;
1116 		event->mmap2.pid   = machine->pid;
1117 
1118 		perf_record_mmap2__read_build_id(&event->mmap2, true);
1119 	} else {
1120 		size = snprintf(event->mmap.filename, sizeof(event->mmap.filename),
1121 				"%s%s", machine->mmap_name, kmap->ref_reloc_sym->name) + 1;
1122 		size = PERF_ALIGN(size, sizeof(u64));
1123 		event->mmap.header.type = PERF_RECORD_MMAP;
1124 		event->mmap.header.size = (sizeof(event->mmap) -
1125 				(sizeof(event->mmap.filename) - size) + machine->id_hdr_size);
1126 		event->mmap.pgoff = kmap->ref_reloc_sym->addr;
1127 		event->mmap.start = map->start;
1128 		event->mmap.len   = map->end - event->mmap.start;
1129 		event->mmap.pid   = machine->pid;
1130 	}
1131 
1132 	err = perf_tool__process_synth_event(tool, event, machine, process);
1133 	free(event);
1134 
1135 	return err;
1136 }
1137 
1138 int perf_event__synthesize_kernel_mmap(struct perf_tool *tool,
1139 				       perf_event__handler_t process,
1140 				       struct machine *machine)
1141 {
1142 	int err;
1143 
1144 	err = __perf_event__synthesize_kernel_mmap(tool, process, machine);
1145 	if (err < 0)
1146 		return err;
1147 
1148 	return perf_event__synthesize_extra_kmaps(tool, process, machine);
1149 }
1150 
1151 int perf_event__synthesize_thread_map2(struct perf_tool *tool,
1152 				      struct perf_thread_map *threads,
1153 				      perf_event__handler_t process,
1154 				      struct machine *machine)
1155 {
1156 	union perf_event *event;
1157 	int i, err, size;
1158 
1159 	size  = sizeof(event->thread_map);
1160 	size +=	threads->nr * sizeof(event->thread_map.entries[0]);
1161 
1162 	event = zalloc(size);
1163 	if (!event)
1164 		return -ENOMEM;
1165 
1166 	event->header.type = PERF_RECORD_THREAD_MAP;
1167 	event->header.size = size;
1168 	event->thread_map.nr = threads->nr;
1169 
1170 	for (i = 0; i < threads->nr; i++) {
1171 		struct perf_record_thread_map_entry *entry = &event->thread_map.entries[i];
1172 		char *comm = perf_thread_map__comm(threads, i);
1173 
1174 		if (!comm)
1175 			comm = (char *) "";
1176 
1177 		entry->pid = perf_thread_map__pid(threads, i);
1178 		strncpy((char *) &entry->comm, comm, sizeof(entry->comm));
1179 	}
1180 
1181 	err = process(tool, event, NULL, machine);
1182 
1183 	free(event);
1184 	return err;
1185 }
1186 
1187 static void synthesize_cpus(struct perf_record_cpu_map_data *data,
1188 			    const struct perf_cpu_map *map)
1189 {
1190 	int i, map_nr = perf_cpu_map__nr(map);
1191 
1192 	data->cpus_data.nr = map_nr;
1193 
1194 	for (i = 0; i < map_nr; i++)
1195 		data->cpus_data.cpu[i] = perf_cpu_map__cpu(map, i).cpu;
1196 }
1197 
1198 static void synthesize_mask(struct perf_record_cpu_map_data *data,
1199 			    const struct perf_cpu_map *map, int max)
1200 {
1201 	int idx;
1202 	struct perf_cpu cpu;
1203 
1204 	/* Due to padding, the 4bytes per entry mask variant is always smaller. */
1205 	data->mask32_data.nr = BITS_TO_U32(max);
1206 	data->mask32_data.long_size = 4;
1207 
1208 	perf_cpu_map__for_each_cpu(cpu, idx, map) {
1209 		int bit_word = cpu.cpu / 32;
1210 		__u32 bit_mask = 1U << (cpu.cpu & 31);
1211 
1212 		data->mask32_data.mask[bit_word] |= bit_mask;
1213 	}
1214 }
1215 
1216 static size_t cpus_size(const struct perf_cpu_map *map)
1217 {
1218 	return sizeof(struct cpu_map_entries) + perf_cpu_map__nr(map) * sizeof(u16);
1219 }
1220 
1221 static size_t mask_size(const struct perf_cpu_map *map, int *max)
1222 {
1223 	*max = perf_cpu_map__max(map).cpu;
1224 	return sizeof(struct perf_record_mask_cpu_map32) + BITS_TO_U32(*max) * sizeof(__u32);
1225 }
1226 
1227 static void *cpu_map_data__alloc(const struct perf_cpu_map *map, size_t *size,
1228 				 u16 *type, int *max)
1229 {
1230 	size_t size_cpus, size_mask;
1231 	bool is_dummy = perf_cpu_map__empty(map);
1232 
1233 	/*
1234 	 * Both array and mask data have variable size based
1235 	 * on the number of cpus and their actual values.
1236 	 * The size of the 'struct perf_record_cpu_map_data' is:
1237 	 *
1238 	 *   array = size of 'struct cpu_map_entries' +
1239 	 *           number of cpus * sizeof(u64)
1240 	 *
1241 	 *   mask  = size of 'struct perf_record_record_cpu_map' +
1242 	 *           maximum cpu bit converted to size of longs
1243 	 *
1244 	 * and finally + the size of 'struct perf_record_cpu_map_data'.
1245 	 */
1246 	size_cpus = cpus_size(map);
1247 	size_mask = mask_size(map, max);
1248 
1249 	if (is_dummy || (size_cpus < size_mask)) {
1250 		*size += size_cpus;
1251 		*type  = PERF_CPU_MAP__CPUS;
1252 	} else {
1253 		*size += size_mask;
1254 		*type  = PERF_CPU_MAP__MASK;
1255 	}
1256 
1257 	*size += sizeof(__u16); /* For perf_record_cpu_map_data.type. */
1258 	*size = PERF_ALIGN(*size, sizeof(u64));
1259 	return zalloc(*size);
1260 }
1261 
1262 static void cpu_map_data__synthesize(struct perf_record_cpu_map_data *data,
1263 				     const struct perf_cpu_map *map,
1264 				     u16 type, int max)
1265 {
1266 	data->type = type;
1267 
1268 	switch (type) {
1269 	case PERF_CPU_MAP__CPUS:
1270 		synthesize_cpus(data, map);
1271 		break;
1272 	case PERF_CPU_MAP__MASK:
1273 		synthesize_mask(data, map, max);
1274 	default:
1275 		break;
1276 	}
1277 }
1278 
1279 static struct perf_record_cpu_map *cpu_map_event__new(const struct perf_cpu_map *map)
1280 {
1281 	size_t size = sizeof(struct perf_event_header);
1282 	struct perf_record_cpu_map *event;
1283 	int max;
1284 	u16 type;
1285 
1286 	event = cpu_map_data__alloc(map, &size, &type, &max);
1287 	if (!event)
1288 		return NULL;
1289 
1290 	event->header.type = PERF_RECORD_CPU_MAP;
1291 	event->header.size = size;
1292 	event->data.type   = type;
1293 
1294 	cpu_map_data__synthesize(&event->data, map, type, max);
1295 	return event;
1296 }
1297 
1298 int perf_event__synthesize_cpu_map(struct perf_tool *tool,
1299 				   const struct perf_cpu_map *map,
1300 				   perf_event__handler_t process,
1301 				   struct machine *machine)
1302 {
1303 	struct perf_record_cpu_map *event;
1304 	int err;
1305 
1306 	event = cpu_map_event__new(map);
1307 	if (!event)
1308 		return -ENOMEM;
1309 
1310 	err = process(tool, (union perf_event *) event, NULL, machine);
1311 
1312 	free(event);
1313 	return err;
1314 }
1315 
1316 int perf_event__synthesize_stat_config(struct perf_tool *tool,
1317 				       struct perf_stat_config *config,
1318 				       perf_event__handler_t process,
1319 				       struct machine *machine)
1320 {
1321 	struct perf_record_stat_config *event;
1322 	int size, i = 0, err;
1323 
1324 	size  = sizeof(*event);
1325 	size += (PERF_STAT_CONFIG_TERM__MAX * sizeof(event->data[0]));
1326 
1327 	event = zalloc(size);
1328 	if (!event)
1329 		return -ENOMEM;
1330 
1331 	event->header.type = PERF_RECORD_STAT_CONFIG;
1332 	event->header.size = size;
1333 	event->nr          = PERF_STAT_CONFIG_TERM__MAX;
1334 
1335 #define ADD(__term, __val)					\
1336 	event->data[i].tag = PERF_STAT_CONFIG_TERM__##__term;	\
1337 	event->data[i].val = __val;				\
1338 	i++;
1339 
1340 	ADD(AGGR_MODE,	config->aggr_mode)
1341 	ADD(INTERVAL,	config->interval)
1342 	ADD(SCALE,	config->scale)
1343 
1344 	WARN_ONCE(i != PERF_STAT_CONFIG_TERM__MAX,
1345 		  "stat config terms unbalanced\n");
1346 #undef ADD
1347 
1348 	err = process(tool, (union perf_event *) event, NULL, machine);
1349 
1350 	free(event);
1351 	return err;
1352 }
1353 
1354 int perf_event__synthesize_stat(struct perf_tool *tool,
1355 				struct perf_cpu cpu, u32 thread, u64 id,
1356 				struct perf_counts_values *count,
1357 				perf_event__handler_t process,
1358 				struct machine *machine)
1359 {
1360 	struct perf_record_stat event;
1361 
1362 	event.header.type = PERF_RECORD_STAT;
1363 	event.header.size = sizeof(event);
1364 	event.header.misc = 0;
1365 
1366 	event.id        = id;
1367 	event.cpu       = cpu.cpu;
1368 	event.thread    = thread;
1369 	event.val       = count->val;
1370 	event.ena       = count->ena;
1371 	event.run       = count->run;
1372 
1373 	return process(tool, (union perf_event *) &event, NULL, machine);
1374 }
1375 
1376 int perf_event__synthesize_stat_round(struct perf_tool *tool,
1377 				      u64 evtime, u64 type,
1378 				      perf_event__handler_t process,
1379 				      struct machine *machine)
1380 {
1381 	struct perf_record_stat_round event;
1382 
1383 	event.header.type = PERF_RECORD_STAT_ROUND;
1384 	event.header.size = sizeof(event);
1385 	event.header.misc = 0;
1386 
1387 	event.time = evtime;
1388 	event.type = type;
1389 
1390 	return process(tool, (union perf_event *) &event, NULL, machine);
1391 }
1392 
1393 size_t perf_event__sample_event_size(const struct perf_sample *sample, u64 type, u64 read_format)
1394 {
1395 	size_t sz, result = sizeof(struct perf_record_sample);
1396 
1397 	if (type & PERF_SAMPLE_IDENTIFIER)
1398 		result += sizeof(u64);
1399 
1400 	if (type & PERF_SAMPLE_IP)
1401 		result += sizeof(u64);
1402 
1403 	if (type & PERF_SAMPLE_TID)
1404 		result += sizeof(u64);
1405 
1406 	if (type & PERF_SAMPLE_TIME)
1407 		result += sizeof(u64);
1408 
1409 	if (type & PERF_SAMPLE_ADDR)
1410 		result += sizeof(u64);
1411 
1412 	if (type & PERF_SAMPLE_ID)
1413 		result += sizeof(u64);
1414 
1415 	if (type & PERF_SAMPLE_STREAM_ID)
1416 		result += sizeof(u64);
1417 
1418 	if (type & PERF_SAMPLE_CPU)
1419 		result += sizeof(u64);
1420 
1421 	if (type & PERF_SAMPLE_PERIOD)
1422 		result += sizeof(u64);
1423 
1424 	if (type & PERF_SAMPLE_READ) {
1425 		result += sizeof(u64);
1426 		if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1427 			result += sizeof(u64);
1428 		if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1429 			result += sizeof(u64);
1430 		/* PERF_FORMAT_ID is forced for PERF_SAMPLE_READ */
1431 		if (read_format & PERF_FORMAT_GROUP) {
1432 			sz = sample_read_value_size(read_format);
1433 			result += sz * sample->read.group.nr;
1434 		} else {
1435 			result += sizeof(u64);
1436 			if (read_format & PERF_FORMAT_LOST)
1437 				result += sizeof(u64);
1438 		}
1439 	}
1440 
1441 	if (type & PERF_SAMPLE_CALLCHAIN) {
1442 		sz = (sample->callchain->nr + 1) * sizeof(u64);
1443 		result += sz;
1444 	}
1445 
1446 	if (type & PERF_SAMPLE_RAW) {
1447 		result += sizeof(u32);
1448 		result += sample->raw_size;
1449 	}
1450 
1451 	if (type & PERF_SAMPLE_BRANCH_STACK) {
1452 		sz = sample->branch_stack->nr * sizeof(struct branch_entry);
1453 		/* nr, hw_idx */
1454 		sz += 2 * sizeof(u64);
1455 		result += sz;
1456 	}
1457 
1458 	if (type & PERF_SAMPLE_REGS_USER) {
1459 		if (sample->user_regs.abi) {
1460 			result += sizeof(u64);
1461 			sz = hweight64(sample->user_regs.mask) * sizeof(u64);
1462 			result += sz;
1463 		} else {
1464 			result += sizeof(u64);
1465 		}
1466 	}
1467 
1468 	if (type & PERF_SAMPLE_STACK_USER) {
1469 		sz = sample->user_stack.size;
1470 		result += sizeof(u64);
1471 		if (sz) {
1472 			result += sz;
1473 			result += sizeof(u64);
1474 		}
1475 	}
1476 
1477 	if (type & PERF_SAMPLE_WEIGHT_TYPE)
1478 		result += sizeof(u64);
1479 
1480 	if (type & PERF_SAMPLE_DATA_SRC)
1481 		result += sizeof(u64);
1482 
1483 	if (type & PERF_SAMPLE_TRANSACTION)
1484 		result += sizeof(u64);
1485 
1486 	if (type & PERF_SAMPLE_REGS_INTR) {
1487 		if (sample->intr_regs.abi) {
1488 			result += sizeof(u64);
1489 			sz = hweight64(sample->intr_regs.mask) * sizeof(u64);
1490 			result += sz;
1491 		} else {
1492 			result += sizeof(u64);
1493 		}
1494 	}
1495 
1496 	if (type & PERF_SAMPLE_PHYS_ADDR)
1497 		result += sizeof(u64);
1498 
1499 	if (type & PERF_SAMPLE_CGROUP)
1500 		result += sizeof(u64);
1501 
1502 	if (type & PERF_SAMPLE_DATA_PAGE_SIZE)
1503 		result += sizeof(u64);
1504 
1505 	if (type & PERF_SAMPLE_CODE_PAGE_SIZE)
1506 		result += sizeof(u64);
1507 
1508 	if (type & PERF_SAMPLE_AUX) {
1509 		result += sizeof(u64);
1510 		result += sample->aux_sample.size;
1511 	}
1512 
1513 	return result;
1514 }
1515 
1516 void __weak arch_perf_synthesize_sample_weight(const struct perf_sample *data,
1517 					       __u64 *array, u64 type __maybe_unused)
1518 {
1519 	*array = data->weight;
1520 }
1521 
1522 static __u64 *copy_read_group_values(__u64 *array, __u64 read_format,
1523 				     const struct perf_sample *sample)
1524 {
1525 	size_t sz = sample_read_value_size(read_format);
1526 	struct sample_read_value *v = sample->read.group.values;
1527 
1528 	sample_read_group__for_each(v, sample->read.group.nr, read_format) {
1529 		/* PERF_FORMAT_ID is forced for PERF_SAMPLE_READ */
1530 		memcpy(array, v, sz);
1531 		array = (void *)array + sz;
1532 	}
1533 	return array;
1534 }
1535 
1536 int perf_event__synthesize_sample(union perf_event *event, u64 type, u64 read_format,
1537 				  const struct perf_sample *sample)
1538 {
1539 	__u64 *array;
1540 	size_t sz;
1541 	/*
1542 	 * used for cross-endian analysis. See git commit 65014ab3
1543 	 * for why this goofiness is needed.
1544 	 */
1545 	union u64_swap u;
1546 
1547 	array = event->sample.array;
1548 
1549 	if (type & PERF_SAMPLE_IDENTIFIER) {
1550 		*array = sample->id;
1551 		array++;
1552 	}
1553 
1554 	if (type & PERF_SAMPLE_IP) {
1555 		*array = sample->ip;
1556 		array++;
1557 	}
1558 
1559 	if (type & PERF_SAMPLE_TID) {
1560 		u.val32[0] = sample->pid;
1561 		u.val32[1] = sample->tid;
1562 		*array = u.val64;
1563 		array++;
1564 	}
1565 
1566 	if (type & PERF_SAMPLE_TIME) {
1567 		*array = sample->time;
1568 		array++;
1569 	}
1570 
1571 	if (type & PERF_SAMPLE_ADDR) {
1572 		*array = sample->addr;
1573 		array++;
1574 	}
1575 
1576 	if (type & PERF_SAMPLE_ID) {
1577 		*array = sample->id;
1578 		array++;
1579 	}
1580 
1581 	if (type & PERF_SAMPLE_STREAM_ID) {
1582 		*array = sample->stream_id;
1583 		array++;
1584 	}
1585 
1586 	if (type & PERF_SAMPLE_CPU) {
1587 		u.val32[0] = sample->cpu;
1588 		u.val32[1] = 0;
1589 		*array = u.val64;
1590 		array++;
1591 	}
1592 
1593 	if (type & PERF_SAMPLE_PERIOD) {
1594 		*array = sample->period;
1595 		array++;
1596 	}
1597 
1598 	if (type & PERF_SAMPLE_READ) {
1599 		if (read_format & PERF_FORMAT_GROUP)
1600 			*array = sample->read.group.nr;
1601 		else
1602 			*array = sample->read.one.value;
1603 		array++;
1604 
1605 		if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
1606 			*array = sample->read.time_enabled;
1607 			array++;
1608 		}
1609 
1610 		if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
1611 			*array = sample->read.time_running;
1612 			array++;
1613 		}
1614 
1615 		/* PERF_FORMAT_ID is forced for PERF_SAMPLE_READ */
1616 		if (read_format & PERF_FORMAT_GROUP) {
1617 			array = copy_read_group_values(array, read_format,
1618 						       sample);
1619 		} else {
1620 			*array = sample->read.one.id;
1621 			array++;
1622 
1623 			if (read_format & PERF_FORMAT_LOST) {
1624 				*array = sample->read.one.lost;
1625 				array++;
1626 			}
1627 		}
1628 	}
1629 
1630 	if (type & PERF_SAMPLE_CALLCHAIN) {
1631 		sz = (sample->callchain->nr + 1) * sizeof(u64);
1632 		memcpy(array, sample->callchain, sz);
1633 		array = (void *)array + sz;
1634 	}
1635 
1636 	if (type & PERF_SAMPLE_RAW) {
1637 		u.val32[0] = sample->raw_size;
1638 		*array = u.val64;
1639 		array = (void *)array + sizeof(u32);
1640 
1641 		memcpy(array, sample->raw_data, sample->raw_size);
1642 		array = (void *)array + sample->raw_size;
1643 	}
1644 
1645 	if (type & PERF_SAMPLE_BRANCH_STACK) {
1646 		sz = sample->branch_stack->nr * sizeof(struct branch_entry);
1647 		/* nr, hw_idx */
1648 		sz += 2 * sizeof(u64);
1649 		memcpy(array, sample->branch_stack, sz);
1650 		array = (void *)array + sz;
1651 	}
1652 
1653 	if (type & PERF_SAMPLE_REGS_USER) {
1654 		if (sample->user_regs.abi) {
1655 			*array++ = sample->user_regs.abi;
1656 			sz = hweight64(sample->user_regs.mask) * sizeof(u64);
1657 			memcpy(array, sample->user_regs.regs, sz);
1658 			array = (void *)array + sz;
1659 		} else {
1660 			*array++ = 0;
1661 		}
1662 	}
1663 
1664 	if (type & PERF_SAMPLE_STACK_USER) {
1665 		sz = sample->user_stack.size;
1666 		*array++ = sz;
1667 		if (sz) {
1668 			memcpy(array, sample->user_stack.data, sz);
1669 			array = (void *)array + sz;
1670 			*array++ = sz;
1671 		}
1672 	}
1673 
1674 	if (type & PERF_SAMPLE_WEIGHT_TYPE) {
1675 		arch_perf_synthesize_sample_weight(sample, array, type);
1676 		array++;
1677 	}
1678 
1679 	if (type & PERF_SAMPLE_DATA_SRC) {
1680 		*array = sample->data_src;
1681 		array++;
1682 	}
1683 
1684 	if (type & PERF_SAMPLE_TRANSACTION) {
1685 		*array = sample->transaction;
1686 		array++;
1687 	}
1688 
1689 	if (type & PERF_SAMPLE_REGS_INTR) {
1690 		if (sample->intr_regs.abi) {
1691 			*array++ = sample->intr_regs.abi;
1692 			sz = hweight64(sample->intr_regs.mask) * sizeof(u64);
1693 			memcpy(array, sample->intr_regs.regs, sz);
1694 			array = (void *)array + sz;
1695 		} else {
1696 			*array++ = 0;
1697 		}
1698 	}
1699 
1700 	if (type & PERF_SAMPLE_PHYS_ADDR) {
1701 		*array = sample->phys_addr;
1702 		array++;
1703 	}
1704 
1705 	if (type & PERF_SAMPLE_CGROUP) {
1706 		*array = sample->cgroup;
1707 		array++;
1708 	}
1709 
1710 	if (type & PERF_SAMPLE_DATA_PAGE_SIZE) {
1711 		*array = sample->data_page_size;
1712 		array++;
1713 	}
1714 
1715 	if (type & PERF_SAMPLE_CODE_PAGE_SIZE) {
1716 		*array = sample->code_page_size;
1717 		array++;
1718 	}
1719 
1720 	if (type & PERF_SAMPLE_AUX) {
1721 		sz = sample->aux_sample.size;
1722 		*array++ = sz;
1723 		memcpy(array, sample->aux_sample.data, sz);
1724 		array = (void *)array + sz;
1725 	}
1726 
1727 	return 0;
1728 }
1729 
1730 int perf_event__synthesize_id_sample(__u64 *array, u64 type, const struct perf_sample *sample)
1731 {
1732 	__u64 *start = array;
1733 
1734 	/*
1735 	 * used for cross-endian analysis. See git commit 65014ab3
1736 	 * for why this goofiness is needed.
1737 	 */
1738 	union u64_swap u;
1739 
1740 	if (type & PERF_SAMPLE_TID) {
1741 		u.val32[0] = sample->pid;
1742 		u.val32[1] = sample->tid;
1743 		*array = u.val64;
1744 		array++;
1745 	}
1746 
1747 	if (type & PERF_SAMPLE_TIME) {
1748 		*array = sample->time;
1749 		array++;
1750 	}
1751 
1752 	if (type & PERF_SAMPLE_ID) {
1753 		*array = sample->id;
1754 		array++;
1755 	}
1756 
1757 	if (type & PERF_SAMPLE_STREAM_ID) {
1758 		*array = sample->stream_id;
1759 		array++;
1760 	}
1761 
1762 	if (type & PERF_SAMPLE_CPU) {
1763 		u.val32[0] = sample->cpu;
1764 		u.val32[1] = 0;
1765 		*array = u.val64;
1766 		array++;
1767 	}
1768 
1769 	if (type & PERF_SAMPLE_IDENTIFIER) {
1770 		*array = sample->id;
1771 		array++;
1772 	}
1773 
1774 	return (void *)array - (void *)start;
1775 }
1776 
1777 int __perf_event__synthesize_id_index(struct perf_tool *tool, perf_event__handler_t process,
1778 				      struct evlist *evlist, struct machine *machine, size_t from)
1779 {
1780 	union perf_event *ev;
1781 	struct evsel *evsel;
1782 	size_t nr = 0, i = 0, sz, max_nr, n, pos;
1783 	size_t e1_sz = sizeof(struct id_index_entry);
1784 	size_t e2_sz = sizeof(struct id_index_entry_2);
1785 	size_t etot_sz = e1_sz + e2_sz;
1786 	bool e2_needed = false;
1787 	int err;
1788 
1789 	max_nr = (UINT16_MAX - sizeof(struct perf_record_id_index)) / etot_sz;
1790 
1791 	pos = 0;
1792 	evlist__for_each_entry(evlist, evsel) {
1793 		if (pos++ < from)
1794 			continue;
1795 		nr += evsel->core.ids;
1796 	}
1797 
1798 	if (!nr)
1799 		return 0;
1800 
1801 	pr_debug2("Synthesizing id index\n");
1802 
1803 	n = nr > max_nr ? max_nr : nr;
1804 	sz = sizeof(struct perf_record_id_index) + n * etot_sz;
1805 	ev = zalloc(sz);
1806 	if (!ev)
1807 		return -ENOMEM;
1808 
1809 	sz = sizeof(struct perf_record_id_index) + n * e1_sz;
1810 
1811 	ev->id_index.header.type = PERF_RECORD_ID_INDEX;
1812 	ev->id_index.nr = n;
1813 
1814 	pos = 0;
1815 	evlist__for_each_entry(evlist, evsel) {
1816 		u32 j;
1817 
1818 		if (pos++ < from)
1819 			continue;
1820 		for (j = 0; j < evsel->core.ids; j++, i++) {
1821 			struct id_index_entry *e;
1822 			struct id_index_entry_2 *e2;
1823 			struct perf_sample_id *sid;
1824 
1825 			if (i >= n) {
1826 				ev->id_index.header.size = sz + (e2_needed ? n * e2_sz : 0);
1827 				err = process(tool, ev, NULL, machine);
1828 				if (err)
1829 					goto out_err;
1830 				nr -= n;
1831 				i = 0;
1832 				e2_needed = false;
1833 			}
1834 
1835 			e = &ev->id_index.entries[i];
1836 
1837 			e->id = evsel->core.id[j];
1838 
1839 			sid = evlist__id2sid(evlist, e->id);
1840 			if (!sid) {
1841 				free(ev);
1842 				return -ENOENT;
1843 			}
1844 
1845 			e->idx = sid->idx;
1846 			e->cpu = sid->cpu.cpu;
1847 			e->tid = sid->tid;
1848 
1849 			if (sid->machine_pid)
1850 				e2_needed = true;
1851 
1852 			e2 = (void *)ev + sz;
1853 			e2[i].machine_pid = sid->machine_pid;
1854 			e2[i].vcpu        = sid->vcpu.cpu;
1855 		}
1856 	}
1857 
1858 	sz = sizeof(struct perf_record_id_index) + nr * e1_sz;
1859 	ev->id_index.header.size = sz + (e2_needed ? nr * e2_sz : 0);
1860 	ev->id_index.nr = nr;
1861 
1862 	err = process(tool, ev, NULL, machine);
1863 out_err:
1864 	free(ev);
1865 
1866 	return err;
1867 }
1868 
1869 int perf_event__synthesize_id_index(struct perf_tool *tool, perf_event__handler_t process,
1870 				    struct evlist *evlist, struct machine *machine)
1871 {
1872 	return __perf_event__synthesize_id_index(tool, process, evlist, machine, 0);
1873 }
1874 
1875 int __machine__synthesize_threads(struct machine *machine, struct perf_tool *tool,
1876 				  struct target *target, struct perf_thread_map *threads,
1877 				  perf_event__handler_t process, bool needs_mmap,
1878 				  bool data_mmap, unsigned int nr_threads_synthesize)
1879 {
1880 	/*
1881 	 * When perf runs in non-root PID namespace, and the namespace's proc FS
1882 	 * is not mounted, nsinfo__is_in_root_namespace() returns false.
1883 	 * In this case, the proc FS is coming for the parent namespace, thus
1884 	 * perf tool will wrongly gather process info from its parent PID
1885 	 * namespace.
1886 	 *
1887 	 * To avoid the confusion that the perf tool runs in a child PID
1888 	 * namespace but it synthesizes thread info from its parent PID
1889 	 * namespace, returns failure with warning.
1890 	 */
1891 	if (!nsinfo__is_in_root_namespace()) {
1892 		pr_err("Perf runs in non-root PID namespace but it tries to ");
1893 		pr_err("gather process info from its parent PID namespace.\n");
1894 		pr_err("Please mount the proc file system properly, e.g. ");
1895 		pr_err("add the option '--mount-proc' for unshare command.\n");
1896 		return -EPERM;
1897 	}
1898 
1899 	if (target__has_task(target))
1900 		return perf_event__synthesize_thread_map(tool, threads, process, machine,
1901 							 needs_mmap, data_mmap);
1902 	else if (target__has_cpu(target))
1903 		return perf_event__synthesize_threads(tool, process, machine,
1904 						      needs_mmap, data_mmap,
1905 						      nr_threads_synthesize);
1906 	/* command specified */
1907 	return 0;
1908 }
1909 
1910 int machine__synthesize_threads(struct machine *machine, struct target *target,
1911 				struct perf_thread_map *threads, bool needs_mmap,
1912 				bool data_mmap, unsigned int nr_threads_synthesize)
1913 {
1914 	return __machine__synthesize_threads(machine, NULL, target, threads,
1915 					     perf_event__process, needs_mmap,
1916 					     data_mmap, nr_threads_synthesize);
1917 }
1918 
1919 static struct perf_record_event_update *event_update_event__new(size_t size, u64 type, u64 id)
1920 {
1921 	struct perf_record_event_update *ev;
1922 
1923 	size += sizeof(*ev);
1924 	size  = PERF_ALIGN(size, sizeof(u64));
1925 
1926 	ev = zalloc(size);
1927 	if (ev) {
1928 		ev->header.type = PERF_RECORD_EVENT_UPDATE;
1929 		ev->header.size = (u16)size;
1930 		ev->type	= type;
1931 		ev->id		= id;
1932 	}
1933 	return ev;
1934 }
1935 
1936 int perf_event__synthesize_event_update_unit(struct perf_tool *tool, struct evsel *evsel,
1937 					     perf_event__handler_t process)
1938 {
1939 	size_t size = strlen(evsel->unit);
1940 	struct perf_record_event_update *ev;
1941 	int err;
1942 
1943 	ev = event_update_event__new(size + 1, PERF_EVENT_UPDATE__UNIT, evsel->core.id[0]);
1944 	if (ev == NULL)
1945 		return -ENOMEM;
1946 
1947 	strlcpy(ev->data, evsel->unit, size + 1);
1948 	err = process(tool, (union perf_event *)ev, NULL, NULL);
1949 	free(ev);
1950 	return err;
1951 }
1952 
1953 int perf_event__synthesize_event_update_scale(struct perf_tool *tool, struct evsel *evsel,
1954 					      perf_event__handler_t process)
1955 {
1956 	struct perf_record_event_update *ev;
1957 	struct perf_record_event_update_scale *ev_data;
1958 	int err;
1959 
1960 	ev = event_update_event__new(sizeof(*ev_data), PERF_EVENT_UPDATE__SCALE, evsel->core.id[0]);
1961 	if (ev == NULL)
1962 		return -ENOMEM;
1963 
1964 	ev_data = (struct perf_record_event_update_scale *)ev->data;
1965 	ev_data->scale = evsel->scale;
1966 	err = process(tool, (union perf_event *)ev, NULL, NULL);
1967 	free(ev);
1968 	return err;
1969 }
1970 
1971 int perf_event__synthesize_event_update_name(struct perf_tool *tool, struct evsel *evsel,
1972 					     perf_event__handler_t process)
1973 {
1974 	struct perf_record_event_update *ev;
1975 	size_t len = strlen(evsel->name);
1976 	int err;
1977 
1978 	ev = event_update_event__new(len + 1, PERF_EVENT_UPDATE__NAME, evsel->core.id[0]);
1979 	if (ev == NULL)
1980 		return -ENOMEM;
1981 
1982 	strlcpy(ev->data, evsel->name, len + 1);
1983 	err = process(tool, (union perf_event *)ev, NULL, NULL);
1984 	free(ev);
1985 	return err;
1986 }
1987 
1988 int perf_event__synthesize_event_update_cpus(struct perf_tool *tool, struct evsel *evsel,
1989 					     perf_event__handler_t process)
1990 {
1991 	size_t size = sizeof(struct perf_record_event_update);
1992 	struct perf_record_event_update *ev;
1993 	int max, err;
1994 	u16 type;
1995 
1996 	if (!evsel->core.own_cpus)
1997 		return 0;
1998 
1999 	ev = cpu_map_data__alloc(evsel->core.own_cpus, &size, &type, &max);
2000 	if (!ev)
2001 		return -ENOMEM;
2002 
2003 	ev->header.type = PERF_RECORD_EVENT_UPDATE;
2004 	ev->header.size = (u16)size;
2005 	ev->type	= PERF_EVENT_UPDATE__CPUS;
2006 	ev->id		= evsel->core.id[0];
2007 
2008 	cpu_map_data__synthesize((struct perf_record_cpu_map_data *)ev->data,
2009 				 evsel->core.own_cpus, type, max);
2010 
2011 	err = process(tool, (union perf_event *)ev, NULL, NULL);
2012 	free(ev);
2013 	return err;
2014 }
2015 
2016 int perf_event__synthesize_attrs(struct perf_tool *tool, struct evlist *evlist,
2017 				 perf_event__handler_t process)
2018 {
2019 	struct evsel *evsel;
2020 	int err = 0;
2021 
2022 	evlist__for_each_entry(evlist, evsel) {
2023 		err = perf_event__synthesize_attr(tool, &evsel->core.attr, evsel->core.ids,
2024 						  evsel->core.id, process);
2025 		if (err) {
2026 			pr_debug("failed to create perf header attribute\n");
2027 			return err;
2028 		}
2029 	}
2030 
2031 	return err;
2032 }
2033 
2034 static bool has_unit(struct evsel *evsel)
2035 {
2036 	return evsel->unit && *evsel->unit;
2037 }
2038 
2039 static bool has_scale(struct evsel *evsel)
2040 {
2041 	return evsel->scale != 1;
2042 }
2043 
2044 int perf_event__synthesize_extra_attr(struct perf_tool *tool, struct evlist *evsel_list,
2045 				      perf_event__handler_t process, bool is_pipe)
2046 {
2047 	struct evsel *evsel;
2048 	int err;
2049 
2050 	/*
2051 	 * Synthesize other events stuff not carried within
2052 	 * attr event - unit, scale, name
2053 	 */
2054 	evlist__for_each_entry(evsel_list, evsel) {
2055 		if (!evsel->supported)
2056 			continue;
2057 
2058 		/*
2059 		 * Synthesize unit and scale only if it's defined.
2060 		 */
2061 		if (has_unit(evsel)) {
2062 			err = perf_event__synthesize_event_update_unit(tool, evsel, process);
2063 			if (err < 0) {
2064 				pr_err("Couldn't synthesize evsel unit.\n");
2065 				return err;
2066 			}
2067 		}
2068 
2069 		if (has_scale(evsel)) {
2070 			err = perf_event__synthesize_event_update_scale(tool, evsel, process);
2071 			if (err < 0) {
2072 				pr_err("Couldn't synthesize evsel evsel.\n");
2073 				return err;
2074 			}
2075 		}
2076 
2077 		if (evsel->core.own_cpus) {
2078 			err = perf_event__synthesize_event_update_cpus(tool, evsel, process);
2079 			if (err < 0) {
2080 				pr_err("Couldn't synthesize evsel cpus.\n");
2081 				return err;
2082 			}
2083 		}
2084 
2085 		/*
2086 		 * Name is needed only for pipe output,
2087 		 * perf.data carries event names.
2088 		 */
2089 		if (is_pipe) {
2090 			err = perf_event__synthesize_event_update_name(tool, evsel, process);
2091 			if (err < 0) {
2092 				pr_err("Couldn't synthesize evsel name.\n");
2093 				return err;
2094 			}
2095 		}
2096 	}
2097 	return 0;
2098 }
2099 
2100 int perf_event__synthesize_attr(struct perf_tool *tool, struct perf_event_attr *attr,
2101 				u32 ids, u64 *id, perf_event__handler_t process)
2102 {
2103 	union perf_event *ev;
2104 	size_t size;
2105 	int err;
2106 
2107 	size = sizeof(struct perf_event_attr);
2108 	size = PERF_ALIGN(size, sizeof(u64));
2109 	size += sizeof(struct perf_event_header);
2110 	size += ids * sizeof(u64);
2111 
2112 	ev = zalloc(size);
2113 
2114 	if (ev == NULL)
2115 		return -ENOMEM;
2116 
2117 	ev->attr.attr = *attr;
2118 	memcpy(ev->attr.id, id, ids * sizeof(u64));
2119 
2120 	ev->attr.header.type = PERF_RECORD_HEADER_ATTR;
2121 	ev->attr.header.size = (u16)size;
2122 
2123 	if (ev->attr.header.size == size)
2124 		err = process(tool, ev, NULL, NULL);
2125 	else
2126 		err = -E2BIG;
2127 
2128 	free(ev);
2129 
2130 	return err;
2131 }
2132 
2133 int perf_event__synthesize_tracing_data(struct perf_tool *tool, int fd, struct evlist *evlist,
2134 					perf_event__handler_t process)
2135 {
2136 	union perf_event ev;
2137 	struct tracing_data *tdata;
2138 	ssize_t size = 0, aligned_size = 0, padding;
2139 	struct feat_fd ff;
2140 
2141 	/*
2142 	 * We are going to store the size of the data followed
2143 	 * by the data contents. Since the fd descriptor is a pipe,
2144 	 * we cannot seek back to store the size of the data once
2145 	 * we know it. Instead we:
2146 	 *
2147 	 * - write the tracing data to the temp file
2148 	 * - get/write the data size to pipe
2149 	 * - write the tracing data from the temp file
2150 	 *   to the pipe
2151 	 */
2152 	tdata = tracing_data_get(&evlist->core.entries, fd, true);
2153 	if (!tdata)
2154 		return -1;
2155 
2156 	memset(&ev, 0, sizeof(ev));
2157 
2158 	ev.tracing_data.header.type = PERF_RECORD_HEADER_TRACING_DATA;
2159 	size = tdata->size;
2160 	aligned_size = PERF_ALIGN(size, sizeof(u64));
2161 	padding = aligned_size - size;
2162 	ev.tracing_data.header.size = sizeof(ev.tracing_data);
2163 	ev.tracing_data.size = aligned_size;
2164 
2165 	process(tool, &ev, NULL, NULL);
2166 
2167 	/*
2168 	 * The put function will copy all the tracing data
2169 	 * stored in temp file to the pipe.
2170 	 */
2171 	tracing_data_put(tdata);
2172 
2173 	ff = (struct feat_fd){ .fd = fd };
2174 	if (write_padded(&ff, NULL, 0, padding))
2175 		return -1;
2176 
2177 	return aligned_size;
2178 }
2179 
2180 int perf_event__synthesize_build_id(struct perf_tool *tool, struct dso *pos, u16 misc,
2181 				    perf_event__handler_t process, struct machine *machine)
2182 {
2183 	union perf_event ev;
2184 	size_t len;
2185 
2186 	if (!pos->hit)
2187 		return 0;
2188 
2189 	memset(&ev, 0, sizeof(ev));
2190 
2191 	len = pos->long_name_len + 1;
2192 	len = PERF_ALIGN(len, NAME_ALIGN);
2193 	memcpy(&ev.build_id.build_id, pos->bid.data, sizeof(pos->bid.data));
2194 	ev.build_id.header.type = PERF_RECORD_HEADER_BUILD_ID;
2195 	ev.build_id.header.misc = misc;
2196 	ev.build_id.pid = machine->pid;
2197 	ev.build_id.header.size = sizeof(ev.build_id) + len;
2198 	memcpy(&ev.build_id.filename, pos->long_name, pos->long_name_len);
2199 
2200 	return process(tool, &ev, NULL, machine);
2201 }
2202 
2203 int perf_event__synthesize_stat_events(struct perf_stat_config *config, struct perf_tool *tool,
2204 				       struct evlist *evlist, perf_event__handler_t process, bool attrs)
2205 {
2206 	int err;
2207 
2208 	if (attrs) {
2209 		err = perf_event__synthesize_attrs(tool, evlist, process);
2210 		if (err < 0) {
2211 			pr_err("Couldn't synthesize attrs.\n");
2212 			return err;
2213 		}
2214 	}
2215 
2216 	err = perf_event__synthesize_extra_attr(tool, evlist, process, attrs);
2217 	err = perf_event__synthesize_thread_map2(tool, evlist->core.threads, process, NULL);
2218 	if (err < 0) {
2219 		pr_err("Couldn't synthesize thread map.\n");
2220 		return err;
2221 	}
2222 
2223 	err = perf_event__synthesize_cpu_map(tool, evlist->core.user_requested_cpus, process, NULL);
2224 	if (err < 0) {
2225 		pr_err("Couldn't synthesize thread map.\n");
2226 		return err;
2227 	}
2228 
2229 	err = perf_event__synthesize_stat_config(tool, config, process, NULL);
2230 	if (err < 0) {
2231 		pr_err("Couldn't synthesize config.\n");
2232 		return err;
2233 	}
2234 
2235 	return 0;
2236 }
2237 
2238 extern const struct perf_header_feature_ops feat_ops[HEADER_LAST_FEATURE];
2239 
2240 int perf_event__synthesize_features(struct perf_tool *tool, struct perf_session *session,
2241 				    struct evlist *evlist, perf_event__handler_t process)
2242 {
2243 	struct perf_header *header = &session->header;
2244 	struct perf_record_header_feature *fe;
2245 	struct feat_fd ff;
2246 	size_t sz, sz_hdr;
2247 	int feat, ret;
2248 
2249 	sz_hdr = sizeof(fe->header);
2250 	sz = sizeof(union perf_event);
2251 	/* get a nice alignment */
2252 	sz = PERF_ALIGN(sz, page_size);
2253 
2254 	memset(&ff, 0, sizeof(ff));
2255 
2256 	ff.buf = malloc(sz);
2257 	if (!ff.buf)
2258 		return -ENOMEM;
2259 
2260 	ff.size = sz - sz_hdr;
2261 	ff.ph = &session->header;
2262 
2263 	for_each_set_bit(feat, header->adds_features, HEADER_FEAT_BITS) {
2264 		if (!feat_ops[feat].synthesize) {
2265 			pr_debug("No record header feature for header :%d\n", feat);
2266 			continue;
2267 		}
2268 
2269 		ff.offset = sizeof(*fe);
2270 
2271 		ret = feat_ops[feat].write(&ff, evlist);
2272 		if (ret || ff.offset <= (ssize_t)sizeof(*fe)) {
2273 			pr_debug("Error writing feature\n");
2274 			continue;
2275 		}
2276 		/* ff.buf may have changed due to realloc in do_write() */
2277 		fe = ff.buf;
2278 		memset(fe, 0, sizeof(*fe));
2279 
2280 		fe->feat_id = feat;
2281 		fe->header.type = PERF_RECORD_HEADER_FEATURE;
2282 		fe->header.size = ff.offset;
2283 
2284 		ret = process(tool, ff.buf, NULL, NULL);
2285 		if (ret) {
2286 			free(ff.buf);
2287 			return ret;
2288 		}
2289 	}
2290 
2291 	/* Send HEADER_LAST_FEATURE mark. */
2292 	fe = ff.buf;
2293 	fe->feat_id     = HEADER_LAST_FEATURE;
2294 	fe->header.type = PERF_RECORD_HEADER_FEATURE;
2295 	fe->header.size = sizeof(*fe);
2296 
2297 	ret = process(tool, ff.buf, NULL, NULL);
2298 
2299 	free(ff.buf);
2300 	return ret;
2301 }
2302 
2303 int perf_event__synthesize_for_pipe(struct perf_tool *tool,
2304 				    struct perf_session *session,
2305 				    struct perf_data *data,
2306 				    perf_event__handler_t process)
2307 {
2308 	int err;
2309 	int ret = 0;
2310 	struct evlist *evlist = session->evlist;
2311 
2312 	/*
2313 	 * We need to synthesize events first, because some
2314 	 * features works on top of them (on report side).
2315 	 */
2316 	err = perf_event__synthesize_attrs(tool, evlist, process);
2317 	if (err < 0) {
2318 		pr_err("Couldn't synthesize attrs.\n");
2319 		return err;
2320 	}
2321 	ret += err;
2322 
2323 	err = perf_event__synthesize_features(tool, session, evlist, process);
2324 	if (err < 0) {
2325 		pr_err("Couldn't synthesize features.\n");
2326 		return err;
2327 	}
2328 	ret += err;
2329 
2330 	if (have_tracepoints(&evlist->core.entries)) {
2331 		int fd = perf_data__fd(data);
2332 
2333 		/*
2334 		 * FIXME err <= 0 here actually means that
2335 		 * there were no tracepoints so its not really
2336 		 * an error, just that we don't need to
2337 		 * synthesize anything.  We really have to
2338 		 * return this more properly and also
2339 		 * propagate errors that now are calling die()
2340 		 */
2341 		err = perf_event__synthesize_tracing_data(tool,	fd, evlist,
2342 							  process);
2343 		if (err <= 0) {
2344 			pr_err("Couldn't record tracing data.\n");
2345 			return err;
2346 		}
2347 		ret += err;
2348 	}
2349 
2350 	return ret;
2351 }
2352 
2353 int parse_synth_opt(char *synth)
2354 {
2355 	char *p, *q;
2356 	int ret = 0;
2357 
2358 	if (synth == NULL)
2359 		return -1;
2360 
2361 	for (q = synth; (p = strsep(&q, ",")); p = q) {
2362 		if (!strcasecmp(p, "no") || !strcasecmp(p, "none"))
2363 			return 0;
2364 
2365 		if (!strcasecmp(p, "all"))
2366 			return PERF_SYNTH_ALL;
2367 
2368 		if (!strcasecmp(p, "task"))
2369 			ret |= PERF_SYNTH_TASK;
2370 		else if (!strcasecmp(p, "mmap"))
2371 			ret |= PERF_SYNTH_TASK | PERF_SYNTH_MMAP;
2372 		else if (!strcasecmp(p, "cgroup"))
2373 			ret |= PERF_SYNTH_CGROUP;
2374 		else
2375 			return -1;
2376 	}
2377 
2378 	return ret;
2379 }
2380