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