linux/tools/perf/util/probe-event.c
<<
>>
Prefs
   1/*
   2 * probe-event.c : perf-probe definition to probe_events format converter
   3 *
   4 * Written by Masami Hiramatsu <mhiramat@redhat.com>
   5 *
   6 * This program is free software; you can redistribute it and/or modify
   7 * it under the terms of the GNU General Public License as published by
   8 * the Free Software Foundation; either version 2 of the License, or
   9 * (at your option) any later version.
  10 *
  11 * This program is distributed in the hope that it will be useful,
  12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14 * GNU General Public License for more details.
  15 *
  16 * You should have received a copy of the GNU General Public License
  17 * along with this program; if not, write to the Free Software
  18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  19 *
  20 */
  21
  22#include <sys/utsname.h>
  23#include <sys/types.h>
  24#include <sys/stat.h>
  25#include <fcntl.h>
  26#include <errno.h>
  27#include <stdio.h>
  28#include <unistd.h>
  29#include <stdlib.h>
  30#include <string.h>
  31#include <stdarg.h>
  32#include <limits.h>
  33#include <elf.h>
  34
  35#include "util.h"
  36#include "event.h"
  37#include "strlist.h"
  38#include "debug.h"
  39#include "cache.h"
  40#include "color.h"
  41#include "symbol.h"
  42#include "thread.h"
  43#include <api/fs/fs.h>
  44#include "trace-event.h"        /* For __maybe_unused */
  45#include "probe-event.h"
  46#include "probe-finder.h"
  47#include "probe-file.h"
  48#include "session.h"
  49
  50#define MAX_CMDLEN 256
  51#define PERFPROBE_GROUP "probe"
  52
  53bool probe_event_dry_run;       /* Dry run flag */
  54struct probe_conf probe_conf;
  55
  56#define semantic_error(msg ...) pr_err("Semantic error :" msg)
  57
  58int e_snprintf(char *str, size_t size, const char *format, ...)
  59{
  60        int ret;
  61        va_list ap;
  62        va_start(ap, format);
  63        ret = vsnprintf(str, size, format, ap);
  64        va_end(ap);
  65        if (ret >= (int)size)
  66                ret = -E2BIG;
  67        return ret;
  68}
  69
  70static struct machine *host_machine;
  71
  72/* Initialize symbol maps and path of vmlinux/modules */
  73int init_probe_symbol_maps(bool user_only)
  74{
  75        int ret;
  76
  77        symbol_conf.sort_by_name = true;
  78        symbol_conf.allow_aliases = true;
  79        ret = symbol__init(NULL);
  80        if (ret < 0) {
  81                pr_debug("Failed to init symbol map.\n");
  82                goto out;
  83        }
  84
  85        if (host_machine || user_only)  /* already initialized */
  86                return 0;
  87
  88        if (symbol_conf.vmlinux_name)
  89                pr_debug("Use vmlinux: %s\n", symbol_conf.vmlinux_name);
  90
  91        host_machine = machine__new_host();
  92        if (!host_machine) {
  93                pr_debug("machine__new_host() failed.\n");
  94                symbol__exit();
  95                ret = -1;
  96        }
  97out:
  98        if (ret < 0)
  99                pr_warning("Failed to init vmlinux path.\n");
 100        return ret;
 101}
 102
 103void exit_probe_symbol_maps(void)
 104{
 105        machine__delete(host_machine);
 106        host_machine = NULL;
 107        symbol__exit();
 108}
 109
 110static struct symbol *__find_kernel_function_by_name(const char *name,
 111                                                     struct map **mapp)
 112{
 113        return machine__find_kernel_function_by_name(host_machine, name, mapp);
 114}
 115
 116static struct symbol *__find_kernel_function(u64 addr, struct map **mapp)
 117{
 118        return machine__find_kernel_function(host_machine, addr, mapp);
 119}
 120
 121static struct ref_reloc_sym *kernel_get_ref_reloc_sym(void)
 122{
 123        /* kmap->ref_reloc_sym should be set if host_machine is initialized */
 124        struct kmap *kmap;
 125        struct map *map = machine__kernel_map(host_machine);
 126
 127        if (map__load(map) < 0)
 128                return NULL;
 129
 130        kmap = map__kmap(map);
 131        if (!kmap)
 132                return NULL;
 133        return kmap->ref_reloc_sym;
 134}
 135
 136static int kernel_get_symbol_address_by_name(const char *name, u64 *addr,
 137                                             bool reloc, bool reladdr)
 138{
 139        struct ref_reloc_sym *reloc_sym;
 140        struct symbol *sym;
 141        struct map *map;
 142
 143        /* ref_reloc_sym is just a label. Need a special fix*/
 144        reloc_sym = kernel_get_ref_reloc_sym();
 145        if (reloc_sym && strcmp(name, reloc_sym->name) == 0)
 146                *addr = (reloc) ? reloc_sym->addr : reloc_sym->unrelocated_addr;
 147        else {
 148                sym = __find_kernel_function_by_name(name, &map);
 149                if (!sym)
 150                        return -ENOENT;
 151                *addr = map->unmap_ip(map, sym->start) -
 152                        ((reloc) ? 0 : map->reloc) -
 153                        ((reladdr) ? map->start : 0);
 154        }
 155        return 0;
 156}
 157
 158static struct map *kernel_get_module_map(const char *module)
 159{
 160        struct map_groups *grp = &host_machine->kmaps;
 161        struct maps *maps = &grp->maps[MAP__FUNCTION];
 162        struct map *pos;
 163
 164        /* A file path -- this is an offline module */
 165        if (module && strchr(module, '/'))
 166                return machine__findnew_module_map(host_machine, 0, module);
 167
 168        if (!module)
 169                module = "kernel";
 170
 171        for (pos = maps__first(maps); pos; pos = map__next(pos)) {
 172                /* short_name is "[module]" */
 173                if (strncmp(pos->dso->short_name + 1, module,
 174                            pos->dso->short_name_len - 2) == 0 &&
 175                    module[pos->dso->short_name_len - 2] == '\0') {
 176                        return pos;
 177                }
 178        }
 179        return NULL;
 180}
 181
 182struct map *get_target_map(const char *target, bool user)
 183{
 184        /* Init maps of given executable or kernel */
 185        if (user)
 186                return dso__new_map(target);
 187        else
 188                return kernel_get_module_map(target);
 189}
 190
 191static void put_target_map(struct map *map, bool user)
 192{
 193        if (map && user) {
 194                /* Only the user map needs to be released */
 195                map__put(map);
 196        }
 197}
 198
 199
 200static int convert_exec_to_group(const char *exec, char **result)
 201{
 202        char *ptr1, *ptr2, *exec_copy;
 203        char buf[64];
 204        int ret;
 205
 206        exec_copy = strdup(exec);
 207        if (!exec_copy)
 208                return -ENOMEM;
 209
 210        ptr1 = basename(exec_copy);
 211        if (!ptr1) {
 212                ret = -EINVAL;
 213                goto out;
 214        }
 215
 216        for (ptr2 = ptr1; *ptr2 != '\0'; ptr2++) {
 217                if (!isalnum(*ptr2) && *ptr2 != '_') {
 218                        *ptr2 = '\0';
 219                        break;
 220                }
 221        }
 222
 223        ret = e_snprintf(buf, 64, "%s_%s", PERFPROBE_GROUP, ptr1);
 224        if (ret < 0)
 225                goto out;
 226
 227        *result = strdup(buf);
 228        ret = *result ? 0 : -ENOMEM;
 229
 230out:
 231        free(exec_copy);
 232        return ret;
 233}
 234
 235static void clear_perf_probe_point(struct perf_probe_point *pp)
 236{
 237        free(pp->file);
 238        free(pp->function);
 239        free(pp->lazy_line);
 240}
 241
 242static void clear_probe_trace_events(struct probe_trace_event *tevs, int ntevs)
 243{
 244        int i;
 245
 246        for (i = 0; i < ntevs; i++)
 247                clear_probe_trace_event(tevs + i);
 248}
 249
 250static bool kprobe_blacklist__listed(unsigned long address);
 251static bool kprobe_warn_out_range(const char *symbol, unsigned long address)
 252{
 253        u64 etext_addr = 0;
 254        int ret;
 255
 256        /* Get the address of _etext for checking non-probable text symbol */
 257        ret = kernel_get_symbol_address_by_name("_etext", &etext_addr,
 258                                                false, false);
 259
 260        if (ret == 0 && etext_addr < address)
 261                pr_warning("%s is out of .text, skip it.\n", symbol);
 262        else if (kprobe_blacklist__listed(address))
 263                pr_warning("%s is blacklisted function, skip it.\n", symbol);
 264        else
 265                return false;
 266
 267        return true;
 268}
 269
 270/*
 271 * NOTE:
 272 * '.gnu.linkonce.this_module' section of kernel module elf directly
 273 * maps to 'struct module' from linux/module.h. This section contains
 274 * actual module name which will be used by kernel after loading it.
 275 * But, we cannot use 'struct module' here since linux/module.h is not
 276 * exposed to user-space. Offset of 'name' has remained same from long
 277 * time, so hardcoding it here.
 278 */
 279#ifdef __LP64__
 280#define MOD_NAME_OFFSET 24
 281#else
 282#define MOD_NAME_OFFSET 12
 283#endif
 284
 285/*
 286 * @module can be module name of module file path. In case of path,
 287 * inspect elf and find out what is actual module name.
 288 * Caller has to free mod_name after using it.
 289 */
 290static char *find_module_name(const char *module)
 291{
 292        int fd;
 293        Elf *elf;
 294        GElf_Ehdr ehdr;
 295        GElf_Shdr shdr;
 296        Elf_Data *data;
 297        Elf_Scn *sec;
 298        char *mod_name = NULL;
 299
 300        fd = open(module, O_RDONLY);
 301        if (fd < 0)
 302                return NULL;
 303
 304        elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
 305        if (elf == NULL)
 306                goto elf_err;
 307
 308        if (gelf_getehdr(elf, &ehdr) == NULL)
 309                goto ret_err;
 310
 311        sec = elf_section_by_name(elf, &ehdr, &shdr,
 312                        ".gnu.linkonce.this_module", NULL);
 313        if (!sec)
 314                goto ret_err;
 315
 316        data = elf_getdata(sec, NULL);
 317        if (!data || !data->d_buf)
 318                goto ret_err;
 319
 320        mod_name = strdup((char *)data->d_buf + MOD_NAME_OFFSET);
 321
 322ret_err:
 323        elf_end(elf);
 324elf_err:
 325        close(fd);
 326        return mod_name;
 327}
 328
 329#ifdef HAVE_DWARF_SUPPORT
 330
 331static int kernel_get_module_dso(const char *module, struct dso **pdso)
 332{
 333        struct dso *dso;
 334        struct map *map;
 335        const char *vmlinux_name;
 336        int ret = 0;
 337
 338        if (module) {
 339                char module_name[128];
 340
 341                snprintf(module_name, sizeof(module_name), "[%s]", module);
 342                map = map_groups__find_by_name(&host_machine->kmaps, MAP__FUNCTION, module_name);
 343                if (map) {
 344                        dso = map->dso;
 345                        goto found;
 346                }
 347                pr_debug("Failed to find module %s.\n", module);
 348                return -ENOENT;
 349        }
 350
 351        map = machine__kernel_map(host_machine);
 352        dso = map->dso;
 353
 354        vmlinux_name = symbol_conf.vmlinux_name;
 355        dso->load_errno = 0;
 356        if (vmlinux_name)
 357                ret = dso__load_vmlinux(dso, map, vmlinux_name, false);
 358        else
 359                ret = dso__load_vmlinux_path(dso, map);
 360found:
 361        *pdso = dso;
 362        return ret;
 363}
 364
 365/*
 366 * Some binaries like glibc have special symbols which are on the symbol
 367 * table, but not in the debuginfo. If we can find the address of the
 368 * symbol from map, we can translate the address back to the probe point.
 369 */
 370static int find_alternative_probe_point(struct debuginfo *dinfo,
 371                                        struct perf_probe_point *pp,
 372                                        struct perf_probe_point *result,
 373                                        const char *target, bool uprobes)
 374{
 375        struct map *map = NULL;
 376        struct symbol *sym;
 377        u64 address = 0;
 378        int ret = -ENOENT;
 379
 380        /* This can work only for function-name based one */
 381        if (!pp->function || pp->file)
 382                return -ENOTSUP;
 383
 384        map = get_target_map(target, uprobes);
 385        if (!map)
 386                return -EINVAL;
 387
 388        /* Find the address of given function */
 389        map__for_each_symbol_by_name(map, pp->function, sym) {
 390                if (uprobes)
 391                        address = sym->start;
 392                else
 393                        address = map->unmap_ip(map, sym->start) - map->reloc;
 394                break;
 395        }
 396        if (!address) {
 397                ret = -ENOENT;
 398                goto out;
 399        }
 400        pr_debug("Symbol %s address found : %" PRIx64 "\n",
 401                        pp->function, address);
 402
 403        ret = debuginfo__find_probe_point(dinfo, (unsigned long)address,
 404                                          result);
 405        if (ret <= 0)
 406                ret = (!ret) ? -ENOENT : ret;
 407        else {
 408                result->offset += pp->offset;
 409                result->line += pp->line;
 410                result->retprobe = pp->retprobe;
 411                ret = 0;
 412        }
 413
 414out:
 415        put_target_map(map, uprobes);
 416        return ret;
 417
 418}
 419
 420static int get_alternative_probe_event(struct debuginfo *dinfo,
 421                                       struct perf_probe_event *pev,
 422                                       struct perf_probe_point *tmp)
 423{
 424        int ret;
 425
 426        memcpy(tmp, &pev->point, sizeof(*tmp));
 427        memset(&pev->point, 0, sizeof(pev->point));
 428        ret = find_alternative_probe_point(dinfo, tmp, &pev->point,
 429                                           pev->target, pev->uprobes);
 430        if (ret < 0)
 431                memcpy(&pev->point, tmp, sizeof(*tmp));
 432
 433        return ret;
 434}
 435
 436static int get_alternative_line_range(struct debuginfo *dinfo,
 437                                      struct line_range *lr,
 438                                      const char *target, bool user)
 439{
 440        struct perf_probe_point pp = { .function = lr->function,
 441                                       .file = lr->file,
 442                                       .line = lr->start };
 443        struct perf_probe_point result;
 444        int ret, len = 0;
 445
 446        memset(&result, 0, sizeof(result));
 447
 448        if (lr->end != INT_MAX)
 449                len = lr->end - lr->start;
 450        ret = find_alternative_probe_point(dinfo, &pp, &result,
 451                                           target, user);
 452        if (!ret) {
 453                lr->function = result.function;
 454                lr->file = result.file;
 455                lr->start = result.line;
 456                if (lr->end != INT_MAX)
 457                        lr->end = lr->start + len;
 458                clear_perf_probe_point(&pp);
 459        }
 460        return ret;
 461}
 462
 463/* Open new debuginfo of given module */
 464static struct debuginfo *open_debuginfo(const char *module, bool silent)
 465{
 466        const char *path = module;
 467        char reason[STRERR_BUFSIZE];
 468        struct debuginfo *ret = NULL;
 469        struct dso *dso = NULL;
 470        int err;
 471
 472        if (!module || !strchr(module, '/')) {
 473                err = kernel_get_module_dso(module, &dso);
 474                if (err < 0) {
 475                        if (!dso || dso->load_errno == 0) {
 476                                if (!str_error_r(-err, reason, STRERR_BUFSIZE))
 477                                        strcpy(reason, "(unknown)");
 478                        } else
 479                                dso__strerror_load(dso, reason, STRERR_BUFSIZE);
 480                        if (!silent)
 481                                pr_err("Failed to find the path for %s: %s\n",
 482                                        module ?: "kernel", reason);
 483                        return NULL;
 484                }
 485                path = dso->long_name;
 486        }
 487        ret = debuginfo__new(path);
 488        if (!ret && !silent) {
 489                pr_warning("The %s file has no debug information.\n", path);
 490                if (!module || !strtailcmp(path, ".ko"))
 491                        pr_warning("Rebuild with CONFIG_DEBUG_INFO=y, ");
 492                else
 493                        pr_warning("Rebuild with -g, ");
 494                pr_warning("or install an appropriate debuginfo package.\n");
 495        }
 496        return ret;
 497}
 498
 499/* For caching the last debuginfo */
 500static struct debuginfo *debuginfo_cache;
 501static char *debuginfo_cache_path;
 502
 503static struct debuginfo *debuginfo_cache__open(const char *module, bool silent)
 504{
 505        const char *path = module;
 506
 507        /* If the module is NULL, it should be the kernel. */
 508        if (!module)
 509                path = "kernel";
 510
 511        if (debuginfo_cache_path && !strcmp(debuginfo_cache_path, path))
 512                goto out;
 513
 514        /* Copy module path */
 515        free(debuginfo_cache_path);
 516        debuginfo_cache_path = strdup(path);
 517        if (!debuginfo_cache_path) {
 518                debuginfo__delete(debuginfo_cache);
 519                debuginfo_cache = NULL;
 520                goto out;
 521        }
 522
 523        debuginfo_cache = open_debuginfo(module, silent);
 524        if (!debuginfo_cache)
 525                zfree(&debuginfo_cache_path);
 526out:
 527        return debuginfo_cache;
 528}
 529
 530static void debuginfo_cache__exit(void)
 531{
 532        debuginfo__delete(debuginfo_cache);
 533        debuginfo_cache = NULL;
 534        zfree(&debuginfo_cache_path);
 535}
 536
 537
 538static int get_text_start_address(const char *exec, unsigned long *address)
 539{
 540        Elf *elf;
 541        GElf_Ehdr ehdr;
 542        GElf_Shdr shdr;
 543        int fd, ret = -ENOENT;
 544
 545        fd = open(exec, O_RDONLY);
 546        if (fd < 0)
 547                return -errno;
 548
 549        elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
 550        if (elf == NULL) {
 551                ret = -EINVAL;
 552                goto out_close;
 553        }
 554
 555        if (gelf_getehdr(elf, &ehdr) == NULL)
 556                goto out;
 557
 558        if (!elf_section_by_name(elf, &ehdr, &shdr, ".text", NULL))
 559                goto out;
 560
 561        *address = shdr.sh_addr - shdr.sh_offset;
 562        ret = 0;
 563out:
 564        elf_end(elf);
 565out_close:
 566        close(fd);
 567
 568        return ret;
 569}
 570
 571/*
 572 * Convert trace point to probe point with debuginfo
 573 */
 574static int find_perf_probe_point_from_dwarf(struct probe_trace_point *tp,
 575                                            struct perf_probe_point *pp,
 576                                            bool is_kprobe)
 577{
 578        struct debuginfo *dinfo = NULL;
 579        unsigned long stext = 0;
 580        u64 addr = tp->address;
 581        int ret = -ENOENT;
 582
 583        /* convert the address to dwarf address */
 584        if (!is_kprobe) {
 585                if (!addr) {
 586                        ret = -EINVAL;
 587                        goto error;
 588                }
 589                ret = get_text_start_address(tp->module, &stext);
 590                if (ret < 0)
 591                        goto error;
 592                addr += stext;
 593        } else if (tp->symbol) {
 594                /* If the module is given, this returns relative address */
 595                ret = kernel_get_symbol_address_by_name(tp->symbol, &addr,
 596                                                        false, !!tp->module);
 597                if (ret != 0)
 598                        goto error;
 599                addr += tp->offset;
 600        }
 601
 602        pr_debug("try to find information at %" PRIx64 " in %s\n", addr,
 603                 tp->module ? : "kernel");
 604
 605        dinfo = debuginfo_cache__open(tp->module, verbose == 0);
 606        if (dinfo)
 607                ret = debuginfo__find_probe_point(dinfo,
 608                                                 (unsigned long)addr, pp);
 609        else
 610                ret = -ENOENT;
 611
 612        if (ret > 0) {
 613                pp->retprobe = tp->retprobe;
 614                return 0;
 615        }
 616error:
 617        pr_debug("Failed to find corresponding probes from debuginfo.\n");
 618        return ret ? : -ENOENT;
 619}
 620
 621static int add_exec_to_probe_trace_events(struct probe_trace_event *tevs,
 622                                          int ntevs, const char *exec)
 623{
 624        int i, ret = 0;
 625        unsigned long stext = 0;
 626
 627        if (!exec)
 628                return 0;
 629
 630        ret = get_text_start_address(exec, &stext);
 631        if (ret < 0)
 632                return ret;
 633
 634        for (i = 0; i < ntevs && ret >= 0; i++) {
 635                /* point.address is the addres of point.symbol + point.offset */
 636                tevs[i].point.address -= stext;
 637                tevs[i].point.module = strdup(exec);
 638                if (!tevs[i].point.module) {
 639                        ret = -ENOMEM;
 640                        break;
 641                }
 642                tevs[i].uprobes = true;
 643        }
 644
 645        return ret;
 646}
 647
 648static int add_module_to_probe_trace_events(struct probe_trace_event *tevs,
 649                                            int ntevs, const char *module)
 650{
 651        int i, ret = 0;
 652        char *mod_name = NULL;
 653
 654        if (!module)
 655                return 0;
 656
 657        mod_name = find_module_name(module);
 658
 659        for (i = 0; i < ntevs; i++) {
 660                tevs[i].point.module =
 661                        strdup(mod_name ? mod_name : module);
 662                if (!tevs[i].point.module) {
 663                        ret = -ENOMEM;
 664                        break;
 665                }
 666        }
 667
 668        free(mod_name);
 669        return ret;
 670}
 671
 672static int
 673post_process_kernel_probe_trace_events(struct probe_trace_event *tevs,
 674                                       int ntevs)
 675{
 676        struct ref_reloc_sym *reloc_sym;
 677        char *tmp;
 678        int i, skipped = 0;
 679
 680        /* Skip post process if the target is an offline kernel */
 681        if (symbol_conf.ignore_vmlinux_buildid)
 682                return 0;
 683
 684        reloc_sym = kernel_get_ref_reloc_sym();
 685        if (!reloc_sym) {
 686                pr_warning("Relocated base symbol is not found!\n");
 687                return -EINVAL;
 688        }
 689
 690        for (i = 0; i < ntevs; i++) {
 691                if (!tevs[i].point.address || tevs[i].point.retprobe)
 692                        continue;
 693                /* If we found a wrong one, mark it by NULL symbol */
 694                if (kprobe_warn_out_range(tevs[i].point.symbol,
 695                                          tevs[i].point.address)) {
 696                        tmp = NULL;
 697                        skipped++;
 698                } else {
 699                        tmp = strdup(reloc_sym->name);
 700                        if (!tmp)
 701                                return -ENOMEM;
 702                }
 703                /* If we have no realname, use symbol for it */
 704                if (!tevs[i].point.realname)
 705                        tevs[i].point.realname = tevs[i].point.symbol;
 706                else
 707                        free(tevs[i].point.symbol);
 708                tevs[i].point.symbol = tmp;
 709                tevs[i].point.offset = tevs[i].point.address -
 710                                       reloc_sym->unrelocated_addr;
 711        }
 712        return skipped;
 713}
 714
 715void __weak
 716arch__post_process_probe_trace_events(struct perf_probe_event *pev __maybe_unused,
 717                                      int ntevs __maybe_unused)
 718{
 719}
 720
 721/* Post processing the probe events */
 722static int post_process_probe_trace_events(struct perf_probe_event *pev,
 723                                           struct probe_trace_event *tevs,
 724                                           int ntevs, const char *module,
 725                                           bool uprobe)
 726{
 727        int ret;
 728
 729        if (uprobe)
 730                ret = add_exec_to_probe_trace_events(tevs, ntevs, module);
 731        else if (module)
 732                /* Currently ref_reloc_sym based probe is not for drivers */
 733                ret = add_module_to_probe_trace_events(tevs, ntevs, module);
 734        else
 735                ret = post_process_kernel_probe_trace_events(tevs, ntevs);
 736
 737        if (ret >= 0)
 738                arch__post_process_probe_trace_events(pev, ntevs);
 739
 740        return ret;
 741}
 742
 743/* Try to find perf_probe_event with debuginfo */
 744static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
 745                                          struct probe_trace_event **tevs)
 746{
 747        bool need_dwarf = perf_probe_event_need_dwarf(pev);
 748        struct perf_probe_point tmp;
 749        struct debuginfo *dinfo;
 750        int ntevs, ret = 0;
 751
 752        dinfo = open_debuginfo(pev->target, !need_dwarf);
 753        if (!dinfo) {
 754                if (need_dwarf)
 755                        return -ENOENT;
 756                pr_debug("Could not open debuginfo. Try to use symbols.\n");
 757                return 0;
 758        }
 759
 760        pr_debug("Try to find probe point from debuginfo.\n");
 761        /* Searching trace events corresponding to a probe event */
 762        ntevs = debuginfo__find_trace_events(dinfo, pev, tevs);
 763
 764        if (ntevs == 0) {  /* Not found, retry with an alternative */
 765                ret = get_alternative_probe_event(dinfo, pev, &tmp);
 766                if (!ret) {
 767                        ntevs = debuginfo__find_trace_events(dinfo, pev, tevs);
 768                        /*
 769                         * Write back to the original probe_event for
 770                         * setting appropriate (user given) event name
 771                         */
 772                        clear_perf_probe_point(&pev->point);
 773                        memcpy(&pev->point, &tmp, sizeof(tmp));
 774                }
 775        }
 776
 777        debuginfo__delete(dinfo);
 778
 779        if (ntevs > 0) {        /* Succeeded to find trace events */
 780                pr_debug("Found %d probe_trace_events.\n", ntevs);
 781                ret = post_process_probe_trace_events(pev, *tevs, ntevs,
 782                                                pev->target, pev->uprobes);
 783                if (ret < 0 || ret == ntevs) {
 784                        clear_probe_trace_events(*tevs, ntevs);
 785                        zfree(tevs);
 786                }
 787                if (ret != ntevs)
 788                        return ret < 0 ? ret : ntevs;
 789                ntevs = 0;
 790                /* Fall through */
 791        }
 792
 793        if (ntevs == 0) {       /* No error but failed to find probe point. */
 794                pr_warning("Probe point '%s' not found.\n",
 795                           synthesize_perf_probe_point(&pev->point));
 796                return -ENOENT;
 797        }
 798        /* Error path : ntevs < 0 */
 799        pr_debug("An error occurred in debuginfo analysis (%d).\n", ntevs);
 800        if (ntevs < 0) {
 801                if (ntevs == -EBADF)
 802                        pr_warning("Warning: No dwarf info found in the vmlinux - "
 803                                "please rebuild kernel with CONFIG_DEBUG_INFO=y.\n");
 804                if (!need_dwarf) {
 805                        pr_debug("Trying to use symbols.\n");
 806                        return 0;
 807                }
 808        }
 809        return ntevs;
 810}
 811
 812#define LINEBUF_SIZE 256
 813#define NR_ADDITIONAL_LINES 2
 814
 815static int __show_one_line(FILE *fp, int l, bool skip, bool show_num)
 816{
 817        char buf[LINEBUF_SIZE], sbuf[STRERR_BUFSIZE];
 818        const char *color = show_num ? "" : PERF_COLOR_BLUE;
 819        const char *prefix = NULL;
 820
 821        do {
 822                if (fgets(buf, LINEBUF_SIZE, fp) == NULL)
 823                        goto error;
 824                if (skip)
 825                        continue;
 826                if (!prefix) {
 827                        prefix = show_num ? "%7d  " : "         ";
 828                        color_fprintf(stdout, color, prefix, l);
 829                }
 830                color_fprintf(stdout, color, "%s", buf);
 831
 832        } while (strchr(buf, '\n') == NULL);
 833
 834        return 1;
 835error:
 836        if (ferror(fp)) {
 837                pr_warning("File read error: %s\n",
 838                           str_error_r(errno, sbuf, sizeof(sbuf)));
 839                return -1;
 840        }
 841        return 0;
 842}
 843
 844static int _show_one_line(FILE *fp, int l, bool skip, bool show_num)
 845{
 846        int rv = __show_one_line(fp, l, skip, show_num);
 847        if (rv == 0) {
 848                pr_warning("Source file is shorter than expected.\n");
 849                rv = -1;
 850        }
 851        return rv;
 852}
 853
 854#define show_one_line_with_num(f,l)     _show_one_line(f,l,false,true)
 855#define show_one_line(f,l)              _show_one_line(f,l,false,false)
 856#define skip_one_line(f,l)              _show_one_line(f,l,true,false)
 857#define show_one_line_or_eof(f,l)       __show_one_line(f,l,false,false)
 858
 859/*
 860 * Show line-range always requires debuginfo to find source file and
 861 * line number.
 862 */
 863static int __show_line_range(struct line_range *lr, const char *module,
 864                             bool user)
 865{
 866        int l = 1;
 867        struct int_node *ln;
 868        struct debuginfo *dinfo;
 869        FILE *fp;
 870        int ret;
 871        char *tmp;
 872        char sbuf[STRERR_BUFSIZE];
 873
 874        /* Search a line range */
 875        dinfo = open_debuginfo(module, false);
 876        if (!dinfo)
 877                return -ENOENT;
 878
 879        ret = debuginfo__find_line_range(dinfo, lr);
 880        if (!ret) {     /* Not found, retry with an alternative */
 881                ret = get_alternative_line_range(dinfo, lr, module, user);
 882                if (!ret)
 883                        ret = debuginfo__find_line_range(dinfo, lr);
 884        }
 885        debuginfo__delete(dinfo);
 886        if (ret == 0 || ret == -ENOENT) {
 887                pr_warning("Specified source line is not found.\n");
 888                return -ENOENT;
 889        } else if (ret < 0) {
 890                pr_warning("Debuginfo analysis failed.\n");
 891                return ret;
 892        }
 893
 894        /* Convert source file path */
 895        tmp = lr->path;
 896        ret = get_real_path(tmp, lr->comp_dir, &lr->path);
 897
 898        /* Free old path when new path is assigned */
 899        if (tmp != lr->path)
 900                free(tmp);
 901
 902        if (ret < 0) {
 903                pr_warning("Failed to find source file path.\n");
 904                return ret;
 905        }
 906
 907        setup_pager();
 908
 909        if (lr->function)
 910                fprintf(stdout, "<%s@%s:%d>\n", lr->function, lr->path,
 911                        lr->start - lr->offset);
 912        else
 913                fprintf(stdout, "<%s:%d>\n", lr->path, lr->start);
 914
 915        fp = fopen(lr->path, "r");
 916        if (fp == NULL) {
 917                pr_warning("Failed to open %s: %s\n", lr->path,
 918                           str_error_r(errno, sbuf, sizeof(sbuf)));
 919                return -errno;
 920        }
 921        /* Skip to starting line number */
 922        while (l < lr->start) {
 923                ret = skip_one_line(fp, l++);
 924                if (ret < 0)
 925                        goto end;
 926        }
 927
 928        intlist__for_each_entry(ln, lr->line_list) {
 929                for (; ln->i > l; l++) {
 930                        ret = show_one_line(fp, l - lr->offset);
 931                        if (ret < 0)
 932                                goto end;
 933                }
 934                ret = show_one_line_with_num(fp, l++ - lr->offset);
 935                if (ret < 0)
 936                        goto end;
 937        }
 938
 939        if (lr->end == INT_MAX)
 940                lr->end = l + NR_ADDITIONAL_LINES;
 941        while (l <= lr->end) {
 942                ret = show_one_line_or_eof(fp, l++ - lr->offset);
 943                if (ret <= 0)
 944                        break;
 945        }
 946end:
 947        fclose(fp);
 948        return ret;
 949}
 950
 951int show_line_range(struct line_range *lr, const char *module, bool user)
 952{
 953        int ret;
 954
 955        ret = init_probe_symbol_maps(user);
 956        if (ret < 0)
 957                return ret;
 958        ret = __show_line_range(lr, module, user);
 959        exit_probe_symbol_maps();
 960
 961        return ret;
 962}
 963
 964static int show_available_vars_at(struct debuginfo *dinfo,
 965                                  struct perf_probe_event *pev,
 966                                  struct strfilter *_filter)
 967{
 968        char *buf;
 969        int ret, i, nvars;
 970        struct str_node *node;
 971        struct variable_list *vls = NULL, *vl;
 972        struct perf_probe_point tmp;
 973        const char *var;
 974
 975        buf = synthesize_perf_probe_point(&pev->point);
 976        if (!buf)
 977                return -EINVAL;
 978        pr_debug("Searching variables at %s\n", buf);
 979
 980        ret = debuginfo__find_available_vars_at(dinfo, pev, &vls);
 981        if (!ret) {  /* Not found, retry with an alternative */
 982                ret = get_alternative_probe_event(dinfo, pev, &tmp);
 983                if (!ret) {
 984                        ret = debuginfo__find_available_vars_at(dinfo, pev,
 985                                                                &vls);
 986                        /* Release the old probe_point */
 987                        clear_perf_probe_point(&tmp);
 988                }
 989        }
 990        if (ret <= 0) {
 991                if (ret == 0 || ret == -ENOENT) {
 992                        pr_err("Failed to find the address of %s\n", buf);
 993                        ret = -ENOENT;
 994                } else
 995                        pr_warning("Debuginfo analysis failed.\n");
 996                goto end;
 997        }
 998
 999        /* Some variables are found */
1000        fprintf(stdout, "Available variables at %s\n", buf);
1001        for (i = 0; i < ret; i++) {
1002                vl = &vls[i];
1003                /*
1004                 * A probe point might be converted to
1005                 * several trace points.
1006                 */
1007                fprintf(stdout, "\t@<%s+%lu>\n", vl->point.symbol,
1008                        vl->point.offset);
1009                zfree(&vl->point.symbol);
1010                nvars = 0;
1011                if (vl->vars) {
1012                        strlist__for_each_entry(node, vl->vars) {
1013                                var = strchr(node->s, '\t') + 1;
1014                                if (strfilter__compare(_filter, var)) {
1015                                        fprintf(stdout, "\t\t%s\n", node->s);
1016                                        nvars++;
1017                                }
1018                        }
1019                        strlist__delete(vl->vars);
1020                }
1021                if (nvars == 0)
1022                        fprintf(stdout, "\t\t(No matched variables)\n");
1023        }
1024        free(vls);
1025end:
1026        free(buf);
1027        return ret;
1028}
1029
1030/* Show available variables on given probe point */
1031int show_available_vars(struct perf_probe_event *pevs, int npevs,
1032                        struct strfilter *_filter)
1033{
1034        int i, ret = 0;
1035        struct debuginfo *dinfo;
1036
1037        ret = init_probe_symbol_maps(pevs->uprobes);
1038        if (ret < 0)
1039                return ret;
1040
1041        dinfo = open_debuginfo(pevs->target, false);
1042        if (!dinfo) {
1043                ret = -ENOENT;
1044                goto out;
1045        }
1046
1047        setup_pager();
1048
1049        for (i = 0; i < npevs && ret >= 0; i++)
1050                ret = show_available_vars_at(dinfo, &pevs[i], _filter);
1051
1052        debuginfo__delete(dinfo);
1053out:
1054        exit_probe_symbol_maps();
1055        return ret;
1056}
1057
1058#else   /* !HAVE_DWARF_SUPPORT */
1059
1060static void debuginfo_cache__exit(void)
1061{
1062}
1063
1064static int
1065find_perf_probe_point_from_dwarf(struct probe_trace_point *tp __maybe_unused,
1066                                 struct perf_probe_point *pp __maybe_unused,
1067                                 bool is_kprobe __maybe_unused)
1068{
1069        return -ENOSYS;
1070}
1071
1072static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
1073                                struct probe_trace_event **tevs __maybe_unused)
1074{
1075        if (perf_probe_event_need_dwarf(pev)) {
1076                pr_warning("Debuginfo-analysis is not supported.\n");
1077                return -ENOSYS;
1078        }
1079
1080        return 0;
1081}
1082
1083int show_line_range(struct line_range *lr __maybe_unused,
1084                    const char *module __maybe_unused,
1085                    bool user __maybe_unused)
1086{
1087        pr_warning("Debuginfo-analysis is not supported.\n");
1088        return -ENOSYS;
1089}
1090
1091int show_available_vars(struct perf_probe_event *pevs __maybe_unused,
1092                        int npevs __maybe_unused,
1093                        struct strfilter *filter __maybe_unused)
1094{
1095        pr_warning("Debuginfo-analysis is not supported.\n");
1096        return -ENOSYS;
1097}
1098#endif
1099
1100void line_range__clear(struct line_range *lr)
1101{
1102        free(lr->function);
1103        free(lr->file);
1104        free(lr->path);
1105        free(lr->comp_dir);
1106        intlist__delete(lr->line_list);
1107        memset(lr, 0, sizeof(*lr));
1108}
1109
1110int line_range__init(struct line_range *lr)
1111{
1112        memset(lr, 0, sizeof(*lr));
1113        lr->line_list = intlist__new(NULL);
1114        if (!lr->line_list)
1115                return -ENOMEM;
1116        else
1117                return 0;
1118}
1119
1120static int parse_line_num(char **ptr, int *val, const char *what)
1121{
1122        const char *start = *ptr;
1123
1124        errno = 0;
1125        *val = strtol(*ptr, ptr, 0);
1126        if (errno || *ptr == start) {
1127                semantic_error("'%s' is not a valid number.\n", what);
1128                return -EINVAL;
1129        }
1130        return 0;
1131}
1132
1133/* Check the name is good for event, group or function */
1134static bool is_c_func_name(const char *name)
1135{
1136        if (!isalpha(*name) && *name != '_')
1137                return false;
1138        while (*++name != '\0') {
1139                if (!isalpha(*name) && !isdigit(*name) && *name != '_')
1140                        return false;
1141        }
1142        return true;
1143}
1144
1145/*
1146 * Stuff 'lr' according to the line range described by 'arg'.
1147 * The line range syntax is described by:
1148 *
1149 *         SRC[:SLN[+NUM|-ELN]]
1150 *         FNC[@SRC][:SLN[+NUM|-ELN]]
1151 */
1152int parse_line_range_desc(const char *arg, struct line_range *lr)
1153{
1154        char *range, *file, *name = strdup(arg);
1155        int err;
1156
1157        if (!name)
1158                return -ENOMEM;
1159
1160        lr->start = 0;
1161        lr->end = INT_MAX;
1162
1163        range = strchr(name, ':');
1164        if (range) {
1165                *range++ = '\0';
1166
1167                err = parse_line_num(&range, &lr->start, "start line");
1168                if (err)
1169                        goto err;
1170
1171                if (*range == '+' || *range == '-') {
1172                        const char c = *range++;
1173
1174                        err = parse_line_num(&range, &lr->end, "end line");
1175                        if (err)
1176                                goto err;
1177
1178                        if (c == '+') {
1179                                lr->end += lr->start;
1180                                /*
1181                                 * Adjust the number of lines here.
1182                                 * If the number of lines == 1, the
1183                                 * the end of line should be equal to
1184                                 * the start of line.
1185                                 */
1186                                lr->end--;
1187                        }
1188                }
1189
1190                pr_debug("Line range is %d to %d\n", lr->start, lr->end);
1191
1192                err = -EINVAL;
1193                if (lr->start > lr->end) {
1194                        semantic_error("Start line must be smaller"
1195                                       " than end line.\n");
1196                        goto err;
1197                }
1198                if (*range != '\0') {
1199                        semantic_error("Tailing with invalid str '%s'.\n", range);
1200                        goto err;
1201                }
1202        }
1203
1204        file = strchr(name, '@');
1205        if (file) {
1206                *file = '\0';
1207                lr->file = strdup(++file);
1208                if (lr->file == NULL) {
1209                        err = -ENOMEM;
1210                        goto err;
1211                }
1212                lr->function = name;
1213        } else if (strchr(name, '/') || strchr(name, '.'))
1214                lr->file = name;
1215        else if (is_c_func_name(name))/* We reuse it for checking funcname */
1216                lr->function = name;
1217        else {  /* Invalid name */
1218                semantic_error("'%s' is not a valid function name.\n", name);
1219                err = -EINVAL;
1220                goto err;
1221        }
1222
1223        return 0;
1224err:
1225        free(name);
1226        return err;
1227}
1228
1229static int parse_perf_probe_event_name(char **arg, struct perf_probe_event *pev)
1230{
1231        char *ptr;
1232
1233        ptr = strchr(*arg, ':');
1234        if (ptr) {
1235                *ptr = '\0';
1236                if (!pev->sdt && !is_c_func_name(*arg))
1237                        goto ng_name;
1238                pev->group = strdup(*arg);
1239                if (!pev->group)
1240                        return -ENOMEM;
1241                *arg = ptr + 1;
1242        } else
1243                pev->group = NULL;
1244        if (!pev->sdt && !is_c_func_name(*arg)) {
1245ng_name:
1246                semantic_error("%s is bad for event name -it must "
1247                               "follow C symbol-naming rule.\n", *arg);
1248                return -EINVAL;
1249        }
1250        pev->event = strdup(*arg);
1251        if (pev->event == NULL)
1252                return -ENOMEM;
1253
1254        return 0;
1255}
1256
1257/* Parse probepoint definition. */
1258static int parse_perf_probe_point(char *arg, struct perf_probe_event *pev)
1259{
1260        struct perf_probe_point *pp = &pev->point;
1261        char *ptr, *tmp;
1262        char c, nc = 0;
1263        bool file_spec = false;
1264        int ret;
1265
1266        /*
1267         * <Syntax>
1268         * perf probe [GRP:][EVENT=]SRC[:LN|;PTN]
1269         * perf probe [GRP:][EVENT=]FUNC[@SRC][+OFFS|%return|:LN|;PAT]
1270         * perf probe %[GRP:]SDT_EVENT
1271         */
1272        if (!arg)
1273                return -EINVAL;
1274
1275        /*
1276         * If the probe point starts with '%',
1277         * or starts with "sdt_" and has a ':' but no '=',
1278         * then it should be a SDT/cached probe point.
1279         */
1280        if (arg[0] == '%' ||
1281            (!strncmp(arg, "sdt_", 4) &&
1282             !!strchr(arg, ':') && !strchr(arg, '='))) {
1283                pev->sdt = true;
1284                if (arg[0] == '%')
1285                        arg++;
1286        }
1287
1288        ptr = strpbrk(arg, ";=@+%");
1289        if (pev->sdt) {
1290                if (ptr) {
1291                        if (*ptr != '@') {
1292                                semantic_error("%s must be an SDT name.\n",
1293                                               arg);
1294                                return -EINVAL;
1295                        }
1296                        /* This must be a target file name or build id */
1297                        tmp = build_id_cache__complement(ptr + 1);
1298                        if (tmp) {
1299                                pev->target = build_id_cache__origname(tmp);
1300                                free(tmp);
1301                        } else
1302                                pev->target = strdup(ptr + 1);
1303                        if (!pev->target)
1304                                return -ENOMEM;
1305                        *ptr = '\0';
1306                }
1307                ret = parse_perf_probe_event_name(&arg, pev);
1308                if (ret == 0) {
1309                        if (asprintf(&pev->point.function, "%%%s", pev->event) < 0)
1310                                ret = -errno;
1311                }
1312                return ret;
1313        }
1314
1315        if (ptr && *ptr == '=') {       /* Event name */
1316                *ptr = '\0';
1317                tmp = ptr + 1;
1318                ret = parse_perf_probe_event_name(&arg, pev);
1319                if (ret < 0)
1320                        return ret;
1321
1322                arg = tmp;
1323        }
1324
1325        /*
1326         * Check arg is function or file name and copy it.
1327         *
1328         * We consider arg to be a file spec if and only if it satisfies
1329         * all of the below criteria::
1330         * - it does not include any of "+@%",
1331         * - it includes one of ":;", and
1332         * - it has a period '.' in the name.
1333         *
1334         * Otherwise, we consider arg to be a function specification.
1335         */
1336        if (!strpbrk(arg, "+@%") && (ptr = strpbrk(arg, ";:")) != NULL) {
1337                /* This is a file spec if it includes a '.' before ; or : */
1338                if (memchr(arg, '.', ptr - arg))
1339                        file_spec = true;
1340        }
1341
1342        ptr = strpbrk(arg, ";:+@%");
1343        if (ptr) {
1344                nc = *ptr;
1345                *ptr++ = '\0';
1346        }
1347
1348        if (arg[0] == '\0')
1349                tmp = NULL;
1350        else {
1351                tmp = strdup(arg);
1352                if (tmp == NULL)
1353                        return -ENOMEM;
1354        }
1355
1356        if (file_spec)
1357                pp->file = tmp;
1358        else {
1359                pp->function = tmp;
1360
1361                /*
1362                 * Keep pp->function even if this is absolute address,
1363                 * so it can mark whether abs_address is valid.
1364                 * Which make 'perf probe lib.bin 0x0' possible.
1365                 *
1366                 * Note that checking length of tmp is not needed
1367                 * because when we access tmp[1] we know tmp[0] is '0',
1368                 * so tmp[1] should always valid (but could be '\0').
1369                 */
1370                if (tmp && !strncmp(tmp, "0x", 2)) {
1371                        pp->abs_address = strtoul(pp->function, &tmp, 0);
1372                        if (*tmp != '\0') {
1373                                semantic_error("Invalid absolute address.\n");
1374                                return -EINVAL;
1375                        }
1376                }
1377        }
1378
1379        /* Parse other options */
1380        while (ptr) {
1381                arg = ptr;
1382                c = nc;
1383                if (c == ';') { /* Lazy pattern must be the last part */
1384                        pp->lazy_line = strdup(arg);
1385                        if (pp->lazy_line == NULL)
1386                                return -ENOMEM;
1387                        break;
1388                }
1389                ptr = strpbrk(arg, ";:+@%");
1390                if (ptr) {
1391                        nc = *ptr;
1392                        *ptr++ = '\0';
1393                }
1394                switch (c) {
1395                case ':':       /* Line number */
1396                        pp->line = strtoul(arg, &tmp, 0);
1397                        if (*tmp != '\0') {
1398                                semantic_error("There is non-digit char"
1399                                               " in line number.\n");
1400                                return -EINVAL;
1401                        }
1402                        break;
1403                case '+':       /* Byte offset from a symbol */
1404                        pp->offset = strtoul(arg, &tmp, 0);
1405                        if (*tmp != '\0') {
1406                                semantic_error("There is non-digit character"
1407                                                " in offset.\n");
1408                                return -EINVAL;
1409                        }
1410                        break;
1411                case '@':       /* File name */
1412                        if (pp->file) {
1413                                semantic_error("SRC@SRC is not allowed.\n");
1414                                return -EINVAL;
1415                        }
1416                        pp->file = strdup(arg);
1417                        if (pp->file == NULL)
1418                                return -ENOMEM;
1419                        break;
1420                case '%':       /* Probe places */
1421                        if (strcmp(arg, "return") == 0) {
1422                                pp->retprobe = 1;
1423                        } else {        /* Others not supported yet */
1424                                semantic_error("%%%s is not supported.\n", arg);
1425                                return -ENOTSUP;
1426                        }
1427                        break;
1428                default:        /* Buggy case */
1429                        pr_err("This program has a bug at %s:%d.\n",
1430                                __FILE__, __LINE__);
1431                        return -ENOTSUP;
1432                        break;
1433                }
1434        }
1435
1436        /* Exclusion check */
1437        if (pp->lazy_line && pp->line) {
1438                semantic_error("Lazy pattern can't be used with"
1439                               " line number.\n");
1440                return -EINVAL;
1441        }
1442
1443        if (pp->lazy_line && pp->offset) {
1444                semantic_error("Lazy pattern can't be used with offset.\n");
1445                return -EINVAL;
1446        }
1447
1448        if (pp->line && pp->offset) {
1449                semantic_error("Offset can't be used with line number.\n");
1450                return -EINVAL;
1451        }
1452
1453        if (!pp->line && !pp->lazy_line && pp->file && !pp->function) {
1454                semantic_error("File always requires line number or "
1455                               "lazy pattern.\n");
1456                return -EINVAL;
1457        }
1458
1459        if (pp->offset && !pp->function) {
1460                semantic_error("Offset requires an entry function.\n");
1461                return -EINVAL;
1462        }
1463
1464        if (pp->retprobe && !pp->function) {
1465                semantic_error("Return probe requires an entry function.\n");
1466                return -EINVAL;
1467        }
1468
1469        if ((pp->offset || pp->line || pp->lazy_line) && pp->retprobe) {
1470                semantic_error("Offset/Line/Lazy pattern can't be used with "
1471                               "return probe.\n");
1472                return -EINVAL;
1473        }
1474
1475        pr_debug("symbol:%s file:%s line:%d offset:%lu return:%d lazy:%s\n",
1476                 pp->function, pp->file, pp->line, pp->offset, pp->retprobe,
1477                 pp->lazy_line);
1478        return 0;
1479}
1480
1481/* Parse perf-probe event argument */
1482static int parse_perf_probe_arg(char *str, struct perf_probe_arg *arg)
1483{
1484        char *tmp, *goodname;
1485        struct perf_probe_arg_field **fieldp;
1486
1487        pr_debug("parsing arg: %s into ", str);
1488
1489        tmp = strchr(str, '=');
1490        if (tmp) {
1491                arg->name = strndup(str, tmp - str);
1492                if (arg->name == NULL)
1493                        return -ENOMEM;
1494                pr_debug("name:%s ", arg->name);
1495                str = tmp + 1;
1496        }
1497
1498        tmp = strchr(str, ':');
1499        if (tmp) {      /* Type setting */
1500                *tmp = '\0';
1501                arg->type = strdup(tmp + 1);
1502                if (arg->type == NULL)
1503                        return -ENOMEM;
1504                pr_debug("type:%s ", arg->type);
1505        }
1506
1507        tmp = strpbrk(str, "-.[");
1508        if (!is_c_varname(str) || !tmp) {
1509                /* A variable, register, symbol or special value */
1510                arg->var = strdup(str);
1511                if (arg->var == NULL)
1512                        return -ENOMEM;
1513                pr_debug("%s\n", arg->var);
1514                return 0;
1515        }
1516
1517        /* Structure fields or array element */
1518        arg->var = strndup(str, tmp - str);
1519        if (arg->var == NULL)
1520                return -ENOMEM;
1521        goodname = arg->var;
1522        pr_debug("%s, ", arg->var);
1523        fieldp = &arg->field;
1524
1525        do {
1526                *fieldp = zalloc(sizeof(struct perf_probe_arg_field));
1527                if (*fieldp == NULL)
1528                        return -ENOMEM;
1529                if (*tmp == '[') {      /* Array */
1530                        str = tmp;
1531                        (*fieldp)->index = strtol(str + 1, &tmp, 0);
1532                        (*fieldp)->ref = true;
1533                        if (*tmp != ']' || tmp == str + 1) {
1534                                semantic_error("Array index must be a"
1535                                                " number.\n");
1536                                return -EINVAL;
1537                        }
1538                        tmp++;
1539                        if (*tmp == '\0')
1540                                tmp = NULL;
1541                } else {                /* Structure */
1542                        if (*tmp == '.') {
1543                                str = tmp + 1;
1544                                (*fieldp)->ref = false;
1545                        } else if (tmp[1] == '>') {
1546                                str = tmp + 2;
1547                                (*fieldp)->ref = true;
1548                        } else {
1549                                semantic_error("Argument parse error: %s\n",
1550                                               str);
1551                                return -EINVAL;
1552                        }
1553                        tmp = strpbrk(str, "-.[");
1554                }
1555                if (tmp) {
1556                        (*fieldp)->name = strndup(str, tmp - str);
1557                        if ((*fieldp)->name == NULL)
1558                                return -ENOMEM;
1559                        if (*str != '[')
1560                                goodname = (*fieldp)->name;
1561                        pr_debug("%s(%d), ", (*fieldp)->name, (*fieldp)->ref);
1562                        fieldp = &(*fieldp)->next;
1563                }
1564        } while (tmp);
1565        (*fieldp)->name = strdup(str);
1566        if ((*fieldp)->name == NULL)
1567                return -ENOMEM;
1568        if (*str != '[')
1569                goodname = (*fieldp)->name;
1570        pr_debug("%s(%d)\n", (*fieldp)->name, (*fieldp)->ref);
1571
1572        /* If no name is specified, set the last field name (not array index)*/
1573        if (!arg->name) {
1574                arg->name = strdup(goodname);
1575                if (arg->name == NULL)
1576                        return -ENOMEM;
1577        }
1578        return 0;
1579}
1580
1581/* Parse perf-probe event command */
1582int parse_perf_probe_command(const char *cmd, struct perf_probe_event *pev)
1583{
1584        char **argv;
1585        int argc, i, ret = 0;
1586
1587        argv = argv_split(cmd, &argc);
1588        if (!argv) {
1589                pr_debug("Failed to split arguments.\n");
1590                return -ENOMEM;
1591        }
1592        if (argc - 1 > MAX_PROBE_ARGS) {
1593                semantic_error("Too many probe arguments (%d).\n", argc - 1);
1594                ret = -ERANGE;
1595                goto out;
1596        }
1597        /* Parse probe point */
1598        ret = parse_perf_probe_point(argv[0], pev);
1599        if (ret < 0)
1600                goto out;
1601
1602        /* Copy arguments and ensure return probe has no C argument */
1603        pev->nargs = argc - 1;
1604        pev->args = zalloc(sizeof(struct perf_probe_arg) * pev->nargs);
1605        if (pev->args == NULL) {
1606                ret = -ENOMEM;
1607                goto out;
1608        }
1609        for (i = 0; i < pev->nargs && ret >= 0; i++) {
1610                ret = parse_perf_probe_arg(argv[i + 1], &pev->args[i]);
1611                if (ret >= 0 &&
1612                    is_c_varname(pev->args[i].var) && pev->point.retprobe) {
1613                        semantic_error("You can't specify local variable for"
1614                                       " kretprobe.\n");
1615                        ret = -EINVAL;
1616                }
1617        }
1618out:
1619        argv_free(argv);
1620
1621        return ret;
1622}
1623
1624/* Returns true if *any* ARG is either C variable, $params or $vars. */
1625bool perf_probe_with_var(struct perf_probe_event *pev)
1626{
1627        int i = 0;
1628
1629        for (i = 0; i < pev->nargs; i++)
1630                if (is_c_varname(pev->args[i].var)              ||
1631                    !strcmp(pev->args[i].var, PROBE_ARG_PARAMS) ||
1632                    !strcmp(pev->args[i].var, PROBE_ARG_VARS))
1633                        return true;
1634        return false;
1635}
1636
1637/* Return true if this perf_probe_event requires debuginfo */
1638bool perf_probe_event_need_dwarf(struct perf_probe_event *pev)
1639{
1640        if (pev->point.file || pev->point.line || pev->point.lazy_line)
1641                return true;
1642
1643        if (perf_probe_with_var(pev))
1644                return true;
1645
1646        return false;
1647}
1648
1649/* Parse probe_events event into struct probe_point */
1650int parse_probe_trace_command(const char *cmd, struct probe_trace_event *tev)
1651{
1652        struct probe_trace_point *tp = &tev->point;
1653        char pr;
1654        char *p;
1655        char *argv0_str = NULL, *fmt, *fmt1_str, *fmt2_str, *fmt3_str;
1656        int ret, i, argc;
1657        char **argv;
1658
1659        pr_debug("Parsing probe_events: %s\n", cmd);
1660        argv = argv_split(cmd, &argc);
1661        if (!argv) {
1662                pr_debug("Failed to split arguments.\n");
1663                return -ENOMEM;
1664        }
1665        if (argc < 2) {
1666                semantic_error("Too few probe arguments.\n");
1667                ret = -ERANGE;
1668                goto out;
1669        }
1670
1671        /* Scan event and group name. */
1672        argv0_str = strdup(argv[0]);
1673        if (argv0_str == NULL) {
1674                ret = -ENOMEM;
1675                goto out;
1676        }
1677        fmt1_str = strtok_r(argv0_str, ":", &fmt);
1678        fmt2_str = strtok_r(NULL, "/", &fmt);
1679        fmt3_str = strtok_r(NULL, " \t", &fmt);
1680        if (fmt1_str == NULL || strlen(fmt1_str) != 1 || fmt2_str == NULL
1681            || fmt3_str == NULL) {
1682                semantic_error("Failed to parse event name: %s\n", argv[0]);
1683                ret = -EINVAL;
1684                goto out;
1685        }
1686        pr = fmt1_str[0];
1687        tev->group = strdup(fmt2_str);
1688        tev->event = strdup(fmt3_str);
1689        if (tev->group == NULL || tev->event == NULL) {
1690                ret = -ENOMEM;
1691                goto out;
1692        }
1693        pr_debug("Group:%s Event:%s probe:%c\n", tev->group, tev->event, pr);
1694
1695        tp->retprobe = (pr == 'r');
1696
1697        /* Scan module name(if there), function name and offset */
1698        p = strchr(argv[1], ':');
1699        if (p) {
1700                tp->module = strndup(argv[1], p - argv[1]);
1701                if (!tp->module) {
1702                        ret = -ENOMEM;
1703                        goto out;
1704                }
1705                tev->uprobes = (tp->module[0] == '/');
1706                p++;
1707        } else
1708                p = argv[1];
1709        fmt1_str = strtok_r(p, "+", &fmt);
1710        /* only the address started with 0x */
1711        if (fmt1_str[0] == '0') {
1712                /*
1713                 * Fix a special case:
1714                 * if address == 0, kernel reports something like:
1715                 * p:probe_libc/abs_0 /lib/libc-2.18.so:0x          (null) arg1=%ax
1716                 * Newer kernel may fix that, but we want to
1717                 * support old kernel also.
1718                 */
1719                if (strcmp(fmt1_str, "0x") == 0) {
1720                        if (!argv[2] || strcmp(argv[2], "(null)")) {
1721                                ret = -EINVAL;
1722                                goto out;
1723                        }
1724                        tp->address = 0;
1725
1726                        free(argv[2]);
1727                        for (i = 2; argv[i + 1] != NULL; i++)
1728                                argv[i] = argv[i + 1];
1729
1730                        argv[i] = NULL;
1731                        argc -= 1;
1732                } else
1733                        tp->address = strtoul(fmt1_str, NULL, 0);
1734        } else {
1735                /* Only the symbol-based probe has offset */
1736                tp->symbol = strdup(fmt1_str);
1737                if (tp->symbol == NULL) {
1738                        ret = -ENOMEM;
1739                        goto out;
1740                }
1741                fmt2_str = strtok_r(NULL, "", &fmt);
1742                if (fmt2_str == NULL)
1743                        tp->offset = 0;
1744                else
1745                        tp->offset = strtoul(fmt2_str, NULL, 10);
1746        }
1747
1748        tev->nargs = argc - 2;
1749        tev->args = zalloc(sizeof(struct probe_trace_arg) * tev->nargs);
1750        if (tev->args == NULL) {
1751                ret = -ENOMEM;
1752                goto out;
1753        }
1754        for (i = 0; i < tev->nargs; i++) {
1755                p = strchr(argv[i + 2], '=');
1756                if (p)  /* We don't need which register is assigned. */
1757                        *p++ = '\0';
1758                else
1759                        p = argv[i + 2];
1760                tev->args[i].name = strdup(argv[i + 2]);
1761                /* TODO: parse regs and offset */
1762                tev->args[i].value = strdup(p);
1763                if (tev->args[i].name == NULL || tev->args[i].value == NULL) {
1764                        ret = -ENOMEM;
1765                        goto out;
1766                }
1767        }
1768        ret = 0;
1769out:
1770        free(argv0_str);
1771        argv_free(argv);
1772        return ret;
1773}
1774
1775/* Compose only probe arg */
1776char *synthesize_perf_probe_arg(struct perf_probe_arg *pa)
1777{
1778        struct perf_probe_arg_field *field = pa->field;
1779        struct strbuf buf;
1780        char *ret = NULL;
1781        int err;
1782
1783        if (strbuf_init(&buf, 64) < 0)
1784                return NULL;
1785
1786        if (pa->name && pa->var)
1787                err = strbuf_addf(&buf, "%s=%s", pa->name, pa->var);
1788        else
1789                err = strbuf_addstr(&buf, pa->name ?: pa->var);
1790        if (err)
1791                goto out;
1792
1793        while (field) {
1794                if (field->name[0] == '[')
1795                        err = strbuf_addstr(&buf, field->name);
1796                else
1797                        err = strbuf_addf(&buf, "%s%s", field->ref ? "->" : ".",
1798                                          field->name);
1799                field = field->next;
1800                if (err)
1801                        goto out;
1802        }
1803
1804        if (pa->type)
1805                if (strbuf_addf(&buf, ":%s", pa->type) < 0)
1806                        goto out;
1807
1808        ret = strbuf_detach(&buf, NULL);
1809out:
1810        strbuf_release(&buf);
1811        return ret;
1812}
1813
1814/* Compose only probe point (not argument) */
1815char *synthesize_perf_probe_point(struct perf_probe_point *pp)
1816{
1817        struct strbuf buf;
1818        char *tmp, *ret = NULL;
1819        int len, err = 0;
1820
1821        if (strbuf_init(&buf, 64) < 0)
1822                return NULL;
1823
1824        if (pp->function) {
1825                if (strbuf_addstr(&buf, pp->function) < 0)
1826                        goto out;
1827                if (pp->offset)
1828                        err = strbuf_addf(&buf, "+%lu", pp->offset);
1829                else if (pp->line)
1830                        err = strbuf_addf(&buf, ":%d", pp->line);
1831                else if (pp->retprobe)
1832                        err = strbuf_addstr(&buf, "%return");
1833                if (err)
1834                        goto out;
1835        }
1836        if (pp->file) {
1837                tmp = pp->file;
1838                len = strlen(tmp);
1839                if (len > 30) {
1840                        tmp = strchr(pp->file + len - 30, '/');
1841                        tmp = tmp ? tmp + 1 : pp->file + len - 30;
1842                }
1843                err = strbuf_addf(&buf, "@%s", tmp);
1844                if (!err && !pp->function && pp->line)
1845                        err = strbuf_addf(&buf, ":%d", pp->line);
1846        }
1847        if (!err)
1848                ret = strbuf_detach(&buf, NULL);
1849out:
1850        strbuf_release(&buf);
1851        return ret;
1852}
1853
1854char *synthesize_perf_probe_command(struct perf_probe_event *pev)
1855{
1856        struct strbuf buf;
1857        char *tmp, *ret = NULL;
1858        int i;
1859
1860        if (strbuf_init(&buf, 64))
1861                return NULL;
1862        if (pev->event)
1863                if (strbuf_addf(&buf, "%s:%s=", pev->group ?: PERFPROBE_GROUP,
1864                                pev->event) < 0)
1865                        goto out;
1866
1867        tmp = synthesize_perf_probe_point(&pev->point);
1868        if (!tmp || strbuf_addstr(&buf, tmp) < 0)
1869                goto out;
1870        free(tmp);
1871
1872        for (i = 0; i < pev->nargs; i++) {
1873                tmp = synthesize_perf_probe_arg(pev->args + i);
1874                if (!tmp || strbuf_addf(&buf, " %s", tmp) < 0)
1875                        goto out;
1876                free(tmp);
1877        }
1878
1879        ret = strbuf_detach(&buf, NULL);
1880out:
1881        strbuf_release(&buf);
1882        return ret;
1883}
1884
1885static int __synthesize_probe_trace_arg_ref(struct probe_trace_arg_ref *ref,
1886                                            struct strbuf *buf, int depth)
1887{
1888        int err;
1889        if (ref->next) {
1890                depth = __synthesize_probe_trace_arg_ref(ref->next, buf,
1891                                                         depth + 1);
1892                if (depth < 0)
1893                        return depth;
1894        }
1895        err = strbuf_addf(buf, "%+ld(", ref->offset);
1896        return (err < 0) ? err : depth;
1897}
1898
1899static int synthesize_probe_trace_arg(struct probe_trace_arg *arg,
1900                                      struct strbuf *buf)
1901{
1902        struct probe_trace_arg_ref *ref = arg->ref;
1903        int depth = 0, err;
1904
1905        /* Argument name or separator */
1906        if (arg->name)
1907                err = strbuf_addf(buf, " %s=", arg->name);
1908        else
1909                err = strbuf_addch(buf, ' ');
1910        if (err)
1911                return err;
1912
1913        /* Special case: @XXX */
1914        if (arg->value[0] == '@' && arg->ref)
1915                        ref = ref->next;
1916
1917        /* Dereferencing arguments */
1918        if (ref) {
1919                depth = __synthesize_probe_trace_arg_ref(ref, buf, 1);
1920                if (depth < 0)
1921                        return depth;
1922        }
1923
1924        /* Print argument value */
1925        if (arg->value[0] == '@' && arg->ref)
1926                err = strbuf_addf(buf, "%s%+ld", arg->value, arg->ref->offset);
1927        else
1928                err = strbuf_addstr(buf, arg->value);
1929
1930        /* Closing */
1931        while (!err && depth--)
1932                err = strbuf_addch(buf, ')');
1933
1934        /* Print argument type */
1935        if (!err && arg->type)
1936                err = strbuf_addf(buf, ":%s", arg->type);
1937
1938        return err;
1939}
1940
1941char *synthesize_probe_trace_command(struct probe_trace_event *tev)
1942{
1943        struct probe_trace_point *tp = &tev->point;
1944        struct strbuf buf;
1945        char *ret = NULL;
1946        int i, err;
1947
1948        /* Uprobes must have tp->module */
1949        if (tev->uprobes && !tp->module)
1950                return NULL;
1951
1952        if (strbuf_init(&buf, 32) < 0)
1953                return NULL;
1954
1955        if (strbuf_addf(&buf, "%c:%s/%s ", tp->retprobe ? 'r' : 'p',
1956                        tev->group, tev->event) < 0)
1957                goto error;
1958        /*
1959         * If tp->address == 0, then this point must be a
1960         * absolute address uprobe.
1961         * try_to_find_absolute_address() should have made
1962         * tp->symbol to "0x0".
1963         */
1964        if (tev->uprobes && !tp->address) {
1965                if (!tp->symbol || strcmp(tp->symbol, "0x0"))
1966                        goto error;
1967        }
1968
1969        /* Use the tp->address for uprobes */
1970        if (tev->uprobes)
1971                err = strbuf_addf(&buf, "%s:0x%lx", tp->module, tp->address);
1972        else if (!strncmp(tp->symbol, "0x", 2))
1973                /* Absolute address. See try_to_find_absolute_address() */
1974                err = strbuf_addf(&buf, "%s%s0x%lx", tp->module ?: "",
1975                                  tp->module ? ":" : "", tp->address);
1976        else
1977                err = strbuf_addf(&buf, "%s%s%s+%lu", tp->module ?: "",
1978                                tp->module ? ":" : "", tp->symbol, tp->offset);
1979        if (err)
1980                goto error;
1981
1982        for (i = 0; i < tev->nargs; i++)
1983                if (synthesize_probe_trace_arg(&tev->args[i], &buf) < 0)
1984                        goto error;
1985
1986        ret = strbuf_detach(&buf, NULL);
1987error:
1988        strbuf_release(&buf);
1989        return ret;
1990}
1991
1992static int find_perf_probe_point_from_map(struct probe_trace_point *tp,
1993                                          struct perf_probe_point *pp,
1994                                          bool is_kprobe)
1995{
1996        struct symbol *sym = NULL;
1997        struct map *map;
1998        u64 addr = tp->address;
1999        int ret = -ENOENT;
2000
2001        if (!is_kprobe) {
2002                map = dso__new_map(tp->module);
2003                if (!map)
2004                        goto out;
2005                sym = map__find_symbol(map, addr);
2006        } else {
2007                if (tp->symbol && !addr) {
2008                        if (kernel_get_symbol_address_by_name(tp->symbol,
2009                                                &addr, true, false) < 0)
2010                                goto out;
2011                }
2012                if (addr) {
2013                        addr += tp->offset;
2014                        sym = __find_kernel_function(addr, &map);
2015                }
2016        }
2017
2018        if (!sym)
2019                goto out;
2020
2021        pp->retprobe = tp->retprobe;
2022        pp->offset = addr - map->unmap_ip(map, sym->start);
2023        pp->function = strdup(sym->name);
2024        ret = pp->function ? 0 : -ENOMEM;
2025
2026out:
2027        if (map && !is_kprobe) {
2028                map__put(map);
2029        }
2030
2031        return ret;
2032}
2033
2034static int convert_to_perf_probe_point(struct probe_trace_point *tp,
2035                                       struct perf_probe_point *pp,
2036                                       bool is_kprobe)
2037{
2038        char buf[128];
2039        int ret;
2040
2041        ret = find_perf_probe_point_from_dwarf(tp, pp, is_kprobe);
2042        if (!ret)
2043                return 0;
2044        ret = find_perf_probe_point_from_map(tp, pp, is_kprobe);
2045        if (!ret)
2046                return 0;
2047
2048        pr_debug("Failed to find probe point from both of dwarf and map.\n");
2049
2050        if (tp->symbol) {
2051                pp->function = strdup(tp->symbol);
2052                pp->offset = tp->offset;
2053        } else {
2054                ret = e_snprintf(buf, 128, "0x%" PRIx64, (u64)tp->address);
2055                if (ret < 0)
2056                        return ret;
2057                pp->function = strdup(buf);
2058                pp->offset = 0;
2059        }
2060        if (pp->function == NULL)
2061                return -ENOMEM;
2062
2063        pp->retprobe = tp->retprobe;
2064
2065        return 0;
2066}
2067
2068static int convert_to_perf_probe_event(struct probe_trace_event *tev,
2069                               struct perf_probe_event *pev, bool is_kprobe)
2070{
2071        struct strbuf buf = STRBUF_INIT;
2072        int i, ret;
2073
2074        /* Convert event/group name */
2075        pev->event = strdup(tev->event);
2076        pev->group = strdup(tev->group);
2077        if (pev->event == NULL || pev->group == NULL)
2078                return -ENOMEM;
2079
2080        /* Convert trace_point to probe_point */
2081        ret = convert_to_perf_probe_point(&tev->point, &pev->point, is_kprobe);
2082        if (ret < 0)
2083                return ret;
2084
2085        /* Convert trace_arg to probe_arg */
2086        pev->nargs = tev->nargs;
2087        pev->args = zalloc(sizeof(struct perf_probe_arg) * pev->nargs);
2088        if (pev->args == NULL)
2089                return -ENOMEM;
2090        for (i = 0; i < tev->nargs && ret >= 0; i++) {
2091                if (tev->args[i].name)
2092                        pev->args[i].name = strdup(tev->args[i].name);
2093                else {
2094                        if ((ret = strbuf_init(&buf, 32)) < 0)
2095                                goto error;
2096                        ret = synthesize_probe_trace_arg(&tev->args[i], &buf);
2097                        pev->args[i].name = strbuf_detach(&buf, NULL);
2098                }
2099                if (pev->args[i].name == NULL && ret >= 0)
2100                        ret = -ENOMEM;
2101        }
2102error:
2103        if (ret < 0)
2104                clear_perf_probe_event(pev);
2105
2106        return ret;
2107}
2108
2109void clear_perf_probe_event(struct perf_probe_event *pev)
2110{
2111        struct perf_probe_arg_field *field, *next;
2112        int i;
2113
2114        free(pev->event);
2115        free(pev->group);
2116        free(pev->target);
2117        clear_perf_probe_point(&pev->point);
2118
2119        for (i = 0; i < pev->nargs; i++) {
2120                free(pev->args[i].name);
2121                free(pev->args[i].var);
2122                free(pev->args[i].type);
2123                field = pev->args[i].field;
2124                while (field) {
2125                        next = field->next;
2126                        zfree(&field->name);
2127                        free(field);
2128                        field = next;
2129                }
2130        }
2131        free(pev->args);
2132        memset(pev, 0, sizeof(*pev));
2133}
2134
2135#define strdup_or_goto(str, label)      \
2136({ char *__p = NULL; if (str && !(__p = strdup(str))) goto label; __p; })
2137
2138static int perf_probe_point__copy(struct perf_probe_point *dst,
2139                                  struct perf_probe_point *src)
2140{
2141        dst->file = strdup_or_goto(src->file, out_err);
2142        dst->function = strdup_or_goto(src->function, out_err);
2143        dst->lazy_line = strdup_or_goto(src->lazy_line, out_err);
2144        dst->line = src->line;
2145        dst->retprobe = src->retprobe;
2146        dst->offset = src->offset;
2147        return 0;
2148
2149out_err:
2150        clear_perf_probe_point(dst);
2151        return -ENOMEM;
2152}
2153
2154static int perf_probe_arg__copy(struct perf_probe_arg *dst,
2155                                struct perf_probe_arg *src)
2156{
2157        struct perf_probe_arg_field *field, **ppfield;
2158
2159        dst->name = strdup_or_goto(src->name, out_err);
2160        dst->var = strdup_or_goto(src->var, out_err);
2161        dst->type = strdup_or_goto(src->type, out_err);
2162
2163        field = src->field;
2164        ppfield = &(dst->field);
2165        while (field) {
2166                *ppfield = zalloc(sizeof(*field));
2167                if (!*ppfield)
2168                        goto out_err;
2169                (*ppfield)->name = strdup_or_goto(field->name, out_err);
2170                (*ppfield)->index = field->index;
2171                (*ppfield)->ref = field->ref;
2172                field = field->next;
2173                ppfield = &((*ppfield)->next);
2174        }
2175        return 0;
2176out_err:
2177        return -ENOMEM;
2178}
2179
2180int perf_probe_event__copy(struct perf_probe_event *dst,
2181                           struct perf_probe_event *src)
2182{
2183        int i;
2184
2185        dst->event = strdup_or_goto(src->event, out_err);
2186        dst->group = strdup_or_goto(src->group, out_err);
2187        dst->target = strdup_or_goto(src->target, out_err);
2188        dst->uprobes = src->uprobes;
2189
2190        if (perf_probe_point__copy(&dst->point, &src->point) < 0)
2191                goto out_err;
2192
2193        dst->args = zalloc(sizeof(struct perf_probe_arg) * src->nargs);
2194        if (!dst->args)
2195                goto out_err;
2196        dst->nargs = src->nargs;
2197
2198        for (i = 0; i < src->nargs; i++)
2199                if (perf_probe_arg__copy(&dst->args[i], &src->args[i]) < 0)
2200                        goto out_err;
2201        return 0;
2202
2203out_err:
2204        clear_perf_probe_event(dst);
2205        return -ENOMEM;
2206}
2207
2208void clear_probe_trace_event(struct probe_trace_event *tev)
2209{
2210        struct probe_trace_arg_ref *ref, *next;
2211        int i;
2212
2213        free(tev->event);
2214        free(tev->group);
2215        free(tev->point.symbol);
2216        free(tev->point.realname);
2217        free(tev->point.module);
2218        for (i = 0; i < tev->nargs; i++) {
2219                free(tev->args[i].name);
2220                free(tev->args[i].value);
2221                free(tev->args[i].type);
2222                ref = tev->args[i].ref;
2223                while (ref) {
2224                        next = ref->next;
2225                        free(ref);
2226                        ref = next;
2227                }
2228        }
2229        free(tev->args);
2230        memset(tev, 0, sizeof(*tev));
2231}
2232
2233struct kprobe_blacklist_node {
2234        struct list_head list;
2235        unsigned long start;
2236        unsigned long end;
2237        char *symbol;
2238};
2239
2240static void kprobe_blacklist__delete(struct list_head *blacklist)
2241{
2242        struct kprobe_blacklist_node *node;
2243
2244        while (!list_empty(blacklist)) {
2245                node = list_first_entry(blacklist,
2246                                        struct kprobe_blacklist_node, list);
2247                list_del(&node->list);
2248                free(node->symbol);
2249                free(node);
2250        }
2251}
2252
2253static int kprobe_blacklist__load(struct list_head *blacklist)
2254{
2255        struct kprobe_blacklist_node *node;
2256        const char *__debugfs = debugfs__mountpoint();
2257        char buf[PATH_MAX], *p;
2258        FILE *fp;
2259        int ret;
2260
2261        if (__debugfs == NULL)
2262                return -ENOTSUP;
2263
2264        ret = e_snprintf(buf, PATH_MAX, "%s/kprobes/blacklist", __debugfs);
2265        if (ret < 0)
2266                return ret;
2267
2268        fp = fopen(buf, "r");
2269        if (!fp)
2270                return -errno;
2271
2272        ret = 0;
2273        while (fgets(buf, PATH_MAX, fp)) {
2274                node = zalloc(sizeof(*node));
2275                if (!node) {
2276                        ret = -ENOMEM;
2277                        break;
2278                }
2279                INIT_LIST_HEAD(&node->list);
2280                list_add_tail(&node->list, blacklist);
2281                if (sscanf(buf, "0x%lx-0x%lx", &node->start, &node->end) != 2) {
2282                        ret = -EINVAL;
2283                        break;
2284                }
2285                p = strchr(buf, '\t');
2286                if (p) {
2287                        p++;
2288                        if (p[strlen(p) - 1] == '\n')
2289                                p[strlen(p) - 1] = '\0';
2290                } else
2291                        p = (char *)"unknown";
2292                node->symbol = strdup(p);
2293                if (!node->symbol) {
2294                        ret = -ENOMEM;
2295                        break;
2296                }
2297                pr_debug2("Blacklist: 0x%lx-0x%lx, %s\n",
2298                          node->start, node->end, node->symbol);
2299                ret++;
2300        }
2301        if (ret < 0)
2302                kprobe_blacklist__delete(blacklist);
2303        fclose(fp);
2304
2305        return ret;
2306}
2307
2308static struct kprobe_blacklist_node *
2309kprobe_blacklist__find_by_address(struct list_head *blacklist,
2310                                  unsigned long address)
2311{
2312        struct kprobe_blacklist_node *node;
2313
2314        list_for_each_entry(node, blacklist, list) {
2315                if (node->start <= address && address <= node->end)
2316                        return node;
2317        }
2318
2319        return NULL;
2320}
2321
2322static LIST_HEAD(kprobe_blacklist);
2323
2324static void kprobe_blacklist__init(void)
2325{
2326        if (!list_empty(&kprobe_blacklist))
2327                return;
2328
2329        if (kprobe_blacklist__load(&kprobe_blacklist) < 0)
2330                pr_debug("No kprobe blacklist support, ignored\n");
2331}
2332
2333static void kprobe_blacklist__release(void)
2334{
2335        kprobe_blacklist__delete(&kprobe_blacklist);
2336}
2337
2338static bool kprobe_blacklist__listed(unsigned long address)
2339{
2340        return !!kprobe_blacklist__find_by_address(&kprobe_blacklist, address);
2341}
2342
2343static int perf_probe_event__sprintf(const char *group, const char *event,
2344                                     struct perf_probe_event *pev,
2345                                     const char *module,
2346                                     struct strbuf *result)
2347{
2348        int i, ret;
2349        char *buf;
2350
2351        if (asprintf(&buf, "%s:%s", group, event) < 0)
2352                return -errno;
2353        ret = strbuf_addf(result, "  %-20s (on ", buf);
2354        free(buf);
2355        if (ret)
2356                return ret;
2357
2358        /* Synthesize only event probe point */
2359        buf = synthesize_perf_probe_point(&pev->point);
2360        if (!buf)
2361                return -ENOMEM;
2362        ret = strbuf_addstr(result, buf);
2363        free(buf);
2364
2365        if (!ret && module)
2366                ret = strbuf_addf(result, " in %s", module);
2367
2368        if (!ret && pev->nargs > 0) {
2369                ret = strbuf_add(result, " with", 5);
2370                for (i = 0; !ret && i < pev->nargs; i++) {
2371                        buf = synthesize_perf_probe_arg(&pev->args[i]);
2372                        if (!buf)
2373                                return -ENOMEM;
2374                        ret = strbuf_addf(result, " %s", buf);
2375                        free(buf);
2376                }
2377        }
2378        if (!ret)
2379                ret = strbuf_addch(result, ')');
2380
2381        return ret;
2382}
2383
2384/* Show an event */
2385int show_perf_probe_event(const char *group, const char *event,
2386                          struct perf_probe_event *pev,
2387                          const char *module, bool use_stdout)
2388{
2389        struct strbuf buf = STRBUF_INIT;
2390        int ret;
2391
2392        ret = perf_probe_event__sprintf(group, event, pev, module, &buf);
2393        if (ret >= 0) {
2394                if (use_stdout)
2395                        printf("%s\n", buf.buf);
2396                else
2397                        pr_info("%s\n", buf.buf);
2398        }
2399        strbuf_release(&buf);
2400
2401        return ret;
2402}
2403
2404static bool filter_probe_trace_event(struct probe_trace_event *tev,
2405                                     struct strfilter *filter)
2406{
2407        char tmp[128];
2408
2409        /* At first, check the event name itself */
2410        if (strfilter__compare(filter, tev->event))
2411                return true;
2412
2413        /* Next, check the combination of name and group */
2414        if (e_snprintf(tmp, 128, "%s:%s", tev->group, tev->event) < 0)
2415                return false;
2416        return strfilter__compare(filter, tmp);
2417}
2418
2419static int __show_perf_probe_events(int fd, bool is_kprobe,
2420                                    struct strfilter *filter)
2421{
2422        int ret = 0;
2423        struct probe_trace_event tev;
2424        struct perf_probe_event pev;
2425        struct strlist *rawlist;
2426        struct str_node *ent;
2427
2428        memset(&tev, 0, sizeof(tev));
2429        memset(&pev, 0, sizeof(pev));
2430
2431        rawlist = probe_file__get_rawlist(fd);
2432        if (!rawlist)
2433                return -ENOMEM;
2434
2435        strlist__for_each_entry(ent, rawlist) {
2436                ret = parse_probe_trace_command(ent->s, &tev);
2437                if (ret >= 0) {
2438                        if (!filter_probe_trace_event(&tev, filter))
2439                                goto next;
2440                        ret = convert_to_perf_probe_event(&tev, &pev,
2441                                                                is_kprobe);
2442                        if (ret < 0)
2443                                goto next;
2444                        ret = show_perf_probe_event(pev.group, pev.event,
2445                                                    &pev, tev.point.module,
2446                                                    true);
2447                }
2448next:
2449                clear_perf_probe_event(&pev);
2450                clear_probe_trace_event(&tev);
2451                if (ret < 0)
2452                        break;
2453        }
2454        strlist__delete(rawlist);
2455        /* Cleanup cached debuginfo if needed */
2456        debuginfo_cache__exit();
2457
2458        return ret;
2459}
2460
2461/* List up current perf-probe events */
2462int show_perf_probe_events(struct strfilter *filter)
2463{
2464        int kp_fd, up_fd, ret;
2465
2466        setup_pager();
2467
2468        if (probe_conf.cache)
2469                return probe_cache__show_all_caches(filter);
2470
2471        ret = init_probe_symbol_maps(false);
2472        if (ret < 0)
2473                return ret;
2474
2475        ret = probe_file__open_both(&kp_fd, &up_fd, 0);
2476        if (ret < 0)
2477                return ret;
2478
2479        if (kp_fd >= 0)
2480                ret = __show_perf_probe_events(kp_fd, true, filter);
2481        if (up_fd >= 0 && ret >= 0)
2482                ret = __show_perf_probe_events(up_fd, false, filter);
2483        if (kp_fd > 0)
2484                close(kp_fd);
2485        if (up_fd > 0)
2486                close(up_fd);
2487        exit_probe_symbol_maps();
2488
2489        return ret;
2490}
2491
2492static int get_new_event_name(char *buf, size_t len, const char *base,
2493                              struct strlist *namelist, bool allow_suffix)
2494{
2495        int i, ret;
2496        char *p, *nbase;
2497
2498        if (*base == '.')
2499                base++;
2500        nbase = strdup(base);
2501        if (!nbase)
2502                return -ENOMEM;
2503
2504        /* Cut off the dot suffixes (e.g. .const, .isra)*/
2505        p = strchr(nbase, '.');
2506        if (p && p != nbase)
2507                *p = '\0';
2508
2509        /* Try no suffix number */
2510        ret = e_snprintf(buf, len, "%s", nbase);
2511        if (ret < 0) {
2512                pr_debug("snprintf() failed: %d\n", ret);
2513                goto out;
2514        }
2515        if (!strlist__has_entry(namelist, buf))
2516                goto out;
2517
2518        if (!allow_suffix) {
2519                pr_warning("Error: event \"%s\" already exists.\n"
2520                           " Hint: Remove existing event by 'perf probe -d'\n"
2521                           "       or force duplicates by 'perf probe -f'\n"
2522                           "       or set 'force=yes' in BPF source.\n",
2523                           buf);
2524                ret = -EEXIST;
2525                goto out;
2526        }
2527
2528        /* Try to add suffix */
2529        for (i = 1; i < MAX_EVENT_INDEX; i++) {
2530                ret = e_snprintf(buf, len, "%s_%d", nbase, i);
2531                if (ret < 0) {
2532                        pr_debug("snprintf() failed: %d\n", ret);
2533                        goto out;
2534                }
2535                if (!strlist__has_entry(namelist, buf))
2536                        break;
2537        }
2538        if (i == MAX_EVENT_INDEX) {
2539                pr_warning("Too many events are on the same function.\n");
2540                ret = -ERANGE;
2541        }
2542
2543out:
2544        free(nbase);
2545        return ret;
2546}
2547
2548/* Warn if the current kernel's uprobe implementation is old */
2549static void warn_uprobe_event_compat(struct probe_trace_event *tev)
2550{
2551        int i;
2552        char *buf = synthesize_probe_trace_command(tev);
2553
2554        /* Old uprobe event doesn't support memory dereference */
2555        if (!tev->uprobes || tev->nargs == 0 || !buf)
2556                goto out;
2557
2558        for (i = 0; i < tev->nargs; i++)
2559                if (strglobmatch(tev->args[i].value, "[$@+-]*")) {
2560                        pr_warning("Please upgrade your kernel to at least "
2561                                   "3.14 to have access to feature %s\n",
2562                                   tev->args[i].value);
2563                        break;
2564                }
2565out:
2566        free(buf);
2567}
2568
2569/* Set new name from original perf_probe_event and namelist */
2570static int probe_trace_event__set_name(struct probe_trace_event *tev,
2571                                       struct perf_probe_event *pev,
2572                                       struct strlist *namelist,
2573                                       bool allow_suffix)
2574{
2575        const char *event, *group;
2576        char buf[64];
2577        int ret;
2578
2579        /* If probe_event or trace_event already have the name, reuse it */
2580        if (pev->event && !pev->sdt)
2581                event = pev->event;
2582        else if (tev->event)
2583                event = tev->event;
2584        else {
2585                /* Or generate new one from probe point */
2586                if (pev->point.function &&
2587                        (strncmp(pev->point.function, "0x", 2) != 0) &&
2588                        !strisglob(pev->point.function))
2589                        event = pev->point.function;
2590                else
2591                        event = tev->point.realname;
2592        }
2593        if (pev->group && !pev->sdt)
2594                group = pev->group;
2595        else if (tev->group)
2596                group = tev->group;
2597        else
2598                group = PERFPROBE_GROUP;
2599
2600        /* Get an unused new event name */
2601        ret = get_new_event_name(buf, 64, event,
2602                                 namelist, allow_suffix);
2603        if (ret < 0)
2604                return ret;
2605
2606        event = buf;
2607
2608        tev->event = strdup(event);
2609        tev->group = strdup(group);
2610        if (tev->event == NULL || tev->group == NULL)
2611                return -ENOMEM;
2612
2613        /* Add added event name to namelist */
2614        strlist__add(namelist, event);
2615        return 0;
2616}
2617
2618static int __open_probe_file_and_namelist(bool uprobe,
2619                                          struct strlist **namelist)
2620{
2621        int fd;
2622
2623        fd = probe_file__open(PF_FL_RW | (uprobe ? PF_FL_UPROBE : 0));
2624        if (fd < 0)
2625                return fd;
2626
2627        /* Get current event names */
2628        *namelist = probe_file__get_namelist(fd);
2629        if (!(*namelist)) {
2630                pr_debug("Failed to get current event list.\n");
2631                close(fd);
2632                return -ENOMEM;
2633        }
2634        return fd;
2635}
2636
2637static int __add_probe_trace_events(struct perf_probe_event *pev,
2638                                     struct probe_trace_event *tevs,
2639                                     int ntevs, bool allow_suffix)
2640{
2641        int i, fd[2] = {-1, -1}, up, ret;
2642        struct probe_trace_event *tev = NULL;
2643        struct probe_cache *cache = NULL;
2644        struct strlist *namelist[2] = {NULL, NULL};
2645
2646        up = pev->uprobes ? 1 : 0;
2647        fd[up] = __open_probe_file_and_namelist(up, &namelist[up]);
2648        if (fd[up] < 0)
2649                return fd[up];
2650
2651        ret = 0;
2652        for (i = 0; i < ntevs; i++) {
2653                tev = &tevs[i];
2654                up = tev->uprobes ? 1 : 0;
2655                if (fd[up] == -1) {     /* Open the kprobe/uprobe_events */
2656                        fd[up] = __open_probe_file_and_namelist(up,
2657                                                                &namelist[up]);
2658                        if (fd[up] < 0)
2659                                goto close_out;
2660                }
2661                /* Skip if the symbol is out of .text or blacklisted */
2662                if (!tev->point.symbol && !pev->uprobes)
2663                        continue;
2664
2665                /* Set new name for tev (and update namelist) */
2666                ret = probe_trace_event__set_name(tev, pev, namelist[up],
2667                                                  allow_suffix);
2668                if (ret < 0)
2669                        break;
2670
2671                ret = probe_file__add_event(fd[up], tev);
2672                if (ret < 0)
2673                        break;
2674
2675                /*
2676                 * Probes after the first probe which comes from same
2677                 * user input are always allowed to add suffix, because
2678                 * there might be several addresses corresponding to
2679                 * one code line.
2680                 */
2681                allow_suffix = true;
2682        }
2683        if (ret == -EINVAL && pev->uprobes)
2684                warn_uprobe_event_compat(tev);
2685        if (ret == 0 && probe_conf.cache) {
2686                cache = probe_cache__new(pev->target);
2687                if (!cache ||
2688                    probe_cache__add_entry(cache, pev, tevs, ntevs) < 0 ||
2689                    probe_cache__commit(cache) < 0)
2690                        pr_warning("Failed to add event to probe cache\n");
2691                probe_cache__delete(cache);
2692        }
2693
2694close_out:
2695        for (up = 0; up < 2; up++) {
2696                strlist__delete(namelist[up]);
2697                if (fd[up] >= 0)
2698                        close(fd[up]);
2699        }
2700        return ret;
2701}
2702
2703static int find_probe_functions(struct map *map, char *name,
2704                                struct symbol **syms)
2705{
2706        int found = 0;
2707        struct symbol *sym;
2708        struct rb_node *tmp;
2709
2710        if (map__load(map) < 0)
2711                return 0;
2712
2713        map__for_each_symbol(map, sym, tmp) {
2714                if (strglobmatch(sym->name, name)) {
2715                        found++;
2716                        if (syms && found < probe_conf.max_probes)
2717                                syms[found - 1] = sym;
2718                }
2719        }
2720
2721        return found;
2722}
2723
2724void __weak arch__fix_tev_from_maps(struct perf_probe_event *pev __maybe_unused,
2725                                struct probe_trace_event *tev __maybe_unused,
2726                                struct map *map __maybe_unused,
2727                                struct symbol *sym __maybe_unused) { }
2728
2729/*
2730 * Find probe function addresses from map.
2731 * Return an error or the number of found probe_trace_event
2732 */
2733static int find_probe_trace_events_from_map(struct perf_probe_event *pev,
2734                                            struct probe_trace_event **tevs)
2735{
2736        struct map *map = NULL;
2737        struct ref_reloc_sym *reloc_sym = NULL;
2738        struct symbol *sym;
2739        struct symbol **syms = NULL;
2740        struct probe_trace_event *tev;
2741        struct perf_probe_point *pp = &pev->point;
2742        struct probe_trace_point *tp;
2743        int num_matched_functions;
2744        int ret, i, j, skipped = 0;
2745        char *mod_name;
2746
2747        map = get_target_map(pev->target, pev->uprobes);
2748        if (!map) {
2749                ret = -EINVAL;
2750                goto out;
2751        }
2752
2753        syms = malloc(sizeof(struct symbol *) * probe_conf.max_probes);
2754        if (!syms) {
2755                ret = -ENOMEM;
2756                goto out;
2757        }
2758
2759        /*
2760         * Load matched symbols: Since the different local symbols may have
2761         * same name but different addresses, this lists all the symbols.
2762         */
2763        num_matched_functions = find_probe_functions(map, pp->function, syms);
2764        if (num_matched_functions == 0) {
2765                pr_err("Failed to find symbol %s in %s\n", pp->function,
2766                        pev->target ? : "kernel");
2767                ret = -ENOENT;
2768                goto out;
2769        } else if (num_matched_functions > probe_conf.max_probes) {
2770                pr_err("Too many functions matched in %s\n",
2771                        pev->target ? : "kernel");
2772                ret = -E2BIG;
2773                goto out;
2774        }
2775
2776        /* Note that the symbols in the kmodule are not relocated */
2777        if (!pev->uprobes && !pp->retprobe && !pev->target) {
2778                reloc_sym = kernel_get_ref_reloc_sym();
2779                if (!reloc_sym) {
2780                        pr_warning("Relocated base symbol is not found!\n");
2781                        ret = -EINVAL;
2782                        goto out;
2783                }
2784        }
2785
2786        /* Setup result trace-probe-events */
2787        *tevs = zalloc(sizeof(*tev) * num_matched_functions);
2788        if (!*tevs) {
2789                ret = -ENOMEM;
2790                goto out;
2791        }
2792
2793        ret = 0;
2794
2795        for (j = 0; j < num_matched_functions; j++) {
2796                sym = syms[j];
2797
2798                tev = (*tevs) + ret;
2799                tp = &tev->point;
2800                if (ret == num_matched_functions) {
2801                        pr_warning("Too many symbols are listed. Skip it.\n");
2802                        break;
2803                }
2804                ret++;
2805
2806                if (pp->offset > sym->end - sym->start) {
2807                        pr_warning("Offset %ld is bigger than the size of %s\n",
2808                                   pp->offset, sym->name);
2809                        ret = -ENOENT;
2810                        goto err_out;
2811                }
2812                /* Add one probe point */
2813                tp->address = map->unmap_ip(map, sym->start) + pp->offset;
2814
2815                /* Check the kprobe (not in module) is within .text  */
2816                if (!pev->uprobes && !pev->target &&
2817                    kprobe_warn_out_range(sym->name, tp->address)) {
2818                        tp->symbol = NULL;      /* Skip it */
2819                        skipped++;
2820                } else if (reloc_sym) {
2821                        tp->symbol = strdup_or_goto(reloc_sym->name, nomem_out);
2822                        tp->offset = tp->address - reloc_sym->addr;
2823                } else {
2824                        tp->symbol = strdup_or_goto(sym->name, nomem_out);
2825                        tp->offset = pp->offset;
2826                }
2827                tp->realname = strdup_or_goto(sym->name, nomem_out);
2828
2829                tp->retprobe = pp->retprobe;
2830                if (pev->target) {
2831                        if (pev->uprobes) {
2832                                tev->point.module = strdup_or_goto(pev->target,
2833                                                                   nomem_out);
2834                        } else {
2835                                mod_name = find_module_name(pev->target);
2836                                tev->point.module =
2837                                        strdup(mod_name ? mod_name : pev->target);
2838                                free(mod_name);
2839                                if (!tev->point.module)
2840                                        goto nomem_out;
2841                        }
2842                }
2843                tev->uprobes = pev->uprobes;
2844                tev->nargs = pev->nargs;
2845                if (tev->nargs) {
2846                        tev->args = zalloc(sizeof(struct probe_trace_arg) *
2847                                           tev->nargs);
2848                        if (tev->args == NULL)
2849                                goto nomem_out;
2850                }
2851                for (i = 0; i < tev->nargs; i++) {
2852                        if (pev->args[i].name)
2853                                tev->args[i].name =
2854                                        strdup_or_goto(pev->args[i].name,
2855                                                        nomem_out);
2856
2857                        tev->args[i].value = strdup_or_goto(pev->args[i].var,
2858                                                            nomem_out);
2859                        if (pev->args[i].type)
2860                                tev->args[i].type =
2861                                        strdup_or_goto(pev->args[i].type,
2862                                                        nomem_out);
2863                }
2864                arch__fix_tev_from_maps(pev, tev, map, sym);
2865        }
2866        if (ret == skipped) {
2867                ret = -ENOENT;
2868                goto err_out;
2869        }
2870
2871out:
2872        put_target_map(map, pev->uprobes);
2873        free(syms);
2874        return ret;
2875
2876nomem_out:
2877        ret = -ENOMEM;
2878err_out:
2879        clear_probe_trace_events(*tevs, num_matched_functions);
2880        zfree(tevs);
2881        goto out;
2882}
2883
2884static int try_to_find_absolute_address(struct perf_probe_event *pev,
2885                                        struct probe_trace_event **tevs)
2886{
2887        struct perf_probe_point *pp = &pev->point;
2888        struct probe_trace_event *tev;
2889        struct probe_trace_point *tp;
2890        int i, err;
2891
2892        if (!(pev->point.function && !strncmp(pev->point.function, "0x", 2)))
2893                return -EINVAL;
2894        if (perf_probe_event_need_dwarf(pev))
2895                return -EINVAL;
2896
2897        /*
2898         * This is 'perf probe /lib/libc.so 0xabcd'. Try to probe at
2899         * absolute address.
2900         *
2901         * Only one tev can be generated by this.
2902         */
2903        *tevs = zalloc(sizeof(*tev));
2904        if (!*tevs)
2905                return -ENOMEM;
2906
2907        tev = *tevs;
2908        tp = &tev->point;
2909
2910        /*
2911         * Don't use tp->offset, use address directly, because
2912         * in synthesize_probe_trace_command() address cannot be
2913         * zero.
2914         */
2915        tp->address = pev->point.abs_address;
2916        tp->retprobe = pp->retprobe;
2917        tev->uprobes = pev->uprobes;
2918
2919        err = -ENOMEM;
2920        /*
2921         * Give it a '0x' leading symbol name.
2922         * In __add_probe_trace_events, a NULL symbol is interpreted as
2923         * invalud.
2924         */
2925        if (asprintf(&tp->symbol, "0x%lx", tp->address) < 0)
2926                goto errout;
2927
2928        /* For kprobe, check range */
2929        if ((!tev->uprobes) &&
2930            (kprobe_warn_out_range(tev->point.symbol,
2931                                   tev->point.address))) {
2932                err = -EACCES;
2933                goto errout;
2934        }
2935
2936        if (asprintf(&tp->realname, "abs_%lx", tp->address) < 0)
2937                goto errout;
2938
2939        if (pev->target) {
2940                tp->module = strdup(pev->target);
2941                if (!tp->module)
2942                        goto errout;
2943        }
2944
2945        if (tev->group) {
2946                tev->group = strdup(pev->group);
2947                if (!tev->group)
2948                        goto errout;
2949        }
2950
2951        if (pev->event) {
2952                tev->event = strdup(pev->event);
2953                if (!tev->event)
2954                        goto errout;
2955        }
2956
2957        tev->nargs = pev->nargs;
2958        tev->args = zalloc(sizeof(struct probe_trace_arg) * tev->nargs);
2959        if (!tev->args) {
2960                err = -ENOMEM;
2961                goto errout;
2962        }
2963        for (i = 0; i < tev->nargs; i++)
2964                copy_to_probe_trace_arg(&tev->args[i], &pev->args[i]);
2965
2966        return 1;
2967
2968errout:
2969        if (*tevs) {
2970                clear_probe_trace_events(*tevs, 1);
2971                *tevs = NULL;
2972        }
2973        return err;
2974}
2975
2976/* Concatinate two arrays */
2977static void *memcat(void *a, size_t sz_a, void *b, size_t sz_b)
2978{
2979        void *ret;
2980
2981        ret = malloc(sz_a + sz_b);
2982        if (ret) {
2983                memcpy(ret, a, sz_a);
2984                memcpy(ret + sz_a, b, sz_b);
2985        }
2986        return ret;
2987}
2988
2989static int
2990concat_probe_trace_events(struct probe_trace_event **tevs, int *ntevs,
2991                          struct probe_trace_event **tevs2, int ntevs2)
2992{
2993        struct probe_trace_event *new_tevs;
2994        int ret = 0;
2995
2996        if (ntevs == 0) {
2997                *tevs = *tevs2;
2998                *ntevs = ntevs2;
2999                *tevs2 = NULL;
3000                return 0;
3001        }
3002
3003        if (*ntevs + ntevs2 > probe_conf.max_probes)
3004                ret = -E2BIG;
3005        else {
3006                /* Concatinate the array of probe_trace_event */
3007                new_tevs = memcat(*tevs, (*ntevs) * sizeof(**tevs),
3008                                  *tevs2, ntevs2 * sizeof(**tevs2));
3009                if (!new_tevs)
3010                        ret = -ENOMEM;
3011                else {
3012                        free(*tevs);
3013                        *tevs = new_tevs;
3014                        *ntevs += ntevs2;
3015                }
3016        }
3017        if (ret < 0)
3018                clear_probe_trace_events(*tevs2, ntevs2);
3019        zfree(tevs2);
3020
3021        return ret;
3022}
3023
3024/*
3025 * Try to find probe_trace_event from given probe caches. Return the number
3026 * of cached events found, if an error occurs return the error.
3027 */
3028static int find_cached_events(struct perf_probe_event *pev,
3029                              struct probe_trace_event **tevs,
3030                              const char *target)
3031{
3032        struct probe_cache *cache;
3033        struct probe_cache_entry *entry;
3034        struct probe_trace_event *tmp_tevs = NULL;
3035        int ntevs = 0;
3036        int ret = 0;
3037
3038        cache = probe_cache__new(target);
3039        /* Return 0 ("not found") if the target has no probe cache. */
3040        if (!cache)
3041                return 0;
3042
3043        for_each_probe_cache_entry(entry, cache) {
3044                /* Skip the cache entry which has no name */
3045                if (!entry->pev.event || !entry->pev.group)
3046                        continue;
3047                if ((!pev->group || strglobmatch(entry->pev.group, pev->group)) &&
3048                    strglobmatch(entry->pev.event, pev->event)) {
3049                        ret = probe_cache_entry__get_event(entry, &tmp_tevs);
3050                        if (ret > 0)
3051                                ret = concat_probe_trace_events(tevs, &ntevs,
3052                                                                &tmp_tevs, ret);
3053                        if (ret < 0)
3054                                break;
3055                }
3056        }
3057        probe_cache__delete(cache);
3058        if (ret < 0) {
3059                clear_probe_trace_events(*tevs, ntevs);
3060                zfree(tevs);
3061        } else {
3062                ret = ntevs;
3063                if (ntevs > 0 && target && target[0] == '/')
3064                        pev->uprobes = true;
3065        }
3066
3067        return ret;
3068}
3069
3070/* Try to find probe_trace_event from all probe caches */
3071static int find_cached_events_all(struct perf_probe_event *pev,
3072                                   struct probe_trace_event **tevs)
3073{
3074        struct probe_trace_event *tmp_tevs = NULL;
3075        struct strlist *bidlist;
3076        struct str_node *nd;
3077        char *pathname;
3078        int ntevs = 0;
3079        int ret;
3080
3081        /* Get the buildid list of all valid caches */
3082        bidlist = build_id_cache__list_all(true);
3083        if (!bidlist) {
3084                ret = -errno;
3085                pr_debug("Failed to get buildids: %d\n", ret);
3086                return ret;
3087        }
3088
3089        ret = 0;
3090        strlist__for_each_entry(nd, bidlist) {
3091                pathname = build_id_cache__origname(nd->s);
3092                ret = find_cached_events(pev, &tmp_tevs, pathname);
3093                /* In the case of cnt == 0, we just skip it */
3094                if (ret > 0)
3095                        ret = concat_probe_trace_events(tevs, &ntevs,
3096                                                        &tmp_tevs, ret);
3097                free(pathname);
3098                if (ret < 0)
3099                        break;
3100        }
3101        strlist__delete(bidlist);
3102
3103        if (ret < 0) {
3104                clear_probe_trace_events(*tevs, ntevs);
3105                zfree(tevs);
3106        } else
3107                ret = ntevs;
3108
3109        return ret;
3110}
3111
3112static int find_probe_trace_events_from_cache(struct perf_probe_event *pev,
3113                                              struct probe_trace_event **tevs)
3114{
3115        struct probe_cache *cache;
3116        struct probe_cache_entry *entry;
3117        struct probe_trace_event *tev;
3118        struct str_node *node;
3119        int ret, i;
3120
3121        if (pev->sdt) {
3122                /* For SDT/cached events, we use special search functions */
3123                if (!pev->target)
3124                        return find_cached_events_all(pev, tevs);
3125                else
3126                        return find_cached_events(pev, tevs, pev->target);
3127        }
3128        cache = probe_cache__new(pev->target);
3129        if (!cache)
3130                return 0;
3131
3132        entry = probe_cache__find(cache, pev);
3133        if (!entry) {
3134                /* SDT must be in the cache */
3135                ret = pev->sdt ? -ENOENT : 0;
3136                goto out;
3137        }
3138
3139        ret = strlist__nr_entries(entry->tevlist);
3140        if (ret > probe_conf.max_probes) {
3141                pr_debug("Too many entries matched in the cache of %s\n",
3142                         pev->target ? : "kernel");
3143                ret = -E2BIG;
3144                goto out;
3145        }
3146
3147        *tevs = zalloc(ret * sizeof(*tev));
3148        if (!*tevs) {
3149                ret = -ENOMEM;
3150                goto out;
3151        }
3152
3153        i = 0;
3154        strlist__for_each_entry(node, entry->tevlist) {
3155                tev = &(*tevs)[i++];
3156                ret = parse_probe_trace_command(node->s, tev);
3157                if (ret < 0)
3158                        goto out;
3159                /* Set the uprobes attribute as same as original */
3160                tev->uprobes = pev->uprobes;
3161        }
3162        ret = i;
3163
3164out:
3165        probe_cache__delete(cache);
3166        return ret;
3167}
3168
3169static int convert_to_probe_trace_events(struct perf_probe_event *pev,
3170                                         struct probe_trace_event **tevs)
3171{
3172        int ret;
3173
3174        if (!pev->group && !pev->sdt) {
3175                /* Set group name if not given */
3176                if (!pev->uprobes) {
3177                        pev->group = strdup(PERFPROBE_GROUP);
3178                        ret = pev->group ? 0 : -ENOMEM;
3179                } else
3180                        ret = convert_exec_to_group(pev->target, &pev->group);
3181                if (ret != 0) {
3182                        pr_warning("Failed to make a group name.\n");
3183                        return ret;
3184                }
3185        }
3186
3187        ret = try_to_find_absolute_address(pev, tevs);
3188        if (ret > 0)
3189                return ret;
3190
3191        /* At first, we need to lookup cache entry */
3192        ret = find_probe_trace_events_from_cache(pev, tevs);
3193        if (ret > 0 || pev->sdt)        /* SDT can be found only in the cache */
3194                return ret == 0 ? -ENOENT : ret; /* Found in probe cache */
3195
3196        /* Convert perf_probe_event with debuginfo */
3197        ret = try_to_find_probe_trace_events(pev, tevs);
3198        if (ret != 0)
3199                return ret;     /* Found in debuginfo or got an error */
3200
3201        return find_probe_trace_events_from_map(pev, tevs);
3202}
3203
3204int convert_perf_probe_events(struct perf_probe_event *pevs, int npevs)
3205{
3206        int i, ret;
3207
3208        /* Loop 1: convert all events */
3209        for (i = 0; i < npevs; i++) {
3210                /* Init kprobe blacklist if needed */
3211                if (!pevs[i].uprobes)
3212                        kprobe_blacklist__init();
3213                /* Convert with or without debuginfo */
3214                ret  = convert_to_probe_trace_events(&pevs[i], &pevs[i].tevs);
3215                if (ret < 0)
3216                        return ret;
3217                pevs[i].ntevs = ret;
3218        }
3219        /* This just release blacklist only if allocated */
3220        kprobe_blacklist__release();
3221
3222        return 0;
3223}
3224
3225static int show_probe_trace_event(struct probe_trace_event *tev)
3226{
3227        char *buf = synthesize_probe_trace_command(tev);
3228
3229        if (!buf) {
3230                pr_debug("Failed to synthesize probe trace event.\n");
3231                return -EINVAL;
3232        }
3233
3234        /* Showing definition always go stdout */
3235        printf("%s\n", buf);
3236        free(buf);
3237
3238        return 0;
3239}
3240
3241int show_probe_trace_events(struct perf_probe_event *pevs, int npevs)
3242{
3243        struct strlist *namelist = strlist__new(NULL, NULL);
3244        struct probe_trace_event *tev;
3245        struct perf_probe_event *pev;
3246        int i, j, ret = 0;
3247
3248        if (!namelist)
3249                return -ENOMEM;
3250
3251        for (j = 0; j < npevs && !ret; j++) {
3252                pev = &pevs[j];
3253                for (i = 0; i < pev->ntevs && !ret; i++) {
3254                        tev = &pev->tevs[i];
3255                        /* Skip if the symbol is out of .text or blacklisted */
3256                        if (!tev->point.symbol && !pev->uprobes)
3257                                continue;
3258
3259                        /* Set new name for tev (and update namelist) */
3260                        ret = probe_trace_event__set_name(tev, pev,
3261                                                          namelist, true);
3262                        if (!ret)
3263                                ret = show_probe_trace_event(tev);
3264                }
3265        }
3266        strlist__delete(namelist);
3267
3268        return ret;
3269}
3270
3271int apply_perf_probe_events(struct perf_probe_event *pevs, int npevs)
3272{
3273        int i, ret = 0;
3274
3275        /* Loop 2: add all events */
3276        for (i = 0; i < npevs; i++) {
3277                ret = __add_probe_trace_events(&pevs[i], pevs[i].tevs,
3278                                               pevs[i].ntevs,
3279                                               probe_conf.force_add);
3280                if (ret < 0)
3281                        break;
3282        }
3283        return ret;
3284}
3285
3286void cleanup_perf_probe_events(struct perf_probe_event *pevs, int npevs)
3287{
3288        int i, j;
3289
3290        /* Loop 3: cleanup and free trace events  */
3291        for (i = 0; i < npevs; i++) {
3292                for (j = 0; j < pevs[i].ntevs; j++)
3293                        clear_probe_trace_event(&pevs[i].tevs[j]);
3294                zfree(&pevs[i].tevs);
3295                pevs[i].ntevs = 0;
3296                clear_perf_probe_event(&pevs[i]);
3297        }
3298}
3299
3300int add_perf_probe_events(struct perf_probe_event *pevs, int npevs)
3301{
3302        int ret;
3303
3304        ret = init_probe_symbol_maps(pevs->uprobes);
3305        if (ret < 0)
3306                return ret;
3307
3308        ret = convert_perf_probe_events(pevs, npevs);
3309        if (ret == 0)
3310                ret = apply_perf_probe_events(pevs, npevs);
3311
3312        cleanup_perf_probe_events(pevs, npevs);
3313
3314        exit_probe_symbol_maps();
3315        return ret;
3316}
3317
3318int del_perf_probe_events(struct strfilter *filter)
3319{
3320        int ret, ret2, ufd = -1, kfd = -1;
3321        char *str = strfilter__string(filter);
3322
3323        if (!str)
3324                return -EINVAL;
3325
3326        /* Get current event names */
3327        ret = probe_file__open_both(&kfd, &ufd, PF_FL_RW);
3328        if (ret < 0)
3329                goto out;
3330
3331        ret = probe_file__del_events(kfd, filter);
3332        if (ret < 0 && ret != -ENOENT)
3333                goto error;
3334
3335        ret2 = probe_file__del_events(ufd, filter);
3336        if (ret2 < 0 && ret2 != -ENOENT) {
3337                ret = ret2;
3338                goto error;
3339        }
3340        ret = 0;
3341
3342error:
3343        if (kfd >= 0)
3344                close(kfd);
3345        if (ufd >= 0)
3346                close(ufd);
3347out:
3348        free(str);
3349
3350        return ret;
3351}
3352
3353int show_available_funcs(const char *target, struct strfilter *_filter,
3354                                        bool user)
3355{
3356        struct rb_node *nd;
3357        struct map *map;
3358        int ret;
3359
3360        ret = init_probe_symbol_maps(user);
3361        if (ret < 0)
3362                return ret;
3363
3364        /* Get a symbol map */
3365        if (user)
3366                map = dso__new_map(target);
3367        else
3368                map = kernel_get_module_map(target);
3369        if (!map) {
3370                pr_err("Failed to get a map for %s\n", (target) ? : "kernel");
3371                return -EINVAL;
3372        }
3373
3374        ret = map__load(map);
3375        if (ret) {
3376                if (ret == -2) {
3377                        char *str = strfilter__string(_filter);
3378                        pr_err("Failed to find symbols matched to \"%s\"\n",
3379                               str);
3380                        free(str);
3381                } else
3382                        pr_err("Failed to load symbols in %s\n",
3383                               (target) ? : "kernel");
3384                goto end;
3385        }
3386        if (!dso__sorted_by_name(map->dso, map->type))
3387                dso__sort_by_name(map->dso, map->type);
3388
3389        /* Show all (filtered) symbols */
3390        setup_pager();
3391
3392        for (nd = rb_first(&map->dso->symbol_names[map->type]); nd; nd = rb_next(nd)) {
3393                struct symbol_name_rb_node *pos = rb_entry(nd, struct symbol_name_rb_node, rb_node);
3394
3395                if (strfilter__compare(_filter, pos->sym.name))
3396                        printf("%s\n", pos->sym.name);
3397        }
3398
3399end:
3400        if (user) {
3401                map__put(map);
3402        }
3403        exit_probe_symbol_maps();
3404
3405        return ret;
3406}
3407
3408int copy_to_probe_trace_arg(struct probe_trace_arg *tvar,
3409                            struct perf_probe_arg *pvar)
3410{
3411        tvar->value = strdup(pvar->var);
3412        if (tvar->value == NULL)
3413                return -ENOMEM;
3414        if (pvar->type) {
3415                tvar->type = strdup(pvar->type);
3416                if (tvar->type == NULL)
3417                        return -ENOMEM;
3418        }
3419        if (pvar->name) {
3420                tvar->name = strdup(pvar->name);
3421                if (tvar->name == NULL)
3422                        return -ENOMEM;
3423        } else
3424                tvar->name = NULL;
3425        return 0;
3426}
3427