• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
perf_tool__process_synth_event(struct perf_tool * tool,union perf_event * event,struct machine * machine,perf_event__handler_t process)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  */
perf_event__get_comm_ids(pid_t pid,pid_t tid,char * comm,size_t len,pid_t * tgid,pid_t * ppid,bool * kernel)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 
perf_event__prepare_comm(union perf_event * event,pid_t pid,pid_t tid,struct machine * machine,pid_t * tgid,pid_t * ppid,bool * kernel)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 
perf_event__synthesize_comm(struct perf_tool * tool,union perf_event * event,pid_t pid,perf_event__handler_t process,struct machine * machine)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 
perf_event__get_ns_link_info(pid_t pid,const char * ns,struct perf_ns_link_info * ns_link_info)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 
perf_event__synthesize_namespaces(struct perf_tool * tool,union perf_event * event,pid_t pid,pid_t tgid,perf_event__handler_t process,struct machine * machine)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 
perf_event__synthesize_fork(struct perf_tool * tool,union perf_event * event,pid_t pid,pid_t tgid,pid_t ppid,perf_event__handler_t process,struct machine * machine)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 
read_proc_maps_line(struct io * io,__u64 * start,__u64 * end,u32 * prot,u32 * flags,__u64 * offset,u32 * maj,u32 * min,__u64 * inode,ssize_t pathname_size,char * pathname)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 
perf_record_mmap2__read_build_id(struct perf_record_mmap2 * event,bool is_kernel)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 	struct nsinfo *nsi;
371 	struct nscookie nc;
372 	int rc;
373 
374 	if (is_kernel) {
375 		rc = sysfs__read_build_id("/sys/kernel/notes", &bid);
376 		goto out;
377 	}
378 
379 	nsi = nsinfo__new(event->pid);
380 	nsinfo__mountns_enter(nsi, &nc);
381 
382 	rc = filename__read_build_id(event->filename, &bid) > 0 ? 0 : -1;
383 
384 	nsinfo__mountns_exit(&nc);
385 	nsinfo__put(nsi);
386 
387 out:
388 	if (rc == 0) {
389 		memcpy(event->build_id, bid.data, sizeof(bid.data));
390 		event->build_id_size = (u8) bid.size;
391 		event->header.misc |= PERF_RECORD_MISC_MMAP_BUILD_ID;
392 		event->__reserved_1 = 0;
393 		event->__reserved_2 = 0;
394 	} else {
395 		if (event->filename[0] == '/') {
396 			pr_debug2("Failed to read build ID for %s\n",
397 				  event->filename);
398 		}
399 	}
400 }
401 
perf_event__synthesize_mmap_events(struct perf_tool * tool,union perf_event * event,pid_t pid,pid_t tgid,perf_event__handler_t process,struct machine * machine,bool mmap_data)402 int perf_event__synthesize_mmap_events(struct perf_tool *tool,
403 				       union perf_event *event,
404 				       pid_t pid, pid_t tgid,
405 				       perf_event__handler_t process,
406 				       struct machine *machine,
407 				       bool mmap_data)
408 {
409 	unsigned long long t;
410 	char bf[BUFSIZ];
411 	struct io io;
412 	bool truncation = false;
413 	unsigned long long timeout = proc_map_timeout * 1000000ULL;
414 	int rc = 0;
415 	const char *hugetlbfs_mnt = hugetlbfs__mountpoint();
416 	int hugetlbfs_mnt_len = hugetlbfs_mnt ? strlen(hugetlbfs_mnt) : 0;
417 
418 	if (machine__is_default_guest(machine))
419 		return 0;
420 
421 	snprintf(bf, sizeof(bf), "%s/proc/%d/task/%d/maps",
422 		machine->root_dir, pid, pid);
423 
424 	io.fd = open(bf, O_RDONLY, 0);
425 	if (io.fd < 0) {
426 		/*
427 		 * We raced with a task exiting - just return:
428 		 */
429 		pr_debug("couldn't open %s\n", bf);
430 		return -1;
431 	}
432 	io__init(&io, io.fd, bf, sizeof(bf));
433 
434 	event->header.type = PERF_RECORD_MMAP2;
435 	t = rdclock();
436 
437 	while (!io.eof) {
438 		static const char anonstr[] = "//anon";
439 		size_t size, aligned_size;
440 
441 		/* ensure null termination since stack will be reused. */
442 		event->mmap2.filename[0] = '\0';
443 
444 		/* 00400000-0040c000 r-xp 00000000 fd:01 41038  /bin/cat */
445 		if (!read_proc_maps_line(&io,
446 					&event->mmap2.start,
447 					&event->mmap2.len,
448 					&event->mmap2.prot,
449 					&event->mmap2.flags,
450 					&event->mmap2.pgoff,
451 					&event->mmap2.maj,
452 					&event->mmap2.min,
453 					&event->mmap2.ino,
454 					sizeof(event->mmap2.filename),
455 					event->mmap2.filename))
456 			continue;
457 
458 		if ((rdclock() - t) > timeout) {
459 			pr_warning("Reading %s/proc/%d/task/%d/maps time out. "
460 				   "You may want to increase "
461 				   "the time limit by --proc-map-timeout\n",
462 				   machine->root_dir, pid, pid);
463 			truncation = true;
464 			goto out;
465 		}
466 
467 		event->mmap2.ino_generation = 0;
468 
469 		/*
470 		 * Just like the kernel, see __perf_event_mmap in kernel/perf_event.c
471 		 */
472 		if (machine__is_host(machine))
473 			event->header.misc = PERF_RECORD_MISC_USER;
474 		else
475 			event->header.misc = PERF_RECORD_MISC_GUEST_USER;
476 
477 		if ((event->mmap2.prot & PROT_EXEC) == 0) {
478 			if (!mmap_data || (event->mmap2.prot & PROT_READ) == 0)
479 				continue;
480 
481 			event->header.misc |= PERF_RECORD_MISC_MMAP_DATA;
482 		}
483 
484 out:
485 		if (truncation)
486 			event->header.misc |= PERF_RECORD_MISC_PROC_MAP_PARSE_TIMEOUT;
487 
488 		if (!strcmp(event->mmap2.filename, ""))
489 			strcpy(event->mmap2.filename, anonstr);
490 
491 		if (hugetlbfs_mnt_len &&
492 		    !strncmp(event->mmap2.filename, hugetlbfs_mnt,
493 			     hugetlbfs_mnt_len)) {
494 			strcpy(event->mmap2.filename, anonstr);
495 			event->mmap2.flags |= MAP_HUGETLB;
496 		}
497 
498 		size = strlen(event->mmap2.filename) + 1;
499 		aligned_size = PERF_ALIGN(size, sizeof(u64));
500 		event->mmap2.len -= event->mmap.start;
501 		event->mmap2.header.size = (sizeof(event->mmap2) -
502 					(sizeof(event->mmap2.filename) - aligned_size));
503 		memset(event->mmap2.filename + size, 0, machine->id_hdr_size +
504 			(aligned_size - size));
505 		event->mmap2.header.size += machine->id_hdr_size;
506 		event->mmap2.pid = tgid;
507 		event->mmap2.tid = pid;
508 
509 		if (symbol_conf.buildid_mmap2)
510 			perf_record_mmap2__read_build_id(&event->mmap2, false);
511 
512 		if (perf_tool__process_synth_event(tool, event, machine, process) != 0) {
513 			rc = -1;
514 			break;
515 		}
516 
517 		if (truncation)
518 			break;
519 	}
520 
521 	close(io.fd);
522 	return rc;
523 }
524 
525 #ifdef HAVE_FILE_HANDLE
perf_event__synthesize_cgroup(struct perf_tool * tool,union perf_event * event,char * path,size_t mount_len,perf_event__handler_t process,struct machine * machine)526 static int perf_event__synthesize_cgroup(struct perf_tool *tool,
527 					 union perf_event *event,
528 					 char *path, size_t mount_len,
529 					 perf_event__handler_t process,
530 					 struct machine *machine)
531 {
532 	size_t event_size = sizeof(event->cgroup) - sizeof(event->cgroup.path);
533 	size_t path_len = strlen(path) - mount_len + 1;
534 	struct {
535 		struct file_handle fh;
536 		uint64_t cgroup_id;
537 	} handle;
538 	int mount_id;
539 
540 	while (path_len % sizeof(u64))
541 		path[mount_len + path_len++] = '\0';
542 
543 	memset(&event->cgroup, 0, event_size);
544 
545 	event->cgroup.header.type = PERF_RECORD_CGROUP;
546 	event->cgroup.header.size = event_size + path_len + machine->id_hdr_size;
547 
548 	handle.fh.handle_bytes = sizeof(handle.cgroup_id);
549 	if (name_to_handle_at(AT_FDCWD, path, &handle.fh, &mount_id, 0) < 0) {
550 		pr_debug("stat failed: %s\n", path);
551 		return -1;
552 	}
553 
554 	event->cgroup.id = handle.cgroup_id;
555 	strncpy(event->cgroup.path, path + mount_len, path_len);
556 	memset(event->cgroup.path + path_len, 0, machine->id_hdr_size);
557 
558 	if (perf_tool__process_synth_event(tool, event, machine, process) < 0) {
559 		pr_debug("process synth event failed\n");
560 		return -1;
561 	}
562 
563 	return 0;
564 }
565 
perf_event__walk_cgroup_tree(struct perf_tool * tool,union perf_event * event,char * path,size_t mount_len,perf_event__handler_t process,struct machine * machine)566 static int perf_event__walk_cgroup_tree(struct perf_tool *tool,
567 					union perf_event *event,
568 					char *path, size_t mount_len,
569 					perf_event__handler_t process,
570 					struct machine *machine)
571 {
572 	size_t pos = strlen(path);
573 	DIR *d;
574 	struct dirent *dent;
575 	int ret = 0;
576 
577 	if (perf_event__synthesize_cgroup(tool, event, path, mount_len,
578 					  process, machine) < 0)
579 		return -1;
580 
581 	d = opendir(path);
582 	if (d == NULL) {
583 		pr_debug("failed to open directory: %s\n", path);
584 		return -1;
585 	}
586 
587 	while ((dent = readdir(d)) != NULL) {
588 		if (dent->d_type != DT_DIR)
589 			continue;
590 		if (!strcmp(dent->d_name, ".") ||
591 		    !strcmp(dent->d_name, ".."))
592 			continue;
593 
594 		/* any sane path should be less than PATH_MAX */
595 		if (strlen(path) + strlen(dent->d_name) + 1 >= PATH_MAX)
596 			continue;
597 
598 		if (path[pos - 1] != '/')
599 			strcat(path, "/");
600 		strcat(path, dent->d_name);
601 
602 		ret = perf_event__walk_cgroup_tree(tool, event, path,
603 						   mount_len, process, machine);
604 		if (ret < 0)
605 			break;
606 
607 		path[pos] = '\0';
608 	}
609 
610 	closedir(d);
611 	return ret;
612 }
613 
perf_event__synthesize_cgroups(struct perf_tool * tool,perf_event__handler_t process,struct machine * machine)614 int perf_event__synthesize_cgroups(struct perf_tool *tool,
615 				   perf_event__handler_t process,
616 				   struct machine *machine)
617 {
618 	union perf_event event;
619 	char cgrp_root[PATH_MAX];
620 	size_t mount_len;  /* length of mount point in the path */
621 
622 	if (!tool || !tool->cgroup_events)
623 		return 0;
624 
625 	if (cgroupfs_find_mountpoint(cgrp_root, PATH_MAX, "perf_event") < 0) {
626 		pr_debug("cannot find cgroup mount point\n");
627 		return -1;
628 	}
629 
630 	mount_len = strlen(cgrp_root);
631 	/* make sure the path starts with a slash (after mount point) */
632 	strcat(cgrp_root, "/");
633 
634 	if (perf_event__walk_cgroup_tree(tool, &event, cgrp_root, mount_len,
635 					 process, machine) < 0)
636 		return -1;
637 
638 	return 0;
639 }
640 #else
perf_event__synthesize_cgroups(struct perf_tool * tool __maybe_unused,perf_event__handler_t process __maybe_unused,struct machine * machine __maybe_unused)641 int perf_event__synthesize_cgroups(struct perf_tool *tool __maybe_unused,
642 				   perf_event__handler_t process __maybe_unused,
643 				   struct machine *machine __maybe_unused)
644 {
645 	return -1;
646 }
647 #endif
648 
perf_event__synthesize_modules(struct perf_tool * tool,perf_event__handler_t process,struct machine * machine)649 int perf_event__synthesize_modules(struct perf_tool *tool, perf_event__handler_t process,
650 				   struct machine *machine)
651 {
652 	int rc = 0;
653 	struct map *pos;
654 	struct maps *maps = machine__kernel_maps(machine);
655 	union perf_event *event;
656 	size_t size = symbol_conf.buildid_mmap2 ?
657 			sizeof(event->mmap2) : sizeof(event->mmap);
658 
659 	event = zalloc(size + machine->id_hdr_size);
660 	if (event == NULL) {
661 		pr_debug("Not enough memory synthesizing mmap event "
662 			 "for kernel modules\n");
663 		return -1;
664 	}
665 
666 	/*
667 	 * kernel uses 0 for user space maps, see kernel/perf_event.c
668 	 * __perf_event_mmap
669 	 */
670 	if (machine__is_host(machine))
671 		event->header.misc = PERF_RECORD_MISC_KERNEL;
672 	else
673 		event->header.misc = PERF_RECORD_MISC_GUEST_KERNEL;
674 
675 	maps__for_each_entry(maps, pos) {
676 		if (!__map__is_kmodule(pos))
677 			continue;
678 
679 		if (symbol_conf.buildid_mmap2) {
680 			size = PERF_ALIGN(pos->dso->long_name_len + 1, sizeof(u64));
681 			event->mmap2.header.type = PERF_RECORD_MMAP2;
682 			event->mmap2.header.size = (sizeof(event->mmap2) -
683 						(sizeof(event->mmap2.filename) - size));
684 			memset(event->mmap2.filename + size, 0, machine->id_hdr_size);
685 			event->mmap2.header.size += machine->id_hdr_size;
686 			event->mmap2.start = pos->start;
687 			event->mmap2.len   = pos->end - pos->start;
688 			event->mmap2.pid   = machine->pid;
689 
690 			memcpy(event->mmap2.filename, pos->dso->long_name,
691 			       pos->dso->long_name_len + 1);
692 
693 			perf_record_mmap2__read_build_id(&event->mmap2, false);
694 		} else {
695 			size = PERF_ALIGN(pos->dso->long_name_len + 1, sizeof(u64));
696 			event->mmap.header.type = PERF_RECORD_MMAP;
697 			event->mmap.header.size = (sizeof(event->mmap) -
698 						(sizeof(event->mmap.filename) - size));
699 			memset(event->mmap.filename + size, 0, machine->id_hdr_size);
700 			event->mmap.header.size += machine->id_hdr_size;
701 			event->mmap.start = pos->start;
702 			event->mmap.len   = pos->end - pos->start;
703 			event->mmap.pid   = machine->pid;
704 
705 			memcpy(event->mmap.filename, pos->dso->long_name,
706 			       pos->dso->long_name_len + 1);
707 		}
708 
709 		if (perf_tool__process_synth_event(tool, event, machine, process) != 0) {
710 			rc = -1;
711 			break;
712 		}
713 	}
714 
715 	free(event);
716 	return rc;
717 }
718 
filter_task(const struct dirent * dirent)719 static int filter_task(const struct dirent *dirent)
720 {
721 	return isdigit(dirent->d_name[0]);
722 }
723 
__event__synthesize_thread(union perf_event * comm_event,union perf_event * mmap_event,union perf_event * fork_event,union perf_event * namespaces_event,pid_t pid,int full,perf_event__handler_t process,struct perf_tool * tool,struct machine * machine,bool mmap_data)724 static int __event__synthesize_thread(union perf_event *comm_event,
725 				      union perf_event *mmap_event,
726 				      union perf_event *fork_event,
727 				      union perf_event *namespaces_event,
728 				      pid_t pid, int full, perf_event__handler_t process,
729 				      struct perf_tool *tool, struct machine *machine, bool mmap_data)
730 {
731 	char filename[PATH_MAX];
732 	struct dirent **dirent;
733 	pid_t tgid, ppid;
734 	int rc = 0;
735 	int i, n;
736 
737 	/* special case: only send one comm event using passed in pid */
738 	if (!full) {
739 		tgid = perf_event__synthesize_comm(tool, comm_event, pid,
740 						   process, machine);
741 
742 		if (tgid == -1)
743 			return -1;
744 
745 		if (perf_event__synthesize_namespaces(tool, namespaces_event, pid,
746 						      tgid, process, machine) < 0)
747 			return -1;
748 
749 		/*
750 		 * send mmap only for thread group leader
751 		 * see thread__init_maps()
752 		 */
753 		if (pid == tgid &&
754 		    perf_event__synthesize_mmap_events(tool, mmap_event, pid, tgid,
755 						       process, machine, mmap_data))
756 			return -1;
757 
758 		return 0;
759 	}
760 
761 	if (machine__is_default_guest(machine))
762 		return 0;
763 
764 	snprintf(filename, sizeof(filename), "%s/proc/%d/task",
765 		 machine->root_dir, pid);
766 
767 	n = scandir(filename, &dirent, filter_task, alphasort);
768 	if (n < 0)
769 		return n;
770 
771 	for (i = 0; i < n; i++) {
772 		char *end;
773 		pid_t _pid;
774 		bool kernel_thread = false;
775 
776 		_pid = strtol(dirent[i]->d_name, &end, 10);
777 		if (*end)
778 			continue;
779 
780 		rc = -1;
781 		if (perf_event__prepare_comm(comm_event, pid, _pid, machine,
782 					     &tgid, &ppid, &kernel_thread) != 0)
783 			break;
784 
785 		if (perf_event__synthesize_fork(tool, fork_event, _pid, tgid,
786 						ppid, process, machine) < 0)
787 			break;
788 
789 		if (perf_event__synthesize_namespaces(tool, namespaces_event, _pid,
790 						      tgid, process, machine) < 0)
791 			break;
792 
793 		/*
794 		 * Send the prepared comm event
795 		 */
796 		if (perf_tool__process_synth_event(tool, comm_event, machine, process) != 0)
797 			break;
798 
799 		rc = 0;
800 		if (_pid == pid && !kernel_thread) {
801 			/* process the parent's maps too */
802 			rc = perf_event__synthesize_mmap_events(tool, mmap_event, pid, tgid,
803 						process, machine, mmap_data);
804 			if (rc)
805 				break;
806 		}
807 	}
808 
809 	for (i = 0; i < n; i++)
810 		zfree(&dirent[i]);
811 	free(dirent);
812 
813 	return rc;
814 }
815 
perf_event__synthesize_thread_map(struct perf_tool * tool,struct perf_thread_map * threads,perf_event__handler_t process,struct machine * machine,bool mmap_data)816 int perf_event__synthesize_thread_map(struct perf_tool *tool,
817 				      struct perf_thread_map *threads,
818 				      perf_event__handler_t process,
819 				      struct machine *machine,
820 				      bool mmap_data)
821 {
822 	union perf_event *comm_event, *mmap_event, *fork_event;
823 	union perf_event *namespaces_event;
824 	int err = -1, thread, j;
825 
826 	comm_event = malloc(sizeof(comm_event->comm) + machine->id_hdr_size);
827 	if (comm_event == NULL)
828 		goto out;
829 
830 	mmap_event = malloc(sizeof(mmap_event->mmap2) + machine->id_hdr_size);
831 	if (mmap_event == NULL)
832 		goto out_free_comm;
833 
834 	fork_event = malloc(sizeof(fork_event->fork) + machine->id_hdr_size);
835 	if (fork_event == NULL)
836 		goto out_free_mmap;
837 
838 	namespaces_event = malloc(sizeof(namespaces_event->namespaces) +
839 				  (NR_NAMESPACES * sizeof(struct perf_ns_link_info)) +
840 				  machine->id_hdr_size);
841 	if (namespaces_event == NULL)
842 		goto out_free_fork;
843 
844 	err = 0;
845 	for (thread = 0; thread < threads->nr; ++thread) {
846 		if (__event__synthesize_thread(comm_event, mmap_event,
847 					       fork_event, namespaces_event,
848 					       perf_thread_map__pid(threads, thread), 0,
849 					       process, tool, machine,
850 					       mmap_data)) {
851 			err = -1;
852 			break;
853 		}
854 
855 		/*
856 		 * comm.pid is set to thread group id by
857 		 * perf_event__synthesize_comm
858 		 */
859 		if ((int) comm_event->comm.pid != perf_thread_map__pid(threads, thread)) {
860 			bool need_leader = true;
861 
862 			/* is thread group leader in thread_map? */
863 			for (j = 0; j < threads->nr; ++j) {
864 				if ((int) comm_event->comm.pid == perf_thread_map__pid(threads, j)) {
865 					need_leader = false;
866 					break;
867 				}
868 			}
869 
870 			/* if not, generate events for it */
871 			if (need_leader &&
872 			    __event__synthesize_thread(comm_event, mmap_event,
873 						       fork_event, namespaces_event,
874 						       comm_event->comm.pid, 0,
875 						       process, tool, machine,
876 						       mmap_data)) {
877 				err = -1;
878 				break;
879 			}
880 		}
881 	}
882 	free(namespaces_event);
883 out_free_fork:
884 	free(fork_event);
885 out_free_mmap:
886 	free(mmap_event);
887 out_free_comm:
888 	free(comm_event);
889 out:
890 	return err;
891 }
892 
__perf_event__synthesize_threads(struct perf_tool * tool,perf_event__handler_t process,struct machine * machine,bool mmap_data,struct dirent ** dirent,int start,int num)893 static int __perf_event__synthesize_threads(struct perf_tool *tool,
894 					    perf_event__handler_t process,
895 					    struct machine *machine,
896 					    bool mmap_data,
897 					    struct dirent **dirent,
898 					    int start,
899 					    int num)
900 {
901 	union perf_event *comm_event, *mmap_event, *fork_event;
902 	union perf_event *namespaces_event;
903 	int err = -1;
904 	char *end;
905 	pid_t pid;
906 	int i;
907 
908 	comm_event = malloc(sizeof(comm_event->comm) + machine->id_hdr_size);
909 	if (comm_event == NULL)
910 		goto out;
911 
912 	mmap_event = malloc(sizeof(mmap_event->mmap2) + machine->id_hdr_size);
913 	if (mmap_event == NULL)
914 		goto out_free_comm;
915 
916 	fork_event = malloc(sizeof(fork_event->fork) + machine->id_hdr_size);
917 	if (fork_event == NULL)
918 		goto out_free_mmap;
919 
920 	namespaces_event = malloc(sizeof(namespaces_event->namespaces) +
921 				  (NR_NAMESPACES * sizeof(struct perf_ns_link_info)) +
922 				  machine->id_hdr_size);
923 	if (namespaces_event == NULL)
924 		goto out_free_fork;
925 
926 	for (i = start; i < start + num; i++) {
927 		if (!isdigit(dirent[i]->d_name[0]))
928 			continue;
929 
930 		pid = (pid_t)strtol(dirent[i]->d_name, &end, 10);
931 		/* only interested in proper numerical dirents */
932 		if (*end)
933 			continue;
934 		/*
935 		 * We may race with exiting thread, so don't stop just because
936 		 * one thread couldn't be synthesized.
937 		 */
938 		__event__synthesize_thread(comm_event, mmap_event, fork_event,
939 					   namespaces_event, pid, 1, process,
940 					   tool, machine, mmap_data);
941 	}
942 	err = 0;
943 
944 	free(namespaces_event);
945 out_free_fork:
946 	free(fork_event);
947 out_free_mmap:
948 	free(mmap_event);
949 out_free_comm:
950 	free(comm_event);
951 out:
952 	return err;
953 }
954 
955 struct synthesize_threads_arg {
956 	struct perf_tool *tool;
957 	perf_event__handler_t process;
958 	struct machine *machine;
959 	bool mmap_data;
960 	struct dirent **dirent;
961 	int num;
962 	int start;
963 };
964 
synthesize_threads_worker(void * arg)965 static void *synthesize_threads_worker(void *arg)
966 {
967 	struct synthesize_threads_arg *args = arg;
968 
969 	__perf_event__synthesize_threads(args->tool, args->process,
970 					 args->machine, args->mmap_data,
971 					 args->dirent,
972 					 args->start, args->num);
973 	return NULL;
974 }
975 
perf_event__synthesize_threads(struct perf_tool * tool,perf_event__handler_t process,struct machine * machine,bool mmap_data,unsigned int nr_threads_synthesize)976 int perf_event__synthesize_threads(struct perf_tool *tool,
977 				   perf_event__handler_t process,
978 				   struct machine *machine,
979 				   bool mmap_data,
980 				   unsigned int nr_threads_synthesize)
981 {
982 	struct synthesize_threads_arg *args = NULL;
983 	pthread_t *synthesize_threads = NULL;
984 	char proc_path[PATH_MAX];
985 	struct dirent **dirent;
986 	int num_per_thread;
987 	int m, n, i, j;
988 	int thread_nr;
989 	int base = 0;
990 	int err = -1;
991 
992 
993 	if (machine__is_default_guest(machine))
994 		return 0;
995 
996 	snprintf(proc_path, sizeof(proc_path), "%s/proc", machine->root_dir);
997 	n = scandir(proc_path, &dirent, filter_task, alphasort);
998 	if (n < 0)
999 		return err;
1000 
1001 	if (nr_threads_synthesize == UINT_MAX)
1002 		thread_nr = sysconf(_SC_NPROCESSORS_ONLN);
1003 	else
1004 		thread_nr = nr_threads_synthesize;
1005 
1006 	if (thread_nr <= 1) {
1007 		err = __perf_event__synthesize_threads(tool, process,
1008 						       machine, mmap_data,
1009 						       dirent, base, n);
1010 		goto free_dirent;
1011 	}
1012 	if (thread_nr > n)
1013 		thread_nr = n;
1014 
1015 	synthesize_threads = calloc(sizeof(pthread_t), thread_nr);
1016 	if (synthesize_threads == NULL)
1017 		goto free_dirent;
1018 
1019 	args = calloc(sizeof(*args), thread_nr);
1020 	if (args == NULL)
1021 		goto free_threads;
1022 
1023 	num_per_thread = n / thread_nr;
1024 	m = n % thread_nr;
1025 	for (i = 0; i < thread_nr; i++) {
1026 		args[i].tool = tool;
1027 		args[i].process = process;
1028 		args[i].machine = machine;
1029 		args[i].mmap_data = mmap_data;
1030 		args[i].dirent = dirent;
1031 	}
1032 	for (i = 0; i < m; i++) {
1033 		args[i].num = num_per_thread + 1;
1034 		args[i].start = i * args[i].num;
1035 	}
1036 	if (i != 0)
1037 		base = args[i-1].start + args[i-1].num;
1038 	for (j = i; j < thread_nr; j++) {
1039 		args[j].num = num_per_thread;
1040 		args[j].start = base + (j - i) * args[i].num;
1041 	}
1042 
1043 	for (i = 0; i < thread_nr; i++) {
1044 		if (pthread_create(&synthesize_threads[i], NULL,
1045 				   synthesize_threads_worker, &args[i]))
1046 			goto out_join;
1047 	}
1048 	err = 0;
1049 out_join:
1050 	for (i = 0; i < thread_nr; i++)
1051 		pthread_join(synthesize_threads[i], NULL);
1052 	free(args);
1053 free_threads:
1054 	free(synthesize_threads);
1055 free_dirent:
1056 	for (i = 0; i < n; i++)
1057 		zfree(&dirent[i]);
1058 	free(dirent);
1059 
1060 	return err;
1061 }
1062 
perf_event__synthesize_extra_kmaps(struct perf_tool * tool __maybe_unused,perf_event__handler_t process __maybe_unused,struct machine * machine __maybe_unused)1063 int __weak perf_event__synthesize_extra_kmaps(struct perf_tool *tool __maybe_unused,
1064 					      perf_event__handler_t process __maybe_unused,
1065 					      struct machine *machine __maybe_unused)
1066 {
1067 	return 0;
1068 }
1069 
__perf_event__synthesize_kernel_mmap(struct perf_tool * tool,perf_event__handler_t process,struct machine * machine)1070 static int __perf_event__synthesize_kernel_mmap(struct perf_tool *tool,
1071 						perf_event__handler_t process,
1072 						struct machine *machine)
1073 {
1074 	union perf_event *event;
1075 	size_t size = symbol_conf.buildid_mmap2 ?
1076 			sizeof(event->mmap2) : sizeof(event->mmap);
1077 	struct map *map = machine__kernel_map(machine);
1078 	struct kmap *kmap;
1079 	int err;
1080 
1081 	if (map == NULL)
1082 		return -1;
1083 
1084 	kmap = map__kmap(map);
1085 	if (!kmap->ref_reloc_sym)
1086 		return -1;
1087 
1088 	/*
1089 	 * We should get this from /sys/kernel/sections/.text, but till that is
1090 	 * available use this, and after it is use this as a fallback for older
1091 	 * kernels.
1092 	 */
1093 	event = zalloc(size + machine->id_hdr_size);
1094 	if (event == NULL) {
1095 		pr_debug("Not enough memory synthesizing mmap event "
1096 			 "for kernel modules\n");
1097 		return -1;
1098 	}
1099 
1100 	if (machine__is_host(machine)) {
1101 		/*
1102 		 * kernel uses PERF_RECORD_MISC_USER for user space maps,
1103 		 * see kernel/perf_event.c __perf_event_mmap
1104 		 */
1105 		event->header.misc = PERF_RECORD_MISC_KERNEL;
1106 	} else {
1107 		event->header.misc = PERF_RECORD_MISC_GUEST_KERNEL;
1108 	}
1109 
1110 	if (symbol_conf.buildid_mmap2) {
1111 		size = snprintf(event->mmap2.filename, sizeof(event->mmap2.filename),
1112 				"%s%s", machine->mmap_name, kmap->ref_reloc_sym->name) + 1;
1113 		size = PERF_ALIGN(size, sizeof(u64));
1114 		event->mmap2.header.type = PERF_RECORD_MMAP2;
1115 		event->mmap2.header.size = (sizeof(event->mmap2) -
1116 				(sizeof(event->mmap2.filename) - size) + machine->id_hdr_size);
1117 		event->mmap2.pgoff = kmap->ref_reloc_sym->addr;
1118 		event->mmap2.start = map->start;
1119 		event->mmap2.len   = map->end - event->mmap.start;
1120 		event->mmap2.pid   = machine->pid;
1121 
1122 		perf_record_mmap2__read_build_id(&event->mmap2, true);
1123 	} else {
1124 		size = snprintf(event->mmap.filename, sizeof(event->mmap.filename),
1125 				"%s%s", machine->mmap_name, kmap->ref_reloc_sym->name) + 1;
1126 		size = PERF_ALIGN(size, sizeof(u64));
1127 		event->mmap.header.type = PERF_RECORD_MMAP;
1128 		event->mmap.header.size = (sizeof(event->mmap) -
1129 				(sizeof(event->mmap.filename) - size) + machine->id_hdr_size);
1130 		event->mmap.pgoff = kmap->ref_reloc_sym->addr;
1131 		event->mmap.start = map->start;
1132 		event->mmap.len   = map->end - event->mmap.start;
1133 		event->mmap.pid   = machine->pid;
1134 	}
1135 
1136 	err = perf_tool__process_synth_event(tool, event, machine, process);
1137 	free(event);
1138 
1139 	return err;
1140 }
1141 
perf_event__synthesize_kernel_mmap(struct perf_tool * tool,perf_event__handler_t process,struct machine * machine)1142 int perf_event__synthesize_kernel_mmap(struct perf_tool *tool,
1143 				       perf_event__handler_t process,
1144 				       struct machine *machine)
1145 {
1146 	int err;
1147 
1148 	err = __perf_event__synthesize_kernel_mmap(tool, process, machine);
1149 	if (err < 0)
1150 		return err;
1151 
1152 	return perf_event__synthesize_extra_kmaps(tool, process, machine);
1153 }
1154 
perf_event__synthesize_thread_map2(struct perf_tool * tool,struct perf_thread_map * threads,perf_event__handler_t process,struct machine * machine)1155 int perf_event__synthesize_thread_map2(struct perf_tool *tool,
1156 				      struct perf_thread_map *threads,
1157 				      perf_event__handler_t process,
1158 				      struct machine *machine)
1159 {
1160 	union perf_event *event;
1161 	int i, err, size;
1162 
1163 	size  = sizeof(event->thread_map);
1164 	size +=	threads->nr * sizeof(event->thread_map.entries[0]);
1165 
1166 	event = zalloc(size);
1167 	if (!event)
1168 		return -ENOMEM;
1169 
1170 	event->header.type = PERF_RECORD_THREAD_MAP;
1171 	event->header.size = size;
1172 	event->thread_map.nr = threads->nr;
1173 
1174 	for (i = 0; i < threads->nr; i++) {
1175 		struct perf_record_thread_map_entry *entry = &event->thread_map.entries[i];
1176 		char *comm = perf_thread_map__comm(threads, i);
1177 
1178 		if (!comm)
1179 			comm = (char *) "";
1180 
1181 		entry->pid = perf_thread_map__pid(threads, i);
1182 		strncpy((char *) &entry->comm, comm, sizeof(entry->comm));
1183 	}
1184 
1185 	err = process(tool, event, NULL, machine);
1186 
1187 	free(event);
1188 	return err;
1189 }
1190 
synthesize_cpus(struct cpu_map_entries * cpus,struct perf_cpu_map * map)1191 static void synthesize_cpus(struct cpu_map_entries *cpus,
1192 			    struct perf_cpu_map *map)
1193 {
1194 	int i;
1195 
1196 	cpus->nr = map->nr;
1197 
1198 	for (i = 0; i < map->nr; i++)
1199 		cpus->cpu[i] = map->map[i];
1200 }
1201 
synthesize_mask(struct perf_record_record_cpu_map * mask,struct perf_cpu_map * map,int max)1202 static void synthesize_mask(struct perf_record_record_cpu_map *mask,
1203 			    struct perf_cpu_map *map, int max)
1204 {
1205 	int i;
1206 
1207 	mask->nr = BITS_TO_LONGS(max);
1208 	mask->long_size = sizeof(long);
1209 
1210 	for (i = 0; i < map->nr; i++)
1211 		set_bit(map->map[i], mask->mask);
1212 }
1213 
cpus_size(struct perf_cpu_map * map)1214 static size_t cpus_size(struct perf_cpu_map *map)
1215 {
1216 	return sizeof(struct cpu_map_entries) + map->nr * sizeof(u16);
1217 }
1218 
mask_size(struct perf_cpu_map * map,int * max)1219 static size_t mask_size(struct perf_cpu_map *map, int *max)
1220 {
1221 	int i;
1222 
1223 	*max = 0;
1224 
1225 	for (i = 0; i < map->nr; i++) {
1226 		/* bit position of the cpu is + 1 */
1227 		int bit = map->map[i] + 1;
1228 
1229 		if (bit > *max)
1230 			*max = bit;
1231 	}
1232 
1233 	return sizeof(struct perf_record_record_cpu_map) + BITS_TO_LONGS(*max) * sizeof(long);
1234 }
1235 
cpu_map_data__alloc(struct perf_cpu_map * map,size_t * size,u16 * type,int * max)1236 void *cpu_map_data__alloc(struct perf_cpu_map *map, size_t *size, u16 *type, int *max)
1237 {
1238 	size_t size_cpus, size_mask;
1239 	bool is_dummy = perf_cpu_map__empty(map);
1240 
1241 	/*
1242 	 * Both array and mask data have variable size based
1243 	 * on the number of cpus and their actual values.
1244 	 * The size of the 'struct perf_record_cpu_map_data' is:
1245 	 *
1246 	 *   array = size of 'struct cpu_map_entries' +
1247 	 *           number of cpus * sizeof(u64)
1248 	 *
1249 	 *   mask  = size of 'struct perf_record_record_cpu_map' +
1250 	 *           maximum cpu bit converted to size of longs
1251 	 *
1252 	 * and finally + the size of 'struct perf_record_cpu_map_data'.
1253 	 */
1254 	size_cpus = cpus_size(map);
1255 	size_mask = mask_size(map, max);
1256 
1257 	if (is_dummy || (size_cpus < size_mask)) {
1258 		*size += size_cpus;
1259 		*type  = PERF_CPU_MAP__CPUS;
1260 	} else {
1261 		*size += size_mask;
1262 		*type  = PERF_CPU_MAP__MASK;
1263 	}
1264 
1265 	*size += sizeof(struct perf_record_cpu_map_data);
1266 	*size = PERF_ALIGN(*size, sizeof(u64));
1267 	return zalloc(*size);
1268 }
1269 
cpu_map_data__synthesize(struct perf_record_cpu_map_data * data,struct perf_cpu_map * map,u16 type,int max)1270 void cpu_map_data__synthesize(struct perf_record_cpu_map_data *data, struct perf_cpu_map *map,
1271 			      u16 type, int max)
1272 {
1273 	data->type = type;
1274 
1275 	switch (type) {
1276 	case PERF_CPU_MAP__CPUS:
1277 		synthesize_cpus((struct cpu_map_entries *) data->data, map);
1278 		break;
1279 	case PERF_CPU_MAP__MASK:
1280 		synthesize_mask((struct perf_record_record_cpu_map *)data->data, map, max);
1281 	default:
1282 		break;
1283 	}
1284 }
1285 
cpu_map_event__new(struct perf_cpu_map * map)1286 static struct perf_record_cpu_map *cpu_map_event__new(struct perf_cpu_map *map)
1287 {
1288 	size_t size = sizeof(struct perf_record_cpu_map);
1289 	struct perf_record_cpu_map *event;
1290 	int max;
1291 	u16 type;
1292 
1293 	event = cpu_map_data__alloc(map, &size, &type, &max);
1294 	if (!event)
1295 		return NULL;
1296 
1297 	event->header.type = PERF_RECORD_CPU_MAP;
1298 	event->header.size = size;
1299 	event->data.type   = type;
1300 
1301 	cpu_map_data__synthesize(&event->data, map, type, max);
1302 	return event;
1303 }
1304 
perf_event__synthesize_cpu_map(struct perf_tool * tool,struct perf_cpu_map * map,perf_event__handler_t process,struct machine * machine)1305 int perf_event__synthesize_cpu_map(struct perf_tool *tool,
1306 				   struct perf_cpu_map *map,
1307 				   perf_event__handler_t process,
1308 				   struct machine *machine)
1309 {
1310 	struct perf_record_cpu_map *event;
1311 	int err;
1312 
1313 	event = cpu_map_event__new(map);
1314 	if (!event)
1315 		return -ENOMEM;
1316 
1317 	err = process(tool, (union perf_event *) event, NULL, machine);
1318 
1319 	free(event);
1320 	return err;
1321 }
1322 
perf_event__synthesize_stat_config(struct perf_tool * tool,struct perf_stat_config * config,perf_event__handler_t process,struct machine * machine)1323 int perf_event__synthesize_stat_config(struct perf_tool *tool,
1324 				       struct perf_stat_config *config,
1325 				       perf_event__handler_t process,
1326 				       struct machine *machine)
1327 {
1328 	struct perf_record_stat_config *event;
1329 	int size, i = 0, err;
1330 
1331 	size  = sizeof(*event);
1332 	size += (PERF_STAT_CONFIG_TERM__MAX * sizeof(event->data[0]));
1333 
1334 	event = zalloc(size);
1335 	if (!event)
1336 		return -ENOMEM;
1337 
1338 	event->header.type = PERF_RECORD_STAT_CONFIG;
1339 	event->header.size = size;
1340 	event->nr          = PERF_STAT_CONFIG_TERM__MAX;
1341 
1342 #define ADD(__term, __val)					\
1343 	event->data[i].tag = PERF_STAT_CONFIG_TERM__##__term;	\
1344 	event->data[i].val = __val;				\
1345 	i++;
1346 
1347 	ADD(AGGR_MODE,	config->aggr_mode)
1348 	ADD(INTERVAL,	config->interval)
1349 	ADD(SCALE,	config->scale)
1350 
1351 	WARN_ONCE(i != PERF_STAT_CONFIG_TERM__MAX,
1352 		  "stat config terms unbalanced\n");
1353 #undef ADD
1354 
1355 	err = process(tool, (union perf_event *) event, NULL, machine);
1356 
1357 	free(event);
1358 	return err;
1359 }
1360 
perf_event__synthesize_stat(struct perf_tool * tool,u32 cpu,u32 thread,u64 id,struct perf_counts_values * count,perf_event__handler_t process,struct machine * machine)1361 int perf_event__synthesize_stat(struct perf_tool *tool,
1362 				u32 cpu, u32 thread, u64 id,
1363 				struct perf_counts_values *count,
1364 				perf_event__handler_t process,
1365 				struct machine *machine)
1366 {
1367 	struct perf_record_stat event;
1368 
1369 	event.header.type = PERF_RECORD_STAT;
1370 	event.header.size = sizeof(event);
1371 	event.header.misc = 0;
1372 
1373 	event.id        = id;
1374 	event.cpu       = cpu;
1375 	event.thread    = thread;
1376 	event.val       = count->val;
1377 	event.ena       = count->ena;
1378 	event.run       = count->run;
1379 
1380 	return process(tool, (union perf_event *) &event, NULL, machine);
1381 }
1382 
perf_event__synthesize_stat_round(struct perf_tool * tool,u64 evtime,u64 type,perf_event__handler_t process,struct machine * machine)1383 int perf_event__synthesize_stat_round(struct perf_tool *tool,
1384 				      u64 evtime, u64 type,
1385 				      perf_event__handler_t process,
1386 				      struct machine *machine)
1387 {
1388 	struct perf_record_stat_round event;
1389 
1390 	event.header.type = PERF_RECORD_STAT_ROUND;
1391 	event.header.size = sizeof(event);
1392 	event.header.misc = 0;
1393 
1394 	event.time = evtime;
1395 	event.type = type;
1396 
1397 	return process(tool, (union perf_event *) &event, NULL, machine);
1398 }
1399 
perf_event__sample_event_size(const struct perf_sample * sample,u64 type,u64 read_format)1400 size_t perf_event__sample_event_size(const struct perf_sample *sample, u64 type, u64 read_format)
1401 {
1402 	size_t sz, result = sizeof(struct perf_record_sample);
1403 
1404 	if (type & PERF_SAMPLE_IDENTIFIER)
1405 		result += sizeof(u64);
1406 
1407 	if (type & PERF_SAMPLE_IP)
1408 		result += sizeof(u64);
1409 
1410 	if (type & PERF_SAMPLE_TID)
1411 		result += sizeof(u64);
1412 
1413 	if (type & PERF_SAMPLE_TIME)
1414 		result += sizeof(u64);
1415 
1416 	if (type & PERF_SAMPLE_ADDR)
1417 		result += sizeof(u64);
1418 
1419 	if (type & PERF_SAMPLE_ID)
1420 		result += sizeof(u64);
1421 
1422 	if (type & PERF_SAMPLE_STREAM_ID)
1423 		result += sizeof(u64);
1424 
1425 	if (type & PERF_SAMPLE_CPU)
1426 		result += sizeof(u64);
1427 
1428 	if (type & PERF_SAMPLE_PERIOD)
1429 		result += sizeof(u64);
1430 
1431 	if (type & PERF_SAMPLE_READ) {
1432 		result += sizeof(u64);
1433 		if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1434 			result += sizeof(u64);
1435 		if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1436 			result += sizeof(u64);
1437 		/* PERF_FORMAT_ID is forced for PERF_SAMPLE_READ */
1438 		if (read_format & PERF_FORMAT_GROUP) {
1439 			sz = sample->read.group.nr *
1440 			     sizeof(struct sample_read_value);
1441 			result += sz;
1442 		} else {
1443 			result += sizeof(u64);
1444 		}
1445 	}
1446 
1447 	if (type & PERF_SAMPLE_CALLCHAIN) {
1448 		sz = (sample->callchain->nr + 1) * sizeof(u64);
1449 		result += sz;
1450 	}
1451 
1452 	if (type & PERF_SAMPLE_RAW) {
1453 		result += sizeof(u32);
1454 		result += sample->raw_size;
1455 	}
1456 
1457 	if (type & PERF_SAMPLE_BRANCH_STACK) {
1458 		sz = sample->branch_stack->nr * sizeof(struct branch_entry);
1459 		/* nr, hw_idx */
1460 		sz += 2 * sizeof(u64);
1461 		result += sz;
1462 	}
1463 
1464 	if (type & PERF_SAMPLE_REGS_USER) {
1465 		if (sample->user_regs.abi) {
1466 			result += sizeof(u64);
1467 			sz = hweight64(sample->user_regs.mask) * sizeof(u64);
1468 			result += sz;
1469 		} else {
1470 			result += sizeof(u64);
1471 		}
1472 	}
1473 
1474 	if (type & PERF_SAMPLE_STACK_USER) {
1475 		sz = sample->user_stack.size;
1476 		result += sizeof(u64);
1477 		if (sz) {
1478 			result += sz;
1479 			result += sizeof(u64);
1480 		}
1481 	}
1482 
1483 	if (type & PERF_SAMPLE_WEIGHT_TYPE)
1484 		result += sizeof(u64);
1485 
1486 	if (type & PERF_SAMPLE_DATA_SRC)
1487 		result += sizeof(u64);
1488 
1489 	if (type & PERF_SAMPLE_TRANSACTION)
1490 		result += sizeof(u64);
1491 
1492 	if (type & PERF_SAMPLE_REGS_INTR) {
1493 		if (sample->intr_regs.abi) {
1494 			result += sizeof(u64);
1495 			sz = hweight64(sample->intr_regs.mask) * sizeof(u64);
1496 			result += sz;
1497 		} else {
1498 			result += sizeof(u64);
1499 		}
1500 	}
1501 
1502 	if (type & PERF_SAMPLE_PHYS_ADDR)
1503 		result += sizeof(u64);
1504 
1505 	if (type & PERF_SAMPLE_CGROUP)
1506 		result += sizeof(u64);
1507 
1508 	if (type & PERF_SAMPLE_DATA_PAGE_SIZE)
1509 		result += sizeof(u64);
1510 
1511 	if (type & PERF_SAMPLE_CODE_PAGE_SIZE)
1512 		result += sizeof(u64);
1513 
1514 	if (type & PERF_SAMPLE_AUX) {
1515 		result += sizeof(u64);
1516 		result += sample->aux_sample.size;
1517 	}
1518 
1519 	return result;
1520 }
1521 
arch_perf_synthesize_sample_weight(const struct perf_sample * data,__u64 * array,u64 type __maybe_unused)1522 void __weak arch_perf_synthesize_sample_weight(const struct perf_sample *data,
1523 					       __u64 *array, u64 type __maybe_unused)
1524 {
1525 	*array = data->weight;
1526 }
1527 
perf_event__synthesize_sample(union perf_event * event,u64 type,u64 read_format,const struct perf_sample * sample)1528 int perf_event__synthesize_sample(union perf_event *event, u64 type, u64 read_format,
1529 				  const struct perf_sample *sample)
1530 {
1531 	__u64 *array;
1532 	size_t sz;
1533 	/*
1534 	 * used for cross-endian analysis. See git commit 65014ab3
1535 	 * for why this goofiness is needed.
1536 	 */
1537 	union u64_swap u;
1538 
1539 	array = event->sample.array;
1540 
1541 	if (type & PERF_SAMPLE_IDENTIFIER) {
1542 		*array = sample->id;
1543 		array++;
1544 	}
1545 
1546 	if (type & PERF_SAMPLE_IP) {
1547 		*array = sample->ip;
1548 		array++;
1549 	}
1550 
1551 	if (type & PERF_SAMPLE_TID) {
1552 		u.val32[0] = sample->pid;
1553 		u.val32[1] = sample->tid;
1554 		*array = u.val64;
1555 		array++;
1556 	}
1557 
1558 	if (type & PERF_SAMPLE_TIME) {
1559 		*array = sample->time;
1560 		array++;
1561 	}
1562 
1563 	if (type & PERF_SAMPLE_ADDR) {
1564 		*array = sample->addr;
1565 		array++;
1566 	}
1567 
1568 	if (type & PERF_SAMPLE_ID) {
1569 		*array = sample->id;
1570 		array++;
1571 	}
1572 
1573 	if (type & PERF_SAMPLE_STREAM_ID) {
1574 		*array = sample->stream_id;
1575 		array++;
1576 	}
1577 
1578 	if (type & PERF_SAMPLE_CPU) {
1579 		u.val32[0] = sample->cpu;
1580 		u.val32[1] = 0;
1581 		*array = u.val64;
1582 		array++;
1583 	}
1584 
1585 	if (type & PERF_SAMPLE_PERIOD) {
1586 		*array = sample->period;
1587 		array++;
1588 	}
1589 
1590 	if (type & PERF_SAMPLE_READ) {
1591 		if (read_format & PERF_FORMAT_GROUP)
1592 			*array = sample->read.group.nr;
1593 		else
1594 			*array = sample->read.one.value;
1595 		array++;
1596 
1597 		if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
1598 			*array = sample->read.time_enabled;
1599 			array++;
1600 		}
1601 
1602 		if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
1603 			*array = sample->read.time_running;
1604 			array++;
1605 		}
1606 
1607 		/* PERF_FORMAT_ID is forced for PERF_SAMPLE_READ */
1608 		if (read_format & PERF_FORMAT_GROUP) {
1609 			sz = sample->read.group.nr *
1610 			     sizeof(struct sample_read_value);
1611 			memcpy(array, sample->read.group.values, sz);
1612 			array = (void *)array + sz;
1613 		} else {
1614 			*array = sample->read.one.id;
1615 			array++;
1616 		}
1617 	}
1618 
1619 	if (type & PERF_SAMPLE_CALLCHAIN) {
1620 		sz = (sample->callchain->nr + 1) * sizeof(u64);
1621 		memcpy(array, sample->callchain, sz);
1622 		array = (void *)array + sz;
1623 	}
1624 
1625 	if (type & PERF_SAMPLE_RAW) {
1626 		u.val32[0] = sample->raw_size;
1627 		*array = u.val64;
1628 		array = (void *)array + sizeof(u32);
1629 
1630 		memcpy(array, sample->raw_data, sample->raw_size);
1631 		array = (void *)array + sample->raw_size;
1632 	}
1633 
1634 	if (type & PERF_SAMPLE_BRANCH_STACK) {
1635 		sz = sample->branch_stack->nr * sizeof(struct branch_entry);
1636 		/* nr, hw_idx */
1637 		sz += 2 * sizeof(u64);
1638 		memcpy(array, sample->branch_stack, sz);
1639 		array = (void *)array + sz;
1640 	}
1641 
1642 	if (type & PERF_SAMPLE_REGS_USER) {
1643 		if (sample->user_regs.abi) {
1644 			*array++ = sample->user_regs.abi;
1645 			sz = hweight64(sample->user_regs.mask) * sizeof(u64);
1646 			memcpy(array, sample->user_regs.regs, sz);
1647 			array = (void *)array + sz;
1648 		} else {
1649 			*array++ = 0;
1650 		}
1651 	}
1652 
1653 	if (type & PERF_SAMPLE_STACK_USER) {
1654 		sz = sample->user_stack.size;
1655 		*array++ = sz;
1656 		if (sz) {
1657 			memcpy(array, sample->user_stack.data, sz);
1658 			array = (void *)array + sz;
1659 			*array++ = sz;
1660 		}
1661 	}
1662 
1663 	if (type & PERF_SAMPLE_WEIGHT_TYPE) {
1664 		arch_perf_synthesize_sample_weight(sample, array, type);
1665 		array++;
1666 	}
1667 
1668 	if (type & PERF_SAMPLE_DATA_SRC) {
1669 		*array = sample->data_src;
1670 		array++;
1671 	}
1672 
1673 	if (type & PERF_SAMPLE_TRANSACTION) {
1674 		*array = sample->transaction;
1675 		array++;
1676 	}
1677 
1678 	if (type & PERF_SAMPLE_REGS_INTR) {
1679 		if (sample->intr_regs.abi) {
1680 			*array++ = sample->intr_regs.abi;
1681 			sz = hweight64(sample->intr_regs.mask) * sizeof(u64);
1682 			memcpy(array, sample->intr_regs.regs, sz);
1683 			array = (void *)array + sz;
1684 		} else {
1685 			*array++ = 0;
1686 		}
1687 	}
1688 
1689 	if (type & PERF_SAMPLE_PHYS_ADDR) {
1690 		*array = sample->phys_addr;
1691 		array++;
1692 	}
1693 
1694 	if (type & PERF_SAMPLE_CGROUP) {
1695 		*array = sample->cgroup;
1696 		array++;
1697 	}
1698 
1699 	if (type & PERF_SAMPLE_DATA_PAGE_SIZE) {
1700 		*array = sample->data_page_size;
1701 		array++;
1702 	}
1703 
1704 	if (type & PERF_SAMPLE_CODE_PAGE_SIZE) {
1705 		*array = sample->code_page_size;
1706 		array++;
1707 	}
1708 
1709 	if (type & PERF_SAMPLE_AUX) {
1710 		sz = sample->aux_sample.size;
1711 		*array++ = sz;
1712 		memcpy(array, sample->aux_sample.data, sz);
1713 		array = (void *)array + sz;
1714 	}
1715 
1716 	return 0;
1717 }
1718 
perf_event__synthesize_id_index(struct perf_tool * tool,perf_event__handler_t process,struct evlist * evlist,struct machine * machine)1719 int perf_event__synthesize_id_index(struct perf_tool *tool, perf_event__handler_t process,
1720 				    struct evlist *evlist, struct machine *machine)
1721 {
1722 	union perf_event *ev;
1723 	struct evsel *evsel;
1724 	size_t nr = 0, i = 0, sz, max_nr, n;
1725 	int err;
1726 
1727 	pr_debug2("Synthesizing id index\n");
1728 
1729 	max_nr = (UINT16_MAX - sizeof(struct perf_record_id_index)) /
1730 		 sizeof(struct id_index_entry);
1731 
1732 	evlist__for_each_entry(evlist, evsel)
1733 		nr += evsel->core.ids;
1734 
1735 	n = nr > max_nr ? max_nr : nr;
1736 	sz = sizeof(struct perf_record_id_index) + n * sizeof(struct id_index_entry);
1737 	ev = zalloc(sz);
1738 	if (!ev)
1739 		return -ENOMEM;
1740 
1741 	ev->id_index.header.type = PERF_RECORD_ID_INDEX;
1742 	ev->id_index.header.size = sz;
1743 	ev->id_index.nr = n;
1744 
1745 	evlist__for_each_entry(evlist, evsel) {
1746 		u32 j;
1747 
1748 		for (j = 0; j < evsel->core.ids; j++) {
1749 			struct id_index_entry *e;
1750 			struct perf_sample_id *sid;
1751 
1752 			if (i >= n) {
1753 				err = process(tool, ev, NULL, machine);
1754 				if (err)
1755 					goto out_err;
1756 				nr -= n;
1757 				i = 0;
1758 			}
1759 
1760 			e = &ev->id_index.entries[i++];
1761 
1762 			e->id = evsel->core.id[j];
1763 
1764 			sid = evlist__id2sid(evlist, e->id);
1765 			if (!sid) {
1766 				free(ev);
1767 				return -ENOENT;
1768 			}
1769 
1770 			e->idx = sid->idx;
1771 			e->cpu = sid->cpu;
1772 			e->tid = sid->tid;
1773 		}
1774 	}
1775 
1776 	sz = sizeof(struct perf_record_id_index) + nr * sizeof(struct id_index_entry);
1777 	ev->id_index.header.size = sz;
1778 	ev->id_index.nr = nr;
1779 
1780 	err = process(tool, ev, NULL, machine);
1781 out_err:
1782 	free(ev);
1783 
1784 	return err;
1785 }
1786 
__machine__synthesize_threads(struct machine * machine,struct perf_tool * tool,struct target * target,struct perf_thread_map * threads,perf_event__handler_t process,bool data_mmap,unsigned int nr_threads_synthesize)1787 int __machine__synthesize_threads(struct machine *machine, struct perf_tool *tool,
1788 				  struct target *target, struct perf_thread_map *threads,
1789 				  perf_event__handler_t process, bool data_mmap,
1790 				  unsigned int nr_threads_synthesize)
1791 {
1792 	if (target__has_task(target))
1793 		return perf_event__synthesize_thread_map(tool, threads, process, machine, data_mmap);
1794 	else if (target__has_cpu(target))
1795 		return perf_event__synthesize_threads(tool, process,
1796 						      machine, data_mmap,
1797 						      nr_threads_synthesize);
1798 	/* command specified */
1799 	return 0;
1800 }
1801 
machine__synthesize_threads(struct machine * machine,struct target * target,struct perf_thread_map * threads,bool data_mmap,unsigned int nr_threads_synthesize)1802 int machine__synthesize_threads(struct machine *machine, struct target *target,
1803 				struct perf_thread_map *threads, bool data_mmap,
1804 				unsigned int nr_threads_synthesize)
1805 {
1806 	return __machine__synthesize_threads(machine, NULL, target, threads,
1807 					     perf_event__process, data_mmap,
1808 					     nr_threads_synthesize);
1809 }
1810 
event_update_event__new(size_t size,u64 type,u64 id)1811 static struct perf_record_event_update *event_update_event__new(size_t size, u64 type, u64 id)
1812 {
1813 	struct perf_record_event_update *ev;
1814 
1815 	size += sizeof(*ev);
1816 	size  = PERF_ALIGN(size, sizeof(u64));
1817 
1818 	ev = zalloc(size);
1819 	if (ev) {
1820 		ev->header.type = PERF_RECORD_EVENT_UPDATE;
1821 		ev->header.size = (u16)size;
1822 		ev->type	= type;
1823 		ev->id		= id;
1824 	}
1825 	return ev;
1826 }
1827 
perf_event__synthesize_event_update_unit(struct perf_tool * tool,struct evsel * evsel,perf_event__handler_t process)1828 int perf_event__synthesize_event_update_unit(struct perf_tool *tool, struct evsel *evsel,
1829 					     perf_event__handler_t process)
1830 {
1831 	size_t size = strlen(evsel->unit);
1832 	struct perf_record_event_update *ev;
1833 	int err;
1834 
1835 	ev = event_update_event__new(size + 1, PERF_EVENT_UPDATE__UNIT, evsel->core.id[0]);
1836 	if (ev == NULL)
1837 		return -ENOMEM;
1838 
1839 	strlcpy(ev->data, evsel->unit, size + 1);
1840 	err = process(tool, (union perf_event *)ev, NULL, NULL);
1841 	free(ev);
1842 	return err;
1843 }
1844 
perf_event__synthesize_event_update_scale(struct perf_tool * tool,struct evsel * evsel,perf_event__handler_t process)1845 int perf_event__synthesize_event_update_scale(struct perf_tool *tool, struct evsel *evsel,
1846 					      perf_event__handler_t process)
1847 {
1848 	struct perf_record_event_update *ev;
1849 	struct perf_record_event_update_scale *ev_data;
1850 	int err;
1851 
1852 	ev = event_update_event__new(sizeof(*ev_data), PERF_EVENT_UPDATE__SCALE, evsel->core.id[0]);
1853 	if (ev == NULL)
1854 		return -ENOMEM;
1855 
1856 	ev_data = (struct perf_record_event_update_scale *)ev->data;
1857 	ev_data->scale = evsel->scale;
1858 	err = process(tool, (union perf_event *)ev, NULL, NULL);
1859 	free(ev);
1860 	return err;
1861 }
1862 
perf_event__synthesize_event_update_name(struct perf_tool * tool,struct evsel * evsel,perf_event__handler_t process)1863 int perf_event__synthesize_event_update_name(struct perf_tool *tool, struct evsel *evsel,
1864 					     perf_event__handler_t process)
1865 {
1866 	struct perf_record_event_update *ev;
1867 	size_t len = strlen(evsel->name);
1868 	int err;
1869 
1870 	ev = event_update_event__new(len + 1, PERF_EVENT_UPDATE__NAME, evsel->core.id[0]);
1871 	if (ev == NULL)
1872 		return -ENOMEM;
1873 
1874 	strlcpy(ev->data, evsel->name, len + 1);
1875 	err = process(tool, (union perf_event *)ev, NULL, NULL);
1876 	free(ev);
1877 	return err;
1878 }
1879 
perf_event__synthesize_event_update_cpus(struct perf_tool * tool,struct evsel * evsel,perf_event__handler_t process)1880 int perf_event__synthesize_event_update_cpus(struct perf_tool *tool, struct evsel *evsel,
1881 					     perf_event__handler_t process)
1882 {
1883 	size_t size = sizeof(struct perf_record_event_update);
1884 	struct perf_record_event_update *ev;
1885 	int max, err;
1886 	u16 type;
1887 
1888 	if (!evsel->core.own_cpus)
1889 		return 0;
1890 
1891 	ev = cpu_map_data__alloc(evsel->core.own_cpus, &size, &type, &max);
1892 	if (!ev)
1893 		return -ENOMEM;
1894 
1895 	ev->header.type = PERF_RECORD_EVENT_UPDATE;
1896 	ev->header.size = (u16)size;
1897 	ev->type	= PERF_EVENT_UPDATE__CPUS;
1898 	ev->id		= evsel->core.id[0];
1899 
1900 	cpu_map_data__synthesize((struct perf_record_cpu_map_data *)ev->data,
1901 				 evsel->core.own_cpus, type, max);
1902 
1903 	err = process(tool, (union perf_event *)ev, NULL, NULL);
1904 	free(ev);
1905 	return err;
1906 }
1907 
perf_event__synthesize_attrs(struct perf_tool * tool,struct evlist * evlist,perf_event__handler_t process)1908 int perf_event__synthesize_attrs(struct perf_tool *tool, struct evlist *evlist,
1909 				 perf_event__handler_t process)
1910 {
1911 	struct evsel *evsel;
1912 	int err = 0;
1913 
1914 	evlist__for_each_entry(evlist, evsel) {
1915 		err = perf_event__synthesize_attr(tool, &evsel->core.attr, evsel->core.ids,
1916 						  evsel->core.id, process);
1917 		if (err) {
1918 			pr_debug("failed to create perf header attribute\n");
1919 			return err;
1920 		}
1921 	}
1922 
1923 	return err;
1924 }
1925 
has_unit(struct evsel * evsel)1926 static bool has_unit(struct evsel *evsel)
1927 {
1928 	return evsel->unit && *evsel->unit;
1929 }
1930 
has_scale(struct evsel * evsel)1931 static bool has_scale(struct evsel *evsel)
1932 {
1933 	return evsel->scale != 1;
1934 }
1935 
perf_event__synthesize_extra_attr(struct perf_tool * tool,struct evlist * evsel_list,perf_event__handler_t process,bool is_pipe)1936 int perf_event__synthesize_extra_attr(struct perf_tool *tool, struct evlist *evsel_list,
1937 				      perf_event__handler_t process, bool is_pipe)
1938 {
1939 	struct evsel *evsel;
1940 	int err;
1941 
1942 	/*
1943 	 * Synthesize other events stuff not carried within
1944 	 * attr event - unit, scale, name
1945 	 */
1946 	evlist__for_each_entry(evsel_list, evsel) {
1947 		if (!evsel->supported)
1948 			continue;
1949 
1950 		/*
1951 		 * Synthesize unit and scale only if it's defined.
1952 		 */
1953 		if (has_unit(evsel)) {
1954 			err = perf_event__synthesize_event_update_unit(tool, evsel, process);
1955 			if (err < 0) {
1956 				pr_err("Couldn't synthesize evsel unit.\n");
1957 				return err;
1958 			}
1959 		}
1960 
1961 		if (has_scale(evsel)) {
1962 			err = perf_event__synthesize_event_update_scale(tool, evsel, process);
1963 			if (err < 0) {
1964 				pr_err("Couldn't synthesize evsel evsel.\n");
1965 				return err;
1966 			}
1967 		}
1968 
1969 		if (evsel->core.own_cpus) {
1970 			err = perf_event__synthesize_event_update_cpus(tool, evsel, process);
1971 			if (err < 0) {
1972 				pr_err("Couldn't synthesize evsel cpus.\n");
1973 				return err;
1974 			}
1975 		}
1976 
1977 		/*
1978 		 * Name is needed only for pipe output,
1979 		 * perf.data carries event names.
1980 		 */
1981 		if (is_pipe) {
1982 			err = perf_event__synthesize_event_update_name(tool, evsel, process);
1983 			if (err < 0) {
1984 				pr_err("Couldn't synthesize evsel name.\n");
1985 				return err;
1986 			}
1987 		}
1988 	}
1989 	return 0;
1990 }
1991 
perf_event__synthesize_attr(struct perf_tool * tool,struct perf_event_attr * attr,u32 ids,u64 * id,perf_event__handler_t process)1992 int perf_event__synthesize_attr(struct perf_tool *tool, struct perf_event_attr *attr,
1993 				u32 ids, u64 *id, perf_event__handler_t process)
1994 {
1995 	union perf_event *ev;
1996 	size_t size;
1997 	int err;
1998 
1999 	size = sizeof(struct perf_event_attr);
2000 	size = PERF_ALIGN(size, sizeof(u64));
2001 	size += sizeof(struct perf_event_header);
2002 	size += ids * sizeof(u64);
2003 
2004 	ev = zalloc(size);
2005 
2006 	if (ev == NULL)
2007 		return -ENOMEM;
2008 
2009 	ev->attr.attr = *attr;
2010 	memcpy(ev->attr.id, id, ids * sizeof(u64));
2011 
2012 	ev->attr.header.type = PERF_RECORD_HEADER_ATTR;
2013 	ev->attr.header.size = (u16)size;
2014 
2015 	if (ev->attr.header.size == size)
2016 		err = process(tool, ev, NULL, NULL);
2017 	else
2018 		err = -E2BIG;
2019 
2020 	free(ev);
2021 
2022 	return err;
2023 }
2024 
perf_event__synthesize_tracing_data(struct perf_tool * tool,int fd,struct evlist * evlist,perf_event__handler_t process)2025 int perf_event__synthesize_tracing_data(struct perf_tool *tool, int fd, struct evlist *evlist,
2026 					perf_event__handler_t process)
2027 {
2028 	union perf_event ev;
2029 	struct tracing_data *tdata;
2030 	ssize_t size = 0, aligned_size = 0, padding;
2031 	struct feat_fd ff;
2032 
2033 	/*
2034 	 * We are going to store the size of the data followed
2035 	 * by the data contents. Since the fd descriptor is a pipe,
2036 	 * we cannot seek back to store the size of the data once
2037 	 * we know it. Instead we:
2038 	 *
2039 	 * - write the tracing data to the temp file
2040 	 * - get/write the data size to pipe
2041 	 * - write the tracing data from the temp file
2042 	 *   to the pipe
2043 	 */
2044 	tdata = tracing_data_get(&evlist->core.entries, fd, true);
2045 	if (!tdata)
2046 		return -1;
2047 
2048 	memset(&ev, 0, sizeof(ev));
2049 
2050 	ev.tracing_data.header.type = PERF_RECORD_HEADER_TRACING_DATA;
2051 	size = tdata->size;
2052 	aligned_size = PERF_ALIGN(size, sizeof(u64));
2053 	padding = aligned_size - size;
2054 	ev.tracing_data.header.size = sizeof(ev.tracing_data);
2055 	ev.tracing_data.size = aligned_size;
2056 
2057 	process(tool, &ev, NULL, NULL);
2058 
2059 	/*
2060 	 * The put function will copy all the tracing data
2061 	 * stored in temp file to the pipe.
2062 	 */
2063 	tracing_data_put(tdata);
2064 
2065 	ff = (struct feat_fd){ .fd = fd };
2066 	if (write_padded(&ff, NULL, 0, padding))
2067 		return -1;
2068 
2069 	return aligned_size;
2070 }
2071 
perf_event__synthesize_build_id(struct perf_tool * tool,struct dso * pos,u16 misc,perf_event__handler_t process,struct machine * machine)2072 int perf_event__synthesize_build_id(struct perf_tool *tool, struct dso *pos, u16 misc,
2073 				    perf_event__handler_t process, struct machine *machine)
2074 {
2075 	union perf_event ev;
2076 	size_t len;
2077 
2078 	if (!pos->hit)
2079 		return 0;
2080 
2081 	memset(&ev, 0, sizeof(ev));
2082 
2083 	len = pos->long_name_len + 1;
2084 	len = PERF_ALIGN(len, NAME_ALIGN);
2085 	memcpy(&ev.build_id.build_id, pos->bid.data, sizeof(pos->bid.data));
2086 	ev.build_id.header.type = PERF_RECORD_HEADER_BUILD_ID;
2087 	ev.build_id.header.misc = misc;
2088 	ev.build_id.pid = machine->pid;
2089 	ev.build_id.header.size = sizeof(ev.build_id) + len;
2090 	memcpy(&ev.build_id.filename, pos->long_name, pos->long_name_len);
2091 
2092 	return process(tool, &ev, NULL, machine);
2093 }
2094 
perf_event__synthesize_stat_events(struct perf_stat_config * config,struct perf_tool * tool,struct evlist * evlist,perf_event__handler_t process,bool attrs)2095 int perf_event__synthesize_stat_events(struct perf_stat_config *config, struct perf_tool *tool,
2096 				       struct evlist *evlist, perf_event__handler_t process, bool attrs)
2097 {
2098 	int err;
2099 
2100 	if (attrs) {
2101 		err = perf_event__synthesize_attrs(tool, evlist, process);
2102 		if (err < 0) {
2103 			pr_err("Couldn't synthesize attrs.\n");
2104 			return err;
2105 		}
2106 	}
2107 
2108 	err = perf_event__synthesize_extra_attr(tool, evlist, process, attrs);
2109 	err = perf_event__synthesize_thread_map2(tool, evlist->core.threads, process, NULL);
2110 	if (err < 0) {
2111 		pr_err("Couldn't synthesize thread map.\n");
2112 		return err;
2113 	}
2114 
2115 	err = perf_event__synthesize_cpu_map(tool, evlist->core.cpus, process, NULL);
2116 	if (err < 0) {
2117 		pr_err("Couldn't synthesize thread map.\n");
2118 		return err;
2119 	}
2120 
2121 	err = perf_event__synthesize_stat_config(tool, config, process, NULL);
2122 	if (err < 0) {
2123 		pr_err("Couldn't synthesize config.\n");
2124 		return err;
2125 	}
2126 
2127 	return 0;
2128 }
2129 
2130 extern const struct perf_header_feature_ops feat_ops[HEADER_LAST_FEATURE];
2131 
perf_event__synthesize_features(struct perf_tool * tool,struct perf_session * session,struct evlist * evlist,perf_event__handler_t process)2132 int perf_event__synthesize_features(struct perf_tool *tool, struct perf_session *session,
2133 				    struct evlist *evlist, perf_event__handler_t process)
2134 {
2135 	struct perf_header *header = &session->header;
2136 	struct perf_record_header_feature *fe;
2137 	struct feat_fd ff;
2138 	size_t sz, sz_hdr;
2139 	int feat, ret;
2140 
2141 	sz_hdr = sizeof(fe->header);
2142 	sz = sizeof(union perf_event);
2143 	/* get a nice alignment */
2144 	sz = PERF_ALIGN(sz, page_size);
2145 
2146 	memset(&ff, 0, sizeof(ff));
2147 
2148 	ff.buf = malloc(sz);
2149 	if (!ff.buf)
2150 		return -ENOMEM;
2151 
2152 	ff.size = sz - sz_hdr;
2153 	ff.ph = &session->header;
2154 
2155 	for_each_set_bit(feat, header->adds_features, HEADER_FEAT_BITS) {
2156 		if (!feat_ops[feat].synthesize) {
2157 			pr_debug("No record header feature for header :%d\n", feat);
2158 			continue;
2159 		}
2160 
2161 		ff.offset = sizeof(*fe);
2162 
2163 		ret = feat_ops[feat].write(&ff, evlist);
2164 		if (ret || ff.offset <= (ssize_t)sizeof(*fe)) {
2165 			pr_debug("Error writing feature\n");
2166 			continue;
2167 		}
2168 		/* ff.buf may have changed due to realloc in do_write() */
2169 		fe = ff.buf;
2170 		memset(fe, 0, sizeof(*fe));
2171 
2172 		fe->feat_id = feat;
2173 		fe->header.type = PERF_RECORD_HEADER_FEATURE;
2174 		fe->header.size = ff.offset;
2175 
2176 		ret = process(tool, ff.buf, NULL, NULL);
2177 		if (ret) {
2178 			free(ff.buf);
2179 			return ret;
2180 		}
2181 	}
2182 
2183 	/* Send HEADER_LAST_FEATURE mark. */
2184 	fe = ff.buf;
2185 	fe->feat_id     = HEADER_LAST_FEATURE;
2186 	fe->header.type = PERF_RECORD_HEADER_FEATURE;
2187 	fe->header.size = sizeof(*fe);
2188 
2189 	ret = process(tool, ff.buf, NULL, NULL);
2190 
2191 	free(ff.buf);
2192 	return ret;
2193 }
2194 
perf_event__synthesize_for_pipe(struct perf_tool * tool,struct perf_session * session,struct perf_data * data,perf_event__handler_t process)2195 int perf_event__synthesize_for_pipe(struct perf_tool *tool,
2196 				    struct perf_session *session,
2197 				    struct perf_data *data,
2198 				    perf_event__handler_t process)
2199 {
2200 	int err;
2201 	int ret = 0;
2202 	struct evlist *evlist = session->evlist;
2203 
2204 	/*
2205 	 * We need to synthesize events first, because some
2206 	 * features works on top of them (on report side).
2207 	 */
2208 	err = perf_event__synthesize_attrs(tool, evlist, process);
2209 	if (err < 0) {
2210 		pr_err("Couldn't synthesize attrs.\n");
2211 		return err;
2212 	}
2213 	ret += err;
2214 
2215 	err = perf_event__synthesize_features(tool, session, evlist, process);
2216 	if (err < 0) {
2217 		pr_err("Couldn't synthesize features.\n");
2218 		return err;
2219 	}
2220 	ret += err;
2221 
2222 	if (have_tracepoints(&evlist->core.entries)) {
2223 		int fd = perf_data__fd(data);
2224 
2225 		/*
2226 		 * FIXME err <= 0 here actually means that
2227 		 * there were no tracepoints so its not really
2228 		 * an error, just that we don't need to
2229 		 * synthesize anything.  We really have to
2230 		 * return this more properly and also
2231 		 * propagate errors that now are calling die()
2232 		 */
2233 		err = perf_event__synthesize_tracing_data(tool,	fd, evlist,
2234 							  process);
2235 		if (err <= 0) {
2236 			pr_err("Couldn't record tracing data.\n");
2237 			return err;
2238 		}
2239 		ret += err;
2240 	}
2241 
2242 	return ret;
2243 }
2244