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