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