Merge tag 'io_uring-5.10-2020-10-24' of git://git.kernel.dk/linux-block
[sfrench/cifs-2.6.git] / tools / lib / traceevent / event-parse.c
1 // SPDX-License-Identifier: LGPL-2.1
2 /*
3  * Copyright (C) 2009, 2010 Red Hat Inc, Steven Rostedt <srostedt@redhat.com>
4  *
5  *
6  *  The parts for function graph printing was taken and modified from the
7  *  Linux Kernel that were written by
8  *    - Copyright (C) 2009  Frederic Weisbecker,
9  *  Frederic Weisbecker gave his permission to relicense the code to
10  *  the Lesser General Public License.
11  */
12 #include <inttypes.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <stdarg.h>
17 #include <ctype.h>
18 #include <errno.h>
19 #include <stdint.h>
20 #include <limits.h>
21 #include <linux/time64.h>
22
23 #include <netinet/in.h>
24 #include "event-parse.h"
25
26 #include "event-parse-local.h"
27 #include "event-utils.h"
28 #include "trace-seq.h"
29
30 static const char *input_buf;
31 static unsigned long long input_buf_ptr;
32 static unsigned long long input_buf_siz;
33
34 static int is_flag_field;
35 static int is_symbolic_field;
36
37 static int show_warning = 1;
38
39 #define do_warning(fmt, ...)                            \
40         do {                                            \
41                 if (show_warning)                       \
42                         warning(fmt, ##__VA_ARGS__);    \
43         } while (0)
44
45 #define do_warning_event(event, fmt, ...)                       \
46         do {                                                    \
47                 if (!show_warning)                              \
48                         continue;                               \
49                                                                 \
50                 if (event)                                      \
51                         warning("[%s:%s] " fmt, event->system,  \
52                                 event->name, ##__VA_ARGS__);    \
53                 else                                            \
54                         warning(fmt, ##__VA_ARGS__);            \
55         } while (0)
56
57 /**
58  * init_input_buf - init buffer for parsing
59  * @buf: buffer to parse
60  * @size: the size of the buffer
61  *
62  * Initializes the internal buffer that tep_read_token() will parse.
63  */
64 __hidden void init_input_buf(const char *buf, unsigned long long size)
65 {
66         input_buf = buf;
67         input_buf_siz = size;
68         input_buf_ptr = 0;
69 }
70
71 __hidden const char *get_input_buf(void)
72 {
73         return input_buf;
74 }
75
76 __hidden unsigned long long get_input_buf_ptr(void)
77 {
78         return input_buf_ptr;
79 }
80
81 struct event_handler {
82         struct event_handler            *next;
83         int                             id;
84         const char                      *sys_name;
85         const char                      *event_name;
86         tep_event_handler_func          func;
87         void                            *context;
88 };
89
90 struct func_params {
91         struct func_params      *next;
92         enum tep_func_arg_type  type;
93 };
94
95 struct tep_function_handler {
96         struct tep_function_handler     *next;
97         enum tep_func_arg_type          ret_type;
98         char                            *name;
99         tep_func_handler                func;
100         struct func_params              *params;
101         int                             nr_args;
102 };
103
104 static unsigned long long
105 process_defined_func(struct trace_seq *s, void *data, int size,
106                      struct tep_event *event, struct tep_print_arg *arg);
107
108 static void free_func_handle(struct tep_function_handler *func);
109
110 void breakpoint(void)
111 {
112         static int x;
113         x++;
114 }
115
116 static struct tep_print_arg *alloc_arg(void)
117 {
118         return calloc(1, sizeof(struct tep_print_arg));
119 }
120
121 struct tep_cmdline {
122         char *comm;
123         int pid;
124 };
125
126 static int cmdline_cmp(const void *a, const void *b)
127 {
128         const struct tep_cmdline *ca = a;
129         const struct tep_cmdline *cb = b;
130
131         if (ca->pid < cb->pid)
132                 return -1;
133         if (ca->pid > cb->pid)
134                 return 1;
135
136         return 0;
137 }
138
139 /* Looking for where to place the key */
140 static int cmdline_slot_cmp(const void *a, const void *b)
141 {
142         const struct tep_cmdline *ca = a;
143         const struct tep_cmdline *cb = b;
144         const struct tep_cmdline *cb1 = cb + 1;
145
146         if (ca->pid < cb->pid)
147                 return -1;
148
149         if (ca->pid > cb->pid) {
150                 if (ca->pid <= cb1->pid)
151                         return 0;
152                 return 1;
153         }
154
155         return 0;
156 }
157
158 struct cmdline_list {
159         struct cmdline_list     *next;
160         char                    *comm;
161         int                     pid;
162 };
163
164 static int cmdline_init(struct tep_handle *tep)
165 {
166         struct cmdline_list *cmdlist = tep->cmdlist;
167         struct cmdline_list *item;
168         struct tep_cmdline *cmdlines;
169         int i;
170
171         cmdlines = malloc(sizeof(*cmdlines) * tep->cmdline_count);
172         if (!cmdlines)
173                 return -1;
174
175         i = 0;
176         while (cmdlist) {
177                 cmdlines[i].pid = cmdlist->pid;
178                 cmdlines[i].comm = cmdlist->comm;
179                 i++;
180                 item = cmdlist;
181                 cmdlist = cmdlist->next;
182                 free(item);
183         }
184
185         qsort(cmdlines, tep->cmdline_count, sizeof(*cmdlines), cmdline_cmp);
186
187         tep->cmdlines = cmdlines;
188         tep->cmdlist = NULL;
189
190         return 0;
191 }
192
193 static const char *find_cmdline(struct tep_handle *tep, int pid)
194 {
195         const struct tep_cmdline *comm;
196         struct tep_cmdline key;
197
198         if (!pid)
199                 return "<idle>";
200
201         if (!tep->cmdlines && cmdline_init(tep))
202                 return "<not enough memory for cmdlines!>";
203
204         key.pid = pid;
205
206         comm = bsearch(&key, tep->cmdlines, tep->cmdline_count,
207                        sizeof(*tep->cmdlines), cmdline_cmp);
208
209         if (comm)
210                 return comm->comm;
211         return "<...>";
212 }
213
214 /**
215  * tep_is_pid_registered - return if a pid has a cmdline registered
216  * @tep: a handle to the trace event parser context
217  * @pid: The pid to check if it has a cmdline registered with.
218  *
219  * Returns true if the pid has a cmdline mapped to it
220  * false otherwise.
221  */
222 bool tep_is_pid_registered(struct tep_handle *tep, int pid)
223 {
224         const struct tep_cmdline *comm;
225         struct tep_cmdline key;
226
227         if (!pid)
228                 return true;
229
230         if (!tep->cmdlines && cmdline_init(tep))
231                 return false;
232
233         key.pid = pid;
234
235         comm = bsearch(&key, tep->cmdlines, tep->cmdline_count,
236                        sizeof(*tep->cmdlines), cmdline_cmp);
237
238         if (comm)
239                 return true;
240         return false;
241 }
242
243 /*
244  * If the command lines have been converted to an array, then
245  * we must add this pid. This is much slower than when cmdlines
246  * are added before the array is initialized.
247  */
248 static int add_new_comm(struct tep_handle *tep,
249                         const char *comm, int pid, bool override)
250 {
251         struct tep_cmdline *cmdlines = tep->cmdlines;
252         struct tep_cmdline *cmdline;
253         struct tep_cmdline key;
254         char *new_comm;
255         int cnt;
256
257         if (!pid)
258                 return 0;
259
260         /* avoid duplicates */
261         key.pid = pid;
262
263         cmdline = bsearch(&key, tep->cmdlines, tep->cmdline_count,
264                           sizeof(*tep->cmdlines), cmdline_cmp);
265         if (cmdline) {
266                 if (!override) {
267                         errno = EEXIST;
268                         return -1;
269                 }
270                 new_comm = strdup(comm);
271                 if (!new_comm) {
272                         errno = ENOMEM;
273                         return -1;
274                 }
275                 free(cmdline->comm);
276                 cmdline->comm = new_comm;
277
278                 return 0;
279         }
280
281         cmdlines = realloc(cmdlines, sizeof(*cmdlines) * (tep->cmdline_count + 1));
282         if (!cmdlines) {
283                 errno = ENOMEM;
284                 return -1;
285         }
286         tep->cmdlines = cmdlines;
287
288         key.comm = strdup(comm);
289         if (!key.comm) {
290                 errno = ENOMEM;
291                 return -1;
292         }
293
294         if (!tep->cmdline_count) {
295                 /* no entries yet */
296                 tep->cmdlines[0] = key;
297                 tep->cmdline_count++;
298                 return 0;
299         }
300
301         /* Now find where we want to store the new cmdline */
302         cmdline = bsearch(&key, tep->cmdlines, tep->cmdline_count - 1,
303                           sizeof(*tep->cmdlines), cmdline_slot_cmp);
304
305         cnt = tep->cmdline_count;
306         if (cmdline) {
307                 /* cmdline points to the one before the spot we want */
308                 cmdline++;
309                 cnt -= cmdline - tep->cmdlines;
310
311         } else {
312                 /* The new entry is either before or after the list */
313                 if (key.pid > tep->cmdlines[tep->cmdline_count - 1].pid) {
314                         tep->cmdlines[tep->cmdline_count++] = key;
315                         return 0;
316                 }
317                 cmdline = &tep->cmdlines[0];
318         }
319         memmove(cmdline + 1, cmdline, (cnt * sizeof(*cmdline)));
320         *cmdline = key;
321
322         tep->cmdline_count++;
323
324         return 0;
325 }
326
327 static int _tep_register_comm(struct tep_handle *tep,
328                               const char *comm, int pid, bool override)
329 {
330         struct cmdline_list *item;
331
332         if (tep->cmdlines)
333                 return add_new_comm(tep, comm, pid, override);
334
335         item = malloc(sizeof(*item));
336         if (!item)
337                 return -1;
338
339         if (comm)
340                 item->comm = strdup(comm);
341         else
342                 item->comm = strdup("<...>");
343         if (!item->comm) {
344                 free(item);
345                 return -1;
346         }
347         item->pid = pid;
348         item->next = tep->cmdlist;
349
350         tep->cmdlist = item;
351         tep->cmdline_count++;
352
353         return 0;
354 }
355
356 /**
357  * tep_register_comm - register a pid / comm mapping
358  * @tep: a handle to the trace event parser context
359  * @comm: the command line to register
360  * @pid: the pid to map the command line to
361  *
362  * This adds a mapping to search for command line names with
363  * a given pid. The comm is duplicated. If a command with the same pid
364  * already exist, -1 is returned and errno is set to EEXIST
365  */
366 int tep_register_comm(struct tep_handle *tep, const char *comm, int pid)
367 {
368         return _tep_register_comm(tep, comm, pid, false);
369 }
370
371 /**
372  * tep_override_comm - register a pid / comm mapping
373  * @tep: a handle to the trace event parser context
374  * @comm: the command line to register
375  * @pid: the pid to map the command line to
376  *
377  * This adds a mapping to search for command line names with
378  * a given pid. The comm is duplicated. If a command with the same pid
379  * already exist, the command string is udapted with the new one
380  */
381 int tep_override_comm(struct tep_handle *tep, const char *comm, int pid)
382 {
383         if (!tep->cmdlines && cmdline_init(tep)) {
384                 errno = ENOMEM;
385                 return -1;
386         }
387         return _tep_register_comm(tep, comm, pid, true);
388 }
389
390 struct func_map {
391         unsigned long long              addr;
392         char                            *func;
393         char                            *mod;
394 };
395
396 struct func_list {
397         struct func_list        *next;
398         unsigned long long      addr;
399         char                    *func;
400         char                    *mod;
401 };
402
403 static int func_cmp(const void *a, const void *b)
404 {
405         const struct func_map *fa = a;
406         const struct func_map *fb = b;
407
408         if (fa->addr < fb->addr)
409                 return -1;
410         if (fa->addr > fb->addr)
411                 return 1;
412
413         return 0;
414 }
415
416 /*
417  * We are searching for a record in between, not an exact
418  * match.
419  */
420 static int func_bcmp(const void *a, const void *b)
421 {
422         const struct func_map *fa = a;
423         const struct func_map *fb = b;
424
425         if ((fa->addr == fb->addr) ||
426
427             (fa->addr > fb->addr &&
428              fa->addr < (fb+1)->addr))
429                 return 0;
430
431         if (fa->addr < fb->addr)
432                 return -1;
433
434         return 1;
435 }
436
437 static int func_map_init(struct tep_handle *tep)
438 {
439         struct func_list *funclist;
440         struct func_list *item;
441         struct func_map *func_map;
442         int i;
443
444         func_map = malloc(sizeof(*func_map) * (tep->func_count + 1));
445         if (!func_map)
446                 return -1;
447
448         funclist = tep->funclist;
449
450         i = 0;
451         while (funclist) {
452                 func_map[i].func = funclist->func;
453                 func_map[i].addr = funclist->addr;
454                 func_map[i].mod = funclist->mod;
455                 i++;
456                 item = funclist;
457                 funclist = funclist->next;
458                 free(item);
459         }
460
461         qsort(func_map, tep->func_count, sizeof(*func_map), func_cmp);
462
463         /*
464          * Add a special record at the end.
465          */
466         func_map[tep->func_count].func = NULL;
467         func_map[tep->func_count].addr = 0;
468         func_map[tep->func_count].mod = NULL;
469
470         tep->func_map = func_map;
471         tep->funclist = NULL;
472
473         return 0;
474 }
475
476 static struct func_map *
477 __find_func(struct tep_handle *tep, unsigned long long addr)
478 {
479         struct func_map *func;
480         struct func_map key;
481
482         if (!tep->func_map)
483                 func_map_init(tep);
484
485         key.addr = addr;
486
487         func = bsearch(&key, tep->func_map, tep->func_count,
488                        sizeof(*tep->func_map), func_bcmp);
489
490         return func;
491 }
492
493 struct func_resolver {
494         tep_func_resolver_t     *func;
495         void                    *priv;
496         struct func_map         map;
497 };
498
499 /**
500  * tep_set_function_resolver - set an alternative function resolver
501  * @tep: a handle to the trace event parser context
502  * @resolver: function to be used
503  * @priv: resolver function private state.
504  *
505  * Some tools may have already a way to resolve kernel functions, allow them to
506  * keep using it instead of duplicating all the entries inside tep->funclist.
507  */
508 int tep_set_function_resolver(struct tep_handle *tep,
509                               tep_func_resolver_t *func, void *priv)
510 {
511         struct func_resolver *resolver = malloc(sizeof(*resolver));
512
513         if (resolver == NULL)
514                 return -1;
515
516         resolver->func = func;
517         resolver->priv = priv;
518
519         free(tep->func_resolver);
520         tep->func_resolver = resolver;
521
522         return 0;
523 }
524
525 /**
526  * tep_reset_function_resolver - reset alternative function resolver
527  * @tep: a handle to the trace event parser context
528  *
529  * Stop using whatever alternative resolver was set, use the default
530  * one instead.
531  */
532 void tep_reset_function_resolver(struct tep_handle *tep)
533 {
534         free(tep->func_resolver);
535         tep->func_resolver = NULL;
536 }
537
538 static struct func_map *
539 find_func(struct tep_handle *tep, unsigned long long addr)
540 {
541         struct func_map *map;
542
543         if (!tep->func_resolver)
544                 return __find_func(tep, addr);
545
546         map = &tep->func_resolver->map;
547         map->mod  = NULL;
548         map->addr = addr;
549         map->func = tep->func_resolver->func(tep->func_resolver->priv,
550                                              &map->addr, &map->mod);
551         if (map->func == NULL)
552                 return NULL;
553
554         return map;
555 }
556
557 /**
558  * tep_find_function - find a function by a given address
559  * @tep: a handle to the trace event parser context
560  * @addr: the address to find the function with
561  *
562  * Returns a pointer to the function stored that has the given
563  * address. Note, the address does not have to be exact, it
564  * will select the function that would contain the address.
565  */
566 const char *tep_find_function(struct tep_handle *tep, unsigned long long addr)
567 {
568         struct func_map *map;
569
570         map = find_func(tep, addr);
571         if (!map)
572                 return NULL;
573
574         return map->func;
575 }
576
577 /**
578  * tep_find_function_address - find a function address by a given address
579  * @tep: a handle to the trace event parser context
580  * @addr: the address to find the function with
581  *
582  * Returns the address the function starts at. This can be used in
583  * conjunction with tep_find_function to print both the function
584  * name and the function offset.
585  */
586 unsigned long long
587 tep_find_function_address(struct tep_handle *tep, unsigned long long addr)
588 {
589         struct func_map *map;
590
591         map = find_func(tep, addr);
592         if (!map)
593                 return 0;
594
595         return map->addr;
596 }
597
598 /**
599  * tep_register_function - register a function with a given address
600  * @tep: a handle to the trace event parser context
601  * @function: the function name to register
602  * @addr: the address the function starts at
603  * @mod: the kernel module the function may be in (NULL for none)
604  *
605  * This registers a function name with an address and module.
606  * The @func passed in is duplicated.
607  */
608 int tep_register_function(struct tep_handle *tep, char *func,
609                           unsigned long long addr, char *mod)
610 {
611         struct func_list *item = malloc(sizeof(*item));
612
613         if (!item)
614                 return -1;
615
616         item->next = tep->funclist;
617         item->func = strdup(func);
618         if (!item->func)
619                 goto out_free;
620
621         if (mod) {
622                 item->mod = strdup(mod);
623                 if (!item->mod)
624                         goto out_free_func;
625         } else
626                 item->mod = NULL;
627         item->addr = addr;
628
629         tep->funclist = item;
630         tep->func_count++;
631
632         return 0;
633
634 out_free_func:
635         free(item->func);
636         item->func = NULL;
637 out_free:
638         free(item);
639         errno = ENOMEM;
640         return -1;
641 }
642
643 /**
644  * tep_print_funcs - print out the stored functions
645  * @tep: a handle to the trace event parser context
646  *
647  * This prints out the stored functions.
648  */
649 void tep_print_funcs(struct tep_handle *tep)
650 {
651         int i;
652
653         if (!tep->func_map)
654                 func_map_init(tep);
655
656         for (i = 0; i < (int)tep->func_count; i++) {
657                 printf("%016llx %s",
658                        tep->func_map[i].addr,
659                        tep->func_map[i].func);
660                 if (tep->func_map[i].mod)
661                         printf(" [%s]\n", tep->func_map[i].mod);
662                 else
663                         printf("\n");
664         }
665 }
666
667 struct printk_map {
668         unsigned long long              addr;
669         char                            *printk;
670 };
671
672 struct printk_list {
673         struct printk_list      *next;
674         unsigned long long      addr;
675         char                    *printk;
676 };
677
678 static int printk_cmp(const void *a, const void *b)
679 {
680         const struct printk_map *pa = a;
681         const struct printk_map *pb = b;
682
683         if (pa->addr < pb->addr)
684                 return -1;
685         if (pa->addr > pb->addr)
686                 return 1;
687
688         return 0;
689 }
690
691 static int printk_map_init(struct tep_handle *tep)
692 {
693         struct printk_list *printklist;
694         struct printk_list *item;
695         struct printk_map *printk_map;
696         int i;
697
698         printk_map = malloc(sizeof(*printk_map) * (tep->printk_count + 1));
699         if (!printk_map)
700                 return -1;
701
702         printklist = tep->printklist;
703
704         i = 0;
705         while (printklist) {
706                 printk_map[i].printk = printklist->printk;
707                 printk_map[i].addr = printklist->addr;
708                 i++;
709                 item = printklist;
710                 printklist = printklist->next;
711                 free(item);
712         }
713
714         qsort(printk_map, tep->printk_count, sizeof(*printk_map), printk_cmp);
715
716         tep->printk_map = printk_map;
717         tep->printklist = NULL;
718
719         return 0;
720 }
721
722 static struct printk_map *
723 find_printk(struct tep_handle *tep, unsigned long long addr)
724 {
725         struct printk_map *printk;
726         struct printk_map key;
727
728         if (!tep->printk_map && printk_map_init(tep))
729                 return NULL;
730
731         key.addr = addr;
732
733         printk = bsearch(&key, tep->printk_map, tep->printk_count,
734                          sizeof(*tep->printk_map), printk_cmp);
735
736         return printk;
737 }
738
739 /**
740  * tep_register_print_string - register a string by its address
741  * @tep: a handle to the trace event parser context
742  * @fmt: the string format to register
743  * @addr: the address the string was located at
744  *
745  * This registers a string by the address it was stored in the kernel.
746  * The @fmt passed in is duplicated.
747  */
748 int tep_register_print_string(struct tep_handle *tep, const char *fmt,
749                               unsigned long long addr)
750 {
751         struct printk_list *item = malloc(sizeof(*item));
752         char *p;
753
754         if (!item)
755                 return -1;
756
757         item->next = tep->printklist;
758         item->addr = addr;
759
760         /* Strip off quotes and '\n' from the end */
761         if (fmt[0] == '"')
762                 fmt++;
763         item->printk = strdup(fmt);
764         if (!item->printk)
765                 goto out_free;
766
767         p = item->printk + strlen(item->printk) - 1;
768         if (*p == '"')
769                 *p = 0;
770
771         p -= 2;
772         if (strcmp(p, "\\n") == 0)
773                 *p = 0;
774
775         tep->printklist = item;
776         tep->printk_count++;
777
778         return 0;
779
780 out_free:
781         free(item);
782         errno = ENOMEM;
783         return -1;
784 }
785
786 /**
787  * tep_print_printk - print out the stored strings
788  * @tep: a handle to the trace event parser context
789  *
790  * This prints the string formats that were stored.
791  */
792 void tep_print_printk(struct tep_handle *tep)
793 {
794         int i;
795
796         if (!tep->printk_map)
797                 printk_map_init(tep);
798
799         for (i = 0; i < (int)tep->printk_count; i++) {
800                 printf("%016llx %s\n",
801                        tep->printk_map[i].addr,
802                        tep->printk_map[i].printk);
803         }
804 }
805
806 static struct tep_event *alloc_event(void)
807 {
808         return calloc(1, sizeof(struct tep_event));
809 }
810
811 static int add_event(struct tep_handle *tep, struct tep_event *event)
812 {
813         int i;
814         struct tep_event **events = realloc(tep->events, sizeof(event) *
815                                             (tep->nr_events + 1));
816         if (!events)
817                 return -1;
818
819         tep->events = events;
820
821         for (i = 0; i < tep->nr_events; i++) {
822                 if (tep->events[i]->id > event->id)
823                         break;
824         }
825         if (i < tep->nr_events)
826                 memmove(&tep->events[i + 1],
827                         &tep->events[i],
828                         sizeof(event) * (tep->nr_events - i));
829
830         tep->events[i] = event;
831         tep->nr_events++;
832
833         event->tep = tep;
834
835         return 0;
836 }
837
838 static int event_item_type(enum tep_event_type type)
839 {
840         switch (type) {
841         case TEP_EVENT_ITEM ... TEP_EVENT_SQUOTE:
842                 return 1;
843         case TEP_EVENT_ERROR ... TEP_EVENT_DELIM:
844         default:
845                 return 0;
846         }
847 }
848
849 static void free_flag_sym(struct tep_print_flag_sym *fsym)
850 {
851         struct tep_print_flag_sym *next;
852
853         while (fsym) {
854                 next = fsym->next;
855                 free(fsym->value);
856                 free(fsym->str);
857                 free(fsym);
858                 fsym = next;
859         }
860 }
861
862 static void free_arg(struct tep_print_arg *arg)
863 {
864         struct tep_print_arg *farg;
865
866         if (!arg)
867                 return;
868
869         switch (arg->type) {
870         case TEP_PRINT_ATOM:
871                 free(arg->atom.atom);
872                 break;
873         case TEP_PRINT_FIELD:
874                 free(arg->field.name);
875                 break;
876         case TEP_PRINT_FLAGS:
877                 free_arg(arg->flags.field);
878                 free(arg->flags.delim);
879                 free_flag_sym(arg->flags.flags);
880                 break;
881         case TEP_PRINT_SYMBOL:
882                 free_arg(arg->symbol.field);
883                 free_flag_sym(arg->symbol.symbols);
884                 break;
885         case TEP_PRINT_HEX:
886         case TEP_PRINT_HEX_STR:
887                 free_arg(arg->hex.field);
888                 free_arg(arg->hex.size);
889                 break;
890         case TEP_PRINT_INT_ARRAY:
891                 free_arg(arg->int_array.field);
892                 free_arg(arg->int_array.count);
893                 free_arg(arg->int_array.el_size);
894                 break;
895         case TEP_PRINT_TYPE:
896                 free(arg->typecast.type);
897                 free_arg(arg->typecast.item);
898                 break;
899         case TEP_PRINT_STRING:
900         case TEP_PRINT_BSTRING:
901                 free(arg->string.string);
902                 break;
903         case TEP_PRINT_BITMASK:
904                 free(arg->bitmask.bitmask);
905                 break;
906         case TEP_PRINT_DYNAMIC_ARRAY:
907         case TEP_PRINT_DYNAMIC_ARRAY_LEN:
908                 free(arg->dynarray.index);
909                 break;
910         case TEP_PRINT_OP:
911                 free(arg->op.op);
912                 free_arg(arg->op.left);
913                 free_arg(arg->op.right);
914                 break;
915         case TEP_PRINT_FUNC:
916                 while (arg->func.args) {
917                         farg = arg->func.args;
918                         arg->func.args = farg->next;
919                         free_arg(farg);
920                 }
921                 break;
922
923         case TEP_PRINT_NULL:
924         default:
925                 break;
926         }
927
928         free(arg);
929 }
930
931 static enum tep_event_type get_type(int ch)
932 {
933         if (ch == '\n')
934                 return TEP_EVENT_NEWLINE;
935         if (isspace(ch))
936                 return TEP_EVENT_SPACE;
937         if (isalnum(ch) || ch == '_')
938                 return TEP_EVENT_ITEM;
939         if (ch == '\'')
940                 return TEP_EVENT_SQUOTE;
941         if (ch == '"')
942                 return TEP_EVENT_DQUOTE;
943         if (!isprint(ch))
944                 return TEP_EVENT_NONE;
945         if (ch == '(' || ch == ')' || ch == ',')
946                 return TEP_EVENT_DELIM;
947
948         return TEP_EVENT_OP;
949 }
950
951 static int __read_char(void)
952 {
953         if (input_buf_ptr >= input_buf_siz)
954                 return -1;
955
956         return input_buf[input_buf_ptr++];
957 }
958
959 /**
960  * peek_char - peek at the next character that will be read
961  *
962  * Returns the next character read, or -1 if end of buffer.
963  */
964 __hidden int peek_char(void)
965 {
966         if (input_buf_ptr >= input_buf_siz)
967                 return -1;
968
969         return input_buf[input_buf_ptr];
970 }
971
972 static int extend_token(char **tok, char *buf, int size)
973 {
974         char *newtok = realloc(*tok, size);
975
976         if (!newtok) {
977                 free(*tok);
978                 *tok = NULL;
979                 return -1;
980         }
981
982         if (!*tok)
983                 strcpy(newtok, buf);
984         else
985                 strcat(newtok, buf);
986         *tok = newtok;
987
988         return 0;
989 }
990
991 static enum tep_event_type force_token(const char *str, char **tok);
992
993 static enum tep_event_type __read_token(char **tok)
994 {
995         char buf[BUFSIZ];
996         int ch, last_ch, quote_ch, next_ch;
997         int i = 0;
998         int tok_size = 0;
999         enum tep_event_type type;
1000
1001         *tok = NULL;
1002
1003
1004         ch = __read_char();
1005         if (ch < 0)
1006                 return TEP_EVENT_NONE;
1007
1008         type = get_type(ch);
1009         if (type == TEP_EVENT_NONE)
1010                 return type;
1011
1012         buf[i++] = ch;
1013
1014         switch (type) {
1015         case TEP_EVENT_NEWLINE:
1016         case TEP_EVENT_DELIM:
1017                 if (asprintf(tok, "%c", ch) < 0)
1018                         return TEP_EVENT_ERROR;
1019
1020                 return type;
1021
1022         case TEP_EVENT_OP:
1023                 switch (ch) {
1024                 case '-':
1025                         next_ch = peek_char();
1026                         if (next_ch == '>') {
1027                                 buf[i++] = __read_char();
1028                                 break;
1029                         }
1030                         /* fall through */
1031                 case '+':
1032                 case '|':
1033                 case '&':
1034                 case '>':
1035                 case '<':
1036                         last_ch = ch;
1037                         ch = peek_char();
1038                         if (ch != last_ch)
1039                                 goto test_equal;
1040                         buf[i++] = __read_char();
1041                         switch (last_ch) {
1042                         case '>':
1043                         case '<':
1044                                 goto test_equal;
1045                         default:
1046                                 break;
1047                         }
1048                         break;
1049                 case '!':
1050                 case '=':
1051                         goto test_equal;
1052                 default: /* what should we do instead? */
1053                         break;
1054                 }
1055                 buf[i] = 0;
1056                 *tok = strdup(buf);
1057                 return type;
1058
1059  test_equal:
1060                 ch = peek_char();
1061                 if (ch == '=')
1062                         buf[i++] = __read_char();
1063                 goto out;
1064
1065         case TEP_EVENT_DQUOTE:
1066         case TEP_EVENT_SQUOTE:
1067                 /* don't keep quotes */
1068                 i--;
1069                 quote_ch = ch;
1070                 last_ch = 0;
1071  concat:
1072                 do {
1073                         if (i == (BUFSIZ - 1)) {
1074                                 buf[i] = 0;
1075                                 tok_size += BUFSIZ;
1076
1077                                 if (extend_token(tok, buf, tok_size) < 0)
1078                                         return TEP_EVENT_NONE;
1079                                 i = 0;
1080                         }
1081                         last_ch = ch;
1082                         ch = __read_char();
1083                         buf[i++] = ch;
1084                         /* the '\' '\' will cancel itself */
1085                         if (ch == '\\' && last_ch == '\\')
1086                                 last_ch = 0;
1087                 } while (ch != quote_ch || last_ch == '\\');
1088                 /* remove the last quote */
1089                 i--;
1090
1091                 /*
1092                  * For strings (double quotes) check the next token.
1093                  * If it is another string, concatinate the two.
1094                  */
1095                 if (type == TEP_EVENT_DQUOTE) {
1096                         unsigned long long save_input_buf_ptr = input_buf_ptr;
1097
1098                         do {
1099                                 ch = __read_char();
1100                         } while (isspace(ch));
1101                         if (ch == '"')
1102                                 goto concat;
1103                         input_buf_ptr = save_input_buf_ptr;
1104                 }
1105
1106                 goto out;
1107
1108         case TEP_EVENT_ERROR ... TEP_EVENT_SPACE:
1109         case TEP_EVENT_ITEM:
1110         default:
1111                 break;
1112         }
1113
1114         while (get_type(peek_char()) == type) {
1115                 if (i == (BUFSIZ - 1)) {
1116                         buf[i] = 0;
1117                         tok_size += BUFSIZ;
1118
1119                         if (extend_token(tok, buf, tok_size) < 0)
1120                                 return TEP_EVENT_NONE;
1121                         i = 0;
1122                 }
1123                 ch = __read_char();
1124                 buf[i++] = ch;
1125         }
1126
1127  out:
1128         buf[i] = 0;
1129         if (extend_token(tok, buf, tok_size + i + 1) < 0)
1130                 return TEP_EVENT_NONE;
1131
1132         if (type == TEP_EVENT_ITEM) {
1133                 /*
1134                  * Older versions of the kernel has a bug that
1135                  * creates invalid symbols and will break the mac80211
1136                  * parsing. This is a work around to that bug.
1137                  *
1138                  * See Linux kernel commit:
1139                  *  811cb50baf63461ce0bdb234927046131fc7fa8b
1140                  */
1141                 if (strcmp(*tok, "LOCAL_PR_FMT") == 0) {
1142                         free(*tok);
1143                         *tok = NULL;
1144                         return force_token("\"%s\" ", tok);
1145                 } else if (strcmp(*tok, "STA_PR_FMT") == 0) {
1146                         free(*tok);
1147                         *tok = NULL;
1148                         return force_token("\" sta:%pM\" ", tok);
1149                 } else if (strcmp(*tok, "VIF_PR_FMT") == 0) {
1150                         free(*tok);
1151                         *tok = NULL;
1152                         return force_token("\" vif:%p(%d)\" ", tok);
1153                 }
1154         }
1155
1156         return type;
1157 }
1158
1159 static enum tep_event_type force_token(const char *str, char **tok)
1160 {
1161         const char *save_input_buf;
1162         unsigned long long save_input_buf_ptr;
1163         unsigned long long save_input_buf_siz;
1164         enum tep_event_type type;
1165         
1166         /* save off the current input pointers */
1167         save_input_buf = input_buf;
1168         save_input_buf_ptr = input_buf_ptr;
1169         save_input_buf_siz = input_buf_siz;
1170
1171         init_input_buf(str, strlen(str));
1172
1173         type = __read_token(tok);
1174
1175         /* reset back to original token */
1176         input_buf = save_input_buf;
1177         input_buf_ptr = save_input_buf_ptr;
1178         input_buf_siz = save_input_buf_siz;
1179
1180         return type;
1181 }
1182
1183 /**
1184  * free_token - free a token returned by tep_read_token
1185  * @token: the token to free
1186  */
1187 __hidden void free_token(char *tok)
1188 {
1189         if (tok)
1190                 free(tok);
1191 }
1192
1193 /**
1194  * read_token - access to utilities to use the tep parser
1195  * @tok: The token to return
1196  *
1197  * This will parse tokens from the string given by
1198  * tep_init_data().
1199  *
1200  * Returns the token type.
1201  */
1202 __hidden enum tep_event_type read_token(char **tok)
1203 {
1204         enum tep_event_type type;
1205
1206         for (;;) {
1207                 type = __read_token(tok);
1208                 if (type != TEP_EVENT_SPACE)
1209                         return type;
1210
1211                 free_token(*tok);
1212         }
1213
1214         /* not reached */
1215         *tok = NULL;
1216         return TEP_EVENT_NONE;
1217 }
1218
1219 /* no newline */
1220 static enum tep_event_type read_token_item(char **tok)
1221 {
1222         enum tep_event_type type;
1223
1224         for (;;) {
1225                 type = __read_token(tok);
1226                 if (type != TEP_EVENT_SPACE && type != TEP_EVENT_NEWLINE)
1227                         return type;
1228                 free_token(*tok);
1229                 *tok = NULL;
1230         }
1231
1232         /* not reached */
1233         *tok = NULL;
1234         return TEP_EVENT_NONE;
1235 }
1236
1237 static int test_type(enum tep_event_type type, enum tep_event_type expect)
1238 {
1239         if (type != expect) {
1240                 do_warning("Error: expected type %d but read %d",
1241                     expect, type);
1242                 return -1;
1243         }
1244         return 0;
1245 }
1246
1247 static int test_type_token(enum tep_event_type type, const char *token,
1248                     enum tep_event_type expect, const char *expect_tok)
1249 {
1250         if (type != expect) {
1251                 do_warning("Error: expected type %d but read %d",
1252                     expect, type);
1253                 return -1;
1254         }
1255
1256         if (strcmp(token, expect_tok) != 0) {
1257                 do_warning("Error: expected '%s' but read '%s'",
1258                     expect_tok, token);
1259                 return -1;
1260         }
1261         return 0;
1262 }
1263
1264 static int __read_expect_type(enum tep_event_type expect, char **tok, int newline_ok)
1265 {
1266         enum tep_event_type type;
1267
1268         if (newline_ok)
1269                 type = read_token(tok);
1270         else
1271                 type = read_token_item(tok);
1272         return test_type(type, expect);
1273 }
1274
1275 static int read_expect_type(enum tep_event_type expect, char **tok)
1276 {
1277         return __read_expect_type(expect, tok, 1);
1278 }
1279
1280 static int __read_expected(enum tep_event_type expect, const char *str,
1281                            int newline_ok)
1282 {
1283         enum tep_event_type type;
1284         char *token;
1285         int ret;
1286
1287         if (newline_ok)
1288                 type = read_token(&token);
1289         else
1290                 type = read_token_item(&token);
1291
1292         ret = test_type_token(type, token, expect, str);
1293
1294         free_token(token);
1295
1296         return ret;
1297 }
1298
1299 static int read_expected(enum tep_event_type expect, const char *str)
1300 {
1301         return __read_expected(expect, str, 1);
1302 }
1303
1304 static int read_expected_item(enum tep_event_type expect, const char *str)
1305 {
1306         return __read_expected(expect, str, 0);
1307 }
1308
1309 static char *event_read_name(void)
1310 {
1311         char *token;
1312
1313         if (read_expected(TEP_EVENT_ITEM, "name") < 0)
1314                 return NULL;
1315
1316         if (read_expected(TEP_EVENT_OP, ":") < 0)
1317                 return NULL;
1318
1319         if (read_expect_type(TEP_EVENT_ITEM, &token) < 0)
1320                 goto fail;
1321
1322         return token;
1323
1324  fail:
1325         free_token(token);
1326         return NULL;
1327 }
1328
1329 static int event_read_id(void)
1330 {
1331         char *token;
1332         int id;
1333
1334         if (read_expected_item(TEP_EVENT_ITEM, "ID") < 0)
1335                 return -1;
1336
1337         if (read_expected(TEP_EVENT_OP, ":") < 0)
1338                 return -1;
1339
1340         if (read_expect_type(TEP_EVENT_ITEM, &token) < 0)
1341                 goto fail;
1342
1343         id = strtoul(token, NULL, 0);
1344         free_token(token);
1345         return id;
1346
1347  fail:
1348         free_token(token);
1349         return -1;
1350 }
1351
1352 static int field_is_string(struct tep_format_field *field)
1353 {
1354         if ((field->flags & TEP_FIELD_IS_ARRAY) &&
1355             (strstr(field->type, "char") || strstr(field->type, "u8") ||
1356              strstr(field->type, "s8")))
1357                 return 1;
1358
1359         return 0;
1360 }
1361
1362 static int field_is_dynamic(struct tep_format_field *field)
1363 {
1364         if (strncmp(field->type, "__data_loc", 10) == 0)
1365                 return 1;
1366
1367         return 0;
1368 }
1369
1370 static int field_is_long(struct tep_format_field *field)
1371 {
1372         /* includes long long */
1373         if (strstr(field->type, "long"))
1374                 return 1;
1375
1376         return 0;
1377 }
1378
1379 static unsigned int type_size(const char *name)
1380 {
1381         /* This covers all TEP_FIELD_IS_STRING types. */
1382         static struct {
1383                 const char *type;
1384                 unsigned int size;
1385         } table[] = {
1386                 { "u8",   1 },
1387                 { "u16",  2 },
1388                 { "u32",  4 },
1389                 { "u64",  8 },
1390                 { "s8",   1 },
1391                 { "s16",  2 },
1392                 { "s32",  4 },
1393                 { "s64",  8 },
1394                 { "char", 1 },
1395                 { },
1396         };
1397         int i;
1398
1399         for (i = 0; table[i].type; i++) {
1400                 if (!strcmp(table[i].type, name))
1401                         return table[i].size;
1402         }
1403
1404         return 0;
1405 }
1406
1407 static int append(char **buf, const char *delim, const char *str)
1408 {
1409         char *new_buf;
1410
1411         new_buf = realloc(*buf, strlen(*buf) + strlen(delim) + strlen(str) + 1);
1412         if (!new_buf)
1413                 return -1;
1414         strcat(new_buf, delim);
1415         strcat(new_buf, str);
1416         *buf = new_buf;
1417         return 0;
1418 }
1419
1420 static int event_read_fields(struct tep_event *event, struct tep_format_field **fields)
1421 {
1422         struct tep_format_field *field = NULL;
1423         enum tep_event_type type;
1424         char *token;
1425         char *last_token;
1426         char *delim = " ";
1427         int count = 0;
1428         int ret;
1429
1430         do {
1431                 unsigned int size_dynamic = 0;
1432
1433                 type = read_token(&token);
1434                 if (type == TEP_EVENT_NEWLINE) {
1435                         free_token(token);
1436                         return count;
1437                 }
1438
1439                 count++;
1440
1441                 if (test_type_token(type, token, TEP_EVENT_ITEM, "field"))
1442                         goto fail;
1443                 free_token(token);
1444
1445                 type = read_token(&token);
1446                 /*
1447                  * The ftrace fields may still use the "special" name.
1448                  * Just ignore it.
1449                  */
1450                 if (event->flags & TEP_EVENT_FL_ISFTRACE &&
1451                     type == TEP_EVENT_ITEM && strcmp(token, "special") == 0) {
1452                         free_token(token);
1453                         type = read_token(&token);
1454                 }
1455
1456                 if (test_type_token(type, token, TEP_EVENT_OP, ":") < 0)
1457                         goto fail;
1458
1459                 free_token(token);
1460                 if (read_expect_type(TEP_EVENT_ITEM, &token) < 0)
1461                         goto fail;
1462
1463                 last_token = token;
1464
1465                 field = calloc(1, sizeof(*field));
1466                 if (!field)
1467                         goto fail;
1468
1469                 field->event = event;
1470
1471                 /* read the rest of the type */
1472                 for (;;) {
1473                         type = read_token(&token);
1474                         if (type == TEP_EVENT_ITEM ||
1475                             (type == TEP_EVENT_OP && strcmp(token, "*") == 0) ||
1476                             /*
1477                              * Some of the ftrace fields are broken and have
1478                              * an illegal "." in them.
1479                              */
1480                             (event->flags & TEP_EVENT_FL_ISFTRACE &&
1481                              type == TEP_EVENT_OP && strcmp(token, ".") == 0)) {
1482
1483                                 if (strcmp(token, "*") == 0)
1484                                         field->flags |= TEP_FIELD_IS_POINTER;
1485
1486                                 if (field->type) {
1487                                         ret = append(&field->type, delim, last_token);
1488                                         free(last_token);
1489                                         if (ret < 0)
1490                                                 goto fail;
1491                                 } else
1492                                         field->type = last_token;
1493                                 last_token = token;
1494                                 delim = " ";
1495                                 continue;
1496                         }
1497
1498                         /* Handle __attribute__((user)) */
1499                         if ((type == TEP_EVENT_DELIM) &&
1500                             strcmp("__attribute__", last_token) == 0 &&
1501                             token[0] == '(') {
1502                                 int depth = 1;
1503                                 int ret;
1504
1505                                 ret = append(&field->type, " ", last_token);
1506                                 ret |= append(&field->type, "", "(");
1507                                 if (ret < 0)
1508                                         goto fail;
1509
1510                                 delim = " ";
1511                                 while ((type = read_token(&token)) != TEP_EVENT_NONE) {
1512                                         if (type == TEP_EVENT_DELIM) {
1513                                                 if (token[0] == '(')
1514                                                         depth++;
1515                                                 else if (token[0] == ')')
1516                                                         depth--;
1517                                                 if (!depth)
1518                                                         break;
1519                                                 ret = append(&field->type, "", token);
1520                                                 delim = "";
1521                                         } else {
1522                                                 ret = append(&field->type, delim, token);
1523                                                 delim = " ";
1524                                         }
1525                                         if (ret < 0)
1526                                                 goto fail;
1527                                         free(last_token);
1528                                         last_token = token;
1529                                 }
1530                                 continue;
1531                         }
1532                         break;
1533                 }
1534
1535                 if (!field->type) {
1536                         do_warning_event(event, "%s: no type found", __func__);
1537                         goto fail;
1538                 }
1539                 field->name = field->alias = last_token;
1540
1541                 if (test_type(type, TEP_EVENT_OP))
1542                         goto fail;
1543
1544                 if (strcmp(token, "[") == 0) {
1545                         enum tep_event_type last_type = type;
1546                         char *brackets = token;
1547
1548                         field->flags |= TEP_FIELD_IS_ARRAY;
1549
1550                         type = read_token(&token);
1551
1552                         if (type == TEP_EVENT_ITEM)
1553                                 field->arraylen = strtoul(token, NULL, 0);
1554                         else
1555                                 field->arraylen = 0;
1556
1557                         while (strcmp(token, "]") != 0) {
1558                                 const char *delim;
1559
1560                                 if (last_type == TEP_EVENT_ITEM &&
1561                                     type == TEP_EVENT_ITEM)
1562                                         delim = " ";
1563                                 else
1564                                         delim = "";
1565
1566                                 last_type = type;
1567
1568                                 ret = append(&brackets, delim, token);
1569                                 if (ret < 0) {
1570                                         free(brackets);
1571                                         goto fail;
1572                                 }
1573                                 /* We only care about the last token */
1574                                 field->arraylen = strtoul(token, NULL, 0);
1575                                 free_token(token);
1576                                 type = read_token(&token);
1577                                 if (type == TEP_EVENT_NONE) {
1578                                         free(brackets);
1579                                         do_warning_event(event, "failed to find token");
1580                                         goto fail;
1581                                 }
1582                         }
1583
1584                         free_token(token);
1585
1586                         ret = append(&brackets, "", "]");
1587                         if (ret < 0) {
1588                                 free(brackets);
1589                                 goto fail;
1590                         }
1591
1592                         /* add brackets to type */
1593
1594                         type = read_token(&token);
1595                         /*
1596                          * If the next token is not an OP, then it is of
1597                          * the format: type [] item;
1598                          */
1599                         if (type == TEP_EVENT_ITEM) {
1600                                 ret = append(&field->type, " ", field->name);
1601                                 if (ret < 0) {
1602                                         free(brackets);
1603                                         goto fail;
1604                                 }
1605                                 ret = append(&field->type, "", brackets);
1606
1607                                 size_dynamic = type_size(field->name);
1608                                 free_token(field->name);
1609                                 field->name = field->alias = token;
1610                                 type = read_token(&token);
1611                         } else {
1612                                 ret = append(&field->type, "", brackets);
1613                                 if (ret < 0) {
1614                                         free(brackets);
1615                                         goto fail;
1616                                 }
1617                         }
1618                         free(brackets);
1619                 }
1620
1621                 if (field_is_string(field))
1622                         field->flags |= TEP_FIELD_IS_STRING;
1623                 if (field_is_dynamic(field))
1624                         field->flags |= TEP_FIELD_IS_DYNAMIC;
1625                 if (field_is_long(field))
1626                         field->flags |= TEP_FIELD_IS_LONG;
1627
1628                 if (test_type_token(type, token,  TEP_EVENT_OP, ";"))
1629                         goto fail;
1630                 free_token(token);
1631
1632                 if (read_expected(TEP_EVENT_ITEM, "offset") < 0)
1633                         goto fail_expect;
1634
1635                 if (read_expected(TEP_EVENT_OP, ":") < 0)
1636                         goto fail_expect;
1637
1638                 if (read_expect_type(TEP_EVENT_ITEM, &token))
1639                         goto fail;
1640                 field->offset = strtoul(token, NULL, 0);
1641                 free_token(token);
1642
1643                 if (read_expected(TEP_EVENT_OP, ";") < 0)
1644                         goto fail_expect;
1645
1646                 if (read_expected(TEP_EVENT_ITEM, "size") < 0)
1647                         goto fail_expect;
1648
1649                 if (read_expected(TEP_EVENT_OP, ":") < 0)
1650                         goto fail_expect;
1651
1652                 if (read_expect_type(TEP_EVENT_ITEM, &token))
1653                         goto fail;
1654                 field->size = strtoul(token, NULL, 0);
1655                 free_token(token);
1656
1657                 if (read_expected(TEP_EVENT_OP, ";") < 0)
1658                         goto fail_expect;
1659
1660                 type = read_token(&token);
1661                 if (type != TEP_EVENT_NEWLINE) {
1662                         /* newer versions of the kernel have a "signed" type */
1663                         if (test_type_token(type, token, TEP_EVENT_ITEM, "signed"))
1664                                 goto fail;
1665
1666                         free_token(token);
1667
1668                         if (read_expected(TEP_EVENT_OP, ":") < 0)
1669                                 goto fail_expect;
1670
1671                         if (read_expect_type(TEP_EVENT_ITEM, &token))
1672                                 goto fail;
1673
1674                         if (strtoul(token, NULL, 0))
1675                                 field->flags |= TEP_FIELD_IS_SIGNED;
1676
1677                         free_token(token);
1678                         if (read_expected(TEP_EVENT_OP, ";") < 0)
1679                                 goto fail_expect;
1680
1681                         if (read_expect_type(TEP_EVENT_NEWLINE, &token))
1682                                 goto fail;
1683                 }
1684
1685                 free_token(token);
1686
1687                 if (field->flags & TEP_FIELD_IS_ARRAY) {
1688                         if (field->arraylen)
1689                                 field->elementsize = field->size / field->arraylen;
1690                         else if (field->flags & TEP_FIELD_IS_DYNAMIC)
1691                                 field->elementsize = size_dynamic;
1692                         else if (field->flags & TEP_FIELD_IS_STRING)
1693                                 field->elementsize = 1;
1694                         else if (field->flags & TEP_FIELD_IS_LONG)
1695                                 field->elementsize = event->tep ?
1696                                                      event->tep->long_size :
1697                                                      sizeof(long);
1698                 } else
1699                         field->elementsize = field->size;
1700
1701                 *fields = field;
1702                 fields = &field->next;
1703
1704         } while (1);
1705
1706         return 0;
1707
1708 fail:
1709         free_token(token);
1710 fail_expect:
1711         if (field) {
1712                 free(field->type);
1713                 free(field->name);
1714                 free(field);
1715         }
1716         return -1;
1717 }
1718
1719 static int event_read_format(struct tep_event *event)
1720 {
1721         char *token;
1722         int ret;
1723
1724         if (read_expected_item(TEP_EVENT_ITEM, "format") < 0)
1725                 return -1;
1726
1727         if (read_expected(TEP_EVENT_OP, ":") < 0)
1728                 return -1;
1729
1730         if (read_expect_type(TEP_EVENT_NEWLINE, &token))
1731                 goto fail;
1732         free_token(token);
1733
1734         ret = event_read_fields(event, &event->format.common_fields);
1735         if (ret < 0)
1736                 return ret;
1737         event->format.nr_common = ret;
1738
1739         ret = event_read_fields(event, &event->format.fields);
1740         if (ret < 0)
1741                 return ret;
1742         event->format.nr_fields = ret;
1743
1744         return 0;
1745
1746  fail:
1747         free_token(token);
1748         return -1;
1749 }
1750
1751 static enum tep_event_type
1752 process_arg_token(struct tep_event *event, struct tep_print_arg *arg,
1753                   char **tok, enum tep_event_type type);
1754
1755 static enum tep_event_type
1756 process_arg(struct tep_event *event, struct tep_print_arg *arg, char **tok)
1757 {
1758         enum tep_event_type type;
1759         char *token;
1760
1761         type = read_token(&token);
1762         *tok = token;
1763
1764         return process_arg_token(event, arg, tok, type);
1765 }
1766
1767 static enum tep_event_type
1768 process_op(struct tep_event *event, struct tep_print_arg *arg, char **tok);
1769
1770 /*
1771  * For __print_symbolic() and __print_flags, we need to completely
1772  * evaluate the first argument, which defines what to print next.
1773  */
1774 static enum tep_event_type
1775 process_field_arg(struct tep_event *event, struct tep_print_arg *arg, char **tok)
1776 {
1777         enum tep_event_type type;
1778
1779         type = process_arg(event, arg, tok);
1780
1781         while (type == TEP_EVENT_OP) {
1782                 type = process_op(event, arg, tok);
1783         }
1784
1785         return type;
1786 }
1787
1788 static enum tep_event_type
1789 process_cond(struct tep_event *event, struct tep_print_arg *top, char **tok)
1790 {
1791         struct tep_print_arg *arg, *left, *right;
1792         enum tep_event_type type;
1793         char *token = NULL;
1794
1795         arg = alloc_arg();
1796         left = alloc_arg();
1797         right = alloc_arg();
1798
1799         if (!arg || !left || !right) {
1800                 do_warning_event(event, "%s: not enough memory!", __func__);
1801                 /* arg will be freed at out_free */
1802                 free_arg(left);
1803                 free_arg(right);
1804                 goto out_free;
1805         }
1806
1807         arg->type = TEP_PRINT_OP;
1808         arg->op.left = left;
1809         arg->op.right = right;
1810
1811         *tok = NULL;
1812         type = process_arg(event, left, &token);
1813
1814  again:
1815         if (type == TEP_EVENT_ERROR)
1816                 goto out_free;
1817
1818         /* Handle other operations in the arguments */
1819         if (type == TEP_EVENT_OP && strcmp(token, ":") != 0) {
1820                 type = process_op(event, left, &token);
1821                 goto again;
1822         }
1823
1824         if (test_type_token(type, token, TEP_EVENT_OP, ":"))
1825                 goto out_free;
1826
1827         arg->op.op = token;
1828
1829         type = process_arg(event, right, &token);
1830
1831         top->op.right = arg;
1832
1833         *tok = token;
1834         return type;
1835
1836 out_free:
1837         /* Top may point to itself */
1838         top->op.right = NULL;
1839         free_token(token);
1840         free_arg(arg);
1841         return TEP_EVENT_ERROR;
1842 }
1843
1844 static enum tep_event_type
1845 process_array(struct tep_event *event, struct tep_print_arg *top, char **tok)
1846 {
1847         struct tep_print_arg *arg;
1848         enum tep_event_type type;
1849         char *token = NULL;
1850
1851         arg = alloc_arg();
1852         if (!arg) {
1853                 do_warning_event(event, "%s: not enough memory!", __func__);
1854                 /* '*tok' is set to top->op.op.  No need to free. */
1855                 *tok = NULL;
1856                 return TEP_EVENT_ERROR;
1857         }
1858
1859         *tok = NULL;
1860         type = process_arg(event, arg, &token);
1861         if (test_type_token(type, token, TEP_EVENT_OP, "]"))
1862                 goto out_free;
1863
1864         top->op.right = arg;
1865
1866         free_token(token);
1867         type = read_token_item(&token);
1868         *tok = token;
1869
1870         return type;
1871
1872 out_free:
1873         free_token(token);
1874         free_arg(arg);
1875         return TEP_EVENT_ERROR;
1876 }
1877
1878 static int get_op_prio(char *op)
1879 {
1880         if (!op[1]) {
1881                 switch (op[0]) {
1882                 case '~':
1883                 case '!':
1884                         return 4;
1885                 case '*':
1886                 case '/':
1887                 case '%':
1888                         return 6;
1889                 case '+':
1890                 case '-':
1891                         return 7;
1892                         /* '>>' and '<<' are 8 */
1893                 case '<':
1894                 case '>':
1895                         return 9;
1896                         /* '==' and '!=' are 10 */
1897                 case '&':
1898                         return 11;
1899                 case '^':
1900                         return 12;
1901                 case '|':
1902                         return 13;
1903                 case '?':
1904                         return 16;
1905                 default:
1906                         do_warning("unknown op '%c'", op[0]);
1907                         return -1;
1908                 }
1909         } else {
1910                 if (strcmp(op, "++") == 0 ||
1911                     strcmp(op, "--") == 0) {
1912                         return 3;
1913                 } else if (strcmp(op, ">>") == 0 ||
1914                            strcmp(op, "<<") == 0) {
1915                         return 8;
1916                 } else if (strcmp(op, ">=") == 0 ||
1917                            strcmp(op, "<=") == 0) {
1918                         return 9;
1919                 } else if (strcmp(op, "==") == 0 ||
1920                            strcmp(op, "!=") == 0) {
1921                         return 10;
1922                 } else if (strcmp(op, "&&") == 0) {
1923                         return 14;
1924                 } else if (strcmp(op, "||") == 0) {
1925                         return 15;
1926                 } else {
1927                         do_warning("unknown op '%s'", op);
1928                         return -1;
1929                 }
1930         }
1931 }
1932
1933 static int set_op_prio(struct tep_print_arg *arg)
1934 {
1935
1936         /* single ops are the greatest */
1937         if (!arg->op.left || arg->op.left->type == TEP_PRINT_NULL)
1938                 arg->op.prio = 0;
1939         else
1940                 arg->op.prio = get_op_prio(arg->op.op);
1941
1942         return arg->op.prio;
1943 }
1944
1945 /* Note, *tok does not get freed, but will most likely be saved */
1946 static enum tep_event_type
1947 process_op(struct tep_event *event, struct tep_print_arg *arg, char **tok)
1948 {
1949         struct tep_print_arg *left, *right = NULL;
1950         enum tep_event_type type;
1951         char *token;
1952
1953         /* the op is passed in via tok */
1954         token = *tok;
1955
1956         if (arg->type == TEP_PRINT_OP && !arg->op.left) {
1957                 /* handle single op */
1958                 if (token[1]) {
1959                         do_warning_event(event, "bad op token %s", token);
1960                         goto out_free;
1961                 }
1962                 switch (token[0]) {
1963                 case '~':
1964                 case '!':
1965                 case '+':
1966                 case '-':
1967                         break;
1968                 default:
1969                         do_warning_event(event, "bad op token %s", token);
1970                         goto out_free;
1971
1972                 }
1973
1974                 /* make an empty left */
1975                 left = alloc_arg();
1976                 if (!left)
1977                         goto out_warn_free;
1978
1979                 left->type = TEP_PRINT_NULL;
1980                 arg->op.left = left;
1981
1982                 right = alloc_arg();
1983                 if (!right)
1984                         goto out_warn_free;
1985
1986                 arg->op.right = right;
1987
1988                 /* do not free the token, it belongs to an op */
1989                 *tok = NULL;
1990                 type = process_arg(event, right, tok);
1991
1992         } else if (strcmp(token, "?") == 0) {
1993
1994                 left = alloc_arg();
1995                 if (!left)
1996                         goto out_warn_free;
1997
1998                 /* copy the top arg to the left */
1999                 *left = *arg;
2000
2001                 arg->type = TEP_PRINT_OP;
2002                 arg->op.op = token;
2003                 arg->op.left = left;
2004                 arg->op.prio = 0;
2005
2006                 /* it will set arg->op.right */
2007                 type = process_cond(event, arg, tok);
2008
2009         } else if (strcmp(token, ">>") == 0 ||
2010                    strcmp(token, "<<") == 0 ||
2011                    strcmp(token, "&") == 0 ||
2012                    strcmp(token, "|") == 0 ||
2013                    strcmp(token, "&&") == 0 ||
2014                    strcmp(token, "||") == 0 ||
2015                    strcmp(token, "-") == 0 ||
2016                    strcmp(token, "+") == 0 ||
2017                    strcmp(token, "*") == 0 ||
2018                    strcmp(token, "^") == 0 ||
2019                    strcmp(token, "/") == 0 ||
2020                    strcmp(token, "%") == 0 ||
2021                    strcmp(token, "<") == 0 ||
2022                    strcmp(token, ">") == 0 ||
2023                    strcmp(token, "<=") == 0 ||
2024                    strcmp(token, ">=") == 0 ||
2025                    strcmp(token, "==") == 0 ||
2026                    strcmp(token, "!=") == 0) {
2027
2028                 left = alloc_arg();
2029                 if (!left)
2030                         goto out_warn_free;
2031
2032                 /* copy the top arg to the left */
2033                 *left = *arg;
2034
2035                 arg->type = TEP_PRINT_OP;
2036                 arg->op.op = token;
2037                 arg->op.left = left;
2038                 arg->op.right = NULL;
2039
2040                 if (set_op_prio(arg) == -1) {
2041                         event->flags |= TEP_EVENT_FL_FAILED;
2042                         /* arg->op.op (= token) will be freed at out_free */
2043                         arg->op.op = NULL;
2044                         goto out_free;
2045                 }
2046
2047                 type = read_token_item(&token);
2048                 *tok = token;
2049
2050                 /* could just be a type pointer */
2051                 if ((strcmp(arg->op.op, "*") == 0) &&
2052                     type == TEP_EVENT_DELIM && (strcmp(token, ")") == 0)) {
2053                         int ret;
2054
2055                         if (left->type != TEP_PRINT_ATOM) {
2056                                 do_warning_event(event, "bad pointer type");
2057                                 goto out_free;
2058                         }
2059                         ret = append(&left->atom.atom, " ", "*");
2060                         if (ret < 0)
2061                                 goto out_warn_free;
2062
2063                         free(arg->op.op);
2064                         *arg = *left;
2065                         free(left);
2066
2067                         return type;
2068                 }
2069
2070                 right = alloc_arg();
2071                 if (!right)
2072                         goto out_warn_free;
2073
2074                 type = process_arg_token(event, right, tok, type);
2075                 if (type == TEP_EVENT_ERROR) {
2076                         free_arg(right);
2077                         /* token was freed in process_arg_token() via *tok */
2078                         token = NULL;
2079                         goto out_free;
2080                 }
2081
2082                 if (right->type == TEP_PRINT_OP &&
2083                     get_op_prio(arg->op.op) < get_op_prio(right->op.op)) {
2084                         struct tep_print_arg tmp;
2085
2086                         /* rotate ops according to the priority */
2087                         arg->op.right = right->op.left;
2088
2089                         tmp = *arg;
2090                         *arg = *right;
2091                         *right = tmp;
2092
2093                         arg->op.left = right;
2094                 } else {
2095                         arg->op.right = right;
2096                 }
2097
2098         } else if (strcmp(token, "[") == 0) {
2099
2100                 left = alloc_arg();
2101                 if (!left)
2102                         goto out_warn_free;
2103
2104                 *left = *arg;
2105
2106                 arg->type = TEP_PRINT_OP;
2107                 arg->op.op = token;
2108                 arg->op.left = left;
2109
2110                 arg->op.prio = 0;
2111
2112                 /* it will set arg->op.right */
2113                 type = process_array(event, arg, tok);
2114
2115         } else {
2116                 do_warning_event(event, "unknown op '%s'", token);
2117                 event->flags |= TEP_EVENT_FL_FAILED;
2118                 /* the arg is now the left side */
2119                 goto out_free;
2120         }
2121
2122         if (type == TEP_EVENT_OP && strcmp(*tok, ":") != 0) {
2123                 int prio;
2124
2125                 /* higher prios need to be closer to the root */
2126                 prio = get_op_prio(*tok);
2127
2128                 if (prio > arg->op.prio)
2129                         return process_op(event, arg, tok);
2130
2131                 return process_op(event, right, tok);
2132         }
2133
2134         return type;
2135
2136 out_warn_free:
2137         do_warning_event(event, "%s: not enough memory!", __func__);
2138 out_free:
2139         free_token(token);
2140         *tok = NULL;
2141         return TEP_EVENT_ERROR;
2142 }
2143
2144 static enum tep_event_type
2145 process_entry(struct tep_event *event __maybe_unused, struct tep_print_arg *arg,
2146               char **tok)
2147 {
2148         enum tep_event_type type;
2149         char *field;
2150         char *token;
2151
2152         if (read_expected(TEP_EVENT_OP, "->") < 0)
2153                 goto out_err;
2154
2155         if (read_expect_type(TEP_EVENT_ITEM, &token) < 0)
2156                 goto out_free;
2157         field = token;
2158
2159         arg->type = TEP_PRINT_FIELD;
2160         arg->field.name = field;
2161
2162         if (is_flag_field) {
2163                 arg->field.field = tep_find_any_field(event, arg->field.name);
2164                 arg->field.field->flags |= TEP_FIELD_IS_FLAG;
2165                 is_flag_field = 0;
2166         } else if (is_symbolic_field) {
2167                 arg->field.field = tep_find_any_field(event, arg->field.name);
2168                 arg->field.field->flags |= TEP_FIELD_IS_SYMBOLIC;
2169                 is_symbolic_field = 0;
2170         }
2171
2172         type = read_token(&token);
2173         *tok = token;
2174
2175         return type;
2176
2177  out_free:
2178         free_token(token);
2179  out_err:
2180         *tok = NULL;
2181         return TEP_EVENT_ERROR;
2182 }
2183
2184 static int alloc_and_process_delim(struct tep_event *event, char *next_token,
2185                                    struct tep_print_arg **print_arg)
2186 {
2187         struct tep_print_arg *field;
2188         enum tep_event_type type;
2189         char *token;
2190         int ret = 0;
2191
2192         field = alloc_arg();
2193         if (!field) {
2194                 do_warning_event(event, "%s: not enough memory!", __func__);
2195                 errno = ENOMEM;
2196                 return -1;
2197         }
2198
2199         type = process_arg(event, field, &token);
2200
2201         if (test_type_token(type, token, TEP_EVENT_DELIM, next_token)) {
2202                 errno = EINVAL;
2203                 ret = -1;
2204                 free_arg(field);
2205                 goto out_free_token;
2206         }
2207
2208         *print_arg = field;
2209
2210 out_free_token:
2211         free_token(token);
2212
2213         return ret;
2214 }
2215
2216 static char *arg_eval (struct tep_print_arg *arg);
2217
2218 static unsigned long long
2219 eval_type_str(unsigned long long val, const char *type, int pointer)
2220 {
2221         int sign = 0;
2222         char *ref;
2223         int len;
2224
2225         len = strlen(type);
2226
2227         if (pointer) {
2228
2229                 if (type[len-1] != '*') {
2230                         do_warning("pointer expected with non pointer type");
2231                         return val;
2232                 }
2233
2234                 ref = malloc(len);
2235                 if (!ref) {
2236                         do_warning("%s: not enough memory!", __func__);
2237                         return val;
2238                 }
2239                 memcpy(ref, type, len);
2240
2241                 /* chop off the " *" */
2242                 ref[len - 2] = 0;
2243
2244                 val = eval_type_str(val, ref, 0);
2245                 free(ref);
2246                 return val;
2247         }
2248
2249         /* check if this is a pointer */
2250         if (type[len - 1] == '*')
2251                 return val;
2252
2253         /* Try to figure out the arg size*/
2254         if (strncmp(type, "struct", 6) == 0)
2255                 /* all bets off */
2256                 return val;
2257
2258         if (strcmp(type, "u8") == 0)
2259                 return val & 0xff;
2260
2261         if (strcmp(type, "u16") == 0)
2262                 return val & 0xffff;
2263
2264         if (strcmp(type, "u32") == 0)
2265                 return val & 0xffffffff;
2266
2267         if (strcmp(type, "u64") == 0 ||
2268             strcmp(type, "s64") == 0)
2269                 return val;
2270
2271         if (strcmp(type, "s8") == 0)
2272                 return (unsigned long long)(char)val & 0xff;
2273
2274         if (strcmp(type, "s16") == 0)
2275                 return (unsigned long long)(short)val & 0xffff;
2276
2277         if (strcmp(type, "s32") == 0)
2278                 return (unsigned long long)(int)val & 0xffffffff;
2279
2280         if (strncmp(type, "unsigned ", 9) == 0) {
2281                 sign = 0;
2282                 type += 9;
2283         }
2284
2285         if (strcmp(type, "char") == 0) {
2286                 if (sign)
2287                         return (unsigned long long)(char)val & 0xff;
2288                 else
2289                         return val & 0xff;
2290         }
2291
2292         if (strcmp(type, "short") == 0) {
2293                 if (sign)
2294                         return (unsigned long long)(short)val & 0xffff;
2295                 else
2296                         return val & 0xffff;
2297         }
2298
2299         if (strcmp(type, "int") == 0) {
2300                 if (sign)
2301                         return (unsigned long long)(int)val & 0xffffffff;
2302                 else
2303                         return val & 0xffffffff;
2304         }
2305
2306         return val;
2307 }
2308
2309 /*
2310  * Try to figure out the type.
2311  */
2312 static unsigned long long
2313 eval_type(unsigned long long val, struct tep_print_arg *arg, int pointer)
2314 {
2315         if (arg->type != TEP_PRINT_TYPE) {
2316                 do_warning("expected type argument");
2317                 return 0;
2318         }
2319
2320         return eval_type_str(val, arg->typecast.type, pointer);
2321 }
2322
2323 static int arg_num_eval(struct tep_print_arg *arg, long long *val)
2324 {
2325         long long left, right;
2326         int ret = 1;
2327
2328         switch (arg->type) {
2329         case TEP_PRINT_ATOM:
2330                 *val = strtoll(arg->atom.atom, NULL, 0);
2331                 break;
2332         case TEP_PRINT_TYPE:
2333                 ret = arg_num_eval(arg->typecast.item, val);
2334                 if (!ret)
2335                         break;
2336                 *val = eval_type(*val, arg, 0);
2337                 break;
2338         case TEP_PRINT_OP:
2339                 switch (arg->op.op[0]) {
2340                 case '|':
2341                         ret = arg_num_eval(arg->op.left, &left);
2342                         if (!ret)
2343                                 break;
2344                         ret = arg_num_eval(arg->op.right, &right);
2345                         if (!ret)
2346                                 break;
2347                         if (arg->op.op[1])
2348                                 *val = left || right;
2349                         else
2350                                 *val = left | right;
2351                         break;
2352                 case '&':
2353                         ret = arg_num_eval(arg->op.left, &left);
2354                         if (!ret)
2355                                 break;
2356                         ret = arg_num_eval(arg->op.right, &right);
2357                         if (!ret)
2358                                 break;
2359                         if (arg->op.op[1])
2360                                 *val = left && right;
2361                         else
2362                                 *val = left & right;
2363                         break;
2364                 case '<':
2365                         ret = arg_num_eval(arg->op.left, &left);
2366                         if (!ret)
2367                                 break;
2368                         ret = arg_num_eval(arg->op.right, &right);
2369                         if (!ret)
2370                                 break;
2371                         switch (arg->op.op[1]) {
2372                         case 0:
2373                                 *val = left < right;
2374                                 break;
2375                         case '<':
2376                                 *val = left << right;
2377                                 break;
2378                         case '=':
2379                                 *val = left <= right;
2380                                 break;
2381                         default:
2382                                 do_warning("unknown op '%s'", arg->op.op);
2383                                 ret = 0;
2384                         }
2385                         break;
2386                 case '>':
2387                         ret = arg_num_eval(arg->op.left, &left);
2388                         if (!ret)
2389                                 break;
2390                         ret = arg_num_eval(arg->op.right, &right);
2391                         if (!ret)
2392                                 break;
2393                         switch (arg->op.op[1]) {
2394                         case 0:
2395                                 *val = left > right;
2396                                 break;
2397                         case '>':
2398                                 *val = left >> right;
2399                                 break;
2400                         case '=':
2401                                 *val = left >= right;
2402                                 break;
2403                         default:
2404                                 do_warning("unknown op '%s'", arg->op.op);
2405                                 ret = 0;
2406                         }
2407                         break;
2408                 case '=':
2409                         ret = arg_num_eval(arg->op.left, &left);
2410                         if (!ret)
2411                                 break;
2412                         ret = arg_num_eval(arg->op.right, &right);
2413                         if (!ret)
2414                                 break;
2415
2416                         if (arg->op.op[1] != '=') {
2417                                 do_warning("unknown op '%s'", arg->op.op);
2418                                 ret = 0;
2419                         } else
2420                                 *val = left == right;
2421                         break;
2422                 case '!':
2423                         ret = arg_num_eval(arg->op.left, &left);
2424                         if (!ret)
2425                                 break;
2426                         ret = arg_num_eval(arg->op.right, &right);
2427                         if (!ret)
2428                                 break;
2429
2430                         switch (arg->op.op[1]) {
2431                         case '=':
2432                                 *val = left != right;
2433                                 break;
2434                         default:
2435                                 do_warning("unknown op '%s'", arg->op.op);
2436                                 ret = 0;
2437                         }
2438                         break;
2439                 case '-':
2440                         /* check for negative */
2441                         if (arg->op.left->type == TEP_PRINT_NULL)
2442                                 left = 0;
2443                         else
2444                                 ret = arg_num_eval(arg->op.left, &left);
2445                         if (!ret)
2446                                 break;
2447                         ret = arg_num_eval(arg->op.right, &right);
2448                         if (!ret)
2449                                 break;
2450                         *val = left - right;
2451                         break;
2452                 case '+':
2453                         if (arg->op.left->type == TEP_PRINT_NULL)
2454                                 left = 0;
2455                         else
2456                                 ret = arg_num_eval(arg->op.left, &left);
2457                         if (!ret)
2458                                 break;
2459                         ret = arg_num_eval(arg->op.right, &right);
2460                         if (!ret)
2461                                 break;
2462                         *val = left + right;
2463                         break;
2464                 case '~':
2465                         ret = arg_num_eval(arg->op.right, &right);
2466                         if (!ret)
2467                                 break;
2468                         *val = ~right;
2469                         break;
2470                 default:
2471                         do_warning("unknown op '%s'", arg->op.op);
2472                         ret = 0;
2473                 }
2474                 break;
2475
2476         case TEP_PRINT_NULL:
2477         case TEP_PRINT_FIELD ... TEP_PRINT_SYMBOL:
2478         case TEP_PRINT_STRING:
2479         case TEP_PRINT_BSTRING:
2480         case TEP_PRINT_BITMASK:
2481         default:
2482                 do_warning("invalid eval type %d", arg->type);
2483                 ret = 0;
2484
2485         }
2486         return ret;
2487 }
2488
2489 static char *arg_eval (struct tep_print_arg *arg)
2490 {
2491         long long val;
2492         static char buf[24];
2493
2494         switch (arg->type) {
2495         case TEP_PRINT_ATOM:
2496                 return arg->atom.atom;
2497         case TEP_PRINT_TYPE:
2498                 return arg_eval(arg->typecast.item);
2499         case TEP_PRINT_OP:
2500                 if (!arg_num_eval(arg, &val))
2501                         break;
2502                 sprintf(buf, "%lld", val);
2503                 return buf;
2504
2505         case TEP_PRINT_NULL:
2506         case TEP_PRINT_FIELD ... TEP_PRINT_SYMBOL:
2507         case TEP_PRINT_STRING:
2508         case TEP_PRINT_BSTRING:
2509         case TEP_PRINT_BITMASK:
2510         default:
2511                 do_warning("invalid eval type %d", arg->type);
2512                 break;
2513         }
2514
2515         return NULL;
2516 }
2517
2518 static enum tep_event_type
2519 process_fields(struct tep_event *event, struct tep_print_flag_sym **list, char **tok)
2520 {
2521         enum tep_event_type type;
2522         struct tep_print_arg *arg = NULL;
2523         struct tep_print_flag_sym *field;
2524         char *token = *tok;
2525         char *value;
2526
2527         do {
2528                 free_token(token);
2529                 type = read_token_item(&token);
2530                 if (test_type_token(type, token, TEP_EVENT_OP, "{"))
2531                         break;
2532
2533                 arg = alloc_arg();
2534                 if (!arg)
2535                         goto out_free;
2536
2537                 free_token(token);
2538                 type = process_arg(event, arg, &token);
2539
2540                 if (type == TEP_EVENT_OP)
2541                         type = process_op(event, arg, &token);
2542
2543                 if (type == TEP_EVENT_ERROR)
2544                         goto out_free;
2545
2546                 if (test_type_token(type, token, TEP_EVENT_DELIM, ","))
2547                         goto out_free;
2548
2549                 field = calloc(1, sizeof(*field));
2550                 if (!field)
2551                         goto out_free;
2552
2553                 value = arg_eval(arg);
2554                 if (value == NULL)
2555                         goto out_free_field;
2556                 field->value = strdup(value);
2557                 if (field->value == NULL)
2558                         goto out_free_field;
2559
2560                 free_arg(arg);
2561                 arg = alloc_arg();
2562                 if (!arg)
2563                         goto out_free;
2564
2565                 free_token(token);
2566                 type = process_arg(event, arg, &token);
2567                 if (test_type_token(type, token, TEP_EVENT_OP, "}"))
2568                         goto out_free_field;
2569
2570                 value = arg_eval(arg);
2571                 if (value == NULL)
2572                         goto out_free_field;
2573                 field->str = strdup(value);
2574                 if (field->str == NULL)
2575                         goto out_free_field;
2576                 free_arg(arg);
2577                 arg = NULL;
2578
2579                 *list = field;
2580                 list = &field->next;
2581
2582                 free_token(token);
2583                 type = read_token_item(&token);
2584         } while (type == TEP_EVENT_DELIM && strcmp(token, ",") == 0);
2585
2586         *tok = token;
2587         return type;
2588
2589 out_free_field:
2590         free_flag_sym(field);
2591 out_free:
2592         free_arg(arg);
2593         free_token(token);
2594         *tok = NULL;
2595
2596         return TEP_EVENT_ERROR;
2597 }
2598
2599 static enum tep_event_type
2600 process_flags(struct tep_event *event, struct tep_print_arg *arg, char **tok)
2601 {
2602         struct tep_print_arg *field;
2603         enum tep_event_type type;
2604         char *token = NULL;
2605
2606         memset(arg, 0, sizeof(*arg));
2607         arg->type = TEP_PRINT_FLAGS;
2608
2609         field = alloc_arg();
2610         if (!field) {
2611                 do_warning_event(event, "%s: not enough memory!", __func__);
2612                 goto out_free;
2613         }
2614
2615         type = process_field_arg(event, field, &token);
2616
2617         /* Handle operations in the first argument */
2618         while (type == TEP_EVENT_OP)
2619                 type = process_op(event, field, &token);
2620
2621         if (test_type_token(type, token, TEP_EVENT_DELIM, ","))
2622                 goto out_free_field;
2623         free_token(token);
2624
2625         arg->flags.field = field;
2626
2627         type = read_token_item(&token);
2628         if (event_item_type(type)) {
2629                 arg->flags.delim = token;
2630                 type = read_token_item(&token);
2631         }
2632
2633         if (test_type_token(type, token, TEP_EVENT_DELIM, ","))
2634                 goto out_free;
2635
2636         type = process_fields(event, &arg->flags.flags, &token);
2637         if (test_type_token(type, token, TEP_EVENT_DELIM, ")"))
2638                 goto out_free;
2639
2640         free_token(token);
2641         type = read_token_item(tok);
2642         return type;
2643
2644 out_free_field:
2645         free_arg(field);
2646 out_free:
2647         free_token(token);
2648         *tok = NULL;
2649         return TEP_EVENT_ERROR;
2650 }
2651
2652 static enum tep_event_type
2653 process_symbols(struct tep_event *event, struct tep_print_arg *arg, char **tok)
2654 {
2655         struct tep_print_arg *field;
2656         enum tep_event_type type;
2657         char *token = NULL;
2658
2659         memset(arg, 0, sizeof(*arg));
2660         arg->type = TEP_PRINT_SYMBOL;
2661
2662         field = alloc_arg();
2663         if (!field) {
2664                 do_warning_event(event, "%s: not enough memory!", __func__);
2665                 goto out_free;
2666         }
2667
2668         type = process_field_arg(event, field, &token);
2669
2670         if (test_type_token(type, token, TEP_EVENT_DELIM, ","))
2671                 goto out_free_field;
2672
2673         arg->symbol.field = field;
2674
2675         type = process_fields(event, &arg->symbol.symbols, &token);
2676         if (test_type_token(type, token, TEP_EVENT_DELIM, ")"))
2677                 goto out_free;
2678
2679         free_token(token);
2680         type = read_token_item(tok);
2681         return type;
2682
2683 out_free_field:
2684         free_arg(field);
2685 out_free:
2686         free_token(token);
2687         *tok = NULL;
2688         return TEP_EVENT_ERROR;
2689 }
2690
2691 static enum tep_event_type
2692 process_hex_common(struct tep_event *event, struct tep_print_arg *arg,
2693                    char **tok, enum tep_print_arg_type type)
2694 {
2695         memset(arg, 0, sizeof(*arg));
2696         arg->type = type;
2697
2698         if (alloc_and_process_delim(event, ",", &arg->hex.field))
2699                 goto out;
2700
2701         if (alloc_and_process_delim(event, ")", &arg->hex.size))
2702                 goto free_field;
2703
2704         return read_token_item(tok);
2705
2706 free_field:
2707         free_arg(arg->hex.field);
2708         arg->hex.field = NULL;
2709 out:
2710         *tok = NULL;
2711         return TEP_EVENT_ERROR;
2712 }
2713
2714 static enum tep_event_type
2715 process_hex(struct tep_event *event, struct tep_print_arg *arg, char **tok)
2716 {
2717         return process_hex_common(event, arg, tok, TEP_PRINT_HEX);
2718 }
2719
2720 static enum tep_event_type
2721 process_hex_str(struct tep_event *event, struct tep_print_arg *arg,
2722                 char **tok)
2723 {
2724         return process_hex_common(event, arg, tok, TEP_PRINT_HEX_STR);
2725 }
2726
2727 static enum tep_event_type
2728 process_int_array(struct tep_event *event, struct tep_print_arg *arg, char **tok)
2729 {
2730         memset(arg, 0, sizeof(*arg));
2731         arg->type = TEP_PRINT_INT_ARRAY;
2732
2733         if (alloc_and_process_delim(event, ",", &arg->int_array.field))
2734                 goto out;
2735
2736         if (alloc_and_process_delim(event, ",", &arg->int_array.count))
2737                 goto free_field;
2738
2739         if (alloc_and_process_delim(event, ")", &arg->int_array.el_size))
2740                 goto free_size;
2741
2742         return read_token_item(tok);
2743
2744 free_size:
2745         free_arg(arg->int_array.count);
2746         arg->int_array.count = NULL;
2747 free_field:
2748         free_arg(arg->int_array.field);
2749         arg->int_array.field = NULL;
2750 out:
2751         *tok = NULL;
2752         return TEP_EVENT_ERROR;
2753 }
2754
2755 static enum tep_event_type
2756 process_dynamic_array(struct tep_event *event, struct tep_print_arg *arg, char **tok)
2757 {
2758         struct tep_format_field *field;
2759         enum tep_event_type type;
2760         char *token;
2761
2762         memset(arg, 0, sizeof(*arg));
2763         arg->type = TEP_PRINT_DYNAMIC_ARRAY;
2764
2765         /*
2766          * The item within the parenthesis is another field that holds
2767          * the index into where the array starts.
2768          */
2769         type = read_token(&token);
2770         *tok = token;
2771         if (type != TEP_EVENT_ITEM)
2772                 goto out_free;
2773
2774         /* Find the field */
2775
2776         field = tep_find_field(event, token);
2777         if (!field)
2778                 goto out_free;
2779
2780         arg->dynarray.field = field;
2781         arg->dynarray.index = 0;
2782
2783         if (read_expected(TEP_EVENT_DELIM, ")") < 0)
2784                 goto out_free;
2785
2786         free_token(token);
2787         type = read_token_item(&token);
2788         *tok = token;
2789         if (type != TEP_EVENT_OP || strcmp(token, "[") != 0)
2790                 return type;
2791
2792         free_token(token);
2793         arg = alloc_arg();
2794         if (!arg) {
2795                 do_warning_event(event, "%s: not enough memory!", __func__);
2796                 *tok = NULL;
2797                 return TEP_EVENT_ERROR;
2798         }
2799
2800         type = process_arg(event, arg, &token);
2801         if (type == TEP_EVENT_ERROR)
2802                 goto out_free_arg;
2803
2804         if (!test_type_token(type, token, TEP_EVENT_OP, "]"))
2805                 goto out_free_arg;
2806
2807         free_token(token);
2808         type = read_token_item(tok);
2809         return type;
2810
2811  out_free_arg:
2812         free_arg(arg);
2813  out_free:
2814         free_token(token);
2815         *tok = NULL;
2816         return TEP_EVENT_ERROR;
2817 }
2818
2819 static enum tep_event_type
2820 process_dynamic_array_len(struct tep_event *event, struct tep_print_arg *arg,
2821                           char **tok)
2822 {
2823         struct tep_format_field *field;
2824         enum tep_event_type type;
2825         char *token;
2826
2827         if (read_expect_type(TEP_EVENT_ITEM, &token) < 0)
2828                 goto out_free;
2829
2830         arg->type = TEP_PRINT_DYNAMIC_ARRAY_LEN;
2831
2832         /* Find the field */
2833         field = tep_find_field(event, token);
2834         if (!field)
2835                 goto out_free;
2836
2837         arg->dynarray.field = field;
2838         arg->dynarray.index = 0;
2839
2840         if (read_expected(TEP_EVENT_DELIM, ")") < 0)
2841                 goto out_err;
2842
2843         free_token(token);
2844         type = read_token(&token);
2845         *tok = token;
2846
2847         return type;
2848
2849  out_free:
2850         free_token(token);
2851  out_err:
2852         *tok = NULL;
2853         return TEP_EVENT_ERROR;
2854 }
2855
2856 static enum tep_event_type
2857 process_paren(struct tep_event *event, struct tep_print_arg *arg, char **tok)
2858 {
2859         struct tep_print_arg *item_arg;
2860         enum tep_event_type type;
2861         char *token;
2862
2863         type = process_arg(event, arg, &token);
2864
2865         if (type == TEP_EVENT_ERROR)
2866                 goto out_free;
2867
2868         if (type == TEP_EVENT_OP)
2869                 type = process_op(event, arg, &token);
2870
2871         if (type == TEP_EVENT_ERROR)
2872                 goto out_free;
2873
2874         if (test_type_token(type, token, TEP_EVENT_DELIM, ")"))
2875                 goto out_free;
2876
2877         free_token(token);
2878         type = read_token_item(&token);
2879
2880         /*
2881          * If the next token is an item or another open paren, then
2882          * this was a typecast.
2883          */
2884         if (event_item_type(type) ||
2885             (type == TEP_EVENT_DELIM && strcmp(token, "(") == 0)) {
2886
2887                 /* make this a typecast and contine */
2888
2889                 /* prevous must be an atom */
2890                 if (arg->type != TEP_PRINT_ATOM) {
2891                         do_warning_event(event, "previous needed to be TEP_PRINT_ATOM");
2892                         goto out_free;
2893                 }
2894
2895                 item_arg = alloc_arg();
2896                 if (!item_arg) {
2897                         do_warning_event(event, "%s: not enough memory!",
2898                                          __func__);
2899                         goto out_free;
2900                 }
2901
2902                 arg->type = TEP_PRINT_TYPE;
2903                 arg->typecast.type = arg->atom.atom;
2904                 arg->typecast.item = item_arg;
2905                 type = process_arg_token(event, item_arg, &token, type);
2906
2907         }
2908
2909         *tok = token;
2910         return type;
2911
2912  out_free:
2913         free_token(token);
2914         *tok = NULL;
2915         return TEP_EVENT_ERROR;
2916 }
2917
2918
2919 static enum tep_event_type
2920 process_str(struct tep_event *event __maybe_unused, struct tep_print_arg *arg,
2921             char **tok)
2922 {
2923         enum tep_event_type type;
2924         char *token;
2925
2926         if (read_expect_type(TEP_EVENT_ITEM, &token) < 0)
2927                 goto out_free;
2928
2929         arg->type = TEP_PRINT_STRING;
2930         arg->string.string = token;
2931         arg->string.offset = -1;
2932
2933         if (read_expected(TEP_EVENT_DELIM, ")") < 0)
2934                 goto out_err;
2935
2936         type = read_token(&token);
2937         *tok = token;
2938
2939         return type;
2940
2941  out_free:
2942         free_token(token);
2943  out_err:
2944         *tok = NULL;
2945         return TEP_EVENT_ERROR;
2946 }
2947
2948 static enum tep_event_type
2949 process_bitmask(struct tep_event *event __maybe_unused, struct tep_print_arg *arg,
2950                 char **tok)
2951 {
2952         enum tep_event_type type;
2953         char *token;
2954
2955         if (read_expect_type(TEP_EVENT_ITEM, &token) < 0)
2956                 goto out_free;
2957
2958         arg->type = TEP_PRINT_BITMASK;
2959         arg->bitmask.bitmask = token;
2960         arg->bitmask.offset = -1;
2961
2962         if (read_expected(TEP_EVENT_DELIM, ")") < 0)
2963                 goto out_err;
2964
2965         type = read_token(&token);
2966         *tok = token;
2967
2968         return type;
2969
2970  out_free:
2971         free_token(token);
2972  out_err:
2973         *tok = NULL;
2974         return TEP_EVENT_ERROR;
2975 }
2976
2977 static struct tep_function_handler *
2978 find_func_handler(struct tep_handle *tep, char *func_name)
2979 {
2980         struct tep_function_handler *func;
2981
2982         if (!tep)
2983                 return NULL;
2984
2985         for (func = tep->func_handlers; func; func = func->next) {
2986                 if (strcmp(func->name, func_name) == 0)
2987                         break;
2988         }
2989
2990         return func;
2991 }
2992
2993 static void remove_func_handler(struct tep_handle *tep, char *func_name)
2994 {
2995         struct tep_function_handler *func;
2996         struct tep_function_handler **next;
2997
2998         next = &tep->func_handlers;
2999         while ((func = *next)) {
3000                 if (strcmp(func->name, func_name) == 0) {
3001                         *next = func->next;
3002                         free_func_handle(func);
3003                         break;
3004                 }
3005                 next = &func->next;
3006         }
3007 }
3008
3009 static enum tep_event_type
3010 process_func_handler(struct tep_event *event, struct tep_function_handler *func,
3011                      struct tep_print_arg *arg, char **tok)
3012 {
3013         struct tep_print_arg **next_arg;
3014         struct tep_print_arg *farg;
3015         enum tep_event_type type;
3016         char *token;
3017         int i;
3018
3019         arg->type = TEP_PRINT_FUNC;
3020         arg->func.func = func;
3021
3022         *tok = NULL;
3023
3024         next_arg = &(arg->func.args);
3025         for (i = 0; i < func->nr_args; i++) {
3026                 farg = alloc_arg();
3027                 if (!farg) {
3028                         do_warning_event(event, "%s: not enough memory!",
3029                                          __func__);
3030                         return TEP_EVENT_ERROR;
3031                 }
3032
3033                 type = process_arg(event, farg, &token);
3034                 if (i < (func->nr_args - 1)) {
3035                         if (type != TEP_EVENT_DELIM || strcmp(token, ",") != 0) {
3036                                 do_warning_event(event,
3037                                         "Error: function '%s()' expects %d arguments but event %s only uses %d",
3038                                         func->name, func->nr_args,
3039                                         event->name, i + 1);
3040                                 goto err;
3041                         }
3042                 } else {
3043                         if (type != TEP_EVENT_DELIM || strcmp(token, ")") != 0) {
3044                                 do_warning_event(event,
3045                                         "Error: function '%s()' only expects %d arguments but event %s has more",
3046                                         func->name, func->nr_args, event->name);
3047                                 goto err;
3048                         }
3049                 }
3050
3051                 *next_arg = farg;
3052                 next_arg = &(farg->next);
3053                 free_token(token);
3054         }
3055
3056         type = read_token(&token);
3057         *tok = token;
3058
3059         return type;
3060
3061 err:
3062         free_arg(farg);
3063         free_token(token);
3064         return TEP_EVENT_ERROR;
3065 }
3066
3067 static enum tep_event_type
3068 process_builtin_expect(struct tep_event *event, struct tep_print_arg *arg, char **tok)
3069 {
3070         enum tep_event_type type;
3071         char *token = NULL;
3072
3073         /* Handle __builtin_expect( cond, #) */
3074         type = process_arg(event, arg, &token);
3075
3076         if (type != TEP_EVENT_DELIM || token[0] != ',')
3077                 goto out_free;
3078
3079         free_token(token);
3080
3081         /* We don't care what the second parameter is of the __builtin_expect() */
3082         if (read_expect_type(TEP_EVENT_ITEM, &token) < 0)
3083                 goto out_free;
3084
3085         if (read_expected(TEP_EVENT_DELIM, ")") < 0)
3086                 goto out_free;
3087
3088         free_token(token);
3089         type = read_token_item(tok);
3090         return type;
3091
3092 out_free:
3093         free_token(token);
3094         *tok = NULL;
3095         return TEP_EVENT_ERROR;
3096 }
3097
3098 static enum tep_event_type
3099 process_function(struct tep_event *event, struct tep_print_arg *arg,
3100                  char *token, char **tok)
3101 {
3102         struct tep_function_handler *func;
3103
3104         if (strcmp(token, "__print_flags") == 0) {
3105                 free_token(token);
3106                 is_flag_field = 1;
3107                 return process_flags(event, arg, tok);
3108         }
3109         if (strcmp(token, "__print_symbolic") == 0) {
3110                 free_token(token);
3111                 is_symbolic_field = 1;
3112                 return process_symbols(event, arg, tok);
3113         }
3114         if (strcmp(token, "__print_hex") == 0) {
3115                 free_token(token);
3116                 return process_hex(event, arg, tok);
3117         }
3118         if (strcmp(token, "__print_hex_str") == 0) {
3119                 free_token(token);
3120                 return process_hex_str(event, arg, tok);
3121         }
3122         if (strcmp(token, "__print_array") == 0) {
3123                 free_token(token);
3124                 return process_int_array(event, arg, tok);
3125         }
3126         if (strcmp(token, "__get_str") == 0) {
3127                 free_token(token);
3128                 return process_str(event, arg, tok);
3129         }
3130         if (strcmp(token, "__get_bitmask") == 0) {
3131                 free_token(token);
3132                 return process_bitmask(event, arg, tok);
3133         }
3134         if (strcmp(token, "__get_dynamic_array") == 0) {
3135                 free_token(token);
3136                 return process_dynamic_array(event, arg, tok);
3137         }
3138         if (strcmp(token, "__get_dynamic_array_len") == 0) {
3139                 free_token(token);
3140                 return process_dynamic_array_len(event, arg, tok);
3141         }
3142         if (strcmp(token, "__builtin_expect") == 0) {
3143                 free_token(token);
3144                 return process_builtin_expect(event, arg, tok);
3145         }
3146
3147         func = find_func_handler(event->tep, token);
3148         if (func) {
3149                 free_token(token);
3150                 return process_func_handler(event, func, arg, tok);
3151         }
3152
3153         do_warning_event(event, "function %s not defined", token);
3154         free_token(token);
3155         return TEP_EVENT_ERROR;
3156 }
3157
3158 static enum tep_event_type
3159 process_arg_token(struct tep_event *event, struct tep_print_arg *arg,
3160                   char **tok, enum tep_event_type type)
3161 {
3162         char *token;
3163         char *atom;
3164
3165         token = *tok;
3166
3167         switch (type) {
3168         case TEP_EVENT_ITEM:
3169                 if (strcmp(token, "REC") == 0) {
3170                         free_token(token);
3171                         type = process_entry(event, arg, &token);
3172                         break;
3173                 }
3174                 atom = token;
3175                 /* test the next token */
3176                 type = read_token_item(&token);
3177
3178                 /*
3179                  * If the next token is a parenthesis, then this
3180                  * is a function.
3181                  */
3182                 if (type == TEP_EVENT_DELIM && strcmp(token, "(") == 0) {
3183                         free_token(token);
3184                         token = NULL;
3185                         /* this will free atom. */
3186                         type = process_function(event, arg, atom, &token);
3187                         break;
3188                 }
3189                 /* atoms can be more than one token long */
3190                 while (type == TEP_EVENT_ITEM) {
3191                         int ret;
3192
3193                         ret = append(&atom, " ", token);
3194                         if (ret < 0) {
3195                                 free(atom);
3196                                 *tok = NULL;
3197                                 free_token(token);
3198                                 return TEP_EVENT_ERROR;
3199                         }
3200                         free_token(token);
3201                         type = read_token_item(&token);
3202                 }
3203
3204                 arg->type = TEP_PRINT_ATOM;
3205                 arg->atom.atom = atom;
3206                 break;
3207
3208         case TEP_EVENT_DQUOTE:
3209         case TEP_EVENT_SQUOTE:
3210                 arg->type = TEP_PRINT_ATOM;
3211                 arg->atom.atom = token;
3212                 type = read_token_item(&token);
3213                 break;
3214         case TEP_EVENT_DELIM:
3215                 if (strcmp(token, "(") == 0) {
3216                         free_token(token);
3217                         type = process_paren(event, arg, &token);
3218                         break;
3219                 }
3220         case TEP_EVENT_OP:
3221                 /* handle single ops */
3222                 arg->type = TEP_PRINT_OP;
3223                 arg->op.op = token;
3224                 arg->op.left = NULL;
3225                 type = process_op(event, arg, &token);
3226
3227                 /* On error, the op is freed */
3228                 if (type == TEP_EVENT_ERROR)
3229                         arg->op.op = NULL;
3230
3231                 /* return error type if errored */
3232                 break;
3233
3234         case TEP_EVENT_ERROR ... TEP_EVENT_NEWLINE:
3235         default:
3236                 do_warning_event(event, "unexpected type %d", type);
3237                 return TEP_EVENT_ERROR;
3238         }
3239         *tok = token;
3240
3241         return type;
3242 }
3243
3244 static int event_read_print_args(struct tep_event *event, struct tep_print_arg **list)
3245 {
3246         enum tep_event_type type = TEP_EVENT_ERROR;
3247         struct tep_print_arg *arg;
3248         char *token;
3249         int args = 0;
3250
3251         do {
3252                 if (type == TEP_EVENT_NEWLINE) {
3253                         type = read_token_item(&token);
3254                         continue;
3255                 }
3256
3257                 arg = alloc_arg();
3258                 if (!arg) {
3259                         do_warning_event(event, "%s: not enough memory!",
3260                                          __func__);
3261                         return -1;
3262                 }
3263
3264                 type = process_arg(event, arg, &token);
3265
3266                 if (type == TEP_EVENT_ERROR) {
3267                         free_token(token);
3268                         free_arg(arg);
3269                         return -1;
3270                 }
3271
3272                 *list = arg;
3273                 args++;
3274
3275                 if (type == TEP_EVENT_OP) {
3276                         type = process_op(event, arg, &token);
3277                         free_token(token);
3278                         if (type == TEP_EVENT_ERROR) {
3279                                 *list = NULL;
3280                                 free_arg(arg);
3281                                 return -1;
3282                         }
3283                         list = &arg->next;
3284                         continue;
3285                 }
3286
3287                 if (type == TEP_EVENT_DELIM && strcmp(token, ",") == 0) {
3288                         free_token(token);
3289                         *list = arg;
3290                         list = &arg->next;
3291                         continue;
3292                 }
3293                 break;
3294         } while (type != TEP_EVENT_NONE);
3295
3296         if (type != TEP_EVENT_NONE && type != TEP_EVENT_ERROR)
3297                 free_token(token);
3298
3299         return args;
3300 }
3301
3302 static int event_read_print(struct tep_event *event)
3303 {
3304         enum tep_event_type type;
3305         char *token;
3306         int ret;
3307
3308         if (read_expected_item(TEP_EVENT_ITEM, "print") < 0)
3309                 return -1;
3310
3311         if (read_expected(TEP_EVENT_ITEM, "fmt") < 0)
3312                 return -1;
3313
3314         if (read_expected(TEP_EVENT_OP, ":") < 0)
3315                 return -1;
3316
3317         if (read_expect_type(TEP_EVENT_DQUOTE, &token) < 0)
3318                 goto fail;
3319
3320  concat:
3321         event->print_fmt.format = token;
3322         event->print_fmt.args = NULL;
3323
3324         /* ok to have no arg */
3325         type = read_token_item(&token);
3326
3327         if (type == TEP_EVENT_NONE)
3328                 return 0;
3329
3330         /* Handle concatenation of print lines */
3331         if (type == TEP_EVENT_DQUOTE) {
3332                 char *cat;
3333
3334                 if (asprintf(&cat, "%s%s", event->print_fmt.format, token) < 0)
3335                         goto fail;
3336                 free_token(token);
3337                 free_token(event->print_fmt.format);
3338                 event->print_fmt.format = NULL;
3339                 token = cat;
3340                 goto concat;
3341         }
3342                              
3343         if (test_type_token(type, token, TEP_EVENT_DELIM, ","))
3344                 goto fail;
3345
3346         free_token(token);
3347
3348         ret = event_read_print_args(event, &event->print_fmt.args);
3349         if (ret < 0)
3350                 return -1;
3351
3352         return ret;
3353
3354  fail:
3355         free_token(token);
3356         return -1;
3357 }
3358
3359 /**
3360  * tep_find_common_field - return a common field by event
3361  * @event: handle for the event
3362  * @name: the name of the common field to return
3363  *
3364  * Returns a common field from the event by the given @name.
3365  * This only searches the common fields and not all field.
3366  */
3367 struct tep_format_field *
3368 tep_find_common_field(struct tep_event *event, const char *name)
3369 {
3370         struct tep_format_field *format;
3371
3372         for (format = event->format.common_fields;
3373              format; format = format->next) {
3374                 if (strcmp(format->name, name) == 0)
3375                         break;
3376         }
3377
3378         return format;
3379 }
3380
3381 /**
3382  * tep_find_field - find a non-common field
3383  * @event: handle for the event
3384  * @name: the name of the non-common field
3385  *
3386  * Returns a non-common field by the given @name.
3387  * This does not search common fields.
3388  */
3389 struct tep_format_field *
3390 tep_find_field(struct tep_event *event, const char *name)
3391 {
3392         struct tep_format_field *format;
3393
3394         for (format = event->format.fields;
3395              format; format = format->next) {
3396                 if (strcmp(format->name, name) == 0)
3397                         break;
3398         }
3399
3400         return format;
3401 }
3402
3403 /**
3404  * tep_find_any_field - find any field by name
3405  * @event: handle for the event
3406  * @name: the name of the field
3407  *
3408  * Returns a field by the given @name.
3409  * This searches the common field names first, then
3410  * the non-common ones if a common one was not found.
3411  */
3412 struct tep_format_field *
3413 tep_find_any_field(struct tep_event *event, const char *name)
3414 {
3415         struct tep_format_field *format;
3416
3417         format = tep_find_common_field(event, name);
3418         if (format)
3419                 return format;
3420         return tep_find_field(event, name);
3421 }
3422
3423 /**
3424  * tep_read_number - read a number from data
3425  * @tep: a handle to the trace event parser context
3426  * @ptr: the raw data
3427  * @size: the size of the data that holds the number
3428  *
3429  * Returns the number (converted to host) from the
3430  * raw data.
3431  */
3432 unsigned long long tep_read_number(struct tep_handle *tep,
3433                                    const void *ptr, int size)
3434 {
3435         unsigned long long val;
3436
3437         switch (size) {
3438         case 1:
3439                 return *(unsigned char *)ptr;
3440         case 2:
3441                 return data2host2(tep, *(unsigned short *)ptr);
3442         case 4:
3443                 return data2host4(tep, *(unsigned int *)ptr);
3444         case 8:
3445                 memcpy(&val, (ptr), sizeof(unsigned long long));
3446                 return data2host8(tep, val);
3447         default:
3448                 /* BUG! */
3449                 return 0;
3450         }
3451 }
3452
3453 /**
3454  * tep_read_number_field - read a number from data
3455  * @field: a handle to the field
3456  * @data: the raw data to read
3457  * @value: the value to place the number in
3458  *
3459  * Reads raw data according to a field offset and size,
3460  * and translates it into @value.
3461  *
3462  * Returns 0 on success, -1 otherwise.
3463  */
3464 int tep_read_number_field(struct tep_format_field *field, const void *data,
3465                           unsigned long long *value)
3466 {
3467         if (!field)
3468                 return -1;
3469         switch (field->size) {
3470         case 1:
3471         case 2:
3472         case 4:
3473         case 8:
3474                 *value = tep_read_number(field->event->tep,
3475                                          data + field->offset, field->size);
3476                 return 0;
3477         default:
3478                 return -1;
3479         }
3480 }
3481
3482 static int get_common_info(struct tep_handle *tep,
3483                            const char *type, int *offset, int *size)
3484 {
3485         struct tep_event *event;
3486         struct tep_format_field *field;
3487
3488         /*
3489          * All events should have the same common elements.
3490          * Pick any event to find where the type is;
3491          */
3492         if (!tep->events) {
3493                 do_warning("no event_list!");
3494                 return -1;
3495         }
3496
3497         event = tep->events[0];
3498         field = tep_find_common_field(event, type);
3499         if (!field)
3500                 return -1;
3501
3502         *offset = field->offset;
3503         *size = field->size;
3504
3505         return 0;
3506 }
3507
3508 static int __parse_common(struct tep_handle *tep, void *data,
3509                           int *size, int *offset, const char *name)
3510 {
3511         int ret;
3512
3513         if (!*size) {
3514                 ret = get_common_info(tep, name, offset, size);
3515                 if (ret < 0)
3516                         return ret;
3517         }
3518         return tep_read_number(tep, data + *offset, *size);
3519 }
3520
3521 static int trace_parse_common_type(struct tep_handle *tep, void *data)
3522 {
3523         return __parse_common(tep, data,
3524                               &tep->type_size, &tep->type_offset,
3525                               "common_type");
3526 }
3527
3528 static int parse_common_pid(struct tep_handle *tep, void *data)
3529 {
3530         return __parse_common(tep, data,
3531                               &tep->pid_size, &tep->pid_offset,
3532                               "common_pid");
3533 }
3534
3535 static int parse_common_pc(struct tep_handle *tep, void *data)
3536 {
3537         return __parse_common(tep, data,
3538                               &tep->pc_size, &tep->pc_offset,
3539                               "common_preempt_count");
3540 }
3541
3542 static int parse_common_flags(struct tep_handle *tep, void *data)
3543 {
3544         return __parse_common(tep, data,
3545                               &tep->flags_size, &tep->flags_offset,
3546                               "common_flags");
3547 }
3548
3549 static int parse_common_lock_depth(struct tep_handle *tep, void *data)
3550 {
3551         return __parse_common(tep, data,
3552                               &tep->ld_size, &tep->ld_offset,
3553                               "common_lock_depth");
3554 }
3555
3556 static int parse_common_migrate_disable(struct tep_handle *tep, void *data)
3557 {
3558         return __parse_common(tep, data,
3559                               &tep->ld_size, &tep->ld_offset,
3560                               "common_migrate_disable");
3561 }
3562
3563 static int events_id_cmp(const void *a, const void *b);
3564
3565 /**
3566  * tep_find_event - find an event by given id
3567  * @tep: a handle to the trace event parser context
3568  * @id: the id of the event
3569  *
3570  * Returns an event that has a given @id.
3571  */
3572 struct tep_event *tep_find_event(struct tep_handle *tep, int id)
3573 {
3574         struct tep_event **eventptr;
3575         struct tep_event key;
3576         struct tep_event *pkey = &key;
3577
3578         /* Check cache first */
3579         if (tep->last_event && tep->last_event->id == id)
3580                 return tep->last_event;
3581
3582         key.id = id;
3583
3584         eventptr = bsearch(&pkey, tep->events, tep->nr_events,
3585                            sizeof(*tep->events), events_id_cmp);
3586
3587         if (eventptr) {
3588                 tep->last_event = *eventptr;
3589                 return *eventptr;
3590         }
3591
3592         return NULL;
3593 }
3594
3595 /**
3596  * tep_find_event_by_name - find an event by given name
3597  * @tep: a handle to the trace event parser context
3598  * @sys: the system name to search for
3599  * @name: the name of the event to search for
3600  *
3601  * This returns an event with a given @name and under the system
3602  * @sys. If @sys is NULL the first event with @name is returned.
3603  */
3604 struct tep_event *
3605 tep_find_event_by_name(struct tep_handle *tep,
3606                        const char *sys, const char *name)
3607 {
3608         struct tep_event *event = NULL;
3609         int i;
3610
3611         if (tep->last_event &&
3612             strcmp(tep->last_event->name, name) == 0 &&
3613             (!sys || strcmp(tep->last_event->system, sys) == 0))
3614                 return tep->last_event;
3615
3616         for (i = 0; i < tep->nr_events; i++) {
3617                 event = tep->events[i];
3618                 if (strcmp(event->name, name) == 0) {
3619                         if (!sys)
3620                                 break;
3621                         if (strcmp(event->system, sys) == 0)
3622                                 break;
3623                 }
3624         }
3625         if (i == tep->nr_events)
3626                 event = NULL;
3627
3628         tep->last_event = event;
3629         return event;
3630 }
3631
3632 static unsigned long long
3633 eval_num_arg(void *data, int size, struct tep_event *event, struct tep_print_arg *arg)
3634 {
3635         struct tep_handle *tep = event->tep;
3636         unsigned long long val = 0;
3637         unsigned long long left, right;
3638         struct tep_print_arg *typearg = NULL;
3639         struct tep_print_arg *larg;
3640         unsigned long offset;
3641         unsigned int field_size;
3642
3643         switch (arg->type) {
3644         case TEP_PRINT_NULL:
3645                 /* ?? */
3646                 return 0;
3647         case TEP_PRINT_ATOM:
3648                 return strtoull(arg->atom.atom, NULL, 0);
3649         case TEP_PRINT_FIELD:
3650                 if (!arg->field.field) {
3651                         arg->field.field = tep_find_any_field(event, arg->field.name);
3652                         if (!arg->field.field)
3653                                 goto out_warning_field;
3654                         
3655                 }
3656                 /* must be a number */
3657                 val = tep_read_number(tep, data + arg->field.field->offset,
3658                                       arg->field.field->size);
3659                 break;
3660         case TEP_PRINT_FLAGS:
3661         case TEP_PRINT_SYMBOL:
3662         case TEP_PRINT_INT_ARRAY:
3663         case TEP_PRINT_HEX:
3664         case TEP_PRINT_HEX_STR:
3665                 break;
3666         case TEP_PRINT_TYPE:
3667                 val = eval_num_arg(data, size, event, arg->typecast.item);
3668                 return eval_type(val, arg, 0);
3669         case TEP_PRINT_STRING:
3670         case TEP_PRINT_BSTRING:
3671         case TEP_PRINT_BITMASK:
3672                 return 0;
3673         case TEP_PRINT_FUNC: {
3674                 struct trace_seq s;
3675                 trace_seq_init(&s);
3676                 val = process_defined_func(&s, data, size, event, arg);
3677                 trace_seq_destroy(&s);
3678                 return val;
3679         }
3680         case TEP_PRINT_OP:
3681                 if (strcmp(arg->op.op, "[") == 0) {
3682                         /*
3683                          * Arrays are special, since we don't want
3684                          * to read the arg as is.
3685                          */
3686                         right = eval_num_arg(data, size, event, arg->op.right);
3687
3688                         /* handle typecasts */
3689                         larg = arg->op.left;
3690                         while (larg->type == TEP_PRINT_TYPE) {
3691                                 if (!typearg)
3692                                         typearg = larg;
3693                                 larg = larg->typecast.item;
3694                         }
3695
3696                         /* Default to long size */
3697                         field_size = tep->long_size;
3698
3699                         switch (larg->type) {
3700                         case TEP_PRINT_DYNAMIC_ARRAY:
3701                                 offset = tep_read_number(tep,
3702                                                    data + larg->dynarray.field->offset,
3703                                                    larg->dynarray.field->size);
3704                                 if (larg->dynarray.field->elementsize)
3705                                         field_size = larg->dynarray.field->elementsize;
3706                                 /*
3707                                  * The actual length of the dynamic array is stored
3708                                  * in the top half of the field, and the offset
3709                                  * is in the bottom half of the 32 bit field.
3710                                  */
3711                                 offset &= 0xffff;
3712                                 offset += right;
3713                                 break;
3714                         case TEP_PRINT_FIELD:
3715                                 if (!larg->field.field) {
3716                                         larg->field.field =
3717                                                 tep_find_any_field(event, larg->field.name);
3718                                         if (!larg->field.field) {
3719                                                 arg = larg;
3720                                                 goto out_warning_field;
3721                                         }
3722                                 }
3723                                 field_size = larg->field.field->elementsize;
3724                                 offset = larg->field.field->offset +
3725                                         right * larg->field.field->elementsize;
3726                                 break;
3727                         default:
3728                                 goto default_op; /* oops, all bets off */
3729                         }
3730                         val = tep_read_number(tep,
3731                                               data + offset, field_size);
3732                         if (typearg)
3733                                 val = eval_type(val, typearg, 1);
3734                         break;
3735                 } else if (strcmp(arg->op.op, "?") == 0) {
3736                         left = eval_num_arg(data, size, event, arg->op.left);
3737                         arg = arg->op.right;
3738                         if (left)
3739                                 val = eval_num_arg(data, size, event, arg->op.left);
3740                         else
3741                                 val = eval_num_arg(data, size, event, arg->op.right);
3742                         break;
3743                 }
3744  default_op:
3745                 left = eval_num_arg(data, size, event, arg->op.left);
3746                 right = eval_num_arg(data, size, event, arg->op.right);
3747                 switch (arg->op.op[0]) {
3748                 case '!':
3749                         switch (arg->op.op[1]) {
3750                         case 0:
3751                                 val = !right;
3752                                 break;
3753                         case '=':
3754                                 val = left != right;
3755                                 break;
3756                         default:
3757                                 goto out_warning_op;
3758                         }
3759                         break;
3760                 case '~':
3761                         val = ~right;
3762                         break;
3763                 case '|':
3764                         if (arg->op.op[1])
3765                                 val = left || right;
3766                         else
3767                                 val = left | right;
3768                         break;
3769                 case '&':
3770                         if (arg->op.op[1])
3771                                 val = left && right;
3772                         else
3773                                 val = left & right;
3774                         break;
3775                 case '<':
3776                         switch (arg->op.op[1]) {
3777                         case 0:
3778                                 val = left < right;
3779                                 break;
3780                         case '<':
3781                                 val = left << right;
3782                                 break;
3783                         case '=':
3784                                 val = left <= right;
3785                                 break;
3786                         default:
3787                                 goto out_warning_op;
3788                         }
3789                         break;
3790                 case '>':
3791                         switch (arg->op.op[1]) {
3792                         case 0:
3793                                 val = left > right;
3794                                 break;
3795                         case '>':
3796                                 val = left >> right;
3797                                 break;
3798                         case '=':
3799                                 val = left >= right;
3800                                 break;
3801                         default:
3802                                 goto out_warning_op;
3803                         }
3804                         break;
3805                 case '=':
3806                         if (arg->op.op[1] != '=')
3807                                 goto out_warning_op;
3808
3809                         val = left == right;
3810                         break;
3811                 case '-':
3812                         val = left - right;
3813                         break;
3814                 case '+':
3815                         val = left + right;
3816                         break;
3817                 case '/':
3818                         val = left / right;
3819                         break;
3820                 case '%':
3821                         val = left % right;
3822                         break;
3823                 case '*':
3824                         val = left * right;
3825                         break;
3826                 default:
3827                         goto out_warning_op;
3828                 }
3829                 break;
3830         case TEP_PRINT_DYNAMIC_ARRAY_LEN:
3831                 offset = tep_read_number(tep,
3832                                          data + arg->dynarray.field->offset,
3833                                          arg->dynarray.field->size);
3834                 /*
3835                  * The total allocated length of the dynamic array is
3836                  * stored in the top half of the field, and the offset
3837                  * is in the bottom half of the 32 bit field.
3838                  */
3839                 val = (unsigned long long)(offset >> 16);
3840                 break;
3841         case TEP_PRINT_DYNAMIC_ARRAY:
3842                 /* Without [], we pass the address to the dynamic data */
3843                 offset = tep_read_number(tep,
3844                                          data + arg->dynarray.field->offset,
3845                                          arg->dynarray.field->size);
3846                 /*
3847                  * The total allocated length of the dynamic array is
3848                  * stored in the top half of the field, and the offset
3849                  * is in the bottom half of the 32 bit field.
3850                  */
3851                 offset &= 0xffff;
3852                 val = (unsigned long long)((unsigned long)data + offset);
3853                 break;
3854         default: /* not sure what to do there */
3855                 return 0;
3856         }
3857         return val;
3858
3859 out_warning_op:
3860         do_warning_event(event, "%s: unknown op '%s'", __func__, arg->op.op);
3861         return 0;
3862
3863 out_warning_field:
3864         do_warning_event(event, "%s: field %s not found",
3865                          __func__, arg->field.name);
3866         return 0;
3867 }
3868
3869 struct flag {
3870         const char *name;
3871         unsigned long long value;
3872 };
3873
3874 static const struct flag flags[] = {
3875         { "HI_SOFTIRQ", 0 },
3876         { "TIMER_SOFTIRQ", 1 },
3877         { "NET_TX_SOFTIRQ", 2 },
3878         { "NET_RX_SOFTIRQ", 3 },
3879         { "BLOCK_SOFTIRQ", 4 },
3880         { "IRQ_POLL_SOFTIRQ", 5 },
3881         { "TASKLET_SOFTIRQ", 6 },
3882         { "SCHED_SOFTIRQ", 7 },
3883         { "HRTIMER_SOFTIRQ", 8 },
3884         { "RCU_SOFTIRQ", 9 },
3885
3886         { "HRTIMER_NORESTART", 0 },
3887         { "HRTIMER_RESTART", 1 },
3888 };
3889
3890 static long long eval_flag(const char *flag)
3891 {
3892         int i;
3893
3894         /*
3895          * Some flags in the format files do not get converted.
3896          * If the flag is not numeric, see if it is something that
3897          * we already know about.
3898          */
3899         if (isdigit(flag[0]))
3900                 return strtoull(flag, NULL, 0);
3901
3902         for (i = 0; i < (int)(sizeof(flags)/sizeof(flags[0])); i++)
3903                 if (strcmp(flags[i].name, flag) == 0)
3904                         return flags[i].value;
3905
3906         return -1LL;
3907 }
3908
3909 static void print_str_to_seq(struct trace_seq *s, const char *format,
3910                              int len_arg, const char *str)
3911 {
3912         if (len_arg >= 0)
3913                 trace_seq_printf(s, format, len_arg, str);
3914         else
3915                 trace_seq_printf(s, format, str);
3916 }
3917
3918 static void print_bitmask_to_seq(struct tep_handle *tep,
3919                                  struct trace_seq *s, const char *format,
3920                                  int len_arg, const void *data, int size)
3921 {
3922         int nr_bits = size * 8;
3923         int str_size = (nr_bits + 3) / 4;
3924         int len = 0;
3925         char buf[3];
3926         char *str;
3927         int index;
3928         int i;
3929
3930         /*
3931          * The kernel likes to put in commas every 32 bits, we
3932          * can do the same.
3933          */
3934         str_size += (nr_bits - 1) / 32;
3935
3936         str = malloc(str_size + 1);
3937         if (!str) {
3938                 do_warning("%s: not enough memory!", __func__);
3939                 return;
3940         }
3941         str[str_size] = 0;
3942
3943         /* Start out with -2 for the two chars per byte */
3944         for (i = str_size - 2; i >= 0; i -= 2) {
3945                 /*
3946                  * data points to a bit mask of size bytes.
3947                  * In the kernel, this is an array of long words, thus
3948                  * endianness is very important.
3949                  */
3950                 if (tep->file_bigendian)
3951                         index = size - (len + 1);
3952                 else
3953                         index = len;
3954
3955                 snprintf(buf, 3, "%02x", *((unsigned char *)data + index));
3956                 memcpy(str + i, buf, 2);
3957                 len++;
3958                 if (!(len & 3) && i > 0) {
3959                         i--;
3960                         str[i] = ',';
3961                 }
3962         }
3963
3964         if (len_arg >= 0)
3965                 trace_seq_printf(s, format, len_arg, str);
3966         else
3967                 trace_seq_printf(s, format, str);
3968
3969         free(str);
3970 }
3971
3972 static void print_str_arg(struct trace_seq *s, void *data, int size,
3973                           struct tep_event *event, const char *format,
3974                           int len_arg, struct tep_print_arg *arg)
3975 {
3976         struct tep_handle *tep = event->tep;
3977         struct tep_print_flag_sym *flag;
3978         struct tep_format_field *field;
3979         struct printk_map *printk;
3980         long long val, fval;
3981         unsigned long long addr;
3982         char *str;
3983         unsigned char *hex;
3984         int print;
3985         int i, len;
3986
3987         switch (arg->type) {
3988         case TEP_PRINT_NULL:
3989                 /* ?? */
3990                 return;
3991         case TEP_PRINT_ATOM:
3992                 print_str_to_seq(s, format, len_arg, arg->atom.atom);
3993                 return;
3994         case TEP_PRINT_FIELD:
3995                 field = arg->field.field;
3996                 if (!field) {
3997                         field = tep_find_any_field(event, arg->field.name);
3998                         if (!field) {
3999                                 str = arg->field.name;
4000                                 goto out_warning_field;
4001                         }
4002                         arg->field.field = field;
4003                 }
4004                 /* Zero sized fields, mean the rest of the data */
4005                 len = field->size ? : size - field->offset;
4006
4007                 /*
4008                  * Some events pass in pointers. If this is not an array
4009                  * and the size is the same as long_size, assume that it
4010                  * is a pointer.
4011                  */
4012                 if (!(field->flags & TEP_FIELD_IS_ARRAY) &&
4013                     field->size == tep->long_size) {
4014
4015                         /* Handle heterogeneous recording and processing
4016                          * architectures
4017                          *
4018                          * CASE I:
4019                          * Traces recorded on 32-bit devices (32-bit
4020                          * addressing) and processed on 64-bit devices:
4021                          * In this case, only 32 bits should be read.
4022                          *
4023                          * CASE II:
4024                          * Traces recorded on 64 bit devices and processed
4025                          * on 32-bit devices:
4026                          * In this case, 64 bits must be read.
4027                          */
4028                         addr = (tep->long_size == 8) ?
4029                                 *(unsigned long long *)(data + field->offset) :
4030                                 (unsigned long long)*(unsigned int *)(data + field->offset);
4031
4032                         /* Check if it matches a print format */
4033                         printk = find_printk(tep, addr);
4034                         if (printk)
4035                                 trace_seq_puts(s, printk->printk);
4036                         else
4037                                 trace_seq_printf(s, "%llx", addr);
4038                         break;
4039                 }
4040                 str = malloc(len + 1);
4041                 if (!str) {
4042                         do_warning_event(event, "%s: not enough memory!",
4043                                          __func__);
4044                         return;
4045                 }
4046                 memcpy(str, data + field->offset, len);
4047                 str[len] = 0;
4048                 print_str_to_seq(s, format, len_arg, str);
4049                 free(str);
4050                 break;
4051         case TEP_PRINT_FLAGS:
4052                 val = eval_num_arg(data, size, event, arg->flags.field);
4053                 print = 0;
4054                 for (flag = arg->flags.flags; flag; flag = flag->next) {
4055                         fval = eval_flag(flag->value);
4056                         if (!val && fval < 0) {
4057                                 print_str_to_seq(s, format, len_arg, flag->str);
4058                                 break;
4059                         }
4060                         if (fval > 0 && (val & fval) == fval) {
4061                                 if (print && arg->flags.delim)
4062                                         trace_seq_puts(s, arg->flags.delim);
4063                                 print_str_to_seq(s, format, len_arg, flag->str);
4064                                 print = 1;
4065                                 val &= ~fval;
4066                         }
4067                 }
4068                 if (val) {
4069                         if (print && arg->flags.delim)
4070                                 trace_seq_puts(s, arg->flags.delim);
4071                         trace_seq_printf(s, "0x%llx", val);
4072                 }
4073                 break;
4074         case TEP_PRINT_SYMBOL:
4075                 val = eval_num_arg(data, size, event, arg->symbol.field);
4076                 for (flag = arg->symbol.symbols; flag; flag = flag->next) {
4077                         fval = eval_flag(flag->value);
4078                         if (val == fval) {
4079                                 print_str_to_seq(s, format, len_arg, flag->str);
4080                                 break;
4081                         }
4082                 }
4083                 if (!flag)
4084                         trace_seq_printf(s, "0x%llx", val);
4085                 break;
4086         case TEP_PRINT_HEX:
4087         case TEP_PRINT_HEX_STR:
4088                 if (arg->hex.field->type == TEP_PRINT_DYNAMIC_ARRAY) {
4089                         unsigned long offset;
4090                         offset = tep_read_number(tep,
4091                                 data + arg->hex.field->dynarray.field->offset,
4092                                 arg->hex.field->dynarray.field->size);
4093                         hex = data + (offset & 0xffff);
4094                 } else {
4095                         field = arg->hex.field->field.field;
4096                         if (!field) {
4097                                 str = arg->hex.field->field.name;
4098                                 field = tep_find_any_field(event, str);
4099                                 if (!field)
4100                                         goto out_warning_field;
4101                                 arg->hex.field->field.field = field;
4102                         }
4103                         hex = data + field->offset;
4104                 }
4105                 len = eval_num_arg(data, size, event, arg->hex.size);
4106                 for (i = 0; i < len; i++) {
4107                         if (i && arg->type == TEP_PRINT_HEX)
4108                                 trace_seq_putc(s, ' ');
4109                         trace_seq_printf(s, "%02x", hex[i]);
4110                 }
4111                 break;
4112
4113         case TEP_PRINT_INT_ARRAY: {
4114                 void *num;
4115                 int el_size;
4116
4117                 if (arg->int_array.field->type == TEP_PRINT_DYNAMIC_ARRAY) {
4118                         unsigned long offset;
4119                         struct tep_format_field *field =
4120                                 arg->int_array.field->dynarray.field;
4121                         offset = tep_read_number(tep,
4122                                                  data + field->offset,
4123                                                  field->size);
4124                         num = data + (offset & 0xffff);
4125                 } else {
4126                         field = arg->int_array.field->field.field;
4127                         if (!field) {
4128                                 str = arg->int_array.field->field.name;
4129                                 field = tep_find_any_field(event, str);
4130                                 if (!field)
4131                                         goto out_warning_field;
4132                                 arg->int_array.field->field.field = field;
4133                         }
4134                         num = data + field->offset;
4135                 }
4136                 len = eval_num_arg(data, size, event, arg->int_array.count);
4137                 el_size = eval_num_arg(data, size, event,
4138                                        arg->int_array.el_size);
4139                 for (i = 0; i < len; i++) {
4140                         if (i)
4141                                 trace_seq_putc(s, ' ');
4142
4143                         if (el_size == 1) {
4144                                 trace_seq_printf(s, "%u", *(uint8_t *)num);
4145                         } else if (el_size == 2) {
4146                                 trace_seq_printf(s, "%u", *(uint16_t *)num);
4147                         } else if (el_size == 4) {
4148                                 trace_seq_printf(s, "%u", *(uint32_t *)num);
4149                         } else if (el_size == 8) {
4150                                 trace_seq_printf(s, "%"PRIu64, *(uint64_t *)num);
4151                         } else {
4152                                 trace_seq_printf(s, "BAD SIZE:%d 0x%x",
4153                                                  el_size, *(uint8_t *)num);
4154                                 el_size = 1;
4155                         }
4156
4157                         num += el_size;
4158                 }
4159                 break;
4160         }
4161         case TEP_PRINT_TYPE:
4162                 break;
4163         case TEP_PRINT_STRING: {
4164                 int str_offset;
4165
4166                 if (arg->string.offset == -1) {
4167                         struct tep_format_field *f;
4168
4169                         f = tep_find_any_field(event, arg->string.string);
4170                         arg->string.offset = f->offset;
4171                 }
4172                 str_offset = data2host4(tep, *(unsigned int *)(data + arg->string.offset));
4173                 str_offset &= 0xffff;
4174                 print_str_to_seq(s, format, len_arg, ((char *)data) + str_offset);
4175                 break;
4176         }
4177         case TEP_PRINT_BSTRING:
4178                 print_str_to_seq(s, format, len_arg, arg->string.string);
4179                 break;
4180         case TEP_PRINT_BITMASK: {
4181                 int bitmask_offset;
4182                 int bitmask_size;
4183
4184                 if (arg->bitmask.offset == -1) {
4185                         struct tep_format_field *f;
4186
4187                         f = tep_find_any_field(event, arg->bitmask.bitmask);
4188                         arg->bitmask.offset = f->offset;
4189                 }
4190                 bitmask_offset = data2host4(tep, *(unsigned int *)(data + arg->bitmask.offset));
4191                 bitmask_size = bitmask_offset >> 16;
4192                 bitmask_offset &= 0xffff;
4193                 print_bitmask_to_seq(tep, s, format, len_arg,
4194                                      data + bitmask_offset, bitmask_size);
4195                 break;
4196         }
4197         case TEP_PRINT_OP:
4198                 /*
4199                  * The only op for string should be ? :
4200                  */
4201                 if (arg->op.op[0] != '?')
4202                         return;
4203                 val = eval_num_arg(data, size, event, arg->op.left);
4204                 if (val)
4205                         print_str_arg(s, data, size, event,
4206                                       format, len_arg, arg->op.right->op.left);
4207                 else
4208                         print_str_arg(s, data, size, event,
4209                                       format, len_arg, arg->op.right->op.right);
4210                 break;
4211         case TEP_PRINT_FUNC:
4212                 process_defined_func(s, data, size, event, arg);
4213                 break;
4214         default:
4215                 /* well... */
4216                 break;
4217         }
4218
4219         return;
4220
4221 out_warning_field:
4222         do_warning_event(event, "%s: field %s not found",
4223                          __func__, arg->field.name);
4224 }
4225
4226 static unsigned long long
4227 process_defined_func(struct trace_seq *s, void *data, int size,
4228                      struct tep_event *event, struct tep_print_arg *arg)
4229 {
4230         struct tep_function_handler *func_handle = arg->func.func;
4231         struct func_params *param;
4232         unsigned long long *args;
4233         unsigned long long ret;
4234         struct tep_print_arg *farg;
4235         struct trace_seq str;
4236         struct save_str {
4237                 struct save_str *next;
4238                 char *str;
4239         } *strings = NULL, *string;
4240         int i;
4241
4242         if (!func_handle->nr_args) {
4243                 ret = (*func_handle->func)(s, NULL);
4244                 goto out;
4245         }
4246
4247         farg = arg->func.args;
4248         param = func_handle->params;
4249
4250         ret = ULLONG_MAX;
4251         args = malloc(sizeof(*args) * func_handle->nr_args);
4252         if (!args)
4253                 goto out;
4254
4255         for (i = 0; i < func_handle->nr_args; i++) {
4256                 switch (param->type) {
4257                 case TEP_FUNC_ARG_INT:
4258                 case TEP_FUNC_ARG_LONG:
4259                 case TEP_FUNC_ARG_PTR:
4260                         args[i] = eval_num_arg(data, size, event, farg);
4261                         break;
4262                 case TEP_FUNC_ARG_STRING:
4263                         trace_seq_init(&str);
4264                         print_str_arg(&str, data, size, event, "%s", -1, farg);
4265                         trace_seq_terminate(&str);
4266                         string = malloc(sizeof(*string));
4267                         if (!string) {
4268                                 do_warning_event(event, "%s(%d): malloc str",
4269                                                  __func__, __LINE__);
4270                                 goto out_free;
4271                         }
4272                         string->next = strings;
4273                         string->str = strdup(str.buffer);
4274                         if (!string->str) {
4275                                 free(string);
4276                                 do_warning_event(event, "%s(%d): malloc str",
4277                                                  __func__, __LINE__);
4278                                 goto out_free;
4279                         }
4280                         args[i] = (uintptr_t)string->str;
4281                         strings = string;
4282                         trace_seq_destroy(&str);
4283                         break;
4284                 default:
4285                         /*
4286                          * Something went totally wrong, this is not
4287                          * an input error, something in this code broke.
4288                          */
4289                         do_warning_event(event, "Unexpected end of arguments\n");
4290                         goto out_free;
4291                 }
4292                 farg = farg->next;
4293                 param = param->next;
4294         }
4295
4296         ret = (*func_handle->func)(s, args);
4297 out_free:
4298         free(args);
4299         while (strings) {
4300                 string = strings;
4301                 strings = string->next;
4302                 free(string->str);
4303                 free(string);
4304         }
4305
4306  out:
4307         /* TBD : handle return type here */
4308         return ret;
4309 }
4310
4311 static void free_args(struct tep_print_arg *args)
4312 {
4313         struct tep_print_arg *next;
4314
4315         while (args) {
4316                 next = args->next;
4317
4318                 free_arg(args);
4319                 args = next;
4320         }
4321 }
4322
4323 static struct tep_print_arg *make_bprint_args(char *fmt, void *data, int size, struct tep_event *event)
4324 {
4325         struct tep_handle *tep = event->tep;
4326         struct tep_format_field *field, *ip_field;
4327         struct tep_print_arg *args, *arg, **next;
4328         unsigned long long ip, val;
4329         char *ptr;
4330         void *bptr;
4331         int vsize = 0;
4332
4333         field = tep->bprint_buf_field;
4334         ip_field = tep->bprint_ip_field;
4335
4336         if (!field) {
4337                 field = tep_find_field(event, "buf");
4338                 if (!field) {
4339                         do_warning_event(event, "can't find buffer field for binary printk");
4340                         return NULL;
4341                 }
4342                 ip_field = tep_find_field(event, "ip");
4343                 if (!ip_field) {
4344                         do_warning_event(event, "can't find ip field for binary printk");
4345                         return NULL;
4346                 }
4347                 tep->bprint_buf_field = field;
4348                 tep->bprint_ip_field = ip_field;
4349         }
4350
4351         ip = tep_read_number(tep, data + ip_field->offset, ip_field->size);
4352
4353         /*
4354          * The first arg is the IP pointer.
4355          */
4356         args = alloc_arg();
4357         if (!args) {
4358                 do_warning_event(event, "%s(%d): not enough memory!",
4359                                  __func__, __LINE__);
4360                 return NULL;
4361         }
4362         arg = args;
4363         arg->next = NULL;
4364         next = &arg->next;
4365
4366         arg->type = TEP_PRINT_ATOM;
4367                 
4368         if (asprintf(&arg->atom.atom, "%lld", ip) < 0)
4369                 goto out_free;
4370
4371         /* skip the first "%ps: " */
4372         for (ptr = fmt + 5, bptr = data + field->offset;
4373              bptr < data + size && *ptr; ptr++) {
4374                 int ls = 0;
4375
4376                 if (*ptr == '%') {
4377  process_again:
4378                         ptr++;
4379                         switch (*ptr) {
4380                         case '%':
4381                                 break;
4382                         case 'l':
4383                                 ls++;
4384                                 goto process_again;
4385                         case 'L':
4386                                 ls = 2;
4387                                 goto process_again;
4388                         case '0' ... '9':
4389                                 goto process_again;
4390                         case '.':
4391                                 goto process_again;
4392                         case 'z':
4393                         case 'Z':
4394                                 ls = 1;
4395                                 goto process_again;
4396                         case 'p':
4397                                 ls = 1;
4398                                 if (isalnum(ptr[1])) {
4399                                         ptr++;
4400                                         /* Check for special pointers */
4401                                         switch (*ptr) {
4402                                         case 's':
4403                                         case 'S':
4404                                         case 'x':
4405                                                 break;
4406                                         case 'f':
4407                                         case 'F':
4408                                                 /*
4409                                                  * Pre-5.5 kernels use %pf and
4410                                                  * %pF for printing symbols
4411                                                  * while kernels since 5.5 use
4412                                                  * %pfw for fwnodes. So check
4413                                                  * %p[fF] isn't followed by 'w'.
4414                                                  */
4415                                                 if (ptr[1] != 'w')
4416                                                         break;
4417                                                 /* fall through */
4418                                         default:
4419                                                 /*
4420                                                  * Older kernels do not process
4421                                                  * dereferenced pointers.
4422                                                  * Only process if the pointer
4423                                                  * value is a printable.
4424                                                  */
4425                                                 if (isprint(*(char *)bptr))
4426                                                         goto process_string;
4427                                         }
4428                                 }
4429                                 /* fall through */
4430                         case 'd':
4431                         case 'u':
4432                         case 'i':
4433                         case 'x':
4434                         case 'X':
4435                         case 'o':
4436                                 switch (ls) {
4437                                 case 0:
4438                                         vsize = 4;
4439                                         break;
4440                                 case 1:
4441                                         vsize = tep->long_size;
4442                                         break;
4443                                 case 2:
4444                                         vsize = 8;
4445                                         break;
4446                                 default:
4447                                         vsize = ls; /* ? */
4448                                         break;
4449                                 }
4450                         /* fall through */
4451                         case '*':
4452                                 if (*ptr == '*')
4453                                         vsize = 4;
4454
4455                                 /* the pointers are always 4 bytes aligned */
4456                                 bptr = (void *)(((unsigned long)bptr + 3) &
4457                                                 ~3);
4458                                 val = tep_read_number(tep, bptr, vsize);
4459                                 bptr += vsize;
4460                                 arg = alloc_arg();
4461                                 if (!arg) {
4462                                         do_warning_event(event, "%s(%d): not enough memory!",
4463                                                    __func__, __LINE__);
4464                                         goto out_free;
4465                                 }
4466                                 arg->next = NULL;
4467                                 arg->type = TEP_PRINT_ATOM;
4468                                 if (asprintf(&arg->atom.atom, "%lld", val) < 0) {
4469                                         free(arg);
4470                                         goto out_free;
4471                                 }
4472                                 *next = arg;
4473                                 next = &arg->next;
4474                                 /*
4475                                  * The '*' case means that an arg is used as the length.
4476                                  * We need to continue to figure out for what.
4477                                  */
4478                                 if (*ptr == '*')
4479                                         goto process_again;
4480
4481                                 break;
4482                         case 's':
4483  process_string:
4484                                 arg = alloc_arg();
4485                                 if (!arg) {
4486                                         do_warning_event(event, "%s(%d): not enough memory!",
4487                                                    __func__, __LINE__);
4488                                         goto out_free;
4489                                 }
4490                                 arg->next = NULL;
4491                                 arg->type = TEP_PRINT_BSTRING;
4492                                 arg->string.string = strdup(bptr);
4493                                 if (!arg->string.string)
4494                                         goto out_free;
4495                                 bptr += strlen(bptr) + 1;
4496                                 *next = arg;
4497                                 next = &arg->next;
4498                         default:
4499                                 break;
4500                         }
4501                 }
4502         }
4503
4504         return args;
4505
4506 out_free:
4507         free_args(args);
4508         return NULL;
4509 }
4510
4511 static char *
4512 get_bprint_format(void *data, int size __maybe_unused,
4513                   struct tep_event *event)
4514 {
4515         struct tep_handle *tep = event->tep;
4516         unsigned long long addr;
4517         struct tep_format_field *field;
4518         struct printk_map *printk;
4519         char *format;
4520
4521         field = tep->bprint_fmt_field;
4522
4523         if (!field) {
4524                 field = tep_find_field(event, "fmt");
4525                 if (!field) {
4526                         do_warning_event(event, "can't find format field for binary printk");
4527                         return NULL;
4528                 }
4529                 tep->bprint_fmt_field = field;
4530         }
4531
4532         addr = tep_read_number(tep, data + field->offset, field->size);
4533
4534         printk = find_printk(tep, addr);
4535         if (!printk) {
4536                 if (asprintf(&format, "%%ps: (NO FORMAT FOUND at %llx)\n", addr) < 0)
4537                         return NULL;
4538                 return format;
4539         }
4540
4541         if (asprintf(&format, "%s: %s", "%ps", printk->printk) < 0)
4542                 return NULL;
4543
4544         return format;
4545 }
4546
4547 static int print_mac_arg(struct trace_seq *s, const char *format,
4548                          void *data, int size, struct tep_event *event,
4549                          struct tep_print_arg *arg)
4550 {
4551         const char *fmt = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x";
4552         bool reverse = false;
4553         unsigned char *buf;
4554         int ret = 0;
4555
4556         if (arg->type == TEP_PRINT_FUNC) {
4557                 process_defined_func(s, data, size, event, arg);
4558                 return 0;
4559         }
4560
4561         if (arg->type != TEP_PRINT_FIELD) {
4562                 trace_seq_printf(s, "ARG TYPE NOT FIELD BUT %d",
4563                                  arg->type);
4564                 return 0;
4565         }
4566
4567         if (format[0] == 'm') {
4568                 fmt = "%.2x%.2x%.2x%.2x%.2x%.2x";
4569         } else if (format[0] == 'M' && format[1] == 'F') {
4570                 fmt = "%.2x-%.2x-%.2x-%.2x-%.2x-%.2x";
4571                 ret++;
4572         }
4573         if (format[1] == 'R') {
4574                 reverse = true;
4575                 ret++;
4576         }
4577
4578         if (!arg->field.field) {
4579                 arg->field.field =
4580                         tep_find_any_field(event, arg->field.name);
4581                 if (!arg->field.field) {
4582                         do_warning_event(event, "%s: field %s not found",
4583                                          __func__, arg->field.name);
4584                         return ret;
4585                 }
4586         }
4587         if (arg->field.field->size != 6) {
4588                 trace_seq_printf(s, "INVALIDMAC");
4589                 return ret;
4590         }
4591
4592         buf = data + arg->field.field->offset;
4593         if (reverse)
4594                 trace_seq_printf(s, fmt, buf[5], buf[4], buf[3], buf[2], buf[1], buf[0]);
4595         else
4596                 trace_seq_printf(s, fmt, buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]);
4597
4598         return ret;
4599 }
4600
4601 static int parse_ip4_print_args(struct tep_handle *tep,
4602                                 const char *ptr, bool *reverse)
4603 {
4604         int ret = 0;
4605
4606         *reverse = false;
4607
4608         /* hnbl */
4609         switch (*ptr) {
4610         case 'h':
4611                 if (tep->file_bigendian)
4612                         *reverse = false;
4613                 else
4614                         *reverse = true;
4615                 ret++;
4616                 break;
4617         case 'l':
4618                 *reverse = true;
4619                 ret++;
4620                 break;
4621         case 'n':
4622         case 'b':
4623                 ret++;
4624                 /* fall through */
4625         default:
4626                 *reverse = false;
4627                 break;
4628         }
4629
4630         return ret;
4631 }
4632
4633 static void print_ip4_addr(struct trace_seq *s, char i, bool reverse, unsigned char *buf)
4634 {
4635         const char *fmt;
4636
4637         if (i == 'i')
4638                 fmt = "%03d.%03d.%03d.%03d";
4639         else
4640                 fmt = "%d.%d.%d.%d";
4641
4642         if (reverse)
4643                 trace_seq_printf(s, fmt, buf[3], buf[2], buf[1], buf[0]);
4644         else
4645                 trace_seq_printf(s, fmt, buf[0], buf[1], buf[2], buf[3]);
4646
4647 }
4648
4649 static inline bool ipv6_addr_v4mapped(const struct in6_addr *a)
4650 {
4651         return ((unsigned long)(a->s6_addr32[0] | a->s6_addr32[1]) |
4652                 (unsigned long)(a->s6_addr32[2] ^ htonl(0x0000ffff))) == 0UL;
4653 }
4654
4655 static inline bool ipv6_addr_is_isatap(const struct in6_addr *addr)
4656 {
4657         return (addr->s6_addr32[2] | htonl(0x02000000)) == htonl(0x02005EFE);
4658 }
4659
4660 static void print_ip6c_addr(struct trace_seq *s, unsigned char *addr)
4661 {
4662         int i, j, range;
4663         unsigned char zerolength[8];
4664         int longest = 1;
4665         int colonpos = -1;
4666         uint16_t word;
4667         uint8_t hi, lo;
4668         bool needcolon = false;
4669         bool useIPv4;
4670         struct in6_addr in6;
4671
4672         memcpy(&in6, addr, sizeof(struct in6_addr));
4673
4674         useIPv4 = ipv6_addr_v4mapped(&in6) || ipv6_addr_is_isatap(&in6);
4675
4676         memset(zerolength, 0, sizeof(zerolength));
4677
4678         if (useIPv4)
4679                 range = 6;
4680         else
4681                 range = 8;
4682
4683         /* find position of longest 0 run */
4684         for (i = 0; i < range; i++) {
4685                 for (j = i; j < range; j++) {
4686                         if (in6.s6_addr16[j] != 0)
4687                                 break;
4688                         zerolength[i]++;
4689                 }
4690         }
4691         for (i = 0; i < range; i++) {
4692                 if (zerolength[i] > longest) {
4693                         longest = zerolength[i];
4694                         colonpos = i;
4695                 }
4696         }
4697         if (longest == 1)               /* don't compress a single 0 */
4698                 colonpos = -1;
4699
4700         /* emit address */
4701         for (i = 0; i < range; i++) {
4702                 if (i == colonpos) {
4703                         if (needcolon || i == 0)
4704                                 trace_seq_printf(s, ":");
4705                         trace_seq_printf(s, ":");
4706                         needcolon = false;
4707                         i += longest - 1;
4708                         continue;
4709                 }
4710                 if (needcolon) {
4711                         trace_seq_printf(s, ":");
4712                         needcolon = false;
4713                 }
4714                 /* hex u16 without leading 0s */
4715                 word = ntohs(in6.s6_addr16[i]);
4716                 hi = word >> 8;
4717                 lo = word & 0xff;
4718                 if (hi)
4719                         trace_seq_printf(s, "%x%02x", hi, lo);
4720                 else
4721                         trace_seq_printf(s, "%x", lo);
4722
4723                 needcolon = true;
4724         }
4725
4726         if (useIPv4) {
4727                 if (needcolon)
4728                         trace_seq_printf(s, ":");
4729                 print_ip4_addr(s, 'I', false, &in6.s6_addr[12]);
4730         }
4731
4732         return;
4733 }
4734
4735 static void print_ip6_addr(struct trace_seq *s, char i, unsigned char *buf)
4736 {
4737         int j;
4738
4739         for (j = 0; j < 16; j += 2) {
4740                 trace_seq_printf(s, "%02x%02x", buf[j], buf[j+1]);
4741                 if (i == 'I' && j < 14)
4742                         trace_seq_printf(s, ":");
4743         }
4744 }
4745
4746 /*
4747  * %pi4   print an IPv4 address with leading zeros
4748  * %pI4   print an IPv4 address without leading zeros
4749  * %pi6   print an IPv6 address without colons
4750  * %pI6   print an IPv6 address with colons
4751  * %pI6c  print an IPv6 address in compressed form with colons
4752  * %pISpc print an IP address based on sockaddr; p adds port.
4753  */
4754 static int print_ipv4_arg(struct trace_seq *s, const char *ptr, char i,
4755                           void *data, int size, struct tep_event *event,
4756                           struct tep_print_arg *arg)
4757 {
4758         bool reverse = false;
4759         unsigned char *buf;
4760         int ret;
4761
4762         ret = parse_ip4_print_args(event->tep, ptr, &reverse);
4763
4764         if (arg->type == TEP_PRINT_FUNC) {
4765                 process_defined_func(s, data, size, event, arg);
4766                 return ret;
4767         }
4768
4769         if (arg->type != TEP_PRINT_FIELD) {
4770                 trace_seq_printf(s, "ARG TYPE NOT FIELD BUT %d", arg->type);
4771                 return ret;
4772         }
4773
4774         if (!arg->field.field) {
4775                 arg->field.field =
4776                         tep_find_any_field(event, arg->field.name);
4777                 if (!arg->field.field) {
4778                         do_warning("%s: field %s not found",
4779                                    __func__, arg->field.name);
4780                         return ret;
4781                 }
4782         }
4783
4784         buf = data + arg->field.field->offset;
4785
4786         if (arg->field.field->size != 4) {
4787                 trace_seq_printf(s, "INVALIDIPv4");
4788                 return ret;
4789         }
4790
4791         print_ip4_addr(s, i, reverse, buf);
4792         return ret;
4793
4794 }
4795
4796 static int print_ipv6_arg(struct trace_seq *s, const char *ptr, char i,
4797                           void *data, int size, struct tep_event *event,
4798                           struct tep_print_arg *arg)
4799 {
4800         char have_c = 0;
4801         unsigned char *buf;
4802         int rc = 0;
4803
4804         /* pI6c */
4805         if (i == 'I' && *ptr == 'c') {
4806                 have_c = 1;
4807                 ptr++;
4808                 rc++;
4809         }
4810
4811         if (arg->type == TEP_PRINT_FUNC) {
4812                 process_defined_func(s, data, size, event, arg);
4813                 return rc;
4814         }
4815
4816         if (arg->type != TEP_PRINT_FIELD) {
4817                 trace_seq_printf(s, "ARG TYPE NOT FIELD BUT %d", arg->type);
4818                 return rc;
4819         }
4820
4821         if (!arg->field.field) {
4822                 arg->field.field =
4823                         tep_find_any_field(event, arg->field.name);
4824                 if (!arg->field.field) {
4825                         do_warning("%s: field %s not found",
4826                                    __func__, arg->field.name);
4827                         return rc;
4828                 }
4829         }
4830
4831         buf = data + arg->field.field->offset;
4832
4833         if (arg->field.field->size != 16) {
4834                 trace_seq_printf(s, "INVALIDIPv6");
4835                 return rc;
4836         }
4837
4838         if (have_c)
4839                 print_ip6c_addr(s, buf);
4840         else
4841                 print_ip6_addr(s, i, buf);
4842
4843         return rc;
4844 }
4845
4846 static int print_ipsa_arg(struct trace_seq *s, const char *ptr, char i,
4847                           void *data, int size, struct tep_event *event,
4848                           struct tep_print_arg *arg)
4849 {
4850         char have_c = 0, have_p = 0;
4851         unsigned char *buf;
4852         struct sockaddr_storage *sa;
4853         bool reverse = false;
4854         int rc = 0;
4855         int ret;
4856
4857         /* pISpc */
4858         if (i == 'I') {
4859                 if (*ptr == 'p') {
4860                         have_p = 1;
4861                         ptr++;
4862                         rc++;
4863                 }
4864                 if (*ptr == 'c') {
4865                         have_c = 1;
4866                         ptr++;
4867                         rc++;
4868                 }
4869         }
4870         ret = parse_ip4_print_args(event->tep, ptr, &reverse);
4871         ptr += ret;
4872         rc += ret;
4873
4874         if (arg->type == TEP_PRINT_FUNC) {
4875                 process_defined_func(s, data, size, event, arg);
4876                 return rc;
4877         }
4878
4879         if (arg->type != TEP_PRINT_FIELD) {
4880                 trace_seq_printf(s, "ARG TYPE NOT FIELD BUT %d", arg->type);
4881                 return rc;
4882         }
4883
4884         if (!arg->field.field) {
4885                 arg->field.field =
4886                         tep_find_any_field(event, arg->field.name);
4887                 if (!arg->field.field) {
4888                         do_warning("%s: field %s not found",
4889                                    __func__, arg->field.name);
4890                         return rc;
4891                 }
4892         }
4893
4894         sa = (struct sockaddr_storage *) (data + arg->field.field->offset);
4895
4896         if (sa->ss_family == AF_INET) {
4897                 struct sockaddr_in *sa4 = (struct sockaddr_in *) sa;
4898
4899                 if (arg->field.field->size < sizeof(struct sockaddr_in)) {
4900                         trace_seq_printf(s, "INVALIDIPv4");
4901                         return rc;
4902                 }
4903
4904                 print_ip4_addr(s, i, reverse, (unsigned char *) &sa4->sin_addr);
4905                 if (have_p)
4906                         trace_seq_printf(s, ":%d", ntohs(sa4->sin_port));
4907
4908
4909         } else if (sa->ss_family == AF_INET6) {
4910                 struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *) sa;
4911
4912                 if (arg->field.field->size < sizeof(struct sockaddr_in6)) {
4913                         trace_seq_printf(s, "INVALIDIPv6");
4914                         return rc;
4915                 }
4916
4917                 if (have_p)
4918                         trace_seq_printf(s, "[");
4919
4920                 buf = (unsigned char *) &sa6->sin6_addr;
4921                 if (have_c)
4922                         print_ip6c_addr(s, buf);
4923                 else
4924                         print_ip6_addr(s, i, buf);
4925
4926                 if (have_p)
4927                         trace_seq_printf(s, "]:%d", ntohs(sa6->sin6_port));
4928         }
4929
4930         return rc;
4931 }
4932
4933 static int print_ip_arg(struct trace_seq *s, const char *ptr,
4934                         void *data, int size, struct tep_event *event,
4935                         struct tep_print_arg *arg)
4936 {
4937         char i = *ptr;  /* 'i' or 'I' */
4938         int rc = 1;
4939
4940         /* IP version */
4941         ptr++;
4942
4943         switch (*ptr) {
4944         case '4':
4945                 rc += print_ipv4_arg(s, ptr + 1, i, data, size, event, arg);
4946                 break;
4947         case '6':
4948                 rc += print_ipv6_arg(s, ptr + 1, i, data, size, event, arg);
4949                 break;
4950         case 'S':
4951                 rc += print_ipsa_arg(s, ptr + 1, i, data, size, event, arg);
4952                 break;
4953         default:
4954                 return 0;
4955         }
4956
4957         return rc;
4958 }
4959
4960 static const int guid_index[16] = {3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15};
4961 static const int uuid_index[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
4962
4963 static int print_uuid_arg(struct trace_seq *s, const char *ptr,
4964                         void *data, int size, struct tep_event *event,
4965                         struct tep_print_arg *arg)
4966 {
4967         const int *index = uuid_index;
4968         char *format = "%02x";
4969         int ret = 0;
4970         char *buf;
4971         int i;
4972
4973         switch (*(ptr + 1)) {
4974         case 'L':
4975                 format = "%02X";
4976                 /* fall through */
4977         case 'l':
4978                 index = guid_index;
4979                 ret++;
4980                 break;
4981         case 'B':
4982                 format = "%02X";
4983                 /* fall through */
4984         case 'b':
4985                 ret++;
4986                 break;
4987         }
4988
4989         if (arg->type == TEP_PRINT_FUNC) {
4990                 process_defined_func(s, data, size, event, arg);
4991                 return ret;
4992         }
4993
4994         if (arg->type != TEP_PRINT_FIELD) {
4995                 trace_seq_printf(s, "ARG TYPE NOT FIELD BUT %d", arg->type);
4996                 return ret;
4997         }
4998
4999         if (!arg->field.field) {
5000                 arg->field.field =
5001                         tep_find_any_field(event, arg->field.name);
5002                 if (!arg->field.field) {
5003                         do_warning("%s: field %s not found",
5004                                    __func__, arg->field.name);
5005                         return ret;
5006                 }
5007         }
5008
5009         if (arg->field.field->size != 16) {
5010                 trace_seq_printf(s, "INVALIDUUID");
5011                 return ret;
5012         }
5013
5014         buf = data + arg->field.field->offset;
5015
5016         for (i = 0; i < 16; i++) {
5017                 trace_seq_printf(s, format, buf[index[i]] & 0xff);
5018                 switch (i) {
5019                 case 3:
5020                 case 5:
5021                 case 7:
5022                 case 9:
5023                         trace_seq_printf(s, "-");
5024                         break;
5025                 }
5026         }
5027
5028         return ret;
5029 }
5030
5031 static int print_raw_buff_arg(struct trace_seq *s, const char *ptr,
5032                               void *data, int size, struct tep_event *event,
5033                               struct tep_print_arg *arg, int print_len)
5034 {
5035         int plen = print_len;
5036         char *delim = " ";
5037         int ret = 0;
5038         char *buf;
5039         int i;
5040         unsigned long offset;
5041         int arr_len;
5042
5043         switch (*(ptr + 1)) {
5044         case 'C':
5045                 delim = ":";
5046                 ret++;
5047                 break;
5048         case 'D':
5049                 delim = "-";
5050                 ret++;
5051                 break;
5052         case 'N':
5053                 delim = "";
5054                 ret++;
5055                 break;
5056         }
5057
5058         if (arg->type == TEP_PRINT_FUNC) {
5059                 process_defined_func(s, data, size, event, arg);
5060                 return ret;
5061         }
5062
5063         if (arg->type != TEP_PRINT_DYNAMIC_ARRAY) {
5064                 trace_seq_printf(s, "ARG TYPE NOT FIELD BUT %d", arg->type);
5065                 return ret;
5066         }
5067
5068         offset = tep_read_number(event->tep,
5069                                  data + arg->dynarray.field->offset,
5070                                  arg->dynarray.field->size);
5071         arr_len = (unsigned long long)(offset >> 16);
5072         buf = data + (offset & 0xffff);
5073
5074         if (arr_len < plen)
5075                 plen = arr_len;
5076
5077         if (plen < 1)
5078                 return ret;
5079
5080         trace_seq_printf(s, "%02x", buf[0] & 0xff);
5081         for (i = 1; i < plen; i++)
5082                 trace_seq_printf(s, "%s%02x", delim, buf[i] & 0xff);
5083
5084         return ret;
5085 }
5086
5087 static int is_printable_array(char *p, unsigned int len)
5088 {
5089         unsigned int i;
5090
5091         for (i = 0; i < len && p[i]; i++)
5092                 if (!isprint(p[i]) && !isspace(p[i]))
5093                     return 0;
5094         return 1;
5095 }
5096
5097 void tep_print_field(struct trace_seq *s, void *data,
5098                      struct tep_format_field *field)
5099 {
5100         unsigned long long val;
5101         unsigned int offset, len, i;
5102         struct tep_handle *tep = field->event->tep;
5103
5104         if (field->flags & TEP_FIELD_IS_ARRAY) {
5105                 offset = field->offset;
5106                 len = field->size;
5107                 if (field->flags & TEP_FIELD_IS_DYNAMIC) {
5108                         val = tep_read_number(tep, data + offset, len);
5109                         offset = val;
5110                         len = offset >> 16;
5111                         offset &= 0xffff;
5112                 }
5113                 if (field->flags & TEP_FIELD_IS_STRING &&
5114                     is_printable_array(data + offset, len)) {
5115                         trace_seq_printf(s, "%s", (char *)data + offset);
5116                 } else {
5117                         trace_seq_puts(s, "ARRAY[");
5118                         for (i = 0; i < len; i++) {
5119                                 if (i)
5120                                         trace_seq_puts(s, ", ");
5121                                 trace_seq_printf(s, "%02x",
5122                                                  *((unsigned char *)data + offset + i));
5123                         }
5124                         trace_seq_putc(s, ']');
5125                         field->flags &= ~TEP_FIELD_IS_STRING;
5126                 }
5127         } else {
5128                 val = tep_read_number(tep, data + field->offset,
5129                                       field->size);
5130                 if (field->flags & TEP_FIELD_IS_POINTER) {
5131                         trace_seq_printf(s, "0x%llx", val);
5132                 } else if (field->flags & TEP_FIELD_IS_SIGNED) {
5133                         switch (field->size) {
5134                         case 4:
5135                                 /*
5136                                  * If field is long then print it in hex.
5137                                  * A long usually stores pointers.
5138                                  */
5139                                 if (field->flags & TEP_FIELD_IS_LONG)
5140                                         trace_seq_printf(s, "0x%x", (int)val);
5141                                 else
5142                                         trace_seq_printf(s, "%d", (int)val);
5143                                 break;
5144                         case 2:
5145                                 trace_seq_printf(s, "%2d", (short)val);
5146                                 break;
5147                         case 1:
5148                                 trace_seq_printf(s, "%1d", (char)val);
5149                                 break;
5150                         default:
5151                                 trace_seq_printf(s, "%lld", val);
5152                         }
5153                 } else {
5154                         if (field->flags & TEP_FIELD_IS_LONG)
5155                                 trace_seq_printf(s, "0x%llx", val);
5156                         else
5157                                 trace_seq_printf(s, "%llu", val);
5158                 }
5159         }
5160 }
5161
5162 void tep_print_fields(struct trace_seq *s, void *data,
5163                       int size __maybe_unused, struct tep_event *event)
5164 {
5165         struct tep_format_field *field;
5166
5167         field = event->format.fields;
5168         while (field) {
5169                 trace_seq_printf(s, " %s=", field->name);
5170                 tep_print_field(s, data, field);
5171                 field = field->next;
5172         }
5173 }
5174
5175 static int print_function(struct trace_seq *s, const char *format,
5176                           void *data, int size, struct tep_event *event,
5177                           struct tep_print_arg *arg)
5178 {
5179         struct func_map *func;
5180         unsigned long long val;
5181
5182         val = eval_num_arg(data, size, event, arg);
5183         func = find_func(event->tep, val);
5184         if (func) {
5185                 trace_seq_puts(s, func->func);
5186                 if (*format == 'F' || *format == 'S')
5187                         trace_seq_printf(s, "+0x%llx", val - func->addr);
5188         } else {
5189                 if (event->tep->long_size == 4)
5190                         trace_seq_printf(s, "0x%lx", (long)val);
5191                 else
5192                         trace_seq_printf(s, "0x%llx", (long long)val);
5193         }
5194
5195         return 0;
5196 }
5197
5198 static int print_arg_pointer(struct trace_seq *s, const char *format, int plen,
5199                              void *data, int size,
5200                              struct tep_event *event, struct tep_print_arg *arg)
5201 {
5202         unsigned long long val;
5203         int ret = 1;
5204
5205         if (arg->type == TEP_PRINT_BSTRING) {
5206                 trace_seq_puts(s, arg->string.string);
5207                 return 0;
5208         }
5209         while (*format) {
5210                 if (*format == 'p') {
5211                         format++;
5212                         break;
5213                 }
5214                 format++;
5215         }
5216
5217         switch (*format) {
5218         case 'F':
5219         case 'f':
5220         case 'S':
5221         case 's':
5222                 ret += print_function(s, format, data, size, event, arg);
5223                 break;
5224         case 'M':
5225         case 'm':
5226                 ret += print_mac_arg(s, format, data, size, event, arg);
5227                 break;
5228         case 'I':
5229         case 'i':
5230                 ret += print_ip_arg(s, format, data, size, event, arg);
5231                 break;
5232         case 'U':
5233                 ret += print_uuid_arg(s, format, data, size, event, arg);
5234                 break;
5235         case 'h':
5236                 ret += print_raw_buff_arg(s, format, data, size, event, arg, plen);
5237                 break;
5238         default:
5239                 ret = 0;
5240                 val = eval_num_arg(data, size, event, arg);
5241                 trace_seq_printf(s, "%p", (void *)(intptr_t)val);
5242                 break;
5243         }
5244
5245         return ret;
5246
5247 }
5248
5249 static int print_arg_number(struct trace_seq *s, const char *format, int plen,
5250                             void *data, int size, int ls,
5251                             struct tep_event *event, struct tep_print_arg *arg)
5252 {
5253         unsigned long long val;
5254
5255         val = eval_num_arg(data, size, event, arg);
5256
5257         switch (ls) {
5258         case -2:
5259                 if (plen >= 0)
5260                         trace_seq_printf(s, format, plen, (char)val);
5261                 else
5262                         trace_seq_printf(s, format, (char)val);
5263                 break;
5264         case -1:
5265                 if (plen >= 0)
5266                         trace_seq_printf(s, format, plen, (short)val);
5267                 else
5268                         trace_seq_printf(s, format, (short)val);
5269                 break;
5270         case 0:
5271                 if (plen >= 0)
5272                         trace_seq_printf(s, format, plen, (int)val);
5273                 else
5274                         trace_seq_printf(s, format, (int)val);
5275                 break;
5276         case 1:
5277                 if (plen >= 0)
5278                         trace_seq_printf(s, format, plen, (long)val);
5279                 else
5280                         trace_seq_printf(s, format, (long)val);
5281                 break;
5282         case 2:
5283                 if (plen >= 0)
5284                         trace_seq_printf(s, format, plen, (long long)val);
5285                 else
5286                         trace_seq_printf(s, format, (long long)val);
5287                 break;
5288         default:
5289                 do_warning_event(event, "bad count (%d)", ls);
5290                 event->flags |= TEP_EVENT_FL_FAILED;
5291         }
5292         return 0;
5293 }
5294
5295
5296 static void print_arg_string(struct trace_seq *s, const char *format, int plen,
5297                              void *data, int size,
5298                              struct tep_event *event, struct tep_print_arg *arg)
5299 {
5300         struct trace_seq p;
5301
5302         /* Use helper trace_seq */
5303         trace_seq_init(&p);
5304         print_str_arg(&p, data, size, event,
5305                       format, plen, arg);
5306         trace_seq_terminate(&p);
5307         trace_seq_puts(s, p.buffer);
5308         trace_seq_destroy(&p);
5309 }
5310
5311 static int parse_arg_format_pointer(const char *format)
5312 {
5313         int ret = 0;
5314         int index;
5315         int loop;
5316
5317         switch (*format) {
5318         case 'F':
5319         case 'S':
5320         case 'f':
5321         case 's':
5322                 ret++;
5323                 break;
5324         case 'M':
5325         case 'm':
5326                 /* [mM]R , [mM]F */
5327                 switch (format[1]) {
5328                 case 'R':
5329                 case 'F':
5330                         ret++;
5331                         break;
5332                 }
5333                 ret++;
5334                 break;
5335         case 'I':
5336         case 'i':
5337                 index = 2;
5338                 loop = 1;
5339                 switch (format[1]) {
5340                 case 'S':
5341                         /*[S][pfs]*/
5342                         while (loop) {
5343                                 switch (format[index]) {
5344                                 case 'p':
5345                                 case 'f':
5346                                 case 's':
5347                                         ret++;
5348                                         index++;
5349                                         break;
5350                                 default:
5351                                         loop = 0;
5352                                         break;
5353                                 }
5354                         }
5355                         /* fall through */
5356                 case '4':
5357                         /* [4S][hnbl] */
5358                         switch (format[index]) {
5359                         case 'h':
5360                         case 'n':
5361                         case 'l':
5362                         case 'b':
5363                                 ret++;
5364                                 index++;
5365                                 break;
5366                         }
5367                         if (format[1] == '4') {
5368                                 ret++;
5369                                 break;
5370                         }
5371                         /* fall through */
5372                 case '6':
5373                         /* [6S]c */
5374                         if (format[index] == 'c')
5375                                 ret++;
5376                         ret++;
5377                         break;
5378                 }
5379                 ret++;
5380                 break;
5381         case 'U':
5382                 switch (format[1]) {
5383                 case 'L':
5384                 case 'l':
5385                 case 'B':
5386                 case 'b':
5387                         ret++;
5388                         break;
5389                 }
5390                 ret++;
5391                 break;
5392         case 'h':
5393                 switch (format[1]) {
5394                 case 'C':
5395                 case 'D':
5396                 case 'N':
5397                         ret++;
5398                         break;
5399                 }
5400                 ret++;
5401                 break;
5402         default:
5403                 break;
5404         }
5405
5406         return ret;
5407 }
5408
5409 static void free_parse_args(struct tep_print_parse *arg)
5410 {
5411         struct tep_print_parse *del;
5412
5413         while (arg) {
5414                 del = arg;
5415                 arg = del->next;
5416                 free(del->format);
5417                 free(del);
5418         }
5419 }
5420
5421 static int parse_arg_add(struct tep_print_parse **parse, char *format,
5422                          enum tep_print_parse_type type,
5423                          struct tep_print_arg *arg,
5424                          struct tep_print_arg *len_as_arg,
5425                          int ls)
5426 {
5427         struct tep_print_parse *parg = NULL;
5428
5429         parg = calloc(1, sizeof(*parg));
5430         if (!parg)
5431                 goto error;
5432         parg->format = strdup(format);
5433         if (!parg->format)
5434                 goto error;
5435         parg->type = type;
5436         parg->arg = arg;
5437         parg->len_as_arg = len_as_arg;
5438         parg->ls = ls;
5439         *parse = parg;
5440         return 0;
5441 error:
5442         if (parg) {
5443                 free(parg->format);
5444                 free(parg);
5445         }
5446         return -1;
5447 }
5448
5449 static int parse_arg_format(struct tep_print_parse **parse,
5450                             struct tep_event *event,
5451                             const char *format, struct tep_print_arg **arg)
5452 {
5453         struct tep_print_arg *len_arg = NULL;
5454         char print_format[32];
5455         const char *start = format;
5456         int ret = 0;
5457         int ls = 0;
5458         int res;
5459         int len;
5460
5461         format++;
5462         ret++;
5463         for (; *format; format++) {
5464                 switch (*format) {
5465                 case '#':
5466                         /* FIXME: need to handle properly */
5467                         break;
5468                 case 'h':
5469                         ls--;
5470                         break;
5471                 case 'l':
5472                         ls++;
5473                         break;
5474                 case 'L':
5475                         ls = 2;
5476                         break;
5477                 case '.':
5478                 case 'z':
5479                 case 'Z':
5480                 case '0' ... '9':
5481                 case '-':
5482                         break;
5483                 case '*':
5484                         /* The argument is the length. */
5485                         if (!*arg) {
5486                                 do_warning_event(event, "no argument match");
5487                                 event->flags |= TEP_EVENT_FL_FAILED;
5488                                 goto out_failed;
5489                         }
5490                         if (len_arg) {
5491                                 do_warning_event(event, "argument already matched");
5492                                 event->flags |= TEP_EVENT_FL_FAILED;
5493                                 goto out_failed;
5494                         }
5495                         len_arg = *arg;
5496                         *arg = (*arg)->next;
5497                         break;
5498                 case 'p':
5499                         if (!*arg) {
5500                                 do_warning_event(event, "no argument match");
5501                                 event->flags |= TEP_EVENT_FL_FAILED;
5502                                 goto out_failed;
5503                         }
5504                         res = parse_arg_format_pointer(format + 1);
5505                         if (res > 0) {
5506                                 format += res;
5507                                 ret += res;
5508                         }
5509                         len = ((unsigned long)format + 1) -
5510                                 (unsigned long)start;
5511                         /* should never happen */
5512                         if (len > 31) {
5513                                 do_warning_event(event, "bad format!");
5514                                 event->flags |= TEP_EVENT_FL_FAILED;
5515                                 len = 31;
5516                         }
5517                         memcpy(print_format, start, len);
5518                         print_format[len] = 0;
5519
5520                         parse_arg_add(parse, print_format,
5521                                       PRINT_FMT_ARG_POINTER, *arg, len_arg, ls);
5522                         *arg = (*arg)->next;
5523                         ret++;
5524                         return ret;
5525                 case 'd':
5526                 case 'u':
5527                 case 'i':
5528                 case 'x':
5529                 case 'X':
5530                 case 'o':
5531                         if (!*arg) {
5532                                 do_warning_event(event, "no argument match");
5533                                 event->flags |= TEP_EVENT_FL_FAILED;
5534                                 goto out_failed;
5535                         }
5536
5537                         len = ((unsigned long)format + 1) -
5538                                 (unsigned long)start;
5539
5540                         /* should never happen */
5541                         if (len > 30) {
5542                                 do_warning_event(event, "bad format!");
5543                                 event->flags |= TEP_EVENT_FL_FAILED;
5544                                 len = 31;
5545                         }
5546                         memcpy(print_format, start, len);
5547                         print_format[len] = 0;
5548
5549                         if (event->tep->long_size == 8 && ls == 1 &&
5550                             sizeof(long) != 8) {
5551                                 char *p;
5552
5553                                 /* make %l into %ll */
5554                                 if (ls == 1 && (p = strchr(print_format, 'l')))
5555                                         memmove(p+1, p, strlen(p)+1);
5556                                 ls = 2;
5557                         }
5558                         if (ls < -2 || ls > 2) {
5559                                 do_warning_event(event, "bad count (%d)", ls);
5560                                 event->flags |= TEP_EVENT_FL_FAILED;
5561                         }
5562                         parse_arg_add(parse, print_format,
5563                                       PRINT_FMT_ARG_DIGIT, *arg, len_arg, ls);
5564                         *arg = (*arg)->next;
5565                         ret++;
5566                         return ret;
5567                 case 's':
5568                         if (!*arg) {
5569                                 do_warning_event(event, "no matching argument");
5570                                 event->flags |= TEP_EVENT_FL_FAILED;
5571                                 goto out_failed;
5572                         }
5573
5574                         len = ((unsigned long)format + 1) -
5575                                 (unsigned long)start;
5576
5577                         /* should never happen */
5578                         if (len > 31) {
5579                                 do_warning_event(event, "bad format!");
5580                                 event->flags |= TEP_EVENT_FL_FAILED;
5581                                 len = 31;
5582                         }
5583
5584                         memcpy(print_format, start, len);
5585                         print_format[len] = 0;
5586
5587                         parse_arg_add(parse, print_format,
5588                                         PRINT_FMT_ARG_STRING, *arg, len_arg, 0);
5589                         *arg = (*arg)->next;
5590                         ret++;
5591                         return ret;
5592                 default:
5593                         snprintf(print_format, 32, ">%c<", *format);
5594                         parse_arg_add(parse, print_format,
5595                                         PRINT_FMT_STRING, NULL, NULL, 0);
5596                         ret++;
5597                         return ret;
5598                 }
5599                 ret++;
5600         }
5601
5602 out_failed:
5603         return ret;
5604
5605 }
5606
5607 static int parse_arg_string(struct tep_print_parse **parse, const char *format)
5608 {
5609         struct trace_seq s;
5610         int ret = 0;
5611
5612         trace_seq_init(&s);
5613         for (; *format; format++) {
5614                 if (*format == '\\') {
5615                         format++;
5616                         ret++;
5617                         switch (*format) {
5618                         case 'n':
5619                                 trace_seq_putc(&s, '\n');
5620                                 break;
5621                         case 't':
5622                                 trace_seq_putc(&s, '\t');
5623                                 break;
5624                         case 'r':
5625                                 trace_seq_putc(&s, '\r');
5626                                 break;
5627                         case '\\':
5628                                 trace_seq_putc(&s, '\\');
5629                                 break;
5630                         default:
5631                                 trace_seq_putc(&s, *format);
5632                                 break;
5633                         }
5634                 } else if (*format == '%') {
5635                         if (*(format + 1) == '%') {
5636                                 trace_seq_putc(&s, '%');
5637                                 format++;
5638                                 ret++;
5639                         } else
5640                                 break;
5641                 } else
5642                         trace_seq_putc(&s, *format);
5643
5644                 ret++;
5645         }
5646         trace_seq_terminate(&s);
5647         parse_arg_add(parse, s.buffer, PRINT_FMT_STRING, NULL, NULL, 0);
5648         trace_seq_destroy(&s);
5649
5650         return ret;
5651 }
5652
5653 static struct tep_print_parse *
5654 parse_args(struct tep_event *event, const char *format, struct tep_print_arg *arg)
5655 {
5656         struct tep_print_parse *parse_ret = NULL;
5657         struct tep_print_parse **parse = NULL;
5658         int ret;
5659         int len;
5660
5661         len = strlen(format);
5662         while (*format) {
5663                 if (!parse_ret)
5664                         parse = &parse_ret;
5665                 if (*format == '%' && *(format + 1) != '%')
5666                         ret = parse_arg_format(parse, event, format, &arg);
5667                 else
5668                         ret = parse_arg_string(parse, format);
5669                 if (*parse)
5670                         parse = &((*parse)->next);
5671
5672                 len -= ret;
5673                 if (len > 0)
5674                         format += ret;
5675                 else
5676                         break;
5677         }
5678         return parse_ret;
5679 }
5680
5681 static void print_event_cache(struct tep_print_parse *parse, struct trace_seq *s,
5682                               void *data, int size, struct tep_event *event)
5683 {
5684         int len_arg;
5685
5686         while (parse) {
5687                 if (parse->len_as_arg)
5688                         len_arg = eval_num_arg(data, size, event, parse->len_as_arg);
5689                 switch (parse->type) {
5690                 case PRINT_FMT_ARG_DIGIT:
5691                         print_arg_number(s, parse->format,
5692                                         parse->len_as_arg ? len_arg : -1, data,
5693                                          size, parse->ls, event, parse->arg);
5694                         break;
5695                 case PRINT_FMT_ARG_POINTER:
5696                         print_arg_pointer(s, parse->format,
5697                                           parse->len_as_arg ? len_arg : 1,
5698                                           data, size, event, parse->arg);
5699                         break;
5700                 case PRINT_FMT_ARG_STRING:
5701                         print_arg_string(s, parse->format,
5702                                          parse->len_as_arg ? len_arg : -1,
5703                                          data, size, event, parse->arg);
5704                         break;
5705                 case PRINT_FMT_STRING:
5706                 default:
5707                         trace_seq_printf(s, "%s", parse->format);
5708                         break;
5709                 }
5710                 parse = parse->next;
5711         }
5712 }
5713
5714 static void pretty_print(struct trace_seq *s, void *data, int size, struct tep_event *event)
5715 {
5716         struct tep_print_parse *parse = event->print_fmt.print_cache;
5717         struct tep_print_arg *args = NULL;
5718         char *bprint_fmt = NULL;
5719
5720         if (event->flags & TEP_EVENT_FL_FAILED) {
5721                 trace_seq_printf(s, "[FAILED TO PARSE]");
5722                 tep_print_fields(s, data, size, event);
5723                 return;
5724         }
5725
5726         if (event->flags & TEP_EVENT_FL_ISBPRINT) {
5727                 bprint_fmt = get_bprint_format(data, size, event);
5728                 args = make_bprint_args(bprint_fmt, data, size, event);
5729                 parse = parse_args(event, bprint_fmt, args);
5730         }
5731
5732         print_event_cache(parse, s, data, size, event);
5733
5734         if (event->flags & TEP_EVENT_FL_ISBPRINT) {
5735                 free_parse_args(parse);
5736                 free_args(args);
5737                 free(bprint_fmt);
5738         }
5739 }
5740
5741 /*
5742  * This parses out the Latency format (interrupts disabled,
5743  * need rescheduling, in hard/soft interrupt, preempt count
5744  * and lock depth) and places it into the trace_seq.
5745  */
5746 static void data_latency_format(struct tep_handle *tep, struct trace_seq *s,
5747                                 char *format, struct tep_record *record)
5748 {
5749         static int check_lock_depth = 1;
5750         static int check_migrate_disable = 1;
5751         static int lock_depth_exists;
5752         static int migrate_disable_exists;
5753         unsigned int lat_flags;
5754         struct trace_seq sq;
5755         unsigned int pc;
5756         int lock_depth = 0;
5757         int migrate_disable = 0;
5758         int hardirq;
5759         int softirq;
5760         void *data = record->data;
5761
5762         trace_seq_init(&sq);
5763         lat_flags = parse_common_flags(tep, data);
5764         pc = parse_common_pc(tep, data);
5765         /* lock_depth may not always exist */
5766         if (lock_depth_exists)
5767                 lock_depth = parse_common_lock_depth(tep, data);
5768         else if (check_lock_depth) {
5769                 lock_depth = parse_common_lock_depth(tep, data);
5770                 if (lock_depth < 0)
5771                         check_lock_depth = 0;
5772                 else
5773                         lock_depth_exists = 1;
5774         }
5775
5776         /* migrate_disable may not always exist */
5777         if (migrate_disable_exists)
5778                 migrate_disable = parse_common_migrate_disable(tep, data);
5779         else if (check_migrate_disable) {
5780                 migrate_disable = parse_common_migrate_disable(tep, data);
5781                 if (migrate_disable < 0)
5782                         check_migrate_disable = 0;
5783                 else
5784                         migrate_disable_exists = 1;
5785         }
5786
5787         hardirq = lat_flags & TRACE_FLAG_HARDIRQ;
5788         softirq = lat_flags & TRACE_FLAG_SOFTIRQ;
5789
5790         trace_seq_printf(&sq, "%c%c%c",
5791                (lat_flags & TRACE_FLAG_IRQS_OFF) ? 'd' :
5792                (lat_flags & TRACE_FLAG_IRQS_NOSUPPORT) ?
5793                'X' : '.',
5794                (lat_flags & TRACE_FLAG_NEED_RESCHED) ?
5795                'N' : '.',
5796                (hardirq && softirq) ? 'H' :
5797                hardirq ? 'h' : softirq ? 's' : '.');
5798
5799         if (pc)
5800                 trace_seq_printf(&sq, "%x", pc);
5801         else
5802                 trace_seq_printf(&sq, ".");
5803
5804         if (migrate_disable_exists) {
5805                 if (migrate_disable < 0)
5806                         trace_seq_printf(&sq, ".");
5807                 else
5808                         trace_seq_printf(&sq, "%d", migrate_disable);
5809         }
5810
5811         if (lock_depth_exists) {
5812                 if (lock_depth < 0)
5813                         trace_seq_printf(&sq, ".");
5814                 else
5815                         trace_seq_printf(&sq, "%d", lock_depth);
5816         }
5817
5818         if (sq.state == TRACE_SEQ__MEM_ALLOC_FAILED) {
5819                 s->state = TRACE_SEQ__MEM_ALLOC_FAILED;
5820                 return;
5821         }
5822
5823         trace_seq_terminate(&sq);
5824         trace_seq_puts(s, sq.buffer);
5825         trace_seq_destroy(&sq);
5826         trace_seq_terminate(s);
5827 }
5828
5829 /**
5830  * tep_data_type - parse out the given event type
5831  * @tep: a handle to the trace event parser context
5832  * @rec: the record to read from
5833  *
5834  * This returns the event id from the @rec.
5835  */
5836 int tep_data_type(struct tep_handle *tep, struct tep_record *rec)
5837 {
5838         return trace_parse_common_type(tep, rec->data);
5839 }
5840
5841 /**
5842  * tep_data_pid - parse the PID from record
5843  * @tep: a handle to the trace event parser context
5844  * @rec: the record to parse
5845  *
5846  * This returns the PID from a record.
5847  */
5848 int tep_data_pid(struct tep_handle *tep, struct tep_record *rec)
5849 {
5850         return parse_common_pid(tep, rec->data);
5851 }
5852
5853 /**
5854  * tep_data_preempt_count - parse the preempt count from the record
5855  * @tep: a handle to the trace event parser context
5856  * @rec: the record to parse
5857  *
5858  * This returns the preempt count from a record.
5859  */
5860 int tep_data_preempt_count(struct tep_handle *tep, struct tep_record *rec)
5861 {
5862         return parse_common_pc(tep, rec->data);
5863 }
5864
5865 /**
5866  * tep_data_flags - parse the latency flags from the record
5867  * @tep: a handle to the trace event parser context
5868  * @rec: the record to parse
5869  *
5870  * This returns the latency flags from a record.
5871  *
5872  *  Use trace_flag_type enum for the flags (see event-parse.h).
5873  */
5874 int tep_data_flags(struct tep_handle *tep, struct tep_record *rec)
5875 {
5876         return parse_common_flags(tep, rec->data);
5877 }
5878
5879 /**
5880  * tep_data_comm_from_pid - return the command line from PID
5881  * @tep: a handle to the trace event parser context
5882  * @pid: the PID of the task to search for
5883  *
5884  * This returns a pointer to the command line that has the given
5885  * @pid.
5886  */
5887 const char *tep_data_comm_from_pid(struct tep_handle *tep, int pid)
5888 {
5889         const char *comm;
5890
5891         comm = find_cmdline(tep, pid);
5892         return comm;
5893 }
5894
5895 static struct tep_cmdline *
5896 pid_from_cmdlist(struct tep_handle *tep, const char *comm, struct tep_cmdline *next)
5897 {
5898         struct cmdline_list *cmdlist = (struct cmdline_list *)next;
5899
5900         if (cmdlist)
5901                 cmdlist = cmdlist->next;
5902         else
5903                 cmdlist = tep->cmdlist;
5904
5905         while (cmdlist && strcmp(cmdlist->comm, comm) != 0)
5906                 cmdlist = cmdlist->next;
5907
5908         return (struct tep_cmdline *)cmdlist;
5909 }
5910
5911 /**
5912  * tep_data_pid_from_comm - return the pid from a given comm
5913  * @tep: a handle to the trace event parser context
5914  * @comm: the cmdline to find the pid from
5915  * @next: the cmdline structure to find the next comm
5916  *
5917  * This returns the cmdline structure that holds a pid for a given
5918  * comm, or NULL if none found. As there may be more than one pid for
5919  * a given comm, the result of this call can be passed back into
5920  * a recurring call in the @next parameter, and then it will find the
5921  * next pid.
5922  * Also, it does a linear search, so it may be slow.
5923  */
5924 struct tep_cmdline *tep_data_pid_from_comm(struct tep_handle *tep, const char *comm,
5925                                            struct tep_cmdline *next)
5926 {
5927         struct tep_cmdline *cmdline;
5928
5929         /*
5930          * If the cmdlines have not been converted yet, then use
5931          * the list.
5932          */
5933         if (!tep->cmdlines)
5934                 return pid_from_cmdlist(tep, comm, next);
5935
5936         if (next) {
5937                 /*
5938                  * The next pointer could have been still from
5939                  * a previous call before cmdlines were created
5940                  */
5941                 if (next < tep->cmdlines ||
5942                     next >= tep->cmdlines + tep->cmdline_count)
5943                         next = NULL;
5944                 else
5945                         cmdline  = next++;
5946         }
5947
5948         if (!next)
5949                 cmdline = tep->cmdlines;
5950
5951         while (cmdline < tep->cmdlines + tep->cmdline_count) {
5952                 if (strcmp(cmdline->comm, comm) == 0)
5953                         return cmdline;
5954                 cmdline++;
5955         }
5956         return NULL;
5957 }
5958
5959 /**
5960  * tep_cmdline_pid - return the pid associated to a given cmdline
5961  * @tep: a handle to the trace event parser context
5962  * @cmdline: The cmdline structure to get the pid from
5963  *
5964  * Returns the pid for a give cmdline. If @cmdline is NULL, then
5965  * -1 is returned.
5966  */
5967 int tep_cmdline_pid(struct tep_handle *tep, struct tep_cmdline *cmdline)
5968 {
5969         struct cmdline_list *cmdlist = (struct cmdline_list *)cmdline;
5970
5971         if (!cmdline)
5972                 return -1;
5973
5974         /*
5975          * If cmdlines have not been created yet, or cmdline is
5976          * not part of the array, then treat it as a cmdlist instead.
5977          */
5978         if (!tep->cmdlines ||
5979             cmdline < tep->cmdlines ||
5980             cmdline >= tep->cmdlines + tep->cmdline_count)
5981                 return cmdlist->pid;
5982
5983         return cmdline->pid;
5984 }
5985
5986 /*
5987  * This parses the raw @data using the given @event information and
5988  * writes the print format into the trace_seq.
5989  */
5990 static void print_event_info(struct trace_seq *s, char *format, bool raw,
5991                              struct tep_event *event, struct tep_record *record)
5992 {
5993         int print_pretty = 1;
5994
5995         if (raw || (event->flags & TEP_EVENT_FL_PRINTRAW))
5996                 tep_print_fields(s, record->data, record->size, event);
5997         else {
5998
5999                 if (event->handler && !(event->flags & TEP_EVENT_FL_NOHANDLE))
6000                         print_pretty = event->handler(s, record, event,
6001                                                       event->context);
6002
6003                 if (print_pretty)
6004                         pretty_print(s, record->data, record->size, event);
6005         }
6006
6007         trace_seq_terminate(s);
6008 }
6009
6010 /**
6011  * tep_find_event_by_record - return the event from a given record
6012  * @tep: a handle to the trace event parser context
6013  * @record: The record to get the event from
6014  *
6015  * Returns the associated event for a given record, or NULL if non is
6016  * is found.
6017  */
6018 struct tep_event *
6019 tep_find_event_by_record(struct tep_handle *tep, struct tep_record *record)
6020 {
6021         int type;
6022
6023         if (record->size < 0) {
6024                 do_warning("ug! negative record size %d", record->size);
6025                 return NULL;
6026         }
6027
6028         type = trace_parse_common_type(tep, record->data);
6029
6030         return tep_find_event(tep, type);
6031 }
6032
6033 /*
6034  * Writes the timestamp of the record into @s. Time divisor and precision can be
6035  * specified as part of printf @format string. Example:
6036  *      "%3.1000d" - divide the time by 1000 and print the first 3 digits
6037  *      before the dot. Thus, the timestamp "123456000" will be printed as
6038  *      "123.456"
6039  */
6040 static void print_event_time(struct tep_handle *tep, struct trace_seq *s,
6041                                  char *format, struct tep_event *event,
6042                                  struct tep_record *record)
6043 {
6044         unsigned long long time;
6045         char *divstr;
6046         int prec = 0, pr;
6047         int div = 0;
6048         int p10 = 1;
6049
6050         if (isdigit(*(format + 1)))
6051                 prec = atoi(format + 1);
6052         divstr = strchr(format, '.');
6053         if (divstr && isdigit(*(divstr + 1)))
6054                 div = atoi(divstr + 1);
6055         time = record->ts;
6056         if (div) {
6057                 time += div / 2;
6058                 time /= div;
6059         }
6060         pr = prec;
6061         while (pr--)
6062                 p10 *= 10;
6063
6064         if (p10 > 1 && p10 < time)
6065                 trace_seq_printf(s, "%5llu.%0*llu", time / p10, prec, time % p10);
6066         else
6067                 trace_seq_printf(s, "%12llu", time);
6068 }
6069
6070 struct print_event_type {
6071         enum {
6072                 EVENT_TYPE_INT = 1,
6073                 EVENT_TYPE_STRING,
6074                 EVENT_TYPE_UNKNOWN,
6075         } type;
6076         char format[32];
6077 };
6078
6079 static void print_string(struct tep_handle *tep, struct trace_seq *s,
6080                          struct tep_record *record, struct tep_event *event,
6081                          const char *arg, struct print_event_type *type)
6082 {
6083         const char *comm;
6084         int pid;
6085
6086         if (strncmp(arg, TEP_PRINT_LATENCY, strlen(TEP_PRINT_LATENCY)) == 0) {
6087                 data_latency_format(tep, s, type->format, record);
6088         } else if (strncmp(arg, TEP_PRINT_COMM, strlen(TEP_PRINT_COMM)) == 0) {
6089                 pid = parse_common_pid(tep, record->data);
6090                 comm = find_cmdline(tep, pid);
6091                 trace_seq_printf(s, type->format, comm);
6092         } else if (strncmp(arg, TEP_PRINT_INFO_RAW, strlen(TEP_PRINT_INFO_RAW)) == 0) {
6093                 print_event_info(s, type->format, true, event, record);
6094         } else if (strncmp(arg, TEP_PRINT_INFO, strlen(TEP_PRINT_INFO)) == 0) {
6095                 print_event_info(s, type->format, false, event, record);
6096         } else if  (strncmp(arg, TEP_PRINT_NAME, strlen(TEP_PRINT_NAME)) == 0) {
6097                 trace_seq_printf(s, type->format, event->name);
6098         } else {
6099                 trace_seq_printf(s, "[UNKNOWN TEP TYPE %s]", arg);
6100         }
6101
6102 }
6103
6104 static void print_int(struct tep_handle *tep, struct trace_seq *s,
6105                       struct tep_record *record, struct tep_event *event,
6106                       int arg, struct print_event_type *type)
6107 {
6108         int param;
6109
6110         switch (arg) {
6111         case TEP_PRINT_CPU:
6112                 param = record->cpu;
6113                 break;
6114         case TEP_PRINT_PID:
6115                 param = parse_common_pid(tep, record->data);
6116                 break;
6117         case TEP_PRINT_TIME:
6118                 return print_event_time(tep, s, type->format, event, record);
6119         default:
6120                 return;
6121         }
6122         trace_seq_printf(s, type->format, param);
6123 }
6124
6125 static int tep_print_event_param_type(char *format,
6126                                       struct print_event_type *type)
6127 {
6128         char *str = format + 1;
6129         int i = 1;
6130
6131         type->type = EVENT_TYPE_UNKNOWN;
6132         while (*str) {
6133                 switch (*str) {
6134                 case 'd':
6135                 case 'u':
6136                 case 'i':
6137                 case 'x':
6138                 case 'X':
6139                 case 'o':
6140                         type->type = EVENT_TYPE_INT;
6141                         break;
6142                 case 's':
6143                         type->type = EVENT_TYPE_STRING;
6144                         break;
6145                 }
6146                 str++;
6147                 i++;
6148                 if (type->type != EVENT_TYPE_UNKNOWN)
6149                         break;
6150         }
6151         memset(type->format, 0, 32);
6152         memcpy(type->format, format, i < 32 ? i : 31);
6153         return i;
6154 }
6155
6156 /**
6157  * tep_print_event - Write various event information
6158  * @tep: a handle to the trace event parser context
6159  * @s: the trace_seq to write to
6160  * @record: The record to get the event from
6161  * @format: a printf format string. Supported event fileds:
6162  *      TEP_PRINT_PID, "%d" - event PID
6163  *      TEP_PRINT_CPU, "%d" - event CPU
6164  *      TEP_PRINT_COMM, "%s" - event command string
6165  *      TEP_PRINT_NAME, "%s" - event name
6166  *      TEP_PRINT_LATENCY, "%s" - event latency
6167  *      TEP_PRINT_TIME, %d - event time stamp. A divisor and precision
6168  *                      can be specified as part of this format string:
6169  *                      "%precision.divisord". Example:
6170  *                      "%3.1000d" - divide the time by 1000 and print the first
6171  *                      3 digits before the dot. Thus, the time stamp
6172  *                      "123456000" will be printed as "123.456"
6173  *      TEP_PRINT_INFO, "%s" - event information. If any width is specified in
6174  *                      the format string, the event information will be printed
6175  *                      in raw format.
6176  * Writes the specified event information into @s.
6177  */
6178 void tep_print_event(struct tep_handle *tep, struct trace_seq *s,
6179                      struct tep_record *record, const char *fmt, ...)
6180 {
6181         struct print_event_type type;
6182         char *format = strdup(fmt);
6183         char *current = format;
6184         char *str = format;
6185         int offset;
6186         va_list args;
6187         struct tep_event *event;
6188
6189         if (!format)
6190                 return;
6191
6192         event = tep_find_event_by_record(tep, record);
6193         va_start(args, fmt);
6194         while (*current) {
6195                 current = strchr(str, '%');
6196                 if (!current) {
6197                         trace_seq_puts(s, str);
6198                         break;
6199                 }
6200                 memset(&type, 0, sizeof(type));
6201                 offset = tep_print_event_param_type(current, &type);
6202                 *current = '\0';
6203                 trace_seq_puts(s, str);
6204                 current += offset;
6205                 switch (type.type) {
6206                 case EVENT_TYPE_STRING:
6207                         print_string(tep, s, record, event,
6208                                      va_arg(args, char*), &type);
6209                         break;
6210                 case EVENT_TYPE_INT:
6211                         print_int(tep, s, record, event,
6212                                   va_arg(args, int), &type);
6213                         break;
6214                 case EVENT_TYPE_UNKNOWN:
6215                 default:
6216                         trace_seq_printf(s, "[UNKNOWN TYPE]");
6217                         break;
6218                 }
6219                 str = current;
6220
6221         }
6222         va_end(args);
6223         free(format);
6224 }
6225
6226 static int events_id_cmp(const void *a, const void *b)
6227 {
6228         struct tep_event * const * ea = a;
6229         struct tep_event * const * eb = b;
6230
6231         if ((*ea)->id < (*eb)->id)
6232                 return -1;
6233
6234         if ((*ea)->id > (*eb)->id)
6235                 return 1;
6236
6237         return 0;
6238 }
6239
6240 static int events_name_cmp(const void *a, const void *b)
6241 {
6242         struct tep_event * const * ea = a;
6243         struct tep_event * const * eb = b;
6244         int res;
6245
6246         res = strcmp((*ea)->name, (*eb)->name);
6247         if (res)
6248                 return res;
6249
6250         res = strcmp((*ea)->system, (*eb)->system);
6251         if (res)
6252                 return res;
6253
6254         return events_id_cmp(a, b);
6255 }
6256
6257 static int events_system_cmp(const void *a, const void *b)
6258 {
6259         struct tep_event * const * ea = a;
6260         struct tep_event * const * eb = b;
6261         int res;
6262
6263         res = strcmp((*ea)->system, (*eb)->system);
6264         if (res)
6265                 return res;
6266
6267         res = strcmp((*ea)->name, (*eb)->name);
6268         if (res)
6269                 return res;
6270
6271         return events_id_cmp(a, b);
6272 }
6273
6274 static struct tep_event **list_events_copy(struct tep_handle *tep)
6275 {
6276         struct tep_event **events;
6277
6278         if (!tep)
6279                 return NULL;
6280
6281         events = malloc(sizeof(*events) * (tep->nr_events + 1));
6282         if (!events)
6283                 return NULL;
6284
6285         memcpy(events, tep->events, sizeof(*events) * tep->nr_events);
6286         events[tep->nr_events] = NULL;
6287         return events;
6288 }
6289
6290 static void list_events_sort(struct tep_event **events, int nr_events,
6291                              enum tep_event_sort_type sort_type)
6292 {
6293         int (*sort)(const void *a, const void *b);
6294
6295         switch (sort_type) {
6296         case TEP_EVENT_SORT_ID:
6297                 sort = events_id_cmp;
6298                 break;
6299         case TEP_EVENT_SORT_NAME:
6300                 sort = events_name_cmp;
6301                 break;
6302         case TEP_EVENT_SORT_SYSTEM:
6303                 sort = events_system_cmp;
6304                 break;
6305         default:
6306                 sort = NULL;
6307         }
6308
6309         if (sort)
6310                 qsort(events, nr_events, sizeof(*events), sort);
6311 }
6312
6313 /**
6314  * tep_list_events - Get events, sorted by given criteria.
6315  * @tep: a handle to the tep context
6316  * @sort_type: desired sort order of the events in the array
6317  *
6318  * Returns an array of pointers to all events, sorted by the given
6319  * @sort_type criteria. The last element of the array is NULL. The returned
6320  * memory must not be freed, it is managed by the library.
6321  * The function is not thread safe.
6322  */
6323 struct tep_event **tep_list_events(struct tep_handle *tep,
6324                                    enum tep_event_sort_type sort_type)
6325 {
6326         struct tep_event **events;
6327
6328         if (!tep)
6329                 return NULL;
6330
6331         events = tep->sort_events;
6332         if (events && tep->last_type == sort_type)
6333                 return events;
6334
6335         if (!events) {
6336                 events = list_events_copy(tep);
6337                 if (!events)
6338                         return NULL;
6339
6340                 tep->sort_events = events;
6341
6342                 /* the internal events are sorted by id */
6343                 if (sort_type == TEP_EVENT_SORT_ID) {
6344                         tep->last_type = sort_type;
6345                         return events;
6346                 }
6347         }
6348
6349         list_events_sort(events, tep->nr_events, sort_type);
6350         tep->last_type = sort_type;
6351
6352         return events;
6353 }
6354
6355
6356 /**
6357  * tep_list_events_copy - Thread safe version of tep_list_events()
6358  * @tep: a handle to the tep context
6359  * @sort_type: desired sort order of the events in the array
6360  *
6361  * Returns an array of pointers to all events, sorted by the given
6362  * @sort_type criteria. The last element of the array is NULL. The returned
6363  * array is newly allocated inside the function and must be freed by the caller
6364  */
6365 struct tep_event **tep_list_events_copy(struct tep_handle *tep,
6366                                         enum tep_event_sort_type sort_type)
6367 {
6368         struct tep_event **events;
6369
6370         if (!tep)
6371                 return NULL;
6372
6373         events = list_events_copy(tep);
6374         if (!events)
6375                 return NULL;
6376
6377         /* the internal events are sorted by id */
6378         if (sort_type == TEP_EVENT_SORT_ID)
6379                 return events;
6380
6381         list_events_sort(events, tep->nr_events, sort_type);
6382
6383         return events;
6384 }
6385
6386 static struct tep_format_field **
6387 get_event_fields(const char *type, const char *name,
6388                  int count, struct tep_format_field *list)
6389 {
6390         struct tep_format_field **fields;
6391         struct tep_format_field *field;
6392         int i = 0;
6393
6394         fields = malloc(sizeof(*fields) * (count + 1));
6395         if (!fields)
6396                 return NULL;
6397
6398         for (field = list; field; field = field->next) {
6399                 fields[i++] = field;
6400                 if (i == count + 1) {
6401                         do_warning("event %s has more %s fields than specified",
6402                                 name, type);
6403                         i--;
6404                         break;
6405                 }
6406         }
6407
6408         if (i != count)
6409                 do_warning("event %s has less %s fields than specified",
6410                         name, type);
6411
6412         fields[i] = NULL;
6413
6414         return fields;
6415 }
6416
6417 /**
6418  * tep_event_common_fields - return a list of common fields for an event
6419  * @event: the event to return the common fields of.
6420  *
6421  * Returns an allocated array of fields. The last item in the array is NULL.
6422  * The array must be freed with free().
6423  */
6424 struct tep_format_field **tep_event_common_fields(struct tep_event *event)
6425 {
6426         return get_event_fields("common", event->name,
6427                                 event->format.nr_common,
6428                                 event->format.common_fields);
6429 }
6430
6431 /**
6432  * tep_event_fields - return a list of event specific fields for an event
6433  * @event: the event to return the fields of.
6434  *
6435  * Returns an allocated array of fields. The last item in the array is NULL.
6436  * The array must be freed with free().
6437  */
6438 struct tep_format_field **tep_event_fields(struct tep_event *event)
6439 {
6440         return get_event_fields("event", event->name,
6441                                 event->format.nr_fields,
6442                                 event->format.fields);
6443 }
6444
6445 static void print_fields(struct trace_seq *s, struct tep_print_flag_sym *field)
6446 {
6447         trace_seq_printf(s, "{ %s, %s }", field->value, field->str);
6448         if (field->next) {
6449                 trace_seq_puts(s, ", ");
6450                 print_fields(s, field->next);
6451         }
6452 }
6453
6454 /* for debugging */
6455 static void print_args(struct tep_print_arg *args)
6456 {
6457         int print_paren = 1;
6458         struct trace_seq s;
6459
6460         switch (args->type) {
6461         case TEP_PRINT_NULL:
6462                 printf("null");
6463                 break;
6464         case TEP_PRINT_ATOM:
6465                 printf("%s", args->atom.atom);
6466                 break;
6467         case TEP_PRINT_FIELD:
6468                 printf("REC->%s", args->field.name);
6469                 break;
6470         case TEP_PRINT_FLAGS:
6471                 printf("__print_flags(");
6472                 print_args(args->flags.field);
6473                 printf(", %s, ", args->flags.delim);
6474                 trace_seq_init(&s);
6475                 print_fields(&s, args->flags.flags);
6476                 trace_seq_do_printf(&s);
6477                 trace_seq_destroy(&s);
6478                 printf(")");
6479                 break;
6480         case TEP_PRINT_SYMBOL:
6481                 printf("__print_symbolic(");
6482                 print_args(args->symbol.field);
6483                 printf(", ");
6484                 trace_seq_init(&s);
6485                 print_fields(&s, args->symbol.symbols);
6486                 trace_seq_do_printf(&s);
6487                 trace_seq_destroy(&s);
6488                 printf(")");
6489                 break;
6490         case TEP_PRINT_HEX:
6491                 printf("__print_hex(");
6492                 print_args(args->hex.field);
6493                 printf(", ");
6494                 print_args(args->hex.size);
6495                 printf(")");
6496                 break;
6497         case TEP_PRINT_HEX_STR:
6498                 printf("__print_hex_str(");
6499                 print_args(args->hex.field);
6500                 printf(", ");
6501                 print_args(args->hex.size);
6502                 printf(")");
6503                 break;
6504         case TEP_PRINT_INT_ARRAY:
6505                 printf("__print_array(");
6506                 print_args(args->int_array.field);
6507                 printf(", ");
6508                 print_args(args->int_array.count);
6509                 printf(", ");
6510                 print_args(args->int_array.el_size);
6511                 printf(")");
6512                 break;
6513         case TEP_PRINT_STRING:
6514         case TEP_PRINT_BSTRING:
6515                 printf("__get_str(%s)", args->string.string);
6516                 break;
6517         case TEP_PRINT_BITMASK:
6518                 printf("__get_bitmask(%s)", args->bitmask.bitmask);
6519                 break;
6520         case TEP_PRINT_TYPE:
6521                 printf("(%s)", args->typecast.type);
6522                 print_args(args->typecast.item);
6523                 break;
6524         case TEP_PRINT_OP:
6525                 if (strcmp(args->op.op, ":") == 0)
6526                         print_paren = 0;
6527                 if (print_paren)
6528                         printf("(");
6529                 print_args(args->op.left);
6530                 printf(" %s ", args->op.op);
6531                 print_args(args->op.right);
6532                 if (print_paren)
6533                         printf(")");
6534                 break;
6535         default:
6536                 /* we should warn... */
6537                 return;
6538         }
6539         if (args->next) {
6540                 printf("\n");
6541                 print_args(args->next);
6542         }
6543 }
6544
6545 static void parse_header_field(const char *field,
6546                                int *offset, int *size, int mandatory)
6547 {
6548         unsigned long long save_input_buf_ptr;
6549         unsigned long long save_input_buf_siz;
6550         char *token;
6551         int type;
6552
6553         save_input_buf_ptr = input_buf_ptr;
6554         save_input_buf_siz = input_buf_siz;
6555
6556         if (read_expected(TEP_EVENT_ITEM, "field") < 0)
6557                 return;
6558         if (read_expected(TEP_EVENT_OP, ":") < 0)
6559                 return;
6560
6561         /* type */
6562         if (read_expect_type(TEP_EVENT_ITEM, &token) < 0)
6563                 goto fail;
6564         free_token(token);
6565
6566         /*
6567          * If this is not a mandatory field, then test it first.
6568          */
6569         if (mandatory) {
6570                 if (read_expected(TEP_EVENT_ITEM, field) < 0)
6571                         return;
6572         } else {
6573                 if (read_expect_type(TEP_EVENT_ITEM, &token) < 0)
6574                         goto fail;
6575                 if (strcmp(token, field) != 0)
6576                         goto discard;
6577                 free_token(token);
6578         }
6579
6580         if (read_expected(TEP_EVENT_OP, ";") < 0)
6581                 return;
6582         if (read_expected(TEP_EVENT_ITEM, "offset") < 0)
6583                 return;
6584         if (read_expected(TEP_EVENT_OP, ":") < 0)
6585                 return;
6586         if (read_expect_type(TEP_EVENT_ITEM, &token) < 0)
6587                 goto fail;
6588         *offset = atoi(token);
6589         free_token(token);
6590         if (read_expected(TEP_EVENT_OP, ";") < 0)
6591                 return;
6592         if (read_expected(TEP_EVENT_ITEM, "size") < 0)
6593                 return;
6594         if (read_expected(TEP_EVENT_OP, ":") < 0)
6595                 return;
6596         if (read_expect_type(TEP_EVENT_ITEM, &token) < 0)
6597                 goto fail;
6598         *size = atoi(token);
6599         free_token(token);
6600         if (read_expected(TEP_EVENT_OP, ";") < 0)
6601                 return;
6602         type = read_token(&token);
6603         if (type != TEP_EVENT_NEWLINE) {
6604                 /* newer versions of the kernel have a "signed" type */
6605                 if (type != TEP_EVENT_ITEM)
6606                         goto fail;
6607
6608                 if (strcmp(token, "signed") != 0)
6609                         goto fail;
6610
6611                 free_token(token);
6612
6613                 if (read_expected(TEP_EVENT_OP, ":") < 0)
6614                         return;
6615
6616                 if (read_expect_type(TEP_EVENT_ITEM, &token))
6617                         goto fail;
6618
6619                 free_token(token);
6620                 if (read_expected(TEP_EVENT_OP, ";") < 0)
6621                         return;
6622
6623                 if (read_expect_type(TEP_EVENT_NEWLINE, &token))
6624                         goto fail;
6625         }
6626  fail:
6627         free_token(token);
6628         return;
6629
6630  discard:
6631         input_buf_ptr = save_input_buf_ptr;
6632         input_buf_siz = save_input_buf_siz;
6633         *offset = 0;
6634         *size = 0;
6635         free_token(token);
6636 }
6637
6638 /**
6639  * tep_parse_header_page - parse the data stored in the header page
6640  * @tep: a handle to the trace event parser context
6641  * @buf: the buffer storing the header page format string
6642  * @size: the size of @buf
6643  * @long_size: the long size to use if there is no header
6644  *
6645  * This parses the header page format for information on the
6646  * ring buffer used. The @buf should be copied from
6647  *
6648  * /sys/kernel/debug/tracing/events/header_page
6649  */
6650 int tep_parse_header_page(struct tep_handle *tep, char *buf, unsigned long size,
6651                           int long_size)
6652 {
6653         int ignore;
6654
6655         if (!size) {
6656                 /*
6657                  * Old kernels did not have header page info.
6658                  * Sorry but we just use what we find here in user space.
6659                  */
6660                 tep->header_page_ts_size = sizeof(long long);
6661                 tep->header_page_size_size = long_size;
6662                 tep->header_page_data_offset = sizeof(long long) + long_size;
6663                 tep->old_format = 1;
6664                 return -1;
6665         }
6666         init_input_buf(buf, size);
6667
6668         parse_header_field("timestamp", &tep->header_page_ts_offset,
6669                            &tep->header_page_ts_size, 1);
6670         parse_header_field("commit", &tep->header_page_size_offset,
6671                            &tep->header_page_size_size, 1);
6672         parse_header_field("overwrite", &tep->header_page_overwrite,
6673                            &ignore, 0);
6674         parse_header_field("data", &tep->header_page_data_offset,
6675                            &tep->header_page_data_size, 1);
6676
6677         return 0;
6678 }
6679
6680 static int event_matches(struct tep_event *event,
6681                          int id, const char *sys_name,
6682                          const char *event_name)
6683 {
6684         if (id >= 0 && id != event->id)
6685                 return 0;
6686
6687         if (event_name && (strcmp(event_name, event->name) != 0))
6688                 return 0;
6689
6690         if (sys_name && (strcmp(sys_name, event->system) != 0))
6691                 return 0;
6692
6693         return 1;
6694 }
6695
6696 static void free_handler(struct event_handler *handle)
6697 {
6698         free((void *)handle->sys_name);
6699         free((void *)handle->event_name);
6700         free(handle);
6701 }
6702
6703 static int find_event_handle(struct tep_handle *tep, struct tep_event *event)
6704 {
6705         struct event_handler *handle, **next;
6706
6707         for (next = &tep->handlers; *next;
6708              next = &(*next)->next) {
6709                 handle = *next;
6710                 if (event_matches(event, handle->id,
6711                                   handle->sys_name,
6712                                   handle->event_name))
6713                         break;
6714         }
6715
6716         if (!(*next))
6717                 return 0;
6718
6719         pr_stat("overriding event (%d) %s:%s with new print handler",
6720                 event->id, event->system, event->name);
6721
6722         event->handler = handle->func;
6723         event->context = handle->context;
6724
6725         *next = handle->next;
6726         free_handler(handle);
6727
6728         return 1;
6729 }
6730
6731 /**
6732  * parse_format - parse the event format
6733  * @buf: the buffer storing the event format string
6734  * @size: the size of @buf
6735  * @sys: the system the event belongs to
6736  *
6737  * This parses the event format and creates an event structure
6738  * to quickly parse raw data for a given event.
6739  *
6740  * These files currently come from:
6741  *
6742  * /sys/kernel/debug/tracing/events/.../.../format
6743  */
6744 static enum tep_errno parse_format(struct tep_event **eventp,
6745                                    struct tep_handle *tep, const char *buf,
6746                                    unsigned long size, const char *sys)
6747 {
6748         struct tep_event *event;
6749         int ret;
6750
6751         init_input_buf(buf, size);
6752
6753         *eventp = event = alloc_event();
6754         if (!event)
6755                 return TEP_ERRNO__MEM_ALLOC_FAILED;
6756
6757         event->name = event_read_name();
6758         if (!event->name) {
6759                 /* Bad event? */
6760                 ret = TEP_ERRNO__MEM_ALLOC_FAILED;
6761                 goto event_alloc_failed;
6762         }
6763
6764         if (strcmp(sys, "ftrace") == 0) {
6765                 event->flags |= TEP_EVENT_FL_ISFTRACE;
6766
6767                 if (strcmp(event->name, "bprint") == 0)
6768                         event->flags |= TEP_EVENT_FL_ISBPRINT;
6769         }
6770                 
6771         event->id = event_read_id();
6772         if (event->id < 0) {
6773                 ret = TEP_ERRNO__READ_ID_FAILED;
6774                 /*
6775                  * This isn't an allocation error actually.
6776                  * But as the ID is critical, just bail out.
6777                  */
6778                 goto event_alloc_failed;
6779         }
6780
6781         event->system = strdup(sys);
6782         if (!event->system) {
6783                 ret = TEP_ERRNO__MEM_ALLOC_FAILED;
6784                 goto event_alloc_failed;
6785         }
6786
6787         /* Add tep to event so that it can be referenced */
6788         event->tep = tep;
6789
6790         ret = event_read_format(event);
6791         if (ret < 0) {
6792                 ret = TEP_ERRNO__READ_FORMAT_FAILED;
6793                 goto event_parse_failed;
6794         }
6795
6796         /*
6797          * If the event has an override, don't print warnings if the event
6798          * print format fails to parse.
6799          */
6800         if (tep && find_event_handle(tep, event))
6801                 show_warning = 0;
6802
6803         ret = event_read_print(event);
6804         show_warning = 1;
6805
6806         if (ret < 0) {
6807                 ret = TEP_ERRNO__READ_PRINT_FAILED;
6808                 goto event_parse_failed;
6809         }
6810
6811         if (!ret && (event->flags & TEP_EVENT_FL_ISFTRACE)) {
6812                 struct tep_format_field *field;
6813                 struct tep_print_arg *arg, **list;
6814
6815                 /* old ftrace had no args */
6816                 list = &event->print_fmt.args;
6817                 for (field = event->format.fields; field; field = field->next) {
6818                         arg = alloc_arg();
6819                         if (!arg) {
6820                                 event->flags |= TEP_EVENT_FL_FAILED;
6821                                 return TEP_ERRNO__OLD_FTRACE_ARG_FAILED;
6822                         }
6823                         arg->type = TEP_PRINT_FIELD;
6824                         arg->field.name = strdup(field->name);
6825                         if (!arg->field.name) {
6826                                 event->flags |= TEP_EVENT_FL_FAILED;
6827                                 free_arg(arg);
6828                                 return TEP_ERRNO__OLD_FTRACE_ARG_FAILED;
6829                         }
6830                         arg->field.field = field;
6831                         *list = arg;
6832                         list = &arg->next;
6833                 }
6834         }
6835
6836         if (!(event->flags & TEP_EVENT_FL_ISBPRINT))
6837                 event->print_fmt.print_cache = parse_args(event,
6838                                                           event->print_fmt.format,
6839                                                           event->print_fmt.args);
6840
6841         return 0;
6842
6843  event_parse_failed:
6844         event->flags |= TEP_EVENT_FL_FAILED;
6845         return ret;
6846
6847  event_alloc_failed:
6848         free(event->system);
6849         free(event->name);
6850         free(event);
6851         *eventp = NULL;
6852         return ret;
6853 }
6854
6855 static enum tep_errno
6856 __parse_event(struct tep_handle *tep,
6857               struct tep_event **eventp,
6858               const char *buf, unsigned long size,
6859               const char *sys)
6860 {
6861         int ret = parse_format(eventp, tep, buf, size, sys);
6862         struct tep_event *event = *eventp;
6863
6864         if (event == NULL)
6865                 return ret;
6866
6867         if (tep && add_event(tep, event)) {
6868                 ret = TEP_ERRNO__MEM_ALLOC_FAILED;
6869                 goto event_add_failed;
6870         }
6871
6872 #define PRINT_ARGS 0
6873         if (PRINT_ARGS && event->print_fmt.args)
6874                 print_args(event->print_fmt.args);
6875
6876         return 0;
6877
6878 event_add_failed:
6879         free_tep_event(event);
6880         return ret;
6881 }
6882
6883 /**
6884  * tep_parse_format - parse the event format
6885  * @tep: a handle to the trace event parser context
6886  * @eventp: returned format
6887  * @buf: the buffer storing the event format string
6888  * @size: the size of @buf
6889  * @sys: the system the event belongs to
6890  *
6891  * This parses the event format and creates an event structure
6892  * to quickly parse raw data for a given event.
6893  *
6894  * These files currently come from:
6895  *
6896  * /sys/kernel/debug/tracing/events/.../.../format
6897  */
6898 enum tep_errno tep_parse_format(struct tep_handle *tep,
6899                                 struct tep_event **eventp,
6900                                 const char *buf,
6901                                 unsigned long size, const char *sys)
6902 {
6903         return __parse_event(tep, eventp, buf, size, sys);
6904 }
6905
6906 /**
6907  * tep_parse_event - parse the event format
6908  * @tep: a handle to the trace event parser context
6909  * @buf: the buffer storing the event format string
6910  * @size: the size of @buf
6911  * @sys: the system the event belongs to
6912  *
6913  * This parses the event format and creates an event structure
6914  * to quickly parse raw data for a given event.
6915  *
6916  * These files currently come from:
6917  *
6918  * /sys/kernel/debug/tracing/events/.../.../format
6919  */
6920 enum tep_errno tep_parse_event(struct tep_handle *tep, const char *buf,
6921                                unsigned long size, const char *sys)
6922 {
6923         struct tep_event *event = NULL;
6924         return __parse_event(tep, &event, buf, size, sys);
6925 }
6926
6927 int get_field_val(struct trace_seq *s, struct tep_format_field *field,
6928                   const char *name, struct tep_record *record,
6929                   unsigned long long *val, int err)
6930 {
6931         if (!field) {
6932                 if (err)
6933                         trace_seq_printf(s, "<CANT FIND FIELD %s>", name);
6934                 return -1;
6935         }
6936
6937         if (tep_read_number_field(field, record->data, val)) {
6938                 if (err)
6939                         trace_seq_printf(s, " %s=INVALID", name);
6940                 return -1;
6941         }
6942
6943         return 0;
6944 }
6945
6946 /**
6947  * tep_get_field_raw - return the raw pointer into the data field
6948  * @s: The seq to print to on error
6949  * @event: the event that the field is for
6950  * @name: The name of the field
6951  * @record: The record with the field name.
6952  * @len: place to store the field length.
6953  * @err: print default error if failed.
6954  *
6955  * Returns a pointer into record->data of the field and places
6956  * the length of the field in @len.
6957  *
6958  * On failure, it returns NULL.
6959  */
6960 void *tep_get_field_raw(struct trace_seq *s, struct tep_event *event,
6961                         const char *name, struct tep_record *record,
6962                         int *len, int err)
6963 {
6964         struct tep_format_field *field;
6965         void *data = record->data;
6966         unsigned offset;
6967         int dummy;
6968
6969         if (!event)
6970                 return NULL;
6971
6972         field = tep_find_field(event, name);
6973
6974         if (!field) {
6975                 if (err)
6976                         trace_seq_printf(s, "<CANT FIND FIELD %s>", name);
6977                 return NULL;
6978         }
6979
6980         /* Allow @len to be NULL */
6981         if (!len)
6982                 len = &dummy;
6983
6984         offset = field->offset;
6985         if (field->flags & TEP_FIELD_IS_DYNAMIC) {
6986                 offset = tep_read_number(event->tep,
6987                                          data + offset, field->size);
6988                 *len = offset >> 16;
6989                 offset &= 0xffff;
6990         } else
6991                 *len = field->size;
6992
6993         return data + offset;
6994 }
6995
6996 /**
6997  * tep_get_field_val - find a field and return its value
6998  * @s: The seq to print to on error
6999  * @event: the event that the field is for
7000  * @name: The name of the field
7001  * @record: The record with the field name.
7002  * @val: place to store the value of the field.
7003  * @err: print default error if failed.
7004  *
7005  * Returns 0 on success -1 on field not found.
7006  */
7007 int tep_get_field_val(struct trace_seq *s, struct tep_event *event,
7008                       const char *name, struct tep_record *record,
7009                       unsigned long long *val, int err)
7010 {
7011         struct tep_format_field *field;
7012
7013         if (!event)
7014                 return -1;
7015
7016         field = tep_find_field(event, name);
7017
7018         return get_field_val(s, field, name, record, val, err);
7019 }
7020
7021 /**
7022  * tep_get_common_field_val - find a common field and return its value
7023  * @s: The seq to print to on error
7024  * @event: the event that the field is for
7025  * @name: The name of the field
7026  * @record: The record with the field name.
7027  * @val: place to store the value of the field.
7028  * @err: print default error if failed.
7029  *
7030  * Returns 0 on success -1 on field not found.
7031  */
7032 int tep_get_common_field_val(struct trace_seq *s, struct tep_event *event,
7033                              const char *name, struct tep_record *record,
7034                              unsigned long long *val, int err)
7035 {
7036         struct tep_format_field *field;
7037
7038         if (!event)
7039                 return -1;
7040
7041         field = tep_find_common_field(event, name);
7042
7043         return get_field_val(s, field, name, record, val, err);
7044 }
7045
7046 /**
7047  * tep_get_any_field_val - find a any field and return its value
7048  * @s: The seq to print to on error
7049  * @event: the event that the field is for
7050  * @name: The name of the field
7051  * @record: The record with the field name.
7052  * @val: place to store the value of the field.
7053  * @err: print default error if failed.
7054  *
7055  * Returns 0 on success -1 on field not found.
7056  */
7057 int tep_get_any_field_val(struct trace_seq *s, struct tep_event *event,
7058                           const char *name, struct tep_record *record,
7059                           unsigned long long *val, int err)
7060 {
7061         struct tep_format_field *field;
7062
7063         if (!event)
7064                 return -1;
7065
7066         field = tep_find_any_field(event, name);
7067
7068         return get_field_val(s, field, name, record, val, err);
7069 }
7070
7071 /**
7072  * tep_print_num_field - print a field and a format
7073  * @s: The seq to print to
7074  * @fmt: The printf format to print the field with.
7075  * @event: the event that the field is for
7076  * @name: The name of the field
7077  * @record: The record with the field name.
7078  * @err: print default error if failed.
7079  *
7080  * Returns positive value on success, negative in case of an error,
7081  * or 0 if buffer is full.
7082  */
7083 int tep_print_num_field(struct trace_seq *s, const char *fmt,
7084                         struct tep_event *event, const char *name,
7085                         struct tep_record *record, int err)
7086 {
7087         struct tep_format_field *field = tep_find_field(event, name);
7088         unsigned long long val;
7089
7090         if (!field)
7091                 goto failed;
7092
7093         if (tep_read_number_field(field, record->data, &val))
7094                 goto failed;
7095
7096         return trace_seq_printf(s, fmt, val);
7097
7098  failed:
7099         if (err)
7100                 trace_seq_printf(s, "CAN'T FIND FIELD \"%s\"", name);
7101         return -1;
7102 }
7103
7104 /**
7105  * tep_print_func_field - print a field and a format for function pointers
7106  * @s: The seq to print to
7107  * @fmt: The printf format to print the field with.
7108  * @event: the event that the field is for
7109  * @name: The name of the field
7110  * @record: The record with the field name.
7111  * @err: print default error if failed.
7112  *
7113  * Returns positive value on success, negative in case of an error,
7114  * or 0 if buffer is full.
7115  */
7116 int tep_print_func_field(struct trace_seq *s, const char *fmt,
7117                          struct tep_event *event, const char *name,
7118                          struct tep_record *record, int err)
7119 {
7120         struct tep_format_field *field = tep_find_field(event, name);
7121         struct tep_handle *tep = event->tep;
7122         unsigned long long val;
7123         struct func_map *func;
7124         char tmp[128];
7125
7126         if (!field)
7127                 goto failed;
7128
7129         if (tep_read_number_field(field, record->data, &val))
7130                 goto failed;
7131
7132         func = find_func(tep, val);
7133
7134         if (func)
7135                 snprintf(tmp, 128, "%s/0x%llx", func->func, func->addr - val);
7136         else
7137                 sprintf(tmp, "0x%08llx", val);
7138
7139         return trace_seq_printf(s, fmt, tmp);
7140
7141  failed:
7142         if (err)
7143                 trace_seq_printf(s, "CAN'T FIND FIELD \"%s\"", name);
7144         return -1;
7145 }
7146
7147 static void free_func_handle(struct tep_function_handler *func)
7148 {
7149         struct func_params *params;
7150
7151         free(func->name);
7152
7153         while (func->params) {
7154                 params = func->params;
7155                 func->params = params->next;
7156                 free(params);
7157         }
7158
7159         free(func);
7160 }
7161
7162 /**
7163  * tep_register_print_function - register a helper function
7164  * @tep: a handle to the trace event parser context
7165  * @func: the function to process the helper function
7166  * @ret_type: the return type of the helper function
7167  * @name: the name of the helper function
7168  * @parameters: A list of enum tep_func_arg_type
7169  *
7170  * Some events may have helper functions in the print format arguments.
7171  * This allows a plugin to dynamically create a way to process one
7172  * of these functions.
7173  *
7174  * The @parameters is a variable list of tep_func_arg_type enums that
7175  * must end with TEP_FUNC_ARG_VOID.
7176  */
7177 int tep_register_print_function(struct tep_handle *tep,
7178                                 tep_func_handler func,
7179                                 enum tep_func_arg_type ret_type,
7180                                 char *name, ...)
7181 {
7182         struct tep_function_handler *func_handle;
7183         struct func_params **next_param;
7184         struct func_params *param;
7185         enum tep_func_arg_type type;
7186         va_list ap;
7187         int ret;
7188
7189         func_handle = find_func_handler(tep, name);
7190         if (func_handle) {
7191                 /*
7192                  * This is most like caused by the users own
7193                  * plugins updating the function. This overrides the
7194                  * system defaults.
7195                  */
7196                 pr_stat("override of function helper '%s'", name);
7197                 remove_func_handler(tep, name);
7198         }
7199
7200         func_handle = calloc(1, sizeof(*func_handle));
7201         if (!func_handle) {
7202                 do_warning("Failed to allocate function handler");
7203                 return TEP_ERRNO__MEM_ALLOC_FAILED;
7204         }
7205
7206         func_handle->ret_type = ret_type;
7207         func_handle->name = strdup(name);
7208         func_handle->func = func;
7209         if (!func_handle->name) {
7210                 do_warning("Failed to allocate function name");
7211                 free(func_handle);
7212                 return TEP_ERRNO__MEM_ALLOC_FAILED;
7213         }
7214
7215         next_param = &(func_handle->params);
7216         va_start(ap, name);
7217         for (;;) {
7218                 type = va_arg(ap, enum tep_func_arg_type);
7219                 if (type == TEP_FUNC_ARG_VOID)
7220                         break;
7221
7222                 if (type >= TEP_FUNC_ARG_MAX_TYPES) {
7223                         do_warning("Invalid argument type %d", type);
7224                         ret = TEP_ERRNO__INVALID_ARG_TYPE;
7225                         goto out_free;
7226                 }
7227
7228                 param = malloc(sizeof(*param));
7229                 if (!param) {
7230                         do_warning("Failed to allocate function param");
7231                         ret = TEP_ERRNO__MEM_ALLOC_FAILED;
7232                         goto out_free;
7233                 }
7234                 param->type = type;
7235                 param->next = NULL;
7236
7237                 *next_param = param;
7238                 next_param = &(param->next);
7239
7240                 func_handle->nr_args++;
7241         }
7242         va_end(ap);
7243
7244         func_handle->next = tep->func_handlers;
7245         tep->func_handlers = func_handle;
7246
7247         return 0;
7248  out_free:
7249         va_end(ap);
7250         free_func_handle(func_handle);
7251         return ret;
7252 }
7253
7254 /**
7255  * tep_unregister_print_function - unregister a helper function
7256  * @tep: a handle to the trace event parser context
7257  * @func: the function to process the helper function
7258  * @name: the name of the helper function
7259  *
7260  * This function removes existing print handler for function @name.
7261  *
7262  * Returns 0 if the handler was removed successully, -1 otherwise.
7263  */
7264 int tep_unregister_print_function(struct tep_handle *tep,
7265                                   tep_func_handler func, char *name)
7266 {
7267         struct tep_function_handler *func_handle;
7268
7269         func_handle = find_func_handler(tep, name);
7270         if (func_handle && func_handle->func == func) {
7271                 remove_func_handler(tep, name);
7272                 return 0;
7273         }
7274         return -1;
7275 }
7276
7277 static struct tep_event *search_event(struct tep_handle *tep, int id,
7278                                       const char *sys_name,
7279                                       const char *event_name)
7280 {
7281         struct tep_event *event;
7282
7283         if (id >= 0) {
7284                 /* search by id */
7285                 event = tep_find_event(tep, id);
7286                 if (!event)
7287                         return NULL;
7288                 if (event_name && (strcmp(event_name, event->name) != 0))
7289                         return NULL;
7290                 if (sys_name && (strcmp(sys_name, event->system) != 0))
7291                         return NULL;
7292         } else {
7293                 event = tep_find_event_by_name(tep, sys_name, event_name);
7294                 if (!event)
7295                         return NULL;
7296         }
7297         return event;
7298 }
7299
7300 /**
7301  * tep_register_event_handler - register a way to parse an event
7302  * @tep: a handle to the trace event parser context
7303  * @id: the id of the event to register
7304  * @sys_name: the system name the event belongs to
7305  * @event_name: the name of the event
7306  * @func: the function to call to parse the event information
7307  * @context: the data to be passed to @func
7308  *
7309  * This function allows a developer to override the parsing of
7310  * a given event. If for some reason the default print format
7311  * is not sufficient, this function will register a function
7312  * for an event to be used to parse the data instead.
7313  *
7314  * If @id is >= 0, then it is used to find the event.
7315  * else @sys_name and @event_name are used.
7316  *
7317  * Returns:
7318  *  TEP_REGISTER_SUCCESS_OVERWRITE if an existing handler is overwritten
7319  *  TEP_REGISTER_SUCCESS if a new handler is registered successfully
7320  *  negative TEP_ERRNO_... in case of an error
7321  *
7322  */
7323 int tep_register_event_handler(struct tep_handle *tep, int id,
7324                                const char *sys_name, const char *event_name,
7325                                tep_event_handler_func func, void *context)
7326 {
7327         struct tep_event *event;
7328         struct event_handler *handle;
7329
7330         event = search_event(tep, id, sys_name, event_name);
7331         if (event == NULL)
7332                 goto not_found;
7333
7334         pr_stat("overriding event (%d) %s:%s with new print handler",
7335                 event->id, event->system, event->name);
7336
7337         event->handler = func;
7338         event->context = context;
7339         return TEP_REGISTER_SUCCESS_OVERWRITE;
7340
7341  not_found:
7342         /* Save for later use. */
7343         handle = calloc(1, sizeof(*handle));
7344         if (!handle) {
7345                 do_warning("Failed to allocate event handler");
7346                 return TEP_ERRNO__MEM_ALLOC_FAILED;
7347         }
7348
7349         handle->id = id;
7350         if (event_name)
7351                 handle->event_name = strdup(event_name);
7352         if (sys_name)
7353                 handle->sys_name = strdup(sys_name);
7354
7355         if ((event_name && !handle->event_name) ||
7356             (sys_name && !handle->sys_name)) {
7357                 do_warning("Failed to allocate event/sys name");
7358                 free((void *)handle->event_name);
7359                 free((void *)handle->sys_name);
7360                 free(handle);
7361                 return TEP_ERRNO__MEM_ALLOC_FAILED;
7362         }
7363
7364         handle->func = func;
7365         handle->next = tep->handlers;
7366         tep->handlers = handle;
7367         handle->context = context;
7368
7369         return TEP_REGISTER_SUCCESS;
7370 }
7371
7372 static int handle_matches(struct event_handler *handler, int id,
7373                           const char *sys_name, const char *event_name,
7374                           tep_event_handler_func func, void *context)
7375 {
7376         if (id >= 0 && id != handler->id)
7377                 return 0;
7378
7379         if (event_name && (strcmp(event_name, handler->event_name) != 0))
7380                 return 0;
7381
7382         if (sys_name && (strcmp(sys_name, handler->sys_name) != 0))
7383                 return 0;
7384
7385         if (func != handler->func || context != handler->context)
7386                 return 0;
7387
7388         return 1;
7389 }
7390
7391 /**
7392  * tep_unregister_event_handler - unregister an existing event handler
7393  * @tep: a handle to the trace event parser context
7394  * @id: the id of the event to unregister
7395  * @sys_name: the system name the handler belongs to
7396  * @event_name: the name of the event handler
7397  * @func: the function to call to parse the event information
7398  * @context: the data to be passed to @func
7399  *
7400  * This function removes existing event handler (parser).
7401  *
7402  * If @id is >= 0, then it is used to find the event.
7403  * else @sys_name and @event_name are used.
7404  *
7405  * Returns 0 if handler was removed successfully, -1 if event was not found.
7406  */
7407 int tep_unregister_event_handler(struct tep_handle *tep, int id,
7408                                  const char *sys_name, const char *event_name,
7409                                  tep_event_handler_func func, void *context)
7410 {
7411         struct tep_event *event;
7412         struct event_handler *handle;
7413         struct event_handler **next;
7414
7415         event = search_event(tep, id, sys_name, event_name);
7416         if (event == NULL)
7417                 goto not_found;
7418
7419         if (event->handler == func && event->context == context) {
7420                 pr_stat("removing override handler for event (%d) %s:%s. Going back to default handler.",
7421                         event->id, event->system, event->name);
7422
7423                 event->handler = NULL;
7424                 event->context = NULL;
7425                 return 0;
7426         }
7427
7428 not_found:
7429         for (next = &tep->handlers; *next; next = &(*next)->next) {
7430                 handle = *next;
7431                 if (handle_matches(handle, id, sys_name, event_name,
7432                                    func, context))
7433                         break;
7434         }
7435
7436         if (!(*next))
7437                 return -1;
7438
7439         *next = handle->next;
7440         free_handler(handle);
7441
7442         return 0;
7443 }
7444
7445 /**
7446  * tep_alloc - create a tep handle
7447  */
7448 struct tep_handle *tep_alloc(void)
7449 {
7450         struct tep_handle *tep = calloc(1, sizeof(*tep));
7451
7452         if (tep) {
7453                 tep->ref_count = 1;
7454                 tep->host_bigendian = tep_is_bigendian();
7455         }
7456
7457         return tep;
7458 }
7459
7460 void tep_ref(struct tep_handle *tep)
7461 {
7462         tep->ref_count++;
7463 }
7464
7465 int tep_get_ref(struct tep_handle *tep)
7466 {
7467         if (tep)
7468                 return tep->ref_count;
7469         return 0;
7470 }
7471
7472 __hidden void free_tep_format_field(struct tep_format_field *field)
7473 {
7474         free(field->type);
7475         if (field->alias != field->name)
7476                 free(field->alias);
7477         free(field->name);
7478         free(field);
7479 }
7480
7481 static void free_format_fields(struct tep_format_field *field)
7482 {
7483         struct tep_format_field *next;
7484
7485         while (field) {
7486                 next = field->next;
7487                 free_tep_format_field(field);
7488                 field = next;
7489         }
7490 }
7491
7492 static void free_formats(struct tep_format *format)
7493 {
7494         free_format_fields(format->common_fields);
7495         free_format_fields(format->fields);
7496 }
7497
7498 __hidden void free_tep_event(struct tep_event *event)
7499 {
7500         free(event->name);
7501         free(event->system);
7502
7503         free_formats(&event->format);
7504
7505         free(event->print_fmt.format);
7506         free_args(event->print_fmt.args);
7507         free_parse_args(event->print_fmt.print_cache);
7508         free(event);
7509 }
7510
7511 /**
7512  * tep_free - free a tep handle
7513  * @tep: the tep handle to free
7514  */
7515 void tep_free(struct tep_handle *tep)
7516 {
7517         struct cmdline_list *cmdlist, *cmdnext;
7518         struct func_list *funclist, *funcnext;
7519         struct printk_list *printklist, *printknext;
7520         struct tep_function_handler *func_handler;
7521         struct event_handler *handle;
7522         int i;
7523
7524         if (!tep)
7525                 return;
7526
7527         cmdlist = tep->cmdlist;
7528         funclist = tep->funclist;
7529         printklist = tep->printklist;
7530
7531         tep->ref_count--;
7532         if (tep->ref_count)
7533                 return;
7534
7535         if (tep->cmdlines) {
7536                 for (i = 0; i < tep->cmdline_count; i++)
7537                         free(tep->cmdlines[i].comm);
7538                 free(tep->cmdlines);
7539         }
7540
7541         while (cmdlist) {
7542                 cmdnext = cmdlist->next;
7543                 free(cmdlist->comm);
7544                 free(cmdlist);
7545                 cmdlist = cmdnext;
7546         }
7547
7548         if (tep->func_map) {
7549                 for (i = 0; i < (int)tep->func_count; i++) {
7550                         free(tep->func_map[i].func);
7551                         free(tep->func_map[i].mod);
7552                 }
7553                 free(tep->func_map);
7554         }
7555
7556         while (funclist) {
7557                 funcnext = funclist->next;
7558                 free(funclist->func);
7559                 free(funclist->mod);
7560                 free(funclist);
7561                 funclist = funcnext;
7562         }
7563
7564         while (tep->func_handlers) {
7565                 func_handler = tep->func_handlers;
7566                 tep->func_handlers = func_handler->next;
7567                 free_func_handle(func_handler);
7568         }
7569
7570         if (tep->printk_map) {
7571                 for (i = 0; i < (int)tep->printk_count; i++)
7572                         free(tep->printk_map[i].printk);
7573                 free(tep->printk_map);
7574         }
7575
7576         while (printklist) {
7577                 printknext = printklist->next;
7578                 free(printklist->printk);
7579                 free(printklist);
7580                 printklist = printknext;
7581         }
7582
7583         for (i = 0; i < tep->nr_events; i++)
7584                 free_tep_event(tep->events[i]);
7585
7586         while (tep->handlers) {
7587                 handle = tep->handlers;
7588                 tep->handlers = handle->next;
7589                 free_handler(handle);
7590         }
7591
7592         free(tep->events);
7593         free(tep->sort_events);
7594         free(tep->func_resolver);
7595         free_tep_plugin_paths(tep);
7596
7597         free(tep);
7598 }
7599
7600 void tep_unref(struct tep_handle *tep)
7601 {
7602         tep_free(tep);
7603 }