xref: /openbmc/linux/tools/perf/util/header.c (revision 0da85d1e)
1 #include "util.h"
2 #include <sys/types.h>
3 #include <byteswap.h>
4 #include <unistd.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <linux/list.h>
8 #include <linux/kernel.h>
9 #include <linux/bitops.h>
10 #include <sys/utsname.h>
11 
12 #include "evlist.h"
13 #include "evsel.h"
14 #include "header.h"
15 #include "../perf.h"
16 #include "trace-event.h"
17 #include "session.h"
18 #include "symbol.h"
19 #include "debug.h"
20 #include "cpumap.h"
21 #include "pmu.h"
22 #include "vdso.h"
23 #include "strbuf.h"
24 #include "build-id.h"
25 #include "data.h"
26 
27 static u32 header_argc;
28 static const char **header_argv;
29 
30 /*
31  * magic2 = "PERFILE2"
32  * must be a numerical value to let the endianness
33  * determine the memory layout. That way we are able
34  * to detect endianness when reading the perf.data file
35  * back.
36  *
37  * we check for legacy (PERFFILE) format.
38  */
39 static const char *__perf_magic1 = "PERFFILE";
40 static const u64 __perf_magic2    = 0x32454c4946524550ULL;
41 static const u64 __perf_magic2_sw = 0x50455246494c4532ULL;
42 
43 #define PERF_MAGIC	__perf_magic2
44 
45 struct perf_file_attr {
46 	struct perf_event_attr	attr;
47 	struct perf_file_section	ids;
48 };
49 
50 void perf_header__set_feat(struct perf_header *header, int feat)
51 {
52 	set_bit(feat, header->adds_features);
53 }
54 
55 void perf_header__clear_feat(struct perf_header *header, int feat)
56 {
57 	clear_bit(feat, header->adds_features);
58 }
59 
60 bool perf_header__has_feat(const struct perf_header *header, int feat)
61 {
62 	return test_bit(feat, header->adds_features);
63 }
64 
65 static int do_write(int fd, const void *buf, size_t size)
66 {
67 	while (size) {
68 		int ret = write(fd, buf, size);
69 
70 		if (ret < 0)
71 			return -errno;
72 
73 		size -= ret;
74 		buf += ret;
75 	}
76 
77 	return 0;
78 }
79 
80 int write_padded(int fd, const void *bf, size_t count, size_t count_aligned)
81 {
82 	static const char zero_buf[NAME_ALIGN];
83 	int err = do_write(fd, bf, count);
84 
85 	if (!err)
86 		err = do_write(fd, zero_buf, count_aligned - count);
87 
88 	return err;
89 }
90 
91 static int do_write_string(int fd, const char *str)
92 {
93 	u32 len, olen;
94 	int ret;
95 
96 	olen = strlen(str) + 1;
97 	len = PERF_ALIGN(olen, NAME_ALIGN);
98 
99 	/* write len, incl. \0 */
100 	ret = do_write(fd, &len, sizeof(len));
101 	if (ret < 0)
102 		return ret;
103 
104 	return write_padded(fd, str, olen, len);
105 }
106 
107 static char *do_read_string(int fd, struct perf_header *ph)
108 {
109 	ssize_t sz, ret;
110 	u32 len;
111 	char *buf;
112 
113 	sz = readn(fd, &len, sizeof(len));
114 	if (sz < (ssize_t)sizeof(len))
115 		return NULL;
116 
117 	if (ph->needs_swap)
118 		len = bswap_32(len);
119 
120 	buf = malloc(len);
121 	if (!buf)
122 		return NULL;
123 
124 	ret = readn(fd, buf, len);
125 	if (ret == (ssize_t)len) {
126 		/*
127 		 * strings are padded by zeroes
128 		 * thus the actual strlen of buf
129 		 * may be less than len
130 		 */
131 		return buf;
132 	}
133 
134 	free(buf);
135 	return NULL;
136 }
137 
138 int
139 perf_header__set_cmdline(int argc, const char **argv)
140 {
141 	int i;
142 
143 	/*
144 	 * If header_argv has already been set, do not override it.
145 	 * This allows a command to set the cmdline, parse args and
146 	 * then call another builtin function that implements a
147 	 * command -- e.g, cmd_kvm calling cmd_record.
148 	 */
149 	if (header_argv)
150 		return 0;
151 
152 	header_argc = (u32)argc;
153 
154 	/* do not include NULL termination */
155 	header_argv = calloc(argc, sizeof(char *));
156 	if (!header_argv)
157 		return -ENOMEM;
158 
159 	/*
160 	 * must copy argv contents because it gets moved
161 	 * around during option parsing
162 	 */
163 	for (i = 0; i < argc ; i++)
164 		header_argv[i] = argv[i];
165 
166 	return 0;
167 }
168 
169 static int write_tracing_data(int fd, struct perf_header *h __maybe_unused,
170 			    struct perf_evlist *evlist)
171 {
172 	return read_tracing_data(fd, &evlist->entries);
173 }
174 
175 
176 static int write_build_id(int fd, struct perf_header *h,
177 			  struct perf_evlist *evlist __maybe_unused)
178 {
179 	struct perf_session *session;
180 	int err;
181 
182 	session = container_of(h, struct perf_session, header);
183 
184 	if (!perf_session__read_build_ids(session, true))
185 		return -1;
186 
187 	err = perf_session__write_buildid_table(session, fd);
188 	if (err < 0) {
189 		pr_debug("failed to write buildid table\n");
190 		return err;
191 	}
192 	perf_session__cache_build_ids(session);
193 
194 	return 0;
195 }
196 
197 static int write_hostname(int fd, struct perf_header *h __maybe_unused,
198 			  struct perf_evlist *evlist __maybe_unused)
199 {
200 	struct utsname uts;
201 	int ret;
202 
203 	ret = uname(&uts);
204 	if (ret < 0)
205 		return -1;
206 
207 	return do_write_string(fd, uts.nodename);
208 }
209 
210 static int write_osrelease(int fd, struct perf_header *h __maybe_unused,
211 			   struct perf_evlist *evlist __maybe_unused)
212 {
213 	struct utsname uts;
214 	int ret;
215 
216 	ret = uname(&uts);
217 	if (ret < 0)
218 		return -1;
219 
220 	return do_write_string(fd, uts.release);
221 }
222 
223 static int write_arch(int fd, struct perf_header *h __maybe_unused,
224 		      struct perf_evlist *evlist __maybe_unused)
225 {
226 	struct utsname uts;
227 	int ret;
228 
229 	ret = uname(&uts);
230 	if (ret < 0)
231 		return -1;
232 
233 	return do_write_string(fd, uts.machine);
234 }
235 
236 static int write_version(int fd, struct perf_header *h __maybe_unused,
237 			 struct perf_evlist *evlist __maybe_unused)
238 {
239 	return do_write_string(fd, perf_version_string);
240 }
241 
242 static int __write_cpudesc(int fd, const char *cpuinfo_proc)
243 {
244 	FILE *file;
245 	char *buf = NULL;
246 	char *s, *p;
247 	const char *search = cpuinfo_proc;
248 	size_t len = 0;
249 	int ret = -1;
250 
251 	if (!search)
252 		return -1;
253 
254 	file = fopen("/proc/cpuinfo", "r");
255 	if (!file)
256 		return -1;
257 
258 	while (getline(&buf, &len, file) > 0) {
259 		ret = strncmp(buf, search, strlen(search));
260 		if (!ret)
261 			break;
262 	}
263 
264 	if (ret) {
265 		ret = -1;
266 		goto done;
267 	}
268 
269 	s = buf;
270 
271 	p = strchr(buf, ':');
272 	if (p && *(p+1) == ' ' && *(p+2))
273 		s = p + 2;
274 	p = strchr(s, '\n');
275 	if (p)
276 		*p = '\0';
277 
278 	/* squash extra space characters (branding string) */
279 	p = s;
280 	while (*p) {
281 		if (isspace(*p)) {
282 			char *r = p + 1;
283 			char *q = r;
284 			*p = ' ';
285 			while (*q && isspace(*q))
286 				q++;
287 			if (q != (p+1))
288 				while ((*r++ = *q++));
289 		}
290 		p++;
291 	}
292 	ret = do_write_string(fd, s);
293 done:
294 	free(buf);
295 	fclose(file);
296 	return ret;
297 }
298 
299 static int write_cpudesc(int fd, struct perf_header *h __maybe_unused,
300 		       struct perf_evlist *evlist __maybe_unused)
301 {
302 #ifndef CPUINFO_PROC
303 #define CPUINFO_PROC {"model name", }
304 #endif
305 	const char *cpuinfo_procs[] = CPUINFO_PROC;
306 	unsigned int i;
307 
308 	for (i = 0; i < ARRAY_SIZE(cpuinfo_procs); i++) {
309 		int ret;
310 		ret = __write_cpudesc(fd, cpuinfo_procs[i]);
311 		if (ret >= 0)
312 			return ret;
313 	}
314 	return -1;
315 }
316 
317 
318 static int write_nrcpus(int fd, struct perf_header *h __maybe_unused,
319 			struct perf_evlist *evlist __maybe_unused)
320 {
321 	long nr;
322 	u32 nrc, nra;
323 	int ret;
324 
325 	nr = sysconf(_SC_NPROCESSORS_CONF);
326 	if (nr < 0)
327 		return -1;
328 
329 	nrc = (u32)(nr & UINT_MAX);
330 
331 	nr = sysconf(_SC_NPROCESSORS_ONLN);
332 	if (nr < 0)
333 		return -1;
334 
335 	nra = (u32)(nr & UINT_MAX);
336 
337 	ret = do_write(fd, &nrc, sizeof(nrc));
338 	if (ret < 0)
339 		return ret;
340 
341 	return do_write(fd, &nra, sizeof(nra));
342 }
343 
344 static int write_event_desc(int fd, struct perf_header *h __maybe_unused,
345 			    struct perf_evlist *evlist)
346 {
347 	struct perf_evsel *evsel;
348 	u32 nre, nri, sz;
349 	int ret;
350 
351 	nre = evlist->nr_entries;
352 
353 	/*
354 	 * write number of events
355 	 */
356 	ret = do_write(fd, &nre, sizeof(nre));
357 	if (ret < 0)
358 		return ret;
359 
360 	/*
361 	 * size of perf_event_attr struct
362 	 */
363 	sz = (u32)sizeof(evsel->attr);
364 	ret = do_write(fd, &sz, sizeof(sz));
365 	if (ret < 0)
366 		return ret;
367 
368 	evlist__for_each(evlist, evsel) {
369 		ret = do_write(fd, &evsel->attr, sz);
370 		if (ret < 0)
371 			return ret;
372 		/*
373 		 * write number of unique id per event
374 		 * there is one id per instance of an event
375 		 *
376 		 * copy into an nri to be independent of the
377 		 * type of ids,
378 		 */
379 		nri = evsel->ids;
380 		ret = do_write(fd, &nri, sizeof(nri));
381 		if (ret < 0)
382 			return ret;
383 
384 		/*
385 		 * write event string as passed on cmdline
386 		 */
387 		ret = do_write_string(fd, perf_evsel__name(evsel));
388 		if (ret < 0)
389 			return ret;
390 		/*
391 		 * write unique ids for this event
392 		 */
393 		ret = do_write(fd, evsel->id, evsel->ids * sizeof(u64));
394 		if (ret < 0)
395 			return ret;
396 	}
397 	return 0;
398 }
399 
400 static int write_cmdline(int fd, struct perf_header *h __maybe_unused,
401 			 struct perf_evlist *evlist __maybe_unused)
402 {
403 	char buf[MAXPATHLEN];
404 	char proc[32];
405 	u32 i, n;
406 	int ret;
407 
408 	/*
409 	 * actual atual path to perf binary
410 	 */
411 	sprintf(proc, "/proc/%d/exe", getpid());
412 	ret = readlink(proc, buf, sizeof(buf));
413 	if (ret <= 0)
414 		return -1;
415 
416 	/* readlink() does not add null termination */
417 	buf[ret] = '\0';
418 
419 	/* account for binary path */
420 	n = header_argc + 1;
421 
422 	ret = do_write(fd, &n, sizeof(n));
423 	if (ret < 0)
424 		return ret;
425 
426 	ret = do_write_string(fd, buf);
427 	if (ret < 0)
428 		return ret;
429 
430 	for (i = 0 ; i < header_argc; i++) {
431 		ret = do_write_string(fd, header_argv[i]);
432 		if (ret < 0)
433 			return ret;
434 	}
435 	return 0;
436 }
437 
438 #define CORE_SIB_FMT \
439 	"/sys/devices/system/cpu/cpu%d/topology/core_siblings_list"
440 #define THRD_SIB_FMT \
441 	"/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list"
442 
443 struct cpu_topo {
444 	u32 core_sib;
445 	u32 thread_sib;
446 	char **core_siblings;
447 	char **thread_siblings;
448 };
449 
450 static int build_cpu_topo(struct cpu_topo *tp, int cpu)
451 {
452 	FILE *fp;
453 	char filename[MAXPATHLEN];
454 	char *buf = NULL, *p;
455 	size_t len = 0;
456 	ssize_t sret;
457 	u32 i = 0;
458 	int ret = -1;
459 
460 	sprintf(filename, CORE_SIB_FMT, cpu);
461 	fp = fopen(filename, "r");
462 	if (!fp)
463 		goto try_threads;
464 
465 	sret = getline(&buf, &len, fp);
466 	fclose(fp);
467 	if (sret <= 0)
468 		goto try_threads;
469 
470 	p = strchr(buf, '\n');
471 	if (p)
472 		*p = '\0';
473 
474 	for (i = 0; i < tp->core_sib; i++) {
475 		if (!strcmp(buf, tp->core_siblings[i]))
476 			break;
477 	}
478 	if (i == tp->core_sib) {
479 		tp->core_siblings[i] = buf;
480 		tp->core_sib++;
481 		buf = NULL;
482 		len = 0;
483 	}
484 	ret = 0;
485 
486 try_threads:
487 	sprintf(filename, THRD_SIB_FMT, cpu);
488 	fp = fopen(filename, "r");
489 	if (!fp)
490 		goto done;
491 
492 	if (getline(&buf, &len, fp) <= 0)
493 		goto done;
494 
495 	p = strchr(buf, '\n');
496 	if (p)
497 		*p = '\0';
498 
499 	for (i = 0; i < tp->thread_sib; i++) {
500 		if (!strcmp(buf, tp->thread_siblings[i]))
501 			break;
502 	}
503 	if (i == tp->thread_sib) {
504 		tp->thread_siblings[i] = buf;
505 		tp->thread_sib++;
506 		buf = NULL;
507 	}
508 	ret = 0;
509 done:
510 	if(fp)
511 		fclose(fp);
512 	free(buf);
513 	return ret;
514 }
515 
516 static void free_cpu_topo(struct cpu_topo *tp)
517 {
518 	u32 i;
519 
520 	if (!tp)
521 		return;
522 
523 	for (i = 0 ; i < tp->core_sib; i++)
524 		zfree(&tp->core_siblings[i]);
525 
526 	for (i = 0 ; i < tp->thread_sib; i++)
527 		zfree(&tp->thread_siblings[i]);
528 
529 	free(tp);
530 }
531 
532 static struct cpu_topo *build_cpu_topology(void)
533 {
534 	struct cpu_topo *tp;
535 	void *addr;
536 	u32 nr, i;
537 	size_t sz;
538 	long ncpus;
539 	int ret = -1;
540 
541 	ncpus = sysconf(_SC_NPROCESSORS_CONF);
542 	if (ncpus < 0)
543 		return NULL;
544 
545 	nr = (u32)(ncpus & UINT_MAX);
546 
547 	sz = nr * sizeof(char *);
548 
549 	addr = calloc(1, sizeof(*tp) + 2 * sz);
550 	if (!addr)
551 		return NULL;
552 
553 	tp = addr;
554 
555 	addr += sizeof(*tp);
556 	tp->core_siblings = addr;
557 	addr += sz;
558 	tp->thread_siblings = addr;
559 
560 	for (i = 0; i < nr; i++) {
561 		ret = build_cpu_topo(tp, i);
562 		if (ret < 0)
563 			break;
564 	}
565 	if (ret) {
566 		free_cpu_topo(tp);
567 		tp = NULL;
568 	}
569 	return tp;
570 }
571 
572 static int write_cpu_topology(int fd, struct perf_header *h __maybe_unused,
573 			  struct perf_evlist *evlist __maybe_unused)
574 {
575 	struct cpu_topo *tp;
576 	u32 i;
577 	int ret;
578 
579 	tp = build_cpu_topology();
580 	if (!tp)
581 		return -1;
582 
583 	ret = do_write(fd, &tp->core_sib, sizeof(tp->core_sib));
584 	if (ret < 0)
585 		goto done;
586 
587 	for (i = 0; i < tp->core_sib; i++) {
588 		ret = do_write_string(fd, tp->core_siblings[i]);
589 		if (ret < 0)
590 			goto done;
591 	}
592 	ret = do_write(fd, &tp->thread_sib, sizeof(tp->thread_sib));
593 	if (ret < 0)
594 		goto done;
595 
596 	for (i = 0; i < tp->thread_sib; i++) {
597 		ret = do_write_string(fd, tp->thread_siblings[i]);
598 		if (ret < 0)
599 			break;
600 	}
601 done:
602 	free_cpu_topo(tp);
603 	return ret;
604 }
605 
606 
607 
608 static int write_total_mem(int fd, struct perf_header *h __maybe_unused,
609 			  struct perf_evlist *evlist __maybe_unused)
610 {
611 	char *buf = NULL;
612 	FILE *fp;
613 	size_t len = 0;
614 	int ret = -1, n;
615 	uint64_t mem;
616 
617 	fp = fopen("/proc/meminfo", "r");
618 	if (!fp)
619 		return -1;
620 
621 	while (getline(&buf, &len, fp) > 0) {
622 		ret = strncmp(buf, "MemTotal:", 9);
623 		if (!ret)
624 			break;
625 	}
626 	if (!ret) {
627 		n = sscanf(buf, "%*s %"PRIu64, &mem);
628 		if (n == 1)
629 			ret = do_write(fd, &mem, sizeof(mem));
630 	} else
631 		ret = -1;
632 	free(buf);
633 	fclose(fp);
634 	return ret;
635 }
636 
637 static int write_topo_node(int fd, int node)
638 {
639 	char str[MAXPATHLEN];
640 	char field[32];
641 	char *buf = NULL, *p;
642 	size_t len = 0;
643 	FILE *fp;
644 	u64 mem_total, mem_free, mem;
645 	int ret = -1;
646 
647 	sprintf(str, "/sys/devices/system/node/node%d/meminfo", node);
648 	fp = fopen(str, "r");
649 	if (!fp)
650 		return -1;
651 
652 	while (getline(&buf, &len, fp) > 0) {
653 		/* skip over invalid lines */
654 		if (!strchr(buf, ':'))
655 			continue;
656 		if (sscanf(buf, "%*s %*d %31s %"PRIu64, field, &mem) != 2)
657 			goto done;
658 		if (!strcmp(field, "MemTotal:"))
659 			mem_total = mem;
660 		if (!strcmp(field, "MemFree:"))
661 			mem_free = mem;
662 	}
663 
664 	fclose(fp);
665 	fp = NULL;
666 
667 	ret = do_write(fd, &mem_total, sizeof(u64));
668 	if (ret)
669 		goto done;
670 
671 	ret = do_write(fd, &mem_free, sizeof(u64));
672 	if (ret)
673 		goto done;
674 
675 	ret = -1;
676 	sprintf(str, "/sys/devices/system/node/node%d/cpulist", node);
677 
678 	fp = fopen(str, "r");
679 	if (!fp)
680 		goto done;
681 
682 	if (getline(&buf, &len, fp) <= 0)
683 		goto done;
684 
685 	p = strchr(buf, '\n');
686 	if (p)
687 		*p = '\0';
688 
689 	ret = do_write_string(fd, buf);
690 done:
691 	free(buf);
692 	if (fp)
693 		fclose(fp);
694 	return ret;
695 }
696 
697 static int write_numa_topology(int fd, struct perf_header *h __maybe_unused,
698 			  struct perf_evlist *evlist __maybe_unused)
699 {
700 	char *buf = NULL;
701 	size_t len = 0;
702 	FILE *fp;
703 	struct cpu_map *node_map = NULL;
704 	char *c;
705 	u32 nr, i, j;
706 	int ret = -1;
707 
708 	fp = fopen("/sys/devices/system/node/online", "r");
709 	if (!fp)
710 		return -1;
711 
712 	if (getline(&buf, &len, fp) <= 0)
713 		goto done;
714 
715 	c = strchr(buf, '\n');
716 	if (c)
717 		*c = '\0';
718 
719 	node_map = cpu_map__new(buf);
720 	if (!node_map)
721 		goto done;
722 
723 	nr = (u32)node_map->nr;
724 
725 	ret = do_write(fd, &nr, sizeof(nr));
726 	if (ret < 0)
727 		goto done;
728 
729 	for (i = 0; i < nr; i++) {
730 		j = (u32)node_map->map[i];
731 		ret = do_write(fd, &j, sizeof(j));
732 		if (ret < 0)
733 			break;
734 
735 		ret = write_topo_node(fd, i);
736 		if (ret < 0)
737 			break;
738 	}
739 done:
740 	free(buf);
741 	fclose(fp);
742 	free(node_map);
743 	return ret;
744 }
745 
746 /*
747  * File format:
748  *
749  * struct pmu_mappings {
750  *	u32	pmu_num;
751  *	struct pmu_map {
752  *		u32	type;
753  *		char	name[];
754  *	}[pmu_num];
755  * };
756  */
757 
758 static int write_pmu_mappings(int fd, struct perf_header *h __maybe_unused,
759 			      struct perf_evlist *evlist __maybe_unused)
760 {
761 	struct perf_pmu *pmu = NULL;
762 	off_t offset = lseek(fd, 0, SEEK_CUR);
763 	__u32 pmu_num = 0;
764 	int ret;
765 
766 	/* write real pmu_num later */
767 	ret = do_write(fd, &pmu_num, sizeof(pmu_num));
768 	if (ret < 0)
769 		return ret;
770 
771 	while ((pmu = perf_pmu__scan(pmu))) {
772 		if (!pmu->name)
773 			continue;
774 		pmu_num++;
775 
776 		ret = do_write(fd, &pmu->type, sizeof(pmu->type));
777 		if (ret < 0)
778 			return ret;
779 
780 		ret = do_write_string(fd, pmu->name);
781 		if (ret < 0)
782 			return ret;
783 	}
784 
785 	if (pwrite(fd, &pmu_num, sizeof(pmu_num), offset) != sizeof(pmu_num)) {
786 		/* discard all */
787 		lseek(fd, offset, SEEK_SET);
788 		return -1;
789 	}
790 
791 	return 0;
792 }
793 
794 /*
795  * File format:
796  *
797  * struct group_descs {
798  *	u32	nr_groups;
799  *	struct group_desc {
800  *		char	name[];
801  *		u32	leader_idx;
802  *		u32	nr_members;
803  *	}[nr_groups];
804  * };
805  */
806 static int write_group_desc(int fd, struct perf_header *h __maybe_unused,
807 			    struct perf_evlist *evlist)
808 {
809 	u32 nr_groups = evlist->nr_groups;
810 	struct perf_evsel *evsel;
811 	int ret;
812 
813 	ret = do_write(fd, &nr_groups, sizeof(nr_groups));
814 	if (ret < 0)
815 		return ret;
816 
817 	evlist__for_each(evlist, evsel) {
818 		if (perf_evsel__is_group_leader(evsel) &&
819 		    evsel->nr_members > 1) {
820 			const char *name = evsel->group_name ?: "{anon_group}";
821 			u32 leader_idx = evsel->idx;
822 			u32 nr_members = evsel->nr_members;
823 
824 			ret = do_write_string(fd, name);
825 			if (ret < 0)
826 				return ret;
827 
828 			ret = do_write(fd, &leader_idx, sizeof(leader_idx));
829 			if (ret < 0)
830 				return ret;
831 
832 			ret = do_write(fd, &nr_members, sizeof(nr_members));
833 			if (ret < 0)
834 				return ret;
835 		}
836 	}
837 	return 0;
838 }
839 
840 /*
841  * default get_cpuid(): nothing gets recorded
842  * actual implementation must be in arch/$(ARCH)/util/header.c
843  */
844 int __attribute__ ((weak)) get_cpuid(char *buffer __maybe_unused,
845 				     size_t sz __maybe_unused)
846 {
847 	return -1;
848 }
849 
850 static int write_cpuid(int fd, struct perf_header *h __maybe_unused,
851 		       struct perf_evlist *evlist __maybe_unused)
852 {
853 	char buffer[64];
854 	int ret;
855 
856 	ret = get_cpuid(buffer, sizeof(buffer));
857 	if (!ret)
858 		goto write_it;
859 
860 	return -1;
861 write_it:
862 	return do_write_string(fd, buffer);
863 }
864 
865 static int write_branch_stack(int fd __maybe_unused,
866 			      struct perf_header *h __maybe_unused,
867 		       struct perf_evlist *evlist __maybe_unused)
868 {
869 	return 0;
870 }
871 
872 static int write_auxtrace(int fd, struct perf_header *h,
873 			  struct perf_evlist *evlist __maybe_unused)
874 {
875 	struct perf_session *session;
876 	int err;
877 
878 	session = container_of(h, struct perf_session, header);
879 
880 	err = auxtrace_index__write(fd, &session->auxtrace_index);
881 	if (err < 0)
882 		pr_err("Failed to write auxtrace index\n");
883 	return err;
884 }
885 
886 static void print_hostname(struct perf_header *ph, int fd __maybe_unused,
887 			   FILE *fp)
888 {
889 	fprintf(fp, "# hostname : %s\n", ph->env.hostname);
890 }
891 
892 static void print_osrelease(struct perf_header *ph, int fd __maybe_unused,
893 			    FILE *fp)
894 {
895 	fprintf(fp, "# os release : %s\n", ph->env.os_release);
896 }
897 
898 static void print_arch(struct perf_header *ph, int fd __maybe_unused, FILE *fp)
899 {
900 	fprintf(fp, "# arch : %s\n", ph->env.arch);
901 }
902 
903 static void print_cpudesc(struct perf_header *ph, int fd __maybe_unused,
904 			  FILE *fp)
905 {
906 	fprintf(fp, "# cpudesc : %s\n", ph->env.cpu_desc);
907 }
908 
909 static void print_nrcpus(struct perf_header *ph, int fd __maybe_unused,
910 			 FILE *fp)
911 {
912 	fprintf(fp, "# nrcpus online : %u\n", ph->env.nr_cpus_online);
913 	fprintf(fp, "# nrcpus avail : %u\n", ph->env.nr_cpus_avail);
914 }
915 
916 static void print_version(struct perf_header *ph, int fd __maybe_unused,
917 			  FILE *fp)
918 {
919 	fprintf(fp, "# perf version : %s\n", ph->env.version);
920 }
921 
922 static void print_cmdline(struct perf_header *ph, int fd __maybe_unused,
923 			  FILE *fp)
924 {
925 	int nr, i;
926 	char *str;
927 
928 	nr = ph->env.nr_cmdline;
929 	str = ph->env.cmdline;
930 
931 	fprintf(fp, "# cmdline : ");
932 
933 	for (i = 0; i < nr; i++) {
934 		fprintf(fp, "%s ", str);
935 		str += strlen(str) + 1;
936 	}
937 	fputc('\n', fp);
938 }
939 
940 static void print_cpu_topology(struct perf_header *ph, int fd __maybe_unused,
941 			       FILE *fp)
942 {
943 	int nr, i;
944 	char *str;
945 
946 	nr = ph->env.nr_sibling_cores;
947 	str = ph->env.sibling_cores;
948 
949 	for (i = 0; i < nr; i++) {
950 		fprintf(fp, "# sibling cores   : %s\n", str);
951 		str += strlen(str) + 1;
952 	}
953 
954 	nr = ph->env.nr_sibling_threads;
955 	str = ph->env.sibling_threads;
956 
957 	for (i = 0; i < nr; i++) {
958 		fprintf(fp, "# sibling threads : %s\n", str);
959 		str += strlen(str) + 1;
960 	}
961 }
962 
963 static void free_event_desc(struct perf_evsel *events)
964 {
965 	struct perf_evsel *evsel;
966 
967 	if (!events)
968 		return;
969 
970 	for (evsel = events; evsel->attr.size; evsel++) {
971 		zfree(&evsel->name);
972 		zfree(&evsel->id);
973 	}
974 
975 	free(events);
976 }
977 
978 static struct perf_evsel *
979 read_event_desc(struct perf_header *ph, int fd)
980 {
981 	struct perf_evsel *evsel, *events = NULL;
982 	u64 *id;
983 	void *buf = NULL;
984 	u32 nre, sz, nr, i, j;
985 	ssize_t ret;
986 	size_t msz;
987 
988 	/* number of events */
989 	ret = readn(fd, &nre, sizeof(nre));
990 	if (ret != (ssize_t)sizeof(nre))
991 		goto error;
992 
993 	if (ph->needs_swap)
994 		nre = bswap_32(nre);
995 
996 	ret = readn(fd, &sz, sizeof(sz));
997 	if (ret != (ssize_t)sizeof(sz))
998 		goto error;
999 
1000 	if (ph->needs_swap)
1001 		sz = bswap_32(sz);
1002 
1003 	/* buffer to hold on file attr struct */
1004 	buf = malloc(sz);
1005 	if (!buf)
1006 		goto error;
1007 
1008 	/* the last event terminates with evsel->attr.size == 0: */
1009 	events = calloc(nre + 1, sizeof(*events));
1010 	if (!events)
1011 		goto error;
1012 
1013 	msz = sizeof(evsel->attr);
1014 	if (sz < msz)
1015 		msz = sz;
1016 
1017 	for (i = 0, evsel = events; i < nre; evsel++, i++) {
1018 		evsel->idx = i;
1019 
1020 		/*
1021 		 * must read entire on-file attr struct to
1022 		 * sync up with layout.
1023 		 */
1024 		ret = readn(fd, buf, sz);
1025 		if (ret != (ssize_t)sz)
1026 			goto error;
1027 
1028 		if (ph->needs_swap)
1029 			perf_event__attr_swap(buf);
1030 
1031 		memcpy(&evsel->attr, buf, msz);
1032 
1033 		ret = readn(fd, &nr, sizeof(nr));
1034 		if (ret != (ssize_t)sizeof(nr))
1035 			goto error;
1036 
1037 		if (ph->needs_swap) {
1038 			nr = bswap_32(nr);
1039 			evsel->needs_swap = true;
1040 		}
1041 
1042 		evsel->name = do_read_string(fd, ph);
1043 
1044 		if (!nr)
1045 			continue;
1046 
1047 		id = calloc(nr, sizeof(*id));
1048 		if (!id)
1049 			goto error;
1050 		evsel->ids = nr;
1051 		evsel->id = id;
1052 
1053 		for (j = 0 ; j < nr; j++) {
1054 			ret = readn(fd, id, sizeof(*id));
1055 			if (ret != (ssize_t)sizeof(*id))
1056 				goto error;
1057 			if (ph->needs_swap)
1058 				*id = bswap_64(*id);
1059 			id++;
1060 		}
1061 	}
1062 out:
1063 	free(buf);
1064 	return events;
1065 error:
1066 	if (events)
1067 		free_event_desc(events);
1068 	events = NULL;
1069 	goto out;
1070 }
1071 
1072 static int __desc_attr__fprintf(FILE *fp, const char *name, const char *val,
1073 				void *priv __attribute__((unused)))
1074 {
1075 	return fprintf(fp, ", %s = %s", name, val);
1076 }
1077 
1078 static void print_event_desc(struct perf_header *ph, int fd, FILE *fp)
1079 {
1080 	struct perf_evsel *evsel, *events = read_event_desc(ph, fd);
1081 	u32 j;
1082 	u64 *id;
1083 
1084 	if (!events) {
1085 		fprintf(fp, "# event desc: not available or unable to read\n");
1086 		return;
1087 	}
1088 
1089 	for (evsel = events; evsel->attr.size; evsel++) {
1090 		fprintf(fp, "# event : name = %s, ", evsel->name);
1091 
1092 		if (evsel->ids) {
1093 			fprintf(fp, ", id = {");
1094 			for (j = 0, id = evsel->id; j < evsel->ids; j++, id++) {
1095 				if (j)
1096 					fputc(',', fp);
1097 				fprintf(fp, " %"PRIu64, *id);
1098 			}
1099 			fprintf(fp, " }");
1100 		}
1101 
1102 		perf_event_attr__fprintf(fp, &evsel->attr, __desc_attr__fprintf, NULL);
1103 
1104 		fputc('\n', fp);
1105 	}
1106 
1107 	free_event_desc(events);
1108 }
1109 
1110 static void print_total_mem(struct perf_header *ph, int fd __maybe_unused,
1111 			    FILE *fp)
1112 {
1113 	fprintf(fp, "# total memory : %Lu kB\n", ph->env.total_mem);
1114 }
1115 
1116 static void print_numa_topology(struct perf_header *ph, int fd __maybe_unused,
1117 				FILE *fp)
1118 {
1119 	u32 nr, c, i;
1120 	char *str, *tmp;
1121 	uint64_t mem_total, mem_free;
1122 
1123 	/* nr nodes */
1124 	nr = ph->env.nr_numa_nodes;
1125 	str = ph->env.numa_nodes;
1126 
1127 	for (i = 0; i < nr; i++) {
1128 		/* node number */
1129 		c = strtoul(str, &tmp, 0);
1130 		if (*tmp != ':')
1131 			goto error;
1132 
1133 		str = tmp + 1;
1134 		mem_total = strtoull(str, &tmp, 0);
1135 		if (*tmp != ':')
1136 			goto error;
1137 
1138 		str = tmp + 1;
1139 		mem_free = strtoull(str, &tmp, 0);
1140 		if (*tmp != ':')
1141 			goto error;
1142 
1143 		fprintf(fp, "# node%u meminfo  : total = %"PRIu64" kB,"
1144 			    " free = %"PRIu64" kB\n",
1145 			c, mem_total, mem_free);
1146 
1147 		str = tmp + 1;
1148 		fprintf(fp, "# node%u cpu list : %s\n", c, str);
1149 
1150 		str += strlen(str) + 1;
1151 	}
1152 	return;
1153 error:
1154 	fprintf(fp, "# numa topology : not available\n");
1155 }
1156 
1157 static void print_cpuid(struct perf_header *ph, int fd __maybe_unused, FILE *fp)
1158 {
1159 	fprintf(fp, "# cpuid : %s\n", ph->env.cpuid);
1160 }
1161 
1162 static void print_branch_stack(struct perf_header *ph __maybe_unused,
1163 			       int fd __maybe_unused, FILE *fp)
1164 {
1165 	fprintf(fp, "# contains samples with branch stack\n");
1166 }
1167 
1168 static void print_auxtrace(struct perf_header *ph __maybe_unused,
1169 			   int fd __maybe_unused, FILE *fp)
1170 {
1171 	fprintf(fp, "# contains AUX area data (e.g. instruction trace)\n");
1172 }
1173 
1174 static void print_pmu_mappings(struct perf_header *ph, int fd __maybe_unused,
1175 			       FILE *fp)
1176 {
1177 	const char *delimiter = "# pmu mappings: ";
1178 	char *str, *tmp;
1179 	u32 pmu_num;
1180 	u32 type;
1181 
1182 	pmu_num = ph->env.nr_pmu_mappings;
1183 	if (!pmu_num) {
1184 		fprintf(fp, "# pmu mappings: not available\n");
1185 		return;
1186 	}
1187 
1188 	str = ph->env.pmu_mappings;
1189 
1190 	while (pmu_num) {
1191 		type = strtoul(str, &tmp, 0);
1192 		if (*tmp != ':')
1193 			goto error;
1194 
1195 		str = tmp + 1;
1196 		fprintf(fp, "%s%s = %" PRIu32, delimiter, str, type);
1197 
1198 		delimiter = ", ";
1199 		str += strlen(str) + 1;
1200 		pmu_num--;
1201 	}
1202 
1203 	fprintf(fp, "\n");
1204 
1205 	if (!pmu_num)
1206 		return;
1207 error:
1208 	fprintf(fp, "# pmu mappings: unable to read\n");
1209 }
1210 
1211 static void print_group_desc(struct perf_header *ph, int fd __maybe_unused,
1212 			     FILE *fp)
1213 {
1214 	struct perf_session *session;
1215 	struct perf_evsel *evsel;
1216 	u32 nr = 0;
1217 
1218 	session = container_of(ph, struct perf_session, header);
1219 
1220 	evlist__for_each(session->evlist, evsel) {
1221 		if (perf_evsel__is_group_leader(evsel) &&
1222 		    evsel->nr_members > 1) {
1223 			fprintf(fp, "# group: %s{%s", evsel->group_name ?: "",
1224 				perf_evsel__name(evsel));
1225 
1226 			nr = evsel->nr_members - 1;
1227 		} else if (nr) {
1228 			fprintf(fp, ",%s", perf_evsel__name(evsel));
1229 
1230 			if (--nr == 0)
1231 				fprintf(fp, "}\n");
1232 		}
1233 	}
1234 }
1235 
1236 static int __event_process_build_id(struct build_id_event *bev,
1237 				    char *filename,
1238 				    struct perf_session *session)
1239 {
1240 	int err = -1;
1241 	struct dsos *dsos;
1242 	struct machine *machine;
1243 	u16 misc;
1244 	struct dso *dso;
1245 	enum dso_kernel_type dso_type;
1246 
1247 	machine = perf_session__findnew_machine(session, bev->pid);
1248 	if (!machine)
1249 		goto out;
1250 
1251 	misc = bev->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
1252 
1253 	switch (misc) {
1254 	case PERF_RECORD_MISC_KERNEL:
1255 		dso_type = DSO_TYPE_KERNEL;
1256 		dsos = &machine->kernel_dsos;
1257 		break;
1258 	case PERF_RECORD_MISC_GUEST_KERNEL:
1259 		dso_type = DSO_TYPE_GUEST_KERNEL;
1260 		dsos = &machine->kernel_dsos;
1261 		break;
1262 	case PERF_RECORD_MISC_USER:
1263 	case PERF_RECORD_MISC_GUEST_USER:
1264 		dso_type = DSO_TYPE_USER;
1265 		dsos = &machine->user_dsos;
1266 		break;
1267 	default:
1268 		goto out;
1269 	}
1270 
1271 	dso = __dsos__findnew(dsos, filename);
1272 	if (dso != NULL) {
1273 		char sbuild_id[BUILD_ID_SIZE * 2 + 1];
1274 
1275 		dso__set_build_id(dso, &bev->build_id);
1276 
1277 		if (!is_kernel_module(filename))
1278 			dso->kernel = dso_type;
1279 
1280 		build_id__sprintf(dso->build_id, sizeof(dso->build_id),
1281 				  sbuild_id);
1282 		pr_debug("build id event received for %s: %s\n",
1283 			 dso->long_name, sbuild_id);
1284 	}
1285 
1286 	err = 0;
1287 out:
1288 	return err;
1289 }
1290 
1291 static int perf_header__read_build_ids_abi_quirk(struct perf_header *header,
1292 						 int input, u64 offset, u64 size)
1293 {
1294 	struct perf_session *session = container_of(header, struct perf_session, header);
1295 	struct {
1296 		struct perf_event_header   header;
1297 		u8			   build_id[PERF_ALIGN(BUILD_ID_SIZE, sizeof(u64))];
1298 		char			   filename[0];
1299 	} old_bev;
1300 	struct build_id_event bev;
1301 	char filename[PATH_MAX];
1302 	u64 limit = offset + size;
1303 
1304 	while (offset < limit) {
1305 		ssize_t len;
1306 
1307 		if (readn(input, &old_bev, sizeof(old_bev)) != sizeof(old_bev))
1308 			return -1;
1309 
1310 		if (header->needs_swap)
1311 			perf_event_header__bswap(&old_bev.header);
1312 
1313 		len = old_bev.header.size - sizeof(old_bev);
1314 		if (readn(input, filename, len) != len)
1315 			return -1;
1316 
1317 		bev.header = old_bev.header;
1318 
1319 		/*
1320 		 * As the pid is the missing value, we need to fill
1321 		 * it properly. The header.misc value give us nice hint.
1322 		 */
1323 		bev.pid	= HOST_KERNEL_ID;
1324 		if (bev.header.misc == PERF_RECORD_MISC_GUEST_USER ||
1325 		    bev.header.misc == PERF_RECORD_MISC_GUEST_KERNEL)
1326 			bev.pid	= DEFAULT_GUEST_KERNEL_ID;
1327 
1328 		memcpy(bev.build_id, old_bev.build_id, sizeof(bev.build_id));
1329 		__event_process_build_id(&bev, filename, session);
1330 
1331 		offset += bev.header.size;
1332 	}
1333 
1334 	return 0;
1335 }
1336 
1337 static int perf_header__read_build_ids(struct perf_header *header,
1338 				       int input, u64 offset, u64 size)
1339 {
1340 	struct perf_session *session = container_of(header, struct perf_session, header);
1341 	struct build_id_event bev;
1342 	char filename[PATH_MAX];
1343 	u64 limit = offset + size, orig_offset = offset;
1344 	int err = -1;
1345 
1346 	while (offset < limit) {
1347 		ssize_t len;
1348 
1349 		if (readn(input, &bev, sizeof(bev)) != sizeof(bev))
1350 			goto out;
1351 
1352 		if (header->needs_swap)
1353 			perf_event_header__bswap(&bev.header);
1354 
1355 		len = bev.header.size - sizeof(bev);
1356 		if (readn(input, filename, len) != len)
1357 			goto out;
1358 		/*
1359 		 * The a1645ce1 changeset:
1360 		 *
1361 		 * "perf: 'perf kvm' tool for monitoring guest performance from host"
1362 		 *
1363 		 * Added a field to struct build_id_event that broke the file
1364 		 * format.
1365 		 *
1366 		 * Since the kernel build-id is the first entry, process the
1367 		 * table using the old format if the well known
1368 		 * '[kernel.kallsyms]' string for the kernel build-id has the
1369 		 * first 4 characters chopped off (where the pid_t sits).
1370 		 */
1371 		if (memcmp(filename, "nel.kallsyms]", 13) == 0) {
1372 			if (lseek(input, orig_offset, SEEK_SET) == (off_t)-1)
1373 				return -1;
1374 			return perf_header__read_build_ids_abi_quirk(header, input, offset, size);
1375 		}
1376 
1377 		__event_process_build_id(&bev, filename, session);
1378 
1379 		offset += bev.header.size;
1380 	}
1381 	err = 0;
1382 out:
1383 	return err;
1384 }
1385 
1386 static int process_tracing_data(struct perf_file_section *section __maybe_unused,
1387 				struct perf_header *ph __maybe_unused,
1388 				int fd, void *data)
1389 {
1390 	ssize_t ret = trace_report(fd, data, false);
1391 	return ret < 0 ? -1 : 0;
1392 }
1393 
1394 static int process_build_id(struct perf_file_section *section,
1395 			    struct perf_header *ph, int fd,
1396 			    void *data __maybe_unused)
1397 {
1398 	if (perf_header__read_build_ids(ph, fd, section->offset, section->size))
1399 		pr_debug("Failed to read buildids, continuing...\n");
1400 	return 0;
1401 }
1402 
1403 static int process_hostname(struct perf_file_section *section __maybe_unused,
1404 			    struct perf_header *ph, int fd,
1405 			    void *data __maybe_unused)
1406 {
1407 	ph->env.hostname = do_read_string(fd, ph);
1408 	return ph->env.hostname ? 0 : -ENOMEM;
1409 }
1410 
1411 static int process_osrelease(struct perf_file_section *section __maybe_unused,
1412 			     struct perf_header *ph, int fd,
1413 			     void *data __maybe_unused)
1414 {
1415 	ph->env.os_release = do_read_string(fd, ph);
1416 	return ph->env.os_release ? 0 : -ENOMEM;
1417 }
1418 
1419 static int process_version(struct perf_file_section *section __maybe_unused,
1420 			   struct perf_header *ph, int fd,
1421 			   void *data __maybe_unused)
1422 {
1423 	ph->env.version = do_read_string(fd, ph);
1424 	return ph->env.version ? 0 : -ENOMEM;
1425 }
1426 
1427 static int process_arch(struct perf_file_section *section __maybe_unused,
1428 			struct perf_header *ph,	int fd,
1429 			void *data __maybe_unused)
1430 {
1431 	ph->env.arch = do_read_string(fd, ph);
1432 	return ph->env.arch ? 0 : -ENOMEM;
1433 }
1434 
1435 static int process_nrcpus(struct perf_file_section *section __maybe_unused,
1436 			  struct perf_header *ph, int fd,
1437 			  void *data __maybe_unused)
1438 {
1439 	ssize_t ret;
1440 	u32 nr;
1441 
1442 	ret = readn(fd, &nr, sizeof(nr));
1443 	if (ret != sizeof(nr))
1444 		return -1;
1445 
1446 	if (ph->needs_swap)
1447 		nr = bswap_32(nr);
1448 
1449 	ph->env.nr_cpus_online = nr;
1450 
1451 	ret = readn(fd, &nr, sizeof(nr));
1452 	if (ret != sizeof(nr))
1453 		return -1;
1454 
1455 	if (ph->needs_swap)
1456 		nr = bswap_32(nr);
1457 
1458 	ph->env.nr_cpus_avail = nr;
1459 	return 0;
1460 }
1461 
1462 static int process_cpudesc(struct perf_file_section *section __maybe_unused,
1463 			   struct perf_header *ph, int fd,
1464 			   void *data __maybe_unused)
1465 {
1466 	ph->env.cpu_desc = do_read_string(fd, ph);
1467 	return ph->env.cpu_desc ? 0 : -ENOMEM;
1468 }
1469 
1470 static int process_cpuid(struct perf_file_section *section __maybe_unused,
1471 			 struct perf_header *ph,  int fd,
1472 			 void *data __maybe_unused)
1473 {
1474 	ph->env.cpuid = do_read_string(fd, ph);
1475 	return ph->env.cpuid ? 0 : -ENOMEM;
1476 }
1477 
1478 static int process_total_mem(struct perf_file_section *section __maybe_unused,
1479 			     struct perf_header *ph, int fd,
1480 			     void *data __maybe_unused)
1481 {
1482 	uint64_t mem;
1483 	ssize_t ret;
1484 
1485 	ret = readn(fd, &mem, sizeof(mem));
1486 	if (ret != sizeof(mem))
1487 		return -1;
1488 
1489 	if (ph->needs_swap)
1490 		mem = bswap_64(mem);
1491 
1492 	ph->env.total_mem = mem;
1493 	return 0;
1494 }
1495 
1496 static struct perf_evsel *
1497 perf_evlist__find_by_index(struct perf_evlist *evlist, int idx)
1498 {
1499 	struct perf_evsel *evsel;
1500 
1501 	evlist__for_each(evlist, evsel) {
1502 		if (evsel->idx == idx)
1503 			return evsel;
1504 	}
1505 
1506 	return NULL;
1507 }
1508 
1509 static void
1510 perf_evlist__set_event_name(struct perf_evlist *evlist,
1511 			    struct perf_evsel *event)
1512 {
1513 	struct perf_evsel *evsel;
1514 
1515 	if (!event->name)
1516 		return;
1517 
1518 	evsel = perf_evlist__find_by_index(evlist, event->idx);
1519 	if (!evsel)
1520 		return;
1521 
1522 	if (evsel->name)
1523 		return;
1524 
1525 	evsel->name = strdup(event->name);
1526 }
1527 
1528 static int
1529 process_event_desc(struct perf_file_section *section __maybe_unused,
1530 		   struct perf_header *header, int fd,
1531 		   void *data __maybe_unused)
1532 {
1533 	struct perf_session *session;
1534 	struct perf_evsel *evsel, *events = read_event_desc(header, fd);
1535 
1536 	if (!events)
1537 		return 0;
1538 
1539 	session = container_of(header, struct perf_session, header);
1540 	for (evsel = events; evsel->attr.size; evsel++)
1541 		perf_evlist__set_event_name(session->evlist, evsel);
1542 
1543 	free_event_desc(events);
1544 
1545 	return 0;
1546 }
1547 
1548 static int process_cmdline(struct perf_file_section *section __maybe_unused,
1549 			   struct perf_header *ph, int fd,
1550 			   void *data __maybe_unused)
1551 {
1552 	ssize_t ret;
1553 	char *str;
1554 	u32 nr, i;
1555 	struct strbuf sb;
1556 
1557 	ret = readn(fd, &nr, sizeof(nr));
1558 	if (ret != sizeof(nr))
1559 		return -1;
1560 
1561 	if (ph->needs_swap)
1562 		nr = bswap_32(nr);
1563 
1564 	ph->env.nr_cmdline = nr;
1565 	strbuf_init(&sb, 128);
1566 
1567 	for (i = 0; i < nr; i++) {
1568 		str = do_read_string(fd, ph);
1569 		if (!str)
1570 			goto error;
1571 
1572 		/* include a NULL character at the end */
1573 		strbuf_add(&sb, str, strlen(str) + 1);
1574 		free(str);
1575 	}
1576 	ph->env.cmdline = strbuf_detach(&sb, NULL);
1577 	return 0;
1578 
1579 error:
1580 	strbuf_release(&sb);
1581 	return -1;
1582 }
1583 
1584 static int process_cpu_topology(struct perf_file_section *section __maybe_unused,
1585 				struct perf_header *ph, int fd,
1586 				void *data __maybe_unused)
1587 {
1588 	ssize_t ret;
1589 	u32 nr, i;
1590 	char *str;
1591 	struct strbuf sb;
1592 
1593 	ret = readn(fd, &nr, sizeof(nr));
1594 	if (ret != sizeof(nr))
1595 		return -1;
1596 
1597 	if (ph->needs_swap)
1598 		nr = bswap_32(nr);
1599 
1600 	ph->env.nr_sibling_cores = nr;
1601 	strbuf_init(&sb, 128);
1602 
1603 	for (i = 0; i < nr; i++) {
1604 		str = do_read_string(fd, ph);
1605 		if (!str)
1606 			goto error;
1607 
1608 		/* include a NULL character at the end */
1609 		strbuf_add(&sb, str, strlen(str) + 1);
1610 		free(str);
1611 	}
1612 	ph->env.sibling_cores = strbuf_detach(&sb, NULL);
1613 
1614 	ret = readn(fd, &nr, sizeof(nr));
1615 	if (ret != sizeof(nr))
1616 		return -1;
1617 
1618 	if (ph->needs_swap)
1619 		nr = bswap_32(nr);
1620 
1621 	ph->env.nr_sibling_threads = nr;
1622 
1623 	for (i = 0; i < nr; i++) {
1624 		str = do_read_string(fd, ph);
1625 		if (!str)
1626 			goto error;
1627 
1628 		/* include a NULL character at the end */
1629 		strbuf_add(&sb, str, strlen(str) + 1);
1630 		free(str);
1631 	}
1632 	ph->env.sibling_threads = strbuf_detach(&sb, NULL);
1633 	return 0;
1634 
1635 error:
1636 	strbuf_release(&sb);
1637 	return -1;
1638 }
1639 
1640 static int process_numa_topology(struct perf_file_section *section __maybe_unused,
1641 				 struct perf_header *ph, int fd,
1642 				 void *data __maybe_unused)
1643 {
1644 	ssize_t ret;
1645 	u32 nr, node, i;
1646 	char *str;
1647 	uint64_t mem_total, mem_free;
1648 	struct strbuf sb;
1649 
1650 	/* nr nodes */
1651 	ret = readn(fd, &nr, sizeof(nr));
1652 	if (ret != sizeof(nr))
1653 		goto error;
1654 
1655 	if (ph->needs_swap)
1656 		nr = bswap_32(nr);
1657 
1658 	ph->env.nr_numa_nodes = nr;
1659 	strbuf_init(&sb, 256);
1660 
1661 	for (i = 0; i < nr; i++) {
1662 		/* node number */
1663 		ret = readn(fd, &node, sizeof(node));
1664 		if (ret != sizeof(node))
1665 			goto error;
1666 
1667 		ret = readn(fd, &mem_total, sizeof(u64));
1668 		if (ret != sizeof(u64))
1669 			goto error;
1670 
1671 		ret = readn(fd, &mem_free, sizeof(u64));
1672 		if (ret != sizeof(u64))
1673 			goto error;
1674 
1675 		if (ph->needs_swap) {
1676 			node = bswap_32(node);
1677 			mem_total = bswap_64(mem_total);
1678 			mem_free = bswap_64(mem_free);
1679 		}
1680 
1681 		strbuf_addf(&sb, "%u:%"PRIu64":%"PRIu64":",
1682 			    node, mem_total, mem_free);
1683 
1684 		str = do_read_string(fd, ph);
1685 		if (!str)
1686 			goto error;
1687 
1688 		/* include a NULL character at the end */
1689 		strbuf_add(&sb, str, strlen(str) + 1);
1690 		free(str);
1691 	}
1692 	ph->env.numa_nodes = strbuf_detach(&sb, NULL);
1693 	return 0;
1694 
1695 error:
1696 	strbuf_release(&sb);
1697 	return -1;
1698 }
1699 
1700 static int process_pmu_mappings(struct perf_file_section *section __maybe_unused,
1701 				struct perf_header *ph, int fd,
1702 				void *data __maybe_unused)
1703 {
1704 	ssize_t ret;
1705 	char *name;
1706 	u32 pmu_num;
1707 	u32 type;
1708 	struct strbuf sb;
1709 
1710 	ret = readn(fd, &pmu_num, sizeof(pmu_num));
1711 	if (ret != sizeof(pmu_num))
1712 		return -1;
1713 
1714 	if (ph->needs_swap)
1715 		pmu_num = bswap_32(pmu_num);
1716 
1717 	if (!pmu_num) {
1718 		pr_debug("pmu mappings not available\n");
1719 		return 0;
1720 	}
1721 
1722 	ph->env.nr_pmu_mappings = pmu_num;
1723 	strbuf_init(&sb, 128);
1724 
1725 	while (pmu_num) {
1726 		if (readn(fd, &type, sizeof(type)) != sizeof(type))
1727 			goto error;
1728 		if (ph->needs_swap)
1729 			type = bswap_32(type);
1730 
1731 		name = do_read_string(fd, ph);
1732 		if (!name)
1733 			goto error;
1734 
1735 		strbuf_addf(&sb, "%u:%s", type, name);
1736 		/* include a NULL character at the end */
1737 		strbuf_add(&sb, "", 1);
1738 
1739 		free(name);
1740 		pmu_num--;
1741 	}
1742 	ph->env.pmu_mappings = strbuf_detach(&sb, NULL);
1743 	return 0;
1744 
1745 error:
1746 	strbuf_release(&sb);
1747 	return -1;
1748 }
1749 
1750 static int process_group_desc(struct perf_file_section *section __maybe_unused,
1751 			      struct perf_header *ph, int fd,
1752 			      void *data __maybe_unused)
1753 {
1754 	size_t ret = -1;
1755 	u32 i, nr, nr_groups;
1756 	struct perf_session *session;
1757 	struct perf_evsel *evsel, *leader = NULL;
1758 	struct group_desc {
1759 		char *name;
1760 		u32 leader_idx;
1761 		u32 nr_members;
1762 	} *desc;
1763 
1764 	if (readn(fd, &nr_groups, sizeof(nr_groups)) != sizeof(nr_groups))
1765 		return -1;
1766 
1767 	if (ph->needs_swap)
1768 		nr_groups = bswap_32(nr_groups);
1769 
1770 	ph->env.nr_groups = nr_groups;
1771 	if (!nr_groups) {
1772 		pr_debug("group desc not available\n");
1773 		return 0;
1774 	}
1775 
1776 	desc = calloc(nr_groups, sizeof(*desc));
1777 	if (!desc)
1778 		return -1;
1779 
1780 	for (i = 0; i < nr_groups; i++) {
1781 		desc[i].name = do_read_string(fd, ph);
1782 		if (!desc[i].name)
1783 			goto out_free;
1784 
1785 		if (readn(fd, &desc[i].leader_idx, sizeof(u32)) != sizeof(u32))
1786 			goto out_free;
1787 
1788 		if (readn(fd, &desc[i].nr_members, sizeof(u32)) != sizeof(u32))
1789 			goto out_free;
1790 
1791 		if (ph->needs_swap) {
1792 			desc[i].leader_idx = bswap_32(desc[i].leader_idx);
1793 			desc[i].nr_members = bswap_32(desc[i].nr_members);
1794 		}
1795 	}
1796 
1797 	/*
1798 	 * Rebuild group relationship based on the group_desc
1799 	 */
1800 	session = container_of(ph, struct perf_session, header);
1801 	session->evlist->nr_groups = nr_groups;
1802 
1803 	i = nr = 0;
1804 	evlist__for_each(session->evlist, evsel) {
1805 		if (evsel->idx == (int) desc[i].leader_idx) {
1806 			evsel->leader = evsel;
1807 			/* {anon_group} is a dummy name */
1808 			if (strcmp(desc[i].name, "{anon_group}")) {
1809 				evsel->group_name = desc[i].name;
1810 				desc[i].name = NULL;
1811 			}
1812 			evsel->nr_members = desc[i].nr_members;
1813 
1814 			if (i >= nr_groups || nr > 0) {
1815 				pr_debug("invalid group desc\n");
1816 				goto out_free;
1817 			}
1818 
1819 			leader = evsel;
1820 			nr = evsel->nr_members - 1;
1821 			i++;
1822 		} else if (nr) {
1823 			/* This is a group member */
1824 			evsel->leader = leader;
1825 
1826 			nr--;
1827 		}
1828 	}
1829 
1830 	if (i != nr_groups || nr != 0) {
1831 		pr_debug("invalid group desc\n");
1832 		goto out_free;
1833 	}
1834 
1835 	ret = 0;
1836 out_free:
1837 	for (i = 0; i < nr_groups; i++)
1838 		zfree(&desc[i].name);
1839 	free(desc);
1840 
1841 	return ret;
1842 }
1843 
1844 static int process_auxtrace(struct perf_file_section *section,
1845 			    struct perf_header *ph, int fd,
1846 			    void *data __maybe_unused)
1847 {
1848 	struct perf_session *session;
1849 	int err;
1850 
1851 	session = container_of(ph, struct perf_session, header);
1852 
1853 	err = auxtrace_index__process(fd, section->size, session,
1854 				      ph->needs_swap);
1855 	if (err < 0)
1856 		pr_err("Failed to process auxtrace index\n");
1857 	return err;
1858 }
1859 
1860 struct feature_ops {
1861 	int (*write)(int fd, struct perf_header *h, struct perf_evlist *evlist);
1862 	void (*print)(struct perf_header *h, int fd, FILE *fp);
1863 	int (*process)(struct perf_file_section *section,
1864 		       struct perf_header *h, int fd, void *data);
1865 	const char *name;
1866 	bool full_only;
1867 };
1868 
1869 #define FEAT_OPA(n, func) \
1870 	[n] = { .name = #n, .write = write_##func, .print = print_##func }
1871 #define FEAT_OPP(n, func) \
1872 	[n] = { .name = #n, .write = write_##func, .print = print_##func, \
1873 		.process = process_##func }
1874 #define FEAT_OPF(n, func) \
1875 	[n] = { .name = #n, .write = write_##func, .print = print_##func, \
1876 		.process = process_##func, .full_only = true }
1877 
1878 /* feature_ops not implemented: */
1879 #define print_tracing_data	NULL
1880 #define print_build_id		NULL
1881 
1882 static const struct feature_ops feat_ops[HEADER_LAST_FEATURE] = {
1883 	FEAT_OPP(HEADER_TRACING_DATA,	tracing_data),
1884 	FEAT_OPP(HEADER_BUILD_ID,	build_id),
1885 	FEAT_OPP(HEADER_HOSTNAME,	hostname),
1886 	FEAT_OPP(HEADER_OSRELEASE,	osrelease),
1887 	FEAT_OPP(HEADER_VERSION,	version),
1888 	FEAT_OPP(HEADER_ARCH,		arch),
1889 	FEAT_OPP(HEADER_NRCPUS,		nrcpus),
1890 	FEAT_OPP(HEADER_CPUDESC,	cpudesc),
1891 	FEAT_OPP(HEADER_CPUID,		cpuid),
1892 	FEAT_OPP(HEADER_TOTAL_MEM,	total_mem),
1893 	FEAT_OPP(HEADER_EVENT_DESC,	event_desc),
1894 	FEAT_OPP(HEADER_CMDLINE,	cmdline),
1895 	FEAT_OPF(HEADER_CPU_TOPOLOGY,	cpu_topology),
1896 	FEAT_OPF(HEADER_NUMA_TOPOLOGY,	numa_topology),
1897 	FEAT_OPA(HEADER_BRANCH_STACK,	branch_stack),
1898 	FEAT_OPP(HEADER_PMU_MAPPINGS,	pmu_mappings),
1899 	FEAT_OPP(HEADER_GROUP_DESC,	group_desc),
1900 	FEAT_OPP(HEADER_AUXTRACE,	auxtrace),
1901 };
1902 
1903 struct header_print_data {
1904 	FILE *fp;
1905 	bool full; /* extended list of headers */
1906 };
1907 
1908 static int perf_file_section__fprintf_info(struct perf_file_section *section,
1909 					   struct perf_header *ph,
1910 					   int feat, int fd, void *data)
1911 {
1912 	struct header_print_data *hd = data;
1913 
1914 	if (lseek(fd, section->offset, SEEK_SET) == (off_t)-1) {
1915 		pr_debug("Failed to lseek to %" PRIu64 " offset for feature "
1916 				"%d, continuing...\n", section->offset, feat);
1917 		return 0;
1918 	}
1919 	if (feat >= HEADER_LAST_FEATURE) {
1920 		pr_warning("unknown feature %d\n", feat);
1921 		return 0;
1922 	}
1923 	if (!feat_ops[feat].print)
1924 		return 0;
1925 
1926 	if (!feat_ops[feat].full_only || hd->full)
1927 		feat_ops[feat].print(ph, fd, hd->fp);
1928 	else
1929 		fprintf(hd->fp, "# %s info available, use -I to display\n",
1930 			feat_ops[feat].name);
1931 
1932 	return 0;
1933 }
1934 
1935 int perf_header__fprintf_info(struct perf_session *session, FILE *fp, bool full)
1936 {
1937 	struct header_print_data hd;
1938 	struct perf_header *header = &session->header;
1939 	int fd = perf_data_file__fd(session->file);
1940 	hd.fp = fp;
1941 	hd.full = full;
1942 
1943 	perf_header__process_sections(header, fd, &hd,
1944 				      perf_file_section__fprintf_info);
1945 	return 0;
1946 }
1947 
1948 static int do_write_feat(int fd, struct perf_header *h, int type,
1949 			 struct perf_file_section **p,
1950 			 struct perf_evlist *evlist)
1951 {
1952 	int err;
1953 	int ret = 0;
1954 
1955 	if (perf_header__has_feat(h, type)) {
1956 		if (!feat_ops[type].write)
1957 			return -1;
1958 
1959 		(*p)->offset = lseek(fd, 0, SEEK_CUR);
1960 
1961 		err = feat_ops[type].write(fd, h, evlist);
1962 		if (err < 0) {
1963 			pr_debug("failed to write feature %d\n", type);
1964 
1965 			/* undo anything written */
1966 			lseek(fd, (*p)->offset, SEEK_SET);
1967 
1968 			return -1;
1969 		}
1970 		(*p)->size = lseek(fd, 0, SEEK_CUR) - (*p)->offset;
1971 		(*p)++;
1972 	}
1973 	return ret;
1974 }
1975 
1976 static int perf_header__adds_write(struct perf_header *header,
1977 				   struct perf_evlist *evlist, int fd)
1978 {
1979 	int nr_sections;
1980 	struct perf_file_section *feat_sec, *p;
1981 	int sec_size;
1982 	u64 sec_start;
1983 	int feat;
1984 	int err;
1985 
1986 	nr_sections = bitmap_weight(header->adds_features, HEADER_FEAT_BITS);
1987 	if (!nr_sections)
1988 		return 0;
1989 
1990 	feat_sec = p = calloc(nr_sections, sizeof(*feat_sec));
1991 	if (feat_sec == NULL)
1992 		return -ENOMEM;
1993 
1994 	sec_size = sizeof(*feat_sec) * nr_sections;
1995 
1996 	sec_start = header->feat_offset;
1997 	lseek(fd, sec_start + sec_size, SEEK_SET);
1998 
1999 	for_each_set_bit(feat, header->adds_features, HEADER_FEAT_BITS) {
2000 		if (do_write_feat(fd, header, feat, &p, evlist))
2001 			perf_header__clear_feat(header, feat);
2002 	}
2003 
2004 	lseek(fd, sec_start, SEEK_SET);
2005 	/*
2006 	 * may write more than needed due to dropped feature, but
2007 	 * this is okay, reader will skip the mising entries
2008 	 */
2009 	err = do_write(fd, feat_sec, sec_size);
2010 	if (err < 0)
2011 		pr_debug("failed to write feature section\n");
2012 	free(feat_sec);
2013 	return err;
2014 }
2015 
2016 int perf_header__write_pipe(int fd)
2017 {
2018 	struct perf_pipe_file_header f_header;
2019 	int err;
2020 
2021 	f_header = (struct perf_pipe_file_header){
2022 		.magic	   = PERF_MAGIC,
2023 		.size	   = sizeof(f_header),
2024 	};
2025 
2026 	err = do_write(fd, &f_header, sizeof(f_header));
2027 	if (err < 0) {
2028 		pr_debug("failed to write perf pipe header\n");
2029 		return err;
2030 	}
2031 
2032 	return 0;
2033 }
2034 
2035 int perf_session__write_header(struct perf_session *session,
2036 			       struct perf_evlist *evlist,
2037 			       int fd, bool at_exit)
2038 {
2039 	struct perf_file_header f_header;
2040 	struct perf_file_attr   f_attr;
2041 	struct perf_header *header = &session->header;
2042 	struct perf_evsel *evsel;
2043 	u64 attr_offset;
2044 	int err;
2045 
2046 	lseek(fd, sizeof(f_header), SEEK_SET);
2047 
2048 	evlist__for_each(session->evlist, evsel) {
2049 		evsel->id_offset = lseek(fd, 0, SEEK_CUR);
2050 		err = do_write(fd, evsel->id, evsel->ids * sizeof(u64));
2051 		if (err < 0) {
2052 			pr_debug("failed to write perf header\n");
2053 			return err;
2054 		}
2055 	}
2056 
2057 	attr_offset = lseek(fd, 0, SEEK_CUR);
2058 
2059 	evlist__for_each(evlist, evsel) {
2060 		f_attr = (struct perf_file_attr){
2061 			.attr = evsel->attr,
2062 			.ids  = {
2063 				.offset = evsel->id_offset,
2064 				.size   = evsel->ids * sizeof(u64),
2065 			}
2066 		};
2067 		err = do_write(fd, &f_attr, sizeof(f_attr));
2068 		if (err < 0) {
2069 			pr_debug("failed to write perf header attribute\n");
2070 			return err;
2071 		}
2072 	}
2073 
2074 	if (!header->data_offset)
2075 		header->data_offset = lseek(fd, 0, SEEK_CUR);
2076 	header->feat_offset = header->data_offset + header->data_size;
2077 
2078 	if (at_exit) {
2079 		err = perf_header__adds_write(header, evlist, fd);
2080 		if (err < 0)
2081 			return err;
2082 	}
2083 
2084 	f_header = (struct perf_file_header){
2085 		.magic	   = PERF_MAGIC,
2086 		.size	   = sizeof(f_header),
2087 		.attr_size = sizeof(f_attr),
2088 		.attrs = {
2089 			.offset = attr_offset,
2090 			.size   = evlist->nr_entries * sizeof(f_attr),
2091 		},
2092 		.data = {
2093 			.offset = header->data_offset,
2094 			.size	= header->data_size,
2095 		},
2096 		/* event_types is ignored, store zeros */
2097 	};
2098 
2099 	memcpy(&f_header.adds_features, &header->adds_features, sizeof(header->adds_features));
2100 
2101 	lseek(fd, 0, SEEK_SET);
2102 	err = do_write(fd, &f_header, sizeof(f_header));
2103 	if (err < 0) {
2104 		pr_debug("failed to write perf header\n");
2105 		return err;
2106 	}
2107 	lseek(fd, header->data_offset + header->data_size, SEEK_SET);
2108 
2109 	return 0;
2110 }
2111 
2112 static int perf_header__getbuffer64(struct perf_header *header,
2113 				    int fd, void *buf, size_t size)
2114 {
2115 	if (readn(fd, buf, size) <= 0)
2116 		return -1;
2117 
2118 	if (header->needs_swap)
2119 		mem_bswap_64(buf, size);
2120 
2121 	return 0;
2122 }
2123 
2124 int perf_header__process_sections(struct perf_header *header, int fd,
2125 				  void *data,
2126 				  int (*process)(struct perf_file_section *section,
2127 						 struct perf_header *ph,
2128 						 int feat, int fd, void *data))
2129 {
2130 	struct perf_file_section *feat_sec, *sec;
2131 	int nr_sections;
2132 	int sec_size;
2133 	int feat;
2134 	int err;
2135 
2136 	nr_sections = bitmap_weight(header->adds_features, HEADER_FEAT_BITS);
2137 	if (!nr_sections)
2138 		return 0;
2139 
2140 	feat_sec = sec = calloc(nr_sections, sizeof(*feat_sec));
2141 	if (!feat_sec)
2142 		return -1;
2143 
2144 	sec_size = sizeof(*feat_sec) * nr_sections;
2145 
2146 	lseek(fd, header->feat_offset, SEEK_SET);
2147 
2148 	err = perf_header__getbuffer64(header, fd, feat_sec, sec_size);
2149 	if (err < 0)
2150 		goto out_free;
2151 
2152 	for_each_set_bit(feat, header->adds_features, HEADER_LAST_FEATURE) {
2153 		err = process(sec++, header, feat, fd, data);
2154 		if (err < 0)
2155 			goto out_free;
2156 	}
2157 	err = 0;
2158 out_free:
2159 	free(feat_sec);
2160 	return err;
2161 }
2162 
2163 static const int attr_file_abi_sizes[] = {
2164 	[0] = PERF_ATTR_SIZE_VER0,
2165 	[1] = PERF_ATTR_SIZE_VER1,
2166 	[2] = PERF_ATTR_SIZE_VER2,
2167 	[3] = PERF_ATTR_SIZE_VER3,
2168 	[4] = PERF_ATTR_SIZE_VER4,
2169 	0,
2170 };
2171 
2172 /*
2173  * In the legacy file format, the magic number is not used to encode endianness.
2174  * hdr_sz was used to encode endianness. But given that hdr_sz can vary based
2175  * on ABI revisions, we need to try all combinations for all endianness to
2176  * detect the endianness.
2177  */
2178 static int try_all_file_abis(uint64_t hdr_sz, struct perf_header *ph)
2179 {
2180 	uint64_t ref_size, attr_size;
2181 	int i;
2182 
2183 	for (i = 0 ; attr_file_abi_sizes[i]; i++) {
2184 		ref_size = attr_file_abi_sizes[i]
2185 			 + sizeof(struct perf_file_section);
2186 		if (hdr_sz != ref_size) {
2187 			attr_size = bswap_64(hdr_sz);
2188 			if (attr_size != ref_size)
2189 				continue;
2190 
2191 			ph->needs_swap = true;
2192 		}
2193 		pr_debug("ABI%d perf.data file detected, need_swap=%d\n",
2194 			 i,
2195 			 ph->needs_swap);
2196 		return 0;
2197 	}
2198 	/* could not determine endianness */
2199 	return -1;
2200 }
2201 
2202 #define PERF_PIPE_HDR_VER0	16
2203 
2204 static const size_t attr_pipe_abi_sizes[] = {
2205 	[0] = PERF_PIPE_HDR_VER0,
2206 	0,
2207 };
2208 
2209 /*
2210  * In the legacy pipe format, there is an implicit assumption that endiannesss
2211  * between host recording the samples, and host parsing the samples is the
2212  * same. This is not always the case given that the pipe output may always be
2213  * redirected into a file and analyzed on a different machine with possibly a
2214  * different endianness and perf_event ABI revsions in the perf tool itself.
2215  */
2216 static int try_all_pipe_abis(uint64_t hdr_sz, struct perf_header *ph)
2217 {
2218 	u64 attr_size;
2219 	int i;
2220 
2221 	for (i = 0 ; attr_pipe_abi_sizes[i]; i++) {
2222 		if (hdr_sz != attr_pipe_abi_sizes[i]) {
2223 			attr_size = bswap_64(hdr_sz);
2224 			if (attr_size != hdr_sz)
2225 				continue;
2226 
2227 			ph->needs_swap = true;
2228 		}
2229 		pr_debug("Pipe ABI%d perf.data file detected\n", i);
2230 		return 0;
2231 	}
2232 	return -1;
2233 }
2234 
2235 bool is_perf_magic(u64 magic)
2236 {
2237 	if (!memcmp(&magic, __perf_magic1, sizeof(magic))
2238 		|| magic == __perf_magic2
2239 		|| magic == __perf_magic2_sw)
2240 		return true;
2241 
2242 	return false;
2243 }
2244 
2245 static int check_magic_endian(u64 magic, uint64_t hdr_sz,
2246 			      bool is_pipe, struct perf_header *ph)
2247 {
2248 	int ret;
2249 
2250 	/* check for legacy format */
2251 	ret = memcmp(&magic, __perf_magic1, sizeof(magic));
2252 	if (ret == 0) {
2253 		ph->version = PERF_HEADER_VERSION_1;
2254 		pr_debug("legacy perf.data format\n");
2255 		if (is_pipe)
2256 			return try_all_pipe_abis(hdr_sz, ph);
2257 
2258 		return try_all_file_abis(hdr_sz, ph);
2259 	}
2260 	/*
2261 	 * the new magic number serves two purposes:
2262 	 * - unique number to identify actual perf.data files
2263 	 * - encode endianness of file
2264 	 */
2265 	ph->version = PERF_HEADER_VERSION_2;
2266 
2267 	/* check magic number with one endianness */
2268 	if (magic == __perf_magic2)
2269 		return 0;
2270 
2271 	/* check magic number with opposite endianness */
2272 	if (magic != __perf_magic2_sw)
2273 		return -1;
2274 
2275 	ph->needs_swap = true;
2276 
2277 	return 0;
2278 }
2279 
2280 int perf_file_header__read(struct perf_file_header *header,
2281 			   struct perf_header *ph, int fd)
2282 {
2283 	ssize_t ret;
2284 
2285 	lseek(fd, 0, SEEK_SET);
2286 
2287 	ret = readn(fd, header, sizeof(*header));
2288 	if (ret <= 0)
2289 		return -1;
2290 
2291 	if (check_magic_endian(header->magic,
2292 			       header->attr_size, false, ph) < 0) {
2293 		pr_debug("magic/endian check failed\n");
2294 		return -1;
2295 	}
2296 
2297 	if (ph->needs_swap) {
2298 		mem_bswap_64(header, offsetof(struct perf_file_header,
2299 			     adds_features));
2300 	}
2301 
2302 	if (header->size != sizeof(*header)) {
2303 		/* Support the previous format */
2304 		if (header->size == offsetof(typeof(*header), adds_features))
2305 			bitmap_zero(header->adds_features, HEADER_FEAT_BITS);
2306 		else
2307 			return -1;
2308 	} else if (ph->needs_swap) {
2309 		/*
2310 		 * feature bitmap is declared as an array of unsigned longs --
2311 		 * not good since its size can differ between the host that
2312 		 * generated the data file and the host analyzing the file.
2313 		 *
2314 		 * We need to handle endianness, but we don't know the size of
2315 		 * the unsigned long where the file was generated. Take a best
2316 		 * guess at determining it: try 64-bit swap first (ie., file
2317 		 * created on a 64-bit host), and check if the hostname feature
2318 		 * bit is set (this feature bit is forced on as of fbe96f2).
2319 		 * If the bit is not, undo the 64-bit swap and try a 32-bit
2320 		 * swap. If the hostname bit is still not set (e.g., older data
2321 		 * file), punt and fallback to the original behavior --
2322 		 * clearing all feature bits and setting buildid.
2323 		 */
2324 		mem_bswap_64(&header->adds_features,
2325 			    BITS_TO_U64(HEADER_FEAT_BITS));
2326 
2327 		if (!test_bit(HEADER_HOSTNAME, header->adds_features)) {
2328 			/* unswap as u64 */
2329 			mem_bswap_64(&header->adds_features,
2330 				    BITS_TO_U64(HEADER_FEAT_BITS));
2331 
2332 			/* unswap as u32 */
2333 			mem_bswap_32(&header->adds_features,
2334 				    BITS_TO_U32(HEADER_FEAT_BITS));
2335 		}
2336 
2337 		if (!test_bit(HEADER_HOSTNAME, header->adds_features)) {
2338 			bitmap_zero(header->adds_features, HEADER_FEAT_BITS);
2339 			set_bit(HEADER_BUILD_ID, header->adds_features);
2340 		}
2341 	}
2342 
2343 	memcpy(&ph->adds_features, &header->adds_features,
2344 	       sizeof(ph->adds_features));
2345 
2346 	ph->data_offset  = header->data.offset;
2347 	ph->data_size	 = header->data.size;
2348 	ph->feat_offset  = header->data.offset + header->data.size;
2349 	return 0;
2350 }
2351 
2352 static int perf_file_section__process(struct perf_file_section *section,
2353 				      struct perf_header *ph,
2354 				      int feat, int fd, void *data)
2355 {
2356 	if (lseek(fd, section->offset, SEEK_SET) == (off_t)-1) {
2357 		pr_debug("Failed to lseek to %" PRIu64 " offset for feature "
2358 			  "%d, continuing...\n", section->offset, feat);
2359 		return 0;
2360 	}
2361 
2362 	if (feat >= HEADER_LAST_FEATURE) {
2363 		pr_debug("unknown feature %d, continuing...\n", feat);
2364 		return 0;
2365 	}
2366 
2367 	if (!feat_ops[feat].process)
2368 		return 0;
2369 
2370 	return feat_ops[feat].process(section, ph, fd, data);
2371 }
2372 
2373 static int perf_file_header__read_pipe(struct perf_pipe_file_header *header,
2374 				       struct perf_header *ph, int fd,
2375 				       bool repipe)
2376 {
2377 	ssize_t ret;
2378 
2379 	ret = readn(fd, header, sizeof(*header));
2380 	if (ret <= 0)
2381 		return -1;
2382 
2383 	if (check_magic_endian(header->magic, header->size, true, ph) < 0) {
2384 		pr_debug("endian/magic failed\n");
2385 		return -1;
2386 	}
2387 
2388 	if (ph->needs_swap)
2389 		header->size = bswap_64(header->size);
2390 
2391 	if (repipe && do_write(STDOUT_FILENO, header, sizeof(*header)) < 0)
2392 		return -1;
2393 
2394 	return 0;
2395 }
2396 
2397 static int perf_header__read_pipe(struct perf_session *session)
2398 {
2399 	struct perf_header *header = &session->header;
2400 	struct perf_pipe_file_header f_header;
2401 
2402 	if (perf_file_header__read_pipe(&f_header, header,
2403 					perf_data_file__fd(session->file),
2404 					session->repipe) < 0) {
2405 		pr_debug("incompatible file format\n");
2406 		return -EINVAL;
2407 	}
2408 
2409 	return 0;
2410 }
2411 
2412 static int read_attr(int fd, struct perf_header *ph,
2413 		     struct perf_file_attr *f_attr)
2414 {
2415 	struct perf_event_attr *attr = &f_attr->attr;
2416 	size_t sz, left;
2417 	size_t our_sz = sizeof(f_attr->attr);
2418 	ssize_t ret;
2419 
2420 	memset(f_attr, 0, sizeof(*f_attr));
2421 
2422 	/* read minimal guaranteed structure */
2423 	ret = readn(fd, attr, PERF_ATTR_SIZE_VER0);
2424 	if (ret <= 0) {
2425 		pr_debug("cannot read %d bytes of header attr\n",
2426 			 PERF_ATTR_SIZE_VER0);
2427 		return -1;
2428 	}
2429 
2430 	/* on file perf_event_attr size */
2431 	sz = attr->size;
2432 
2433 	if (ph->needs_swap)
2434 		sz = bswap_32(sz);
2435 
2436 	if (sz == 0) {
2437 		/* assume ABI0 */
2438 		sz =  PERF_ATTR_SIZE_VER0;
2439 	} else if (sz > our_sz) {
2440 		pr_debug("file uses a more recent and unsupported ABI"
2441 			 " (%zu bytes extra)\n", sz - our_sz);
2442 		return -1;
2443 	}
2444 	/* what we have not yet read and that we know about */
2445 	left = sz - PERF_ATTR_SIZE_VER0;
2446 	if (left) {
2447 		void *ptr = attr;
2448 		ptr += PERF_ATTR_SIZE_VER0;
2449 
2450 		ret = readn(fd, ptr, left);
2451 	}
2452 	/* read perf_file_section, ids are read in caller */
2453 	ret = readn(fd, &f_attr->ids, sizeof(f_attr->ids));
2454 
2455 	return ret <= 0 ? -1 : 0;
2456 }
2457 
2458 static int perf_evsel__prepare_tracepoint_event(struct perf_evsel *evsel,
2459 						struct pevent *pevent)
2460 {
2461 	struct event_format *event;
2462 	char bf[128];
2463 
2464 	/* already prepared */
2465 	if (evsel->tp_format)
2466 		return 0;
2467 
2468 	if (pevent == NULL) {
2469 		pr_debug("broken or missing trace data\n");
2470 		return -1;
2471 	}
2472 
2473 	event = pevent_find_event(pevent, evsel->attr.config);
2474 	if (event == NULL)
2475 		return -1;
2476 
2477 	if (!evsel->name) {
2478 		snprintf(bf, sizeof(bf), "%s:%s", event->system, event->name);
2479 		evsel->name = strdup(bf);
2480 		if (evsel->name == NULL)
2481 			return -1;
2482 	}
2483 
2484 	evsel->tp_format = event;
2485 	return 0;
2486 }
2487 
2488 static int perf_evlist__prepare_tracepoint_events(struct perf_evlist *evlist,
2489 						  struct pevent *pevent)
2490 {
2491 	struct perf_evsel *pos;
2492 
2493 	evlist__for_each(evlist, pos) {
2494 		if (pos->attr.type == PERF_TYPE_TRACEPOINT &&
2495 		    perf_evsel__prepare_tracepoint_event(pos, pevent))
2496 			return -1;
2497 	}
2498 
2499 	return 0;
2500 }
2501 
2502 int perf_session__read_header(struct perf_session *session)
2503 {
2504 	struct perf_data_file *file = session->file;
2505 	struct perf_header *header = &session->header;
2506 	struct perf_file_header	f_header;
2507 	struct perf_file_attr	f_attr;
2508 	u64			f_id;
2509 	int nr_attrs, nr_ids, i, j;
2510 	int fd = perf_data_file__fd(file);
2511 
2512 	session->evlist = perf_evlist__new();
2513 	if (session->evlist == NULL)
2514 		return -ENOMEM;
2515 
2516 	if (perf_data_file__is_pipe(file))
2517 		return perf_header__read_pipe(session);
2518 
2519 	if (perf_file_header__read(&f_header, header, fd) < 0)
2520 		return -EINVAL;
2521 
2522 	/*
2523 	 * Sanity check that perf.data was written cleanly; data size is
2524 	 * initialized to 0 and updated only if the on_exit function is run.
2525 	 * If data size is still 0 then the file contains only partial
2526 	 * information.  Just warn user and process it as much as it can.
2527 	 */
2528 	if (f_header.data.size == 0) {
2529 		pr_warning("WARNING: The %s file's data size field is 0 which is unexpected.\n"
2530 			   "Was the 'perf record' command properly terminated?\n",
2531 			   file->path);
2532 	}
2533 
2534 	nr_attrs = f_header.attrs.size / f_header.attr_size;
2535 	lseek(fd, f_header.attrs.offset, SEEK_SET);
2536 
2537 	for (i = 0; i < nr_attrs; i++) {
2538 		struct perf_evsel *evsel;
2539 		off_t tmp;
2540 
2541 		if (read_attr(fd, header, &f_attr) < 0)
2542 			goto out_errno;
2543 
2544 		if (header->needs_swap) {
2545 			f_attr.ids.size   = bswap_64(f_attr.ids.size);
2546 			f_attr.ids.offset = bswap_64(f_attr.ids.offset);
2547 			perf_event__attr_swap(&f_attr.attr);
2548 		}
2549 
2550 		tmp = lseek(fd, 0, SEEK_CUR);
2551 		evsel = perf_evsel__new(&f_attr.attr);
2552 
2553 		if (evsel == NULL)
2554 			goto out_delete_evlist;
2555 
2556 		evsel->needs_swap = header->needs_swap;
2557 		/*
2558 		 * Do it before so that if perf_evsel__alloc_id fails, this
2559 		 * entry gets purged too at perf_evlist__delete().
2560 		 */
2561 		perf_evlist__add(session->evlist, evsel);
2562 
2563 		nr_ids = f_attr.ids.size / sizeof(u64);
2564 		/*
2565 		 * We don't have the cpu and thread maps on the header, so
2566 		 * for allocating the perf_sample_id table we fake 1 cpu and
2567 		 * hattr->ids threads.
2568 		 */
2569 		if (perf_evsel__alloc_id(evsel, 1, nr_ids))
2570 			goto out_delete_evlist;
2571 
2572 		lseek(fd, f_attr.ids.offset, SEEK_SET);
2573 
2574 		for (j = 0; j < nr_ids; j++) {
2575 			if (perf_header__getbuffer64(header, fd, &f_id, sizeof(f_id)))
2576 				goto out_errno;
2577 
2578 			perf_evlist__id_add(session->evlist, evsel, 0, j, f_id);
2579 		}
2580 
2581 		lseek(fd, tmp, SEEK_SET);
2582 	}
2583 
2584 	symbol_conf.nr_events = nr_attrs;
2585 
2586 	perf_header__process_sections(header, fd, &session->tevent,
2587 				      perf_file_section__process);
2588 
2589 	if (perf_evlist__prepare_tracepoint_events(session->evlist,
2590 						   session->tevent.pevent))
2591 		goto out_delete_evlist;
2592 
2593 	return 0;
2594 out_errno:
2595 	return -errno;
2596 
2597 out_delete_evlist:
2598 	perf_evlist__delete(session->evlist);
2599 	session->evlist = NULL;
2600 	return -ENOMEM;
2601 }
2602 
2603 int perf_event__synthesize_attr(struct perf_tool *tool,
2604 				struct perf_event_attr *attr, u32 ids, u64 *id,
2605 				perf_event__handler_t process)
2606 {
2607 	union perf_event *ev;
2608 	size_t size;
2609 	int err;
2610 
2611 	size = sizeof(struct perf_event_attr);
2612 	size = PERF_ALIGN(size, sizeof(u64));
2613 	size += sizeof(struct perf_event_header);
2614 	size += ids * sizeof(u64);
2615 
2616 	ev = malloc(size);
2617 
2618 	if (ev == NULL)
2619 		return -ENOMEM;
2620 
2621 	ev->attr.attr = *attr;
2622 	memcpy(ev->attr.id, id, ids * sizeof(u64));
2623 
2624 	ev->attr.header.type = PERF_RECORD_HEADER_ATTR;
2625 	ev->attr.header.size = (u16)size;
2626 
2627 	if (ev->attr.header.size == size)
2628 		err = process(tool, ev, NULL, NULL);
2629 	else
2630 		err = -E2BIG;
2631 
2632 	free(ev);
2633 
2634 	return err;
2635 }
2636 
2637 int perf_event__synthesize_attrs(struct perf_tool *tool,
2638 				   struct perf_session *session,
2639 				   perf_event__handler_t process)
2640 {
2641 	struct perf_evsel *evsel;
2642 	int err = 0;
2643 
2644 	evlist__for_each(session->evlist, evsel) {
2645 		err = perf_event__synthesize_attr(tool, &evsel->attr, evsel->ids,
2646 						  evsel->id, process);
2647 		if (err) {
2648 			pr_debug("failed to create perf header attribute\n");
2649 			return err;
2650 		}
2651 	}
2652 
2653 	return err;
2654 }
2655 
2656 int perf_event__process_attr(struct perf_tool *tool __maybe_unused,
2657 			     union perf_event *event,
2658 			     struct perf_evlist **pevlist)
2659 {
2660 	u32 i, ids, n_ids;
2661 	struct perf_evsel *evsel;
2662 	struct perf_evlist *evlist = *pevlist;
2663 
2664 	if (evlist == NULL) {
2665 		*pevlist = evlist = perf_evlist__new();
2666 		if (evlist == NULL)
2667 			return -ENOMEM;
2668 	}
2669 
2670 	evsel = perf_evsel__new(&event->attr.attr);
2671 	if (evsel == NULL)
2672 		return -ENOMEM;
2673 
2674 	perf_evlist__add(evlist, evsel);
2675 
2676 	ids = event->header.size;
2677 	ids -= (void *)&event->attr.id - (void *)event;
2678 	n_ids = ids / sizeof(u64);
2679 	/*
2680 	 * We don't have the cpu and thread maps on the header, so
2681 	 * for allocating the perf_sample_id table we fake 1 cpu and
2682 	 * hattr->ids threads.
2683 	 */
2684 	if (perf_evsel__alloc_id(evsel, 1, n_ids))
2685 		return -ENOMEM;
2686 
2687 	for (i = 0; i < n_ids; i++) {
2688 		perf_evlist__id_add(evlist, evsel, 0, i, event->attr.id[i]);
2689 	}
2690 
2691 	symbol_conf.nr_events = evlist->nr_entries;
2692 
2693 	return 0;
2694 }
2695 
2696 int perf_event__synthesize_tracing_data(struct perf_tool *tool, int fd,
2697 					struct perf_evlist *evlist,
2698 					perf_event__handler_t process)
2699 {
2700 	union perf_event ev;
2701 	struct tracing_data *tdata;
2702 	ssize_t size = 0, aligned_size = 0, padding;
2703 	int err __maybe_unused = 0;
2704 
2705 	/*
2706 	 * We are going to store the size of the data followed
2707 	 * by the data contents. Since the fd descriptor is a pipe,
2708 	 * we cannot seek back to store the size of the data once
2709 	 * we know it. Instead we:
2710 	 *
2711 	 * - write the tracing data to the temp file
2712 	 * - get/write the data size to pipe
2713 	 * - write the tracing data from the temp file
2714 	 *   to the pipe
2715 	 */
2716 	tdata = tracing_data_get(&evlist->entries, fd, true);
2717 	if (!tdata)
2718 		return -1;
2719 
2720 	memset(&ev, 0, sizeof(ev));
2721 
2722 	ev.tracing_data.header.type = PERF_RECORD_HEADER_TRACING_DATA;
2723 	size = tdata->size;
2724 	aligned_size = PERF_ALIGN(size, sizeof(u64));
2725 	padding = aligned_size - size;
2726 	ev.tracing_data.header.size = sizeof(ev.tracing_data);
2727 	ev.tracing_data.size = aligned_size;
2728 
2729 	process(tool, &ev, NULL, NULL);
2730 
2731 	/*
2732 	 * The put function will copy all the tracing data
2733 	 * stored in temp file to the pipe.
2734 	 */
2735 	tracing_data_put(tdata);
2736 
2737 	write_padded(fd, NULL, 0, padding);
2738 
2739 	return aligned_size;
2740 }
2741 
2742 int perf_event__process_tracing_data(struct perf_tool *tool __maybe_unused,
2743 				     union perf_event *event,
2744 				     struct perf_session *session)
2745 {
2746 	ssize_t size_read, padding, size = event->tracing_data.size;
2747 	int fd = perf_data_file__fd(session->file);
2748 	off_t offset = lseek(fd, 0, SEEK_CUR);
2749 	char buf[BUFSIZ];
2750 
2751 	/* setup for reading amidst mmap */
2752 	lseek(fd, offset + sizeof(struct tracing_data_event),
2753 	      SEEK_SET);
2754 
2755 	size_read = trace_report(fd, &session->tevent,
2756 				 session->repipe);
2757 	padding = PERF_ALIGN(size_read, sizeof(u64)) - size_read;
2758 
2759 	if (readn(fd, buf, padding) < 0) {
2760 		pr_err("%s: reading input file", __func__);
2761 		return -1;
2762 	}
2763 	if (session->repipe) {
2764 		int retw = write(STDOUT_FILENO, buf, padding);
2765 		if (retw <= 0 || retw != padding) {
2766 			pr_err("%s: repiping tracing data padding", __func__);
2767 			return -1;
2768 		}
2769 	}
2770 
2771 	if (size_read + padding != size) {
2772 		pr_err("%s: tracing data size mismatch", __func__);
2773 		return -1;
2774 	}
2775 
2776 	perf_evlist__prepare_tracepoint_events(session->evlist,
2777 					       session->tevent.pevent);
2778 
2779 	return size_read + padding;
2780 }
2781 
2782 int perf_event__synthesize_build_id(struct perf_tool *tool,
2783 				    struct dso *pos, u16 misc,
2784 				    perf_event__handler_t process,
2785 				    struct machine *machine)
2786 {
2787 	union perf_event ev;
2788 	size_t len;
2789 	int err = 0;
2790 
2791 	if (!pos->hit)
2792 		return err;
2793 
2794 	memset(&ev, 0, sizeof(ev));
2795 
2796 	len = pos->long_name_len + 1;
2797 	len = PERF_ALIGN(len, NAME_ALIGN);
2798 	memcpy(&ev.build_id.build_id, pos->build_id, sizeof(pos->build_id));
2799 	ev.build_id.header.type = PERF_RECORD_HEADER_BUILD_ID;
2800 	ev.build_id.header.misc = misc;
2801 	ev.build_id.pid = machine->pid;
2802 	ev.build_id.header.size = sizeof(ev.build_id) + len;
2803 	memcpy(&ev.build_id.filename, pos->long_name, pos->long_name_len);
2804 
2805 	err = process(tool, &ev, NULL, machine);
2806 
2807 	return err;
2808 }
2809 
2810 int perf_event__process_build_id(struct perf_tool *tool __maybe_unused,
2811 				 union perf_event *event,
2812 				 struct perf_session *session)
2813 {
2814 	__event_process_build_id(&event->build_id,
2815 				 event->build_id.filename,
2816 				 session);
2817 	return 0;
2818 }
2819