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