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