linux/tools/perf/util/llvm-utils.c
<<
>>
Prefs
   1// SPDX-License-Identifier: GPL-2.0
   2/*
   3 * Copyright (C) 2015, Wang Nan <wangnan0@huawei.com>
   4 * Copyright (C) 2015, Huawei Inc.
   5 */
   6
   7#include <errno.h>
   8#include <limits.h>
   9#include <stdio.h>
  10#include <stdlib.h>
  11#include <linux/err.h>
  12#include <linux/zalloc.h>
  13#include "debug.h"
  14#include "llvm-utils.h"
  15#include "config.h"
  16#include "util.h"
  17#include <sys/wait.h>
  18#include <subcmd/exec-cmd.h>
  19
  20#define CLANG_BPF_CMD_DEFAULT_TEMPLATE                          \
  21                "$CLANG_EXEC -D__KERNEL__ -D__NR_CPUS__=$NR_CPUS "\
  22                "-DLINUX_VERSION_CODE=$LINUX_VERSION_CODE "     \
  23                "$CLANG_OPTIONS $PERF_BPF_INC_OPTIONS $KERNEL_INC_OPTIONS " \
  24                "-Wno-unused-value -Wno-pointer-sign "          \
  25                "-working-directory $WORKING_DIR "              \
  26                "-c \"$CLANG_SOURCE\" -target bpf $CLANG_EMIT_LLVM -O2 -o - $LLVM_OPTIONS_PIPE"
  27
  28struct llvm_param llvm_param = {
  29        .clang_path = "clang",
  30        .llc_path = "llc",
  31        .clang_bpf_cmd_template = CLANG_BPF_CMD_DEFAULT_TEMPLATE,
  32        .clang_opt = NULL,
  33        .opts = NULL,
  34        .kbuild_dir = NULL,
  35        .kbuild_opts = NULL,
  36        .user_set_param = false,
  37};
  38
  39int perf_llvm_config(const char *var, const char *value)
  40{
  41        if (!strstarts(var, "llvm."))
  42                return 0;
  43        var += sizeof("llvm.") - 1;
  44
  45        if (!strcmp(var, "clang-path"))
  46                llvm_param.clang_path = strdup(value);
  47        else if (!strcmp(var, "clang-bpf-cmd-template"))
  48                llvm_param.clang_bpf_cmd_template = strdup(value);
  49        else if (!strcmp(var, "clang-opt"))
  50                llvm_param.clang_opt = strdup(value);
  51        else if (!strcmp(var, "kbuild-dir"))
  52                llvm_param.kbuild_dir = strdup(value);
  53        else if (!strcmp(var, "kbuild-opts"))
  54                llvm_param.kbuild_opts = strdup(value);
  55        else if (!strcmp(var, "dump-obj"))
  56                llvm_param.dump_obj = !!perf_config_bool(var, value);
  57        else if (!strcmp(var, "opts"))
  58                llvm_param.opts = strdup(value);
  59        else {
  60                pr_debug("Invalid LLVM config option: %s\n", value);
  61                return -1;
  62        }
  63        llvm_param.user_set_param = true;
  64        return 0;
  65}
  66
  67static int
  68search_program(const char *def, const char *name,
  69               char *output)
  70{
  71        char *env, *path, *tmp = NULL;
  72        char buf[PATH_MAX];
  73        int ret;
  74
  75        output[0] = '\0';
  76        if (def && def[0] != '\0') {
  77                if (def[0] == '/') {
  78                        if (access(def, F_OK) == 0) {
  79                                strlcpy(output, def, PATH_MAX);
  80                                return 0;
  81                        }
  82                } else if (def[0] != '\0')
  83                        name = def;
  84        }
  85
  86        env = getenv("PATH");
  87        if (!env)
  88                return -1;
  89        env = strdup(env);
  90        if (!env)
  91                return -1;
  92
  93        ret = -ENOENT;
  94        path = strtok_r(env, ":",  &tmp);
  95        while (path) {
  96                scnprintf(buf, sizeof(buf), "%s/%s", path, name);
  97                if (access(buf, F_OK) == 0) {
  98                        strlcpy(output, buf, PATH_MAX);
  99                        ret = 0;
 100                        break;
 101                }
 102                path = strtok_r(NULL, ":", &tmp);
 103        }
 104
 105        free(env);
 106        return ret;
 107}
 108
 109#define READ_SIZE       4096
 110static int
 111read_from_pipe(const char *cmd, void **p_buf, size_t *p_read_sz)
 112{
 113        int err = 0;
 114        void *buf = NULL;
 115        FILE *file = NULL;
 116        size_t read_sz = 0, buf_sz = 0;
 117        char serr[STRERR_BUFSIZE];
 118
 119        file = popen(cmd, "r");
 120        if (!file) {
 121                pr_err("ERROR: unable to popen cmd: %s\n",
 122                       str_error_r(errno, serr, sizeof(serr)));
 123                return -EINVAL;
 124        }
 125
 126        while (!feof(file) && !ferror(file)) {
 127                /*
 128                 * Make buf_sz always have obe byte extra space so we
 129                 * can put '\0' there.
 130                 */
 131                if (buf_sz - read_sz < READ_SIZE + 1) {
 132                        void *new_buf;
 133
 134                        buf_sz = read_sz + READ_SIZE + 1;
 135                        new_buf = realloc(buf, buf_sz);
 136
 137                        if (!new_buf) {
 138                                pr_err("ERROR: failed to realloc memory\n");
 139                                err = -ENOMEM;
 140                                goto errout;
 141                        }
 142
 143                        buf = new_buf;
 144                }
 145                read_sz += fread(buf + read_sz, 1, READ_SIZE, file);
 146        }
 147
 148        if (buf_sz - read_sz < 1) {
 149                pr_err("ERROR: internal error\n");
 150                err = -EINVAL;
 151                goto errout;
 152        }
 153
 154        if (ferror(file)) {
 155                pr_err("ERROR: error occurred when reading from pipe: %s\n",
 156                       str_error_r(errno, serr, sizeof(serr)));
 157                err = -EIO;
 158                goto errout;
 159        }
 160
 161        err = WEXITSTATUS(pclose(file));
 162        file = NULL;
 163        if (err) {
 164                err = -EINVAL;
 165                goto errout;
 166        }
 167
 168        /*
 169         * If buf is string, give it terminal '\0' to make our life
 170         * easier. If buf is not string, that '\0' is out of space
 171         * indicated by read_sz so caller won't even notice it.
 172         */
 173        ((char *)buf)[read_sz] = '\0';
 174
 175        if (!p_buf)
 176                free(buf);
 177        else
 178                *p_buf = buf;
 179
 180        if (p_read_sz)
 181                *p_read_sz = read_sz;
 182        return 0;
 183
 184errout:
 185        if (file)
 186                pclose(file);
 187        free(buf);
 188        if (p_buf)
 189                *p_buf = NULL;
 190        if (p_read_sz)
 191                *p_read_sz = 0;
 192        return err;
 193}
 194
 195static inline void
 196force_set_env(const char *var, const char *value)
 197{
 198        if (value) {
 199                setenv(var, value, 1);
 200                pr_debug("set env: %s=%s\n", var, value);
 201        } else {
 202                unsetenv(var);
 203                pr_debug("unset env: %s\n", var);
 204        }
 205}
 206
 207static void
 208version_notice(void)
 209{
 210        pr_err(
 211"     \tLLVM 3.7 or newer is required. Which can be found from http://llvm.org\n"
 212"     \tYou may want to try git trunk:\n"
 213"     \t\tgit clone http://llvm.org/git/llvm.git\n"
 214"     \t\t     and\n"
 215"     \t\tgit clone http://llvm.org/git/clang.git\n\n"
 216"     \tOr fetch the latest clang/llvm 3.7 from pre-built llvm packages for\n"
 217"     \tdebian/ubuntu:\n"
 218"     \t\thttp://llvm.org/apt\n\n"
 219"     \tIf you are using old version of clang, change 'clang-bpf-cmd-template'\n"
 220"     \toption in [llvm] section of ~/.perfconfig to:\n\n"
 221"     \t  \"$CLANG_EXEC $CLANG_OPTIONS $KERNEL_INC_OPTIONS $PERF_BPF_INC_OPTIONS \\\n"
 222"     \t     -working-directory $WORKING_DIR -c $CLANG_SOURCE \\\n"
 223"     \t     -emit-llvm -o - | /path/to/llc -march=bpf -filetype=obj -o -\"\n"
 224"     \t(Replace /path/to/llc with path to your llc)\n\n"
 225);
 226}
 227
 228static int detect_kbuild_dir(char **kbuild_dir)
 229{
 230        const char *test_dir = llvm_param.kbuild_dir;
 231        const char *prefix_dir = "";
 232        const char *suffix_dir = "";
 233
 234        char *autoconf_path;
 235
 236        int err;
 237
 238        if (!test_dir) {
 239                /* _UTSNAME_LENGTH is 65 */
 240                char release[128];
 241
 242                err = fetch_kernel_version(NULL, release,
 243                                           sizeof(release));
 244                if (err)
 245                        return -EINVAL;
 246
 247                test_dir = release;
 248                prefix_dir = "/lib/modules/";
 249                suffix_dir = "/build";
 250        }
 251
 252        err = asprintf(&autoconf_path, "%s%s%s/include/generated/autoconf.h",
 253                       prefix_dir, test_dir, suffix_dir);
 254        if (err < 0)
 255                return -ENOMEM;
 256
 257        if (access(autoconf_path, R_OK) == 0) {
 258                free(autoconf_path);
 259
 260                err = asprintf(kbuild_dir, "%s%s%s", prefix_dir, test_dir,
 261                               suffix_dir);
 262                if (err < 0)
 263                        return -ENOMEM;
 264                return 0;
 265        }
 266        free(autoconf_path);
 267        return -ENOENT;
 268}
 269
 270static const char *kinc_fetch_script =
 271"#!/usr/bin/env sh\n"
 272"if ! test -d \"$KBUILD_DIR\"\n"
 273"then\n"
 274"       exit 1\n"
 275"fi\n"
 276"if ! test -f \"$KBUILD_DIR/include/generated/autoconf.h\"\n"
 277"then\n"
 278"       exit 1\n"
 279"fi\n"
 280"TMPDIR=`mktemp -d`\n"
 281"if test -z \"$TMPDIR\"\n"
 282"then\n"
 283"    exit 1\n"
 284"fi\n"
 285"cat << EOF > $TMPDIR/Makefile\n"
 286"obj-y := dummy.o\n"
 287"\\$(obj)/%.o: \\$(src)/%.c\n"
 288"\t@echo -n \"\\$(NOSTDINC_FLAGS) \\$(LINUXINCLUDE) \\$(EXTRA_CFLAGS)\"\n"
 289"EOF\n"
 290"touch $TMPDIR/dummy.c\n"
 291"make -s -C $KBUILD_DIR M=$TMPDIR $KBUILD_OPTS dummy.o 2>/dev/null\n"
 292"RET=$?\n"
 293"rm -rf $TMPDIR\n"
 294"exit $RET\n";
 295
 296void llvm__get_kbuild_opts(char **kbuild_dir, char **kbuild_include_opts)
 297{
 298        static char *saved_kbuild_dir;
 299        static char *saved_kbuild_include_opts;
 300        int err;
 301
 302        if (!kbuild_dir || !kbuild_include_opts)
 303                return;
 304
 305        *kbuild_dir = NULL;
 306        *kbuild_include_opts = NULL;
 307
 308        if (saved_kbuild_dir && saved_kbuild_include_opts &&
 309            !IS_ERR(saved_kbuild_dir) && !IS_ERR(saved_kbuild_include_opts)) {
 310                *kbuild_dir = strdup(saved_kbuild_dir);
 311                *kbuild_include_opts = strdup(saved_kbuild_include_opts);
 312
 313                if (*kbuild_dir && *kbuild_include_opts)
 314                        return;
 315
 316                zfree(kbuild_dir);
 317                zfree(kbuild_include_opts);
 318                /*
 319                 * Don't fall through: it may breaks saved_kbuild_dir and
 320                 * saved_kbuild_include_opts if detect them again when
 321                 * memory is low.
 322                 */
 323                return;
 324        }
 325
 326        if (llvm_param.kbuild_dir && !llvm_param.kbuild_dir[0]) {
 327                pr_debug("[llvm.kbuild-dir] is set to \"\" deliberately.\n");
 328                pr_debug("Skip kbuild options detection.\n");
 329                goto errout;
 330        }
 331
 332        err = detect_kbuild_dir(kbuild_dir);
 333        if (err) {
 334                pr_warning(
 335"WARNING:\tunable to get correct kernel building directory.\n"
 336"Hint:\tSet correct kbuild directory using 'kbuild-dir' option in [llvm]\n"
 337"     \tsection of ~/.perfconfig or set it to \"\" to suppress kbuild\n"
 338"     \tdetection.\n\n");
 339                goto errout;
 340        }
 341
 342        pr_debug("Kernel build dir is set to %s\n", *kbuild_dir);
 343        force_set_env("KBUILD_DIR", *kbuild_dir);
 344        force_set_env("KBUILD_OPTS", llvm_param.kbuild_opts);
 345        err = read_from_pipe(kinc_fetch_script,
 346                             (void **)kbuild_include_opts,
 347                             NULL);
 348        if (err) {
 349                pr_warning(
 350"WARNING:\tunable to get kernel include directories from '%s'\n"
 351"Hint:\tTry set clang include options using 'clang-bpf-cmd-template'\n"
 352"     \toption in [llvm] section of ~/.perfconfig and set 'kbuild-dir'\n"
 353"     \toption in [llvm] to \"\" to suppress this detection.\n\n",
 354                        *kbuild_dir);
 355
 356                zfree(kbuild_dir);
 357                goto errout;
 358        }
 359
 360        pr_debug("include option is set to %s\n", *kbuild_include_opts);
 361
 362        saved_kbuild_dir = strdup(*kbuild_dir);
 363        saved_kbuild_include_opts = strdup(*kbuild_include_opts);
 364
 365        if (!saved_kbuild_dir || !saved_kbuild_include_opts) {
 366                zfree(&saved_kbuild_dir);
 367                zfree(&saved_kbuild_include_opts);
 368        }
 369        return;
 370errout:
 371        saved_kbuild_dir = ERR_PTR(-EINVAL);
 372        saved_kbuild_include_opts = ERR_PTR(-EINVAL);
 373}
 374
 375int llvm__get_nr_cpus(void)
 376{
 377        static int nr_cpus_avail = 0;
 378        char serr[STRERR_BUFSIZE];
 379
 380        if (nr_cpus_avail > 0)
 381                return nr_cpus_avail;
 382
 383        nr_cpus_avail = sysconf(_SC_NPROCESSORS_CONF);
 384        if (nr_cpus_avail <= 0) {
 385                pr_err(
 386"WARNING:\tunable to get available CPUs in this system: %s\n"
 387"        \tUse 128 instead.\n", str_error_r(errno, serr, sizeof(serr)));
 388                nr_cpus_avail = 128;
 389        }
 390        return nr_cpus_avail;
 391}
 392
 393void llvm__dump_obj(const char *path, void *obj_buf, size_t size)
 394{
 395        char *obj_path = strdup(path);
 396        FILE *fp;
 397        char *p;
 398
 399        if (!obj_path) {
 400                pr_warning("WARNING: Not enough memory, skip object dumping\n");
 401                return;
 402        }
 403
 404        p = strrchr(obj_path, '.');
 405        if (!p || (strcmp(p, ".c") != 0)) {
 406                pr_warning("WARNING: invalid llvm source path: '%s', skip object dumping\n",
 407                           obj_path);
 408                goto out;
 409        }
 410
 411        p[1] = 'o';
 412        fp = fopen(obj_path, "wb");
 413        if (!fp) {
 414                pr_warning("WARNING: failed to open '%s': %s, skip object dumping\n",
 415                           obj_path, strerror(errno));
 416                goto out;
 417        }
 418
 419        pr_info("LLVM: dumping %s\n", obj_path);
 420        if (fwrite(obj_buf, size, 1, fp) != 1)
 421                pr_warning("WARNING: failed to write to file '%s': %s, skip object dumping\n",
 422                           obj_path, strerror(errno));
 423        fclose(fp);
 424out:
 425        free(obj_path);
 426}
 427
 428int llvm__compile_bpf(const char *path, void **p_obj_buf,
 429                      size_t *p_obj_buf_sz)
 430{
 431        size_t obj_buf_sz;
 432        void *obj_buf = NULL;
 433        int err, nr_cpus_avail;
 434        unsigned int kernel_version;
 435        char linux_version_code_str[64];
 436        const char *clang_opt = llvm_param.clang_opt;
 437        char clang_path[PATH_MAX], llc_path[PATH_MAX], abspath[PATH_MAX], nr_cpus_avail_str[64];
 438        char serr[STRERR_BUFSIZE];
 439        char *kbuild_dir = NULL, *kbuild_include_opts = NULL,
 440             *perf_bpf_include_opts = NULL;
 441        const char *template = llvm_param.clang_bpf_cmd_template;
 442        char *pipe_template = NULL;
 443        const char *opts = llvm_param.opts;
 444        char *command_echo = NULL, *command_out;
 445        char *perf_include_dir = system_path(PERF_INCLUDE_DIR);
 446
 447        if (path[0] != '-' && realpath(path, abspath) == NULL) {
 448                err = errno;
 449                pr_err("ERROR: problems with path %s: %s\n",
 450                       path, str_error_r(err, serr, sizeof(serr)));
 451                return -err;
 452        }
 453
 454        if (!template)
 455                template = CLANG_BPF_CMD_DEFAULT_TEMPLATE;
 456
 457        err = search_program(llvm_param.clang_path,
 458                             "clang", clang_path);
 459        if (err) {
 460                pr_err(
 461"ERROR:\tunable to find clang.\n"
 462"Hint:\tTry to install latest clang/llvm to support BPF. Check your $PATH\n"
 463"     \tand 'clang-path' option in [llvm] section of ~/.perfconfig.\n");
 464                version_notice();
 465                return -ENOENT;
 466        }
 467
 468        /*
 469         * This is an optional work. Even it fail we can continue our
 470         * work. Needn't to check error return.
 471         */
 472        llvm__get_kbuild_opts(&kbuild_dir, &kbuild_include_opts);
 473
 474        nr_cpus_avail = llvm__get_nr_cpus();
 475        snprintf(nr_cpus_avail_str, sizeof(nr_cpus_avail_str), "%d",
 476                 nr_cpus_avail);
 477
 478        if (fetch_kernel_version(&kernel_version, NULL, 0))
 479                kernel_version = 0;
 480
 481        snprintf(linux_version_code_str, sizeof(linux_version_code_str),
 482                 "0x%x", kernel_version);
 483        if (asprintf(&perf_bpf_include_opts, "-I%s/bpf", perf_include_dir) < 0)
 484                goto errout;
 485        force_set_env("NR_CPUS", nr_cpus_avail_str);
 486        force_set_env("LINUX_VERSION_CODE", linux_version_code_str);
 487        force_set_env("CLANG_EXEC", clang_path);
 488        force_set_env("CLANG_OPTIONS", clang_opt);
 489        force_set_env("KERNEL_INC_OPTIONS", kbuild_include_opts);
 490        force_set_env("PERF_BPF_INC_OPTIONS", perf_bpf_include_opts);
 491        force_set_env("WORKING_DIR", kbuild_dir ? : ".");
 492
 493        if (opts) {
 494                err = search_program(llvm_param.llc_path, "llc", llc_path);
 495                if (err) {
 496                        pr_err("ERROR:\tunable to find llc.\n"
 497                               "Hint:\tTry to install latest clang/llvm to support BPF. Check your $PATH\n"
 498                               "     \tand 'llc-path' option in [llvm] section of ~/.perfconfig.\n");
 499                        version_notice();
 500                        goto errout;
 501                }
 502
 503                if (asprintf(&pipe_template, "%s -emit-llvm | %s -march=bpf %s -filetype=obj -o -",
 504                              template, llc_path, opts) < 0) {
 505                        pr_err("ERROR:\tnot enough memory to setup command line\n");
 506                        goto errout;
 507                }
 508
 509                template = pipe_template;
 510
 511        }
 512
 513        /*
 514         * Since we may reset clang's working dir, path of source file
 515         * should be transferred into absolute path, except we want
 516         * stdin to be source file (testing).
 517         */
 518        force_set_env("CLANG_SOURCE",
 519                      (path[0] == '-') ? path : abspath);
 520
 521        pr_debug("llvm compiling command template: %s\n", template);
 522
 523        if (asprintf(&command_echo, "echo -n \"%s\"", template) < 0)
 524                goto errout;
 525
 526        err = read_from_pipe(command_echo, (void **) &command_out, NULL);
 527        if (err)
 528                goto errout;
 529
 530        pr_debug("llvm compiling command : %s\n", command_out);
 531
 532        err = read_from_pipe(template, &obj_buf, &obj_buf_sz);
 533        if (err) {
 534                pr_err("ERROR:\tunable to compile %s\n", path);
 535                pr_err("Hint:\tCheck error message shown above.\n");
 536                pr_err("Hint:\tYou can also pre-compile it into .o using:\n");
 537                pr_err("     \t\tclang -target bpf -O2 -c %s\n", path);
 538                pr_err("     \twith proper -I and -D options.\n");
 539                goto errout;
 540        }
 541
 542        free(command_echo);
 543        free(command_out);
 544        free(kbuild_dir);
 545        free(kbuild_include_opts);
 546        free(perf_bpf_include_opts);
 547        free(perf_include_dir);
 548
 549        if (!p_obj_buf)
 550                free(obj_buf);
 551        else
 552                *p_obj_buf = obj_buf;
 553
 554        if (p_obj_buf_sz)
 555                *p_obj_buf_sz = obj_buf_sz;
 556        return 0;
 557errout:
 558        free(command_echo);
 559        free(kbuild_dir);
 560        free(kbuild_include_opts);
 561        free(obj_buf);
 562        free(perf_bpf_include_opts);
 563        free(perf_include_dir);
 564        free(pipe_template);
 565        if (p_obj_buf)
 566                *p_obj_buf = NULL;
 567        if (p_obj_buf_sz)
 568                *p_obj_buf_sz = 0;
 569        return err;
 570}
 571
 572int llvm__search_clang(void)
 573{
 574        char clang_path[PATH_MAX];
 575
 576        return search_program(llvm_param.clang_path, "clang", clang_path);
 577}
 578