xref: /linux/tools/perf/util/header.c (revision f4f346c3465949ebba80c6cc52cd8d2eeaa545fd)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <errno.h>
3 #include <inttypes.h>
4 #include "string2.h"
5 #include <sys/param.h>
6 #include <sys/types.h>
7 #include <byteswap.h>
8 #include <unistd.h>
9 #include <regex.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <linux/compiler.h>
13 #include <linux/list.h>
14 #include <linux/kernel.h>
15 #include <linux/bitops.h>
16 #include <linux/string.h>
17 #include <linux/stringify.h>
18 #include <linux/zalloc.h>
19 #include <sys/stat.h>
20 #include <sys/utsname.h>
21 #include <linux/time64.h>
22 #include <dirent.h>
23 #ifdef HAVE_LIBBPF_SUPPORT
24 #include <bpf/libbpf.h>
25 #endif
26 #include <perf/cpumap.h>
27 #include <tools/libc_compat.h> // reallocarray
28 
29 #include "dso.h"
30 #include "evlist.h"
31 #include "evsel.h"
32 #include "util/evsel_fprintf.h"
33 #include "header.h"
34 #include "memswap.h"
35 #include "trace-event.h"
36 #include "session.h"
37 #include "symbol.h"
38 #include "debug.h"
39 #include "cpumap.h"
40 #include "pmu.h"
41 #include "pmus.h"
42 #include "vdso.h"
43 #include "strbuf.h"
44 #include "build-id.h"
45 #include "data.h"
46 #include <api/fs/fs.h>
47 #include <api/io_dir.h>
48 #include "asm/bug.h"
49 #include "tool.h"
50 #include "time-utils.h"
51 #include "units.h"
52 #include "util/util.h" // perf_exe()
53 #include "cputopo.h"
54 #include "bpf-event.h"
55 #include "bpf-utils.h"
56 #include "clockid.h"
57 
58 #include <linux/ctype.h>
59 #include <internal/lib.h>
60 
61 #ifdef HAVE_LIBTRACEEVENT
62 #include <event-parse.h>
63 #endif
64 
65 /*
66  * magic2 = "PERFILE2"
67  * must be a numerical value to let the endianness
68  * determine the memory layout. That way we are able
69  * to detect endianness when reading the perf.data file
70  * back.
71  *
72  * we check for legacy (PERFFILE) format.
73  */
74 static const char *__perf_magic1 = "PERFFILE";
75 static const u64 __perf_magic2    = 0x32454c4946524550ULL;
76 static const u64 __perf_magic2_sw = 0x50455246494c4532ULL;
77 
78 #define PERF_MAGIC	__perf_magic2
79 
80 const char perf_version_string[] = PERF_VERSION;
81 
82 struct perf_file_attr {
83 	struct perf_event_attr	attr;
84 	struct perf_file_section	ids;
85 };
86 
perf_header__set_feat(struct perf_header * header,int feat)87 void perf_header__set_feat(struct perf_header *header, int feat)
88 {
89 	__set_bit(feat, header->adds_features);
90 }
91 
perf_header__clear_feat(struct perf_header * header,int feat)92 void perf_header__clear_feat(struct perf_header *header, int feat)
93 {
94 	__clear_bit(feat, header->adds_features);
95 }
96 
perf_header__has_feat(const struct perf_header * header,int feat)97 bool perf_header__has_feat(const struct perf_header *header, int feat)
98 {
99 	return test_bit(feat, header->adds_features);
100 }
101 
__do_write_fd(struct feat_fd * ff,const void * buf,size_t size)102 static int __do_write_fd(struct feat_fd *ff, const void *buf, size_t size)
103 {
104 	ssize_t ret = writen(ff->fd, buf, size);
105 
106 	if (ret != (ssize_t)size)
107 		return ret < 0 ? (int)ret : -1;
108 	return 0;
109 }
110 
__do_write_buf(struct feat_fd * ff,const void * buf,size_t size)111 static int __do_write_buf(struct feat_fd *ff,  const void *buf, size_t size)
112 {
113 	/* struct perf_event_header::size is u16 */
114 	const size_t max_size = 0xffff - sizeof(struct perf_event_header);
115 	size_t new_size = ff->size;
116 	void *addr;
117 
118 	if (size + ff->offset > max_size)
119 		return -E2BIG;
120 
121 	while (size > (new_size - ff->offset))
122 		new_size <<= 1;
123 	new_size = min(max_size, new_size);
124 
125 	if (ff->size < new_size) {
126 		addr = realloc(ff->buf, new_size);
127 		if (!addr)
128 			return -ENOMEM;
129 		ff->buf = addr;
130 		ff->size = new_size;
131 	}
132 
133 	memcpy(ff->buf + ff->offset, buf, size);
134 	ff->offset += size;
135 
136 	return 0;
137 }
138 
139 /* Return: 0 if succeeded, -ERR if failed. */
do_write(struct feat_fd * ff,const void * buf,size_t size)140 int do_write(struct feat_fd *ff, const void *buf, size_t size)
141 {
142 	if (!ff->buf)
143 		return __do_write_fd(ff, buf, size);
144 	return __do_write_buf(ff, buf, size);
145 }
146 
147 /* Return: 0 if succeeded, -ERR if failed. */
do_write_bitmap(struct feat_fd * ff,unsigned long * set,u64 size)148 static int do_write_bitmap(struct feat_fd *ff, unsigned long *set, u64 size)
149 {
150 	u64 *p = (u64 *) set;
151 	int i, ret;
152 
153 	ret = do_write(ff, &size, sizeof(size));
154 	if (ret < 0)
155 		return ret;
156 
157 	for (i = 0; (u64) i < BITS_TO_U64(size); i++) {
158 		ret = do_write(ff, p + i, sizeof(*p));
159 		if (ret < 0)
160 			return ret;
161 	}
162 
163 	return 0;
164 }
165 
166 /* Return: 0 if succeeded, -ERR if failed. */
write_padded(struct feat_fd * ff,const void * bf,size_t count,size_t count_aligned)167 int write_padded(struct feat_fd *ff, const void *bf,
168 		 size_t count, size_t count_aligned)
169 {
170 	static const char zero_buf[NAME_ALIGN];
171 	int err = do_write(ff, bf, count);
172 
173 	if (!err)
174 		err = do_write(ff, zero_buf, count_aligned - count);
175 
176 	return err;
177 }
178 
179 #define string_size(str)						\
180 	(PERF_ALIGN((strlen(str) + 1), NAME_ALIGN) + sizeof(u32))
181 
182 /* Return: 0 if succeeded, -ERR if failed. */
do_write_string(struct feat_fd * ff,const char * str)183 static int do_write_string(struct feat_fd *ff, const char *str)
184 {
185 	u32 len, olen;
186 	int ret;
187 
188 	olen = strlen(str) + 1;
189 	len = PERF_ALIGN(olen, NAME_ALIGN);
190 
191 	/* write len, incl. \0 */
192 	ret = do_write(ff, &len, sizeof(len));
193 	if (ret < 0)
194 		return ret;
195 
196 	return write_padded(ff, str, olen, len);
197 }
198 
__do_read_fd(struct feat_fd * ff,void * addr,ssize_t size)199 static int __do_read_fd(struct feat_fd *ff, void *addr, ssize_t size)
200 {
201 	ssize_t ret = readn(ff->fd, addr, size);
202 
203 	if (ret != size)
204 		return ret < 0 ? (int)ret : -1;
205 	return 0;
206 }
207 
__do_read_buf(struct feat_fd * ff,void * addr,ssize_t size)208 static int __do_read_buf(struct feat_fd *ff, void *addr, ssize_t size)
209 {
210 	if (size > (ssize_t)ff->size - ff->offset)
211 		return -1;
212 
213 	memcpy(addr, ff->buf + ff->offset, size);
214 	ff->offset += size;
215 
216 	return 0;
217 
218 }
219 
__do_read(struct feat_fd * ff,void * addr,ssize_t size)220 static int __do_read(struct feat_fd *ff, void *addr, ssize_t size)
221 {
222 	if (!ff->buf)
223 		return __do_read_fd(ff, addr, size);
224 	return __do_read_buf(ff, addr, size);
225 }
226 
do_read_u32(struct feat_fd * ff,u32 * addr)227 static int do_read_u32(struct feat_fd *ff, u32 *addr)
228 {
229 	int ret;
230 
231 	ret = __do_read(ff, addr, sizeof(*addr));
232 	if (ret)
233 		return ret;
234 
235 	if (ff->ph->needs_swap)
236 		*addr = bswap_32(*addr);
237 	return 0;
238 }
239 
do_read_u64(struct feat_fd * ff,u64 * addr)240 static int do_read_u64(struct feat_fd *ff, u64 *addr)
241 {
242 	int ret;
243 
244 	ret = __do_read(ff, addr, sizeof(*addr));
245 	if (ret)
246 		return ret;
247 
248 	if (ff->ph->needs_swap)
249 		*addr = bswap_64(*addr);
250 	return 0;
251 }
252 
do_read_string(struct feat_fd * ff)253 static char *do_read_string(struct feat_fd *ff)
254 {
255 	u32 len;
256 	char *buf;
257 
258 	if (do_read_u32(ff, &len))
259 		return NULL;
260 
261 	buf = malloc(len);
262 	if (!buf)
263 		return NULL;
264 
265 	if (!__do_read(ff, buf, len)) {
266 		/*
267 		 * strings are padded by zeroes
268 		 * thus the actual strlen of buf
269 		 * may be less than len
270 		 */
271 		return buf;
272 	}
273 
274 	free(buf);
275 	return NULL;
276 }
277 
278 /* Return: 0 if succeeded, -ERR if failed. */
do_read_bitmap(struct feat_fd * ff,unsigned long ** pset,u64 * psize)279 static int do_read_bitmap(struct feat_fd *ff, unsigned long **pset, u64 *psize)
280 {
281 	unsigned long *set;
282 	u64 size, *p;
283 	int i, ret;
284 
285 	ret = do_read_u64(ff, &size);
286 	if (ret)
287 		return ret;
288 
289 	set = bitmap_zalloc(size);
290 	if (!set)
291 		return -ENOMEM;
292 
293 	p = (u64 *) set;
294 
295 	for (i = 0; (u64) i < BITS_TO_U64(size); i++) {
296 		ret = do_read_u64(ff, p + i);
297 		if (ret < 0) {
298 			free(set);
299 			return ret;
300 		}
301 	}
302 
303 	*pset  = set;
304 	*psize = size;
305 	return 0;
306 }
307 
308 #ifdef HAVE_LIBTRACEEVENT
write_tracing_data(struct feat_fd * ff,struct evlist * evlist)309 static int write_tracing_data(struct feat_fd *ff,
310 			      struct evlist *evlist)
311 {
312 	if (WARN(ff->buf, "Error: calling %s in pipe-mode.\n", __func__))
313 		return -1;
314 
315 	return read_tracing_data(ff->fd, &evlist->core.entries);
316 }
317 #endif
318 
write_build_id(struct feat_fd * ff,struct evlist * evlist __maybe_unused)319 static int write_build_id(struct feat_fd *ff,
320 			  struct evlist *evlist __maybe_unused)
321 {
322 	struct perf_session *session;
323 	int err;
324 
325 	session = container_of(ff->ph, struct perf_session, header);
326 
327 	if (!perf_session__read_build_ids(session, true))
328 		return -1;
329 
330 	if (WARN(ff->buf, "Error: calling %s in pipe-mode.\n", __func__))
331 		return -1;
332 
333 	err = perf_session__write_buildid_table(session, ff);
334 	if (err < 0) {
335 		pr_debug("failed to write buildid table\n");
336 		return err;
337 	}
338 	perf_session__cache_build_ids(session);
339 
340 	return 0;
341 }
342 
write_hostname(struct feat_fd * ff,struct evlist * evlist __maybe_unused)343 static int write_hostname(struct feat_fd *ff,
344 			  struct evlist *evlist __maybe_unused)
345 {
346 	struct utsname uts;
347 	int ret;
348 
349 	ret = uname(&uts);
350 	if (ret < 0)
351 		return -1;
352 
353 	return do_write_string(ff, uts.nodename);
354 }
355 
write_osrelease(struct feat_fd * ff,struct evlist * evlist __maybe_unused)356 static int write_osrelease(struct feat_fd *ff,
357 			   struct evlist *evlist __maybe_unused)
358 {
359 	struct utsname uts;
360 	int ret;
361 
362 	ret = uname(&uts);
363 	if (ret < 0)
364 		return -1;
365 
366 	return do_write_string(ff, uts.release);
367 }
368 
write_arch(struct feat_fd * ff,struct evlist * evlist __maybe_unused)369 static int write_arch(struct feat_fd *ff,
370 		      struct evlist *evlist __maybe_unused)
371 {
372 	struct utsname uts;
373 	int ret;
374 
375 	ret = uname(&uts);
376 	if (ret < 0)
377 		return -1;
378 
379 	return do_write_string(ff, uts.machine);
380 }
381 
write_version(struct feat_fd * ff,struct evlist * evlist __maybe_unused)382 static int write_version(struct feat_fd *ff,
383 			 struct evlist *evlist __maybe_unused)
384 {
385 	return do_write_string(ff, perf_version_string);
386 }
387 
__write_cpudesc(struct feat_fd * ff,const char * cpuinfo_proc)388 static int __write_cpudesc(struct feat_fd *ff, const char *cpuinfo_proc)
389 {
390 	FILE *file;
391 	char *buf = NULL;
392 	char *s, *p;
393 	const char *search = cpuinfo_proc;
394 	size_t len = 0;
395 	int ret = -1;
396 
397 	if (!search)
398 		return -1;
399 
400 	file = fopen("/proc/cpuinfo", "r");
401 	if (!file)
402 		return -1;
403 
404 	while (getline(&buf, &len, file) > 0) {
405 		ret = strncmp(buf, search, strlen(search));
406 		if (!ret)
407 			break;
408 	}
409 
410 	if (ret) {
411 		ret = -1;
412 		goto done;
413 	}
414 
415 	s = buf;
416 
417 	p = strchr(buf, ':');
418 	if (p && *(p+1) == ' ' && *(p+2))
419 		s = p + 2;
420 	p = strchr(s, '\n');
421 	if (p)
422 		*p = '\0';
423 
424 	/* squash extra space characters (branding string) */
425 	p = s;
426 	while (*p) {
427 		if (isspace(*p)) {
428 			char *r = p + 1;
429 			char *q = skip_spaces(r);
430 			*p = ' ';
431 			if (q != (p+1))
432 				while ((*r++ = *q++));
433 		}
434 		p++;
435 	}
436 	ret = do_write_string(ff, s);
437 done:
438 	free(buf);
439 	fclose(file);
440 	return ret;
441 }
442 
write_cpudesc(struct feat_fd * ff,struct evlist * evlist __maybe_unused)443 static int write_cpudesc(struct feat_fd *ff,
444 		       struct evlist *evlist __maybe_unused)
445 {
446 #if defined(__powerpc__) || defined(__hppa__) || defined(__sparc__)
447 #define CPUINFO_PROC	{ "cpu", }
448 #elif defined(__s390__)
449 #define CPUINFO_PROC	{ "vendor_id", }
450 #elif defined(__sh__)
451 #define CPUINFO_PROC	{ "cpu type", }
452 #elif defined(__alpha__) || defined(__mips__)
453 #define CPUINFO_PROC	{ "cpu model", }
454 #elif defined(__arm__)
455 #define CPUINFO_PROC	{ "model name", "Processor", }
456 #elif defined(__arc__)
457 #define CPUINFO_PROC	{ "Processor", }
458 #elif defined(__xtensa__)
459 #define CPUINFO_PROC	{ "core ID", }
460 #elif defined(__loongarch__)
461 #define CPUINFO_PROC	{ "Model Name", }
462 #else
463 #define CPUINFO_PROC	{ "model name", }
464 #endif
465 	const char *cpuinfo_procs[] = CPUINFO_PROC;
466 #undef CPUINFO_PROC
467 	unsigned int i;
468 
469 	for (i = 0; i < ARRAY_SIZE(cpuinfo_procs); i++) {
470 		int ret;
471 		ret = __write_cpudesc(ff, cpuinfo_procs[i]);
472 		if (ret >= 0)
473 			return ret;
474 	}
475 	return -1;
476 }
477 
478 
write_nrcpus(struct feat_fd * ff,struct evlist * evlist __maybe_unused)479 static int write_nrcpus(struct feat_fd *ff,
480 			struct evlist *evlist __maybe_unused)
481 {
482 	long nr;
483 	u32 nrc, nra;
484 	int ret;
485 
486 	nrc = cpu__max_present_cpu().cpu;
487 
488 	nr = sysconf(_SC_NPROCESSORS_ONLN);
489 	if (nr < 0)
490 		return -1;
491 
492 	nra = (u32)(nr & UINT_MAX);
493 
494 	ret = do_write(ff, &nrc, sizeof(nrc));
495 	if (ret < 0)
496 		return ret;
497 
498 	return do_write(ff, &nra, sizeof(nra));
499 }
500 
write_event_desc(struct feat_fd * ff,struct evlist * evlist)501 static int write_event_desc(struct feat_fd *ff,
502 			    struct evlist *evlist)
503 {
504 	struct evsel *evsel;
505 	u32 nre, nri, sz;
506 	int ret;
507 
508 	nre = evlist->core.nr_entries;
509 
510 	/*
511 	 * write number of events
512 	 */
513 	ret = do_write(ff, &nre, sizeof(nre));
514 	if (ret < 0)
515 		return ret;
516 
517 	/*
518 	 * size of perf_event_attr struct
519 	 */
520 	sz = (u32)sizeof(evsel->core.attr);
521 	ret = do_write(ff, &sz, sizeof(sz));
522 	if (ret < 0)
523 		return ret;
524 
525 	evlist__for_each_entry(evlist, evsel) {
526 		ret = do_write(ff, &evsel->core.attr, sz);
527 		if (ret < 0)
528 			return ret;
529 		/*
530 		 * write number of unique id per event
531 		 * there is one id per instance of an event
532 		 *
533 		 * copy into an nri to be independent of the
534 		 * type of ids,
535 		 */
536 		nri = evsel->core.ids;
537 		ret = do_write(ff, &nri, sizeof(nri));
538 		if (ret < 0)
539 			return ret;
540 
541 		/*
542 		 * write event string as passed on cmdline
543 		 */
544 		ret = do_write_string(ff, evsel__name(evsel));
545 		if (ret < 0)
546 			return ret;
547 		/*
548 		 * write unique ids for this event
549 		 */
550 		ret = do_write(ff, evsel->core.id, evsel->core.ids * sizeof(u64));
551 		if (ret < 0)
552 			return ret;
553 	}
554 	return 0;
555 }
556 
write_cmdline(struct feat_fd * ff,struct evlist * evlist __maybe_unused)557 static int write_cmdline(struct feat_fd *ff,
558 			 struct evlist *evlist __maybe_unused)
559 {
560 	struct perf_env *env = &ff->ph->env;
561 	char pbuf[MAXPATHLEN], *buf;
562 	int i, ret, n;
563 
564 	/* actual path to perf binary */
565 	buf = perf_exe(pbuf, MAXPATHLEN);
566 
567 	/* account for binary path */
568 	n = env->nr_cmdline + 1;
569 
570 	ret = do_write(ff, &n, sizeof(n));
571 	if (ret < 0)
572 		return ret;
573 
574 	ret = do_write_string(ff, buf);
575 	if (ret < 0)
576 		return ret;
577 
578 	for (i = 0 ; i < env->nr_cmdline; i++) {
579 		ret = do_write_string(ff, env->cmdline_argv[i]);
580 		if (ret < 0)
581 			return ret;
582 	}
583 	return 0;
584 }
585 
586 
write_cpu_topology(struct feat_fd * ff,struct evlist * evlist __maybe_unused)587 static int write_cpu_topology(struct feat_fd *ff,
588 			      struct evlist *evlist __maybe_unused)
589 {
590 	struct perf_env *env = &ff->ph->env;
591 	struct cpu_topology *tp;
592 	u32 i;
593 	int ret, j;
594 
595 	tp = cpu_topology__new();
596 	if (!tp)
597 		return -1;
598 
599 	ret = do_write(ff, &tp->package_cpus_lists, sizeof(tp->package_cpus_lists));
600 	if (ret < 0)
601 		goto done;
602 
603 	for (i = 0; i < tp->package_cpus_lists; i++) {
604 		ret = do_write_string(ff, tp->package_cpus_list[i]);
605 		if (ret < 0)
606 			goto done;
607 	}
608 	ret = do_write(ff, &tp->core_cpus_lists, sizeof(tp->core_cpus_lists));
609 	if (ret < 0)
610 		goto done;
611 
612 	for (i = 0; i < tp->core_cpus_lists; i++) {
613 		ret = do_write_string(ff, tp->core_cpus_list[i]);
614 		if (ret < 0)
615 			break;
616 	}
617 
618 	ret = perf_env__read_cpu_topology_map(env);
619 	if (ret < 0)
620 		goto done;
621 
622 	for (j = 0; j < env->nr_cpus_avail; j++) {
623 		ret = do_write(ff, &env->cpu[j].core_id,
624 			       sizeof(env->cpu[j].core_id));
625 		if (ret < 0)
626 			return ret;
627 		ret = do_write(ff, &env->cpu[j].socket_id,
628 			       sizeof(env->cpu[j].socket_id));
629 		if (ret < 0)
630 			return ret;
631 	}
632 
633 	if (!tp->die_cpus_lists)
634 		goto done;
635 
636 	ret = do_write(ff, &tp->die_cpus_lists, sizeof(tp->die_cpus_lists));
637 	if (ret < 0)
638 		goto done;
639 
640 	for (i = 0; i < tp->die_cpus_lists; i++) {
641 		ret = do_write_string(ff, tp->die_cpus_list[i]);
642 		if (ret < 0)
643 			goto done;
644 	}
645 
646 	for (j = 0; j < env->nr_cpus_avail; j++) {
647 		ret = do_write(ff, &env->cpu[j].die_id,
648 			       sizeof(env->cpu[j].die_id));
649 		if (ret < 0)
650 			return ret;
651 	}
652 
653 done:
654 	cpu_topology__delete(tp);
655 	return ret;
656 }
657 
658 
659 
write_total_mem(struct feat_fd * ff,struct evlist * evlist __maybe_unused)660 static int write_total_mem(struct feat_fd *ff,
661 			   struct evlist *evlist __maybe_unused)
662 {
663 	char *buf = NULL;
664 	FILE *fp;
665 	size_t len = 0;
666 	int ret = -1, n;
667 	uint64_t mem;
668 
669 	fp = fopen("/proc/meminfo", "r");
670 	if (!fp)
671 		return -1;
672 
673 	while (getline(&buf, &len, fp) > 0) {
674 		ret = strncmp(buf, "MemTotal:", 9);
675 		if (!ret)
676 			break;
677 	}
678 	if (!ret) {
679 		n = sscanf(buf, "%*s %"PRIu64, &mem);
680 		if (n == 1)
681 			ret = do_write(ff, &mem, sizeof(mem));
682 	} else
683 		ret = -1;
684 	free(buf);
685 	fclose(fp);
686 	return ret;
687 }
688 
write_numa_topology(struct feat_fd * ff,struct evlist * evlist __maybe_unused)689 static int write_numa_topology(struct feat_fd *ff,
690 			       struct evlist *evlist __maybe_unused)
691 {
692 	struct numa_topology *tp;
693 	int ret = -1;
694 	u32 i;
695 
696 	tp = numa_topology__new();
697 	if (!tp)
698 		return -ENOMEM;
699 
700 	ret = do_write(ff, &tp->nr, sizeof(u32));
701 	if (ret < 0)
702 		goto err;
703 
704 	for (i = 0; i < tp->nr; i++) {
705 		struct numa_topology_node *n = &tp->nodes[i];
706 
707 		ret = do_write(ff, &n->node, sizeof(u32));
708 		if (ret < 0)
709 			goto err;
710 
711 		ret = do_write(ff, &n->mem_total, sizeof(u64));
712 		if (ret)
713 			goto err;
714 
715 		ret = do_write(ff, &n->mem_free, sizeof(u64));
716 		if (ret)
717 			goto err;
718 
719 		ret = do_write_string(ff, n->cpus);
720 		if (ret < 0)
721 			goto err;
722 	}
723 
724 	ret = 0;
725 
726 err:
727 	numa_topology__delete(tp);
728 	return ret;
729 }
730 
731 /*
732  * File format:
733  *
734  * struct pmu_mappings {
735  *	u32	pmu_num;
736  *	struct pmu_map {
737  *		u32	type;
738  *		char	name[];
739  *	}[pmu_num];
740  * };
741  */
742 
write_pmu_mappings(struct feat_fd * ff,struct evlist * evlist __maybe_unused)743 static int write_pmu_mappings(struct feat_fd *ff,
744 			      struct evlist *evlist __maybe_unused)
745 {
746 	struct perf_pmu *pmu = NULL;
747 	u32 pmu_num = 0;
748 	int ret;
749 
750 	/*
751 	 * Do a first pass to count number of pmu to avoid lseek so this
752 	 * works in pipe mode as well.
753 	 */
754 	while ((pmu = perf_pmus__scan(pmu)))
755 		pmu_num++;
756 
757 	ret = do_write(ff, &pmu_num, sizeof(pmu_num));
758 	if (ret < 0)
759 		return ret;
760 
761 	while ((pmu = perf_pmus__scan(pmu))) {
762 		ret = do_write(ff, &pmu->type, sizeof(pmu->type));
763 		if (ret < 0)
764 			return ret;
765 
766 		ret = do_write_string(ff, pmu->name);
767 		if (ret < 0)
768 			return ret;
769 	}
770 
771 	return 0;
772 }
773 
774 /*
775  * File format:
776  *
777  * struct group_descs {
778  *	u32	nr_groups;
779  *	struct group_desc {
780  *		char	name[];
781  *		u32	leader_idx;
782  *		u32	nr_members;
783  *	}[nr_groups];
784  * };
785  */
write_group_desc(struct feat_fd * ff,struct evlist * evlist)786 static int write_group_desc(struct feat_fd *ff,
787 			    struct evlist *evlist)
788 {
789 	u32 nr_groups = evlist__nr_groups(evlist);
790 	struct evsel *evsel;
791 	int ret;
792 
793 	ret = do_write(ff, &nr_groups, sizeof(nr_groups));
794 	if (ret < 0)
795 		return ret;
796 
797 	evlist__for_each_entry(evlist, evsel) {
798 		if (evsel__is_group_leader(evsel) && evsel->core.nr_members > 1) {
799 			const char *name = evsel->group_name ?: "{anon_group}";
800 			u32 leader_idx = evsel->core.idx;
801 			u32 nr_members = evsel->core.nr_members;
802 
803 			ret = do_write_string(ff, name);
804 			if (ret < 0)
805 				return ret;
806 
807 			ret = do_write(ff, &leader_idx, sizeof(leader_idx));
808 			if (ret < 0)
809 				return ret;
810 
811 			ret = do_write(ff, &nr_members, sizeof(nr_members));
812 			if (ret < 0)
813 				return ret;
814 		}
815 	}
816 	return 0;
817 }
818 
819 /*
820  * Return the CPU id as a raw string.
821  *
822  * Each architecture should provide a more precise id string that
823  * can be use to match the architecture's "mapfile".
824  */
get_cpuid_str(struct perf_cpu cpu __maybe_unused)825 char * __weak get_cpuid_str(struct perf_cpu cpu __maybe_unused)
826 {
827 	return NULL;
828 }
829 
get_cpuid_allow_env_override(struct perf_cpu cpu)830 char *get_cpuid_allow_env_override(struct perf_cpu cpu)
831 {
832 	char *cpuid;
833 	static bool printed;
834 
835 	cpuid = getenv("PERF_CPUID");
836 	if (cpuid)
837 		cpuid = strdup(cpuid);
838 	if (!cpuid)
839 		cpuid = get_cpuid_str(cpu);
840 	if (!cpuid)
841 		return NULL;
842 
843 	if (!printed) {
844 		pr_debug("Using CPUID %s\n", cpuid);
845 		printed = true;
846 	}
847 	return cpuid;
848 }
849 
850 /* Return zero when the cpuid from the mapfile.csv matches the
851  * cpuid string generated on this platform.
852  * Otherwise return non-zero.
853  */
strcmp_cpuid_str(const char * mapcpuid,const char * cpuid)854 int __weak strcmp_cpuid_str(const char *mapcpuid, const char *cpuid)
855 {
856 	regex_t re;
857 	regmatch_t pmatch[1];
858 	int match;
859 
860 	if (regcomp(&re, mapcpuid, REG_EXTENDED) != 0) {
861 		/* Warn unable to generate match particular string. */
862 		pr_info("Invalid regular expression %s\n", mapcpuid);
863 		return 1;
864 	}
865 
866 	match = !regexec(&re, cpuid, 1, pmatch, 0);
867 	regfree(&re);
868 	if (match) {
869 		size_t match_len = (pmatch[0].rm_eo - pmatch[0].rm_so);
870 
871 		/* Verify the entire string matched. */
872 		if (match_len == strlen(cpuid))
873 			return 0;
874 	}
875 	return 1;
876 }
877 
878 /*
879  * default get_cpuid(): nothing gets recorded
880  * actual implementation must be in arch/$(SRCARCH)/util/header.c
881  */
get_cpuid(char * buffer __maybe_unused,size_t sz __maybe_unused,struct perf_cpu cpu __maybe_unused)882 int __weak get_cpuid(char *buffer __maybe_unused, size_t sz __maybe_unused,
883 		     struct perf_cpu cpu __maybe_unused)
884 {
885 	return ENOSYS; /* Not implemented */
886 }
887 
write_cpuid(struct feat_fd * ff,struct evlist * evlist)888 static int write_cpuid(struct feat_fd *ff, struct evlist *evlist)
889 {
890 	struct perf_cpu cpu = perf_cpu_map__min(evlist->core.all_cpus);
891 	char buffer[64];
892 	int ret;
893 
894 	ret = get_cpuid(buffer, sizeof(buffer), cpu);
895 	if (ret)
896 		return -1;
897 
898 	return do_write_string(ff, buffer);
899 }
900 
write_branch_stack(struct feat_fd * ff __maybe_unused,struct evlist * evlist __maybe_unused)901 static int write_branch_stack(struct feat_fd *ff __maybe_unused,
902 			      struct evlist *evlist __maybe_unused)
903 {
904 	return 0;
905 }
906 
write_auxtrace(struct feat_fd * ff,struct evlist * evlist __maybe_unused)907 static int write_auxtrace(struct feat_fd *ff,
908 			  struct evlist *evlist __maybe_unused)
909 {
910 	struct perf_session *session;
911 	int err;
912 
913 	if (WARN(ff->buf, "Error: calling %s in pipe-mode.\n", __func__))
914 		return -1;
915 
916 	session = container_of(ff->ph, struct perf_session, header);
917 
918 	err = auxtrace_index__write(ff->fd, &session->auxtrace_index);
919 	if (err < 0)
920 		pr_err("Failed to write auxtrace index\n");
921 	return err;
922 }
923 
write_clockid(struct feat_fd * ff,struct evlist * evlist __maybe_unused)924 static int write_clockid(struct feat_fd *ff,
925 			 struct evlist *evlist __maybe_unused)
926 {
927 	return do_write(ff, &ff->ph->env.clock.clockid_res_ns,
928 			sizeof(ff->ph->env.clock.clockid_res_ns));
929 }
930 
write_clock_data(struct feat_fd * ff,struct evlist * evlist __maybe_unused)931 static int write_clock_data(struct feat_fd *ff,
932 			    struct evlist *evlist __maybe_unused)
933 {
934 	u64 *data64;
935 	u32 data32;
936 	int ret;
937 
938 	/* version */
939 	data32 = 1;
940 
941 	ret = do_write(ff, &data32, sizeof(data32));
942 	if (ret < 0)
943 		return ret;
944 
945 	/* clockid */
946 	data32 = ff->ph->env.clock.clockid;
947 
948 	ret = do_write(ff, &data32, sizeof(data32));
949 	if (ret < 0)
950 		return ret;
951 
952 	/* TOD ref time */
953 	data64 = &ff->ph->env.clock.tod_ns;
954 
955 	ret = do_write(ff, data64, sizeof(*data64));
956 	if (ret < 0)
957 		return ret;
958 
959 	/* clockid ref time */
960 	data64 = &ff->ph->env.clock.clockid_ns;
961 
962 	return do_write(ff, data64, sizeof(*data64));
963 }
964 
write_hybrid_topology(struct feat_fd * ff,struct evlist * evlist __maybe_unused)965 static int write_hybrid_topology(struct feat_fd *ff,
966 				 struct evlist *evlist __maybe_unused)
967 {
968 	struct hybrid_topology *tp;
969 	int ret;
970 	u32 i;
971 
972 	tp = hybrid_topology__new();
973 	if (!tp)
974 		return -ENOENT;
975 
976 	ret = do_write(ff, &tp->nr, sizeof(u32));
977 	if (ret < 0)
978 		goto err;
979 
980 	for (i = 0; i < tp->nr; i++) {
981 		struct hybrid_topology_node *n = &tp->nodes[i];
982 
983 		ret = do_write_string(ff, n->pmu_name);
984 		if (ret < 0)
985 			goto err;
986 
987 		ret = do_write_string(ff, n->cpus);
988 		if (ret < 0)
989 			goto err;
990 	}
991 
992 	ret = 0;
993 
994 err:
995 	hybrid_topology__delete(tp);
996 	return ret;
997 }
998 
write_dir_format(struct feat_fd * ff,struct evlist * evlist __maybe_unused)999 static int write_dir_format(struct feat_fd *ff,
1000 			    struct evlist *evlist __maybe_unused)
1001 {
1002 	struct perf_session *session;
1003 	struct perf_data *data;
1004 
1005 	session = container_of(ff->ph, struct perf_session, header);
1006 	data = session->data;
1007 
1008 	if (WARN_ON(!perf_data__is_dir(data)))
1009 		return -1;
1010 
1011 	return do_write(ff, &data->dir.version, sizeof(data->dir.version));
1012 }
1013 
1014 #ifdef HAVE_LIBBPF_SUPPORT
write_bpf_prog_info(struct feat_fd * ff,struct evlist * evlist __maybe_unused)1015 static int write_bpf_prog_info(struct feat_fd *ff,
1016 			       struct evlist *evlist __maybe_unused)
1017 {
1018 	struct perf_env *env = &ff->ph->env;
1019 	struct rb_root *root;
1020 	struct rb_node *next;
1021 	int ret = 0;
1022 
1023 	down_read(&env->bpf_progs.lock);
1024 
1025 	if (env->bpf_progs.infos_cnt == 0)
1026 		goto out;
1027 
1028 	ret = do_write(ff, &env->bpf_progs.infos_cnt,
1029 		       sizeof(env->bpf_progs.infos_cnt));
1030 	if (ret < 0)
1031 		goto out;
1032 
1033 	root = &env->bpf_progs.infos;
1034 	next = rb_first(root);
1035 	while (next) {
1036 		struct bpf_prog_info_node *node;
1037 		size_t len;
1038 
1039 		node = rb_entry(next, struct bpf_prog_info_node, rb_node);
1040 		next = rb_next(&node->rb_node);
1041 		len = sizeof(struct perf_bpil) +
1042 			node->info_linear->data_len;
1043 
1044 		/* before writing to file, translate address to offset */
1045 		bpil_addr_to_offs(node->info_linear);
1046 		ret = do_write(ff, node->info_linear, len);
1047 		/*
1048 		 * translate back to address even when do_write() fails,
1049 		 * so that this function never changes the data.
1050 		 */
1051 		bpil_offs_to_addr(node->info_linear);
1052 		if (ret < 0)
1053 			goto out;
1054 	}
1055 out:
1056 	up_read(&env->bpf_progs.lock);
1057 	return ret;
1058 }
1059 
write_bpf_btf(struct feat_fd * ff,struct evlist * evlist __maybe_unused)1060 static int write_bpf_btf(struct feat_fd *ff,
1061 			 struct evlist *evlist __maybe_unused)
1062 {
1063 	struct perf_env *env = &ff->ph->env;
1064 	struct rb_root *root;
1065 	struct rb_node *next;
1066 	int ret = 0;
1067 
1068 	down_read(&env->bpf_progs.lock);
1069 
1070 	if (env->bpf_progs.btfs_cnt == 0)
1071 		goto out;
1072 
1073 	ret = do_write(ff, &env->bpf_progs.btfs_cnt,
1074 		       sizeof(env->bpf_progs.btfs_cnt));
1075 
1076 	if (ret < 0)
1077 		goto out;
1078 
1079 	root = &env->bpf_progs.btfs;
1080 	next = rb_first(root);
1081 	while (next) {
1082 		struct btf_node *node;
1083 
1084 		node = rb_entry(next, struct btf_node, rb_node);
1085 		next = rb_next(&node->rb_node);
1086 		ret = do_write(ff, &node->id,
1087 			       sizeof(u32) * 2 + node->data_size);
1088 		if (ret < 0)
1089 			goto out;
1090 	}
1091 out:
1092 	up_read(&env->bpf_progs.lock);
1093 	return ret;
1094 }
1095 #endif // HAVE_LIBBPF_SUPPORT
1096 
cpu_cache_level__sort(const void * a,const void * b)1097 static int cpu_cache_level__sort(const void *a, const void *b)
1098 {
1099 	struct cpu_cache_level *cache_a = (struct cpu_cache_level *)a;
1100 	struct cpu_cache_level *cache_b = (struct cpu_cache_level *)b;
1101 
1102 	return cache_a->level - cache_b->level;
1103 }
1104 
cpu_cache_level__cmp(struct cpu_cache_level * a,struct cpu_cache_level * b)1105 static bool cpu_cache_level__cmp(struct cpu_cache_level *a, struct cpu_cache_level *b)
1106 {
1107 	if (a->level != b->level)
1108 		return false;
1109 
1110 	if (a->line_size != b->line_size)
1111 		return false;
1112 
1113 	if (a->sets != b->sets)
1114 		return false;
1115 
1116 	if (a->ways != b->ways)
1117 		return false;
1118 
1119 	if (strcmp(a->type, b->type))
1120 		return false;
1121 
1122 	if (strcmp(a->size, b->size))
1123 		return false;
1124 
1125 	if (strcmp(a->map, b->map))
1126 		return false;
1127 
1128 	return true;
1129 }
1130 
cpu_cache_level__read(struct cpu_cache_level * cache,u32 cpu,u16 level)1131 static int cpu_cache_level__read(struct cpu_cache_level *cache, u32 cpu, u16 level)
1132 {
1133 	char path[PATH_MAX], file[PATH_MAX];
1134 	struct stat st;
1135 	size_t len;
1136 
1137 	scnprintf(path, PATH_MAX, "devices/system/cpu/cpu%d/cache/index%d/", cpu, level);
1138 	scnprintf(file, PATH_MAX, "%s/%s", sysfs__mountpoint(), path);
1139 
1140 	if (stat(file, &st))
1141 		return 1;
1142 
1143 	scnprintf(file, PATH_MAX, "%s/level", path);
1144 	if (sysfs__read_int(file, (int *) &cache->level))
1145 		return -1;
1146 
1147 	scnprintf(file, PATH_MAX, "%s/coherency_line_size", path);
1148 	if (sysfs__read_int(file, (int *) &cache->line_size))
1149 		return -1;
1150 
1151 	scnprintf(file, PATH_MAX, "%s/number_of_sets", path);
1152 	if (sysfs__read_int(file, (int *) &cache->sets))
1153 		return -1;
1154 
1155 	scnprintf(file, PATH_MAX, "%s/ways_of_associativity", path);
1156 	if (sysfs__read_int(file, (int *) &cache->ways))
1157 		return -1;
1158 
1159 	scnprintf(file, PATH_MAX, "%s/type", path);
1160 	if (sysfs__read_str(file, &cache->type, &len))
1161 		return -1;
1162 
1163 	cache->type[len] = 0;
1164 	cache->type = strim(cache->type);
1165 
1166 	scnprintf(file, PATH_MAX, "%s/size", path);
1167 	if (sysfs__read_str(file, &cache->size, &len)) {
1168 		zfree(&cache->type);
1169 		return -1;
1170 	}
1171 
1172 	cache->size[len] = 0;
1173 	cache->size = strim(cache->size);
1174 
1175 	scnprintf(file, PATH_MAX, "%s/shared_cpu_list", path);
1176 	if (sysfs__read_str(file, &cache->map, &len)) {
1177 		zfree(&cache->size);
1178 		zfree(&cache->type);
1179 		return -1;
1180 	}
1181 
1182 	cache->map[len] = 0;
1183 	cache->map = strim(cache->map);
1184 	return 0;
1185 }
1186 
cpu_cache_level__fprintf(FILE * out,struct cpu_cache_level * c)1187 static void cpu_cache_level__fprintf(FILE *out, struct cpu_cache_level *c)
1188 {
1189 	fprintf(out, "L%d %-15s %8s [%s]\n", c->level, c->type, c->size, c->map);
1190 }
1191 
1192 /*
1193  * Build caches levels for a particular CPU from the data in
1194  * /sys/devices/system/cpu/cpu<cpu>/cache/
1195  * The cache level data is stored in caches[] from index at
1196  * *cntp.
1197  */
build_caches_for_cpu(u32 cpu,struct cpu_cache_level caches[],u32 * cntp)1198 int build_caches_for_cpu(u32 cpu, struct cpu_cache_level caches[], u32 *cntp)
1199 {
1200 	u16 level;
1201 
1202 	for (level = 0; level < MAX_CACHE_LVL; level++) {
1203 		struct cpu_cache_level c;
1204 		int err;
1205 		u32 i;
1206 
1207 		err = cpu_cache_level__read(&c, cpu, level);
1208 		if (err < 0)
1209 			return err;
1210 
1211 		if (err == 1)
1212 			break;
1213 
1214 		for (i = 0; i < *cntp; i++) {
1215 			if (cpu_cache_level__cmp(&c, &caches[i]))
1216 				break;
1217 		}
1218 
1219 		if (i == *cntp) {
1220 			caches[*cntp] = c;
1221 			*cntp = *cntp + 1;
1222 		} else
1223 			cpu_cache_level__free(&c);
1224 	}
1225 
1226 	return 0;
1227 }
1228 
build_caches(struct cpu_cache_level caches[],u32 * cntp)1229 static int build_caches(struct cpu_cache_level caches[], u32 *cntp)
1230 {
1231 	u32 nr, cpu, cnt = 0;
1232 
1233 	nr = cpu__max_cpu().cpu;
1234 
1235 	for (cpu = 0; cpu < nr; cpu++) {
1236 		int ret = build_caches_for_cpu(cpu, caches, &cnt);
1237 
1238 		if (ret)
1239 			return ret;
1240 	}
1241 	*cntp = cnt;
1242 	return 0;
1243 }
1244 
write_cache(struct feat_fd * ff,struct evlist * evlist __maybe_unused)1245 static int write_cache(struct feat_fd *ff,
1246 		       struct evlist *evlist __maybe_unused)
1247 {
1248 	u32 max_caches = cpu__max_cpu().cpu * MAX_CACHE_LVL;
1249 	struct cpu_cache_level caches[max_caches];
1250 	u32 cnt = 0, i, version = 1;
1251 	int ret;
1252 
1253 	ret = build_caches(caches, &cnt);
1254 	if (ret)
1255 		goto out;
1256 
1257 	qsort(&caches, cnt, sizeof(struct cpu_cache_level), cpu_cache_level__sort);
1258 
1259 	ret = do_write(ff, &version, sizeof(u32));
1260 	if (ret < 0)
1261 		goto out;
1262 
1263 	ret = do_write(ff, &cnt, sizeof(u32));
1264 	if (ret < 0)
1265 		goto out;
1266 
1267 	for (i = 0; i < cnt; i++) {
1268 		struct cpu_cache_level *c = &caches[i];
1269 
1270 		#define _W(v)					\
1271 			ret = do_write(ff, &c->v, sizeof(u32));	\
1272 			if (ret < 0)				\
1273 				goto out;
1274 
1275 		_W(level)
1276 		_W(line_size)
1277 		_W(sets)
1278 		_W(ways)
1279 		#undef _W
1280 
1281 		#define _W(v)						\
1282 			ret = do_write_string(ff, (const char *) c->v);	\
1283 			if (ret < 0)					\
1284 				goto out;
1285 
1286 		_W(type)
1287 		_W(size)
1288 		_W(map)
1289 		#undef _W
1290 	}
1291 
1292 out:
1293 	for (i = 0; i < cnt; i++)
1294 		cpu_cache_level__free(&caches[i]);
1295 	return ret;
1296 }
1297 
write_stat(struct feat_fd * ff __maybe_unused,struct evlist * evlist __maybe_unused)1298 static int write_stat(struct feat_fd *ff __maybe_unused,
1299 		      struct evlist *evlist __maybe_unused)
1300 {
1301 	return 0;
1302 }
1303 
write_sample_time(struct feat_fd * ff,struct evlist * evlist)1304 static int write_sample_time(struct feat_fd *ff,
1305 			     struct evlist *evlist)
1306 {
1307 	int ret;
1308 
1309 	ret = do_write(ff, &evlist->first_sample_time,
1310 		       sizeof(evlist->first_sample_time));
1311 	if (ret < 0)
1312 		return ret;
1313 
1314 	return do_write(ff, &evlist->last_sample_time,
1315 			sizeof(evlist->last_sample_time));
1316 }
1317 
1318 
memory_node__read(struct memory_node * n,unsigned long idx)1319 static int memory_node__read(struct memory_node *n, unsigned long idx)
1320 {
1321 	unsigned int phys, size = 0;
1322 	char path[PATH_MAX];
1323 	struct io_dirent64 *ent;
1324 	struct io_dir dir;
1325 
1326 #define for_each_memory(mem, dir)					\
1327 	while ((ent = io_dir__readdir(&dir)) != NULL)			\
1328 		if (strcmp(ent->d_name, ".") &&				\
1329 		    strcmp(ent->d_name, "..") &&			\
1330 		    sscanf(ent->d_name, "memory%u", &mem) == 1)
1331 
1332 	scnprintf(path, PATH_MAX,
1333 		  "%s/devices/system/node/node%lu",
1334 		  sysfs__mountpoint(), idx);
1335 
1336 	io_dir__init(&dir, open(path, O_CLOEXEC | O_DIRECTORY | O_RDONLY));
1337 	if (dir.dirfd < 0) {
1338 		pr_warning("failed: can't open memory sysfs data '%s'\n", path);
1339 		return -1;
1340 	}
1341 
1342 	for_each_memory(phys, dir) {
1343 		size = max(phys, size);
1344 	}
1345 
1346 	size++;
1347 
1348 	n->set = bitmap_zalloc(size);
1349 	if (!n->set) {
1350 		close(dir.dirfd);
1351 		return -ENOMEM;
1352 	}
1353 
1354 	n->node = idx;
1355 	n->size = size;
1356 
1357 	io_dir__rewinddir(&dir);
1358 
1359 	for_each_memory(phys, dir) {
1360 		__set_bit(phys, n->set);
1361 	}
1362 
1363 	close(dir.dirfd);
1364 	return 0;
1365 }
1366 
memory_node__delete_nodes(struct memory_node * nodesp,u64 cnt)1367 static void memory_node__delete_nodes(struct memory_node *nodesp, u64 cnt)
1368 {
1369 	for (u64 i = 0; i < cnt; i++)
1370 		bitmap_free(nodesp[i].set);
1371 
1372 	free(nodesp);
1373 }
1374 
memory_node__sort(const void * a,const void * b)1375 static int memory_node__sort(const void *a, const void *b)
1376 {
1377 	const struct memory_node *na = a;
1378 	const struct memory_node *nb = b;
1379 
1380 	return na->node - nb->node;
1381 }
1382 
build_mem_topology(struct memory_node ** nodesp,u64 * cntp)1383 static int build_mem_topology(struct memory_node **nodesp, u64 *cntp)
1384 {
1385 	char path[PATH_MAX];
1386 	struct io_dirent64 *ent;
1387 	struct io_dir dir;
1388 	int ret = 0;
1389 	size_t cnt = 0, size = 0;
1390 	struct memory_node *nodes = NULL;
1391 
1392 	scnprintf(path, PATH_MAX, "%s/devices/system/node/",
1393 		  sysfs__mountpoint());
1394 
1395 	io_dir__init(&dir, open(path, O_CLOEXEC | O_DIRECTORY | O_RDONLY));
1396 	if (dir.dirfd < 0) {
1397 		pr_debug2("%s: couldn't read %s, does this arch have topology information?\n",
1398 			  __func__, path);
1399 		return -1;
1400 	}
1401 
1402 	while (!ret && (ent = io_dir__readdir(&dir))) {
1403 		unsigned int idx;
1404 		int r;
1405 
1406 		if (!strcmp(ent->d_name, ".") ||
1407 		    !strcmp(ent->d_name, ".."))
1408 			continue;
1409 
1410 		r = sscanf(ent->d_name, "node%u", &idx);
1411 		if (r != 1)
1412 			continue;
1413 
1414 		if (cnt >= size) {
1415 			struct memory_node *new_nodes =
1416 				reallocarray(nodes, cnt + 4, sizeof(*nodes));
1417 
1418 			if (!new_nodes) {
1419 				pr_err("Failed to write MEM_TOPOLOGY, size %zd nodes\n", size);
1420 				ret = -ENOMEM;
1421 				goto out;
1422 			}
1423 			nodes = new_nodes;
1424 			size += 4;
1425 		}
1426 		ret = memory_node__read(&nodes[cnt], idx);
1427 		if (!ret)
1428 			cnt += 1;
1429 	}
1430 out:
1431 	close(dir.dirfd);
1432 	if (!ret) {
1433 		*cntp = cnt;
1434 		*nodesp = nodes;
1435 		qsort(nodes, cnt, sizeof(nodes[0]), memory_node__sort);
1436 	} else
1437 		memory_node__delete_nodes(nodes, cnt);
1438 
1439 	return ret;
1440 }
1441 
1442 /*
1443  * The MEM_TOPOLOGY holds physical memory map for every
1444  * node in system. The format of data is as follows:
1445  *
1446  *  0 - version          | for future changes
1447  *  8 - block_size_bytes | /sys/devices/system/memory/block_size_bytes
1448  * 16 - count            | number of nodes
1449  *
1450  * For each node we store map of physical indexes for
1451  * each node:
1452  *
1453  * 32 - node id          | node index
1454  * 40 - size             | size of bitmap
1455  * 48 - bitmap           | bitmap of memory indexes that belongs to node
1456  */
write_mem_topology(struct feat_fd * ff __maybe_unused,struct evlist * evlist __maybe_unused)1457 static int write_mem_topology(struct feat_fd *ff __maybe_unused,
1458 			      struct evlist *evlist __maybe_unused)
1459 {
1460 	struct memory_node *nodes = NULL;
1461 	u64 bsize, version = 1, i, nr = 0;
1462 	int ret;
1463 
1464 	ret = sysfs__read_xll("devices/system/memory/block_size_bytes",
1465 			      (unsigned long long *) &bsize);
1466 	if (ret)
1467 		return ret;
1468 
1469 	ret = build_mem_topology(&nodes, &nr);
1470 	if (ret)
1471 		return ret;
1472 
1473 	ret = do_write(ff, &version, sizeof(version));
1474 	if (ret < 0)
1475 		goto out;
1476 
1477 	ret = do_write(ff, &bsize, sizeof(bsize));
1478 	if (ret < 0)
1479 		goto out;
1480 
1481 	ret = do_write(ff, &nr, sizeof(nr));
1482 	if (ret < 0)
1483 		goto out;
1484 
1485 	for (i = 0; i < nr; i++) {
1486 		struct memory_node *n = &nodes[i];
1487 
1488 		#define _W(v)						\
1489 			ret = do_write(ff, &n->v, sizeof(n->v));	\
1490 			if (ret < 0)					\
1491 				goto out;
1492 
1493 		_W(node)
1494 		_W(size)
1495 
1496 		#undef _W
1497 
1498 		ret = do_write_bitmap(ff, n->set, n->size);
1499 		if (ret < 0)
1500 			goto out;
1501 	}
1502 
1503 out:
1504 	memory_node__delete_nodes(nodes, nr);
1505 	return ret;
1506 }
1507 
write_compressed(struct feat_fd * ff __maybe_unused,struct evlist * evlist __maybe_unused)1508 static int write_compressed(struct feat_fd *ff __maybe_unused,
1509 			    struct evlist *evlist __maybe_unused)
1510 {
1511 	int ret;
1512 
1513 	ret = do_write(ff, &(ff->ph->env.comp_ver), sizeof(ff->ph->env.comp_ver));
1514 	if (ret)
1515 		return ret;
1516 
1517 	ret = do_write(ff, &(ff->ph->env.comp_type), sizeof(ff->ph->env.comp_type));
1518 	if (ret)
1519 		return ret;
1520 
1521 	ret = do_write(ff, &(ff->ph->env.comp_level), sizeof(ff->ph->env.comp_level));
1522 	if (ret)
1523 		return ret;
1524 
1525 	ret = do_write(ff, &(ff->ph->env.comp_ratio), sizeof(ff->ph->env.comp_ratio));
1526 	if (ret)
1527 		return ret;
1528 
1529 	return do_write(ff, &(ff->ph->env.comp_mmap_len), sizeof(ff->ph->env.comp_mmap_len));
1530 }
1531 
__write_pmu_caps(struct feat_fd * ff,struct perf_pmu * pmu,bool write_pmu)1532 static int __write_pmu_caps(struct feat_fd *ff, struct perf_pmu *pmu,
1533 			    bool write_pmu)
1534 {
1535 	struct perf_pmu_caps *caps = NULL;
1536 	int ret;
1537 
1538 	ret = do_write(ff, &pmu->nr_caps, sizeof(pmu->nr_caps));
1539 	if (ret < 0)
1540 		return ret;
1541 
1542 	list_for_each_entry(caps, &pmu->caps, list) {
1543 		ret = do_write_string(ff, caps->name);
1544 		if (ret < 0)
1545 			return ret;
1546 
1547 		ret = do_write_string(ff, caps->value);
1548 		if (ret < 0)
1549 			return ret;
1550 	}
1551 
1552 	if (write_pmu) {
1553 		ret = do_write_string(ff, pmu->name);
1554 		if (ret < 0)
1555 			return ret;
1556 	}
1557 
1558 	return ret;
1559 }
1560 
write_cpu_pmu_caps(struct feat_fd * ff,struct evlist * evlist __maybe_unused)1561 static int write_cpu_pmu_caps(struct feat_fd *ff,
1562 			      struct evlist *evlist __maybe_unused)
1563 {
1564 	struct perf_pmu *cpu_pmu = perf_pmus__find("cpu");
1565 	int ret;
1566 
1567 	if (!cpu_pmu)
1568 		return -ENOENT;
1569 
1570 	ret = perf_pmu__caps_parse(cpu_pmu);
1571 	if (ret < 0)
1572 		return ret;
1573 
1574 	return __write_pmu_caps(ff, cpu_pmu, false);
1575 }
1576 
write_pmu_caps(struct feat_fd * ff,struct evlist * evlist __maybe_unused)1577 static int write_pmu_caps(struct feat_fd *ff,
1578 			  struct evlist *evlist __maybe_unused)
1579 {
1580 	struct perf_pmu *pmu = NULL;
1581 	int nr_pmu = 0;
1582 	int ret;
1583 
1584 	while ((pmu = perf_pmus__scan(pmu))) {
1585 		if (!strcmp(pmu->name, "cpu")) {
1586 			/*
1587 			 * The "cpu" PMU is special and covered by
1588 			 * HEADER_CPU_PMU_CAPS. Note, core PMUs are
1589 			 * counted/written here for ARM, s390 and Intel hybrid.
1590 			 */
1591 			continue;
1592 		}
1593 		if (perf_pmu__caps_parse(pmu) <= 0)
1594 			continue;
1595 		nr_pmu++;
1596 	}
1597 
1598 	ret = do_write(ff, &nr_pmu, sizeof(nr_pmu));
1599 	if (ret < 0)
1600 		return ret;
1601 
1602 	if (!nr_pmu)
1603 		return 0;
1604 
1605 	/*
1606 	 * Note older perf tools assume core PMUs come first, this is a property
1607 	 * of perf_pmus__scan.
1608 	 */
1609 	pmu = NULL;
1610 	while ((pmu = perf_pmus__scan(pmu))) {
1611 		if (!strcmp(pmu->name, "cpu")) {
1612 			/* Skip as above. */
1613 			continue;
1614 		}
1615 		if (perf_pmu__caps_parse(pmu) <= 0)
1616 			continue;
1617 		ret = __write_pmu_caps(ff, pmu, true);
1618 		if (ret < 0)
1619 			return ret;
1620 	}
1621 	return 0;
1622 }
1623 
print_hostname(struct feat_fd * ff,FILE * fp)1624 static void print_hostname(struct feat_fd *ff, FILE *fp)
1625 {
1626 	fprintf(fp, "# hostname : %s\n", ff->ph->env.hostname);
1627 }
1628 
print_osrelease(struct feat_fd * ff,FILE * fp)1629 static void print_osrelease(struct feat_fd *ff, FILE *fp)
1630 {
1631 	fprintf(fp, "# os release : %s\n", ff->ph->env.os_release);
1632 }
1633 
print_arch(struct feat_fd * ff,FILE * fp)1634 static void print_arch(struct feat_fd *ff, FILE *fp)
1635 {
1636 	fprintf(fp, "# arch : %s\n", ff->ph->env.arch);
1637 }
1638 
print_cpudesc(struct feat_fd * ff,FILE * fp)1639 static void print_cpudesc(struct feat_fd *ff, FILE *fp)
1640 {
1641 	fprintf(fp, "# cpudesc : %s\n", ff->ph->env.cpu_desc);
1642 }
1643 
print_nrcpus(struct feat_fd * ff,FILE * fp)1644 static void print_nrcpus(struct feat_fd *ff, FILE *fp)
1645 {
1646 	fprintf(fp, "# nrcpus online : %u\n", ff->ph->env.nr_cpus_online);
1647 	fprintf(fp, "# nrcpus avail : %u\n", ff->ph->env.nr_cpus_avail);
1648 }
1649 
print_version(struct feat_fd * ff,FILE * fp)1650 static void print_version(struct feat_fd *ff, FILE *fp)
1651 {
1652 	fprintf(fp, "# perf version : %s\n", ff->ph->env.version);
1653 }
1654 
print_cmdline(struct feat_fd * ff,FILE * fp)1655 static void print_cmdline(struct feat_fd *ff, FILE *fp)
1656 {
1657 	int nr, i;
1658 
1659 	nr = ff->ph->env.nr_cmdline;
1660 
1661 	fprintf(fp, "# cmdline : ");
1662 
1663 	for (i = 0; i < nr; i++) {
1664 		char *argv_i = strdup(ff->ph->env.cmdline_argv[i]);
1665 		if (!argv_i) {
1666 			fprintf(fp, "%s ", ff->ph->env.cmdline_argv[i]);
1667 		} else {
1668 			char *mem = argv_i;
1669 			do {
1670 				char *quote = strchr(argv_i, '\'');
1671 				if (!quote)
1672 					break;
1673 				*quote++ = '\0';
1674 				fprintf(fp, "%s\\\'", argv_i);
1675 				argv_i = quote;
1676 			} while (1);
1677 			fprintf(fp, "%s ", argv_i);
1678 			free(mem);
1679 		}
1680 	}
1681 	fputc('\n', fp);
1682 }
1683 
print_cpu_topology(struct feat_fd * ff,FILE * fp)1684 static void print_cpu_topology(struct feat_fd *ff, FILE *fp)
1685 {
1686 	struct perf_header *ph = ff->ph;
1687 	int cpu_nr = ph->env.nr_cpus_avail;
1688 	int nr, i;
1689 	char *str;
1690 
1691 	nr = ph->env.nr_sibling_cores;
1692 	str = ph->env.sibling_cores;
1693 
1694 	for (i = 0; i < nr; i++) {
1695 		fprintf(fp, "# sibling sockets : %s\n", str);
1696 		str += strlen(str) + 1;
1697 	}
1698 
1699 	if (ph->env.nr_sibling_dies) {
1700 		nr = ph->env.nr_sibling_dies;
1701 		str = ph->env.sibling_dies;
1702 
1703 		for (i = 0; i < nr; i++) {
1704 			fprintf(fp, "# sibling dies    : %s\n", str);
1705 			str += strlen(str) + 1;
1706 		}
1707 	}
1708 
1709 	nr = ph->env.nr_sibling_threads;
1710 	str = ph->env.sibling_threads;
1711 
1712 	for (i = 0; i < nr; i++) {
1713 		fprintf(fp, "# sibling threads : %s\n", str);
1714 		str += strlen(str) + 1;
1715 	}
1716 
1717 	if (ph->env.nr_sibling_dies) {
1718 		if (ph->env.cpu != NULL) {
1719 			for (i = 0; i < cpu_nr; i++)
1720 				fprintf(fp, "# CPU %d: Core ID %d, "
1721 					    "Die ID %d, Socket ID %d\n",
1722 					    i, ph->env.cpu[i].core_id,
1723 					    ph->env.cpu[i].die_id,
1724 					    ph->env.cpu[i].socket_id);
1725 		} else
1726 			fprintf(fp, "# Core ID, Die ID and Socket ID "
1727 				    "information is not available\n");
1728 	} else {
1729 		if (ph->env.cpu != NULL) {
1730 			for (i = 0; i < cpu_nr; i++)
1731 				fprintf(fp, "# CPU %d: Core ID %d, "
1732 					    "Socket ID %d\n",
1733 					    i, ph->env.cpu[i].core_id,
1734 					    ph->env.cpu[i].socket_id);
1735 		} else
1736 			fprintf(fp, "# Core ID and Socket ID "
1737 				    "information is not available\n");
1738 	}
1739 }
1740 
print_clockid(struct feat_fd * ff,FILE * fp)1741 static void print_clockid(struct feat_fd *ff, FILE *fp)
1742 {
1743 	fprintf(fp, "# clockid frequency: %"PRIu64" MHz\n",
1744 		ff->ph->env.clock.clockid_res_ns * 1000);
1745 }
1746 
print_clock_data(struct feat_fd * ff,FILE * fp)1747 static void print_clock_data(struct feat_fd *ff, FILE *fp)
1748 {
1749 	struct timespec clockid_ns;
1750 	char tstr[64], date[64];
1751 	struct timeval tod_ns;
1752 	clockid_t clockid;
1753 	struct tm ltime;
1754 	u64 ref;
1755 
1756 	if (!ff->ph->env.clock.enabled) {
1757 		fprintf(fp, "# reference time disabled\n");
1758 		return;
1759 	}
1760 
1761 	/* Compute TOD time. */
1762 	ref = ff->ph->env.clock.tod_ns;
1763 	tod_ns.tv_sec = ref / NSEC_PER_SEC;
1764 	ref -= tod_ns.tv_sec * NSEC_PER_SEC;
1765 	tod_ns.tv_usec = ref / NSEC_PER_USEC;
1766 
1767 	/* Compute clockid time. */
1768 	ref = ff->ph->env.clock.clockid_ns;
1769 	clockid_ns.tv_sec = ref / NSEC_PER_SEC;
1770 	ref -= clockid_ns.tv_sec * NSEC_PER_SEC;
1771 	clockid_ns.tv_nsec = ref;
1772 
1773 	clockid = ff->ph->env.clock.clockid;
1774 
1775 	if (localtime_r(&tod_ns.tv_sec, &ltime) == NULL)
1776 		snprintf(tstr, sizeof(tstr), "<error>");
1777 	else {
1778 		strftime(date, sizeof(date), "%F %T", &ltime);
1779 		scnprintf(tstr, sizeof(tstr), "%s.%06d",
1780 			  date, (int) tod_ns.tv_usec);
1781 	}
1782 
1783 	fprintf(fp, "# clockid: %s (%u)\n", clockid_name(clockid), clockid);
1784 	fprintf(fp, "# reference time: %s = %ld.%06d (TOD) = %ld.%09ld (%s)\n",
1785 		    tstr, (long) tod_ns.tv_sec, (int) tod_ns.tv_usec,
1786 		    (long) clockid_ns.tv_sec, clockid_ns.tv_nsec,
1787 		    clockid_name(clockid));
1788 }
1789 
print_hybrid_topology(struct feat_fd * ff,FILE * fp)1790 static void print_hybrid_topology(struct feat_fd *ff, FILE *fp)
1791 {
1792 	int i;
1793 	struct hybrid_node *n;
1794 
1795 	fprintf(fp, "# hybrid cpu system:\n");
1796 	for (i = 0; i < ff->ph->env.nr_hybrid_nodes; i++) {
1797 		n = &ff->ph->env.hybrid_nodes[i];
1798 		fprintf(fp, "# %s cpu list : %s\n", n->pmu_name, n->cpus);
1799 	}
1800 }
1801 
print_dir_format(struct feat_fd * ff,FILE * fp)1802 static void print_dir_format(struct feat_fd *ff, FILE *fp)
1803 {
1804 	struct perf_session *session;
1805 	struct perf_data *data;
1806 
1807 	session = container_of(ff->ph, struct perf_session, header);
1808 	data = session->data;
1809 
1810 	fprintf(fp, "# directory data version : %"PRIu64"\n", data->dir.version);
1811 }
1812 
1813 #ifdef HAVE_LIBBPF_SUPPORT
print_bpf_prog_info(struct feat_fd * ff,FILE * fp)1814 static void print_bpf_prog_info(struct feat_fd *ff, FILE *fp)
1815 {
1816 	struct perf_env *env = &ff->ph->env;
1817 	struct rb_root *root;
1818 	struct rb_node *next;
1819 
1820 	down_read(&env->bpf_progs.lock);
1821 
1822 	root = &env->bpf_progs.infos;
1823 	next = rb_first(root);
1824 
1825 	if (!next)
1826 		printf("# bpf_prog_info empty\n");
1827 
1828 	while (next) {
1829 		struct bpf_prog_info_node *node;
1830 
1831 		node = rb_entry(next, struct bpf_prog_info_node, rb_node);
1832 		next = rb_next(&node->rb_node);
1833 
1834 		__bpf_event__print_bpf_prog_info(&node->info_linear->info,
1835 						 env, fp);
1836 	}
1837 
1838 	up_read(&env->bpf_progs.lock);
1839 }
1840 
print_bpf_btf(struct feat_fd * ff,FILE * fp)1841 static void print_bpf_btf(struct feat_fd *ff, FILE *fp)
1842 {
1843 	struct perf_env *env = &ff->ph->env;
1844 	struct rb_root *root;
1845 	struct rb_node *next;
1846 
1847 	down_read(&env->bpf_progs.lock);
1848 
1849 	root = &env->bpf_progs.btfs;
1850 	next = rb_first(root);
1851 
1852 	if (!next)
1853 		printf("# btf info empty\n");
1854 
1855 	while (next) {
1856 		struct btf_node *node;
1857 
1858 		node = rb_entry(next, struct btf_node, rb_node);
1859 		next = rb_next(&node->rb_node);
1860 		fprintf(fp, "# btf info of id %u\n", node->id);
1861 	}
1862 
1863 	up_read(&env->bpf_progs.lock);
1864 }
1865 #endif // HAVE_LIBBPF_SUPPORT
1866 
free_event_desc(struct evsel * events)1867 static void free_event_desc(struct evsel *events)
1868 {
1869 	struct evsel *evsel;
1870 
1871 	if (!events)
1872 		return;
1873 
1874 	for (evsel = events; evsel->core.attr.size; evsel++) {
1875 		zfree(&evsel->name);
1876 		zfree(&evsel->core.id);
1877 	}
1878 
1879 	free(events);
1880 }
1881 
perf_attr_check(struct perf_event_attr * attr)1882 static bool perf_attr_check(struct perf_event_attr *attr)
1883 {
1884 	if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3) {
1885 		pr_warning("Reserved bits are set unexpectedly. "
1886 			   "Please update perf tool.\n");
1887 		return false;
1888 	}
1889 
1890 	if (attr->sample_type & ~(PERF_SAMPLE_MAX-1)) {
1891 		pr_warning("Unknown sample type (0x%llx) is detected. "
1892 			   "Please update perf tool.\n",
1893 			   attr->sample_type);
1894 		return false;
1895 	}
1896 
1897 	if (attr->read_format & ~(PERF_FORMAT_MAX-1)) {
1898 		pr_warning("Unknown read format (0x%llx) is detected. "
1899 			   "Please update perf tool.\n",
1900 			   attr->read_format);
1901 		return false;
1902 	}
1903 
1904 	if ((attr->sample_type & PERF_SAMPLE_BRANCH_STACK) &&
1905 	    (attr->branch_sample_type & ~(PERF_SAMPLE_BRANCH_MAX-1))) {
1906 		pr_warning("Unknown branch sample type (0x%llx) is detected. "
1907 			   "Please update perf tool.\n",
1908 			   attr->branch_sample_type);
1909 
1910 		return false;
1911 	}
1912 
1913 	return true;
1914 }
1915 
read_event_desc(struct feat_fd * ff)1916 static struct evsel *read_event_desc(struct feat_fd *ff)
1917 {
1918 	struct evsel *evsel, *events = NULL;
1919 	u64 *id;
1920 	void *buf = NULL;
1921 	u32 nre, sz, nr, i, j;
1922 	size_t msz;
1923 
1924 	/* number of events */
1925 	if (do_read_u32(ff, &nre))
1926 		goto error;
1927 
1928 	if (do_read_u32(ff, &sz))
1929 		goto error;
1930 
1931 	/* buffer to hold on file attr struct */
1932 	buf = malloc(sz);
1933 	if (!buf)
1934 		goto error;
1935 
1936 	/* the last event terminates with evsel->core.attr.size == 0: */
1937 	events = calloc(nre + 1, sizeof(*events));
1938 	if (!events)
1939 		goto error;
1940 
1941 	msz = sizeof(evsel->core.attr);
1942 	if (sz < msz)
1943 		msz = sz;
1944 
1945 	for (i = 0, evsel = events; i < nre; evsel++, i++) {
1946 		evsel->core.idx = i;
1947 
1948 		/*
1949 		 * must read entire on-file attr struct to
1950 		 * sync up with layout.
1951 		 */
1952 		if (__do_read(ff, buf, sz))
1953 			goto error;
1954 
1955 		if (ff->ph->needs_swap)
1956 			perf_event__attr_swap(buf);
1957 
1958 		memcpy(&evsel->core.attr, buf, msz);
1959 
1960 		if (!perf_attr_check(&evsel->core.attr))
1961 			goto error;
1962 
1963 		if (do_read_u32(ff, &nr))
1964 			goto error;
1965 
1966 		if (ff->ph->needs_swap)
1967 			evsel->needs_swap = true;
1968 
1969 		evsel->name = do_read_string(ff);
1970 		if (!evsel->name)
1971 			goto error;
1972 
1973 		if (!nr)
1974 			continue;
1975 
1976 		id = calloc(nr, sizeof(*id));
1977 		if (!id)
1978 			goto error;
1979 		evsel->core.ids = nr;
1980 		evsel->core.id = id;
1981 
1982 		for (j = 0 ; j < nr; j++) {
1983 			if (do_read_u64(ff, id))
1984 				goto error;
1985 			id++;
1986 		}
1987 	}
1988 out:
1989 	free(buf);
1990 	return events;
1991 error:
1992 	free_event_desc(events);
1993 	events = NULL;
1994 	goto out;
1995 }
1996 
__desc_attr__fprintf(FILE * fp,const char * name,const char * val,void * priv __maybe_unused)1997 static int __desc_attr__fprintf(FILE *fp, const char *name, const char *val,
1998 				void *priv __maybe_unused)
1999 {
2000 	return fprintf(fp, ", %s = %s", name, val);
2001 }
2002 
print_event_desc(struct feat_fd * ff,FILE * fp)2003 static void print_event_desc(struct feat_fd *ff, FILE *fp)
2004 {
2005 	struct evsel *evsel, *events;
2006 	u32 j;
2007 	u64 *id;
2008 
2009 	if (ff->events)
2010 		events = ff->events;
2011 	else
2012 		events = read_event_desc(ff);
2013 
2014 	if (!events) {
2015 		fprintf(fp, "# event desc: not available or unable to read\n");
2016 		return;
2017 	}
2018 
2019 	for (evsel = events; evsel->core.attr.size; evsel++) {
2020 		fprintf(fp, "# event : name = %s, ", evsel->name);
2021 
2022 		if (evsel->core.ids) {
2023 			fprintf(fp, ", id = {");
2024 			for (j = 0, id = evsel->core.id; j < evsel->core.ids; j++, id++) {
2025 				if (j)
2026 					fputc(',', fp);
2027 				fprintf(fp, " %"PRIu64, *id);
2028 			}
2029 			fprintf(fp, " }");
2030 		}
2031 
2032 		perf_event_attr__fprintf(fp, &evsel->core.attr, __desc_attr__fprintf, NULL);
2033 
2034 		fputc('\n', fp);
2035 	}
2036 
2037 	free_event_desc(events);
2038 	ff->events = NULL;
2039 }
2040 
print_total_mem(struct feat_fd * ff,FILE * fp)2041 static void print_total_mem(struct feat_fd *ff, FILE *fp)
2042 {
2043 	fprintf(fp, "# total memory : %llu kB\n", ff->ph->env.total_mem);
2044 }
2045 
print_numa_topology(struct feat_fd * ff,FILE * fp)2046 static void print_numa_topology(struct feat_fd *ff, FILE *fp)
2047 {
2048 	int i;
2049 	struct numa_node *n;
2050 
2051 	for (i = 0; i < ff->ph->env.nr_numa_nodes; i++) {
2052 		n = &ff->ph->env.numa_nodes[i];
2053 
2054 		fprintf(fp, "# node%u meminfo  : total = %"PRIu64" kB,"
2055 			    " free = %"PRIu64" kB\n",
2056 			n->node, n->mem_total, n->mem_free);
2057 
2058 		fprintf(fp, "# node%u cpu list : ", n->node);
2059 		cpu_map__fprintf(n->map, fp);
2060 	}
2061 }
2062 
print_cpuid(struct feat_fd * ff,FILE * fp)2063 static void print_cpuid(struct feat_fd *ff, FILE *fp)
2064 {
2065 	fprintf(fp, "# cpuid : %s\n", ff->ph->env.cpuid);
2066 }
2067 
print_branch_stack(struct feat_fd * ff __maybe_unused,FILE * fp)2068 static void print_branch_stack(struct feat_fd *ff __maybe_unused, FILE *fp)
2069 {
2070 	fprintf(fp, "# contains samples with branch stack\n");
2071 }
2072 
print_auxtrace(struct feat_fd * ff __maybe_unused,FILE * fp)2073 static void print_auxtrace(struct feat_fd *ff __maybe_unused, FILE *fp)
2074 {
2075 	fprintf(fp, "# contains AUX area data (e.g. instruction trace)\n");
2076 }
2077 
print_stat(struct feat_fd * ff __maybe_unused,FILE * fp)2078 static void print_stat(struct feat_fd *ff __maybe_unused, FILE *fp)
2079 {
2080 	fprintf(fp, "# contains stat data\n");
2081 }
2082 
print_cache(struct feat_fd * ff,FILE * fp __maybe_unused)2083 static void print_cache(struct feat_fd *ff, FILE *fp __maybe_unused)
2084 {
2085 	int i;
2086 
2087 	fprintf(fp, "# CPU cache info:\n");
2088 	for (i = 0; i < ff->ph->env.caches_cnt; i++) {
2089 		fprintf(fp, "#  ");
2090 		cpu_cache_level__fprintf(fp, &ff->ph->env.caches[i]);
2091 	}
2092 }
2093 
print_compressed(struct feat_fd * ff,FILE * fp)2094 static void print_compressed(struct feat_fd *ff, FILE *fp)
2095 {
2096 	fprintf(fp, "# compressed : %s, level = %d, ratio = %d\n",
2097 		ff->ph->env.comp_type == PERF_COMP_ZSTD ? "Zstd" : "Unknown",
2098 		ff->ph->env.comp_level, ff->ph->env.comp_ratio);
2099 }
2100 
__print_pmu_caps(FILE * fp,int nr_caps,char ** caps,char * pmu_name)2101 static void __print_pmu_caps(FILE *fp, int nr_caps, char **caps, char *pmu_name)
2102 {
2103 	const char *delimiter = "";
2104 	int i;
2105 
2106 	if (!nr_caps) {
2107 		fprintf(fp, "# %s pmu capabilities: not available\n", pmu_name);
2108 		return;
2109 	}
2110 
2111 	fprintf(fp, "# %s pmu capabilities: ", pmu_name);
2112 	for (i = 0; i < nr_caps; i++) {
2113 		fprintf(fp, "%s%s", delimiter, caps[i]);
2114 		delimiter = ", ";
2115 	}
2116 
2117 	fprintf(fp, "\n");
2118 }
2119 
print_cpu_pmu_caps(struct feat_fd * ff,FILE * fp)2120 static void print_cpu_pmu_caps(struct feat_fd *ff, FILE *fp)
2121 {
2122 	__print_pmu_caps(fp, ff->ph->env.nr_cpu_pmu_caps,
2123 			 ff->ph->env.cpu_pmu_caps, (char *)"cpu");
2124 }
2125 
print_pmu_caps(struct feat_fd * ff,FILE * fp)2126 static void print_pmu_caps(struct feat_fd *ff, FILE *fp)
2127 {
2128 	struct perf_env *env = &ff->ph->env;
2129 	struct pmu_caps *pmu_caps;
2130 
2131 	for (int i = 0; i < env->nr_pmus_with_caps; i++) {
2132 		pmu_caps = &env->pmu_caps[i];
2133 		__print_pmu_caps(fp, pmu_caps->nr_caps, pmu_caps->caps,
2134 				 pmu_caps->pmu_name);
2135 	}
2136 
2137 	if (strcmp(perf_env__arch(env), "x86") == 0 &&
2138 	    perf_env__has_pmu_mapping(env, "ibs_op")) {
2139 		char *max_precise = perf_env__find_pmu_cap(env, "cpu", "max_precise");
2140 
2141 		if (max_precise != NULL && atoi(max_precise) == 0)
2142 			fprintf(fp, "# AMD systems uses ibs_op// PMU for some precise events, e.g.: cycles:p, see the 'perf list' man page for further details.\n");
2143 	}
2144 }
2145 
print_pmu_mappings(struct feat_fd * ff,FILE * fp)2146 static void print_pmu_mappings(struct feat_fd *ff, FILE *fp)
2147 {
2148 	struct perf_env *env = &ff->ph->env;
2149 	const char *delimiter = "# pmu mappings: ";
2150 	char *str, *tmp;
2151 	u32 pmu_num;
2152 	u32 type;
2153 
2154 	pmu_num = env->nr_pmu_mappings;
2155 	if (!pmu_num) {
2156 		fprintf(fp, "# pmu mappings: not available\n");
2157 		return;
2158 	}
2159 
2160 	str = env->pmu_mappings;
2161 
2162 	while (pmu_num) {
2163 		type = strtoul(str, &tmp, 0);
2164 		if (*tmp != ':')
2165 			goto error;
2166 
2167 		str = tmp + 1;
2168 		fprintf(fp, "%s%s = %" PRIu32, delimiter, str, type);
2169 
2170 		delimiter = ", ";
2171 		str += strlen(str) + 1;
2172 		pmu_num--;
2173 	}
2174 
2175 	fprintf(fp, "\n");
2176 
2177 	if (!pmu_num)
2178 		return;
2179 error:
2180 	fprintf(fp, "# pmu mappings: unable to read\n");
2181 }
2182 
print_group_desc(struct feat_fd * ff,FILE * fp)2183 static void print_group_desc(struct feat_fd *ff, FILE *fp)
2184 {
2185 	struct perf_session *session;
2186 	struct evsel *evsel;
2187 	u32 nr = 0;
2188 
2189 	session = container_of(ff->ph, struct perf_session, header);
2190 
2191 	evlist__for_each_entry(session->evlist, evsel) {
2192 		if (evsel__is_group_leader(evsel) && evsel->core.nr_members > 1) {
2193 			fprintf(fp, "# group: %s{%s", evsel->group_name ?: "", evsel__name(evsel));
2194 
2195 			nr = evsel->core.nr_members - 1;
2196 		} else if (nr) {
2197 			fprintf(fp, ",%s", evsel__name(evsel));
2198 
2199 			if (--nr == 0)
2200 				fprintf(fp, "}\n");
2201 		}
2202 	}
2203 }
2204 
print_sample_time(struct feat_fd * ff,FILE * fp)2205 static void print_sample_time(struct feat_fd *ff, FILE *fp)
2206 {
2207 	struct perf_session *session;
2208 	char time_buf[32];
2209 	double d;
2210 
2211 	session = container_of(ff->ph, struct perf_session, header);
2212 
2213 	timestamp__scnprintf_usec(session->evlist->first_sample_time,
2214 				  time_buf, sizeof(time_buf));
2215 	fprintf(fp, "# time of first sample : %s\n", time_buf);
2216 
2217 	timestamp__scnprintf_usec(session->evlist->last_sample_time,
2218 				  time_buf, sizeof(time_buf));
2219 	fprintf(fp, "# time of last sample : %s\n", time_buf);
2220 
2221 	d = (double)(session->evlist->last_sample_time -
2222 		session->evlist->first_sample_time) / NSEC_PER_MSEC;
2223 
2224 	fprintf(fp, "# sample duration : %10.3f ms\n", d);
2225 }
2226 
memory_node__fprintf(struct memory_node * n,unsigned long long bsize,FILE * fp)2227 static void memory_node__fprintf(struct memory_node *n,
2228 				 unsigned long long bsize, FILE *fp)
2229 {
2230 	char buf_map[100], buf_size[50];
2231 	unsigned long long size;
2232 
2233 	size = bsize * bitmap_weight(n->set, n->size);
2234 	unit_number__scnprintf(buf_size, 50, size);
2235 
2236 	bitmap_scnprintf(n->set, n->size, buf_map, 100);
2237 	fprintf(fp, "#  %3" PRIu64 " [%s]: %s\n", n->node, buf_size, buf_map);
2238 }
2239 
print_mem_topology(struct feat_fd * ff,FILE * fp)2240 static void print_mem_topology(struct feat_fd *ff, FILE *fp)
2241 {
2242 	struct perf_env *env = &ff->ph->env;
2243 	struct memory_node *nodes;
2244 	int i, nr;
2245 
2246 	nodes = env->memory_nodes;
2247 	nr    = env->nr_memory_nodes;
2248 
2249 	fprintf(fp, "# memory nodes (nr %d, block size 0x%llx):\n",
2250 		nr, env->memory_bsize);
2251 
2252 	for (i = 0; i < nr; i++) {
2253 		memory_node__fprintf(&nodes[i], env->memory_bsize, fp);
2254 	}
2255 }
2256 
__event_process_build_id(struct perf_record_header_build_id * bev,char * filename,struct perf_session * session)2257 static int __event_process_build_id(struct perf_record_header_build_id *bev,
2258 				    char *filename,
2259 				    struct perf_session *session)
2260 {
2261 	int err = -1;
2262 	struct machine *machine;
2263 	u16 cpumode;
2264 	struct dso *dso;
2265 	enum dso_space_type dso_space;
2266 
2267 	machine = perf_session__findnew_machine(session, bev->pid);
2268 	if (!machine)
2269 		goto out;
2270 
2271 	cpumode = bev->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
2272 
2273 	switch (cpumode) {
2274 	case PERF_RECORD_MISC_KERNEL:
2275 		dso_space = DSO_SPACE__KERNEL;
2276 		break;
2277 	case PERF_RECORD_MISC_GUEST_KERNEL:
2278 		dso_space = DSO_SPACE__KERNEL_GUEST;
2279 		break;
2280 	case PERF_RECORD_MISC_USER:
2281 	case PERF_RECORD_MISC_GUEST_USER:
2282 		dso_space = DSO_SPACE__USER;
2283 		break;
2284 	default:
2285 		goto out;
2286 	}
2287 
2288 	dso = machine__findnew_dso(machine, filename);
2289 	if (dso != NULL) {
2290 		char sbuild_id[SBUILD_ID_SIZE];
2291 		struct build_id bid;
2292 		size_t size = BUILD_ID_SIZE;
2293 
2294 		if (bev->header.misc & PERF_RECORD_MISC_BUILD_ID_SIZE)
2295 			size = bev->size;
2296 
2297 		build_id__init(&bid, bev->data, size);
2298 		dso__set_build_id(dso, &bid);
2299 		dso__set_header_build_id(dso, true);
2300 
2301 		if (dso_space != DSO_SPACE__USER) {
2302 			struct kmod_path m = { .name = NULL, };
2303 
2304 			if (!kmod_path__parse_name(&m, filename) && m.kmod)
2305 				dso__set_module_info(dso, &m, machine);
2306 
2307 			dso__set_kernel(dso, dso_space);
2308 			free(m.name);
2309 		}
2310 
2311 		build_id__snprintf(dso__bid(dso), sbuild_id, sizeof(sbuild_id));
2312 		pr_debug("build id event received for %s: %s [%zu]\n",
2313 			 dso__long_name(dso), sbuild_id, size);
2314 		dso__put(dso);
2315 	}
2316 
2317 	err = 0;
2318 out:
2319 	return err;
2320 }
2321 
perf_header__read_build_ids_abi_quirk(struct perf_header * header,int input,u64 offset,u64 size)2322 static int perf_header__read_build_ids_abi_quirk(struct perf_header *header,
2323 						 int input, u64 offset, u64 size)
2324 {
2325 	struct perf_session *session = container_of(header, struct perf_session, header);
2326 	struct {
2327 		struct perf_event_header   header;
2328 		u8			   build_id[PERF_ALIGN(BUILD_ID_SIZE, sizeof(u64))];
2329 		char			   filename[0];
2330 	} old_bev;
2331 	struct perf_record_header_build_id bev;
2332 	char filename[PATH_MAX];
2333 	u64 limit = offset + size;
2334 
2335 	while (offset < limit) {
2336 		ssize_t len;
2337 
2338 		if (readn(input, &old_bev, sizeof(old_bev)) != sizeof(old_bev))
2339 			return -1;
2340 
2341 		if (header->needs_swap)
2342 			perf_event_header__bswap(&old_bev.header);
2343 
2344 		len = old_bev.header.size - sizeof(old_bev);
2345 		if (readn(input, filename, len) != len)
2346 			return -1;
2347 
2348 		bev.header = old_bev.header;
2349 
2350 		/*
2351 		 * As the pid is the missing value, we need to fill
2352 		 * it properly. The header.misc value give us nice hint.
2353 		 */
2354 		bev.pid	= HOST_KERNEL_ID;
2355 		if (bev.header.misc == PERF_RECORD_MISC_GUEST_USER ||
2356 		    bev.header.misc == PERF_RECORD_MISC_GUEST_KERNEL)
2357 			bev.pid	= DEFAULT_GUEST_KERNEL_ID;
2358 
2359 		memcpy(bev.build_id, old_bev.build_id, sizeof(bev.build_id));
2360 		__event_process_build_id(&bev, filename, session);
2361 
2362 		offset += bev.header.size;
2363 	}
2364 
2365 	return 0;
2366 }
2367 
perf_header__read_build_ids(struct perf_header * header,int input,u64 offset,u64 size)2368 static int perf_header__read_build_ids(struct perf_header *header,
2369 				       int input, u64 offset, u64 size)
2370 {
2371 	struct perf_session *session = container_of(header, struct perf_session, header);
2372 	struct perf_record_header_build_id bev;
2373 	char filename[PATH_MAX];
2374 	u64 limit = offset + size, orig_offset = offset;
2375 	int err = -1;
2376 
2377 	while (offset < limit) {
2378 		ssize_t len;
2379 
2380 		if (readn(input, &bev, sizeof(bev)) != sizeof(bev))
2381 			goto out;
2382 
2383 		if (header->needs_swap)
2384 			perf_event_header__bswap(&bev.header);
2385 
2386 		len = bev.header.size - sizeof(bev);
2387 		if (readn(input, filename, len) != len)
2388 			goto out;
2389 		/*
2390 		 * The a1645ce1 changeset:
2391 		 *
2392 		 * "perf: 'perf kvm' tool for monitoring guest performance from host"
2393 		 *
2394 		 * Added a field to struct perf_record_header_build_id that broke the file
2395 		 * format.
2396 		 *
2397 		 * Since the kernel build-id is the first entry, process the
2398 		 * table using the old format if the well known
2399 		 * '[kernel.kallsyms]' string for the kernel build-id has the
2400 		 * first 4 characters chopped off (where the pid_t sits).
2401 		 */
2402 		if (memcmp(filename, "nel.kallsyms]", 13) == 0) {
2403 			if (lseek(input, orig_offset, SEEK_SET) == (off_t)-1)
2404 				return -1;
2405 			return perf_header__read_build_ids_abi_quirk(header, input, offset, size);
2406 		}
2407 
2408 		__event_process_build_id(&bev, filename, session);
2409 
2410 		offset += bev.header.size;
2411 	}
2412 	err = 0;
2413 out:
2414 	return err;
2415 }
2416 
2417 /* Macro for features that simply need to read and store a string. */
2418 #define FEAT_PROCESS_STR_FUN(__feat, __feat_env) \
2419 static int process_##__feat(struct feat_fd *ff, void *data __maybe_unused) \
2420 {\
2421 	free(ff->ph->env.__feat_env);		     \
2422 	ff->ph->env.__feat_env = do_read_string(ff); \
2423 	return ff->ph->env.__feat_env ? 0 : -ENOMEM; \
2424 }
2425 
2426 FEAT_PROCESS_STR_FUN(hostname, hostname);
2427 FEAT_PROCESS_STR_FUN(osrelease, os_release);
2428 FEAT_PROCESS_STR_FUN(version, version);
2429 FEAT_PROCESS_STR_FUN(arch, arch);
2430 FEAT_PROCESS_STR_FUN(cpudesc, cpu_desc);
2431 FEAT_PROCESS_STR_FUN(cpuid, cpuid);
2432 
2433 #ifdef HAVE_LIBTRACEEVENT
process_tracing_data(struct feat_fd * ff,void * data)2434 static int process_tracing_data(struct feat_fd *ff, void *data)
2435 {
2436 	ssize_t ret = trace_report(ff->fd, data, false);
2437 
2438 	return ret < 0 ? -1 : 0;
2439 }
2440 #endif
2441 
process_build_id(struct feat_fd * ff,void * data __maybe_unused)2442 static int process_build_id(struct feat_fd *ff, void *data __maybe_unused)
2443 {
2444 	if (perf_header__read_build_ids(ff->ph, ff->fd, ff->offset, ff->size))
2445 		pr_debug("Failed to read buildids, continuing...\n");
2446 	return 0;
2447 }
2448 
process_nrcpus(struct feat_fd * ff,void * data __maybe_unused)2449 static int process_nrcpus(struct feat_fd *ff, void *data __maybe_unused)
2450 {
2451 	struct perf_env *env = &ff->ph->env;
2452 	int ret;
2453 	u32 nr_cpus_avail, nr_cpus_online;
2454 
2455 	ret = do_read_u32(ff, &nr_cpus_avail);
2456 	if (ret)
2457 		return ret;
2458 
2459 	ret = do_read_u32(ff, &nr_cpus_online);
2460 	if (ret)
2461 		return ret;
2462 	env->nr_cpus_avail = (int)nr_cpus_avail;
2463 	env->nr_cpus_online = (int)nr_cpus_online;
2464 	return 0;
2465 }
2466 
process_total_mem(struct feat_fd * ff,void * data __maybe_unused)2467 static int process_total_mem(struct feat_fd *ff, void *data __maybe_unused)
2468 {
2469 	struct perf_env *env = &ff->ph->env;
2470 	u64 total_mem;
2471 	int ret;
2472 
2473 	ret = do_read_u64(ff, &total_mem);
2474 	if (ret)
2475 		return -1;
2476 	env->total_mem = (unsigned long long)total_mem;
2477 	return 0;
2478 }
2479 
evlist__find_by_index(struct evlist * evlist,int idx)2480 static struct evsel *evlist__find_by_index(struct evlist *evlist, int idx)
2481 {
2482 	struct evsel *evsel;
2483 
2484 	evlist__for_each_entry(evlist, evsel) {
2485 		if (evsel->core.idx == idx)
2486 			return evsel;
2487 	}
2488 
2489 	return NULL;
2490 }
2491 
evlist__set_event_name(struct evlist * evlist,struct evsel * event)2492 static void evlist__set_event_name(struct evlist *evlist, struct evsel *event)
2493 {
2494 	struct evsel *evsel;
2495 
2496 	if (!event->name)
2497 		return;
2498 
2499 	evsel = evlist__find_by_index(evlist, event->core.idx);
2500 	if (!evsel)
2501 		return;
2502 
2503 	if (evsel->name)
2504 		return;
2505 
2506 	evsel->name = strdup(event->name);
2507 }
2508 
2509 static int
process_event_desc(struct feat_fd * ff,void * data __maybe_unused)2510 process_event_desc(struct feat_fd *ff, void *data __maybe_unused)
2511 {
2512 	struct perf_session *session;
2513 	struct evsel *evsel, *events = read_event_desc(ff);
2514 
2515 	if (!events)
2516 		return 0;
2517 
2518 	session = container_of(ff->ph, struct perf_session, header);
2519 
2520 	if (session->data->is_pipe) {
2521 		/* Save events for reading later by print_event_desc,
2522 		 * since they can't be read again in pipe mode. */
2523 		ff->events = events;
2524 	}
2525 
2526 	for (evsel = events; evsel->core.attr.size; evsel++)
2527 		evlist__set_event_name(session->evlist, evsel);
2528 
2529 	if (!session->data->is_pipe)
2530 		free_event_desc(events);
2531 
2532 	return 0;
2533 }
2534 
process_cmdline(struct feat_fd * ff,void * data __maybe_unused)2535 static int process_cmdline(struct feat_fd *ff, void *data __maybe_unused)
2536 {
2537 	struct perf_env *env = &ff->ph->env;
2538 	char *str, *cmdline = NULL, **argv = NULL;
2539 	u32 nr, i, len = 0;
2540 
2541 	if (do_read_u32(ff, &nr))
2542 		return -1;
2543 
2544 	env->nr_cmdline = nr;
2545 
2546 	cmdline = zalloc(ff->size + nr + 1);
2547 	if (!cmdline)
2548 		return -1;
2549 
2550 	argv = zalloc(sizeof(char *) * (nr + 1));
2551 	if (!argv)
2552 		goto error;
2553 
2554 	for (i = 0; i < nr; i++) {
2555 		str = do_read_string(ff);
2556 		if (!str)
2557 			goto error;
2558 
2559 		argv[i] = cmdline + len;
2560 		memcpy(argv[i], str, strlen(str) + 1);
2561 		len += strlen(str) + 1;
2562 		free(str);
2563 	}
2564 	env->cmdline = cmdline;
2565 	env->cmdline_argv = (const char **) argv;
2566 	return 0;
2567 
2568 error:
2569 	free(argv);
2570 	free(cmdline);
2571 	return -1;
2572 }
2573 
process_cpu_topology(struct feat_fd * ff,void * data __maybe_unused)2574 static int process_cpu_topology(struct feat_fd *ff, void *data __maybe_unused)
2575 {
2576 	u32 nr, i;
2577 	char *str = NULL;
2578 	struct strbuf sb;
2579 	struct perf_env *env = &ff->ph->env;
2580 	int cpu_nr = env->nr_cpus_avail;
2581 	u64 size = 0;
2582 
2583 	env->cpu = calloc(cpu_nr, sizeof(*env->cpu));
2584 	if (!env->cpu)
2585 		return -1;
2586 
2587 	if (do_read_u32(ff, &nr))
2588 		goto free_cpu;
2589 
2590 	env->nr_sibling_cores = nr;
2591 	size += sizeof(u32);
2592 	if (strbuf_init(&sb, 128) < 0)
2593 		goto free_cpu;
2594 
2595 	for (i = 0; i < nr; i++) {
2596 		str = do_read_string(ff);
2597 		if (!str)
2598 			goto error;
2599 
2600 		/* include a NULL character at the end */
2601 		if (strbuf_add(&sb, str, strlen(str) + 1) < 0)
2602 			goto error;
2603 		size += string_size(str);
2604 		zfree(&str);
2605 	}
2606 	env->sibling_cores = strbuf_detach(&sb, NULL);
2607 
2608 	if (do_read_u32(ff, &nr))
2609 		return -1;
2610 
2611 	env->nr_sibling_threads = nr;
2612 	size += sizeof(u32);
2613 
2614 	for (i = 0; i < nr; i++) {
2615 		str = do_read_string(ff);
2616 		if (!str)
2617 			goto error;
2618 
2619 		/* include a NULL character at the end */
2620 		if (strbuf_add(&sb, str, strlen(str) + 1) < 0)
2621 			goto error;
2622 		size += string_size(str);
2623 		zfree(&str);
2624 	}
2625 	env->sibling_threads = strbuf_detach(&sb, NULL);
2626 
2627 	/*
2628 	 * The header may be from old perf,
2629 	 * which doesn't include core id and socket id information.
2630 	 */
2631 	if (ff->size <= size) {
2632 		zfree(&env->cpu);
2633 		return 0;
2634 	}
2635 
2636 	for (i = 0; i < (u32)cpu_nr; i++) {
2637 		if (do_read_u32(ff, &nr))
2638 			goto free_cpu;
2639 
2640 		env->cpu[i].core_id = nr;
2641 		size += sizeof(u32);
2642 
2643 		if (do_read_u32(ff, &nr))
2644 			goto free_cpu;
2645 
2646 		env->cpu[i].socket_id = nr;
2647 		size += sizeof(u32);
2648 	}
2649 
2650 	/*
2651 	 * The header may be from old perf,
2652 	 * which doesn't include die information.
2653 	 */
2654 	if (ff->size <= size)
2655 		return 0;
2656 
2657 	if (do_read_u32(ff, &nr))
2658 		return -1;
2659 
2660 	env->nr_sibling_dies = nr;
2661 	size += sizeof(u32);
2662 
2663 	for (i = 0; i < nr; i++) {
2664 		str = do_read_string(ff);
2665 		if (!str)
2666 			goto error;
2667 
2668 		/* include a NULL character at the end */
2669 		if (strbuf_add(&sb, str, strlen(str) + 1) < 0)
2670 			goto error;
2671 		size += string_size(str);
2672 		zfree(&str);
2673 	}
2674 	env->sibling_dies = strbuf_detach(&sb, NULL);
2675 
2676 	for (i = 0; i < (u32)cpu_nr; i++) {
2677 		if (do_read_u32(ff, &nr))
2678 			goto free_cpu;
2679 
2680 		env->cpu[i].die_id = nr;
2681 	}
2682 
2683 	return 0;
2684 
2685 error:
2686 	strbuf_release(&sb);
2687 	zfree(&str);
2688 free_cpu:
2689 	zfree(&env->cpu);
2690 	return -1;
2691 }
2692 
process_numa_topology(struct feat_fd * ff,void * data __maybe_unused)2693 static int process_numa_topology(struct feat_fd *ff, void *data __maybe_unused)
2694 {
2695 	struct perf_env *env = &ff->ph->env;
2696 	struct numa_node *nodes, *n;
2697 	u32 nr, i;
2698 	char *str;
2699 
2700 	/* nr nodes */
2701 	if (do_read_u32(ff, &nr))
2702 		return -1;
2703 
2704 	nodes = zalloc(sizeof(*nodes) * nr);
2705 	if (!nodes)
2706 		return -ENOMEM;
2707 
2708 	for (i = 0; i < nr; i++) {
2709 		n = &nodes[i];
2710 
2711 		/* node number */
2712 		if (do_read_u32(ff, &n->node))
2713 			goto error;
2714 
2715 		if (do_read_u64(ff, &n->mem_total))
2716 			goto error;
2717 
2718 		if (do_read_u64(ff, &n->mem_free))
2719 			goto error;
2720 
2721 		str = do_read_string(ff);
2722 		if (!str)
2723 			goto error;
2724 
2725 		n->map = perf_cpu_map__new(str);
2726 		free(str);
2727 		if (!n->map)
2728 			goto error;
2729 	}
2730 	env->nr_numa_nodes = nr;
2731 	env->numa_nodes = nodes;
2732 	return 0;
2733 
2734 error:
2735 	free(nodes);
2736 	return -1;
2737 }
2738 
process_pmu_mappings(struct feat_fd * ff,void * data __maybe_unused)2739 static int process_pmu_mappings(struct feat_fd *ff, void *data __maybe_unused)
2740 {
2741 	struct perf_env *env = &ff->ph->env;
2742 	char *name;
2743 	u32 pmu_num;
2744 	u32 type;
2745 	struct strbuf sb;
2746 
2747 	if (do_read_u32(ff, &pmu_num))
2748 		return -1;
2749 
2750 	if (!pmu_num) {
2751 		pr_debug("pmu mappings not available\n");
2752 		return 0;
2753 	}
2754 
2755 	env->nr_pmu_mappings = pmu_num;
2756 	if (strbuf_init(&sb, 128) < 0)
2757 		return -1;
2758 
2759 	while (pmu_num) {
2760 		if (do_read_u32(ff, &type))
2761 			goto error;
2762 
2763 		name = do_read_string(ff);
2764 		if (!name)
2765 			goto error;
2766 
2767 		if (strbuf_addf(&sb, "%u:%s", type, name) < 0)
2768 			goto error;
2769 		/* include a NULL character at the end */
2770 		if (strbuf_add(&sb, "", 1) < 0)
2771 			goto error;
2772 
2773 		if (!strcmp(name, "msr"))
2774 			env->msr_pmu_type = type;
2775 
2776 		free(name);
2777 		pmu_num--;
2778 	}
2779 	/* AMD may set it by evlist__has_amd_ibs() from perf_session__new() */
2780 	free(env->pmu_mappings);
2781 	env->pmu_mappings = strbuf_detach(&sb, NULL);
2782 	return 0;
2783 
2784 error:
2785 	strbuf_release(&sb);
2786 	return -1;
2787 }
2788 
process_group_desc(struct feat_fd * ff,void * data __maybe_unused)2789 static int process_group_desc(struct feat_fd *ff, void *data __maybe_unused)
2790 {
2791 	struct perf_env *env = &ff->ph->env;
2792 	size_t ret = -1;
2793 	u32 i, nr, nr_groups;
2794 	struct perf_session *session;
2795 	struct evsel *evsel, *leader = NULL;
2796 	struct group_desc {
2797 		char *name;
2798 		u32 leader_idx;
2799 		u32 nr_members;
2800 	} *desc;
2801 
2802 	if (do_read_u32(ff, &nr_groups))
2803 		return -1;
2804 
2805 	env->nr_groups = nr_groups;
2806 	if (!nr_groups) {
2807 		pr_debug("group desc not available\n");
2808 		return 0;
2809 	}
2810 
2811 	desc = calloc(nr_groups, sizeof(*desc));
2812 	if (!desc)
2813 		return -1;
2814 
2815 	for (i = 0; i < nr_groups; i++) {
2816 		desc[i].name = do_read_string(ff);
2817 		if (!desc[i].name)
2818 			goto out_free;
2819 
2820 		if (do_read_u32(ff, &desc[i].leader_idx))
2821 			goto out_free;
2822 
2823 		if (do_read_u32(ff, &desc[i].nr_members))
2824 			goto out_free;
2825 	}
2826 
2827 	/*
2828 	 * Rebuild group relationship based on the group_desc
2829 	 */
2830 	session = container_of(ff->ph, struct perf_session, header);
2831 
2832 	i = nr = 0;
2833 	evlist__for_each_entry(session->evlist, evsel) {
2834 		if (i < nr_groups && evsel->core.idx == (int) desc[i].leader_idx) {
2835 			evsel__set_leader(evsel, evsel);
2836 			/* {anon_group} is a dummy name */
2837 			if (strcmp(desc[i].name, "{anon_group}")) {
2838 				evsel->group_name = desc[i].name;
2839 				desc[i].name = NULL;
2840 			}
2841 			evsel->core.nr_members = desc[i].nr_members;
2842 
2843 			if (i >= nr_groups || nr > 0) {
2844 				pr_debug("invalid group desc\n");
2845 				goto out_free;
2846 			}
2847 
2848 			leader = evsel;
2849 			nr = evsel->core.nr_members - 1;
2850 			i++;
2851 		} else if (nr) {
2852 			/* This is a group member */
2853 			evsel__set_leader(evsel, leader);
2854 
2855 			nr--;
2856 		}
2857 	}
2858 
2859 	if (i != nr_groups || nr != 0) {
2860 		pr_debug("invalid group desc\n");
2861 		goto out_free;
2862 	}
2863 
2864 	ret = 0;
2865 out_free:
2866 	for (i = 0; i < nr_groups; i++)
2867 		zfree(&desc[i].name);
2868 	free(desc);
2869 
2870 	return ret;
2871 }
2872 
process_auxtrace(struct feat_fd * ff,void * data __maybe_unused)2873 static int process_auxtrace(struct feat_fd *ff, void *data __maybe_unused)
2874 {
2875 	struct perf_session *session;
2876 	int err;
2877 
2878 	session = container_of(ff->ph, struct perf_session, header);
2879 
2880 	err = auxtrace_index__process(ff->fd, ff->size, session,
2881 				      ff->ph->needs_swap);
2882 	if (err < 0)
2883 		pr_err("Failed to process auxtrace index\n");
2884 	return err;
2885 }
2886 
process_cache(struct feat_fd * ff,void * data __maybe_unused)2887 static int process_cache(struct feat_fd *ff, void *data __maybe_unused)
2888 {
2889 	struct perf_env *env = &ff->ph->env;
2890 	struct cpu_cache_level *caches;
2891 	u32 cnt, i, version;
2892 
2893 	if (do_read_u32(ff, &version))
2894 		return -1;
2895 
2896 	if (version != 1)
2897 		return -1;
2898 
2899 	if (do_read_u32(ff, &cnt))
2900 		return -1;
2901 
2902 	caches = zalloc(sizeof(*caches) * cnt);
2903 	if (!caches)
2904 		return -1;
2905 
2906 	for (i = 0; i < cnt; i++) {
2907 		struct cpu_cache_level *c = &caches[i];
2908 
2909 		#define _R(v)						\
2910 			if (do_read_u32(ff, &c->v))			\
2911 				goto out_free_caches;			\
2912 
2913 		_R(level)
2914 		_R(line_size)
2915 		_R(sets)
2916 		_R(ways)
2917 		#undef _R
2918 
2919 		#define _R(v)					\
2920 			c->v = do_read_string(ff);		\
2921 			if (!c->v)				\
2922 				goto out_free_caches;		\
2923 
2924 		_R(type)
2925 		_R(size)
2926 		_R(map)
2927 		#undef _R
2928 	}
2929 
2930 	env->caches = caches;
2931 	env->caches_cnt = cnt;
2932 	return 0;
2933 out_free_caches:
2934 	for (i = 0; i < cnt; i++) {
2935 		free(caches[i].type);
2936 		free(caches[i].size);
2937 		free(caches[i].map);
2938 	}
2939 	free(caches);
2940 	return -1;
2941 }
2942 
process_sample_time(struct feat_fd * ff,void * data __maybe_unused)2943 static int process_sample_time(struct feat_fd *ff, void *data __maybe_unused)
2944 {
2945 	struct perf_session *session;
2946 	u64 first_sample_time, last_sample_time;
2947 	int ret;
2948 
2949 	session = container_of(ff->ph, struct perf_session, header);
2950 
2951 	ret = do_read_u64(ff, &first_sample_time);
2952 	if (ret)
2953 		return -1;
2954 
2955 	ret = do_read_u64(ff, &last_sample_time);
2956 	if (ret)
2957 		return -1;
2958 
2959 	session->evlist->first_sample_time = first_sample_time;
2960 	session->evlist->last_sample_time = last_sample_time;
2961 	return 0;
2962 }
2963 
process_mem_topology(struct feat_fd * ff,void * data __maybe_unused)2964 static int process_mem_topology(struct feat_fd *ff,
2965 				void *data __maybe_unused)
2966 {
2967 	struct perf_env *env = &ff->ph->env;
2968 	struct memory_node *nodes;
2969 	u64 version, i, nr, bsize;
2970 	int ret = -1;
2971 
2972 	if (do_read_u64(ff, &version))
2973 		return -1;
2974 
2975 	if (version != 1)
2976 		return -1;
2977 
2978 	if (do_read_u64(ff, &bsize))
2979 		return -1;
2980 
2981 	if (do_read_u64(ff, &nr))
2982 		return -1;
2983 
2984 	nodes = zalloc(sizeof(*nodes) * nr);
2985 	if (!nodes)
2986 		return -1;
2987 
2988 	for (i = 0; i < nr; i++) {
2989 		struct memory_node n;
2990 
2991 		#define _R(v)				\
2992 			if (do_read_u64(ff, &n.v))	\
2993 				goto out;		\
2994 
2995 		_R(node)
2996 		_R(size)
2997 
2998 		#undef _R
2999 
3000 		if (do_read_bitmap(ff, &n.set, &n.size))
3001 			goto out;
3002 
3003 		nodes[i] = n;
3004 	}
3005 
3006 	env->memory_bsize    = bsize;
3007 	env->memory_nodes    = nodes;
3008 	env->nr_memory_nodes = nr;
3009 	ret = 0;
3010 
3011 out:
3012 	if (ret)
3013 		free(nodes);
3014 	return ret;
3015 }
3016 
process_clockid(struct feat_fd * ff,void * data __maybe_unused)3017 static int process_clockid(struct feat_fd *ff,
3018 			   void *data __maybe_unused)
3019 {
3020 	struct perf_env *env = &ff->ph->env;
3021 
3022 	if (do_read_u64(ff, &env->clock.clockid_res_ns))
3023 		return -1;
3024 
3025 	return 0;
3026 }
3027 
process_clock_data(struct feat_fd * ff,void * _data __maybe_unused)3028 static int process_clock_data(struct feat_fd *ff,
3029 			      void *_data __maybe_unused)
3030 {
3031 	struct perf_env *env = &ff->ph->env;
3032 	u32 data32;
3033 	u64 data64;
3034 
3035 	/* version */
3036 	if (do_read_u32(ff, &data32))
3037 		return -1;
3038 
3039 	if (data32 != 1)
3040 		return -1;
3041 
3042 	/* clockid */
3043 	if (do_read_u32(ff, &data32))
3044 		return -1;
3045 
3046 	env->clock.clockid = data32;
3047 
3048 	/* TOD ref time */
3049 	if (do_read_u64(ff, &data64))
3050 		return -1;
3051 
3052 	env->clock.tod_ns = data64;
3053 
3054 	/* clockid ref time */
3055 	if (do_read_u64(ff, &data64))
3056 		return -1;
3057 
3058 	env->clock.clockid_ns = data64;
3059 	env->clock.enabled = true;
3060 	return 0;
3061 }
3062 
process_hybrid_topology(struct feat_fd * ff,void * data __maybe_unused)3063 static int process_hybrid_topology(struct feat_fd *ff,
3064 				   void *data __maybe_unused)
3065 {
3066 	struct perf_env *env = &ff->ph->env;
3067 	struct hybrid_node *nodes, *n;
3068 	u32 nr, i;
3069 
3070 	/* nr nodes */
3071 	if (do_read_u32(ff, &nr))
3072 		return -1;
3073 
3074 	nodes = zalloc(sizeof(*nodes) * nr);
3075 	if (!nodes)
3076 		return -ENOMEM;
3077 
3078 	for (i = 0; i < nr; i++) {
3079 		n = &nodes[i];
3080 
3081 		n->pmu_name = do_read_string(ff);
3082 		if (!n->pmu_name)
3083 			goto error;
3084 
3085 		n->cpus = do_read_string(ff);
3086 		if (!n->cpus)
3087 			goto error;
3088 	}
3089 
3090 	env->nr_hybrid_nodes = nr;
3091 	env->hybrid_nodes = nodes;
3092 	return 0;
3093 
3094 error:
3095 	for (i = 0; i < nr; i++) {
3096 		free(nodes[i].pmu_name);
3097 		free(nodes[i].cpus);
3098 	}
3099 
3100 	free(nodes);
3101 	return -1;
3102 }
3103 
process_dir_format(struct feat_fd * ff,void * _data __maybe_unused)3104 static int process_dir_format(struct feat_fd *ff,
3105 			      void *_data __maybe_unused)
3106 {
3107 	struct perf_session *session;
3108 	struct perf_data *data;
3109 
3110 	session = container_of(ff->ph, struct perf_session, header);
3111 	data = session->data;
3112 
3113 	if (WARN_ON(!perf_data__is_dir(data)))
3114 		return -1;
3115 
3116 	return do_read_u64(ff, &data->dir.version);
3117 }
3118 
3119 #ifdef HAVE_LIBBPF_SUPPORT
process_bpf_prog_info(struct feat_fd * ff,void * data __maybe_unused)3120 static int process_bpf_prog_info(struct feat_fd *ff, void *data __maybe_unused)
3121 {
3122 	struct bpf_prog_info_node *info_node;
3123 	struct perf_env *env = &ff->ph->env;
3124 	struct perf_bpil *info_linear;
3125 	u32 count, i;
3126 	int err = -1;
3127 
3128 	if (ff->ph->needs_swap) {
3129 		pr_warning("interpreting bpf_prog_info from systems with endianness is not yet supported\n");
3130 		return 0;
3131 	}
3132 
3133 	if (do_read_u32(ff, &count))
3134 		return -1;
3135 
3136 	down_write(&env->bpf_progs.lock);
3137 
3138 	for (i = 0; i < count; ++i) {
3139 		u32 info_len, data_len;
3140 
3141 		info_linear = NULL;
3142 		info_node = NULL;
3143 		if (do_read_u32(ff, &info_len))
3144 			goto out;
3145 		if (do_read_u32(ff, &data_len))
3146 			goto out;
3147 
3148 		if (info_len > sizeof(struct bpf_prog_info)) {
3149 			pr_warning("detected invalid bpf_prog_info\n");
3150 			goto out;
3151 		}
3152 
3153 		info_linear = malloc(sizeof(struct perf_bpil) +
3154 				     data_len);
3155 		if (!info_linear)
3156 			goto out;
3157 		info_linear->info_len = sizeof(struct bpf_prog_info);
3158 		info_linear->data_len = data_len;
3159 		if (do_read_u64(ff, (u64 *)(&info_linear->arrays)))
3160 			goto out;
3161 		if (__do_read(ff, &info_linear->info, info_len))
3162 			goto out;
3163 		if (info_len < sizeof(struct bpf_prog_info))
3164 			memset(((void *)(&info_linear->info)) + info_len, 0,
3165 			       sizeof(struct bpf_prog_info) - info_len);
3166 
3167 		if (__do_read(ff, info_linear->data, data_len))
3168 			goto out;
3169 
3170 		info_node = malloc(sizeof(struct bpf_prog_info_node));
3171 		if (!info_node)
3172 			goto out;
3173 
3174 		/* after reading from file, translate offset to address */
3175 		bpil_offs_to_addr(info_linear);
3176 		info_node->info_linear = info_linear;
3177 		info_node->metadata = NULL;
3178 		if (!__perf_env__insert_bpf_prog_info(env, info_node)) {
3179 			free(info_linear);
3180 			free(info_node);
3181 		}
3182 	}
3183 
3184 	up_write(&env->bpf_progs.lock);
3185 	return 0;
3186 out:
3187 	free(info_linear);
3188 	free(info_node);
3189 	up_write(&env->bpf_progs.lock);
3190 	return err;
3191 }
3192 
process_bpf_btf(struct feat_fd * ff,void * data __maybe_unused)3193 static int process_bpf_btf(struct feat_fd *ff, void *data __maybe_unused)
3194 {
3195 	struct perf_env *env = &ff->ph->env;
3196 	struct btf_node *node = NULL;
3197 	u32 count, i;
3198 	int err = -1;
3199 
3200 	if (ff->ph->needs_swap) {
3201 		pr_warning("interpreting btf from systems with endianness is not yet supported\n");
3202 		return 0;
3203 	}
3204 
3205 	if (do_read_u32(ff, &count))
3206 		return -1;
3207 
3208 	down_write(&env->bpf_progs.lock);
3209 
3210 	for (i = 0; i < count; ++i) {
3211 		u32 id, data_size;
3212 
3213 		if (do_read_u32(ff, &id))
3214 			goto out;
3215 		if (do_read_u32(ff, &data_size))
3216 			goto out;
3217 
3218 		node = malloc(sizeof(struct btf_node) + data_size);
3219 		if (!node)
3220 			goto out;
3221 
3222 		node->id = id;
3223 		node->data_size = data_size;
3224 
3225 		if (__do_read(ff, node->data, data_size))
3226 			goto out;
3227 
3228 		if (!__perf_env__insert_btf(env, node))
3229 			free(node);
3230 		node = NULL;
3231 	}
3232 
3233 	err = 0;
3234 out:
3235 	up_write(&env->bpf_progs.lock);
3236 	free(node);
3237 	return err;
3238 }
3239 #endif // HAVE_LIBBPF_SUPPORT
3240 
process_compressed(struct feat_fd * ff,void * data __maybe_unused)3241 static int process_compressed(struct feat_fd *ff,
3242 			      void *data __maybe_unused)
3243 {
3244 	struct perf_env *env = &ff->ph->env;
3245 
3246 	if (do_read_u32(ff, &(env->comp_ver)))
3247 		return -1;
3248 
3249 	if (do_read_u32(ff, &(env->comp_type)))
3250 		return -1;
3251 
3252 	if (do_read_u32(ff, &(env->comp_level)))
3253 		return -1;
3254 
3255 	if (do_read_u32(ff, &(env->comp_ratio)))
3256 		return -1;
3257 
3258 	if (do_read_u32(ff, &(env->comp_mmap_len)))
3259 		return -1;
3260 
3261 	return 0;
3262 }
3263 
__process_pmu_caps(struct feat_fd * ff,int * nr_caps,char *** caps,unsigned int * max_branches,unsigned int * br_cntr_nr,unsigned int * br_cntr_width)3264 static int __process_pmu_caps(struct feat_fd *ff, int *nr_caps,
3265 			      char ***caps, unsigned int *max_branches,
3266 			      unsigned int *br_cntr_nr,
3267 			      unsigned int *br_cntr_width)
3268 {
3269 	char *name, *value, *ptr;
3270 	u32 nr_pmu_caps, i;
3271 
3272 	*nr_caps = 0;
3273 	*caps = NULL;
3274 
3275 	if (do_read_u32(ff, &nr_pmu_caps))
3276 		return -1;
3277 
3278 	if (!nr_pmu_caps)
3279 		return 0;
3280 
3281 	*caps = zalloc(sizeof(char *) * nr_pmu_caps);
3282 	if (!*caps)
3283 		return -1;
3284 
3285 	for (i = 0; i < nr_pmu_caps; i++) {
3286 		name = do_read_string(ff);
3287 		if (!name)
3288 			goto error;
3289 
3290 		value = do_read_string(ff);
3291 		if (!value)
3292 			goto free_name;
3293 
3294 		if (asprintf(&ptr, "%s=%s", name, value) < 0)
3295 			goto free_value;
3296 
3297 		(*caps)[i] = ptr;
3298 
3299 		if (!strcmp(name, "branches"))
3300 			*max_branches = atoi(value);
3301 
3302 		if (!strcmp(name, "branch_counter_nr"))
3303 			*br_cntr_nr = atoi(value);
3304 
3305 		if (!strcmp(name, "branch_counter_width"))
3306 			*br_cntr_width = atoi(value);
3307 
3308 		free(value);
3309 		free(name);
3310 	}
3311 	*nr_caps = nr_pmu_caps;
3312 	return 0;
3313 
3314 free_value:
3315 	free(value);
3316 free_name:
3317 	free(name);
3318 error:
3319 	for (; i > 0; i--)
3320 		free((*caps)[i - 1]);
3321 	free(*caps);
3322 	*caps = NULL;
3323 	*nr_caps = 0;
3324 	return -1;
3325 }
3326 
process_cpu_pmu_caps(struct feat_fd * ff,void * data __maybe_unused)3327 static int process_cpu_pmu_caps(struct feat_fd *ff,
3328 				void *data __maybe_unused)
3329 {
3330 	struct perf_env *env = &ff->ph->env;
3331 	int ret = __process_pmu_caps(ff, &env->nr_cpu_pmu_caps,
3332 				     &env->cpu_pmu_caps,
3333 				     &env->max_branches,
3334 				     &env->br_cntr_nr,
3335 				     &env->br_cntr_width);
3336 
3337 	if (!ret && !env->cpu_pmu_caps)
3338 		pr_debug("cpu pmu capabilities not available\n");
3339 	return ret;
3340 }
3341 
process_pmu_caps(struct feat_fd * ff,void * data __maybe_unused)3342 static int process_pmu_caps(struct feat_fd *ff, void *data __maybe_unused)
3343 {
3344 	struct perf_env *env = &ff->ph->env;
3345 	struct pmu_caps *pmu_caps;
3346 	u32 nr_pmu, i;
3347 	int ret;
3348 	int j;
3349 
3350 	if (do_read_u32(ff, &nr_pmu))
3351 		return -1;
3352 
3353 	if (!nr_pmu) {
3354 		pr_debug("pmu capabilities not available\n");
3355 		return 0;
3356 	}
3357 
3358 	pmu_caps = zalloc(sizeof(*pmu_caps) * nr_pmu);
3359 	if (!pmu_caps)
3360 		return -ENOMEM;
3361 
3362 	for (i = 0; i < nr_pmu; i++) {
3363 		ret = __process_pmu_caps(ff, &pmu_caps[i].nr_caps,
3364 					 &pmu_caps[i].caps,
3365 					 &pmu_caps[i].max_branches,
3366 					 &pmu_caps[i].br_cntr_nr,
3367 					 &pmu_caps[i].br_cntr_width);
3368 		if (ret)
3369 			goto err;
3370 
3371 		pmu_caps[i].pmu_name = do_read_string(ff);
3372 		if (!pmu_caps[i].pmu_name) {
3373 			ret = -1;
3374 			goto err;
3375 		}
3376 		if (!pmu_caps[i].nr_caps) {
3377 			pr_debug("%s pmu capabilities not available\n",
3378 				 pmu_caps[i].pmu_name);
3379 		}
3380 	}
3381 
3382 	env->nr_pmus_with_caps = nr_pmu;
3383 	env->pmu_caps = pmu_caps;
3384 	return 0;
3385 
3386 err:
3387 	for (i = 0; i < nr_pmu; i++) {
3388 		for (j = 0; j < pmu_caps[i].nr_caps; j++)
3389 			free(pmu_caps[i].caps[j]);
3390 		free(pmu_caps[i].caps);
3391 		free(pmu_caps[i].pmu_name);
3392 	}
3393 
3394 	free(pmu_caps);
3395 	return ret;
3396 }
3397 
3398 #define FEAT_OPR(n, func, __full_only) \
3399 	[HEADER_##n] = {					\
3400 		.name	    = __stringify(n),			\
3401 		.write	    = write_##func,			\
3402 		.print	    = print_##func,			\
3403 		.full_only  = __full_only,			\
3404 		.process    = process_##func,			\
3405 		.synthesize = true				\
3406 	}
3407 
3408 #define FEAT_OPN(n, func, __full_only) \
3409 	[HEADER_##n] = {					\
3410 		.name	    = __stringify(n),			\
3411 		.write	    = write_##func,			\
3412 		.print	    = print_##func,			\
3413 		.full_only  = __full_only,			\
3414 		.process    = process_##func			\
3415 	}
3416 
3417 /* feature_ops not implemented: */
3418 #define print_tracing_data	NULL
3419 #define print_build_id		NULL
3420 
3421 #define process_branch_stack	NULL
3422 #define process_stat		NULL
3423 
3424 // Only used in util/synthetic-events.c
3425 const struct perf_header_feature_ops feat_ops[HEADER_LAST_FEATURE];
3426 
3427 const struct perf_header_feature_ops feat_ops[HEADER_LAST_FEATURE] = {
3428 #ifdef HAVE_LIBTRACEEVENT
3429 	FEAT_OPN(TRACING_DATA,	tracing_data,	false),
3430 #endif
3431 	FEAT_OPN(BUILD_ID,	build_id,	false),
3432 	FEAT_OPR(HOSTNAME,	hostname,	false),
3433 	FEAT_OPR(OSRELEASE,	osrelease,	false),
3434 	FEAT_OPR(VERSION,	version,	false),
3435 	FEAT_OPR(ARCH,		arch,		false),
3436 	FEAT_OPR(NRCPUS,	nrcpus,		false),
3437 	FEAT_OPR(CPUDESC,	cpudesc,	false),
3438 	FEAT_OPR(CPUID,		cpuid,		false),
3439 	FEAT_OPR(TOTAL_MEM,	total_mem,	false),
3440 	FEAT_OPR(EVENT_DESC,	event_desc,	false),
3441 	FEAT_OPR(CMDLINE,	cmdline,	false),
3442 	FEAT_OPR(CPU_TOPOLOGY,	cpu_topology,	true),
3443 	FEAT_OPR(NUMA_TOPOLOGY,	numa_topology,	true),
3444 	FEAT_OPN(BRANCH_STACK,	branch_stack,	false),
3445 	FEAT_OPR(PMU_MAPPINGS,	pmu_mappings,	false),
3446 	FEAT_OPR(GROUP_DESC,	group_desc,	false),
3447 	FEAT_OPN(AUXTRACE,	auxtrace,	false),
3448 	FEAT_OPN(STAT,		stat,		false),
3449 	FEAT_OPN(CACHE,		cache,		true),
3450 	FEAT_OPR(SAMPLE_TIME,	sample_time,	false),
3451 	FEAT_OPR(MEM_TOPOLOGY,	mem_topology,	true),
3452 	FEAT_OPR(CLOCKID,	clockid,	false),
3453 	FEAT_OPN(DIR_FORMAT,	dir_format,	false),
3454 #ifdef HAVE_LIBBPF_SUPPORT
3455 	FEAT_OPR(BPF_PROG_INFO, bpf_prog_info,  false),
3456 	FEAT_OPR(BPF_BTF,       bpf_btf,        false),
3457 #endif
3458 	FEAT_OPR(COMPRESSED,	compressed,	false),
3459 	FEAT_OPR(CPU_PMU_CAPS,	cpu_pmu_caps,	false),
3460 	FEAT_OPR(CLOCK_DATA,	clock_data,	false),
3461 	FEAT_OPN(HYBRID_TOPOLOGY,	hybrid_topology,	true),
3462 	FEAT_OPR(PMU_CAPS,	pmu_caps,	false),
3463 };
3464 
3465 struct header_print_data {
3466 	FILE *fp;
3467 	bool full; /* extended list of headers */
3468 };
3469 
perf_file_section__fprintf_info(struct perf_file_section * section,struct perf_header * ph,int feat,int fd,void * data)3470 static int perf_file_section__fprintf_info(struct perf_file_section *section,
3471 					   struct perf_header *ph,
3472 					   int feat, int fd, void *data)
3473 {
3474 	struct header_print_data *hd = data;
3475 	struct feat_fd ff;
3476 
3477 	if (lseek(fd, section->offset, SEEK_SET) == (off_t)-1) {
3478 		pr_debug("Failed to lseek to %" PRIu64 " offset for feature "
3479 				"%d, continuing...\n", section->offset, feat);
3480 		return 0;
3481 	}
3482 	if (feat >= HEADER_LAST_FEATURE) {
3483 		pr_warning("unknown feature %d\n", feat);
3484 		return 0;
3485 	}
3486 	if (!feat_ops[feat].print)
3487 		return 0;
3488 
3489 	ff = (struct  feat_fd) {
3490 		.fd = fd,
3491 		.ph = ph,
3492 	};
3493 
3494 	if (!feat_ops[feat].full_only || hd->full)
3495 		feat_ops[feat].print(&ff, hd->fp);
3496 	else
3497 		fprintf(hd->fp, "# %s info available, use -I to display\n",
3498 			feat_ops[feat].name);
3499 
3500 	return 0;
3501 }
3502 
perf_header__fprintf_info(struct perf_session * session,FILE * fp,bool full)3503 int perf_header__fprintf_info(struct perf_session *session, FILE *fp, bool full)
3504 {
3505 	struct header_print_data hd;
3506 	struct perf_header *header = &session->header;
3507 	int fd = perf_data__fd(session->data);
3508 	struct stat st;
3509 	time_t stctime;
3510 	int ret, bit;
3511 
3512 	hd.fp = fp;
3513 	hd.full = full;
3514 
3515 	ret = fstat(fd, &st);
3516 	if (ret == -1)
3517 		return -1;
3518 
3519 	stctime = st.st_mtime;
3520 	fprintf(fp, "# captured on    : %s", ctime(&stctime));
3521 
3522 	fprintf(fp, "# header version : %u\n", header->version);
3523 	fprintf(fp, "# data offset    : %" PRIu64 "\n", header->data_offset);
3524 	fprintf(fp, "# data size      : %" PRIu64 "\n", header->data_size);
3525 	fprintf(fp, "# feat offset    : %" PRIu64 "\n", header->feat_offset);
3526 
3527 	perf_header__process_sections(header, fd, &hd,
3528 				      perf_file_section__fprintf_info);
3529 
3530 	if (session->data->is_pipe)
3531 		return 0;
3532 
3533 	fprintf(fp, "# missing features: ");
3534 	for_each_clear_bit(bit, header->adds_features, HEADER_LAST_FEATURE) {
3535 		if (bit)
3536 			fprintf(fp, "%s ", feat_ops[bit].name);
3537 	}
3538 
3539 	fprintf(fp, "\n");
3540 	return 0;
3541 }
3542 
3543 struct header_fw {
3544 	struct feat_writer	fw;
3545 	struct feat_fd		*ff;
3546 };
3547 
feat_writer_cb(struct feat_writer * fw,void * buf,size_t sz)3548 static int feat_writer_cb(struct feat_writer *fw, void *buf, size_t sz)
3549 {
3550 	struct header_fw *h = container_of(fw, struct header_fw, fw);
3551 
3552 	return do_write(h->ff, buf, sz);
3553 }
3554 
do_write_feat(struct feat_fd * ff,int type,struct perf_file_section ** p,struct evlist * evlist,struct feat_copier * fc)3555 static int do_write_feat(struct feat_fd *ff, int type,
3556 			 struct perf_file_section **p,
3557 			 struct evlist *evlist,
3558 			 struct feat_copier *fc)
3559 {
3560 	int err;
3561 	int ret = 0;
3562 
3563 	if (perf_header__has_feat(ff->ph, type)) {
3564 		if (!feat_ops[type].write)
3565 			return -1;
3566 
3567 		if (WARN(ff->buf, "Error: calling %s in pipe-mode.\n", __func__))
3568 			return -1;
3569 
3570 		(*p)->offset = lseek(ff->fd, 0, SEEK_CUR);
3571 
3572 		/*
3573 		 * Hook to let perf inject copy features sections from the input
3574 		 * file.
3575 		 */
3576 		if (fc && fc->copy) {
3577 			struct header_fw h = {
3578 				.fw.write = feat_writer_cb,
3579 				.ff = ff,
3580 			};
3581 
3582 			/* ->copy() returns 0 if the feature was not copied */
3583 			err = fc->copy(fc, type, &h.fw);
3584 		} else {
3585 			err = 0;
3586 		}
3587 		if (!err)
3588 			err = feat_ops[type].write(ff, evlist);
3589 		if (err < 0) {
3590 			pr_debug("failed to write feature %s\n", feat_ops[type].name);
3591 
3592 			/* undo anything written */
3593 			lseek(ff->fd, (*p)->offset, SEEK_SET);
3594 
3595 			return -1;
3596 		}
3597 		(*p)->size = lseek(ff->fd, 0, SEEK_CUR) - (*p)->offset;
3598 		(*p)++;
3599 	}
3600 	return ret;
3601 }
3602 
perf_header__adds_write(struct perf_header * header,struct evlist * evlist,int fd,struct feat_copier * fc)3603 static int perf_header__adds_write(struct perf_header *header,
3604 				   struct evlist *evlist, int fd,
3605 				   struct feat_copier *fc)
3606 {
3607 	int nr_sections;
3608 	struct feat_fd ff = {
3609 		.fd  = fd,
3610 		.ph = header,
3611 	};
3612 	struct perf_file_section *feat_sec, *p;
3613 	int sec_size;
3614 	u64 sec_start;
3615 	int feat;
3616 	int err;
3617 
3618 	nr_sections = bitmap_weight(header->adds_features, HEADER_FEAT_BITS);
3619 	if (!nr_sections)
3620 		return 0;
3621 
3622 	feat_sec = p = calloc(nr_sections, sizeof(*feat_sec));
3623 	if (feat_sec == NULL)
3624 		return -ENOMEM;
3625 
3626 	sec_size = sizeof(*feat_sec) * nr_sections;
3627 
3628 	sec_start = header->feat_offset;
3629 	lseek(fd, sec_start + sec_size, SEEK_SET);
3630 
3631 	for_each_set_bit(feat, header->adds_features, HEADER_FEAT_BITS) {
3632 		if (do_write_feat(&ff, feat, &p, evlist, fc))
3633 			perf_header__clear_feat(header, feat);
3634 	}
3635 
3636 	lseek(fd, sec_start, SEEK_SET);
3637 	/*
3638 	 * may write more than needed due to dropped feature, but
3639 	 * this is okay, reader will skip the missing entries
3640 	 */
3641 	err = do_write(&ff, feat_sec, sec_size);
3642 	if (err < 0)
3643 		pr_debug("failed to write feature section\n");
3644 	free(ff.buf); /* TODO: added to silence clang-tidy. */
3645 	free(feat_sec);
3646 	return err;
3647 }
3648 
perf_header__write_pipe(int fd)3649 int perf_header__write_pipe(int fd)
3650 {
3651 	struct perf_pipe_file_header f_header;
3652 	struct feat_fd ff = {
3653 		.fd = fd,
3654 	};
3655 	int err;
3656 
3657 	f_header = (struct perf_pipe_file_header){
3658 		.magic	   = PERF_MAGIC,
3659 		.size	   = sizeof(f_header),
3660 	};
3661 
3662 	err = do_write(&ff, &f_header, sizeof(f_header));
3663 	if (err < 0) {
3664 		pr_debug("failed to write perf pipe header\n");
3665 		return err;
3666 	}
3667 	free(ff.buf);
3668 	return 0;
3669 }
3670 
perf_session__do_write_header(struct perf_session * session,struct evlist * evlist,int fd,bool at_exit,struct feat_copier * fc,bool write_attrs_after_data)3671 static int perf_session__do_write_header(struct perf_session *session,
3672 					 struct evlist *evlist,
3673 					 int fd, bool at_exit,
3674 					 struct feat_copier *fc,
3675 					 bool write_attrs_after_data)
3676 {
3677 	struct perf_file_header f_header;
3678 	struct perf_header *header = &session->header;
3679 	struct evsel *evsel;
3680 	struct feat_fd ff = {
3681 		.ph = header,
3682 		.fd = fd,
3683 	};
3684 	u64 attr_offset = sizeof(f_header), attr_size = 0;
3685 	int err;
3686 
3687 	if (write_attrs_after_data && at_exit) {
3688 		/*
3689 		 * Write features at the end of the file first so that
3690 		 * attributes may come after them.
3691 		 */
3692 		if (!header->data_offset && header->data_size) {
3693 			pr_err("File contains data but offset unknown\n");
3694 			err = -1;
3695 			goto err_out;
3696 		}
3697 		header->feat_offset = header->data_offset + header->data_size;
3698 		err = perf_header__adds_write(header, evlist, fd, fc);
3699 		if (err < 0)
3700 			goto err_out;
3701 		attr_offset = lseek(fd, 0, SEEK_CUR);
3702 	} else {
3703 		lseek(fd, attr_offset, SEEK_SET);
3704 	}
3705 
3706 	evlist__for_each_entry(session->evlist, evsel) {
3707 		evsel->id_offset = attr_offset;
3708 		/* Avoid writing at the end of the file until the session is exiting. */
3709 		if (!write_attrs_after_data || at_exit) {
3710 			err = do_write(&ff, evsel->core.id, evsel->core.ids * sizeof(u64));
3711 			if (err < 0) {
3712 				pr_debug("failed to write perf header\n");
3713 				goto err_out;
3714 			}
3715 		}
3716 		attr_offset += evsel->core.ids * sizeof(u64);
3717 	}
3718 
3719 	evlist__for_each_entry(evlist, evsel) {
3720 		if (evsel->core.attr.size < sizeof(evsel->core.attr)) {
3721 			/*
3722 			 * We are likely in "perf inject" and have read
3723 			 * from an older file. Update attr size so that
3724 			 * reader gets the right offset to the ids.
3725 			 */
3726 			evsel->core.attr.size = sizeof(evsel->core.attr);
3727 		}
3728 		/* Avoid writing at the end of the file until the session is exiting. */
3729 		if (!write_attrs_after_data || at_exit) {
3730 			struct perf_file_attr f_attr = {
3731 				.attr = evsel->core.attr,
3732 				.ids  = {
3733 					.offset = evsel->id_offset,
3734 					.size   = evsel->core.ids * sizeof(u64),
3735 				}
3736 			};
3737 			err = do_write(&ff, &f_attr, sizeof(f_attr));
3738 			if (err < 0) {
3739 				pr_debug("failed to write perf header attribute\n");
3740 				goto err_out;
3741 			}
3742 		}
3743 		attr_size += sizeof(struct perf_file_attr);
3744 	}
3745 
3746 	if (!header->data_offset) {
3747 		if (write_attrs_after_data)
3748 			header->data_offset = sizeof(f_header);
3749 		else
3750 			header->data_offset = attr_offset + attr_size;
3751 	}
3752 	header->feat_offset = header->data_offset + header->data_size;
3753 
3754 	if (!write_attrs_after_data && at_exit) {
3755 		/* Write features now feat_offset is known. */
3756 		err = perf_header__adds_write(header, evlist, fd, fc);
3757 		if (err < 0)
3758 			goto err_out;
3759 	}
3760 
3761 	f_header = (struct perf_file_header){
3762 		.magic	   = PERF_MAGIC,
3763 		.size	   = sizeof(f_header),
3764 		.attr_size = sizeof(struct perf_file_attr),
3765 		.attrs = {
3766 			.offset = attr_offset,
3767 			.size   = attr_size,
3768 		},
3769 		.data = {
3770 			.offset = header->data_offset,
3771 			.size	= header->data_size,
3772 		},
3773 		/* event_types is ignored, store zeros */
3774 	};
3775 
3776 	memcpy(&f_header.adds_features, &header->adds_features, sizeof(header->adds_features));
3777 
3778 	lseek(fd, 0, SEEK_SET);
3779 	err = do_write(&ff, &f_header, sizeof(f_header));
3780 	if (err < 0) {
3781 		pr_debug("failed to write perf header\n");
3782 		goto err_out;
3783 	} else {
3784 		lseek(fd, 0, SEEK_END);
3785 		err = 0;
3786 	}
3787 err_out:
3788 	free(ff.buf);
3789 	return err;
3790 }
3791 
perf_session__write_header(struct perf_session * session,struct evlist * evlist,int fd,bool at_exit)3792 int perf_session__write_header(struct perf_session *session,
3793 			       struct evlist *evlist,
3794 			       int fd, bool at_exit)
3795 {
3796 	return perf_session__do_write_header(session, evlist, fd, at_exit, /*fc=*/NULL,
3797 					     /*write_attrs_after_data=*/false);
3798 }
3799 
perf_session__data_offset(const struct evlist * evlist)3800 size_t perf_session__data_offset(const struct evlist *evlist)
3801 {
3802 	struct evsel *evsel;
3803 	size_t data_offset;
3804 
3805 	data_offset = sizeof(struct perf_file_header);
3806 	evlist__for_each_entry(evlist, evsel) {
3807 		data_offset += evsel->core.ids * sizeof(u64);
3808 	}
3809 	data_offset += evlist->core.nr_entries * sizeof(struct perf_file_attr);
3810 
3811 	return data_offset;
3812 }
3813 
perf_session__inject_header(struct perf_session * session,struct evlist * evlist,int fd,struct feat_copier * fc,bool write_attrs_after_data)3814 int perf_session__inject_header(struct perf_session *session,
3815 				struct evlist *evlist,
3816 				int fd,
3817 				struct feat_copier *fc,
3818 				bool write_attrs_after_data)
3819 {
3820 	return perf_session__do_write_header(session, evlist, fd, true, fc,
3821 					     write_attrs_after_data);
3822 }
3823 
perf_header__getbuffer64(struct perf_header * header,int fd,void * buf,size_t size)3824 static int perf_header__getbuffer64(struct perf_header *header,
3825 				    int fd, void *buf, size_t size)
3826 {
3827 	if (readn(fd, buf, size) <= 0)
3828 		return -1;
3829 
3830 	if (header->needs_swap)
3831 		mem_bswap_64(buf, size);
3832 
3833 	return 0;
3834 }
3835 
perf_header__process_sections(struct perf_header * header,int fd,void * data,int (* process)(struct perf_file_section * section,struct perf_header * ph,int feat,int fd,void * data))3836 int perf_header__process_sections(struct perf_header *header, int fd,
3837 				  void *data,
3838 				  int (*process)(struct perf_file_section *section,
3839 						 struct perf_header *ph,
3840 						 int feat, int fd, void *data))
3841 {
3842 	struct perf_file_section *feat_sec, *sec;
3843 	int nr_sections;
3844 	int sec_size;
3845 	int feat;
3846 	int err;
3847 
3848 	nr_sections = bitmap_weight(header->adds_features, HEADER_FEAT_BITS);
3849 	if (!nr_sections)
3850 		return 0;
3851 
3852 	feat_sec = sec = calloc(nr_sections, sizeof(*feat_sec));
3853 	if (!feat_sec)
3854 		return -1;
3855 
3856 	sec_size = sizeof(*feat_sec) * nr_sections;
3857 
3858 	lseek(fd, header->feat_offset, SEEK_SET);
3859 
3860 	err = perf_header__getbuffer64(header, fd, feat_sec, sec_size);
3861 	if (err < 0)
3862 		goto out_free;
3863 
3864 	for_each_set_bit(feat, header->adds_features, HEADER_LAST_FEATURE) {
3865 		err = process(sec++, header, feat, fd, data);
3866 		if (err < 0)
3867 			goto out_free;
3868 	}
3869 	err = 0;
3870 out_free:
3871 	free(feat_sec);
3872 	return err;
3873 }
3874 
3875 static const int attr_file_abi_sizes[] = {
3876 	[0] = PERF_ATTR_SIZE_VER0,
3877 	[1] = PERF_ATTR_SIZE_VER1,
3878 	[2] = PERF_ATTR_SIZE_VER2,
3879 	[3] = PERF_ATTR_SIZE_VER3,
3880 	[4] = PERF_ATTR_SIZE_VER4,
3881 	0,
3882 };
3883 
3884 /*
3885  * In the legacy file format, the magic number is not used to encode endianness.
3886  * hdr_sz was used to encode endianness. But given that hdr_sz can vary based
3887  * on ABI revisions, we need to try all combinations for all endianness to
3888  * detect the endianness.
3889  */
try_all_file_abis(uint64_t hdr_sz,struct perf_header * ph)3890 static int try_all_file_abis(uint64_t hdr_sz, struct perf_header *ph)
3891 {
3892 	uint64_t ref_size, attr_size;
3893 	int i;
3894 
3895 	for (i = 0 ; attr_file_abi_sizes[i]; i++) {
3896 		ref_size = attr_file_abi_sizes[i]
3897 			 + sizeof(struct perf_file_section);
3898 		if (hdr_sz != ref_size) {
3899 			attr_size = bswap_64(hdr_sz);
3900 			if (attr_size != ref_size)
3901 				continue;
3902 
3903 			ph->needs_swap = true;
3904 		}
3905 		pr_debug("ABI%d perf.data file detected, need_swap=%d\n",
3906 			 i,
3907 			 ph->needs_swap);
3908 		return 0;
3909 	}
3910 	/* could not determine endianness */
3911 	return -1;
3912 }
3913 
3914 #define PERF_PIPE_HDR_VER0	16
3915 
3916 static const size_t attr_pipe_abi_sizes[] = {
3917 	[0] = PERF_PIPE_HDR_VER0,
3918 	0,
3919 };
3920 
3921 /*
3922  * In the legacy pipe format, there is an implicit assumption that endianness
3923  * between host recording the samples, and host parsing the samples is the
3924  * same. This is not always the case given that the pipe output may always be
3925  * redirected into a file and analyzed on a different machine with possibly a
3926  * different endianness and perf_event ABI revisions in the perf tool itself.
3927  */
try_all_pipe_abis(uint64_t hdr_sz,struct perf_header * ph)3928 static int try_all_pipe_abis(uint64_t hdr_sz, struct perf_header *ph)
3929 {
3930 	u64 attr_size;
3931 	int i;
3932 
3933 	for (i = 0 ; attr_pipe_abi_sizes[i]; i++) {
3934 		if (hdr_sz != attr_pipe_abi_sizes[i]) {
3935 			attr_size = bswap_64(hdr_sz);
3936 			if (attr_size != hdr_sz)
3937 				continue;
3938 
3939 			ph->needs_swap = true;
3940 		}
3941 		pr_debug("Pipe ABI%d perf.data file detected\n", i);
3942 		return 0;
3943 	}
3944 	return -1;
3945 }
3946 
is_perf_magic(u64 magic)3947 bool is_perf_magic(u64 magic)
3948 {
3949 	if (!memcmp(&magic, __perf_magic1, sizeof(magic))
3950 		|| magic == __perf_magic2
3951 		|| magic == __perf_magic2_sw)
3952 		return true;
3953 
3954 	return false;
3955 }
3956 
check_magic_endian(u64 magic,uint64_t hdr_sz,bool is_pipe,struct perf_header * ph)3957 static int check_magic_endian(u64 magic, uint64_t hdr_sz,
3958 			      bool is_pipe, struct perf_header *ph)
3959 {
3960 	int ret;
3961 
3962 	/* check for legacy format */
3963 	ret = memcmp(&magic, __perf_magic1, sizeof(magic));
3964 	if (ret == 0) {
3965 		ph->version = PERF_HEADER_VERSION_1;
3966 		pr_debug("legacy perf.data format\n");
3967 		if (is_pipe)
3968 			return try_all_pipe_abis(hdr_sz, ph);
3969 
3970 		return try_all_file_abis(hdr_sz, ph);
3971 	}
3972 	/*
3973 	 * the new magic number serves two purposes:
3974 	 * - unique number to identify actual perf.data files
3975 	 * - encode endianness of file
3976 	 */
3977 	ph->version = PERF_HEADER_VERSION_2;
3978 
3979 	/* check magic number with one endianness */
3980 	if (magic == __perf_magic2)
3981 		return 0;
3982 
3983 	/* check magic number with opposite endianness */
3984 	if (magic != __perf_magic2_sw)
3985 		return -1;
3986 
3987 	ph->needs_swap = true;
3988 
3989 	return 0;
3990 }
3991 
perf_file_header__read(struct perf_file_header * header,struct perf_header * ph,int fd)3992 int perf_file_header__read(struct perf_file_header *header,
3993 			   struct perf_header *ph, int fd)
3994 {
3995 	ssize_t ret;
3996 
3997 	lseek(fd, 0, SEEK_SET);
3998 
3999 	ret = readn(fd, header, sizeof(*header));
4000 	if (ret <= 0)
4001 		return -1;
4002 
4003 	if (check_magic_endian(header->magic,
4004 			       header->attr_size, false, ph) < 0) {
4005 		pr_debug("magic/endian check failed\n");
4006 		return -1;
4007 	}
4008 
4009 	if (ph->needs_swap) {
4010 		mem_bswap_64(header, offsetof(struct perf_file_header,
4011 			     adds_features));
4012 	}
4013 
4014 	if (header->size > header->attrs.offset) {
4015 		pr_err("Perf file header corrupt: header overlaps attrs\n");
4016 		return -1;
4017 	}
4018 
4019 	if (header->size > header->data.offset) {
4020 		pr_err("Perf file header corrupt: header overlaps data\n");
4021 		return -1;
4022 	}
4023 
4024 	if ((header->attrs.offset <= header->data.offset &&
4025 	     header->attrs.offset + header->attrs.size > header->data.offset) ||
4026 	    (header->attrs.offset > header->data.offset &&
4027 	     header->data.offset + header->data.size > header->attrs.offset)) {
4028 		pr_err("Perf file header corrupt: Attributes and data overlap\n");
4029 		return -1;
4030 	}
4031 
4032 	if (header->size != sizeof(*header)) {
4033 		/* Support the previous format */
4034 		if (header->size == offsetof(typeof(*header), adds_features))
4035 			bitmap_zero(header->adds_features, HEADER_FEAT_BITS);
4036 		else
4037 			return -1;
4038 	} else if (ph->needs_swap) {
4039 		/*
4040 		 * feature bitmap is declared as an array of unsigned longs --
4041 		 * not good since its size can differ between the host that
4042 		 * generated the data file and the host analyzing the file.
4043 		 *
4044 		 * We need to handle endianness, but we don't know the size of
4045 		 * the unsigned long where the file was generated. Take a best
4046 		 * guess at determining it: try 64-bit swap first (ie., file
4047 		 * created on a 64-bit host), and check if the hostname feature
4048 		 * bit is set (this feature bit is forced on as of fbe96f2).
4049 		 * If the bit is not, undo the 64-bit swap and try a 32-bit
4050 		 * swap. If the hostname bit is still not set (e.g., older data
4051 		 * file), punt and fallback to the original behavior --
4052 		 * clearing all feature bits and setting buildid.
4053 		 */
4054 		mem_bswap_64(&header->adds_features,
4055 			    BITS_TO_U64(HEADER_FEAT_BITS));
4056 
4057 		if (!test_bit(HEADER_HOSTNAME, header->adds_features)) {
4058 			/* unswap as u64 */
4059 			mem_bswap_64(&header->adds_features,
4060 				    BITS_TO_U64(HEADER_FEAT_BITS));
4061 
4062 			/* unswap as u32 */
4063 			mem_bswap_32(&header->adds_features,
4064 				    BITS_TO_U32(HEADER_FEAT_BITS));
4065 		}
4066 
4067 		if (!test_bit(HEADER_HOSTNAME, header->adds_features)) {
4068 			bitmap_zero(header->adds_features, HEADER_FEAT_BITS);
4069 			__set_bit(HEADER_BUILD_ID, header->adds_features);
4070 		}
4071 	}
4072 
4073 	memcpy(&ph->adds_features, &header->adds_features,
4074 	       sizeof(ph->adds_features));
4075 
4076 	ph->data_offset  = header->data.offset;
4077 	ph->data_size	 = header->data.size;
4078 	ph->feat_offset  = header->data.offset + header->data.size;
4079 	return 0;
4080 }
4081 
perf_file_section__process(struct perf_file_section * section,struct perf_header * ph,int feat,int fd,void * data)4082 static int perf_file_section__process(struct perf_file_section *section,
4083 				      struct perf_header *ph,
4084 				      int feat, int fd, void *data)
4085 {
4086 	struct feat_fd fdd = {
4087 		.fd	= fd,
4088 		.ph	= ph,
4089 		.size	= section->size,
4090 		.offset	= section->offset,
4091 	};
4092 
4093 	if (lseek(fd, section->offset, SEEK_SET) == (off_t)-1) {
4094 		pr_debug("Failed to lseek to %" PRIu64 " offset for feature "
4095 			  "%d, continuing...\n", section->offset, feat);
4096 		return 0;
4097 	}
4098 
4099 	if (feat >= HEADER_LAST_FEATURE) {
4100 		pr_debug("unknown feature %d, continuing...\n", feat);
4101 		return 0;
4102 	}
4103 
4104 	if (!feat_ops[feat].process)
4105 		return 0;
4106 
4107 	return feat_ops[feat].process(&fdd, data);
4108 }
4109 
perf_file_header__read_pipe(struct perf_pipe_file_header * header,struct perf_header * ph,struct perf_data * data)4110 static int perf_file_header__read_pipe(struct perf_pipe_file_header *header,
4111 				       struct perf_header *ph,
4112 				       struct perf_data *data)
4113 {
4114 	ssize_t ret;
4115 
4116 	ret = perf_data__read(data, header, sizeof(*header));
4117 	if (ret <= 0)
4118 		return -1;
4119 
4120 	if (check_magic_endian(header->magic, header->size, true, ph) < 0) {
4121 		pr_debug("endian/magic failed\n");
4122 		return -1;
4123 	}
4124 
4125 	if (ph->needs_swap)
4126 		header->size = bswap_64(header->size);
4127 
4128 	return 0;
4129 }
4130 
perf_header__read_pipe(struct perf_session * session)4131 static int perf_header__read_pipe(struct perf_session *session)
4132 {
4133 	struct perf_header *header = &session->header;
4134 	struct perf_pipe_file_header f_header;
4135 
4136 	if (perf_file_header__read_pipe(&f_header, header, session->data) < 0) {
4137 		pr_debug("incompatible file format\n");
4138 		return -EINVAL;
4139 	}
4140 
4141 	return f_header.size == sizeof(f_header) ? 0 : -1;
4142 }
4143 
read_attr(int fd,struct perf_header * ph,struct perf_file_attr * f_attr)4144 static int read_attr(int fd, struct perf_header *ph,
4145 		     struct perf_file_attr *f_attr)
4146 {
4147 	struct perf_event_attr *attr = &f_attr->attr;
4148 	size_t sz, left;
4149 	size_t our_sz = sizeof(f_attr->attr);
4150 	ssize_t ret;
4151 
4152 	memset(f_attr, 0, sizeof(*f_attr));
4153 
4154 	/* read minimal guaranteed structure */
4155 	ret = readn(fd, attr, PERF_ATTR_SIZE_VER0);
4156 	if (ret <= 0) {
4157 		pr_debug("cannot read %d bytes of header attr\n",
4158 			 PERF_ATTR_SIZE_VER0);
4159 		return -1;
4160 	}
4161 
4162 	/* on file perf_event_attr size */
4163 	sz = attr->size;
4164 
4165 	if (ph->needs_swap)
4166 		sz = bswap_32(sz);
4167 
4168 	if (sz == 0) {
4169 		/* assume ABI0 */
4170 		sz =  PERF_ATTR_SIZE_VER0;
4171 	} else if (sz > our_sz) {
4172 		pr_debug("file uses a more recent and unsupported ABI"
4173 			 " (%zu bytes extra)\n", sz - our_sz);
4174 		return -1;
4175 	}
4176 	/* what we have not yet read and that we know about */
4177 	left = sz - PERF_ATTR_SIZE_VER0;
4178 	if (left) {
4179 		void *ptr = attr;
4180 		ptr += PERF_ATTR_SIZE_VER0;
4181 
4182 		ret = readn(fd, ptr, left);
4183 	}
4184 	/* read perf_file_section, ids are read in caller */
4185 	ret = readn(fd, &f_attr->ids, sizeof(f_attr->ids));
4186 
4187 	return ret <= 0 ? -1 : 0;
4188 }
4189 
4190 #ifdef HAVE_LIBTRACEEVENT
evsel__prepare_tracepoint_event(struct evsel * evsel,struct tep_handle * pevent)4191 static int evsel__prepare_tracepoint_event(struct evsel *evsel, struct tep_handle *pevent)
4192 {
4193 	struct tep_event *event;
4194 	char bf[128];
4195 
4196 	/* already prepared */
4197 	if (evsel->tp_format)
4198 		return 0;
4199 
4200 	if (pevent == NULL) {
4201 		pr_debug("broken or missing trace data\n");
4202 		return -1;
4203 	}
4204 
4205 	event = tep_find_event(pevent, evsel->core.attr.config);
4206 	if (event == NULL) {
4207 		pr_debug("cannot find event format for %d\n", (int)evsel->core.attr.config);
4208 		return -1;
4209 	}
4210 
4211 	if (!evsel->name) {
4212 		snprintf(bf, sizeof(bf), "%s:%s", event->system, event->name);
4213 		evsel->name = strdup(bf);
4214 		if (evsel->name == NULL)
4215 			return -1;
4216 	}
4217 
4218 	evsel->tp_format = event;
4219 	return 0;
4220 }
4221 
evlist__prepare_tracepoint_events(struct evlist * evlist,struct tep_handle * pevent)4222 static int evlist__prepare_tracepoint_events(struct evlist *evlist, struct tep_handle *pevent)
4223 {
4224 	struct evsel *pos;
4225 
4226 	evlist__for_each_entry(evlist, pos) {
4227 		if (pos->core.attr.type == PERF_TYPE_TRACEPOINT &&
4228 		    evsel__prepare_tracepoint_event(pos, pevent))
4229 			return -1;
4230 	}
4231 
4232 	return 0;
4233 }
4234 #endif
4235 
perf_session__read_header(struct perf_session * session)4236 int perf_session__read_header(struct perf_session *session)
4237 {
4238 	struct perf_data *data = session->data;
4239 	struct perf_header *header = &session->header;
4240 	struct perf_file_header	f_header;
4241 	struct perf_file_attr	f_attr;
4242 	u64			f_id;
4243 	int nr_attrs, nr_ids, i, j, err;
4244 	int fd = perf_data__fd(data);
4245 
4246 	session->evlist = evlist__new();
4247 	if (session->evlist == NULL)
4248 		return -ENOMEM;
4249 
4250 	session->evlist->session = session;
4251 	session->machines.host.env = &header->env;
4252 
4253 	/*
4254 	 * We can read 'pipe' data event from regular file,
4255 	 * check for the pipe header regardless of source.
4256 	 */
4257 	err = perf_header__read_pipe(session);
4258 	if (!err || perf_data__is_pipe(data)) {
4259 		data->is_pipe = true;
4260 		return err;
4261 	}
4262 
4263 	if (perf_file_header__read(&f_header, header, fd) < 0)
4264 		return -EINVAL;
4265 
4266 	if (header->needs_swap && data->in_place_update) {
4267 		pr_err("In-place update not supported when byte-swapping is required\n");
4268 		return -EINVAL;
4269 	}
4270 
4271 	/*
4272 	 * Sanity check that perf.data was written cleanly; data size is
4273 	 * initialized to 0 and updated only if the on_exit function is run.
4274 	 * If data size is still 0 then the file contains only partial
4275 	 * information.  Just warn user and process it as much as it can.
4276 	 */
4277 	if (f_header.data.size == 0) {
4278 		pr_warning("WARNING: The %s file's data size field is 0 which is unexpected.\n"
4279 			   "Was the 'perf record' command properly terminated?\n",
4280 			   data->file.path);
4281 	}
4282 
4283 	if (f_header.attr_size == 0) {
4284 		pr_err("ERROR: The %s file's attr size field is 0 which is unexpected.\n"
4285 		       "Was the 'perf record' command properly terminated?\n",
4286 		       data->file.path);
4287 		return -EINVAL;
4288 	}
4289 
4290 	nr_attrs = f_header.attrs.size / f_header.attr_size;
4291 	lseek(fd, f_header.attrs.offset, SEEK_SET);
4292 
4293 	for (i = 0; i < nr_attrs; i++) {
4294 		struct evsel *evsel;
4295 		off_t tmp;
4296 
4297 		if (read_attr(fd, header, &f_attr) < 0)
4298 			goto out_errno;
4299 
4300 		if (header->needs_swap) {
4301 			f_attr.ids.size   = bswap_64(f_attr.ids.size);
4302 			f_attr.ids.offset = bswap_64(f_attr.ids.offset);
4303 			perf_event__attr_swap(&f_attr.attr);
4304 		}
4305 
4306 		tmp = lseek(fd, 0, SEEK_CUR);
4307 		evsel = evsel__new(&f_attr.attr);
4308 
4309 		if (evsel == NULL)
4310 			goto out_delete_evlist;
4311 
4312 		evsel->needs_swap = header->needs_swap;
4313 		/*
4314 		 * Do it before so that if perf_evsel__alloc_id fails, this
4315 		 * entry gets purged too at evlist__delete().
4316 		 */
4317 		evlist__add(session->evlist, evsel);
4318 
4319 		nr_ids = f_attr.ids.size / sizeof(u64);
4320 		/*
4321 		 * We don't have the cpu and thread maps on the header, so
4322 		 * for allocating the perf_sample_id table we fake 1 cpu and
4323 		 * hattr->ids threads.
4324 		 */
4325 		if (perf_evsel__alloc_id(&evsel->core, 1, nr_ids))
4326 			goto out_delete_evlist;
4327 
4328 		lseek(fd, f_attr.ids.offset, SEEK_SET);
4329 
4330 		for (j = 0; j < nr_ids; j++) {
4331 			if (perf_header__getbuffer64(header, fd, &f_id, sizeof(f_id)))
4332 				goto out_errno;
4333 
4334 			perf_evlist__id_add(&session->evlist->core, &evsel->core, 0, j, f_id);
4335 		}
4336 
4337 		lseek(fd, tmp, SEEK_SET);
4338 	}
4339 
4340 #ifdef HAVE_LIBTRACEEVENT
4341 	perf_header__process_sections(header, fd, &session->tevent,
4342 				      perf_file_section__process);
4343 
4344 	if (evlist__prepare_tracepoint_events(session->evlist, session->tevent.pevent))
4345 		goto out_delete_evlist;
4346 #else
4347 	perf_header__process_sections(header, fd, NULL, perf_file_section__process);
4348 #endif
4349 
4350 	return 0;
4351 out_errno:
4352 	return -errno;
4353 
4354 out_delete_evlist:
4355 	evlist__delete(session->evlist);
4356 	session->evlist = NULL;
4357 	return -ENOMEM;
4358 }
4359 
perf_event__process_feature(struct perf_session * session,union perf_event * event)4360 int perf_event__process_feature(struct perf_session *session,
4361 				union perf_event *event)
4362 {
4363 	struct feat_fd ff = { .fd = 0 };
4364 	struct perf_record_header_feature *fe = (struct perf_record_header_feature *)event;
4365 	int type = fe->header.type;
4366 	u64 feat = fe->feat_id;
4367 	int ret = 0;
4368 	bool print = dump_trace;
4369 
4370 	if (type < 0 || type >= PERF_RECORD_HEADER_MAX) {
4371 		pr_warning("invalid record type %d in pipe-mode\n", type);
4372 		return 0;
4373 	}
4374 	if (feat == HEADER_RESERVED || feat >= HEADER_LAST_FEATURE) {
4375 		pr_warning("invalid record type %d in pipe-mode\n", type);
4376 		return -1;
4377 	}
4378 
4379 	ff.buf  = (void *)fe->data;
4380 	ff.size = event->header.size - sizeof(*fe);
4381 	ff.ph = &session->header;
4382 
4383 	if (feat_ops[feat].process && feat_ops[feat].process(&ff, NULL)) {
4384 		ret = -1;
4385 		goto out;
4386 	}
4387 
4388 	if (session->tool->show_feat_hdr) {
4389 		if (!feat_ops[feat].full_only ||
4390 		    session->tool->show_feat_hdr >= SHOW_FEAT_HEADER_FULL_INFO) {
4391 			print = true;
4392 		} else {
4393 			fprintf(stdout, "# %s info available, use -I to display\n",
4394 				feat_ops[feat].name);
4395 		}
4396 	}
4397 
4398 	if (dump_trace)
4399 		printf(", ");
4400 
4401 	if (print) {
4402 		if (feat_ops[feat].print)
4403 			feat_ops[feat].print(&ff, stdout);
4404 		else
4405 			printf("# %s", feat_ops[feat].name);
4406 	}
4407 
4408 out:
4409 	free_event_desc(ff.events);
4410 	return ret;
4411 }
4412 
perf_event__fprintf_event_update(union perf_event * event,FILE * fp)4413 size_t perf_event__fprintf_event_update(union perf_event *event, FILE *fp)
4414 {
4415 	struct perf_record_event_update *ev = &event->event_update;
4416 	struct perf_cpu_map *map;
4417 	size_t ret;
4418 
4419 	ret = fprintf(fp, "\n... id:    %" PRI_lu64 "\n", ev->id);
4420 
4421 	switch (ev->type) {
4422 	case PERF_EVENT_UPDATE__SCALE:
4423 		ret += fprintf(fp, "... scale: %f\n", ev->scale.scale);
4424 		break;
4425 	case PERF_EVENT_UPDATE__UNIT:
4426 		ret += fprintf(fp, "... unit:  %s\n", ev->unit);
4427 		break;
4428 	case PERF_EVENT_UPDATE__NAME:
4429 		ret += fprintf(fp, "... name:  %s\n", ev->name);
4430 		break;
4431 	case PERF_EVENT_UPDATE__CPUS:
4432 		ret += fprintf(fp, "... ");
4433 
4434 		map = cpu_map__new_data(&ev->cpus.cpus);
4435 		if (map) {
4436 			ret += cpu_map__fprintf(map, fp);
4437 			perf_cpu_map__put(map);
4438 		} else
4439 			ret += fprintf(fp, "failed to get cpus\n");
4440 		break;
4441 	default:
4442 		ret += fprintf(fp, "... unknown type\n");
4443 		break;
4444 	}
4445 
4446 	return ret;
4447 }
4448 
perf_event__fprintf_attr(union perf_event * event,FILE * fp)4449 size_t perf_event__fprintf_attr(union perf_event *event, FILE *fp)
4450 {
4451 	return perf_event_attr__fprintf(fp, &event->attr.attr, __desc_attr__fprintf, NULL);
4452 }
4453 
perf_event__process_attr(const struct perf_tool * tool __maybe_unused,union perf_event * event,struct evlist ** pevlist)4454 int perf_event__process_attr(const struct perf_tool *tool __maybe_unused,
4455 			     union perf_event *event,
4456 			     struct evlist **pevlist)
4457 {
4458 	u32 i, n_ids;
4459 	u64 *ids;
4460 	struct evsel *evsel;
4461 	struct evlist *evlist = *pevlist;
4462 
4463 	if (dump_trace)
4464 		perf_event__fprintf_attr(event, stdout);
4465 
4466 	if (evlist == NULL) {
4467 		*pevlist = evlist = evlist__new();
4468 		if (evlist == NULL)
4469 			return -ENOMEM;
4470 	}
4471 
4472 	evsel = evsel__new(&event->attr.attr);
4473 	if (evsel == NULL)
4474 		return -ENOMEM;
4475 
4476 	evlist__add(evlist, evsel);
4477 
4478 	n_ids = event->header.size - sizeof(event->header) - event->attr.attr.size;
4479 	n_ids = n_ids / sizeof(u64);
4480 	/*
4481 	 * We don't have the cpu and thread maps on the header, so
4482 	 * for allocating the perf_sample_id table we fake 1 cpu and
4483 	 * hattr->ids threads.
4484 	 */
4485 	if (perf_evsel__alloc_id(&evsel->core, 1, n_ids))
4486 		return -ENOMEM;
4487 
4488 	ids = perf_record_header_attr_id(event);
4489 	for (i = 0; i < n_ids; i++) {
4490 		perf_evlist__id_add(&evlist->core, &evsel->core, 0, i, ids[i]);
4491 	}
4492 
4493 	return 0;
4494 }
4495 
perf_event__process_event_update(const struct perf_tool * tool __maybe_unused,union perf_event * event,struct evlist ** pevlist)4496 int perf_event__process_event_update(const struct perf_tool *tool __maybe_unused,
4497 				     union perf_event *event,
4498 				     struct evlist **pevlist)
4499 {
4500 	struct perf_record_event_update *ev = &event->event_update;
4501 	struct evlist *evlist;
4502 	struct evsel *evsel;
4503 	struct perf_cpu_map *map;
4504 
4505 	if (dump_trace)
4506 		perf_event__fprintf_event_update(event, stdout);
4507 
4508 	if (!pevlist || *pevlist == NULL)
4509 		return -EINVAL;
4510 
4511 	evlist = *pevlist;
4512 
4513 	evsel = evlist__id2evsel(evlist, ev->id);
4514 	if (evsel == NULL)
4515 		return -EINVAL;
4516 
4517 	switch (ev->type) {
4518 	case PERF_EVENT_UPDATE__UNIT:
4519 		free((char *)evsel->unit);
4520 		evsel->unit = strdup(ev->unit);
4521 		break;
4522 	case PERF_EVENT_UPDATE__NAME:
4523 		free(evsel->name);
4524 		evsel->name = strdup(ev->name);
4525 		break;
4526 	case PERF_EVENT_UPDATE__SCALE:
4527 		evsel->scale = ev->scale.scale;
4528 		break;
4529 	case PERF_EVENT_UPDATE__CPUS:
4530 		map = cpu_map__new_data(&ev->cpus.cpus);
4531 		if (map) {
4532 			perf_cpu_map__put(evsel->core.pmu_cpus);
4533 			evsel->core.pmu_cpus = map;
4534 		} else
4535 			pr_err("failed to get event_update cpus\n");
4536 	default:
4537 		break;
4538 	}
4539 
4540 	return 0;
4541 }
4542 
4543 #ifdef HAVE_LIBTRACEEVENT
perf_event__process_tracing_data(struct perf_session * session,union perf_event * event)4544 int perf_event__process_tracing_data(struct perf_session *session,
4545 				     union perf_event *event)
4546 {
4547 	ssize_t size_read, padding, size = event->tracing_data.size;
4548 	int fd = perf_data__fd(session->data);
4549 	char buf[BUFSIZ];
4550 
4551 	/*
4552 	 * The pipe fd is already in proper place and in any case
4553 	 * we can't move it, and we'd screw the case where we read
4554 	 * 'pipe' data from regular file. The trace_report reads
4555 	 * data from 'fd' so we need to set it directly behind the
4556 	 * event, where the tracing data starts.
4557 	 */
4558 	if (!perf_data__is_pipe(session->data)) {
4559 		off_t offset = lseek(fd, 0, SEEK_CUR);
4560 
4561 		/* setup for reading amidst mmap */
4562 		lseek(fd, offset + sizeof(struct perf_record_header_tracing_data),
4563 		      SEEK_SET);
4564 	}
4565 
4566 	size_read = trace_report(fd, &session->tevent, session->trace_event_repipe);
4567 	padding = PERF_ALIGN(size_read, sizeof(u64)) - size_read;
4568 
4569 	if (readn(fd, buf, padding) < 0) {
4570 		pr_err("%s: reading input file", __func__);
4571 		return -1;
4572 	}
4573 	if (session->trace_event_repipe) {
4574 		int retw = write(STDOUT_FILENO, buf, padding);
4575 		if (retw <= 0 || retw != padding) {
4576 			pr_err("%s: repiping tracing data padding", __func__);
4577 			return -1;
4578 		}
4579 	}
4580 
4581 	if (size_read + padding != size) {
4582 		pr_err("%s: tracing data size mismatch", __func__);
4583 		return -1;
4584 	}
4585 
4586 	evlist__prepare_tracepoint_events(session->evlist, session->tevent.pevent);
4587 
4588 	return size_read + padding;
4589 }
4590 #endif
4591 
perf_event__process_build_id(struct perf_session * session,union perf_event * event)4592 int perf_event__process_build_id(struct perf_session *session,
4593 				 union perf_event *event)
4594 {
4595 	__event_process_build_id(&event->build_id,
4596 				 event->build_id.filename,
4597 				 session);
4598 	return 0;
4599 }
4600