1 // SPDX-License-Identifier: LGPL-2.1
2 /*
3 * Copyright (C) 2022 Google Inc, Steven Rostedt <[email protected]>
4 */
5 #include <stdlib.h>
6 #include <stdarg.h>
7 #include <string.h>
8 #include <stdio.h>
9 #include <errno.h>
10 #include <getopt.h>
11 #include <event-parse.h>
12
13 static char *argv0;
14
get_this_name(void)15 static char *get_this_name(void)
16 {
17 static char *this_name;
18 char *arg;
19 char *p;
20
21 if (this_name)
22 return this_name;
23
24 arg = argv0;
25 p = arg+strlen(arg);
26
27 while (p >= arg && *p != '/')
28 p--;
29 p++;
30
31 this_name = p;
32 return p;
33 }
34
usage(void)35 static void usage(void)
36 {
37 char *p = get_this_name();
38
39 printf("usage: %s [options]\n"
40 " -h : this message\n"
41 " -s system : the system for the event\n"
42 " -e format : the event format file\n"
43 " -f file : file to read the event from\n"
44 " otherwise, reads from stdin\n"
45 "\n",p);
46 exit(-1);
47 }
48
__vdie(const char * fmt,va_list ap,int err)49 static void __vdie(const char *fmt, va_list ap, int err)
50 {
51 int ret = errno;
52 char *p = get_this_name();
53
54 if (err && errno)
55 perror(p);
56 else
57 ret = -1;
58
59 fprintf(stderr, " ");
60 vfprintf(stderr, fmt, ap);
61
62 fprintf(stderr, "\n");
63 exit(ret);
64 }
65
die(const char * fmt,...)66 void die(const char *fmt, ...)
67 {
68 va_list ap;
69
70 va_start(ap, fmt);
71 __vdie(fmt, ap, 0);
72 va_end(ap);
73 }
74
pdie(const char * fmt,...)75 void pdie(const char *fmt, ...)
76 {
77 va_list ap;
78
79 va_start(ap, fmt);
80 __vdie(fmt, ap, 1);
81 va_end(ap);
82 }
83
84 /* Must be a power of two */
85 #define BUFALLOC 1024
86 #define BUFMASK (~(BUFALLOC - 1))
87
main(int argc,char ** argv)88 int main(int argc, char **argv)
89 {
90 struct tep_handle *tep;
91 struct tep_event *event;
92 FILE *file = stdin;
93 FILE *fp = NULL;
94 char *system = NULL;
95 char *event_buf = NULL;
96 int esize = 0;
97 int c;
98
99 argv0 = argv[0];
100
101 while ((c = getopt(argc, argv, "hs:e:f:")) >= 0) {
102 switch (c) {
103 case 's':
104 system = optarg;
105 break;
106 case 'e':
107 event_buf = optarg;
108 file = NULL;
109 break;
110 case 'f':
111 fp = fopen(optarg, "r");
112 if (!fp)
113 pdie("%s", optarg);
114 file = fp;
115 break;
116 case 'h':
117 usage();
118 }
119 }
120 if (file) {
121 char *line = NULL;
122 size_t n = 0;
123 int len;
124
125 while (getline(&line, &n, file) > 0) {
126 len = strlen(line) + 1;
127
128 if (((esize - 1) & BUFMASK) < ((esize + len) & BUFMASK)) {
129 int a;
130
131 a = (esize + len + BUFALLOC - 1) & BUFMASK;
132 event_buf = realloc(event_buf, a);
133 if (!event_buf)
134 pdie("allocating event");
135 }
136 strcpy(event_buf + esize, line);
137 esize += len - 1;
138 }
139 free(line);
140 }
141
142 tep = tep_alloc();
143 if (!tep)
144 pdie("Allocating tep handle");
145
146 tep_set_loglevel(TEP_LOG_ALL);
147
148 if (!system)
149 system = "test";
150
151 if (tep_parse_format(tep, &event, event_buf, esize, system))
152 die("Failed to parse event");
153
154 }
155