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