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