xref: /linux/tools/perf/util/header.c (revision 6cdecad561fffb7c44241ad35a8bdb6a0ed30b5b)
1 // SPDX-License-Identifier: GPL-2.0
2 #include "header.h"
3 
4 #include <errno.h>
5 #include <inttypes.h>
6 #include <limits.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <fcntl.h>
11 
12 #include <byteswap.h>
13 #include <dirent.h>
14 #include <linux/bitops.h>
15 #include <linux/compiler.h>
16 #include <linux/ctype.h>
17 #include <linux/kernel.h>
18 #include <linux/list.h>
19 #include <linux/string.h>
20 #include <linux/stringify.h>
21 #include <linux/time64.h>
22 #include <linux/zalloc.h>
23 #include <regex.h>
24 #include <sys/param.h>
25 #include <sys/stat.h>
26 #include <sys/types.h>
27 #include <sys/utsname.h>
28 #include <unistd.h>
29 
30 #include <api/fs/fs.h>
31 #include <api/io_dir.h>
32 #include <internal/lib.h>
33 #include <perf/cpumap.h>
34 #include <tools/libc_compat.h> // reallocarray
35 
36 #include "../perf.h"
37 #include "bpf-event.h"
38 #include "bpf-utils.h"
39 #include "build-id.h"
40 #include "cacheline.h"
41 #include "clockid.h"
42 #include "cpumap.h"
43 #include "cputopo.h"
44 #include "data.h"
45 #include "debug.h"
46 #include "dso.h"
47 #include "evlist.h"
48 #include "evsel.h"
49 #include "evsel_fprintf.h"
50 #include "memswap.h"
51 #include "pmu.h"
52 #include "pmus.h"
53 #include "session.h"
54 #include "strbuf.h"
55 #include "string2.h"
56 #include "symbol.h"
57 #include "time-utils.h"
58 #include "tool.h"
59 #include "trace-event.h"
60 #include "units.h"
61 #include "util.h" // perf_exe()
62 #include "vdso.h"
63 
64 #ifdef HAVE_LIBBPF_SUPPORT
65 #include <bpf/libbpf.h>
66 #endif
67 
68 #ifdef HAVE_LIBTRACEEVENT
69 #include <event-parse.h>
70 #endif
71 
72 /*
73  * nr_ids * sizeof(struct perf_sample_id) must not overflow
74  * size_t on 32-bit; the struct is ~104 bytes (32-bit) or
75  * ~184 bytes (64-bit), so 1<<24 (16M) keeps the product
76  * under 2 GB on 32-bit.
77  *
78  * This is a per-attribute cap only — the total across all
79  * attributes is not capped because legitimate high-core-count
80  * workloads (e.g. 5000 tracepoints × 4096 CPUs) can exceed
81  * a single-attribute limit.
82  */
83 #define MAX_IDS_PER_ATTR	(1 << 24)
84 /*
85  * Cap nr_attrs to prevent resource exhaustion from crafted
86  * files.  65536 is well beyond any real workload (perf stat
87  * typically uses < 100 events) but prevents u64-to-int
88  * truncation on the attr count.
89  */
90 #define MAX_NR_ATTRS		(1 << 16)
91 #define MAX_BPF_DATA_LEN	(256 * 1024 * 1024)
92 #define MAX_BPF_PROGS		131072
93 #define MAX_CACHE_ENTRIES	32768
94 #define MAX_GROUP_DESC		32768
95 #define MAX_NUMA_NODES		4096
96 #define MAX_PMU_CAPS		512
97 #define MAX_PMU_MAPPINGS	4096
98 #define MAX_SCHED_DOMAINS	64
99 #define MAX_MEMORY_RANGES	256
100 
101 /*
102  * magic2 = "PERFILE2"
103  * must be a numerical value to let the endianness
104  * determine the memory layout. That way we are able
105  * to detect endianness when reading the perf.data file
106  * back.
107  *
108  * we check for legacy (PERFFILE) format.
109  */
110 static const char *__perf_magic1 = "PERFFILE";
111 static const u64 __perf_magic2    = 0x32454c4946524550ULL;
112 static const u64 __perf_magic2_sw = 0x50455246494c4532ULL;
113 
114 #define PERF_MAGIC	__perf_magic2
115 #define DNAME_LEN	16
116 
117 const char perf_version_string[] = PERF_VERSION;
118 
119 struct perf_file_attr {
120 	struct perf_event_attr	attr;
121 	struct perf_file_section	ids;
122 };
123 
124 void perf_header__set_feat(struct perf_header *header, int feat)
125 {
126 	__set_bit(feat, header->adds_features);
127 }
128 
129 void perf_header__clear_feat(struct perf_header *header, int feat)
130 {
131 	__clear_bit(feat, header->adds_features);
132 }
133 
134 bool perf_header__has_feat(const struct perf_header *header, int feat)
135 {
136 	return test_bit(feat, header->adds_features);
137 }
138 
139 static int __do_write_fd(struct feat_fd *ff, const void *buf, size_t size)
140 {
141 	ssize_t ret = writen(ff->fd, buf, size);
142 
143 	if (ret != (ssize_t)size)
144 		return ret < 0 ? (int)ret : -1;
145 	return 0;
146 }
147 
148 static int __do_write_buf(struct feat_fd *ff,  const void *buf, size_t size)
149 {
150 	/* struct perf_event_header::size is u16 */
151 	const size_t max_size = 0xffff - sizeof(struct perf_event_header);
152 	size_t new_size = ff->size;
153 	void *addr;
154 
155 	if (size + ff->offset > max_size)
156 		return -E2BIG;
157 
158 	while (size > (new_size - ff->offset))
159 		new_size <<= 1;
160 	new_size = min(max_size, new_size);
161 
162 	if (ff->size < new_size) {
163 		addr = realloc(ff->buf, new_size);
164 		if (!addr)
165 			return -ENOMEM;
166 		ff->buf = addr;
167 		ff->size = new_size;
168 	}
169 
170 	memcpy(ff->buf + ff->offset, buf, size);
171 	ff->offset += size;
172 
173 	return 0;
174 }
175 
176 /* Return: 0 if succeeded, -ERR if failed. */
177 int do_write(struct feat_fd *ff, const void *buf, size_t size)
178 {
179 	if (!ff->buf)
180 		return __do_write_fd(ff, buf, size);
181 	return __do_write_buf(ff, buf, size);
182 }
183 
184 /* Return: 0 if succeeded, -ERR if failed. */
185 static int do_write_bitmap(struct feat_fd *ff, unsigned long *set, u64 size)
186 {
187 	size_t byte_size = BITS_TO_LONGS(size) * sizeof(unsigned long);
188 	int i, ret;
189 
190 	ret = do_write(ff, &size, sizeof(size));
191 	if (ret < 0)
192 		return ret;
193 
194 	/*
195 	 * The on-disk format uses u64 elements, but the in-memory bitmap
196 	 * uses unsigned long, which is only 4 bytes on 32-bit architectures.
197 	 * Copy with bounded size so the last element doesn't read past the
198 	 * bitmap allocation when BITS_TO_LONGS(size) is odd.
199 	 */
200 	for (i = 0; (u64) i < BITS_TO_U64(size); i++) {
201 		u64 val = 0;
202 		size_t off = i * sizeof(val);
203 
204 		memcpy(&val, (char *)set + off, min(sizeof(val), byte_size - off));
205 		ret = do_write(ff, &val, sizeof(val));
206 		if (ret < 0)
207 			return ret;
208 	}
209 
210 	return 0;
211 }
212 
213 /* Return: 0 if succeeded, -ERR if failed. */
214 int write_padded(struct feat_fd *ff, const void *bf,
215 		 size_t count, size_t count_aligned)
216 {
217 	static const char zero_buf[NAME_ALIGN];
218 	int err = do_write(ff, bf, count);
219 
220 	if (!err)
221 		err = do_write(ff, zero_buf, count_aligned - count);
222 
223 	return err;
224 }
225 
226 #define string_size(str)						\
227 	(PERF_ALIGN((strlen(str) + 1), NAME_ALIGN) + sizeof(u32))
228 
229 /* Return: 0 if succeeded, -ERR if failed. */
230 static int do_write_string(struct feat_fd *ff, const char *str)
231 {
232 	u32 len, olen;
233 	int ret;
234 
235 	olen = strlen(str) + 1;
236 	len = PERF_ALIGN(olen, NAME_ALIGN);
237 
238 	/* write len, incl. \0 */
239 	ret = do_write(ff, &len, sizeof(len));
240 	if (ret < 0)
241 		return ret;
242 
243 	return write_padded(ff, str, olen, len);
244 }
245 
246 static int __do_read_fd(struct feat_fd *ff, void *addr, ssize_t size)
247 {
248 	ssize_t ret = readn(ff->fd, addr, size);
249 
250 	if (ret != size)
251 		return ret < 0 ? (int)ret : -1;
252 	ff->offset += size;
253 	return 0;
254 }
255 
256 static int __do_read_buf(struct feat_fd *ff, void *addr, ssize_t size)
257 {
258 	memcpy(addr, ff->buf + ff->offset, size);
259 	ff->offset += size;
260 
261 	return 0;
262 }
263 
264 static int __do_read(struct feat_fd *ff, void *addr, ssize_t size)
265 {
266 	/*
267 	 * Reject negative sizes, which on 32-bit can occur when a
268 	 * u32 >= 0x80000000 is passed as ssize_t.  The cast to
269 	 * ssize_t is safe because perf_header__process_sections()
270 	 * validates that each section fits within the file size
271 	 * before any feature callback reaches here, and only
272 	 * feature sections (metadata like build IDs, topology, etc.)
273 	 * use this path — these cannot legitimately approach 2GB.
274 	 */
275 	if (size < 0 || size > (ssize_t)ff->size - ff->offset)
276 		return -1;
277 
278 	if (!ff->buf)
279 		return __do_read_fd(ff, addr, size);
280 	return __do_read_buf(ff, addr, size);
281 }
282 
283 static int do_read_u32(struct feat_fd *ff, u32 *addr)
284 {
285 	int ret;
286 
287 	ret = __do_read(ff, addr, sizeof(*addr));
288 	if (ret)
289 		return ret;
290 
291 	if (ff->ph->needs_swap)
292 		*addr = bswap_32(*addr);
293 	return 0;
294 }
295 
296 static int do_read_u64(struct feat_fd *ff, u64 *addr)
297 {
298 	int ret;
299 
300 	ret = __do_read(ff, addr, sizeof(*addr));
301 	if (ret)
302 		return ret;
303 
304 	if (ff->ph->needs_swap)
305 		*addr = bswap_64(*addr);
306 	return 0;
307 }
308 
309 static char *do_read_string(struct feat_fd *ff)
310 {
311 	u32 len;
312 	char *buf;
313 
314 	if (do_read_u32(ff, &len))
315 		return NULL;
316 
317 	/* At least the null terminator. */
318 	if (len < 1 || len > ff->size - ff->offset) {
319 		pr_debug("do_read_string: invalid length %u (remaining %zu)\n",
320 			 len, (size_t)(ff->size - ff->offset));
321 		return NULL;
322 	}
323 
324 	buf = malloc(len);
325 	if (!buf)
326 		return NULL;
327 
328 	if (!__do_read(ff, buf, len)) {
329 		/*
330 		 * do_write_string() writes len including the null
331 		 * terminator, padded to NAME_ALIGN.  Ensure the
332 		 * string is always null-terminated even if the file
333 		 * data has been tampered with.
334 		 */
335 		buf[len - 1] = '\0';
336 		return buf;
337 	}
338 
339 	free(buf);
340 	return NULL;
341 }
342 
343 /* Return: 0 if succeeded, -ERR if failed. */
344 static int do_read_bitmap(struct feat_fd *ff, unsigned long **pset, u64 *psize)
345 {
346 	unsigned long *set;
347 	u64 size, *p;
348 	int i, ret;
349 
350 	ret = do_read_u64(ff, &size);
351 	if (ret)
352 		return ret;
353 
354 	/* Bitmap APIs use int for nbits; reject u64 values that truncate. */
355 	if (size > INT_MAX ||
356 	    BITS_TO_U64(size) > (ff->size - ff->offset) / sizeof(u64)) {
357 		pr_debug("do_read_bitmap: size %" PRIu64 " exceeds section bounds\n", size);
358 		return -1;
359 	}
360 
361 	/*
362 	 * bitmap_zalloc() allocates in unsigned long units, which are only
363 	 * 4 bytes on 32-bit architectures. The read loop below casts the
364 	 * buffer to u64 * and writes 8-byte elements, so allocate in u64
365 	 * units to ensure the buffer is large enough.
366 	 */
367 	set = calloc(BITS_TO_U64(size), sizeof(u64));
368 	if (!set)
369 		return -ENOMEM;
370 
371 	p = (u64 *) set;
372 
373 	for (i = 0; (u64) i < BITS_TO_U64(size); i++) {
374 		ret = do_read_u64(ff, p + i);
375 		if (ret < 0) {
376 			free(set);
377 			return ret;
378 		}
379 	}
380 
381 	*pset  = set;
382 	*psize = size;
383 	return 0;
384 }
385 
386 static int write_tracing_data(struct feat_fd *ff,
387 			      struct evlist *evlist __maybe_unused)
388 {
389 	if (ff->buf) {
390 		pr_warning("Error: calling %s in pipe-mode.\n", __func__);
391 		return -1;
392 	}
393 
394 #ifdef HAVE_LIBTRACEEVENT
395 	return read_tracing_data(ff->fd, &evlist__core(evlist)->entries);
396 #else
397 	pr_err("ERROR: Trying to write tracing data without libtraceevent support.\n");
398 	return -1;
399 #endif
400 }
401 
402 static int write_build_id(struct feat_fd *ff,
403 			  struct evlist *evlist __maybe_unused)
404 {
405 	struct perf_session *session;
406 	int err;
407 
408 	session = container_of(ff->ph, struct perf_session, header);
409 
410 	if (!perf_session__read_build_ids(session, true))
411 		return -1;
412 
413 	if (ff->buf) {
414 		pr_warning("Error: calling %s in pipe-mode.\n", __func__);
415 		return -1;
416 	}
417 
418 	err = perf_session__write_buildid_table(session, ff);
419 	if (err < 0) {
420 		pr_debug("failed to write buildid table\n");
421 		return err;
422 	}
423 
424 	return 0;
425 }
426 
427 static int write_hostname(struct feat_fd *ff,
428 			  struct evlist *evlist __maybe_unused)
429 {
430 	struct utsname uts;
431 	int ret;
432 
433 	ret = uname(&uts);
434 	if (ret < 0)
435 		return -1;
436 
437 	return do_write_string(ff, uts.nodename);
438 }
439 
440 static int write_osrelease(struct feat_fd *ff,
441 			   struct evlist *evlist __maybe_unused)
442 {
443 	struct utsname uts;
444 	const char *release = NULL;
445 
446 	if (evlist__session(evlist))
447 		release = perf_env__os_release(perf_session__env(evlist__session(evlist)));
448 
449 	if (!release) {
450 		int ret = uname(&uts);
451 
452 		if (ret < 0)
453 			return -1;
454 		release = uts.release;
455 	}
456 	return do_write_string(ff, release);
457 }
458 
459 static int write_arch(struct feat_fd *ff, struct evlist *evlist)
460 {
461 	struct utsname uts;
462 	const char *arch = NULL;
463 
464 	if (evlist__session(evlist))
465 		arch = perf_env__arch(perf_session__env(evlist__session(evlist)));
466 
467 	if (!arch) {
468 		int ret = uname(&uts);
469 
470 		if (ret < 0)
471 			return -1;
472 		arch = uts.machine;
473 	}
474 	return do_write_string(ff, arch);
475 }
476 
477 static int write_e_machine(struct feat_fd *ff, struct evlist *evlist)
478 {
479 	/* e_machine expanded from 16 to 32-bits for alignment. */
480 	uint32_t e_flags;
481 	uint32_t e_machine = perf_session__e_machine(evlist__session(evlist), &e_flags);
482 	int ret;
483 
484 	ret = do_write(ff, &e_machine, sizeof(e_machine));
485 	if (ret)
486 		return ret;
487 
488 	return do_write(ff, &e_flags, sizeof(e_flags));
489 }
490 
491 static int write_version(struct feat_fd *ff,
492 			 struct evlist *evlist __maybe_unused)
493 {
494 	return do_write_string(ff, perf_version_string);
495 }
496 
497 static int __write_cpudesc(struct feat_fd *ff, const char *cpuinfo_proc)
498 {
499 	FILE *file;
500 	char *buf = NULL;
501 	char *s, *p;
502 	const char *search = cpuinfo_proc;
503 	size_t len = 0;
504 	int ret = -1;
505 
506 	if (!search)
507 		return -1;
508 
509 	file = fopen("/proc/cpuinfo", "r");
510 	if (!file)
511 		return -1;
512 
513 	while (getline(&buf, &len, file) > 0) {
514 		ret = strncmp(buf, search, strlen(search));
515 		if (!ret)
516 			break;
517 	}
518 
519 	if (ret) {
520 		ret = -1;
521 		goto done;
522 	}
523 
524 	s = buf;
525 
526 	p = strchr(buf, ':');
527 	if (p && *(p+1) == ' ' && *(p+2))
528 		s = p + 2;
529 	p = strchr(s, '\n');
530 	if (p)
531 		*p = '\0';
532 
533 	/* squash extra space characters (branding string) */
534 	p = s;
535 	while (*p) {
536 		if (isspace(*p)) {
537 			char *r = p + 1;
538 			char *q = skip_spaces(r);
539 			*p = ' ';
540 			if (q != (p+1))
541 				while ((*r++ = *q++));
542 		}
543 		p++;
544 	}
545 	ret = do_write_string(ff, s);
546 done:
547 	free(buf);
548 	fclose(file);
549 	return ret;
550 }
551 
552 static int write_cpudesc(struct feat_fd *ff,
553 		       struct evlist *evlist __maybe_unused)
554 {
555 #if defined(__powerpc__) || defined(__hppa__) || defined(__sparc__)
556 #define CPUINFO_PROC	{ "cpu", }
557 #elif defined(__s390__)
558 #define CPUINFO_PROC	{ "vendor_id", }
559 #elif defined(__sh__)
560 #define CPUINFO_PROC	{ "cpu type", }
561 #elif defined(__alpha__) || defined(__mips__)
562 #define CPUINFO_PROC	{ "cpu model", }
563 #elif defined(__arm__)
564 #define CPUINFO_PROC	{ "model name", "Processor", }
565 #elif defined(__arc__)
566 #define CPUINFO_PROC	{ "Processor", }
567 #elif defined(__xtensa__)
568 #define CPUINFO_PROC	{ "core ID", }
569 #elif defined(__loongarch__)
570 #define CPUINFO_PROC	{ "Model Name", }
571 #else
572 #define CPUINFO_PROC	{ "model name", }
573 #endif
574 	const char *cpuinfo_procs[] = CPUINFO_PROC;
575 #undef CPUINFO_PROC
576 	unsigned int i;
577 
578 	for (i = 0; i < ARRAY_SIZE(cpuinfo_procs); i++) {
579 		int ret;
580 		ret = __write_cpudesc(ff, cpuinfo_procs[i]);
581 		if (ret >= 0)
582 			return ret;
583 	}
584 	return -1;
585 }
586 
587 
588 static int write_nrcpus(struct feat_fd *ff,
589 			struct evlist *evlist __maybe_unused)
590 {
591 	long nr;
592 	u32 nrc, nra;
593 	int ret;
594 
595 	nrc = cpu__max_present_cpu().cpu;
596 
597 	nr = sysconf(_SC_NPROCESSORS_ONLN);
598 	if (nr < 0)
599 		return -1;
600 
601 	nra = (u32)(nr & UINT_MAX);
602 
603 	ret = do_write(ff, &nrc, sizeof(nrc));
604 	if (ret < 0)
605 		return ret;
606 
607 	return do_write(ff, &nra, sizeof(nra));
608 }
609 
610 static int write_event_desc(struct feat_fd *ff,
611 			    struct evlist *evlist)
612 {
613 	struct evsel *evsel;
614 	u32 nre, nri, sz;
615 	int ret;
616 
617 	nre = evlist__nr_entries(evlist);
618 
619 	/*
620 	 * write number of events
621 	 */
622 	ret = do_write(ff, &nre, sizeof(nre));
623 	if (ret < 0)
624 		return ret;
625 
626 	/*
627 	 * size of perf_event_attr struct
628 	 */
629 	sz = (u32)sizeof(evsel->core.attr);
630 	ret = do_write(ff, &sz, sizeof(sz));
631 	if (ret < 0)
632 		return ret;
633 
634 	evlist__for_each_entry(evlist, evsel) {
635 		ret = do_write(ff, &evsel->core.attr, sz);
636 		if (ret < 0)
637 			return ret;
638 		/*
639 		 * write number of unique id per event
640 		 * there is one id per instance of an event
641 		 *
642 		 * copy into an nri to be independent of the
643 		 * type of ids,
644 		 */
645 		nri = evsel->core.ids;
646 		ret = do_write(ff, &nri, sizeof(nri));
647 		if (ret < 0)
648 			return ret;
649 
650 		/*
651 		 * write event string as passed on cmdline
652 		 */
653 		ret = do_write_string(ff, evsel__name(evsel));
654 		if (ret < 0)
655 			return ret;
656 		/*
657 		 * write unique ids for this event
658 		 */
659 		ret = do_write(ff, evsel->core.id, evsel->core.ids * sizeof(u64));
660 		if (ret < 0)
661 			return ret;
662 	}
663 	return 0;
664 }
665 
666 static int write_cmdline(struct feat_fd *ff,
667 			 struct evlist *evlist __maybe_unused)
668 {
669 	struct perf_env *env = &ff->ph->env;
670 	char pbuf[MAXPATHLEN], *buf;
671 	int i, ret, n;
672 
673 	/* actual path to perf binary */
674 	buf = perf_exe(pbuf, MAXPATHLEN);
675 
676 	/* account for binary path */
677 	n = env->nr_cmdline + 1;
678 
679 	ret = do_write(ff, &n, sizeof(n));
680 	if (ret < 0)
681 		return ret;
682 
683 	ret = do_write_string(ff, buf);
684 	if (ret < 0)
685 		return ret;
686 
687 	for (i = 0 ; i < env->nr_cmdline; i++) {
688 		ret = do_write_string(ff, env->cmdline_argv[i]);
689 		if (ret < 0)
690 			return ret;
691 	}
692 	return 0;
693 }
694 
695 
696 static int write_cpu_topology(struct feat_fd *ff,
697 			      struct evlist *evlist __maybe_unused)
698 {
699 	struct perf_env *env = &ff->ph->env;
700 	struct cpu_topology *tp;
701 	u32 i;
702 	int ret, j;
703 
704 	tp = cpu_topology__new();
705 	if (!tp)
706 		return -1;
707 
708 	ret = do_write(ff, &tp->package_cpus_lists, sizeof(tp->package_cpus_lists));
709 	if (ret < 0)
710 		goto done;
711 
712 	for (i = 0; i < tp->package_cpus_lists; i++) {
713 		ret = do_write_string(ff, tp->package_cpus_list[i]);
714 		if (ret < 0)
715 			goto done;
716 	}
717 	ret = do_write(ff, &tp->core_cpus_lists, sizeof(tp->core_cpus_lists));
718 	if (ret < 0)
719 		goto done;
720 
721 	for (i = 0; i < tp->core_cpus_lists; i++) {
722 		ret = do_write_string(ff, tp->core_cpus_list[i]);
723 		if (ret < 0)
724 			break;
725 	}
726 
727 	ret = perf_env__read_cpu_topology_map(env);
728 	if (ret < 0)
729 		goto done;
730 
731 	for (j = 0; j < env->nr_cpus_avail; j++) {
732 		ret = do_write(ff, &env->cpu[j].core_id,
733 			       sizeof(env->cpu[j].core_id));
734 		if (ret < 0)
735 			return ret;
736 		ret = do_write(ff, &env->cpu[j].socket_id,
737 			       sizeof(env->cpu[j].socket_id));
738 		if (ret < 0)
739 			return ret;
740 	}
741 
742 	if (!tp->die_cpus_lists)
743 		goto done;
744 
745 	ret = do_write(ff, &tp->die_cpus_lists, sizeof(tp->die_cpus_lists));
746 	if (ret < 0)
747 		goto done;
748 
749 	for (i = 0; i < tp->die_cpus_lists; i++) {
750 		ret = do_write_string(ff, tp->die_cpus_list[i]);
751 		if (ret < 0)
752 			goto done;
753 	}
754 
755 	for (j = 0; j < env->nr_cpus_avail; j++) {
756 		ret = do_write(ff, &env->cpu[j].die_id,
757 			       sizeof(env->cpu[j].die_id));
758 		if (ret < 0)
759 			return ret;
760 	}
761 
762 done:
763 	cpu_topology__delete(tp);
764 	return ret;
765 }
766 
767 
768 
769 static int write_total_mem(struct feat_fd *ff,
770 			   struct evlist *evlist __maybe_unused)
771 {
772 	char *buf = NULL;
773 	FILE *fp;
774 	size_t len = 0;
775 	int ret = -1, n;
776 	uint64_t mem;
777 
778 	fp = fopen("/proc/meminfo", "r");
779 	if (!fp)
780 		return -1;
781 
782 	while (getline(&buf, &len, fp) > 0) {
783 		ret = strncmp(buf, "MemTotal:", 9);
784 		if (!ret)
785 			break;
786 	}
787 	if (!ret) {
788 		n = sscanf(buf, "%*s %"PRIu64, &mem);
789 		if (n == 1)
790 			ret = do_write(ff, &mem, sizeof(mem));
791 	} else
792 		ret = -1;
793 	free(buf);
794 	fclose(fp);
795 	return ret;
796 }
797 
798 static int write_numa_topology(struct feat_fd *ff,
799 			       struct evlist *evlist __maybe_unused)
800 {
801 	struct numa_topology *tp;
802 	int ret = -1;
803 	u32 i;
804 
805 	tp = numa_topology__new();
806 	if (!tp)
807 		return -ENOMEM;
808 
809 	ret = do_write(ff, &tp->nr, sizeof(u32));
810 	if (ret < 0)
811 		goto err;
812 
813 	for (i = 0; i < tp->nr; i++) {
814 		struct numa_topology_node *n = &tp->nodes[i];
815 
816 		ret = do_write(ff, &n->node, sizeof(u32));
817 		if (ret < 0)
818 			goto err;
819 
820 		ret = do_write(ff, &n->mem_total, sizeof(u64));
821 		if (ret)
822 			goto err;
823 
824 		ret = do_write(ff, &n->mem_free, sizeof(u64));
825 		if (ret)
826 			goto err;
827 
828 		ret = do_write_string(ff, n->cpus);
829 		if (ret < 0)
830 			goto err;
831 	}
832 
833 	ret = 0;
834 
835 err:
836 	numa_topology__delete(tp);
837 	return ret;
838 }
839 
840 /*
841  * File format:
842  *
843  * struct pmu_mappings {
844  *	u32	pmu_num;
845  *	struct pmu_map {
846  *		u32	type;
847  *		char	name[];
848  *	}[pmu_num];
849  * };
850  */
851 
852 static int write_pmu_mappings(struct feat_fd *ff,
853 			      struct evlist *evlist __maybe_unused)
854 {
855 	struct perf_pmu *pmu = NULL;
856 	u32 pmu_num = 0;
857 	int ret;
858 
859 	/*
860 	 * Do a first pass to count number of pmu to avoid lseek so this
861 	 * works in pipe mode as well.
862 	 */
863 	while ((pmu = perf_pmus__scan(pmu)))
864 		pmu_num++;
865 
866 	ret = do_write(ff, &pmu_num, sizeof(pmu_num));
867 	if (ret < 0)
868 		return ret;
869 
870 	while ((pmu = perf_pmus__scan(pmu))) {
871 		ret = do_write(ff, &pmu->type, sizeof(pmu->type));
872 		if (ret < 0)
873 			return ret;
874 
875 		ret = do_write_string(ff, pmu->name);
876 		if (ret < 0)
877 			return ret;
878 	}
879 
880 	return 0;
881 }
882 
883 /*
884  * File format:
885  *
886  * struct group_descs {
887  *	u32	nr_groups;
888  *	struct group_desc {
889  *		char	name[];
890  *		u32	leader_idx;
891  *		u32	nr_members;
892  *	}[nr_groups];
893  * };
894  */
895 static int write_group_desc(struct feat_fd *ff,
896 			    struct evlist *evlist)
897 {
898 	u32 nr_groups = evlist__nr_groups(evlist);
899 	struct evsel *evsel;
900 	int ret;
901 
902 	ret = do_write(ff, &nr_groups, sizeof(nr_groups));
903 	if (ret < 0)
904 		return ret;
905 
906 	evlist__for_each_entry(evlist, evsel) {
907 		if (evsel__is_group_leader(evsel) && evsel->core.nr_members > 1) {
908 			const char *name = evsel->group_name ?: "{anon_group}";
909 			u32 leader_idx = evsel->core.idx;
910 			u32 nr_members = evsel->core.nr_members;
911 
912 			ret = do_write_string(ff, name);
913 			if (ret < 0)
914 				return ret;
915 
916 			ret = do_write(ff, &leader_idx, sizeof(leader_idx));
917 			if (ret < 0)
918 				return ret;
919 
920 			ret = do_write(ff, &nr_members, sizeof(nr_members));
921 			if (ret < 0)
922 				return ret;
923 		}
924 	}
925 	return 0;
926 }
927 
928 /*
929  * Return the CPU id as a raw string.
930  *
931  * Each architecture should provide a more precise id string that
932  * can be use to match the architecture's "mapfile".
933  */
934 char * __weak get_cpuid_str(struct perf_cpu cpu __maybe_unused)
935 {
936 	return NULL;
937 }
938 
939 char *get_cpuid_allow_env_override(struct perf_cpu cpu)
940 {
941 	char *cpuid;
942 	static bool printed;
943 
944 	cpuid = getenv("PERF_CPUID");
945 	if (cpuid)
946 		cpuid = strdup(cpuid);
947 	if (!cpuid)
948 		cpuid = get_cpuid_str(cpu);
949 	if (!cpuid)
950 		return NULL;
951 
952 	if (!printed) {
953 		pr_debug("Using CPUID %s\n", cpuid);
954 		printed = true;
955 	}
956 	return cpuid;
957 }
958 
959 /* Return zero when the cpuid from the mapfile.csv matches the
960  * cpuid string generated on this platform.
961  * Otherwise return non-zero.
962  */
963 int __weak strcmp_cpuid_str(const char *mapcpuid, const char *cpuid)
964 {
965 	regex_t re;
966 	regmatch_t pmatch[1];
967 	int match;
968 
969 	if (regcomp(&re, mapcpuid, REG_EXTENDED) != 0) {
970 		/* Warn unable to generate match particular string. */
971 		pr_info("Invalid regular expression %s\n", mapcpuid);
972 		return 1;
973 	}
974 
975 	match = !regexec(&re, cpuid, 1, pmatch, 0);
976 	regfree(&re);
977 	if (match) {
978 		size_t match_len = (pmatch[0].rm_eo - pmatch[0].rm_so);
979 
980 		/* Verify the entire string matched. */
981 		if (match_len == strlen(cpuid))
982 			return 0;
983 	}
984 	return 1;
985 }
986 
987 /*
988  * default get_cpuid(): nothing gets recorded
989  * actual implementation must be in arch/$(SRCARCH)/util/header.c
990  */
991 int __weak get_cpuid(char *buffer __maybe_unused, size_t sz __maybe_unused,
992 		     struct perf_cpu cpu __maybe_unused)
993 {
994 	return ENOSYS; /* Not implemented */
995 }
996 
997 static int write_cpuid(struct feat_fd *ff, struct evlist *evlist)
998 {
999 	struct perf_cpu cpu = perf_cpu_map__min(evlist__core(evlist)->all_cpus);
1000 	char buffer[64];
1001 	int ret;
1002 
1003 	ret = get_cpuid(buffer, sizeof(buffer), cpu);
1004 	if (ret)
1005 		return -1;
1006 
1007 	return do_write_string(ff, buffer);
1008 }
1009 
1010 static int write_branch_stack(struct feat_fd *ff __maybe_unused,
1011 			      struct evlist *evlist __maybe_unused)
1012 {
1013 	return 0;
1014 }
1015 
1016 static int write_auxtrace(struct feat_fd *ff,
1017 			  struct evlist *evlist __maybe_unused)
1018 {
1019 	struct perf_session *session;
1020 	int err;
1021 
1022 	if (ff->buf) {
1023 		pr_warning("Error: calling %s in pipe-mode.\n", __func__);
1024 		return -1;
1025 	}
1026 
1027 	session = container_of(ff->ph, struct perf_session, header);
1028 
1029 	err = auxtrace_index__write(ff->fd, &session->auxtrace_index);
1030 	if (err < 0)
1031 		pr_err("Failed to write auxtrace index\n");
1032 	return err;
1033 }
1034 
1035 static int write_clockid(struct feat_fd *ff,
1036 			 struct evlist *evlist __maybe_unused)
1037 {
1038 	return do_write(ff, &ff->ph->env.clock.clockid_res_ns,
1039 			sizeof(ff->ph->env.clock.clockid_res_ns));
1040 }
1041 
1042 static int write_clock_data(struct feat_fd *ff,
1043 			    struct evlist *evlist __maybe_unused)
1044 {
1045 	u64 *data64;
1046 	u32 data32;
1047 	int ret;
1048 
1049 	/* version */
1050 	data32 = 1;
1051 
1052 	ret = do_write(ff, &data32, sizeof(data32));
1053 	if (ret < 0)
1054 		return ret;
1055 
1056 	/* clockid */
1057 	data32 = ff->ph->env.clock.clockid;
1058 
1059 	ret = do_write(ff, &data32, sizeof(data32));
1060 	if (ret < 0)
1061 		return ret;
1062 
1063 	/* TOD ref time */
1064 	data64 = &ff->ph->env.clock.tod_ns;
1065 
1066 	ret = do_write(ff, data64, sizeof(*data64));
1067 	if (ret < 0)
1068 		return ret;
1069 
1070 	/* clockid ref time */
1071 	data64 = &ff->ph->env.clock.clockid_ns;
1072 
1073 	return do_write(ff, data64, sizeof(*data64));
1074 }
1075 
1076 static int write_hybrid_topology(struct feat_fd *ff,
1077 				 struct evlist *evlist __maybe_unused)
1078 {
1079 	struct hybrid_topology *tp;
1080 	int ret;
1081 	u32 i;
1082 
1083 	tp = hybrid_topology__new();
1084 	if (!tp)
1085 		return -ENOENT;
1086 
1087 	ret = do_write(ff, &tp->nr, sizeof(u32));
1088 	if (ret < 0)
1089 		goto err;
1090 
1091 	for (i = 0; i < tp->nr; i++) {
1092 		struct hybrid_topology_node *n = &tp->nodes[i];
1093 
1094 		ret = do_write_string(ff, n->pmu_name);
1095 		if (ret < 0)
1096 			goto err;
1097 
1098 		ret = do_write_string(ff, n->cpus);
1099 		if (ret < 0)
1100 			goto err;
1101 	}
1102 
1103 	ret = 0;
1104 
1105 err:
1106 	hybrid_topology__delete(tp);
1107 	return ret;
1108 }
1109 
1110 static int write_dir_format(struct feat_fd *ff,
1111 			    struct evlist *evlist __maybe_unused)
1112 {
1113 	struct perf_session *session;
1114 	struct perf_data *data;
1115 
1116 	session = container_of(ff->ph, struct perf_session, header);
1117 	data = session->data;
1118 
1119 	if (!perf_data__is_dir(data)) {
1120 		pr_warning("Expected data to be a directory\n");
1121 		return -1;
1122 	}
1123 	return do_write(ff, &data->dir.version, sizeof(data->dir.version));
1124 }
1125 
1126 static int write_bpf_prog_info(struct feat_fd *ff  __maybe_unused,
1127 			       struct evlist *evlist __maybe_unused)
1128 {
1129 #ifdef HAVE_LIBBPF_SUPPORT
1130 	struct perf_env *env = &ff->ph->env;
1131 	struct rb_root *root;
1132 	struct rb_node *next;
1133 	int ret = 0;
1134 
1135 	/* write lock: bpil_addr_to_offs() temporarily mutates info_linear */
1136 	down_write(&env->bpf_progs.lock);
1137 
1138 	ret = do_write(ff, &env->bpf_progs.infos_cnt,
1139 		       sizeof(env->bpf_progs.infos_cnt));
1140 	if (ret < 0 || env->bpf_progs.infos_cnt == 0)
1141 		goto out;
1142 
1143 	root = &env->bpf_progs.infos;
1144 	next = rb_first(root);
1145 	while (next) {
1146 		struct bpf_prog_info_node *node;
1147 		size_t len;
1148 
1149 		node = rb_entry(next, struct bpf_prog_info_node, rb_node);
1150 		next = rb_next(&node->rb_node);
1151 		len = sizeof(struct perf_bpil) +
1152 			node->info_linear->data_len;
1153 
1154 		/* before writing to file, translate address to offset */
1155 		bpil_addr_to_offs(node->info_linear);
1156 		ret = do_write(ff, node->info_linear, len);
1157 		/*
1158 		 * translate back to address even when do_write() fails,
1159 		 * so that this function never changes the data.
1160 		 */
1161 		bpil_offs_to_addr(node->info_linear);
1162 		if (ret < 0)
1163 			goto out;
1164 	}
1165 out:
1166 	up_write(&env->bpf_progs.lock);
1167 	return ret;
1168 #else
1169 	pr_err("ERROR: Trying to write bpf_prog_info without libbpf support.\n");
1170 	return -1;
1171 #endif // HAVE_LIBBPF_SUPPORT
1172 }
1173 
1174 static int write_bpf_btf(struct feat_fd *ff __maybe_unused,
1175 			 struct evlist *evlist __maybe_unused)
1176 {
1177 #ifdef HAVE_LIBBPF_SUPPORT
1178 	struct perf_env *env = &ff->ph->env;
1179 	struct rb_root *root;
1180 	struct rb_node *next;
1181 	int ret = 0;
1182 
1183 	down_read(&env->bpf_progs.lock);
1184 
1185 	ret = do_write(ff, &env->bpf_progs.btfs_cnt,
1186 		       sizeof(env->bpf_progs.btfs_cnt));
1187 
1188 	if (ret < 0 || env->bpf_progs.btfs_cnt == 0)
1189 		goto out;
1190 
1191 	root = &env->bpf_progs.btfs;
1192 	next = rb_first(root);
1193 	while (next) {
1194 		struct btf_node *node;
1195 
1196 		node = rb_entry(next, struct btf_node, rb_node);
1197 		next = rb_next(&node->rb_node);
1198 		ret = do_write(ff, &node->id,
1199 			       sizeof(u32) * 2 + node->data_size);
1200 		if (ret < 0)
1201 			goto out;
1202 	}
1203 out:
1204 	up_read(&env->bpf_progs.lock);
1205 	return ret;
1206 #else
1207 	pr_err("ERROR: Trying to write btf data without libbpf support.\n");
1208 	return -1;
1209 #endif // HAVE_LIBBPF_SUPPORT
1210 }
1211 
1212 static int cpu_cache_level__sort(const void *a, const void *b)
1213 {
1214 	struct cpu_cache_level *cache_a = (struct cpu_cache_level *)a;
1215 	struct cpu_cache_level *cache_b = (struct cpu_cache_level *)b;
1216 
1217 	return cache_a->level - cache_b->level;
1218 }
1219 
1220 static bool cpu_cache_level__cmp(struct cpu_cache_level *a, struct cpu_cache_level *b)
1221 {
1222 	if (a->level != b->level)
1223 		return false;
1224 
1225 	if (a->line_size != b->line_size)
1226 		return false;
1227 
1228 	if (a->sets != b->sets)
1229 		return false;
1230 
1231 	if (a->ways != b->ways)
1232 		return false;
1233 
1234 	if (strcmp(a->type, b->type))
1235 		return false;
1236 
1237 	if (strcmp(a->size, b->size))
1238 		return false;
1239 
1240 	if (strcmp(a->map, b->map))
1241 		return false;
1242 
1243 	return true;
1244 }
1245 
1246 static int cpu_cache_level__read(struct cpu_cache_level *cache, u32 cpu, u16 level)
1247 {
1248 	char path[PATH_MAX], file[PATH_MAX];
1249 	struct stat st;
1250 	size_t len;
1251 
1252 	scnprintf(path, PATH_MAX, "devices/system/cpu/cpu%d/cache/index%d/", cpu, level);
1253 	scnprintf(file, PATH_MAX, "%s/%s", sysfs__mountpoint(), path);
1254 
1255 	if (stat(file, &st))
1256 		return 1;
1257 
1258 	scnprintf(file, PATH_MAX, "%s/level", path);
1259 	if (sysfs__read_int(file, (int *) &cache->level))
1260 		return -1;
1261 
1262 	scnprintf(file, PATH_MAX, "%s/coherency_line_size", path);
1263 	if (sysfs__read_int(file, (int *) &cache->line_size))
1264 		return -1;
1265 
1266 	scnprintf(file, PATH_MAX, "%s/number_of_sets", path);
1267 	if (sysfs__read_int(file, (int *) &cache->sets))
1268 		return -1;
1269 
1270 	scnprintf(file, PATH_MAX, "%s/ways_of_associativity", path);
1271 	if (sysfs__read_int(file, (int *) &cache->ways))
1272 		return -1;
1273 
1274 	scnprintf(file, PATH_MAX, "%s/type", path);
1275 	if (sysfs__read_str(file, &cache->type, &len))
1276 		return -1;
1277 
1278 	cache->type[len] = 0;
1279 	{
1280 		char *trimmed = strim(cache->type);
1281 
1282 		memmove(cache->type, trimmed, strlen(trimmed) + 1);
1283 	}
1284 
1285 	scnprintf(file, PATH_MAX, "%s/size", path);
1286 	if (sysfs__read_str(file, &cache->size, &len)) {
1287 		zfree(&cache->type);
1288 		return -1;
1289 	}
1290 
1291 	cache->size[len] = 0;
1292 	{
1293 		char *trimmed = strim(cache->size);
1294 
1295 		memmove(cache->size, trimmed, strlen(trimmed) + 1);
1296 	}
1297 
1298 	scnprintf(file, PATH_MAX, "%s/shared_cpu_list", path);
1299 	if (sysfs__read_str(file, &cache->map, &len)) {
1300 		zfree(&cache->size);
1301 		zfree(&cache->type);
1302 		return -1;
1303 	}
1304 
1305 	cache->map[len] = 0;
1306 	{
1307 		char *trimmed = strim(cache->map);
1308 
1309 		memmove(cache->map, trimmed, strlen(trimmed) + 1);
1310 	}
1311 	return 0;
1312 }
1313 
1314 static void cpu_cache_level__fprintf(FILE *out, struct cpu_cache_level *c)
1315 {
1316 	fprintf(out, "L%d %-15s %8s [%s]\n", c->level, c->type, c->size, c->map);
1317 }
1318 
1319 /*
1320  * Build caches levels for a particular CPU from the data in
1321  * /sys/devices/system/cpu/cpu<cpu>/cache/
1322  * The cache level data is stored in caches[] from index at
1323  * *cntp.
1324  */
1325 int build_caches_for_cpu(u32 cpu, struct cpu_cache_level caches[], u32 *cntp)
1326 {
1327 	u16 level;
1328 
1329 	for (level = 0; level < MAX_CACHE_LVL; level++) {
1330 		struct cpu_cache_level c;
1331 		int err;
1332 		u32 i;
1333 
1334 		err = cpu_cache_level__read(&c, cpu, level);
1335 		if (err < 0)
1336 			return err;
1337 
1338 		if (err == 1)
1339 			break;
1340 
1341 		for (i = 0; i < *cntp; i++) {
1342 			if (cpu_cache_level__cmp(&c, &caches[i]))
1343 				break;
1344 		}
1345 
1346 		if (i == *cntp) {
1347 			caches[*cntp] = c;
1348 			*cntp = *cntp + 1;
1349 		} else
1350 			cpu_cache_level__free(&c);
1351 	}
1352 
1353 	return 0;
1354 }
1355 
1356 static int build_caches(struct cpu_cache_level caches[], u32 *cntp)
1357 {
1358 	u32 nr, cpu, cnt = 0;
1359 
1360 	nr = cpu__max_cpu().cpu;
1361 
1362 	for (cpu = 0; cpu < nr; cpu++) {
1363 		int ret = build_caches_for_cpu(cpu, caches, &cnt);
1364 
1365 		if (ret)
1366 			return ret;
1367 	}
1368 	*cntp = cnt;
1369 	return 0;
1370 }
1371 
1372 static int write_cache(struct feat_fd *ff,
1373 		       struct evlist *evlist __maybe_unused)
1374 {
1375 	u32 max_caches = cpu__max_cpu().cpu * MAX_CACHE_LVL;
1376 	struct cpu_cache_level caches[max_caches];
1377 	u32 cnt = 0, i, version = 1;
1378 	int ret;
1379 
1380 	ret = build_caches(caches, &cnt);
1381 	if (ret)
1382 		goto out;
1383 
1384 	qsort(&caches, cnt, sizeof(struct cpu_cache_level), cpu_cache_level__sort);
1385 
1386 	ret = do_write(ff, &version, sizeof(u32));
1387 	if (ret < 0)
1388 		goto out;
1389 
1390 	ret = do_write(ff, &cnt, sizeof(u32));
1391 	if (ret < 0)
1392 		goto out;
1393 
1394 	for (i = 0; i < cnt; i++) {
1395 		struct cpu_cache_level *c = &caches[i];
1396 
1397 		#define _W(v)					\
1398 			ret = do_write(ff, &c->v, sizeof(u32));	\
1399 			if (ret < 0)				\
1400 				goto out;
1401 
1402 		_W(level)
1403 		_W(line_size)
1404 		_W(sets)
1405 		_W(ways)
1406 		#undef _W
1407 
1408 		#define _W(v)						\
1409 			ret = do_write_string(ff, (const char *) c->v);	\
1410 			if (ret < 0)					\
1411 				goto out;
1412 
1413 		_W(type)
1414 		_W(size)
1415 		_W(map)
1416 		#undef _W
1417 	}
1418 
1419 out:
1420 	for (i = 0; i < cnt; i++)
1421 		cpu_cache_level__free(&caches[i]);
1422 	return ret;
1423 }
1424 
1425 static int write_cln_size(struct feat_fd *ff,
1426 		       struct evlist *evlist __maybe_unused)
1427 {
1428 	int cln_size = cacheline_size();
1429 
1430 	if (!cln_size)
1431 		cln_size = DEFAULT_CACHELINE_SIZE;
1432 
1433 	ff->ph->env.cln_size = cln_size;
1434 
1435 	return do_write(ff, &cln_size, sizeof(cln_size));
1436 }
1437 
1438 static int write_stat(struct feat_fd *ff __maybe_unused,
1439 		      struct evlist *evlist __maybe_unused)
1440 {
1441 	return 0;
1442 }
1443 
1444 static int write_sample_time(struct feat_fd *ff,
1445 			     struct evlist *evlist)
1446 {
1447 	int ret;
1448 	u64 data = evlist__first_sample_time(evlist);
1449 
1450 	ret = do_write(ff, &data, sizeof(data));
1451 	if (ret < 0)
1452 		return ret;
1453 
1454 	data = evlist__last_sample_time(evlist);
1455 	return do_write(ff, &data, sizeof(data));
1456 }
1457 
1458 
1459 static int memory_node__read(struct memory_node *n, unsigned long idx)
1460 {
1461 	unsigned int phys, size = 0;
1462 	char path[PATH_MAX];
1463 	struct io_dirent64 *ent;
1464 	struct io_dir dir;
1465 
1466 #define for_each_memory(mem, dir)					\
1467 	while ((ent = io_dir__readdir(&dir)) != NULL)			\
1468 		if (strcmp(ent->d_name, ".") &&				\
1469 		    strcmp(ent->d_name, "..") &&			\
1470 		    sscanf(ent->d_name, "memory%u", &mem) == 1)
1471 
1472 	scnprintf(path, PATH_MAX,
1473 		  "%s/devices/system/node/node%lu",
1474 		  sysfs__mountpoint(), idx);
1475 
1476 	io_dir__init(&dir, open(path, O_CLOEXEC | O_DIRECTORY | O_RDONLY));
1477 	if (dir.dirfd < 0) {
1478 		pr_warning("failed: can't open memory sysfs data '%s'\n", path);
1479 		return -1;
1480 	}
1481 
1482 	for_each_memory(phys, dir) {
1483 		size = max(phys, size);
1484 	}
1485 
1486 	size++;
1487 
1488 	n->set = bitmap_zalloc(size);
1489 	if (!n->set) {
1490 		close(dir.dirfd);
1491 		return -ENOMEM;
1492 	}
1493 
1494 	n->node = idx;
1495 	n->size = size;
1496 
1497 	io_dir__rewinddir(&dir);
1498 
1499 	for_each_memory(phys, dir) {
1500 		__set_bit(phys, n->set);
1501 	}
1502 
1503 	close(dir.dirfd);
1504 	return 0;
1505 }
1506 
1507 static void memory_node__delete_nodes(struct memory_node *nodesp, u64 cnt)
1508 {
1509 	for (u64 i = 0; i < cnt; i++)
1510 		bitmap_free(nodesp[i].set);
1511 
1512 	free(nodesp);
1513 }
1514 
1515 static int memory_node__sort(const void *a, const void *b)
1516 {
1517 	const struct memory_node *na = a;
1518 	const struct memory_node *nb = b;
1519 
1520 	return na->node - nb->node;
1521 }
1522 
1523 static int build_mem_topology(struct memory_node **nodesp, u64 *cntp)
1524 {
1525 	char path[PATH_MAX];
1526 	struct io_dirent64 *ent;
1527 	struct io_dir dir;
1528 	int ret = 0;
1529 	size_t cnt = 0, size = 0;
1530 	struct memory_node *nodes = NULL;
1531 
1532 	scnprintf(path, PATH_MAX, "%s/devices/system/node/",
1533 		  sysfs__mountpoint());
1534 
1535 	io_dir__init(&dir, open(path, O_CLOEXEC | O_DIRECTORY | O_RDONLY));
1536 	if (dir.dirfd < 0) {
1537 		pr_debug2("%s: couldn't read %s, does this arch have topology information?\n",
1538 			  __func__, path);
1539 		return -1;
1540 	}
1541 
1542 	while (!ret && (ent = io_dir__readdir(&dir))) {
1543 		unsigned int idx;
1544 		int r;
1545 
1546 		if (!strcmp(ent->d_name, ".") ||
1547 		    !strcmp(ent->d_name, ".."))
1548 			continue;
1549 
1550 		r = sscanf(ent->d_name, "node%u", &idx);
1551 		if (r != 1)
1552 			continue;
1553 
1554 		if (cnt >= size) {
1555 			struct memory_node *new_nodes =
1556 				reallocarray(nodes, cnt + 4, sizeof(*nodes));
1557 
1558 			if (!new_nodes) {
1559 				pr_err("Failed to write MEM_TOPOLOGY, size %zd nodes\n", size);
1560 				ret = -ENOMEM;
1561 				goto out;
1562 			}
1563 			nodes = new_nodes;
1564 			size += 4;
1565 		}
1566 		ret = memory_node__read(&nodes[cnt], idx);
1567 		if (!ret)
1568 			cnt += 1;
1569 	}
1570 out:
1571 	close(dir.dirfd);
1572 	if (!ret) {
1573 		*cntp = cnt;
1574 		*nodesp = nodes;
1575 		qsort(nodes, cnt, sizeof(nodes[0]), memory_node__sort);
1576 	} else
1577 		memory_node__delete_nodes(nodes, cnt);
1578 
1579 	return ret;
1580 }
1581 
1582 /*
1583  * The MEM_TOPOLOGY holds physical memory map for every
1584  * node in system. The format of data is as follows:
1585  *
1586  *  0 - version          | for future changes
1587  *  8 - block_size_bytes | /sys/devices/system/memory/block_size_bytes
1588  * 16 - count            | number of nodes
1589  *
1590  * For each node we store map of physical indexes for
1591  * each node:
1592  *
1593  * 32 - node id          | node index
1594  * 40 - size             | size of bitmap
1595  * 48 - bitmap           | bitmap of memory indexes that belongs to node
1596  */
1597 static int write_mem_topology(struct feat_fd *ff __maybe_unused,
1598 			      struct evlist *evlist __maybe_unused)
1599 {
1600 	struct memory_node *nodes = NULL;
1601 	u64 bsize, version = 1, i, nr = 0;
1602 	int ret;
1603 
1604 	ret = sysfs__read_xll("devices/system/memory/block_size_bytes",
1605 			      (unsigned long long *) &bsize);
1606 	if (ret)
1607 		return ret;
1608 
1609 	ret = build_mem_topology(&nodes, &nr);
1610 	if (ret)
1611 		return ret;
1612 
1613 	ret = do_write(ff, &version, sizeof(version));
1614 	if (ret < 0)
1615 		goto out;
1616 
1617 	ret = do_write(ff, &bsize, sizeof(bsize));
1618 	if (ret < 0)
1619 		goto out;
1620 
1621 	ret = do_write(ff, &nr, sizeof(nr));
1622 	if (ret < 0)
1623 		goto out;
1624 
1625 	for (i = 0; i < nr; i++) {
1626 		struct memory_node *n = &nodes[i];
1627 
1628 		#define _W(v)						\
1629 			ret = do_write(ff, &n->v, sizeof(n->v));	\
1630 			if (ret < 0)					\
1631 				goto out;
1632 
1633 		_W(node)
1634 		_W(size)
1635 
1636 		#undef _W
1637 
1638 		ret = do_write_bitmap(ff, n->set, n->size);
1639 		if (ret < 0)
1640 			goto out;
1641 	}
1642 
1643 out:
1644 	memory_node__delete_nodes(nodes, nr);
1645 	return ret;
1646 }
1647 
1648 static int write_compressed(struct feat_fd *ff __maybe_unused,
1649 			    struct evlist *evlist __maybe_unused)
1650 {
1651 	int ret;
1652 
1653 	ret = do_write(ff, &(ff->ph->env.comp_ver), sizeof(ff->ph->env.comp_ver));
1654 	if (ret)
1655 		return ret;
1656 
1657 	ret = do_write(ff, &(ff->ph->env.comp_type), sizeof(ff->ph->env.comp_type));
1658 	if (ret)
1659 		return ret;
1660 
1661 	ret = do_write(ff, &(ff->ph->env.comp_level), sizeof(ff->ph->env.comp_level));
1662 	if (ret)
1663 		return ret;
1664 
1665 	ret = do_write(ff, &(ff->ph->env.comp_ratio), sizeof(ff->ph->env.comp_ratio));
1666 	if (ret)
1667 		return ret;
1668 
1669 	return do_write(ff, &(ff->ph->env.comp_mmap_len), sizeof(ff->ph->env.comp_mmap_len));
1670 }
1671 
1672 static int __write_pmu_caps(struct feat_fd *ff, struct perf_pmu *pmu,
1673 			    bool write_pmu)
1674 {
1675 	struct perf_pmu_caps *caps = NULL;
1676 	int ret;
1677 
1678 	ret = do_write(ff, &pmu->nr_caps, sizeof(pmu->nr_caps));
1679 	if (ret < 0)
1680 		return ret;
1681 
1682 	list_for_each_entry(caps, &pmu->caps, list) {
1683 		ret = do_write_string(ff, caps->name);
1684 		if (ret < 0)
1685 			return ret;
1686 
1687 		ret = do_write_string(ff, caps->value);
1688 		if (ret < 0)
1689 			return ret;
1690 	}
1691 
1692 	if (write_pmu) {
1693 		ret = do_write_string(ff, pmu->name);
1694 		if (ret < 0)
1695 			return ret;
1696 	}
1697 
1698 	return ret;
1699 }
1700 
1701 static int write_cpu_pmu_caps(struct feat_fd *ff,
1702 			      struct evlist *evlist __maybe_unused)
1703 {
1704 	struct perf_pmu *cpu_pmu = perf_pmus__find_core_pmu();
1705 	int ret;
1706 
1707 	if (!cpu_pmu)
1708 		return -ENOENT;
1709 
1710 	ret = perf_pmu__caps_parse(cpu_pmu);
1711 	if (ret < 0)
1712 		return ret;
1713 
1714 	return __write_pmu_caps(ff, cpu_pmu, false);
1715 }
1716 
1717 static int write_pmu_caps(struct feat_fd *ff,
1718 			  struct evlist *evlist __maybe_unused)
1719 {
1720 	struct perf_pmu *pmu = NULL;
1721 	int nr_pmu = 0;
1722 	int ret;
1723 
1724 	while ((pmu = perf_pmus__scan(pmu))) {
1725 		if (!strcmp(pmu->name, "cpu")) {
1726 			/*
1727 			 * The "cpu" PMU is special and covered by
1728 			 * HEADER_CPU_PMU_CAPS. Note, core PMUs are
1729 			 * counted/written here for ARM, s390 and Intel hybrid.
1730 			 */
1731 			continue;
1732 		}
1733 		if (perf_pmu__caps_parse(pmu) <= 0)
1734 			continue;
1735 		nr_pmu++;
1736 	}
1737 
1738 	ret = do_write(ff, &nr_pmu, sizeof(nr_pmu));
1739 	if (ret < 0)
1740 		return ret;
1741 
1742 	if (!nr_pmu)
1743 		return 0;
1744 
1745 	/*
1746 	 * Note older perf tools assume core PMUs come first, this is a property
1747 	 * of perf_pmus__scan.
1748 	 */
1749 	pmu = NULL;
1750 	while ((pmu = perf_pmus__scan(pmu))) {
1751 		if (!strcmp(pmu->name, "cpu")) {
1752 			/* Skip as above. */
1753 			continue;
1754 		}
1755 		if (perf_pmu__caps_parse(pmu) <= 0)
1756 			continue;
1757 		ret = __write_pmu_caps(ff, pmu, true);
1758 		if (ret < 0)
1759 			return ret;
1760 	}
1761 	return 0;
1762 }
1763 
1764 struct cpu_domain_map **build_cpu_domain_map(u32 *schedstat_version, u32 *max_sched_domains, u32 nr)
1765 {
1766 	char dname[DNAME_LEN], cpumask[MAX_NR_CPUS];
1767 	struct domain_info *domain_info;
1768 	struct cpu_domain_map **cd_map;
1769 	char cpulist[MAX_NR_CPUS];
1770 	char *line = NULL;
1771 	u32 cpu, domain;
1772 	u32 dcount = 0;
1773 	size_t len;
1774 	FILE *fp;
1775 
1776 	fp = fopen("/proc/schedstat", "r");
1777 	if (!fp) {
1778 		pr_err("Failed to open /proc/schedstat\n");
1779 		return NULL;
1780 	}
1781 
1782 	cd_map = zalloc(sizeof(*cd_map) * nr);
1783 	if (!cd_map)
1784 		goto out;
1785 
1786 	while (getline(&line, &len, fp) > 0) {
1787 		int retval;
1788 
1789 		if (strncmp(line, "version", 7) == 0) {
1790 			retval = sscanf(line, "version %d\n", schedstat_version);
1791 			if (retval != 1)
1792 				continue;
1793 
1794 		} else if (strncmp(line, "cpu", 3) == 0) {
1795 			retval = sscanf(line, "cpu%u %*s", &cpu);
1796 			if (retval == 1) {
1797 				cd_map[cpu] = zalloc(sizeof(*cd_map[cpu]));
1798 				if (!cd_map[cpu])
1799 					goto out_free_line;
1800 				cd_map[cpu]->cpu = cpu;
1801 			} else
1802 				continue;
1803 
1804 			dcount = 0;
1805 		} else if (strncmp(line, "domain", 6) == 0) {
1806 			struct domain_info **temp_domains;
1807 
1808 			dcount++;
1809 			temp_domains = realloc(cd_map[cpu]->domains, dcount * sizeof(domain_info));
1810 			if (!temp_domains)
1811 				goto out_free_line;
1812 			else
1813 				cd_map[cpu]->domains = temp_domains;
1814 
1815 			domain_info = zalloc(sizeof(*domain_info));
1816 			if (!domain_info)
1817 				goto out_free_line;
1818 
1819 			cd_map[cpu]->domains[dcount - 1] = domain_info;
1820 
1821 			if (*schedstat_version >= 17) {
1822 				retval = sscanf(line, "domain%u %s %s %*s", &domain, dname,
1823 						cpumask);
1824 				if (retval != 3)
1825 					continue;
1826 
1827 				domain_info->dname = strdup(dname);
1828 				if (!domain_info->dname)
1829 					goto out_free_line;
1830 			} else {
1831 				retval = sscanf(line, "domain%u %s %*s", &domain, cpumask);
1832 				if (retval != 2)
1833 					continue;
1834 			}
1835 
1836 			domain_info->domain = domain;
1837 			if (domain > *max_sched_domains)
1838 				*max_sched_domains = domain;
1839 
1840 			domain_info->cpumask = strdup(cpumask);
1841 			if (!domain_info->cpumask)
1842 				goto out_free_line;
1843 
1844 			cpumask_to_cpulist(cpumask, cpulist);
1845 			domain_info->cpulist = strdup(cpulist);
1846 			if (!domain_info->cpulist)
1847 				goto out_free_line;
1848 
1849 			cd_map[cpu]->nr_domains = dcount;
1850 		}
1851 	}
1852 
1853 out_free_line:
1854 	free(line);
1855 out:
1856 	fclose(fp);
1857 	return cd_map;
1858 }
1859 
1860 static int write_cpu_domain_info(struct feat_fd *ff,
1861 				 struct evlist *evlist __maybe_unused)
1862 {
1863 	u32 max_sched_domains = 0, schedstat_version = 0;
1864 	struct cpu_domain_map **cd_map;
1865 	u32 i, j, nr, ret;
1866 
1867 	nr = cpu__max_present_cpu().cpu;
1868 
1869 	cd_map = build_cpu_domain_map(&schedstat_version, &max_sched_domains, nr);
1870 	if (!cd_map)
1871 		return -1;
1872 
1873 	ret = do_write(ff, &schedstat_version, sizeof(u32));
1874 	if (ret < 0)
1875 		goto out;
1876 
1877 	max_sched_domains += 1;
1878 	ret = do_write(ff, &max_sched_domains, sizeof(u32));
1879 	if (ret < 0)
1880 		goto out;
1881 
1882 	for (i = 0; i < nr; i++) {
1883 		if (!cd_map[i])
1884 			continue;
1885 
1886 		ret = do_write(ff, &cd_map[i]->cpu, sizeof(u32));
1887 		if (ret < 0)
1888 			goto out;
1889 
1890 		ret = do_write(ff, &cd_map[i]->nr_domains, sizeof(u32));
1891 		if (ret < 0)
1892 			goto out;
1893 
1894 		for (j = 0; j < cd_map[i]->nr_domains; j++) {
1895 			ret = do_write(ff, &cd_map[i]->domains[j]->domain, sizeof(u32));
1896 			if (ret < 0)
1897 				goto out;
1898 			if (schedstat_version >= 17) {
1899 				ret = do_write_string(ff, cd_map[i]->domains[j]->dname);
1900 				if (ret < 0)
1901 					goto out;
1902 			}
1903 
1904 			ret = do_write_string(ff, cd_map[i]->domains[j]->cpumask);
1905 			if (ret < 0)
1906 				goto out;
1907 
1908 			ret = do_write_string(ff, cd_map[i]->domains[j]->cpulist);
1909 			if (ret < 0)
1910 				goto out;
1911 		}
1912 	}
1913 
1914 out:
1915 	free_cpu_domain_info(cd_map, schedstat_version, nr);
1916 	return ret;
1917 }
1918 
1919 static int memory_range__read(struct memory_range *range, const char *path)
1920 {
1921 	char buf[32];
1922 	ssize_t n;
1923 	int dfd, fd, tmp, ret = -1;
1924 
1925 	dfd = open(path, O_RDONLY | O_DIRECTORY);
1926 	if (dfd < 0)
1927 		return -1;
1928 
1929 #define _R(name, dst, conv)			\
1930 	fd = openat(dfd, name, O_RDONLY);	\
1931 	if (fd < 0)				\
1932 		goto out;			\
1933 	n = read(fd, buf, sizeof(buf) - 1);	\
1934 	close(fd);				\
1935 	if (n <= 0)				\
1936 		goto out;			\
1937 	buf[n] = '\0';				\
1938 	dst = conv(buf, NULL, 0);
1939 
1940 	_R("base", range->base, strtoull);
1941 	_R("length", range->length, strtoull);
1942 	_R("node", range->node, strtol);
1943 	_R("local_region_id", tmp, strtol);
1944 	if (tmp < 0 || tmp > UINT8_MAX)
1945 		goto out;
1946 	range->local_region_id = tmp;
1947 	_R("remote_region_id", tmp, strtol);
1948 	if (tmp < 0 || tmp > UINT8_MAX)
1949 		goto out;
1950 	range->remote_region_id = tmp;
1951 #undef _R
1952 
1953 	ret = 0;
1954 out:
1955 	close(dfd);
1956 	return ret;
1957 }
1958 
1959 static int memory_range__parse(struct memory_range **ranges)
1960 {
1961 	const char *sysfs = sysfs__mountpoint();
1962 	int i, err, nr_memory_ranges = 0;
1963 	char path[PATH_MAX];
1964 	struct stat st;
1965 
1966 	if (!sysfs)
1967 		return 0;
1968 
1969 	scnprintf(path, PATH_MAX, "%s/firmware/acpi/memory_ranges", sysfs);
1970 	if (stat(path, &st))
1971 		return 0;
1972 
1973 	while (1) {
1974 		scnprintf(path, PATH_MAX,
1975 			  "%s/firmware/acpi/memory_ranges/range%d",
1976 			  sysfs, nr_memory_ranges);
1977 		if (stat(path, &st))
1978 			break;
1979 
1980 		nr_memory_ranges++;
1981 	}
1982 
1983 	if (nr_memory_ranges == 0)
1984 		return 0;
1985 
1986 	*ranges = calloc(nr_memory_ranges, sizeof(struct memory_range));
1987 	if (!(*ranges))
1988 		return -ENOMEM;
1989 
1990 	for (i = 0; i < nr_memory_ranges; i++) {
1991 		struct memory_range range;
1992 
1993 		scnprintf(path, PATH_MAX,
1994 			  "%s/firmware/acpi/memory_ranges/range%d", sysfs, i);
1995 		err = memory_range__read(&range, path);
1996 		if (err < 0)
1997 			goto out_error;
1998 
1999 		(*ranges)[i] = range;
2000 	}
2001 
2002 	return nr_memory_ranges;
2003 
2004 out_error:
2005 	zfree(ranges);
2006 	return -1;
2007 }
2008 
2009 static int write_memory_ranges(struct feat_fd *ff,
2010 			 struct evlist *evlist __maybe_unused)
2011 {
2012 	struct memory_range *ranges = NULL;
2013 	int nr_memory_ranges = 0, ret;
2014 
2015 	nr_memory_ranges = memory_range__parse(&ranges);
2016 	if (nr_memory_ranges < 0)
2017 		return nr_memory_ranges;
2018 
2019 	ret = do_write(ff, &nr_memory_ranges, sizeof(nr_memory_ranges));
2020 	if (ret < 0)
2021 		goto out;
2022 
2023 	for (int i = 0; i < nr_memory_ranges; i++) {
2024 		ret = do_write(ff, &ranges[i].base, sizeof(u64));
2025 		if (ret < 0)
2026 			goto out;
2027 		ret = do_write(ff, &ranges[i].length, sizeof(u64));
2028 		if (ret < 0)
2029 			goto out;
2030 		ret = do_write(ff, &ranges[i].node, sizeof(u32));
2031 		if (ret < 0)
2032 			goto out;
2033 		ret = do_write(ff, &ranges[i].local_region_id, sizeof(u8));
2034 		if (ret < 0)
2035 			goto out;
2036 		ret = do_write(ff, &ranges[i].remote_region_id, sizeof(u8));
2037 		if (ret < 0)
2038 			goto out;
2039 	}
2040 out:
2041 	zfree(&ranges);
2042 	return ret;
2043 }
2044 
2045 static void print_hostname(struct feat_fd *ff, FILE *fp)
2046 {
2047 	fprintf(fp, "# hostname : %s\n", ff->ph->env.hostname);
2048 }
2049 
2050 static void print_osrelease(struct feat_fd *ff, FILE *fp)
2051 {
2052 	fprintf(fp, "# os release : %s\n", ff->ph->env.os_release);
2053 }
2054 
2055 static void print_arch(struct feat_fd *ff, FILE *fp)
2056 {
2057 	fprintf(fp, "# arch : %s\n", ff->ph->env.arch);
2058 }
2059 
2060 static void print_e_machine(struct feat_fd *ff, FILE *fp)
2061 {
2062 	fprintf(fp, "# e_machine : %u\n", ff->ph->env.e_machine);
2063 	fprintf(fp, "#   e_flags : %u\n", ff->ph->env.e_flags);
2064 }
2065 
2066 static void print_cpudesc(struct feat_fd *ff, FILE *fp)
2067 {
2068 	fprintf(fp, "# cpudesc : %s\n", ff->ph->env.cpu_desc);
2069 }
2070 
2071 static void print_nrcpus(struct feat_fd *ff, FILE *fp)
2072 {
2073 	fprintf(fp, "# nrcpus online : %u\n", ff->ph->env.nr_cpus_online);
2074 	fprintf(fp, "# nrcpus avail : %u\n", ff->ph->env.nr_cpus_avail);
2075 }
2076 
2077 static void print_version(struct feat_fd *ff, FILE *fp)
2078 {
2079 	fprintf(fp, "# perf version : %s\n", ff->ph->env.version);
2080 }
2081 
2082 static void print_cmdline(struct feat_fd *ff, FILE *fp)
2083 {
2084 	int nr, i;
2085 
2086 	nr = ff->ph->env.nr_cmdline;
2087 
2088 	fprintf(fp, "# cmdline : ");
2089 
2090 	for (i = 0; i < nr; i++) {
2091 		char *argv_i = strdup(ff->ph->env.cmdline_argv[i]);
2092 		if (!argv_i) {
2093 			fprintf(fp, "%s ", ff->ph->env.cmdline_argv[i]);
2094 		} else {
2095 			char *mem = argv_i;
2096 			do {
2097 				char *quote = strchr(argv_i, '\'');
2098 				if (!quote)
2099 					break;
2100 				*quote++ = '\0';
2101 				fprintf(fp, "%s\\\'", argv_i);
2102 				argv_i = quote;
2103 			} while (1);
2104 			fprintf(fp, "%s ", argv_i);
2105 			free(mem);
2106 		}
2107 	}
2108 	fputc('\n', fp);
2109 }
2110 
2111 static void print_cpu_topology(struct feat_fd *ff, FILE *fp)
2112 {
2113 	struct perf_header *ph = ff->ph;
2114 	int cpu_nr = ph->env.nr_cpus_avail;
2115 	int nr, i;
2116 	char *str;
2117 
2118 	nr = ph->env.nr_sibling_cores;
2119 	str = ph->env.sibling_cores;
2120 
2121 	for (i = 0; i < nr; i++) {
2122 		fprintf(fp, "# sibling sockets : %s\n", str);
2123 		str += strlen(str) + 1;
2124 	}
2125 
2126 	if (ph->env.nr_sibling_dies) {
2127 		nr = ph->env.nr_sibling_dies;
2128 		str = ph->env.sibling_dies;
2129 
2130 		for (i = 0; i < nr; i++) {
2131 			fprintf(fp, "# sibling dies    : %s\n", str);
2132 			str += strlen(str) + 1;
2133 		}
2134 	}
2135 
2136 	nr = ph->env.nr_sibling_threads;
2137 	str = ph->env.sibling_threads;
2138 
2139 	for (i = 0; i < nr; i++) {
2140 		fprintf(fp, "# sibling threads : %s\n", str);
2141 		str += strlen(str) + 1;
2142 	}
2143 
2144 	if (ph->env.nr_sibling_dies) {
2145 		if (ph->env.cpu != NULL) {
2146 			for (i = 0; i < cpu_nr; i++)
2147 				fprintf(fp, "# CPU %d: Core ID %d, "
2148 					    "Die ID %d, Socket ID %d\n",
2149 					    i, ph->env.cpu[i].core_id,
2150 					    ph->env.cpu[i].die_id,
2151 					    ph->env.cpu[i].socket_id);
2152 		} else
2153 			fprintf(fp, "# Core ID, Die ID and Socket ID "
2154 				    "information is not available\n");
2155 	} else {
2156 		if (ph->env.cpu != NULL) {
2157 			for (i = 0; i < cpu_nr; i++)
2158 				fprintf(fp, "# CPU %d: Core ID %d, "
2159 					    "Socket ID %d\n",
2160 					    i, ph->env.cpu[i].core_id,
2161 					    ph->env.cpu[i].socket_id);
2162 		} else
2163 			fprintf(fp, "# Core ID and Socket ID "
2164 				    "information is not available\n");
2165 	}
2166 }
2167 
2168 static void print_clockid(struct feat_fd *ff, FILE *fp)
2169 {
2170 	fprintf(fp, "# clockid frequency: %"PRIu64" MHz\n",
2171 		ff->ph->env.clock.clockid_res_ns * 1000);
2172 }
2173 
2174 static void print_clock_data(struct feat_fd *ff, FILE *fp)
2175 {
2176 	struct timespec clockid_ns;
2177 	char tstr[64], date[64];
2178 	struct timeval tod_ns;
2179 	clockid_t clockid;
2180 	struct tm ltime;
2181 	u64 ref;
2182 
2183 	if (!ff->ph->env.clock.enabled) {
2184 		fprintf(fp, "# reference time disabled\n");
2185 		return;
2186 	}
2187 
2188 	/* Compute TOD time. */
2189 	ref = ff->ph->env.clock.tod_ns;
2190 	tod_ns.tv_sec = ref / NSEC_PER_SEC;
2191 	ref -= tod_ns.tv_sec * NSEC_PER_SEC;
2192 	tod_ns.tv_usec = ref / NSEC_PER_USEC;
2193 
2194 	/* Compute clockid time. */
2195 	ref = ff->ph->env.clock.clockid_ns;
2196 	clockid_ns.tv_sec = ref / NSEC_PER_SEC;
2197 	ref -= clockid_ns.tv_sec * NSEC_PER_SEC;
2198 	clockid_ns.tv_nsec = ref;
2199 
2200 	clockid = ff->ph->env.clock.clockid;
2201 
2202 	if (localtime_r(&tod_ns.tv_sec, &ltime) == NULL)
2203 		snprintf(tstr, sizeof(tstr), "<error>");
2204 	else {
2205 		strftime(date, sizeof(date), "%F %T", &ltime);
2206 		scnprintf(tstr, sizeof(tstr), "%s.%06d",
2207 			  date, (int) tod_ns.tv_usec);
2208 	}
2209 
2210 	fprintf(fp, "# clockid: %s (%u)\n", clockid_name(clockid), clockid);
2211 	fprintf(fp, "# reference time: %s = %ld.%06d (TOD) = %ld.%09ld (%s)\n",
2212 		    tstr, (long) tod_ns.tv_sec, (int) tod_ns.tv_usec,
2213 		    (long) clockid_ns.tv_sec, clockid_ns.tv_nsec,
2214 		    clockid_name(clockid));
2215 }
2216 
2217 static void print_hybrid_topology(struct feat_fd *ff, FILE *fp)
2218 {
2219 	int i;
2220 	struct hybrid_node *n;
2221 
2222 	fprintf(fp, "# hybrid cpu system:\n");
2223 	for (i = 0; i < ff->ph->env.nr_hybrid_nodes; i++) {
2224 		n = &ff->ph->env.hybrid_nodes[i];
2225 		fprintf(fp, "# %s cpu list : %s\n", n->pmu_name, n->cpus);
2226 	}
2227 }
2228 
2229 static void print_dir_format(struct feat_fd *ff, FILE *fp)
2230 {
2231 	struct perf_session *session;
2232 	struct perf_data *data;
2233 
2234 	session = container_of(ff->ph, struct perf_session, header);
2235 	data = session->data;
2236 
2237 	fprintf(fp, "# directory data version : %"PRIu64"\n", data->dir.version);
2238 }
2239 
2240 static void print_bpf_prog_info(struct feat_fd *ff __maybe_unused, FILE *fp)
2241 {
2242 #ifdef HAVE_LIBBPF_SUPPORT
2243 	struct perf_env *env = &ff->ph->env;
2244 	struct rb_root *root;
2245 	struct rb_node *next;
2246 
2247 	down_read(&env->bpf_progs.lock);
2248 
2249 	root = &env->bpf_progs.infos;
2250 	next = rb_first(root);
2251 
2252 	if (!next)
2253 		fprintf(fp, "# bpf_prog_info empty\n");
2254 
2255 	while (next) {
2256 		struct bpf_prog_info_node *node;
2257 
2258 		node = rb_entry(next, struct bpf_prog_info_node, rb_node);
2259 		next = rb_next(&node->rb_node);
2260 
2261 		__bpf_event__print_bpf_prog_info(node->info_linear, env, fp);
2262 	}
2263 
2264 	up_read(&env->bpf_progs.lock);
2265 #else
2266 	fprintf(fp, "# bpf_prog_info missing, no libbpf support\n");
2267 #endif // HAVE_LIBBPF_SUPPORT
2268 }
2269 
2270 static void print_bpf_btf(struct feat_fd *ff __maybe_unused, FILE *fp)
2271 {
2272 #ifdef HAVE_LIBBPF_SUPPORT
2273 	struct perf_env *env = &ff->ph->env;
2274 	struct rb_root *root;
2275 	struct rb_node *next;
2276 
2277 	down_read(&env->bpf_progs.lock);
2278 
2279 	root = &env->bpf_progs.btfs;
2280 	next = rb_first(root);
2281 
2282 	if (!next)
2283 		printf("# btf info empty\n");
2284 
2285 	while (next) {
2286 		struct btf_node *node;
2287 
2288 		node = rb_entry(next, struct btf_node, rb_node);
2289 		next = rb_next(&node->rb_node);
2290 		fprintf(fp, "# btf info of id %u\n", node->id);
2291 	}
2292 
2293 	up_read(&env->bpf_progs.lock);
2294 #else
2295 	fprintf(fp, "# bpf btf data missing, no libbpf support\n");
2296 #endif // HAVE_LIBBPF_SUPPORT
2297 }
2298 
2299 static void free_event_desc(struct evsel *events)
2300 {
2301 	struct evsel *evsel;
2302 
2303 	if (!events)
2304 		return;
2305 
2306 	for (evsel = events; evsel->core.attr.size; evsel++) {
2307 		zfree(&evsel->name);
2308 		zfree(&evsel->core.id);
2309 	}
2310 
2311 	free(events);
2312 }
2313 
2314 static bool perf_attr_check(struct perf_event_attr *attr)
2315 {
2316 	if (attr->__reserved_1 || attr->__reserved_2 ||
2317 	    attr->__reserved_3 || attr->__reserved_4) {
2318 		pr_warning("Reserved bits are set unexpectedly. "
2319 			   "Please update perf tool.\n");
2320 		return false;
2321 	}
2322 
2323 	if (attr->sample_type & ~(PERF_SAMPLE_MAX-1)) {
2324 		pr_warning("Unknown sample type (0x%llx) is detected. "
2325 			   "Please update perf tool.\n",
2326 			   attr->sample_type);
2327 		return false;
2328 	}
2329 
2330 	if (attr->read_format & ~(PERF_FORMAT_MAX-1)) {
2331 		pr_warning("Unknown read format (0x%llx) is detected. "
2332 			   "Please update perf tool.\n",
2333 			   attr->read_format);
2334 		return false;
2335 	}
2336 
2337 	if ((attr->sample_type & PERF_SAMPLE_BRANCH_STACK) &&
2338 	    (attr->branch_sample_type & ~(PERF_SAMPLE_BRANCH_MAX-1))) {
2339 		pr_warning("Unknown branch sample type (0x%llx) is detected. "
2340 			   "Please update perf tool.\n",
2341 			   attr->branch_sample_type);
2342 
2343 		return false;
2344 	}
2345 
2346 	return true;
2347 }
2348 
2349 static struct evsel *read_event_desc(struct feat_fd *ff)
2350 {
2351 	struct evsel *evsel, *events = NULL;
2352 	u64 *id;
2353 	void *buf = NULL;
2354 	u32 nre, sz, nr, i, j;
2355 	size_t msz;
2356 
2357 	/* number of events */
2358 	if (do_read_u32(ff, &nre))
2359 		goto error;
2360 
2361 	/* Size of each of the nre attributes. */
2362 	if (do_read_u32(ff, &sz))
2363 		goto error;
2364 
2365 	/*
2366 	 * Require at least one event with an attr no smaller than the
2367 	 * first published struct, and reject sz values where
2368 	 * sz + sizeof(u32) would overflow size_t (possible on 32-bit)
2369 	 * or nre == UINT32_MAX where nre + 1 wraps to 0 in the calloc.
2370 	 *
2371 	 * The minimum section footprint per event is sz bytes for the
2372 	 * attr plus a u32 for the id count, check that nre events fit.
2373 	 */
2374 	if (!nre || sz < PERF_ATTR_SIZE_VER0 ||
2375 	    sz > ff->size || (size_t)sz > SIZE_MAX - sizeof(u32) ||
2376 	    nre == UINT32_MAX ||
2377 	    nre > (ff->size - ff->offset) / (sz + sizeof(u32))) {
2378 		pr_err("Invalid HEADER_EVENT_DESC: nre=%u sz=%u (min %d)\n",
2379 		       nre, sz, PERF_ATTR_SIZE_VER0);
2380 		goto error;
2381 	}
2382 
2383 	/* buffer to hold on file attr struct */
2384 	buf = malloc(sz);
2385 	if (!buf)
2386 		goto error;
2387 
2388 	/* the last event terminates with evsel->core.attr.size == 0: */
2389 	events = calloc(nre + 1, sizeof(*events));
2390 	if (!events)
2391 		goto error;
2392 
2393 	msz = sizeof(evsel->core.attr);
2394 	if (sz < msz)
2395 		msz = sz;
2396 
2397 	for (i = 0, evsel = events; i < nre; evsel++, i++) {
2398 		struct perf_event_attr *attr = buf;
2399 		u32 attr_size;
2400 
2401 		evsel->core.idx = i;
2402 
2403 		/*
2404 		 * must read entire on-file attr struct to
2405 		 * sync up with layout.
2406 		 */
2407 		if (__do_read(ff, buf, sz))
2408 			goto error;
2409 
2410 		/* Reject before attr_swap to prevent OOB via bswap_safe() */
2411 		attr_size = ff->ph->needs_swap ? bswap_32(attr->size) : attr->size;
2412 		/* ABI0: size == 0 means the producer didn't set it */
2413 		if (!attr_size) {
2414 			attr_size = PERF_ATTR_SIZE_VER0;
2415 			/*
2416 			 * Write back so free_event_desc() doesn't
2417 			 * treat this event as the end-of-array sentinel
2418 			 * (it iterates while attr.size != 0).
2419 			 *
2420 			 * Only for native — the swap path must NOT
2421 			 * write native-endian VER0 here because
2422 			 * perf_event__attr_swap() would re-swap it
2423 			 * to 0x40000000, defeating bswap_safe() bounds.
2424 			 * perf_event__attr_swap() has its own ABI0
2425 			 * fallback that sets VER0 after swapping.
2426 			 */
2427 			if (!ff->ph->needs_swap)
2428 				attr->size = attr_size;
2429 		}
2430 		if (attr_size < PERF_ATTR_SIZE_VER0 || attr_size > sz) {
2431 			pr_err("Event %d attr.size (%u) invalid (min: %d, max: %u)\n",
2432 			       i, attr_size, PERF_ATTR_SIZE_VER0, sz);
2433 			goto error;
2434 		}
2435 
2436 		if (ff->ph->needs_swap)
2437 			perf_event__attr_swap(buf);
2438 
2439 		memcpy(&evsel->core.attr, buf, msz);
2440 
2441 		if (!perf_attr_check(&evsel->core.attr))
2442 			goto error;
2443 
2444 		if (do_read_u32(ff, &nr))
2445 			goto error;
2446 
2447 		if (ff->ph->needs_swap)
2448 			evsel->needs_swap = true;
2449 
2450 		evsel->name = do_read_string(ff);
2451 		if (!evsel->name)
2452 			goto error;
2453 
2454 		if (!nr)
2455 			continue;
2456 
2457 		/* Prevent oversized allocation from crafted nr */
2458 		if (nr > (ff->size - ff->offset) / sizeof(*id)) {
2459 			pr_err("Event %d: id count %u exceeds remaining section\n", i, nr);
2460 			goto error;
2461 		}
2462 
2463 		id = calloc(nr, sizeof(*id));
2464 		if (!id)
2465 			goto error;
2466 		evsel->core.ids = nr;
2467 		evsel->core.id = id;
2468 
2469 		for (j = 0 ; j < nr; j++) {
2470 			if (do_read_u64(ff, id))
2471 				goto error;
2472 			id++;
2473 		}
2474 	}
2475 out:
2476 	free(buf);
2477 	return events;
2478 error:
2479 	free_event_desc(events);
2480 	events = NULL;
2481 	goto out;
2482 }
2483 
2484 static int __desc_attr__fprintf(FILE *fp, const char *name, const char *val,
2485 				void *priv __maybe_unused)
2486 {
2487 	return fprintf(fp, ", %s = %s", name, val);
2488 }
2489 
2490 static void print_event_desc(struct feat_fd *ff, FILE *fp)
2491 {
2492 	struct evsel *evsel, *events;
2493 	u32 j;
2494 	u64 *id;
2495 
2496 	if (ff->events)
2497 		events = ff->events;
2498 	else
2499 		events = read_event_desc(ff);
2500 
2501 	if (!events) {
2502 		fprintf(fp, "# event desc: not available or unable to read\n");
2503 		return;
2504 	}
2505 
2506 	for (evsel = events; evsel->core.attr.size; evsel++) {
2507 		fprintf(fp, "# event : name = %s, ", evsel->name);
2508 
2509 		if (evsel->core.ids) {
2510 			fprintf(fp, ", id = {");
2511 			for (j = 0, id = evsel->core.id; j < evsel->core.ids; j++, id++) {
2512 				if (j)
2513 					fputc(',', fp);
2514 				fprintf(fp, " %"PRIu64, *id);
2515 			}
2516 			fprintf(fp, " }");
2517 		}
2518 
2519 		perf_event_attr__fprintf(fp, &evsel->core.attr, __desc_attr__fprintf, NULL);
2520 
2521 		fputc('\n', fp);
2522 	}
2523 
2524 	free_event_desc(events);
2525 	ff->events = NULL;
2526 }
2527 
2528 static void print_total_mem(struct feat_fd *ff, FILE *fp)
2529 {
2530 	fprintf(fp, "# total memory : %llu kB\n", ff->ph->env.total_mem);
2531 }
2532 
2533 static void print_numa_topology(struct feat_fd *ff, FILE *fp)
2534 {
2535 	int i;
2536 	struct numa_node *n;
2537 
2538 	for (i = 0; i < ff->ph->env.nr_numa_nodes; i++) {
2539 		n = &ff->ph->env.numa_nodes[i];
2540 
2541 		fprintf(fp, "# node%u meminfo  : total = %"PRIu64" kB,"
2542 			    " free = %"PRIu64" kB\n",
2543 			n->node, n->mem_total, n->mem_free);
2544 
2545 		fprintf(fp, "# node%u cpu list : ", n->node);
2546 		cpu_map__fprintf(n->map, fp);
2547 	}
2548 }
2549 
2550 static void print_cpuid(struct feat_fd *ff, FILE *fp)
2551 {
2552 	fprintf(fp, "# cpuid : %s\n", ff->ph->env.cpuid);
2553 }
2554 
2555 static void print_branch_stack(struct feat_fd *ff __maybe_unused, FILE *fp)
2556 {
2557 	fprintf(fp, "# contains samples with branch stack\n");
2558 }
2559 
2560 static void print_auxtrace(struct feat_fd *ff __maybe_unused, FILE *fp)
2561 {
2562 	fprintf(fp, "# contains AUX area data (e.g. instruction trace)\n");
2563 }
2564 
2565 static void print_stat(struct feat_fd *ff __maybe_unused, FILE *fp)
2566 {
2567 	fprintf(fp, "# contains stat data\n");
2568 }
2569 
2570 static void print_cache(struct feat_fd *ff, FILE *fp __maybe_unused)
2571 {
2572 	int i;
2573 
2574 	fprintf(fp, "# CPU cache info:\n");
2575 	for (i = 0; i < ff->ph->env.caches_cnt; i++) {
2576 		fprintf(fp, "#  ");
2577 		cpu_cache_level__fprintf(fp, &ff->ph->env.caches[i]);
2578 	}
2579 }
2580 
2581 static void print_cln_size(struct feat_fd *ff, FILE *fp)
2582 {
2583 	fprintf(fp, "# cacheline size: %u\n", ff->ph->env.cln_size);
2584 }
2585 
2586 static void print_compressed(struct feat_fd *ff, FILE *fp)
2587 {
2588 	fprintf(fp, "# compressed : %s, level = %d, ratio = %d\n",
2589 		ff->ph->env.comp_type == PERF_COMP_ZSTD ? "Zstd" : "Unknown",
2590 		ff->ph->env.comp_level, ff->ph->env.comp_ratio);
2591 }
2592 
2593 static void __print_pmu_caps(FILE *fp, int nr_caps, char **caps, char *pmu_name)
2594 {
2595 	const char *delimiter = "";
2596 	int i;
2597 
2598 	if (!nr_caps) {
2599 		fprintf(fp, "# %s pmu capabilities: not available\n", pmu_name);
2600 		return;
2601 	}
2602 
2603 	fprintf(fp, "# %s pmu capabilities: ", pmu_name);
2604 	for (i = 0; i < nr_caps; i++) {
2605 		fprintf(fp, "%s%s", delimiter, caps[i]);
2606 		delimiter = ", ";
2607 	}
2608 
2609 	fprintf(fp, "\n");
2610 }
2611 
2612 static void print_cpu_pmu_caps(struct feat_fd *ff, FILE *fp)
2613 {
2614 	__print_pmu_caps(fp, ff->ph->env.nr_cpu_pmu_caps,
2615 			 ff->ph->env.cpu_pmu_caps, (char *)"cpu");
2616 }
2617 
2618 static void print_pmu_caps(struct feat_fd *ff, FILE *fp)
2619 {
2620 	struct perf_env *env = &ff->ph->env;
2621 	uint16_t e_machine = perf_env__e_machine(env, /*e_flags=*/NULL);
2622 
2623 	for (int i = 0; i < env->nr_pmus_with_caps; i++) {
2624 		struct pmu_caps *pmu_caps = &env->pmu_caps[i];
2625 
2626 		__print_pmu_caps(fp, pmu_caps->nr_caps, pmu_caps->caps,
2627 				 pmu_caps->pmu_name);
2628 	}
2629 
2630 	if ((e_machine == EM_X86_64 || e_machine == EM_386) &&
2631 	    perf_env__has_pmu_mapping(env, "ibs_op")) {
2632 		char *max_precise = perf_env__find_pmu_cap(env, "cpu", "max_precise");
2633 
2634 		if (max_precise != NULL && atoi(max_precise) == 0)
2635 			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");
2636 	}
2637 }
2638 
2639 static void print_pmu_mappings(struct feat_fd *ff, FILE *fp)
2640 {
2641 	struct perf_env *env = &ff->ph->env;
2642 	const char *delimiter = "# pmu mappings: ";
2643 	char *str, *tmp;
2644 	u32 pmu_num;
2645 	u32 type;
2646 
2647 	pmu_num = env->nr_pmu_mappings;
2648 	if (!pmu_num) {
2649 		fprintf(fp, "# pmu mappings: not available\n");
2650 		return;
2651 	}
2652 
2653 	str = env->pmu_mappings;
2654 
2655 	while (pmu_num) {
2656 		type = strtoul(str, &tmp, 0);
2657 		if (*tmp != ':')
2658 			goto error;
2659 
2660 		str = tmp + 1;
2661 		fprintf(fp, "%s%s = %" PRIu32, delimiter, str, type);
2662 
2663 		delimiter = ", ";
2664 		str += strlen(str) + 1;
2665 		pmu_num--;
2666 	}
2667 
2668 	fprintf(fp, "\n");
2669 
2670 	if (!pmu_num)
2671 		return;
2672 error:
2673 	fprintf(fp, "# pmu mappings: unable to read\n");
2674 }
2675 
2676 static void print_group_desc(struct feat_fd *ff, FILE *fp)
2677 {
2678 	struct perf_session *session;
2679 	struct evsel *evsel;
2680 	u32 nr = 0;
2681 
2682 	session = container_of(ff->ph, struct perf_session, header);
2683 
2684 	evlist__for_each_entry(session->evlist, evsel) {
2685 		if (evsel__is_group_leader(evsel) && evsel->core.nr_members > 1) {
2686 			fprintf(fp, "# group: %s{%s", evsel->group_name ?: "", evsel__name(evsel));
2687 
2688 			nr = evsel->core.nr_members - 1;
2689 		} else if (nr) {
2690 			fprintf(fp, ",%s", evsel__name(evsel));
2691 
2692 			if (--nr == 0)
2693 				fprintf(fp, "}\n");
2694 		}
2695 	}
2696 }
2697 
2698 static void print_sample_time(struct feat_fd *ff, FILE *fp)
2699 {
2700 	struct perf_session *session;
2701 	char time_buf[32];
2702 	double d;
2703 
2704 	session = container_of(ff->ph, struct perf_session, header);
2705 
2706 	timestamp__scnprintf_usec(evlist__first_sample_time(session->evlist),
2707 				  time_buf, sizeof(time_buf));
2708 	fprintf(fp, "# time of first sample : %s\n", time_buf);
2709 
2710 	timestamp__scnprintf_usec(evlist__last_sample_time(session->evlist),
2711 				  time_buf, sizeof(time_buf));
2712 	fprintf(fp, "# time of last sample : %s\n", time_buf);
2713 
2714 	d = (double)(evlist__last_sample_time(session->evlist) -
2715 		evlist__first_sample_time(session->evlist)) / NSEC_PER_MSEC;
2716 
2717 	fprintf(fp, "# sample duration : %10.3f ms\n", d);
2718 }
2719 
2720 static void memory_node__fprintf(struct memory_node *n,
2721 				 unsigned long long bsize, FILE *fp)
2722 {
2723 	char buf_map[100], buf_size[50];
2724 	unsigned long long size;
2725 
2726 	size = bsize * bitmap_weight(n->set, n->size);
2727 	unit_number__scnprintf(buf_size, 50, size);
2728 
2729 	bitmap_scnprintf(n->set, n->size, buf_map, 100);
2730 	fprintf(fp, "#  %3" PRIu64 " [%s]: %s\n", n->node, buf_size, buf_map);
2731 }
2732 
2733 static void print_mem_topology(struct feat_fd *ff, FILE *fp)
2734 {
2735 	struct perf_env *env = &ff->ph->env;
2736 	struct memory_node *nodes;
2737 	int i, nr;
2738 
2739 	nodes = env->memory_nodes;
2740 	nr    = env->nr_memory_nodes;
2741 
2742 	fprintf(fp, "# memory nodes (nr %d, block size 0x%llx):\n",
2743 		nr, env->memory_bsize);
2744 
2745 	for (i = 0; i < nr; i++) {
2746 		memory_node__fprintf(&nodes[i], env->memory_bsize, fp);
2747 	}
2748 }
2749 
2750 static void print_cpu_domain_info(struct feat_fd *ff, FILE *fp)
2751 {
2752 	struct cpu_domain_map **cd_map = ff->ph->env.cpu_domain;
2753 	u32 nr = ff->ph->env.nr_cpus_avail;
2754 	struct domain_info *d_info;
2755 	u32 i, j;
2756 
2757 	fprintf(fp, "# schedstat version	: %u\n", ff->ph->env.schedstat_version);
2758 	fprintf(fp, "# Maximum sched domains	: %u\n", ff->ph->env.max_sched_domains);
2759 
2760 	for (i = 0; i < nr; i++) {
2761 		if (!cd_map[i])
2762 			continue;
2763 
2764 		fprintf(fp, "# cpu		: %u\n", cd_map[i]->cpu);
2765 		fprintf(fp, "# nr_domains	: %u\n", cd_map[i]->nr_domains);
2766 
2767 		for (j = 0; j < cd_map[i]->nr_domains; j++) {
2768 			d_info = cd_map[i]->domains[j];
2769 			if (!d_info)
2770 				continue;
2771 
2772 			fprintf(fp, "# Domain		: %u\n", d_info->domain);
2773 
2774 			if (ff->ph->env.schedstat_version >= 17)
2775 				fprintf(fp, "# Domain name      : %s\n", d_info->dname);
2776 
2777 			fprintf(fp, "# Domain cpu map   : %s\n", d_info->cpumask);
2778 			fprintf(fp, "# Domain cpu list  : %s\n", d_info->cpulist);
2779 		}
2780 	}
2781 }
2782 
2783 static void print_memory_ranges(struct feat_fd *ff, FILE *fp)
2784 {
2785 	struct memory_range *ranges = ff->ph->env.memory_ranges;
2786 	int nr_memory_ranges = ff->ph->env.nr_memory_ranges;
2787 	int i;
2788 
2789 	fprintf(fp, "# memory ranges (nr %d):\n", nr_memory_ranges);
2790 
2791 	for (i = 0; i < nr_memory_ranges; i++) {
2792 		fprintf(fp, "# range%u: [0x%016" PRIx64 "-0x%016" PRIx64,
2793 			i, ranges[i].base, ranges[i].base + ranges[i].length - 1);
2794 		fprintf(fp, "], node = %d, local_region_id = %d, remote_region_id = %d\n",
2795 			ranges[i].node, ranges[i].local_region_id,
2796 			ranges[i].remote_region_id);
2797 	}
2798 }
2799 
2800 static int __event_process_build_id(struct perf_record_header_build_id *bev,
2801 				    char *filename,
2802 				    struct perf_session *session)
2803 {
2804 	int err = -1;
2805 	struct machine *machine;
2806 	u16 cpumode;
2807 	struct dso *dso;
2808 	enum dso_space_type dso_space;
2809 
2810 	machine = perf_session__findnew_machine(session, bev->pid);
2811 	if (!machine)
2812 		goto out;
2813 
2814 	cpumode = bev->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
2815 
2816 	switch (cpumode) {
2817 	case PERF_RECORD_MISC_KERNEL:
2818 		dso_space = DSO_SPACE__KERNEL;
2819 		break;
2820 	case PERF_RECORD_MISC_GUEST_KERNEL:
2821 		dso_space = DSO_SPACE__KERNEL_GUEST;
2822 		break;
2823 	case PERF_RECORD_MISC_USER:
2824 	case PERF_RECORD_MISC_GUEST_USER:
2825 		dso_space = DSO_SPACE__USER;
2826 		break;
2827 	default:
2828 		goto out;
2829 	}
2830 
2831 	dso = machine__findnew_dso(machine, filename);
2832 	if (dso != NULL) {
2833 		char sbuild_id[SBUILD_ID_SIZE];
2834 		struct build_id bid;
2835 		size_t size = BUILD_ID_SIZE;
2836 
2837 		if (bev->header.misc & PERF_RECORD_MISC_BUILD_ID_SIZE)
2838 			size = bev->size;
2839 
2840 		build_id__init(&bid, bev->data, size);
2841 		dso__set_build_id(dso, &bid);
2842 		dso__set_header_build_id(dso, true);
2843 
2844 		if (dso_space != DSO_SPACE__USER) {
2845 			struct kmod_path m = { .name = NULL, };
2846 
2847 			if (!kmod_path__parse_name(&m, filename) && m.kmod)
2848 				dso__set_module_info(dso, &m, machine);
2849 
2850 			dso__set_kernel(dso, dso_space);
2851 			free(m.name);
2852 		}
2853 
2854 		build_id__snprintf(dso__bid(dso), sbuild_id, sizeof(sbuild_id));
2855 		pr_debug("build id event received for %s: %s [%zu]\n",
2856 			 dso__long_name(dso), sbuild_id, size);
2857 		dso__put(dso);
2858 	}
2859 
2860 	err = 0;
2861 out:
2862 	return err;
2863 }
2864 
2865 static int perf_header__read_build_ids_abi_quirk(struct perf_header *header,
2866 						 int input, u64 offset, u64 size)
2867 {
2868 	struct perf_session *session = container_of(header, struct perf_session, header);
2869 	struct {
2870 		struct perf_event_header   header;
2871 		u8			   build_id[PERF_ALIGN(BUILD_ID_SIZE, sizeof(u64))];
2872 		char			   filename[0];
2873 	} old_bev;
2874 	struct perf_record_header_build_id bev;
2875 	char filename[PATH_MAX];
2876 	u64 limit;
2877 
2878 	/* Prevent offset + size from wrapping past ULLONG_MAX */
2879 	if (size > ULLONG_MAX - offset)
2880 		return -1;
2881 
2882 	limit = offset + size;
2883 
2884 	while (offset < limit) {
2885 		ssize_t len;
2886 
2887 		if (readn(input, &old_bev, sizeof(old_bev)) != sizeof(old_bev))
2888 			return -1;
2889 
2890 		if (header->needs_swap)
2891 			perf_event_header__bswap(&old_bev.header);
2892 
2893 		/* size == 0 loops forever; size > remaining reads past section */
2894 		if (old_bev.header.size == 0 || old_bev.header.size > limit - offset)
2895 			return -1;
2896 
2897 		len = old_bev.header.size - sizeof(old_bev);
2898 		if (len < 0 || len >= PATH_MAX) {
2899 			pr_warning("invalid build_id filename length %zd\n", len);
2900 			return -1;
2901 		}
2902 
2903 		if (readn(input, filename, len) != len)
2904 			return -1;
2905 		/*
2906 		 * The file data may lack a null terminator, which could
2907 		 * indicate a corrupt or crafted perf.data file.  Ensure
2908 		 * filename is always a valid C string before passing it
2909 		 * to functions like machine__findnew_dso().
2910 		 */
2911 		filename[len] = '\0';
2912 
2913 		bev.header = old_bev.header;
2914 
2915 		/*
2916 		 * As the pid is the missing value, we need to fill
2917 		 * it properly. The header.misc value give us nice hint.
2918 		 */
2919 		bev.pid	= HOST_KERNEL_ID;
2920 		if (bev.header.misc == PERF_RECORD_MISC_GUEST_USER ||
2921 		    bev.header.misc == PERF_RECORD_MISC_GUEST_KERNEL)
2922 			bev.pid	= DEFAULT_GUEST_KERNEL_ID;
2923 
2924 		memcpy(bev.build_id, old_bev.build_id, sizeof(bev.build_id));
2925 		__event_process_build_id(&bev, filename, session);
2926 
2927 		offset += bev.header.size;
2928 	}
2929 
2930 	return 0;
2931 }
2932 
2933 static int perf_header__read_build_ids(struct perf_header *header,
2934 				       int input, u64 offset, u64 size)
2935 {
2936 	struct perf_session *session = container_of(header, struct perf_session, header);
2937 	struct perf_record_header_build_id bev;
2938 	char filename[PATH_MAX];
2939 	u64 limit, orig_offset = offset;
2940 	int err = -1;
2941 
2942 	/* Prevent offset + size from wrapping past ULLONG_MAX */
2943 	if (size > ULLONG_MAX - offset)
2944 		return -1;
2945 
2946 	limit = offset + size;
2947 
2948 	while (offset < limit) {
2949 		ssize_t len;
2950 
2951 		if (readn(input, &bev, sizeof(bev)) != sizeof(bev))
2952 			goto out;
2953 
2954 		if (header->needs_swap) {
2955 			perf_event_header__bswap(&bev.header);
2956 			bev.pid = bswap_32(bev.pid);
2957 		}
2958 
2959 		/*
2960 		 * size == 0 would loop forever (offset never advances);
2961 		 * size > remaining would read past the section boundary.
2962 		 */
2963 		if (bev.header.size == 0 || bev.header.size > limit - offset)
2964 			goto out;
2965 
2966 		len = bev.header.size - sizeof(bev);
2967 		if (len < 0 || len >= PATH_MAX) {
2968 			pr_warning("invalid build_id filename length %zd\n", len);
2969 			goto out;
2970 		}
2971 
2972 		if (readn(input, filename, len) != len)
2973 			goto out;
2974 		/*
2975 		 * The file data may lack a null terminator, which could
2976 		 * indicate a corrupt or crafted perf.data file.  Ensure
2977 		 * filename is always a valid C string before passing it
2978 		 * to functions like machine__findnew_dso().
2979 		 */
2980 		filename[len] = '\0';
2981 		/*
2982 		 * The a1645ce1 changeset:
2983 		 *
2984 		 * "perf: 'perf kvm' tool for monitoring guest performance from host"
2985 		 *
2986 		 * Added a field to struct perf_record_header_build_id that broke the file
2987 		 * format.
2988 		 *
2989 		 * Since the kernel build-id is the first entry, process the
2990 		 * table using the old format if the well known
2991 		 * '[kernel.kallsyms]' string for the kernel build-id has the
2992 		 * first 4 characters chopped off (where the pid_t sits).
2993 		 */
2994 		/* Guard short filenames against memcmp reading past the buffer */
2995 		if (len >= (ssize_t)sizeof("nel.kallsyms]") - 1 &&
2996 		    memcmp(filename, "nel.kallsyms]", sizeof("nel.kallsyms]") - 1) == 0) {
2997 			if (lseek(input, orig_offset, SEEK_SET) == (off_t)-1)
2998 				return -1;
2999 			return perf_header__read_build_ids_abi_quirk(header, input, offset, size);
3000 		}
3001 
3002 		__event_process_build_id(&bev, filename, session);
3003 
3004 		offset += bev.header.size;
3005 	}
3006 	err = 0;
3007 out:
3008 	return err;
3009 }
3010 
3011 /* Macro for features that simply need to read and store a string. */
3012 #define FEAT_PROCESS_STR_FUN(__feat, __feat_env) \
3013 static int process_##__feat(struct feat_fd *ff, void *data __maybe_unused) \
3014 {\
3015 	free(ff->ph->env.__feat_env);		     \
3016 	ff->ph->env.__feat_env = do_read_string(ff); \
3017 	return ff->ph->env.__feat_env ? 0 : -ENOMEM; \
3018 }
3019 
3020 FEAT_PROCESS_STR_FUN(hostname, hostname);
3021 FEAT_PROCESS_STR_FUN(osrelease, os_release);
3022 FEAT_PROCESS_STR_FUN(version, version);
3023 FEAT_PROCESS_STR_FUN(cpudesc, cpu_desc);
3024 FEAT_PROCESS_STR_FUN(cpuid, cpuid);
3025 
3026 static int process_arch(struct feat_fd *ff, void *data __maybe_unused)
3027 {
3028 	free(ff->ph->env.arch);
3029 	ff->ph->env.arch = do_read_string(ff);
3030 	if (!ff->ph->env.arch)
3031 		return -ENOMEM;
3032 	return 0;
3033 }
3034 
3035 static int process_e_machine(struct feat_fd *ff, void *data __maybe_unused)
3036 {
3037 	int ret;
3038 
3039 	ret = do_read_u32(ff, &ff->ph->env.e_machine);
3040 	if (ret)
3041 		return ret;
3042 
3043 	return do_read_u32(ff, &ff->ph->env.e_flags);
3044 }
3045 
3046 static int process_tracing_data(struct feat_fd *ff __maybe_unused, void *data __maybe_unused)
3047 {
3048 #ifdef HAVE_LIBTRACEEVENT
3049 	ssize_t ret = trace_report(ff->fd, data, false);
3050 
3051 	return ret < 0 ? -1 : 0;
3052 #else
3053 	/* Not an error — the feature is simply unsupported in this build */
3054 	pr_debug("Tracing data present but libtraceevent not available, skipping.\n");
3055 	return 0;
3056 #endif
3057 }
3058 
3059 static int process_build_id(struct feat_fd *ff, void *data __maybe_unused)
3060 {
3061 	/* lseek fails in pipe mode — fall back to ff->offset */
3062 	off_t offset = lseek(ff->fd, 0, SEEK_CUR);
3063 
3064 	if (offset == (off_t)-1)
3065 		offset = ff->offset;
3066 
3067 	if (perf_header__read_build_ids(ff->ph, ff->fd, offset, ff->size))
3068 		pr_debug("Failed to read buildids, continuing...\n");
3069 	return 0;
3070 }
3071 
3072 static int process_nrcpus(struct feat_fd *ff, void *data __maybe_unused)
3073 {
3074 	struct perf_env *env = &ff->ph->env;
3075 	int ret;
3076 	u32 nr_cpus_avail, nr_cpus_online;
3077 
3078 	ret = do_read_u32(ff, &nr_cpus_avail);
3079 	if (ret)
3080 		return ret;
3081 
3082 	ret = do_read_u32(ff, &nr_cpus_online);
3083 	if (ret)
3084 		return ret;
3085 
3086 	/*
3087 	 * Cap at 1M CPUs — generous for any real system but prevents
3088 	 * stack overflow from VLA allocations sized by nr_cpus_avail
3089 	 * (e.g. DECLARE_BITMAP in builtin-c2c.c node_entry()).
3090 	 */
3091 	if (nr_cpus_avail > (1U << 20)) {
3092 		pr_err("Invalid HEADER_NRCPUS: nr_cpus_avail (%u) exceeds maximum (%u)\n",
3093 		       nr_cpus_avail, 1U << 20);
3094 		return -1;
3095 	}
3096 
3097 	if (nr_cpus_online > nr_cpus_avail) {
3098 		pr_err("Invalid HEADER_NRCPUS: nr_cpus_online (%u) > nr_cpus_avail (%u)\n",
3099 		       nr_cpus_online, nr_cpus_avail);
3100 		return -1;
3101 	}
3102 
3103 	env->nr_cpus_avail = (int)nr_cpus_avail;
3104 	env->nr_cpus_online = (int)nr_cpus_online;
3105 	return 0;
3106 }
3107 
3108 static int process_total_mem(struct feat_fd *ff, void *data __maybe_unused)
3109 {
3110 	struct perf_env *env = &ff->ph->env;
3111 	u64 total_mem;
3112 	int ret;
3113 
3114 	ret = do_read_u64(ff, &total_mem);
3115 	if (ret)
3116 		return -1;
3117 	env->total_mem = (unsigned long long)total_mem;
3118 	return 0;
3119 }
3120 
3121 static struct evsel *evlist__find_by_index(struct evlist *evlist, int idx)
3122 {
3123 	struct evsel *evsel;
3124 
3125 	evlist__for_each_entry(evlist, evsel) {
3126 		if (evsel->core.idx == idx)
3127 			return evsel;
3128 	}
3129 
3130 	return NULL;
3131 }
3132 
3133 static void evlist__set_event_name(struct evlist *evlist, struct evsel *event)
3134 {
3135 	struct evsel *evsel;
3136 
3137 	if (!event->name)
3138 		return;
3139 
3140 	evsel = evlist__find_by_index(evlist, event->core.idx);
3141 	if (!evsel)
3142 		return;
3143 
3144 	if (evsel->name)
3145 		return;
3146 
3147 	evsel->name = strdup(event->name);
3148 }
3149 
3150 static int
3151 process_event_desc(struct feat_fd *ff, void *data __maybe_unused)
3152 {
3153 	struct perf_session *session;
3154 	struct evsel *evsel, *events = read_event_desc(ff);
3155 
3156 	if (!events)
3157 		return 0;
3158 
3159 	session = container_of(ff->ph, struct perf_session, header);
3160 
3161 	if (session->data->is_pipe) {
3162 		/* Save events for reading later by print_event_desc,
3163 		 * since they can't be read again in pipe mode. */
3164 		ff->events = events;
3165 	}
3166 
3167 	for (evsel = events; evsel->core.attr.size; evsel++)
3168 		evlist__set_event_name(session->evlist, evsel);
3169 
3170 	if (!session->data->is_pipe)
3171 		free_event_desc(events);
3172 
3173 	return 0;
3174 }
3175 
3176 /*
3177  * Some arbitrary max for the number of command line arguments,
3178  * Wildcards can expand and end up with tons of command line args.
3179  */
3180 #define MAX_CMDLINE_NR 1048576
3181 
3182 static int process_cmdline(struct feat_fd *ff, void *data __maybe_unused)
3183 {
3184 	struct perf_env *env = &ff->ph->env;
3185 	char *str, *cmdline = NULL, **argv = NULL;
3186 	u32 nr, i, len = 0;
3187 
3188 	if (do_read_u32(ff, &nr))
3189 		return -1;
3190 
3191 	if (nr > MAX_CMDLINE_NR)
3192 		return -1;
3193 
3194 	env->nr_cmdline = nr;
3195 
3196 	cmdline = zalloc(ff->size + nr + 1);
3197 	if (!cmdline)
3198 		return -1;
3199 
3200 	argv = calloc(nr + 1, sizeof(char *));
3201 	if (!argv)
3202 		goto error;
3203 
3204 	for (i = 0; i < nr; i++) {
3205 		str = do_read_string(ff);
3206 		if (!str)
3207 			goto error;
3208 
3209 		argv[i] = cmdline + len;
3210 		memcpy(argv[i], str, strlen(str) + 1);
3211 		len += strlen(str) + 1;
3212 		free(str);
3213 	}
3214 	env->cmdline = cmdline;
3215 	env->cmdline_argv = (const char **) argv;
3216 	return 0;
3217 
3218 error:
3219 	free(argv);
3220 	free(cmdline);
3221 	return -1;
3222 }
3223 
3224 static int process_cpu_topology(struct feat_fd *ff, void *data __maybe_unused)
3225 {
3226 	u32 nr, i;
3227 	char *str = NULL;
3228 	struct strbuf sb;
3229 	struct perf_env *env = &ff->ph->env;
3230 	int cpu_nr = env->nr_cpus_avail;
3231 	u64 size = 0;
3232 
3233 	if (cpu_nr == 0) {
3234 		pr_err("Invalid HEADER_CPU_TOPOLOGY: missing HEADER_NRCPUS\n");
3235 		return -1;
3236 	}
3237 
3238 	env->cpu = calloc(cpu_nr, sizeof(*env->cpu));
3239 	if (!env->cpu)
3240 		return -1;
3241 
3242 	if (do_read_u32(ff, &nr))
3243 		goto free_cpu;
3244 
3245 	if (nr > (u32)cpu_nr) {
3246 		pr_err("Invalid HEADER_CPU_TOPOLOGY: nr_sibling_cores (%u) > nr_cpus_avail (%d)\n",
3247 		       nr, cpu_nr);
3248 		goto free_cpu;
3249 	}
3250 
3251 	env->nr_sibling_cores = nr;
3252 	size += sizeof(u32);
3253 	if (strbuf_init(&sb, 128) < 0)
3254 		goto free_cpu;
3255 
3256 	for (i = 0; i < nr; i++) {
3257 		str = do_read_string(ff);
3258 		if (!str)
3259 			goto error;
3260 
3261 		/* include a NULL character at the end */
3262 		if (strbuf_add(&sb, str, strlen(str) + 1) < 0)
3263 			goto error;
3264 		size += string_size(str);
3265 		zfree(&str);
3266 	}
3267 	env->sibling_cores = strbuf_detach(&sb, NULL);
3268 
3269 	if (do_read_u32(ff, &nr))
3270 		goto free_cpu;
3271 
3272 	if (nr > (u32)cpu_nr) {
3273 		pr_err("Invalid HEADER_CPU_TOPOLOGY: nr_sibling_threads (%u) > nr_cpus_avail (%d)\n",
3274 		       nr, cpu_nr);
3275 		goto free_cpu;
3276 	}
3277 
3278 	env->nr_sibling_threads = nr;
3279 	size += sizeof(u32);
3280 
3281 	for (i = 0; i < nr; i++) {
3282 		str = do_read_string(ff);
3283 		if (!str)
3284 			goto error;
3285 
3286 		/* include a NULL character at the end */
3287 		if (strbuf_add(&sb, str, strlen(str) + 1) < 0)
3288 			goto error;
3289 		size += string_size(str);
3290 		zfree(&str);
3291 	}
3292 	env->sibling_threads = strbuf_detach(&sb, NULL);
3293 
3294 	/*
3295 	 * The header may be from old perf,
3296 	 * which doesn't include core id and socket id information.
3297 	 */
3298 	if (ff->size <= size) {
3299 		zfree(&env->cpu);
3300 		return 0;
3301 	}
3302 
3303 	for (i = 0; i < (u32)cpu_nr; i++) {
3304 		if (do_read_u32(ff, &nr))
3305 			goto free_cpu;
3306 
3307 		env->cpu[i].core_id = nr;
3308 		size += sizeof(u32);
3309 
3310 		if (do_read_u32(ff, &nr))
3311 			goto free_cpu;
3312 
3313 		env->cpu[i].socket_id = nr;
3314 		size += sizeof(u32);
3315 	}
3316 
3317 	/*
3318 	 * The header may be from old perf,
3319 	 * which doesn't include die information.
3320 	 */
3321 	if (ff->size <= size)
3322 		return 0;
3323 
3324 	if (do_read_u32(ff, &nr))
3325 		goto free_cpu;
3326 
3327 	if (nr > (u32)cpu_nr) {
3328 		pr_err("Invalid HEADER_CPU_TOPOLOGY: nr_sibling_dies (%u) > nr_cpus_avail (%d)\n",
3329 		       nr, cpu_nr);
3330 		goto free_cpu;
3331 	}
3332 
3333 	env->nr_sibling_dies = nr;
3334 	size += sizeof(u32);
3335 
3336 	for (i = 0; i < nr; i++) {
3337 		str = do_read_string(ff);
3338 		if (!str)
3339 			goto error;
3340 
3341 		/* include a NULL character at the end */
3342 		if (strbuf_add(&sb, str, strlen(str) + 1) < 0)
3343 			goto error;
3344 		size += string_size(str);
3345 		zfree(&str);
3346 	}
3347 	env->sibling_dies = strbuf_detach(&sb, NULL);
3348 
3349 	for (i = 0; i < (u32)cpu_nr; i++) {
3350 		if (do_read_u32(ff, &nr))
3351 			goto free_cpu;
3352 
3353 		env->cpu[i].die_id = nr;
3354 	}
3355 
3356 	return 0;
3357 
3358 error:
3359 	strbuf_release(&sb);
3360 	zfree(&str);
3361 free_cpu:
3362 	zfree(&env->cpu);
3363 	return -1;
3364 }
3365 
3366 static int process_numa_topology(struct feat_fd *ff, void *data __maybe_unused)
3367 {
3368 	struct perf_env *env = &ff->ph->env;
3369 	struct numa_node *nodes, *n;
3370 	u32 nr, i;
3371 	char *str;
3372 
3373 	/* nr nodes */
3374 	if (do_read_u32(ff, &nr))
3375 		return -1;
3376 
3377 	if (nr > MAX_NUMA_NODES) {
3378 		pr_err("Invalid HEADER_NUMA_TOPOLOGY: nr_nodes (%u) > %u\n",
3379 		       nr, MAX_NUMA_NODES);
3380 		return -1;
3381 	}
3382 
3383 	if (ff->size < sizeof(u32) + nr * (sizeof(u32) + 2 * sizeof(u64))) {
3384 		pr_err("Invalid HEADER_NUMA_TOPOLOGY: section too small (%zu) for %u nodes\n",
3385 		       ff->size, nr);
3386 		return -1;
3387 	}
3388 
3389 	nodes = calloc(nr, sizeof(*nodes));
3390 	if (!nodes)
3391 		return -ENOMEM;
3392 
3393 	for (i = 0; i < nr; i++) {
3394 		n = &nodes[i];
3395 
3396 		/* node number */
3397 		if (do_read_u32(ff, &n->node))
3398 			goto error;
3399 
3400 		if (do_read_u64(ff, &n->mem_total))
3401 			goto error;
3402 
3403 		if (do_read_u64(ff, &n->mem_free))
3404 			goto error;
3405 
3406 		str = do_read_string(ff);
3407 		if (!str)
3408 			goto error;
3409 
3410 		n->map = perf_cpu_map__new(str);
3411 		free(str);
3412 		if (!n->map)
3413 			goto error;
3414 	}
3415 	env->nr_numa_nodes = nr;
3416 	env->numa_nodes = nodes;
3417 	return 0;
3418 
3419 error:
3420 	free(nodes);
3421 	return -1;
3422 }
3423 
3424 static int process_pmu_mappings(struct feat_fd *ff, void *data __maybe_unused)
3425 {
3426 	struct perf_env *env = &ff->ph->env;
3427 	char *name;
3428 	u32 pmu_num;
3429 	u32 type;
3430 	struct strbuf sb;
3431 
3432 	if (do_read_u32(ff, &pmu_num))
3433 		return -1;
3434 
3435 	if (!pmu_num) {
3436 		pr_debug("pmu mappings not available\n");
3437 		return 0;
3438 	}
3439 
3440 	if (pmu_num > MAX_PMU_MAPPINGS) {
3441 		pr_err("Invalid HEADER_PMU_MAPPINGS: pmu_num (%u) > %u\n",
3442 		       pmu_num, MAX_PMU_MAPPINGS);
3443 		return -1;
3444 	}
3445 
3446 	if (ff->size < sizeof(u32) + pmu_num * 2 * sizeof(u32)) {
3447 		pr_err("Invalid HEADER_PMU_MAPPINGS: section too small (%zu) for %u PMUs\n",
3448 		       ff->size, pmu_num);
3449 		return -1;
3450 	}
3451 
3452 	env->nr_pmu_mappings = pmu_num;
3453 	if (strbuf_init(&sb, 128) < 0)
3454 		return -1;
3455 
3456 	while (pmu_num) {
3457 		if (do_read_u32(ff, &type))
3458 			goto error;
3459 
3460 		name = do_read_string(ff);
3461 		if (!name)
3462 			goto error;
3463 
3464 		if (strbuf_addf(&sb, "%u:%s", type, name) < 0)
3465 			goto error;
3466 		/* include a NULL character at the end */
3467 		if (strbuf_add(&sb, "", 1) < 0)
3468 			goto error;
3469 
3470 		if (!strcmp(name, "msr"))
3471 			env->msr_pmu_type = type;
3472 
3473 		free(name);
3474 		pmu_num--;
3475 	}
3476 	/* AMD may set it by evlist__has_amd_ibs() from perf_session__new() */
3477 	free(env->pmu_mappings);
3478 	env->pmu_mappings = strbuf_detach(&sb, NULL);
3479 	return 0;
3480 
3481 error:
3482 	strbuf_release(&sb);
3483 	return -1;
3484 }
3485 
3486 static int process_group_desc(struct feat_fd *ff, void *data __maybe_unused)
3487 {
3488 	struct perf_env *env = &ff->ph->env;
3489 	size_t ret = -1;
3490 	u32 i, nr, nr_groups;
3491 	struct perf_session *session;
3492 	struct evsel *evsel, *leader = NULL;
3493 	struct group_desc {
3494 		char *name;
3495 		u32 leader_idx;
3496 		u32 nr_members;
3497 	} *desc;
3498 
3499 	if (do_read_u32(ff, &nr_groups))
3500 		return -1;
3501 
3502 	if (!nr_groups) {
3503 		pr_debug("group desc not available\n");
3504 		return 0;
3505 	}
3506 
3507 	if (nr_groups > MAX_GROUP_DESC) {
3508 		pr_err("Invalid HEADER_GROUP_DESC: nr_groups (%u) > %u\n",
3509 		       nr_groups, MAX_GROUP_DESC);
3510 		return -1;
3511 	}
3512 
3513 	if (ff->size < sizeof(u32) + nr_groups * 3 * sizeof(u32)) {
3514 		pr_err("Invalid HEADER_GROUP_DESC: section too small (%zu) for %u groups\n",
3515 		       ff->size, nr_groups);
3516 		return -1;
3517 	}
3518 
3519 	env->nr_groups = nr_groups;
3520 
3521 	desc = calloc(nr_groups, sizeof(*desc));
3522 	if (!desc)
3523 		return -1;
3524 
3525 	for (i = 0; i < nr_groups; i++) {
3526 		desc[i].name = do_read_string(ff);
3527 		if (!desc[i].name)
3528 			goto out_free;
3529 
3530 		if (do_read_u32(ff, &desc[i].leader_idx))
3531 			goto out_free;
3532 
3533 		if (do_read_u32(ff, &desc[i].nr_members))
3534 			goto out_free;
3535 	}
3536 
3537 	/*
3538 	 * Rebuild group relationship based on the group_desc
3539 	 */
3540 	session = container_of(ff->ph, struct perf_session, header);
3541 
3542 	i = nr = 0;
3543 	evlist__for_each_entry(session->evlist, evsel) {
3544 		if (i < nr_groups && evsel->core.idx == (int) desc[i].leader_idx) {
3545 			evsel__set_leader(evsel, evsel);
3546 			/* {anon_group} is a dummy name */
3547 			if (strcmp(desc[i].name, "{anon_group}")) {
3548 				evsel->group_name = desc[i].name;
3549 				desc[i].name = NULL;
3550 			}
3551 			evsel->core.nr_members = desc[i].nr_members;
3552 
3553 			if (i >= nr_groups || nr > 0) {
3554 				pr_debug("invalid group desc\n");
3555 				goto out_free;
3556 			}
3557 
3558 			leader = evsel;
3559 			nr = evsel->core.nr_members - 1;
3560 			i++;
3561 		} else if (nr) {
3562 			/* This is a group member */
3563 			evsel__set_leader(evsel, leader);
3564 
3565 			nr--;
3566 		}
3567 	}
3568 
3569 	if (i != nr_groups || nr != 0) {
3570 		pr_debug("invalid group desc\n");
3571 		goto out_free;
3572 	}
3573 
3574 	ret = 0;
3575 out_free:
3576 	for (i = 0; i < nr_groups; i++)
3577 		zfree(&desc[i].name);
3578 	free(desc);
3579 
3580 	return ret;
3581 }
3582 
3583 static int process_auxtrace(struct feat_fd *ff, void *data __maybe_unused)
3584 {
3585 	struct perf_session *session;
3586 	int err;
3587 
3588 	session = container_of(ff->ph, struct perf_session, header);
3589 
3590 	err = auxtrace_index__process(ff->fd, ff->size, session,
3591 				      ff->ph->needs_swap);
3592 	if (err < 0)
3593 		pr_err("Failed to process auxtrace index\n");
3594 	return err;
3595 }
3596 
3597 static int process_cache(struct feat_fd *ff, void *data __maybe_unused)
3598 {
3599 	struct perf_env *env = &ff->ph->env;
3600 	struct cpu_cache_level *caches;
3601 	u32 cnt, i, version;
3602 
3603 	if (do_read_u32(ff, &version))
3604 		return -1;
3605 
3606 	if (version != 1)
3607 		return -1;
3608 
3609 	if (do_read_u32(ff, &cnt))
3610 		return -1;
3611 
3612 	if (cnt > MAX_CACHE_ENTRIES) {
3613 		pr_err("Invalid HEADER_CACHE: cnt (%u) > %u\n",
3614 		       cnt, MAX_CACHE_ENTRIES);
3615 		return -1;
3616 	}
3617 
3618 	if (ff->size < 2 * sizeof(u32) + cnt * 7 * sizeof(u32)) {
3619 		pr_err("Invalid HEADER_CACHE: section too small (%zu) for %u entries\n",
3620 		       ff->size, cnt);
3621 		return -1;
3622 	}
3623 
3624 	caches = calloc(cnt, sizeof(*caches));
3625 	if (!caches)
3626 		return -1;
3627 
3628 	for (i = 0; i < cnt; i++) {
3629 		struct cpu_cache_level *c = &caches[i];
3630 
3631 		#define _R(v)						\
3632 			if (do_read_u32(ff, &c->v))			\
3633 				goto out_free_caches;			\
3634 
3635 		_R(level)
3636 		_R(line_size)
3637 		_R(sets)
3638 		_R(ways)
3639 		#undef _R
3640 
3641 		#define _R(v)					\
3642 			c->v = do_read_string(ff);		\
3643 			if (!c->v)				\
3644 				goto out_free_caches;		\
3645 
3646 		_R(type)
3647 		_R(size)
3648 		_R(map)
3649 		#undef _R
3650 	}
3651 
3652 	env->caches = caches;
3653 	env->caches_cnt = cnt;
3654 	return 0;
3655 out_free_caches:
3656 	for (i = 0; i < cnt; i++) {
3657 		free(caches[i].type);
3658 		free(caches[i].size);
3659 		free(caches[i].map);
3660 	}
3661 	free(caches);
3662 	return -1;
3663 }
3664 
3665 static int process_cln_size(struct feat_fd *ff, void *data __maybe_unused)
3666 {
3667 	struct perf_env *env = &ff->ph->env;
3668 
3669 	if (do_read_u32(ff, &env->cln_size))
3670 		return -1;
3671 
3672 	return 0;
3673 }
3674 
3675 static int process_sample_time(struct feat_fd *ff, void *data __maybe_unused)
3676 {
3677 	struct perf_session *session;
3678 	u64 first_sample_time, last_sample_time;
3679 	int ret;
3680 
3681 	session = container_of(ff->ph, struct perf_session, header);
3682 
3683 	ret = do_read_u64(ff, &first_sample_time);
3684 	if (ret)
3685 		return -1;
3686 
3687 	ret = do_read_u64(ff, &last_sample_time);
3688 	if (ret)
3689 		return -1;
3690 
3691 	evlist__set_first_sample_time(session->evlist, first_sample_time);
3692 	evlist__set_last_sample_time(session->evlist, last_sample_time);
3693 	return 0;
3694 }
3695 
3696 static int process_mem_topology(struct feat_fd *ff,
3697 				void *data __maybe_unused)
3698 {
3699 	struct perf_env *env = &ff->ph->env;
3700 	struct memory_node *nodes;
3701 	u64 version, i, nr, bsize;
3702 	int ret = -1;
3703 
3704 	if (do_read_u64(ff, &version))
3705 		return -1;
3706 
3707 	if (version != 1)
3708 		return -1;
3709 
3710 	if (do_read_u64(ff, &bsize))
3711 		return -1;
3712 
3713 	if (do_read_u64(ff, &nr))
3714 		return -1;
3715 
3716 	if (nr > MAX_NUMA_NODES) {
3717 		pr_err("Invalid HEADER_MEM_TOPOLOGY: nr_nodes (%llu) > %u\n",
3718 		       (unsigned long long)nr, MAX_NUMA_NODES);
3719 		return -1;
3720 	}
3721 
3722 	/* Per node: node_id(u64) + mem_size(u64) + bitmap_nr_bits(u64) */
3723 	if (ff->size < 3 * sizeof(u64) + nr * 3 * sizeof(u64)) {
3724 		pr_err("Invalid HEADER_MEM_TOPOLOGY: section too small (%zu) for %llu nodes\n",
3725 		       ff->size, (unsigned long long)nr);
3726 		return -1;
3727 	}
3728 
3729 	nodes = calloc(nr, sizeof(*nodes));
3730 	if (!nodes)
3731 		return -1;
3732 
3733 	for (i = 0; i < nr; i++) {
3734 		struct memory_node n;
3735 
3736 		#define _R(v)				\
3737 			if (do_read_u64(ff, &n.v))	\
3738 				goto out;		\
3739 
3740 		_R(node)
3741 		_R(size)
3742 
3743 		#undef _R
3744 
3745 		if (do_read_bitmap(ff, &n.set, &n.size))
3746 			goto out;
3747 
3748 		nodes[i] = n;
3749 	}
3750 
3751 	env->memory_bsize    = bsize;
3752 	env->memory_nodes    = nodes;
3753 	env->nr_memory_nodes = nr;
3754 	ret = 0;
3755 
3756 out:
3757 	if (ret)
3758 		memory_node__delete_nodes(nodes, nr);
3759 	return ret;
3760 }
3761 
3762 static int process_clockid(struct feat_fd *ff,
3763 			   void *data __maybe_unused)
3764 {
3765 	struct perf_env *env = &ff->ph->env;
3766 
3767 	if (do_read_u64(ff, &env->clock.clockid_res_ns))
3768 		return -1;
3769 
3770 	return 0;
3771 }
3772 
3773 static int process_clock_data(struct feat_fd *ff,
3774 			      void *_data __maybe_unused)
3775 {
3776 	struct perf_env *env = &ff->ph->env;
3777 	u32 data32;
3778 	u64 data64;
3779 
3780 	/* version */
3781 	if (do_read_u32(ff, &data32))
3782 		return -1;
3783 
3784 	if (data32 != 1)
3785 		return -1;
3786 
3787 	/* clockid */
3788 	if (do_read_u32(ff, &data32))
3789 		return -1;
3790 
3791 	env->clock.clockid = data32;
3792 
3793 	/* TOD ref time */
3794 	if (do_read_u64(ff, &data64))
3795 		return -1;
3796 
3797 	env->clock.tod_ns = data64;
3798 
3799 	/* clockid ref time */
3800 	if (do_read_u64(ff, &data64))
3801 		return -1;
3802 
3803 	env->clock.clockid_ns = data64;
3804 	env->clock.enabled = true;
3805 	return 0;
3806 }
3807 
3808 static int process_hybrid_topology(struct feat_fd *ff,
3809 				   void *data __maybe_unused)
3810 {
3811 	struct perf_env *env = &ff->ph->env;
3812 	struct hybrid_node *nodes, *n;
3813 	u32 nr, i;
3814 
3815 	/* nr nodes */
3816 	if (do_read_u32(ff, &nr))
3817 		return -1;
3818 
3819 	if (nr > MAX_PMU_MAPPINGS) {
3820 		pr_err("Invalid HEADER_HYBRID_TOPOLOGY: nr_nodes (%u) > %u\n",
3821 		       nr, MAX_PMU_MAPPINGS);
3822 		return -1;
3823 	}
3824 
3825 	if (ff->size < sizeof(u32) + nr * 2 * sizeof(u32)) {
3826 		pr_err("Invalid HEADER_HYBRID_TOPOLOGY: section too small (%zu) for %u nodes\n",
3827 		       ff->size, nr);
3828 		return -1;
3829 	}
3830 
3831 	nodes = calloc(nr, sizeof(*nodes));
3832 	if (!nodes)
3833 		return -ENOMEM;
3834 
3835 	for (i = 0; i < nr; i++) {
3836 		n = &nodes[i];
3837 
3838 		n->pmu_name = do_read_string(ff);
3839 		if (!n->pmu_name)
3840 			goto error;
3841 
3842 		n->cpus = do_read_string(ff);
3843 		if (!n->cpus)
3844 			goto error;
3845 	}
3846 
3847 	env->nr_hybrid_nodes = nr;
3848 	env->hybrid_nodes = nodes;
3849 	return 0;
3850 
3851 error:
3852 	for (i = 0; i < nr; i++) {
3853 		free(nodes[i].pmu_name);
3854 		free(nodes[i].cpus);
3855 	}
3856 
3857 	free(nodes);
3858 	return -1;
3859 }
3860 
3861 static int process_dir_format(struct feat_fd *ff,
3862 			      void *_data __maybe_unused)
3863 {
3864 	struct perf_session *session;
3865 	struct perf_data *data;
3866 
3867 	session = container_of(ff->ph, struct perf_session, header);
3868 	data = session->data;
3869 
3870 	if (!perf_data__is_dir(data)) {
3871 		pr_warning("Expected data to be a directory\n");
3872 		return -1;
3873 	}
3874 	return do_read_u64(ff, &data->dir.version);
3875 }
3876 
3877 static int process_bpf_prog_info(struct feat_fd *ff __maybe_unused, void *data __maybe_unused)
3878 {
3879 #ifdef HAVE_LIBBPF_SUPPORT
3880 	struct bpf_prog_info_node *info_node;
3881 	struct perf_env *env = &ff->ph->env;
3882 	struct perf_bpil *info_linear;
3883 	u32 count, i;
3884 	int err = -1;
3885 
3886 	if (ff->ph->needs_swap) {
3887 		pr_warning("interpreting bpf_prog_info from systems with endianness is not yet supported\n");
3888 		return 0;
3889 	}
3890 
3891 	if (do_read_u32(ff, &count))
3892 		return -1;
3893 
3894 	if (count > MAX_BPF_PROGS) {
3895 		pr_err("Invalid HEADER_BPF_PROG_INFO: count (%u) > %u\n",
3896 		       count, MAX_BPF_PROGS);
3897 		return -1;
3898 	}
3899 
3900 	if (ff->size < sizeof(u32) + count * (2 * sizeof(u32) + sizeof(u64))) {
3901 		pr_err("Invalid HEADER_BPF_PROG_INFO: section too small (%zu) for %u entries\n",
3902 		       ff->size, count);
3903 		return -1;
3904 	}
3905 
3906 	down_write(&env->bpf_progs.lock);
3907 
3908 	for (i = 0; i < count; ++i) {
3909 		u32 info_len, data_len;
3910 
3911 		info_linear = NULL;
3912 		info_node = NULL;
3913 		if (do_read_u32(ff, &info_len))
3914 			goto out;
3915 		if (do_read_u32(ff, &data_len))
3916 			goto out;
3917 
3918 		if (info_len > sizeof(struct bpf_prog_info)) {
3919 			pr_warning("detected invalid bpf_prog_info\n");
3920 			goto out;
3921 		}
3922 
3923 		if (data_len > MAX_BPF_DATA_LEN) {
3924 			pr_warning("Invalid HEADER_BPF_PROG_INFO: data_len (%u) too large\n",
3925 				   data_len);
3926 			goto out;
3927 		}
3928 
3929 		info_linear = malloc(sizeof(struct perf_bpil) +
3930 				     data_len);
3931 		if (!info_linear)
3932 			goto out;
3933 		info_linear->info_len = sizeof(struct bpf_prog_info);
3934 		info_linear->data_len = data_len;
3935 		if (do_read_u64(ff, (u64 *)(&info_linear->arrays)))
3936 			goto out;
3937 		if (__do_read(ff, &info_linear->info, info_len))
3938 			goto out;
3939 		if (info_len < sizeof(struct bpf_prog_info))
3940 			memset(((void *)(&info_linear->info)) + info_len, 0,
3941 			       sizeof(struct bpf_prog_info) - info_len);
3942 
3943 		if (__do_read(ff, info_linear->data, data_len))
3944 			goto out;
3945 
3946 		info_node = malloc(sizeof(struct bpf_prog_info_node));
3947 		if (!info_node)
3948 			goto out;
3949 
3950 		/* after reading from file, translate offset to address */
3951 		bpil_offs_to_addr(info_linear);
3952 		info_node->info_linear = info_linear;
3953 		info_node->metadata = NULL;
3954 		if (!__perf_env__insert_bpf_prog_info(env, info_node)) {
3955 			free(info_linear);
3956 			free(info_node);
3957 		}
3958 	}
3959 
3960 	up_write(&env->bpf_progs.lock);
3961 	return 0;
3962 out:
3963 	free(info_linear);
3964 	free(info_node);
3965 	up_write(&env->bpf_progs.lock);
3966 	return err;
3967 #else
3968 	/* Not an error — the feature is simply unsupported in this build */
3969 	pr_debug("BPF prog info present but libbpf not available, skipping.\n");
3970 	return 0;
3971 #endif // HAVE_LIBBPF_SUPPORT
3972 }
3973 
3974 static int process_bpf_btf(struct feat_fd *ff  __maybe_unused, void *data __maybe_unused)
3975 {
3976 #ifdef HAVE_LIBBPF_SUPPORT
3977 	struct perf_env *env = &ff->ph->env;
3978 	struct btf_node *node = NULL;
3979 	u32 count, i;
3980 	int err = -1;
3981 
3982 	if (ff->ph->needs_swap) {
3983 		pr_warning("interpreting btf from systems with endianness is not yet supported\n");
3984 		return 0;
3985 	}
3986 
3987 	if (do_read_u32(ff, &count))
3988 		return -1;
3989 
3990 	if (count > MAX_BPF_PROGS) {
3991 		pr_err("bpf btf count %u too large (max %u)\n", count, MAX_BPF_PROGS);
3992 		return -1;
3993 	}
3994 
3995 	if (ff->size < sizeof(u32) + count * 2 * sizeof(u32)) {
3996 		pr_err("Invalid HEADER_BPF_BTF: section too small (%zu) for %u entries\n",
3997 		       ff->size, count);
3998 		return -1;
3999 	}
4000 
4001 	down_write(&env->bpf_progs.lock);
4002 
4003 	for (i = 0; i < count; ++i) {
4004 		u32 id, data_size;
4005 
4006 		if (do_read_u32(ff, &id))
4007 			goto out;
4008 		if (do_read_u32(ff, &data_size))
4009 			goto out;
4010 
4011 		if (data_size > MAX_BPF_DATA_LEN) {
4012 			pr_err("bpf btf data size %u too large (max %u)\n",
4013 			       data_size, MAX_BPF_DATA_LEN);
4014 			goto out;
4015 		}
4016 
4017 		node = malloc(sizeof(struct btf_node) + data_size);
4018 		if (!node)
4019 			goto out;
4020 
4021 		node->id = id;
4022 		node->data_size = data_size;
4023 
4024 		if (__do_read(ff, node->data, data_size))
4025 			goto out;
4026 
4027 		if (!__perf_env__insert_btf(env, node))
4028 			free(node);
4029 		node = NULL;
4030 	}
4031 
4032 	err = 0;
4033 out:
4034 	up_write(&env->bpf_progs.lock);
4035 	free(node);
4036 	return err;
4037 #else
4038 	/* Not an error — the feature is simply unsupported in this build */
4039 	pr_debug("BTF data present but libbpf not available, skipping.\n");
4040 	return 0;
4041 #endif // HAVE_LIBBPF_SUPPORT
4042 }
4043 
4044 static int process_compressed(struct feat_fd *ff,
4045 			      void *data __maybe_unused)
4046 {
4047 	struct perf_env *env = &ff->ph->env;
4048 
4049 	if (do_read_u32(ff, &(env->comp_ver)))
4050 		return -1;
4051 
4052 	if (do_read_u32(ff, &(env->comp_type)))
4053 		return -1;
4054 
4055 	if (do_read_u32(ff, &(env->comp_level)))
4056 		return -1;
4057 
4058 	if (do_read_u32(ff, &(env->comp_ratio)))
4059 		return -1;
4060 
4061 	if (do_read_u32(ff, &(env->comp_mmap_len)))
4062 		return -1;
4063 
4064 	/*
4065 	 * FIXME: perf.data should record the recording system's page
4066 	 * size — it affects mmap buffer alignment, sample addresses,
4067 	 * and data_page_size/code_page_size interpretation.  Without
4068 	 * it we assume 4K (the smallest Linux page size) as a safe
4069 	 * minimum alignment for comp_mmap_len validation.
4070 	 *
4071 	 * No upper-bound cap: perf_session__process_compressed_event()
4072 	 * checks decomp_len + sizeof(struct decomp) against SIZE_MAX
4073 	 * before allocating, which handles 32-bit safety.
4074 	 */
4075 	if (env->comp_mmap_len &&
4076 	    (env->comp_mmap_len < 4096 || env->comp_mmap_len % 4096)) {
4077 		pr_err("Invalid HEADER_COMPRESSED: comp_mmap_len (%u) must be a 4K-aligned value >= 4096\n",
4078 		       env->comp_mmap_len);
4079 		return -1;
4080 	}
4081 
4082 	return 0;
4083 }
4084 
4085 static int __process_pmu_caps(struct feat_fd *ff, int *nr_caps,
4086 			      char ***caps, unsigned int *max_branches,
4087 			      unsigned int *br_cntr_nr,
4088 			      unsigned int *br_cntr_width)
4089 {
4090 	char *name, *value, *ptr;
4091 	u32 nr_pmu_caps, i;
4092 
4093 	*nr_caps = 0;
4094 	*caps = NULL;
4095 
4096 	if (do_read_u32(ff, &nr_pmu_caps))
4097 		return -1;
4098 
4099 	if (!nr_pmu_caps)
4100 		return 0;
4101 
4102 	if (nr_pmu_caps > MAX_PMU_CAPS) {
4103 		pr_err("Invalid pmu caps: nr_pmu_caps (%u) > %u\n",
4104 		       nr_pmu_caps, MAX_PMU_CAPS);
4105 		return -1;
4106 	}
4107 
4108 	*caps = calloc(nr_pmu_caps, sizeof(char *));
4109 	if (!*caps)
4110 		return -1;
4111 
4112 	for (i = 0; i < nr_pmu_caps; i++) {
4113 		name = do_read_string(ff);
4114 		if (!name)
4115 			goto error;
4116 
4117 		value = do_read_string(ff);
4118 		if (!value)
4119 			goto free_name;
4120 
4121 		if (asprintf(&ptr, "%s=%s", name, value) < 0)
4122 			goto free_value;
4123 
4124 		(*caps)[i] = ptr;
4125 
4126 		if (!strcmp(name, "branches"))
4127 			*max_branches = atoi(value);
4128 
4129 		if (!strcmp(name, "branch_counter_nr"))
4130 			*br_cntr_nr = atoi(value);
4131 
4132 		if (!strcmp(name, "branch_counter_width"))
4133 			*br_cntr_width = atoi(value);
4134 
4135 		free(value);
4136 		free(name);
4137 	}
4138 	*nr_caps = nr_pmu_caps;
4139 	return 0;
4140 
4141 free_value:
4142 	free(value);
4143 free_name:
4144 	free(name);
4145 error:
4146 	for (; i > 0; i--)
4147 		free((*caps)[i - 1]);
4148 	free(*caps);
4149 	*caps = NULL;
4150 	*nr_caps = 0;
4151 	return -1;
4152 }
4153 
4154 static int process_cpu_pmu_caps(struct feat_fd *ff,
4155 				void *data __maybe_unused)
4156 {
4157 	struct perf_env *env = &ff->ph->env;
4158 	int ret = __process_pmu_caps(ff, &env->nr_cpu_pmu_caps,
4159 				     &env->cpu_pmu_caps,
4160 				     &env->max_branches,
4161 				     &env->br_cntr_nr,
4162 				     &env->br_cntr_width);
4163 
4164 	if (!ret && !env->cpu_pmu_caps)
4165 		pr_debug("cpu pmu capabilities not available\n");
4166 	return ret;
4167 }
4168 
4169 static int process_pmu_caps(struct feat_fd *ff, void *data __maybe_unused)
4170 {
4171 	struct perf_env *env = &ff->ph->env;
4172 	struct pmu_caps *pmu_caps;
4173 	u32 nr_pmu, i;
4174 	int ret;
4175 	int j;
4176 
4177 	if (do_read_u32(ff, &nr_pmu))
4178 		return -1;
4179 
4180 	if (!nr_pmu) {
4181 		pr_debug("pmu capabilities not available\n");
4182 		return 0;
4183 	}
4184 
4185 	if (nr_pmu > MAX_PMU_MAPPINGS) {
4186 		pr_err("Invalid HEADER_PMU_CAPS: nr_pmu (%u) > %u\n",
4187 		       nr_pmu, MAX_PMU_MAPPINGS);
4188 		return -1;
4189 	}
4190 
4191 	if (ff->size < sizeof(u32) + nr_pmu * sizeof(u32)) {
4192 		pr_err("Invalid HEADER_PMU_CAPS: section too small (%zu) for %u PMUs\n",
4193 		       ff->size, nr_pmu);
4194 		return -1;
4195 	}
4196 
4197 	pmu_caps = calloc(nr_pmu, sizeof(*pmu_caps));
4198 	if (!pmu_caps)
4199 		return -ENOMEM;
4200 
4201 	for (i = 0; i < nr_pmu; i++) {
4202 		ret = __process_pmu_caps(ff, &pmu_caps[i].nr_caps,
4203 					 &pmu_caps[i].caps,
4204 					 &pmu_caps[i].max_branches,
4205 					 &pmu_caps[i].br_cntr_nr,
4206 					 &pmu_caps[i].br_cntr_width);
4207 		if (ret)
4208 			goto err;
4209 
4210 		pmu_caps[i].pmu_name = do_read_string(ff);
4211 		if (!pmu_caps[i].pmu_name) {
4212 			ret = -1;
4213 			goto err;
4214 		}
4215 		if (!pmu_caps[i].nr_caps) {
4216 			pr_debug("%s pmu capabilities not available\n",
4217 				 pmu_caps[i].pmu_name);
4218 		}
4219 	}
4220 
4221 	env->nr_pmus_with_caps = nr_pmu;
4222 	env->pmu_caps = pmu_caps;
4223 	return 0;
4224 
4225 err:
4226 	for (i = 0; i < nr_pmu; i++) {
4227 		for (j = 0; j < pmu_caps[i].nr_caps; j++)
4228 			free(pmu_caps[i].caps[j]);
4229 		free(pmu_caps[i].caps);
4230 		free(pmu_caps[i].pmu_name);
4231 	}
4232 
4233 	free(pmu_caps);
4234 	return ret;
4235 }
4236 
4237 static int process_cpu_domain_info(struct feat_fd *ff, void *data __maybe_unused)
4238 {
4239 	u32 schedstat_version, max_sched_domains, cpu, domain, nr_domains;
4240 	struct perf_env *env = &ff->ph->env;
4241 	char *dname, *cpumask, *cpulist;
4242 	struct cpu_domain_map **cd_map;
4243 	struct domain_info *d_info;
4244 	u32 nra, nr, i, j;
4245 	int ret;
4246 
4247 	nra = env->nr_cpus_avail;
4248 	nr = env->nr_cpus_online;
4249 
4250 	if (nra == 0 || nr == 0) {
4251 		pr_err("Invalid HEADER_CPU_DOMAIN_INFO: missing HEADER_NRCPUS\n");
4252 		return -1;
4253 	}
4254 
4255 	if (ff->size < 2 * sizeof(u32) + nr * 2 * sizeof(u32)) {
4256 		pr_err("Invalid HEADER_CPU_DOMAIN_INFO: section too small (%zu) for %u CPUs\n",
4257 		       (size_t)ff->size, nr);
4258 		return -1;
4259 	}
4260 
4261 	cd_map = calloc(nra, sizeof(*cd_map));
4262 	if (!cd_map)
4263 		return -1;
4264 
4265 	env->cpu_domain = cd_map;
4266 
4267 	ret = do_read_u32(ff, &schedstat_version);
4268 	if (ret)
4269 		return ret;
4270 
4271 	env->schedstat_version = schedstat_version;
4272 
4273 	ret = do_read_u32(ff, &max_sched_domains);
4274 	if (ret)
4275 		return ret;
4276 
4277 	/*
4278 	 * Sanity check: real systems have at most ~10 sched domain levels
4279 	 * (SMT, CLS, MC, PKG + NUMA hops). Reject obviously bogus values
4280 	 * from malformed perf.data files before they cause excessive
4281 	 * allocation in the per-CPU loop.
4282 	 */
4283 	if (max_sched_domains > MAX_SCHED_DOMAINS) {
4284 		pr_err("Invalid HEADER_CPU_DOMAIN_INFO: max_sched_domains %u > %u\n",
4285 		       max_sched_domains, MAX_SCHED_DOMAINS);
4286 		return -1;
4287 	}
4288 
4289 	env->max_sched_domains = max_sched_domains;
4290 
4291 	for (i = 0; i < nr; i++) {
4292 		if (do_read_u32(ff, &cpu))
4293 			return -1;
4294 
4295 		if (cpu >= nra) {
4296 			pr_err("Invalid HEADER_CPU_DOMAIN_INFO: cpu %d >= nr_cpus_avail (%d)\n", cpu, nra);
4297 			return -1;
4298 		}
4299 
4300 		if (cd_map[cpu]) {
4301 			pr_err("Invalid HEADER_CPU_DOMAIN_INFO: duplicate cpu %u\n", cpu);
4302 			return -1;
4303 		}
4304 
4305 		cd_map[cpu] = zalloc(sizeof(*cd_map[cpu]));
4306 		if (!cd_map[cpu])
4307 			return -1;
4308 
4309 		cd_map[cpu]->cpu = cpu;
4310 
4311 		if (do_read_u32(ff, &nr_domains))
4312 			return -1;
4313 
4314 		if (nr_domains > max_sched_domains) {
4315 			pr_err("Invalid HEADER_CPU_DOMAIN_INFO: nr_domains %u > max_sched_domains (%u)\n",
4316 			       nr_domains, max_sched_domains);
4317 			return -1;
4318 		}
4319 
4320 		cd_map[cpu]->nr_domains = nr_domains;
4321 
4322 		cd_map[cpu]->domains = calloc(max_sched_domains, sizeof(*d_info));
4323 		if (!cd_map[cpu]->domains)
4324 			return -1;
4325 
4326 		for (j = 0; j < nr_domains; j++) {
4327 			if (do_read_u32(ff, &domain))
4328 				return -1;
4329 
4330 			if (domain >= max_sched_domains) {
4331 				pr_err("Invalid HEADER_CPU_DOMAIN_INFO: domain %d >= max_sched_domains (%d)\n",
4332 				       domain, max_sched_domains);
4333 				return -1;
4334 			}
4335 
4336 			d_info = zalloc(sizeof(*d_info));
4337 			if (!d_info)
4338 				return -1;
4339 
4340 			if (cd_map[cpu]->domains[domain]) {
4341 				pr_err("Invalid HEADER_CPU_DOMAIN_INFO: duplicate domain %u for cpu %u\n",
4342 				       domain, cpu);
4343 				free(d_info);
4344 				return -1;
4345 			}
4346 
4347 			cd_map[cpu]->domains[domain] = d_info;
4348 			d_info->domain = domain;
4349 
4350 			if (schedstat_version >= 17) {
4351 				dname = do_read_string(ff);
4352 				if (!dname)
4353 					return -1;
4354 
4355 				d_info->dname = dname;
4356 			}
4357 
4358 			cpumask = do_read_string(ff);
4359 			if (!cpumask)
4360 				return -1;
4361 
4362 			d_info->cpumask = cpumask;
4363 
4364 			cpulist = do_read_string(ff);
4365 			if (!cpulist)
4366 				return -1;
4367 
4368 			d_info->cpulist = cpulist;
4369 		}
4370 	}
4371 
4372 	return ret;
4373 }
4374 
4375 static int process_memory_ranges(struct feat_fd *ff, void *data __maybe_unused)
4376 {
4377 	struct perf_env *env = &ff->ph->env;
4378 	struct memory_range *ranges, *r;
4379 	u32 nr_memory_ranges, i;
4380 
4381 	if (do_read_u32(ff, &nr_memory_ranges))
4382 		return -1;
4383 
4384 	if (!nr_memory_ranges) {
4385 		pr_debug("memory ranges not available\n");
4386 		return 0;
4387 	}
4388 
4389 	/*
4390 	 * According to version 1.1 of the ACPI MRRM table, the maximum
4391 	 * number of memory regions can be at most 255. Do a sanity check
4392 	 * here to guard against a malformed perf.data file.
4393 	 */
4394 	if (nr_memory_ranges > MAX_MEMORY_RANGES) {
4395 		pr_err("Invalid memory_ranges: nr_memory_ranges (%u) > %u\n",
4396 		       nr_memory_ranges, MAX_MEMORY_RANGES);
4397 		return -1;
4398 	}
4399 
4400 	if (ff->size < sizeof(u32) + nr_memory_ranges * (2 * sizeof(u64) + sizeof(u32) + 2 * sizeof(u8))) {
4401 		pr_err("Invalid HEADER_MEMORY_RANGES: section too small (%zu) for %u range entries\n",
4402 		       ff->size, nr_memory_ranges);
4403 		return -1;
4404 	}
4405 
4406 	ranges = calloc(nr_memory_ranges, sizeof(*ranges));
4407 	if (!ranges)
4408 		return -1;
4409 
4410 	for (i = 0; i < nr_memory_ranges; i++) {
4411 		r = &ranges[i];
4412 
4413 		if (do_read_u64(ff, &r->base))
4414 			goto error;
4415 		if (do_read_u64(ff, &r->length))
4416 			goto error;
4417 		if (do_read_u32(ff, (u32 *) &r->node))
4418 			goto error;
4419 		if (__do_read(ff, &r->local_region_id, sizeof(u8)))
4420 			goto error;
4421 		if (__do_read(ff, &r->remote_region_id, sizeof(u8)))
4422 			goto error;
4423 	}
4424 
4425 	env->memory_ranges = ranges;
4426 	env->nr_memory_ranges = nr_memory_ranges;
4427 
4428 	return 0;
4429 error:
4430 	zfree(&ranges);
4431 	return -1;
4432 }
4433 
4434 #define FEAT_OPR(n, func, __full_only) \
4435 	[HEADER_##n] = {					\
4436 		.name	    = __stringify(n),			\
4437 		.write	    = write_##func,			\
4438 		.print	    = print_##func,			\
4439 		.full_only  = __full_only,			\
4440 		.process    = process_##func,			\
4441 		.synthesize = true				\
4442 	}
4443 
4444 #define FEAT_OPN(n, func, __full_only) \
4445 	[HEADER_##n] = {					\
4446 		.name	    = __stringify(n),			\
4447 		.write	    = write_##func,			\
4448 		.print	    = print_##func,			\
4449 		.full_only  = __full_only,			\
4450 		.process    = process_##func			\
4451 	}
4452 
4453 /* feature_ops not implemented: */
4454 #define print_tracing_data	NULL
4455 #define print_build_id		NULL
4456 
4457 #define process_branch_stack	NULL
4458 #define process_stat		NULL
4459 
4460 // Only used in util/synthetic-events.c
4461 const struct perf_header_feature_ops feat_ops[HEADER_LAST_FEATURE];
4462 
4463 const struct perf_header_feature_ops feat_ops[HEADER_LAST_FEATURE] = {
4464 	FEAT_OPN(TRACING_DATA,	tracing_data,	false),
4465 	FEAT_OPN(BUILD_ID,	build_id,	false),
4466 	FEAT_OPR(HOSTNAME,	hostname,	false),
4467 	FEAT_OPR(OSRELEASE,	osrelease,	false),
4468 	FEAT_OPR(VERSION,	version,	false),
4469 	FEAT_OPR(ARCH,		arch,		false),
4470 	FEAT_OPR(NRCPUS,	nrcpus,		false),
4471 	FEAT_OPR(CPUDESC,	cpudesc,	false),
4472 	FEAT_OPR(CPUID,		cpuid,		false),
4473 	FEAT_OPR(TOTAL_MEM,	total_mem,	false),
4474 	FEAT_OPR(EVENT_DESC,	event_desc,	false),
4475 	FEAT_OPR(CMDLINE,	cmdline,	false),
4476 	FEAT_OPR(CPU_TOPOLOGY,	cpu_topology,	true),
4477 	FEAT_OPR(NUMA_TOPOLOGY,	numa_topology,	true),
4478 	FEAT_OPN(BRANCH_STACK,	branch_stack,	false),
4479 	FEAT_OPR(PMU_MAPPINGS,	pmu_mappings,	false),
4480 	FEAT_OPR(GROUP_DESC,	group_desc,	false),
4481 	FEAT_OPN(AUXTRACE,	auxtrace,	false),
4482 	FEAT_OPN(STAT,		stat,		false),
4483 	FEAT_OPN(CACHE,		cache,		true),
4484 	FEAT_OPR(SAMPLE_TIME,	sample_time,	false),
4485 	FEAT_OPR(MEM_TOPOLOGY,	mem_topology,	true),
4486 	FEAT_OPR(CLOCKID,	clockid,	false),
4487 	FEAT_OPN(DIR_FORMAT,	dir_format,	false),
4488 	FEAT_OPR(BPF_PROG_INFO, bpf_prog_info,  false),
4489 	FEAT_OPR(BPF_BTF,       bpf_btf,        false),
4490 	FEAT_OPR(COMPRESSED,	compressed,	false),
4491 	FEAT_OPR(CPU_PMU_CAPS,	cpu_pmu_caps,	false),
4492 	FEAT_OPR(CLOCK_DATA,	clock_data,	false),
4493 	FEAT_OPN(HYBRID_TOPOLOGY,	hybrid_topology,	true),
4494 	FEAT_OPR(PMU_CAPS,	pmu_caps,	false),
4495 	FEAT_OPR(CPU_DOMAIN_INFO,	cpu_domain_info,	true),
4496 	FEAT_OPR(E_MACHINE,	e_machine,	false),
4497 	FEAT_OPR(CLN_SIZE,	cln_size,	false),
4498 	FEAT_OPR(MEMORY_RANGES,	memory_ranges,	false),
4499 };
4500 
4501 struct header_print_data {
4502 	FILE *fp;
4503 	bool full; /* extended list of headers */
4504 };
4505 
4506 const char *header_feat__name(unsigned int id)
4507 {
4508 	if (id < HEADER_LAST_FEATURE)
4509 		return feat_ops[id].name ?: "INVALID";
4510 	return "INVALID";
4511 }
4512 
4513 static int perf_file_section__fprintf_info(struct perf_file_section *section,
4514 					   struct perf_header *ph,
4515 					   int feat, int fd, void *data)
4516 {
4517 	struct header_print_data *hd = data;
4518 	struct feat_fd ff;
4519 
4520 	if (lseek(fd, section->offset, SEEK_SET) == (off_t)-1) {
4521 		pr_debug("Failed to lseek to %" PRIu64 " offset for feature %s (%d), continuing...\n",
4522 			 section->offset, header_feat__name(feat), feat);
4523 		return 0;
4524 	}
4525 	if (feat >= ph->last_feat) {
4526 		pr_warning("unknown feature %d\n", feat);
4527 		return 0;
4528 	}
4529 	if (!feat_ops[feat].print)
4530 		return 0;
4531 
4532 	ff = (struct  feat_fd) {
4533 		.fd = fd,
4534 		.ph = ph,
4535 		.size = section->size,
4536 	};
4537 
4538 	if (!feat_ops[feat].full_only || hd->full)
4539 		feat_ops[feat].print(&ff, hd->fp);
4540 	else
4541 		fprintf(hd->fp, "# %s info available, use -I to display\n",
4542 			feat_ops[feat].name);
4543 
4544 	return 0;
4545 }
4546 
4547 int perf_header__fprintf_info(struct perf_session *session, FILE *fp, bool full)
4548 {
4549 	struct header_print_data hd;
4550 	struct perf_header *header = &session->header;
4551 	int fd = perf_data__fd(session->data);
4552 	struct stat st;
4553 	time_t stctime;
4554 	int ret, bit;
4555 
4556 	hd.fp = fp;
4557 	hd.full = full;
4558 
4559 	ret = fstat(fd, &st);
4560 	if (ret == -1)
4561 		return -1;
4562 
4563 	stctime = st.st_mtime;
4564 	fprintf(fp, "# captured on    : %s", ctime(&stctime));
4565 
4566 	fprintf(fp, "# header version : %u\n", header->version);
4567 	fprintf(fp, "# data offset    : %" PRIu64 "\n", header->data_offset);
4568 	fprintf(fp, "# data size      : %" PRIu64 "\n", header->data_size);
4569 	fprintf(fp, "# feat offset    : %" PRIu64 "\n", header->feat_offset);
4570 
4571 	perf_header__process_sections(header, fd, &hd,
4572 				      perf_file_section__fprintf_info);
4573 
4574 	if (session->data->is_pipe)
4575 		return 0;
4576 
4577 	fprintf(fp, "# missing features: ");
4578 	for_each_clear_bit(bit, header->adds_features, header->last_feat) {
4579 		if (bit)
4580 			fprintf(fp, "%s ", feat_ops[bit].name);
4581 	}
4582 
4583 	fprintf(fp, "\n");
4584 	return 0;
4585 }
4586 
4587 struct header_fw {
4588 	struct feat_writer	fw;
4589 	struct feat_fd		*ff;
4590 };
4591 
4592 static int feat_writer_cb(struct feat_writer *fw, void *buf, size_t sz)
4593 {
4594 	struct header_fw *h = container_of(fw, struct header_fw, fw);
4595 
4596 	return do_write(h->ff, buf, sz);
4597 }
4598 
4599 static int do_write_feat(struct feat_fd *ff, int type,
4600 			 struct perf_file_section **p,
4601 			 struct evlist *evlist,
4602 			 struct feat_copier *fc)
4603 {
4604 	int err;
4605 	int ret = 0;
4606 
4607 	if (perf_header__has_feat(ff->ph, type)) {
4608 		if (!feat_ops[type].write)
4609 			return -1;
4610 
4611 		if (ff->buf) {
4612 			pr_warning("Error: calling %s in pipe-mode.\n", __func__);
4613 			return -1;
4614 		}
4615 
4616 		(*p)->offset = lseek(ff->fd, 0, SEEK_CUR);
4617 
4618 		/*
4619 		 * Hook to let perf inject copy features sections from the input
4620 		 * file.
4621 		 */
4622 		if (fc && fc->copy) {
4623 			struct header_fw h = {
4624 				.fw.write = feat_writer_cb,
4625 				.ff = ff,
4626 			};
4627 
4628 			/* ->copy() returns 0 if the feature was not copied */
4629 			err = fc->copy(fc, type, &h.fw);
4630 		} else {
4631 			err = 0;
4632 		}
4633 		if (!err)
4634 			err = feat_ops[type].write(ff, evlist);
4635 		if (err < 0) {
4636 			pr_debug("failed to write feature %s\n", feat_ops[type].name);
4637 
4638 			/* undo anything written */
4639 			lseek(ff->fd, (*p)->offset, SEEK_SET);
4640 
4641 			return -1;
4642 		}
4643 		(*p)->size = lseek(ff->fd, 0, SEEK_CUR) - (*p)->offset;
4644 		(*p)++;
4645 	}
4646 	return ret;
4647 }
4648 
4649 static int perf_header__adds_write(struct perf_header *header,
4650 				   struct evlist *evlist, int fd,
4651 				   struct feat_copier *fc)
4652 {
4653 	int nr_sections;
4654 	struct feat_fd ff = {
4655 		.fd  = fd,
4656 		.ph = header,
4657 	};
4658 	struct perf_file_section *feat_sec, *p;
4659 	int sec_size;
4660 	u64 sec_start;
4661 	int feat;
4662 	int err;
4663 
4664 	nr_sections = bitmap_weight(header->adds_features, HEADER_FEAT_BITS);
4665 	if (!nr_sections)
4666 		return 0;
4667 
4668 	feat_sec = p = calloc(nr_sections, sizeof(*feat_sec));
4669 	if (feat_sec == NULL)
4670 		return -ENOMEM;
4671 
4672 	sec_size = sizeof(*feat_sec) * nr_sections;
4673 
4674 	sec_start = header->feat_offset;
4675 	lseek(fd, sec_start + sec_size, SEEK_SET);
4676 
4677 	for_each_set_bit(feat, header->adds_features, HEADER_FEAT_BITS) {
4678 		if (do_write_feat(&ff, feat, &p, evlist, fc))
4679 			perf_header__clear_feat(header, feat);
4680 	}
4681 
4682 	lseek(fd, sec_start, SEEK_SET);
4683 	/*
4684 	 * may write more than needed due to dropped feature, but
4685 	 * this is okay, reader will skip the missing entries
4686 	 */
4687 	err = do_write(&ff, feat_sec, sec_size);
4688 	if (err < 0)
4689 		pr_debug("failed to write feature section\n");
4690 	free(ff.buf); /* TODO: added to silence clang-tidy. */
4691 	free(feat_sec);
4692 	return err;
4693 }
4694 
4695 int perf_header__write_pipe(int fd)
4696 {
4697 	struct perf_pipe_file_header f_header;
4698 	struct feat_fd ff = {
4699 		.fd = fd,
4700 	};
4701 	int err;
4702 
4703 	f_header = (struct perf_pipe_file_header){
4704 		.magic	   = PERF_MAGIC,
4705 		.size	   = sizeof(f_header),
4706 	};
4707 
4708 	err = do_write(&ff, &f_header, sizeof(f_header));
4709 	if (err < 0) {
4710 		pr_debug("failed to write perf pipe header\n");
4711 		return err;
4712 	}
4713 	free(ff.buf);
4714 	return 0;
4715 }
4716 
4717 static int perf_session__do_write_header(struct perf_session *session,
4718 					 struct evlist *evlist,
4719 					 int fd, bool at_exit,
4720 					 struct feat_copier *fc,
4721 					 bool write_attrs_after_data)
4722 {
4723 	struct perf_file_header f_header;
4724 	struct perf_header *header = &session->header;
4725 	struct evsel *evsel;
4726 	struct feat_fd ff = {
4727 		.ph = header,
4728 		.fd = fd,
4729 	};
4730 	u64 attr_offset = sizeof(f_header), attr_size = 0;
4731 	int err;
4732 
4733 	if (write_attrs_after_data && at_exit) {
4734 		/*
4735 		 * Write features at the end of the file first so that
4736 		 * attributes may come after them.
4737 		 */
4738 		if (!header->data_offset && header->data_size) {
4739 			pr_err("File contains data but offset unknown\n");
4740 			err = -1;
4741 			goto err_out;
4742 		}
4743 		header->feat_offset = header->data_offset + header->data_size;
4744 		err = perf_header__adds_write(header, evlist, fd, fc);
4745 		if (err < 0)
4746 			goto err_out;
4747 		attr_offset = lseek(fd, 0, SEEK_CUR);
4748 	} else {
4749 		lseek(fd, attr_offset, SEEK_SET);
4750 	}
4751 
4752 	evlist__for_each_entry(session->evlist, evsel) {
4753 		evsel->id_offset = attr_offset;
4754 		/* Avoid writing at the end of the file until the session is exiting. */
4755 		if (!write_attrs_after_data || at_exit) {
4756 			err = do_write(&ff, evsel->core.id, evsel->core.ids * sizeof(u64));
4757 			if (err < 0) {
4758 				pr_debug("failed to write perf header\n");
4759 				goto err_out;
4760 			}
4761 		}
4762 		attr_offset += evsel->core.ids * sizeof(u64);
4763 	}
4764 
4765 	evlist__for_each_entry(evlist, evsel) {
4766 		if (evsel->core.attr.size < sizeof(evsel->core.attr)) {
4767 			/*
4768 			 * We are likely in "perf inject" and have read
4769 			 * from an older file. Update attr size so that
4770 			 * reader gets the right offset to the ids.
4771 			 */
4772 			evsel->core.attr.size = sizeof(evsel->core.attr);
4773 		}
4774 		/* Avoid writing at the end of the file until the session is exiting. */
4775 		if (!write_attrs_after_data || at_exit) {
4776 			struct perf_file_attr f_attr = {
4777 				.attr = evsel->core.attr,
4778 				.ids  = {
4779 					.offset = evsel->id_offset,
4780 					.size   = evsel->core.ids * sizeof(u64),
4781 				}
4782 			};
4783 			err = do_write(&ff, &f_attr, sizeof(f_attr));
4784 			if (err < 0) {
4785 				pr_debug("failed to write perf header attribute\n");
4786 				goto err_out;
4787 			}
4788 		}
4789 		attr_size += sizeof(struct perf_file_attr);
4790 	}
4791 
4792 	if (!header->data_offset) {
4793 		if (write_attrs_after_data)
4794 			header->data_offset = sizeof(f_header);
4795 		else
4796 			header->data_offset = attr_offset + attr_size;
4797 	}
4798 	header->feat_offset = header->data_offset + header->data_size;
4799 
4800 	if (!write_attrs_after_data && at_exit) {
4801 		/* Write features now feat_offset is known. */
4802 		err = perf_header__adds_write(header, evlist, fd, fc);
4803 		if (err < 0)
4804 			goto err_out;
4805 	}
4806 
4807 	f_header = (struct perf_file_header){
4808 		.magic	   = PERF_MAGIC,
4809 		.size	   = sizeof(f_header),
4810 		.attr_size = sizeof(struct perf_file_attr),
4811 		.attrs = {
4812 			.offset = attr_offset,
4813 			.size   = attr_size,
4814 		},
4815 		.data = {
4816 			.offset = header->data_offset,
4817 			.size	= header->data_size,
4818 		},
4819 		/* event_types is ignored, store zeros */
4820 	};
4821 
4822 	memcpy(&f_header.adds_features, &header->adds_features, sizeof(header->adds_features));
4823 
4824 	lseek(fd, 0, SEEK_SET);
4825 	err = do_write(&ff, &f_header, sizeof(f_header));
4826 	if (err < 0) {
4827 		pr_debug("failed to write perf header\n");
4828 		goto err_out;
4829 	} else {
4830 		lseek(fd, 0, SEEK_END);
4831 		err = 0;
4832 	}
4833 err_out:
4834 	free(ff.buf);
4835 	return err;
4836 }
4837 
4838 int perf_session__write_header(struct perf_session *session,
4839 			       struct evlist *evlist,
4840 			       int fd, bool at_exit)
4841 {
4842 	return perf_session__do_write_header(session, evlist, fd, at_exit, /*fc=*/NULL,
4843 					     /*write_attrs_after_data=*/false);
4844 }
4845 
4846 size_t perf_session__data_offset(struct evlist *evlist)
4847 {
4848 	struct evsel *evsel;
4849 	size_t data_offset;
4850 
4851 	data_offset = sizeof(struct perf_file_header);
4852 	evlist__for_each_entry(evlist, evsel) {
4853 		data_offset += evsel->core.ids * sizeof(u64);
4854 	}
4855 	data_offset += evlist__nr_entries(evlist) * sizeof(struct perf_file_attr);
4856 
4857 	return data_offset;
4858 }
4859 
4860 int perf_session__inject_header(struct perf_session *session,
4861 				struct evlist *evlist,
4862 				int fd,
4863 				struct feat_copier *fc,
4864 				bool write_attrs_after_data)
4865 {
4866 	return perf_session__do_write_header(session, evlist, fd, true, fc,
4867 					     write_attrs_after_data);
4868 }
4869 
4870 static int perf_header__getbuffer64(struct perf_header *header,
4871 				    int fd, void *buf, size_t size)
4872 {
4873 	ssize_t n = readn(fd, buf, size);
4874 
4875 	if (n <= 0) {
4876 		if (n == 0)
4877 			errno = EIO;
4878 		return -1;
4879 	}
4880 
4881 	if (header->needs_swap)
4882 		mem_bswap_64(buf, size);
4883 
4884 	return 0;
4885 }
4886 
4887 int perf_header__process_sections(struct perf_header *header, int fd,
4888 				  void *data,
4889 				  int (*process)(struct perf_file_section *section,
4890 						 struct perf_header *ph,
4891 						 int feat, int fd, void *data))
4892 {
4893 	struct perf_file_section *feat_sec, *sec;
4894 	int nr_sections;
4895 	int sec_size;
4896 	int feat;
4897 	int err;
4898 	struct stat st;
4899 
4900 	nr_sections = bitmap_weight(header->adds_features, HEADER_FEAT_BITS);
4901 	if (!nr_sections)
4902 		return 0;
4903 
4904 	feat_sec = sec = calloc(nr_sections, sizeof(*feat_sec));
4905 	if (!feat_sec)
4906 		return -1;
4907 
4908 	sec_size = sizeof(*feat_sec) * nr_sections;
4909 
4910 	lseek(fd, header->feat_offset, SEEK_SET);
4911 
4912 	err = perf_header__getbuffer64(header, fd, feat_sec, sec_size);
4913 	if (err < 0)
4914 		goto out_free;
4915 
4916 	if (fstat(fd, &st) < 0) {
4917 		pr_err("Failed to stat the perf data file\n");
4918 		err = -1;
4919 		goto out_free;
4920 	}
4921 
4922 	for_each_set_bit(feat, header->adds_features, header->last_feat) {
4923 		/*
4924 		 * FIXME: block devices have st_size == 0, so we skip
4925 		 * bounds checking entirely.  Historically perf never
4926 		 * prevented using a block device as input, but it
4927 		 * probably should — there's no valid use case for it
4928 		 * and it bypasses all file-size validation.
4929 		 */
4930 		if (S_ISREG(st.st_mode) &&
4931 		    (sec->offset > (u64)st.st_size ||
4932 		     sec->size > (u64)st.st_size - sec->offset)) {
4933 			pr_err("Feature %s (%d) section extends past EOF (offset=%" PRIu64 ", size=%" PRIu64 ", file=%" PRIu64 ")\n",
4934 			       header_feat__name(feat), feat,
4935 			       sec->offset, sec->size, (u64)st.st_size);
4936 			err = -1;
4937 			goto out_free;
4938 		}
4939 		err = process(sec++, header, feat, fd, data);
4940 		if (err < 0)
4941 			goto out_free;
4942 	}
4943 	err = 0;
4944 out_free:
4945 	free(feat_sec);
4946 	return err;
4947 }
4948 
4949 static const int attr_file_abi_sizes[] = {
4950 	[0] = PERF_ATTR_SIZE_VER0,
4951 	[1] = PERF_ATTR_SIZE_VER1,
4952 	[2] = PERF_ATTR_SIZE_VER2,
4953 	[3] = PERF_ATTR_SIZE_VER3,
4954 	[4] = PERF_ATTR_SIZE_VER4,
4955 	0,
4956 };
4957 
4958 /*
4959  * In the legacy file format, the magic number is not used to encode endianness.
4960  * hdr_sz was used to encode endianness. But given that hdr_sz can vary based
4961  * on ABI revisions, we need to try all combinations for all endianness to
4962  * detect the endianness.
4963  */
4964 static int try_all_file_abis(uint64_t hdr_sz, struct perf_header *ph)
4965 {
4966 	uint64_t ref_size, attr_size;
4967 	int i;
4968 
4969 	for (i = 0 ; attr_file_abi_sizes[i]; i++) {
4970 		ref_size = attr_file_abi_sizes[i]
4971 			 + sizeof(struct perf_file_section);
4972 		if (hdr_sz != ref_size) {
4973 			attr_size = bswap_64(hdr_sz);
4974 			if (attr_size != ref_size)
4975 				continue;
4976 
4977 			ph->needs_swap = true;
4978 		}
4979 		pr_debug("ABI%d perf.data file detected, need_swap=%d\n",
4980 			 i,
4981 			 ph->needs_swap);
4982 		return 0;
4983 	}
4984 	/* could not determine endianness */
4985 	return -1;
4986 }
4987 
4988 #define PERF_PIPE_HDR_VER0	16
4989 
4990 static const size_t attr_pipe_abi_sizes[] = {
4991 	[0] = PERF_PIPE_HDR_VER0,
4992 	0,
4993 };
4994 
4995 /*
4996  * In the legacy pipe format, there is an implicit assumption that endianness
4997  * between host recording the samples, and host parsing the samples is the
4998  * same. This is not always the case given that the pipe output may always be
4999  * redirected into a file and analyzed on a different machine with possibly a
5000  * different endianness and perf_event ABI revisions in the perf tool itself.
5001  */
5002 static int try_all_pipe_abis(uint64_t hdr_sz, struct perf_header *ph)
5003 {
5004 	u64 attr_size;
5005 	int i;
5006 
5007 	for (i = 0 ; attr_pipe_abi_sizes[i]; i++) {
5008 		if (hdr_sz != attr_pipe_abi_sizes[i]) {
5009 			attr_size = bswap_64(hdr_sz);
5010 			if (attr_size != hdr_sz)
5011 				continue;
5012 
5013 			ph->needs_swap = true;
5014 		}
5015 		pr_debug("Pipe ABI%d perf.data file detected\n", i);
5016 		return 0;
5017 	}
5018 	return -1;
5019 }
5020 
5021 bool is_perf_magic(u64 magic)
5022 {
5023 	if (!memcmp(&magic, __perf_magic1, sizeof(magic))
5024 		|| magic == __perf_magic2
5025 		|| magic == __perf_magic2_sw)
5026 		return true;
5027 
5028 	return false;
5029 }
5030 
5031 static int check_magic_endian(u64 magic, uint64_t hdr_sz,
5032 			      bool is_pipe, struct perf_header *ph)
5033 {
5034 	int ret;
5035 
5036 	/* check for legacy format */
5037 	ret = memcmp(&magic, __perf_magic1, sizeof(magic));
5038 	if (ret == 0) {
5039 		ph->version = PERF_HEADER_VERSION_1;
5040 		pr_debug("legacy perf.data format\n");
5041 		if (is_pipe)
5042 			return try_all_pipe_abis(hdr_sz, ph);
5043 
5044 		return try_all_file_abis(hdr_sz, ph);
5045 	}
5046 	/*
5047 	 * the new magic number serves two purposes:
5048 	 * - unique number to identify actual perf.data files
5049 	 * - encode endianness of file
5050 	 */
5051 	ph->version = PERF_HEADER_VERSION_2;
5052 
5053 	/* check magic number with one endianness */
5054 	if (magic == __perf_magic2)
5055 		return 0;
5056 
5057 	/* check magic number with opposite endianness */
5058 	if (magic != __perf_magic2_sw)
5059 		return -1;
5060 
5061 	ph->needs_swap = true;
5062 
5063 	return 0;
5064 }
5065 
5066 int perf_file_header__read(struct perf_file_header *header,
5067 			   struct perf_header *ph, int fd)
5068 {
5069 	ssize_t ret;
5070 
5071 	lseek(fd, 0, SEEK_SET);
5072 
5073 	ret = readn(fd, header, sizeof(*header));
5074 	if (ret <= 0)
5075 		return -1;
5076 
5077 	if (check_magic_endian(header->magic,
5078 			       header->attr_size, false, ph) < 0) {
5079 		pr_debug("magic/endian check failed\n");
5080 		return -1;
5081 	}
5082 
5083 	if (ph->needs_swap) {
5084 		mem_bswap_64(header, offsetof(struct perf_file_header,
5085 			     adds_features));
5086 	}
5087 
5088 	if (header->size > header->attrs.offset) {
5089 		pr_err("Perf file header corrupt: header overlaps attrs\n");
5090 		return -1;
5091 	}
5092 
5093 	if (header->size > header->data.offset) {
5094 		pr_err("Perf file header corrupt: header overlaps data\n");
5095 		return -1;
5096 	}
5097 
5098 	if ((header->attrs.offset <= header->data.offset &&
5099 	     header->attrs.offset + header->attrs.size > header->data.offset) ||
5100 	    (header->attrs.offset > header->data.offset &&
5101 	     header->data.offset + header->data.size > header->attrs.offset)) {
5102 		pr_err("Perf file header corrupt: Attributes and data overlap\n");
5103 		return -1;
5104 	}
5105 
5106 	if (header->size != sizeof(*header)) {
5107 		/* Support the previous format */
5108 		if (header->size == offsetof(typeof(*header), adds_features))
5109 			bitmap_zero(header->adds_features, HEADER_FEAT_BITS);
5110 		else
5111 			return -1;
5112 	} else if (ph->needs_swap) {
5113 		/*
5114 		 * feature bitmap is declared as an array of unsigned longs --
5115 		 * not good since its size can differ between the host that
5116 		 * generated the data file and the host analyzing the file.
5117 		 *
5118 		 * We need to handle endianness, but we don't know the size of
5119 		 * the unsigned long where the file was generated. Take a best
5120 		 * guess at determining it: try 64-bit swap first (ie., file
5121 		 * created on a 64-bit host), and check if the hostname feature
5122 		 * bit is set (this feature bit is forced on as of fbe96f2).
5123 		 * If the bit is not, undo the 64-bit swap and try a 32-bit
5124 		 * swap. If the hostname bit is still not set (e.g., older data
5125 		 * file), punt and fallback to the original behavior --
5126 		 * clearing all feature bits and setting buildid.
5127 		 */
5128 		mem_bswap_64(&header->adds_features,
5129 			    BITS_TO_U64(HEADER_FEAT_BITS));
5130 
5131 		if (!test_bit(HEADER_HOSTNAME, header->adds_features)) {
5132 			/* unswap as u64 */
5133 			mem_bswap_64(&header->adds_features,
5134 				    BITS_TO_U64(HEADER_FEAT_BITS));
5135 
5136 			/* unswap as u32 */
5137 			mem_bswap_32(&header->adds_features,
5138 				    BITS_TO_U32(HEADER_FEAT_BITS));
5139 		}
5140 
5141 		if (!test_bit(HEADER_HOSTNAME, header->adds_features)) {
5142 			bitmap_zero(header->adds_features, HEADER_FEAT_BITS);
5143 			__set_bit(HEADER_BUILD_ID, header->adds_features);
5144 		}
5145 	}
5146 
5147 	memcpy(&ph->adds_features, &header->adds_features,
5148 	       sizeof(ph->adds_features));
5149 
5150 	ph->data_offset  = header->data.offset;
5151 	ph->data_size	 = header->data.size;
5152 	ph->feat_offset  = header->data.offset + header->data.size;
5153 	ph->last_feat	 = HEADER_LAST_FEATURE;
5154 	return 0;
5155 }
5156 
5157 static int perf_file_section__process(struct perf_file_section *section,
5158 				      struct perf_header *ph,
5159 				      int feat, int fd, void *data)
5160 {
5161 	struct feat_fd fdd = {
5162 		.fd	= fd,
5163 		.ph	= ph,
5164 		.size	= section->size,
5165 		.offset	= 0,
5166 	};
5167 
5168 	if (lseek(fd, section->offset, SEEK_SET) == (off_t)-1) {
5169 		pr_debug("Failed to lseek to %" PRIu64 " offset for feature %s (%d), continuing...\n",
5170 			 section->offset, header_feat__name(feat), feat);
5171 		return 0;
5172 	}
5173 
5174 	if (feat >= HEADER_LAST_FEATURE) {
5175 		pr_debug("unknown feature %d, continuing...\n", feat);
5176 		return 0;
5177 	}
5178 
5179 	if (!feat_ops[feat].process)
5180 		return 0;
5181 
5182 	return feat_ops[feat].process(&fdd, data);
5183 }
5184 
5185 static int perf_file_header__read_pipe(struct perf_pipe_file_header *header,
5186 				       struct perf_header *ph,
5187 				       struct perf_data *data)
5188 {
5189 	ssize_t ret;
5190 
5191 	ret = perf_data__read(data, header, sizeof(*header));
5192 	if (ret <= 0)
5193 		return -1;
5194 
5195 	if (check_magic_endian(header->magic, header->size, true, ph) < 0) {
5196 		pr_debug("endian/magic failed\n");
5197 		return -1;
5198 	}
5199 
5200 	if (ph->needs_swap)
5201 		header->size = bswap_64(header->size);
5202 
5203 	/* The last feature is written out as a 0 sized event and will update this value. */
5204 	ph->last_feat = 0;
5205 	return 0;
5206 }
5207 
5208 static int perf_header__read_pipe(struct perf_session *session)
5209 {
5210 	struct perf_header *header = &session->header;
5211 	struct perf_pipe_file_header f_header;
5212 
5213 	if (perf_file_header__read_pipe(&f_header, header, session->data) < 0) {
5214 		pr_debug("incompatible file format\n");
5215 		return -EINVAL;
5216 	}
5217 
5218 	return f_header.size == sizeof(f_header) ? 0 : -1;
5219 }
5220 
5221 static int read_attr(int fd, struct perf_header *ph,
5222 		     struct perf_file_attr *f_attr)
5223 {
5224 	struct perf_event_attr *attr = &f_attr->attr;
5225 	size_t sz, left;
5226 	size_t our_sz = sizeof(f_attr->attr);
5227 	ssize_t ret;
5228 
5229 	memset(f_attr, 0, sizeof(*f_attr));
5230 
5231 	/* read minimal guaranteed structure */
5232 	ret = readn(fd, attr, PERF_ATTR_SIZE_VER0);
5233 	if (ret <= 0) {
5234 		pr_debug("cannot read %d bytes of header attr\n",
5235 			 PERF_ATTR_SIZE_VER0);
5236 		if (ret == 0)
5237 			errno = EIO;
5238 		return -1;
5239 	}
5240 
5241 	/* on file perf_event_attr size */
5242 	sz = attr->size;
5243 
5244 	if (ph->needs_swap)
5245 		sz = bswap_32(sz);
5246 
5247 	if (sz == 0) {
5248 		/* assume ABI0 */
5249 		sz =  PERF_ATTR_SIZE_VER0;
5250 	} else if (sz < PERF_ATTR_SIZE_VER0) {
5251 		pr_debug("bad attr size %zu, expected at least %d\n",
5252 			 sz, PERF_ATTR_SIZE_VER0);
5253 		errno = EINVAL;
5254 		return -1;
5255 	} else if (sz > our_sz) {
5256 		pr_debug("file uses a more recent and unsupported ABI"
5257 			 " (%zu bytes extra)\n", sz - our_sz);
5258 		errno = EINVAL;
5259 		return -1;
5260 	}
5261 	/* what we have not yet read and that we know about */
5262 	left = sz - PERF_ATTR_SIZE_VER0;
5263 	if (left) {
5264 		void *ptr = attr;
5265 		ptr += PERF_ATTR_SIZE_VER0;
5266 
5267 		ret = readn(fd, ptr, left);
5268 		if (ret <= 0) {
5269 			if (ret == 0)
5270 				errno = EIO;
5271 			return -1;
5272 		}
5273 	}
5274 	/* read perf_file_section, ids are read in caller */
5275 	ret = readn(fd, &f_attr->ids, sizeof(f_attr->ids));
5276 	if (ret <= 0) {
5277 		if (ret == 0)
5278 			errno = EIO;
5279 		return -1;
5280 	}
5281 
5282 	return 0;
5283 }
5284 
5285 #ifdef HAVE_LIBTRACEEVENT
5286 static int evsel__prepare_tracepoint_event(struct evsel *evsel, struct tep_handle *pevent)
5287 {
5288 	struct tep_event *event;
5289 	char bf[128];
5290 
5291 	/* already prepared */
5292 	if (evsel->tp_format)
5293 		return 0;
5294 
5295 	if (pevent == NULL) {
5296 		pr_debug("broken or missing trace data\n");
5297 		return -1;
5298 	}
5299 
5300 	event = tep_find_event(pevent, evsel->core.attr.config);
5301 	if (event == NULL) {
5302 		pr_debug("cannot find event format for %d\n", (int)evsel->core.attr.config);
5303 		return -1;
5304 	}
5305 
5306 	if (!evsel->name) {
5307 		snprintf(bf, sizeof(bf), "%s:%s", event->system, event->name);
5308 		evsel->name = strdup(bf);
5309 		if (evsel->name == NULL)
5310 			return -1;
5311 	}
5312 
5313 	evsel->tp_format = event;
5314 	return 0;
5315 }
5316 
5317 static int evlist__prepare_tracepoint_events(struct evlist *evlist, struct tep_handle *pevent)
5318 {
5319 	struct evsel *pos;
5320 
5321 	evlist__for_each_entry(evlist, pos) {
5322 		if (pos->core.attr.type == PERF_TYPE_TRACEPOINT &&
5323 		    evsel__prepare_tracepoint_event(pos, pevent))
5324 			return -1;
5325 	}
5326 
5327 	return 0;
5328 }
5329 #endif
5330 
5331 int perf_session__read_header(struct perf_session *session)
5332 {
5333 	struct perf_data *data = session->data;
5334 	struct perf_header *header = &session->header;
5335 	struct perf_file_header	f_header;
5336 	struct perf_file_attr	f_attr;
5337 	u64			f_id;
5338 	struct stat		input_stat;
5339 	int nr_attrs, nr_ids, i, j, err = -ENOMEM;
5340 	int fd = perf_data__fd(data);
5341 
5342 	session->evlist = evlist__new();
5343 	if (session->evlist == NULL)
5344 		return -ENOMEM;
5345 
5346 	evlist__set_session(session->evlist, session);
5347 	session->machines.host.env = &header->env;
5348 
5349 	/*
5350 	 * We can read 'pipe' data event from regular file,
5351 	 * check for the pipe header regardless of source.
5352 	 */
5353 	err = perf_header__read_pipe(session);
5354 	if (!err || perf_data__is_pipe(data)) {
5355 		data->is_pipe = true;
5356 		return err;
5357 	}
5358 
5359 	err = -ENOMEM;
5360 	if (perf_file_header__read(&f_header, header, fd) < 0)
5361 		return -EINVAL;
5362 
5363 	if (header->needs_swap && data->in_place_update) {
5364 		pr_err("In-place update not supported when byte-swapping is required\n");
5365 		return -EINVAL;
5366 	}
5367 
5368 	/*
5369 	 * Sanity check that perf.data was written cleanly; data size is
5370 	 * initialized to 0 and updated only if the on_exit function is run.
5371 	 * If data size is still 0 then the file contains only partial
5372 	 * information.  Just warn user and process it as much as it can.
5373 	 */
5374 	if (f_header.data.size == 0) {
5375 		pr_warning("WARNING: The %s file's data size field is 0 which is unexpected.\n"
5376 			   "Was the 'perf record' command properly terminated?\n",
5377 			   data->file.path);
5378 	}
5379 
5380 	if (f_header.attr_size == 0) {
5381 		pr_err("ERROR: The %s file's attr size field is 0 which is unexpected.\n"
5382 		       "Was the 'perf record' command properly terminated?\n",
5383 		       data->file.path);
5384 		return -EINVAL;
5385 	}
5386 
5387 	if (fstat(fd, &input_stat) < 0)
5388 		return -errno;
5389 
5390 	/* Check before assigning to int to avoid u64-to-int truncation */
5391 	if (f_header.attrs.size / f_header.attr_size > MAX_NR_ATTRS) {
5392 		pr_err("Too many attributes: %" PRIu64 " (max %d)\n",
5393 		       f_header.attrs.size / f_header.attr_size, MAX_NR_ATTRS);
5394 		return -EINVAL;
5395 	}
5396 	nr_attrs = f_header.attrs.size / f_header.attr_size;
5397 	lseek(fd, f_header.attrs.offset, SEEK_SET);
5398 
5399 	for (i = 0; i < nr_attrs; i++) {
5400 		struct evsel *evsel;
5401 		off_t tmp;
5402 
5403 		if (read_attr(fd, header, &f_attr) < 0)
5404 			goto out_errno;
5405 
5406 		if (header->needs_swap) {
5407 			f_attr.ids.size   = bswap_64(f_attr.ids.size);
5408 			f_attr.ids.offset = bswap_64(f_attr.ids.offset);
5409 			perf_event__attr_swap(&f_attr.attr);
5410 		}
5411 
5412 		/*
5413 		 * Validate ids section: must be aligned to u64, and
5414 		 * the count must fit in an int to avoid truncation in
5415 		 * nr_ids and size_t overflow in perf_evsel__alloc_id()
5416 		 * on 32-bit architectures.
5417 		 */
5418 		if (f_attr.ids.size % sizeof(u64)) {
5419 			pr_err("Invalid ids section size %" PRIu64 " for attr %d, not aligned to u64\n",
5420 			       f_attr.ids.size, i);
5421 			err = -EINVAL;
5422 			goto out_put_evlist;
5423 		}
5424 
5425 		/*
5426 		 * Cap the ID count to avoid int truncation of nr_ids
5427 		 * on 64-bit and size_t overflow in the allocation
5428 		 * paths (nr_ids * sizeof(u64), nr_ids *
5429 		 * sizeof(struct perf_sample_id)) on 32-bit.
5430 		 */
5431 		if (f_attr.ids.size / sizeof(u64) > MAX_IDS_PER_ATTR) {
5432 			pr_err("Invalid ids section size %" PRIu64 " for attr %d, too many IDs\n",
5433 			       f_attr.ids.size, i);
5434 			err = -EINVAL;
5435 			goto out_put_evlist;
5436 		}
5437 
5438 		/*
5439 		 * FIXME: see perf_header__process_sections() — block
5440 		 * devices bypass this check because st_size is 0.
5441 		 */
5442 		if (S_ISREG(input_stat.st_mode) &&
5443 		    (f_attr.ids.offset > (u64)input_stat.st_size ||
5444 		     f_attr.ids.size > (u64)input_stat.st_size - f_attr.ids.offset)) {
5445 			pr_err("Invalid ids section for attr %d: offset=%" PRIu64 " size=%" PRIu64 " exceeds file size %" PRIu64 "\n",
5446 			       i, f_attr.ids.offset, f_attr.ids.size, (u64)input_stat.st_size);
5447 			err = -EINVAL;
5448 			goto out_put_evlist;
5449 		}
5450 
5451 		tmp = lseek(fd, 0, SEEK_CUR);
5452 		evsel = evsel__new(&f_attr.attr);
5453 
5454 		if (evsel == NULL)
5455 			goto out_put_evlist;
5456 
5457 		evsel->needs_swap = header->needs_swap;
5458 		/*
5459 		 * Do it before so that if perf_evsel__alloc_id fails, this
5460 		 * entry gets purged too at evlist__put().
5461 		 */
5462 		evlist__add(session->evlist, evsel);
5463 
5464 		nr_ids = f_attr.ids.size / sizeof(u64);
5465 		/*
5466 		 * We don't have the cpu and thread maps on the header, so
5467 		 * for allocating the perf_sample_id table we fake 1 cpu and
5468 		 * hattr->ids threads.
5469 		 */
5470 		if (perf_evsel__alloc_id(&evsel->core, 1, nr_ids))
5471 			goto out_put_evlist;
5472 
5473 		lseek(fd, f_attr.ids.offset, SEEK_SET);
5474 
5475 		for (j = 0; j < nr_ids; j++) {
5476 			if (perf_header__getbuffer64(header, fd, &f_id, sizeof(f_id)))
5477 				goto out_errno;
5478 
5479 			perf_evlist__id_add(evlist__core(session->evlist),
5480 					    &evsel->core, 0, j, f_id);
5481 		}
5482 
5483 		lseek(fd, tmp, SEEK_SET);
5484 	}
5485 
5486 	/*
5487 	 * Skip feature section processing for truncated files
5488 	 * (data.size == 0 means recording was interrupted).  The
5489 	 * section table is unreliable in that case, and the event
5490 	 * data can still be processed without the feature headers.
5491 	 * Clear the bitmap so has_feat() returns false and tools
5492 	 * use their "feature not present" fallbacks instead of
5493 	 * accessing uninitialized env fields.
5494 	 */
5495 	if (f_header.data.size == 0) {
5496 		bitmap_zero(header->adds_features, HEADER_FEAT_BITS);
5497 	} else {
5498 #ifdef HAVE_LIBTRACEEVENT
5499 		err = perf_header__process_sections(header, fd, &session->tevent,
5500 						    perf_file_section__process);
5501 		if (err < 0)
5502 			goto out_put_evlist;
5503 
5504 		if (evlist__prepare_tracepoint_events(session->evlist,
5505 						      session->tevent.pevent)) {
5506 			err = -ENOMEM;
5507 			goto out_put_evlist;
5508 		}
5509 #else
5510 		err = perf_header__process_sections(header, fd, NULL,
5511 						    perf_file_section__process);
5512 		if (err < 0)
5513 			goto out_put_evlist;
5514 #endif
5515 	}
5516 
5517 	/*
5518 	 * Without nr_cpus_avail the sample CPU bounds check in
5519 	 * perf_session__deliver_event() is bypassed, allowing crafted
5520 	 * CPU IDs to reach downstream consumers that index fixed-size
5521 	 * arrays (timechart, kwork, sched — all sized MAX_NR_CPUS).
5522 	 *
5523 	 * This can happen with truncated files (interrupted recording
5524 	 * loses all feature sections), very old files that predate
5525 	 * HEADER_NRCPUS, or crafted files that omit it.  Fall back to
5526 	 * MAX_NR_CPUS so the bounds check is still effective — any
5527 	 * CPU ID below that limit is safe for all downstream arrays.
5528 	 */
5529 	if (header->env.nr_cpus_avail == 0) {
5530 		header->env.nr_cpus_avail = MAX_NR_CPUS;
5531 		pr_warning("WARNING: perf.data is missing HEADER_NRCPUS, using MAX_NR_CPUS (%d) as CPU bound\n",
5532 			   MAX_NR_CPUS);
5533 	}
5534 
5535 	return 0;
5536 out_errno:
5537 	return -errno;
5538 
5539 out_put_evlist:
5540 	evlist__put(session->evlist);
5541 	session->evlist = NULL;
5542 	return err;
5543 }
5544 
5545 int perf_event__process_feature(const struct perf_tool *tool __maybe_unused,
5546 				struct perf_session *session,
5547 				union perf_event *event)
5548 {
5549 	struct feat_fd ff = { .fd = 0 };
5550 	struct perf_record_header_feature *fe = (struct perf_record_header_feature *)event;
5551 	struct perf_header *header = &session->header;
5552 	int type = fe->header.type;
5553 	int feat = (int)fe->feat_id;
5554 	int ret = 0;
5555 	bool print = dump_trace;
5556 	bool last_feature_mark = false;
5557 
5558 	if (type < 0 || type >= PERF_RECORD_HEADER_MAX) {
5559 		pr_warning("invalid record type %d in pipe-mode\n", type);
5560 		return 0;
5561 	}
5562 	if (feat == HEADER_RESERVED) {
5563 		pr_warning("invalid reserved record type in pipe-mode\n");
5564 		return -1;
5565 	}
5566 	if (feat < 0 || feat == INT_MAX) {
5567 		pr_warning("invalid value for feature type %x\n", feat);
5568 		return -1;
5569 	}
5570 	if (feat >= header->last_feat) {
5571 		if (event->header.size == sizeof(*fe)) {
5572 			/*
5573 			 * Either an unexpected zero size feature or the
5574 			 * HEADER_LAST_FEATURE mark.
5575 			 */
5576 			if (feat > header->last_feat)
5577 				header->last_feat = min(feat, HEADER_LAST_FEATURE);
5578 			last_feature_mark = true;
5579 		} else {
5580 			/*
5581 			 * A feature but beyond what is known as in
5582 			 * bounds. Assume the last feature is 1 beyond this
5583 			 * feature.
5584 			 */
5585 			session->header.last_feat = min(feat + 1, HEADER_LAST_FEATURE);
5586 		}
5587 	}
5588 	if (feat >= HEADER_LAST_FEATURE) {
5589 		if (!last_feature_mark) {
5590 			pr_warning("unknown feature %d for data file version (%s) in this version of perf (%s)\n",
5591 				   feat, header->env.version, perf_version_string);
5592 		}
5593 		return 0;
5594 	}
5595 	if (event->header.size < sizeof(*fe)) {
5596 		pr_warning("feature header size too small\n");
5597 		return -1;
5598 	}
5599 	ff.buf  = (void *)fe->data;
5600 	ff.size = event->header.size - sizeof(*fe);
5601 	ff.ph = header;
5602 
5603 	if (feat_ops[feat].process && feat_ops[feat].process(&ff, NULL)) {
5604 		// Processing failed, ignore when this is the last feature mark.
5605 		if (!last_feature_mark)
5606 			ret = -1;
5607 		goto out;
5608 	}
5609 
5610 	if (session->tool->show_feat_hdr) {
5611 		if (!feat_ops[feat].full_only ||
5612 		    session->tool->show_feat_hdr >= SHOW_FEAT_HEADER_FULL_INFO) {
5613 			print = true;
5614 		} else {
5615 			fprintf(stdout, "# %s info available, use -I to display\n",
5616 				feat_ops[feat].name);
5617 		}
5618 	}
5619 
5620 	if (dump_trace)
5621 		printf(", ");
5622 
5623 	if (print) {
5624 		if (feat_ops[feat].print)
5625 			feat_ops[feat].print(&ff, stdout);
5626 		else
5627 			printf("# %s", feat_ops[feat].name);
5628 	}
5629 
5630 out:
5631 	free_event_desc(ff.events);
5632 	return ret;
5633 }
5634 
5635 size_t perf_event__fprintf_event_update(union perf_event *event, FILE *fp)
5636 {
5637 	struct perf_record_event_update *ev = &event->event_update;
5638 	struct perf_cpu_map *map;
5639 	size_t ret;
5640 
5641 	ret = fprintf(fp, "\n... id:    %" PRI_lu64 "\n", ev->id);
5642 
5643 	switch (ev->type) {
5644 	case PERF_EVENT_UPDATE__SCALE:
5645 		if (event->header.size < offsetof(struct perf_record_event_update, scale) +
5646 					 sizeof(ev->scale)) {
5647 			ret += fprintf(fp, "... scale: (truncated)\n");
5648 			break;
5649 		}
5650 		ret += fprintf(fp, "... scale: %f\n", ev->scale.scale);
5651 		break;
5652 	case PERF_EVENT_UPDATE__UNIT:
5653 	case PERF_EVENT_UPDATE__NAME: {
5654 		size_t str_off = offsetof(struct perf_record_event_update, unit);
5655 		size_t max_len = event->header.size > str_off ?
5656 				 event->header.size - str_off : 0;
5657 
5658 		if (max_len == 0 || strnlen(ev->unit, max_len) == max_len) {
5659 			ret += fprintf(fp, "... %s: (unterminated)\n",
5660 				       ev->type == PERF_EVENT_UPDATE__UNIT ? "unit" : "name");
5661 			break;
5662 		}
5663 		ret += fprintf(fp, "... %s:  %s\n",
5664 			       ev->type == PERF_EVENT_UPDATE__UNIT ? "unit" : "name",
5665 			       ev->unit);
5666 		break;
5667 	}
5668 	case PERF_EVENT_UPDATE__CPUS: {
5669 		size_t cpus_off = offsetof(struct perf_record_event_update, cpus);
5670 		u32 cpus_payload;
5671 
5672 		if (event->header.size < cpus_off + sizeof(__u16) +
5673 					 sizeof(struct perf_record_range_cpu_map)) {
5674 			ret += fprintf(fp, "... cpus: (truncated)\n");
5675 			break;
5676 		}
5677 
5678 		/*
5679 		 * Validate nr against payload — this function may be
5680 		 * called from the stub handler (dump_trace path) which
5681 		 * bypasses perf_event__process_event_update() validation.
5682 		 */
5683 		cpus_payload = event->header.size - cpus_off;
5684 		if (ev->cpus.cpus.type == PERF_CPU_MAP__CPUS) {
5685 			if (cpus_payload < offsetof(struct perf_record_cpu_map_data, cpus_data.cpu) ||
5686 			    ev->cpus.cpus.cpus_data.nr >
5687 			    (cpus_payload - offsetof(struct perf_record_cpu_map_data, cpus_data.cpu)) /
5688 			    sizeof(ev->cpus.cpus.cpus_data.cpu[0])) {
5689 				ret += fprintf(fp, "... cpus: nr %u exceeds payload\n",
5690 					       ev->cpus.cpus.cpus_data.nr);
5691 				break;
5692 			}
5693 		} else if (ev->cpus.cpus.type == PERF_CPU_MAP__MASK) {
5694 			if (ev->cpus.cpus.mask32_data.long_size == 4) {
5695 				if (cpus_payload < offsetof(struct perf_record_cpu_map_data, mask32_data.mask) ||
5696 				    ev->cpus.cpus.mask32_data.nr >
5697 				    (cpus_payload - offsetof(struct perf_record_cpu_map_data, mask32_data.mask)) /
5698 				    sizeof(ev->cpus.cpus.mask32_data.mask[0])) {
5699 					ret += fprintf(fp, "... cpus: mask nr %u exceeds payload\n",
5700 						       ev->cpus.cpus.mask32_data.nr);
5701 					break;
5702 				}
5703 			} else if (ev->cpus.cpus.mask64_data.long_size == 8) {
5704 				if (cpus_payload < offsetof(struct perf_record_cpu_map_data, mask64_data.mask) ||
5705 				    ev->cpus.cpus.mask64_data.nr >
5706 				    (cpus_payload - offsetof(struct perf_record_cpu_map_data, mask64_data.mask)) /
5707 				    sizeof(ev->cpus.cpus.mask64_data.mask[0])) {
5708 					ret += fprintf(fp, "... cpus: mask nr %u exceeds payload\n",
5709 						       ev->cpus.cpus.mask64_data.nr);
5710 					break;
5711 				}
5712 			}
5713 		}
5714 
5715 		ret += fprintf(fp, "... ");
5716 
5717 		map = cpu_map__new_data(&ev->cpus.cpus);
5718 		if (map) {
5719 			ret += cpu_map__fprintf(map, fp);
5720 			perf_cpu_map__put(map);
5721 		} else
5722 			ret += fprintf(fp, "failed to get cpus\n");
5723 		break;
5724 	}
5725 	default:
5726 		ret += fprintf(fp, "... unknown type\n");
5727 		break;
5728 	}
5729 
5730 	return ret;
5731 }
5732 
5733 size_t perf_event__fprintf_attr(union perf_event *event, FILE *fp)
5734 {
5735 	return perf_event_attr__fprintf(fp, &event->attr.attr, __desc_attr__fprintf, NULL);
5736 }
5737 
5738 int perf_event__process_attr(const struct perf_tool *tool __maybe_unused,
5739 			     union perf_event *event,
5740 			     struct evlist **pevlist)
5741 {
5742 	struct perf_event_attr attr;
5743 	u32 i, n_ids, raw_attr_size;
5744 	u64 *ids;
5745 	size_t attr_size, copy_size;
5746 	struct evsel *evsel;
5747 	struct evlist *evlist = *pevlist;
5748 
5749 	/*
5750 	 * HEADER_ATTR event layout (pipe/inject mode):
5751 	 *
5752 	 *   [header (8 bytes)] [attr (attr_size bytes)] [id0 id1 ... idN]
5753 	 *   |<------------------ header.size --------------------------->|
5754 	 *
5755 	 * attr_size varies across perf versions: VER0 = 64 bytes,
5756 	 * current sizeof(struct perf_event_attr) = larger.  A newer
5757 	 * producer may emit a larger attr than we understand.
5758 	 *
5759 	 * attr.size == 0 (ABI0) means the producer didn't set it
5760 	 * (e.g., bench/inject-buildid, older perf).  Treat as VER0.
5761 	 *
5762 	 * Require 8-byte alignment so the u64 ID array is aligned
5763 	 * and attr.size fits cleanly within the payload.
5764 	 *
5765 	 * Read attr.size once — the event may be on a shared mmap
5766 	 * and re-reading could yield a different value.
5767 	 */
5768 	raw_attr_size = event->attr.attr.size;
5769 	if (event->header.size < sizeof(event->header) + PERF_ATTR_SIZE_VER0 ||
5770 	    (raw_attr_size && (raw_attr_size < PERF_ATTR_SIZE_VER0 ||
5771 			      raw_attr_size % sizeof(u64) ||
5772 			      raw_attr_size > event->header.size - sizeof(event->header)))) {
5773 		pr_err("PERF_RECORD_HEADER_ATTR: invalid attr.size %u (event size %u, min %d)\n",
5774 		       raw_attr_size, event->header.size, PERF_ATTR_SIZE_VER0);
5775 		return -EINVAL;
5776 	}
5777 
5778 	if (dump_trace)
5779 		perf_event__fprintf_attr(event, stdout);
5780 
5781 	if (evlist == NULL) {
5782 		*pevlist = evlist = evlist__new();
5783 		if (evlist == NULL)
5784 			return -ENOMEM;
5785 	}
5786 
5787 	/*
5788 	 * attr_size = footprint of the attr in the event — determines
5789 	 * where the ID array starts.  For ABI0, assume VER0 (64 bytes).
5790 	 *
5791 	 * copy_size = how much we copy into our local struct, capped at
5792 	 * sizeof(attr) so a newer producer's larger attr doesn't
5793 	 * overflow.  Fields beyond copy_size are zeroed.
5794 	 *
5795 	 * Do NOT write attr_size back to the event — native-endian
5796 	 * files use MAP_SHARED (read-only), writing would SIGSEGV.
5797 	 * The swap path handles ABI0 in perf_event__attr_swap()
5798 	 * which writes to the writable MAP_PRIVATE copy instead.
5799 	 */
5800 	attr_size = raw_attr_size ?: PERF_ATTR_SIZE_VER0;
5801 	copy_size = min(attr_size, sizeof(attr));
5802 	memcpy(&attr, &event->attr.attr, copy_size);
5803 	if (copy_size < sizeof(attr))
5804 		memset((void *)&attr + copy_size, 0, sizeof(attr) - copy_size);
5805 
5806 	/*
5807 	 * Normalize ABI0: the swap path sets attr.size = VER0 on the
5808 	 * event, but the native path leaves it as 0.  Set it on the
5809 	 * local copy so perf inject re-synthesizes with consistent
5810 	 * layout regardless of endianness.
5811 	 */
5812 	attr.size = attr_size;
5813 
5814 	evsel = evsel__new(&attr);
5815 	if (evsel == NULL)
5816 		return -ENOMEM;
5817 
5818 	evlist__add(evlist, evsel);
5819 
5820 	/*
5821 	 * IDs occupy the remainder after header + attr.  Use attr_size
5822 	 * (not copy_size) — even if the producer's attr is larger than
5823 	 * our struct, the IDs start after attr_size bytes in the event.
5824 	 * Validation above guarantees attr_size <= payload size.
5825 	 */
5826 	n_ids = event->header.size - sizeof(event->header) - attr_size;
5827 	n_ids = n_ids / sizeof(u64);
5828 	/*
5829 	 * We don't have the cpu and thread maps on the header, so
5830 	 * for allocating the perf_sample_id table we fake 1 cpu and
5831 	 * hattr->ids threads.
5832 	 */
5833 	if (perf_evsel__alloc_id(&evsel->core, 1, n_ids))
5834 		return -ENOMEM;
5835 
5836 	/*
5837 	 * Locate IDs at attr_size bytes past the attr start in the
5838 	 * event.  Cannot use perf_record_header_attr_id() — that
5839 	 * macro reads event->attr.attr.size, which is 0 for ABI0
5840 	 * on the native-endian path (no swap handler to fix it up).
5841 	 */
5842 	ids = (void *)&event->attr.attr + attr_size;
5843 	for (i = 0; i < n_ids; i++) {
5844 		perf_evlist__id_add(evlist__core(evlist), &evsel->core, 0, i, ids[i]);
5845 	}
5846 
5847 	return 0;
5848 }
5849 
5850 int perf_event__process_event_update(const struct perf_tool *tool __maybe_unused,
5851 				     union perf_event *event,
5852 				     struct evlist **pevlist)
5853 {
5854 	struct perf_record_event_update *ev = &event->event_update;
5855 	struct evlist *evlist;
5856 	struct evsel *evsel;
5857 	struct perf_cpu_map *map;
5858 
5859 	/*
5860 	 * Validate payload before dump_trace or processing — both
5861 	 * paths access variant-specific fields without further checks.
5862 	 */
5863 	if (ev->type == PERF_EVENT_UPDATE__UNIT ||
5864 	    ev->type == PERF_EVENT_UPDATE__NAME) {
5865 		size_t str_off = offsetof(struct perf_record_event_update, unit);
5866 		size_t max_len = event->header.size > str_off ?
5867 				 event->header.size - str_off : 0;
5868 
5869 		if (max_len == 0 || strnlen(ev->unit, max_len) == max_len) {
5870 			pr_warning("WARNING: PERF_RECORD_EVENT_UPDATE: %s not null-terminated, skipping\n",
5871 				   ev->type == PERF_EVENT_UPDATE__UNIT ? "unit" : "name");
5872 			return 0;
5873 		}
5874 	} else if (ev->type == PERF_EVENT_UPDATE__SCALE) {
5875 		if (event->header.size < offsetof(struct perf_record_event_update, scale) +
5876 					 sizeof(ev->scale)) {
5877 			pr_warning("WARNING: PERF_RECORD_EVENT_UPDATE: SCALE payload too small, skipping\n");
5878 			return 0;
5879 		}
5880 	} else if (ev->type == PERF_EVENT_UPDATE__CPUS) {
5881 		size_t cpus_off = offsetof(struct perf_record_event_update, cpus);
5882 		size_t min_cpus = sizeof(__u16) +
5883 				  sizeof(struct perf_record_range_cpu_map);
5884 		u32 cpus_payload;
5885 
5886 		if (event->header.size < cpus_off + min_cpus) {
5887 			pr_warning("WARNING: PERF_RECORD_EVENT_UPDATE: CPUS payload too small, skipping\n");
5888 			return 0;
5889 		}
5890 
5891 		/*
5892 		 * Validate per-variant nr against the remaining
5893 		 * payload on the native path — the swap path clamps
5894 		 * nr in perf_event__event_update_swap(), but native
5895 		 * events are read-only and cannot be clamped in place.
5896 		 * cpu_map__new_data() trusts nr for allocation and
5897 		 * iteration, so unchecked values cause OOB reads.
5898 		 */
5899 		cpus_payload = event->header.size - cpus_off;
5900 		switch (ev->cpus.cpus.type) {
5901 		case PERF_CPU_MAP__CPUS:
5902 			if (ev->cpus.cpus.cpus_data.nr >
5903 			    (cpus_payload - offsetof(struct perf_record_cpu_map_data, cpus_data.cpu)) /
5904 			    sizeof(ev->cpus.cpus.cpus_data.cpu[0])) {
5905 				pr_warning("WARNING: EVENT_UPDATE CPUS: nr %u exceeds payload, skipping\n",
5906 					   ev->cpus.cpus.cpus_data.nr);
5907 				return 0;
5908 			}
5909 			break;
5910 		case PERF_CPU_MAP__MASK:
5911 			if (ev->cpus.cpus.mask32_data.long_size == 4) {
5912 				if (cpus_payload < offsetof(struct perf_record_cpu_map_data, mask32_data.mask) ||
5913 				    ev->cpus.cpus.mask32_data.nr >
5914 				    (cpus_payload - offsetof(struct perf_record_cpu_map_data, mask32_data.mask)) /
5915 				    sizeof(ev->cpus.cpus.mask32_data.mask[0])) {
5916 					pr_warning("WARNING: EVENT_UPDATE MASK: nr %u exceeds payload, skipping\n",
5917 						   ev->cpus.cpus.mask32_data.nr);
5918 					return 0;
5919 				}
5920 			} else if (ev->cpus.cpus.mask64_data.long_size == 8) {
5921 				if (cpus_payload < offsetof(struct perf_record_cpu_map_data, mask64_data.mask) ||
5922 				    ev->cpus.cpus.mask64_data.nr >
5923 				    (cpus_payload - offsetof(struct perf_record_cpu_map_data, mask64_data.mask)) /
5924 				    sizeof(ev->cpus.cpus.mask64_data.mask[0])) {
5925 					pr_warning("WARNING: EVENT_UPDATE MASK: nr %u exceeds payload, skipping\n",
5926 						   ev->cpus.cpus.mask64_data.nr);
5927 					return 0;
5928 				}
5929 			}
5930 			break;
5931 		default:
5932 			break;
5933 		}
5934 	}
5935 
5936 	if (dump_trace)
5937 		perf_event__fprintf_event_update(event, stdout);
5938 
5939 	if (!pevlist || *pevlist == NULL)
5940 		return -EINVAL;
5941 
5942 	evlist = *pevlist;
5943 
5944 	evsel = evlist__id2evsel(evlist, ev->id);
5945 	if (evsel == NULL)
5946 		return -EINVAL;
5947 
5948 	switch (ev->type) {
5949 	case PERF_EVENT_UPDATE__UNIT:
5950 		free((char *)evsel->unit);
5951 		evsel->unit = strdup(ev->unit);
5952 		break;
5953 	case PERF_EVENT_UPDATE__NAME:
5954 		free(evsel->name);
5955 		evsel->name = strdup(ev->name);
5956 		break;
5957 	case PERF_EVENT_UPDATE__SCALE:
5958 		evsel->scale = ev->scale.scale;
5959 		break;
5960 	case PERF_EVENT_UPDATE__CPUS:
5961 		map = cpu_map__new_data(&ev->cpus.cpus);
5962 		if (map) {
5963 			perf_cpu_map__put(evsel->core.pmu_cpus);
5964 			evsel->core.pmu_cpus = map;
5965 		} else
5966 			pr_err("failed to get event_update cpus\n");
5967 		break;
5968 	default:
5969 		break;
5970 	}
5971 
5972 	return 0;
5973 }
5974 
5975 #ifdef HAVE_LIBTRACEEVENT
5976 int perf_event__process_tracing_data(const struct perf_tool *tool __maybe_unused,
5977 				     struct perf_session *session,
5978 				     union perf_event *event)
5979 {
5980 	ssize_t size_read, padding, size = event->tracing_data.size;
5981 	int fd = perf_data__fd(session->data);
5982 	char buf[BUFSIZ];
5983 
5984 	/*
5985 	 * The pipe fd is already in proper place and in any case
5986 	 * we can't move it, and we'd screw the case where we read
5987 	 * 'pipe' data from regular file. The trace_report reads
5988 	 * data from 'fd' so we need to set it directly behind the
5989 	 * event, where the tracing data starts.
5990 	 */
5991 	if (!perf_data__is_pipe(session->data)) {
5992 		off_t offset = lseek(fd, 0, SEEK_CUR);
5993 
5994 		/* setup for reading amidst mmap */
5995 		lseek(fd, offset + sizeof(struct perf_record_header_tracing_data),
5996 		      SEEK_SET);
5997 	}
5998 
5999 	size_read = trace_report(fd, &session->tevent, session->trace_event_repipe);
6000 	padding = PERF_ALIGN(size_read, sizeof(u64)) - size_read;
6001 
6002 	if (readn(fd, buf, padding) < 0) {
6003 		pr_err("%s: reading input file", __func__);
6004 		return -1;
6005 	}
6006 	if (session->trace_event_repipe) {
6007 		int retw = write(STDOUT_FILENO, buf, padding);
6008 		if (retw <= 0 || retw != padding) {
6009 			pr_err("%s: repiping tracing data padding", __func__);
6010 			return -1;
6011 		}
6012 	}
6013 
6014 	if (size_read + padding != size) {
6015 		pr_err("%s: tracing data size mismatch", __func__);
6016 		return -1;
6017 	}
6018 
6019 	evlist__prepare_tracepoint_events(session->evlist, session->tevent.pevent);
6020 
6021 	return size_read + padding;
6022 }
6023 #endif
6024 
6025 int perf_event__process_build_id(const struct perf_tool *tool __maybe_unused,
6026 				 struct perf_session *session,
6027 				 union perf_event *event)
6028 {
6029 	__event_process_build_id(&event->build_id,
6030 				 event->build_id.filename,
6031 				 session);
6032 	return 0;
6033 }
6034