Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 /*
0003  * Copyright (C) 2015, Wang Nan <wangnan0@huawei.com>
0004  * Copyright (C) 2015, Huawei Inc.
0005  */
0006 
0007 #include <errno.h>
0008 #include <limits.h>
0009 #include <stdio.h>
0010 #include <stdlib.h>
0011 #include <unistd.h>
0012 #include <linux/err.h>
0013 #include <linux/string.h>
0014 #include <linux/zalloc.h>
0015 #include "debug.h"
0016 #include "llvm-utils.h"
0017 #include "config.h"
0018 #include "util.h"
0019 #include <sys/wait.h>
0020 #include <subcmd/exec-cmd.h>
0021 
0022 #define CLANG_BPF_CMD_DEFAULT_TEMPLATE              \
0023         "$CLANG_EXEC -D__KERNEL__ -D__NR_CPUS__=$NR_CPUS "\
0024         "-DLINUX_VERSION_CODE=$LINUX_VERSION_CODE " \
0025         "$CLANG_OPTIONS $PERF_BPF_INC_OPTIONS $KERNEL_INC_OPTIONS " \
0026         "-Wno-unused-value -Wno-pointer-sign "      \
0027         "-working-directory $WORKING_DIR "      \
0028         "-c \"$CLANG_SOURCE\" -target bpf $CLANG_EMIT_LLVM -g -O2 -o - $LLVM_OPTIONS_PIPE"
0029 
0030 struct llvm_param llvm_param = {
0031     .clang_path = "clang",
0032     .llc_path = "llc",
0033     .clang_bpf_cmd_template = CLANG_BPF_CMD_DEFAULT_TEMPLATE,
0034     .clang_opt = NULL,
0035     .opts = NULL,
0036     .kbuild_dir = NULL,
0037     .kbuild_opts = NULL,
0038     .user_set_param = false,
0039 };
0040 
0041 static void version_notice(void);
0042 
0043 int perf_llvm_config(const char *var, const char *value)
0044 {
0045     if (!strstarts(var, "llvm."))
0046         return 0;
0047     var += sizeof("llvm.") - 1;
0048 
0049     if (!strcmp(var, "clang-path"))
0050         llvm_param.clang_path = strdup(value);
0051     else if (!strcmp(var, "clang-bpf-cmd-template"))
0052         llvm_param.clang_bpf_cmd_template = strdup(value);
0053     else if (!strcmp(var, "clang-opt"))
0054         llvm_param.clang_opt = strdup(value);
0055     else if (!strcmp(var, "kbuild-dir"))
0056         llvm_param.kbuild_dir = strdup(value);
0057     else if (!strcmp(var, "kbuild-opts"))
0058         llvm_param.kbuild_opts = strdup(value);
0059     else if (!strcmp(var, "dump-obj"))
0060         llvm_param.dump_obj = !!perf_config_bool(var, value);
0061     else if (!strcmp(var, "opts"))
0062         llvm_param.opts = strdup(value);
0063     else {
0064         pr_debug("Invalid LLVM config option: %s\n", value);
0065         return -1;
0066     }
0067     llvm_param.user_set_param = true;
0068     return 0;
0069 }
0070 
0071 static int
0072 search_program(const char *def, const char *name,
0073            char *output)
0074 {
0075     char *env, *path, *tmp = NULL;
0076     char buf[PATH_MAX];
0077     int ret;
0078 
0079     output[0] = '\0';
0080     if (def && def[0] != '\0') {
0081         if (def[0] == '/') {
0082             if (access(def, F_OK) == 0) {
0083                 strlcpy(output, def, PATH_MAX);
0084                 return 0;
0085             }
0086         } else if (def[0] != '\0')
0087             name = def;
0088     }
0089 
0090     env = getenv("PATH");
0091     if (!env)
0092         return -1;
0093     env = strdup(env);
0094     if (!env)
0095         return -1;
0096 
0097     ret = -ENOENT;
0098     path = strtok_r(env, ":",  &tmp);
0099     while (path) {
0100         scnprintf(buf, sizeof(buf), "%s/%s", path, name);
0101         if (access(buf, F_OK) == 0) {
0102             strlcpy(output, buf, PATH_MAX);
0103             ret = 0;
0104             break;
0105         }
0106         path = strtok_r(NULL, ":", &tmp);
0107     }
0108 
0109     free(env);
0110     return ret;
0111 }
0112 
0113 static int search_program_and_warn(const char *def, const char *name,
0114                    char *output)
0115 {
0116     int ret = search_program(def, name, output);
0117 
0118     if (ret) {
0119         pr_err("ERROR:\tunable to find %s.\n"
0120                "Hint:\tTry to install latest clang/llvm to support BPF. Check your $PATH\n"
0121                "     \tand '%s-path' option in [llvm] section of ~/.perfconfig.\n",
0122                name, name);
0123         version_notice();
0124     }
0125     return ret;
0126 }
0127 
0128 #define READ_SIZE   4096
0129 static int
0130 read_from_pipe(const char *cmd, void **p_buf, size_t *p_read_sz)
0131 {
0132     int err = 0;
0133     void *buf = NULL;
0134     FILE *file = NULL;
0135     size_t read_sz = 0, buf_sz = 0;
0136     char serr[STRERR_BUFSIZE];
0137 
0138     file = popen(cmd, "r");
0139     if (!file) {
0140         pr_err("ERROR: unable to popen cmd: %s\n",
0141                str_error_r(errno, serr, sizeof(serr)));
0142         return -EINVAL;
0143     }
0144 
0145     while (!feof(file) && !ferror(file)) {
0146         /*
0147          * Make buf_sz always have obe byte extra space so we
0148          * can put '\0' there.
0149          */
0150         if (buf_sz - read_sz < READ_SIZE + 1) {
0151             void *new_buf;
0152 
0153             buf_sz = read_sz + READ_SIZE + 1;
0154             new_buf = realloc(buf, buf_sz);
0155 
0156             if (!new_buf) {
0157                 pr_err("ERROR: failed to realloc memory\n");
0158                 err = -ENOMEM;
0159                 goto errout;
0160             }
0161 
0162             buf = new_buf;
0163         }
0164         read_sz += fread(buf + read_sz, 1, READ_SIZE, file);
0165     }
0166 
0167     if (buf_sz - read_sz < 1) {
0168         pr_err("ERROR: internal error\n");
0169         err = -EINVAL;
0170         goto errout;
0171     }
0172 
0173     if (ferror(file)) {
0174         pr_err("ERROR: error occurred when reading from pipe: %s\n",
0175                str_error_r(errno, serr, sizeof(serr)));
0176         err = -EIO;
0177         goto errout;
0178     }
0179 
0180     err = WEXITSTATUS(pclose(file));
0181     file = NULL;
0182     if (err) {
0183         err = -EINVAL;
0184         goto errout;
0185     }
0186 
0187     /*
0188      * If buf is string, give it terminal '\0' to make our life
0189      * easier. If buf is not string, that '\0' is out of space
0190      * indicated by read_sz so caller won't even notice it.
0191      */
0192     ((char *)buf)[read_sz] = '\0';
0193 
0194     if (!p_buf)
0195         free(buf);
0196     else
0197         *p_buf = buf;
0198 
0199     if (p_read_sz)
0200         *p_read_sz = read_sz;
0201     return 0;
0202 
0203 errout:
0204     if (file)
0205         pclose(file);
0206     free(buf);
0207     if (p_buf)
0208         *p_buf = NULL;
0209     if (p_read_sz)
0210         *p_read_sz = 0;
0211     return err;
0212 }
0213 
0214 static inline void
0215 force_set_env(const char *var, const char *value)
0216 {
0217     if (value) {
0218         setenv(var, value, 1);
0219         pr_debug("set env: %s=%s\n", var, value);
0220     } else {
0221         unsetenv(var);
0222         pr_debug("unset env: %s\n", var);
0223     }
0224 }
0225 
0226 static void
0227 version_notice(void)
0228 {
0229     pr_err(
0230 "     \tLLVM 3.7 or newer is required. Which can be found from http://llvm.org\n"
0231 "     \tYou may want to try git trunk:\n"
0232 "     \t\tgit clone http://llvm.org/git/llvm.git\n"
0233 "     \t\t     and\n"
0234 "     \t\tgit clone http://llvm.org/git/clang.git\n\n"
0235 "     \tOr fetch the latest clang/llvm 3.7 from pre-built llvm packages for\n"
0236 "     \tdebian/ubuntu:\n"
0237 "     \t\thttps://apt.llvm.org/\n\n"
0238 "     \tIf you are using old version of clang, change 'clang-bpf-cmd-template'\n"
0239 "     \toption in [llvm] section of ~/.perfconfig to:\n\n"
0240 "     \t  \"$CLANG_EXEC $CLANG_OPTIONS $KERNEL_INC_OPTIONS $PERF_BPF_INC_OPTIONS \\\n"
0241 "     \t     -working-directory $WORKING_DIR -c $CLANG_SOURCE \\\n"
0242 "     \t     -emit-llvm -o - | /path/to/llc -march=bpf -filetype=obj -o -\"\n"
0243 "     \t(Replace /path/to/llc with path to your llc)\n\n"
0244 );
0245 }
0246 
0247 static int detect_kbuild_dir(char **kbuild_dir)
0248 {
0249     const char *test_dir = llvm_param.kbuild_dir;
0250     const char *prefix_dir = "";
0251     const char *suffix_dir = "";
0252 
0253     /* _UTSNAME_LENGTH is 65 */
0254     char release[128];
0255 
0256     char *autoconf_path;
0257 
0258     int err;
0259 
0260     if (!test_dir) {
0261         err = fetch_kernel_version(NULL, release,
0262                        sizeof(release));
0263         if (err)
0264             return -EINVAL;
0265 
0266         test_dir = release;
0267         prefix_dir = "/lib/modules/";
0268         suffix_dir = "/build";
0269     }
0270 
0271     err = asprintf(&autoconf_path, "%s%s%s/include/generated/autoconf.h",
0272                prefix_dir, test_dir, suffix_dir);
0273     if (err < 0)
0274         return -ENOMEM;
0275 
0276     if (access(autoconf_path, R_OK) == 0) {
0277         free(autoconf_path);
0278 
0279         err = asprintf(kbuild_dir, "%s%s%s", prefix_dir, test_dir,
0280                    suffix_dir);
0281         if (err < 0)
0282             return -ENOMEM;
0283         return 0;
0284     }
0285     pr_debug("%s: Couldn't find \"%s\", missing kernel-devel package?.\n",
0286          __func__, autoconf_path);
0287     free(autoconf_path);
0288     return -ENOENT;
0289 }
0290 
0291 static const char *kinc_fetch_script =
0292 "#!/usr/bin/env sh\n"
0293 "if ! test -d \"$KBUILD_DIR\"\n"
0294 "then\n"
0295 "   exit 1\n"
0296 "fi\n"
0297 "if ! test -f \"$KBUILD_DIR/include/generated/autoconf.h\"\n"
0298 "then\n"
0299 "   exit 1\n"
0300 "fi\n"
0301 "TMPDIR=`mktemp -d`\n"
0302 "if test -z \"$TMPDIR\"\n"
0303 "then\n"
0304 "    exit 1\n"
0305 "fi\n"
0306 "cat << EOF > $TMPDIR/Makefile\n"
0307 "obj-y := dummy.o\n"
0308 "\\$(obj)/%.o: \\$(src)/%.c\n"
0309 "\t@echo -n \"\\$(NOSTDINC_FLAGS) \\$(LINUXINCLUDE) \\$(EXTRA_CFLAGS)\"\n"
0310 "\t\\$(CC) -c -o \\$@ \\$<\n"
0311 "EOF\n"
0312 "touch $TMPDIR/dummy.c\n"
0313 "make -s -C $KBUILD_DIR M=$TMPDIR $KBUILD_OPTS dummy.o 2>/dev/null\n"
0314 "RET=$?\n"
0315 "rm -rf $TMPDIR\n"
0316 "exit $RET\n";
0317 
0318 void llvm__get_kbuild_opts(char **kbuild_dir, char **kbuild_include_opts)
0319 {
0320     static char *saved_kbuild_dir;
0321     static char *saved_kbuild_include_opts;
0322     int err;
0323 
0324     if (!kbuild_dir || !kbuild_include_opts)
0325         return;
0326 
0327     *kbuild_dir = NULL;
0328     *kbuild_include_opts = NULL;
0329 
0330     if (saved_kbuild_dir && saved_kbuild_include_opts &&
0331         !IS_ERR(saved_kbuild_dir) && !IS_ERR(saved_kbuild_include_opts)) {
0332         *kbuild_dir = strdup(saved_kbuild_dir);
0333         *kbuild_include_opts = strdup(saved_kbuild_include_opts);
0334 
0335         if (*kbuild_dir && *kbuild_include_opts)
0336             return;
0337 
0338         zfree(kbuild_dir);
0339         zfree(kbuild_include_opts);
0340         /*
0341          * Don't fall through: it may breaks saved_kbuild_dir and
0342          * saved_kbuild_include_opts if detect them again when
0343          * memory is low.
0344          */
0345         return;
0346     }
0347 
0348     if (llvm_param.kbuild_dir && !llvm_param.kbuild_dir[0]) {
0349         pr_debug("[llvm.kbuild-dir] is set to \"\" deliberately.\n");
0350         pr_debug("Skip kbuild options detection.\n");
0351         goto errout;
0352     }
0353 
0354     err = detect_kbuild_dir(kbuild_dir);
0355     if (err) {
0356         pr_warning(
0357 "WARNING:\tunable to get correct kernel building directory.\n"
0358 "Hint:\tSet correct kbuild directory using 'kbuild-dir' option in [llvm]\n"
0359 "     \tsection of ~/.perfconfig or set it to \"\" to suppress kbuild\n"
0360 "     \tdetection.\n\n");
0361         goto errout;
0362     }
0363 
0364     pr_debug("Kernel build dir is set to %s\n", *kbuild_dir);
0365     force_set_env("KBUILD_DIR", *kbuild_dir);
0366     force_set_env("KBUILD_OPTS", llvm_param.kbuild_opts);
0367     err = read_from_pipe(kinc_fetch_script,
0368                  (void **)kbuild_include_opts,
0369                  NULL);
0370     if (err) {
0371         pr_warning(
0372 "WARNING:\tunable to get kernel include directories from '%s'\n"
0373 "Hint:\tTry set clang include options using 'clang-bpf-cmd-template'\n"
0374 "     \toption in [llvm] section of ~/.perfconfig and set 'kbuild-dir'\n"
0375 "     \toption in [llvm] to \"\" to suppress this detection.\n\n",
0376             *kbuild_dir);
0377 
0378         zfree(kbuild_dir);
0379         goto errout;
0380     }
0381 
0382     pr_debug("include option is set to %s\n", *kbuild_include_opts);
0383 
0384     saved_kbuild_dir = strdup(*kbuild_dir);
0385     saved_kbuild_include_opts = strdup(*kbuild_include_opts);
0386 
0387     if (!saved_kbuild_dir || !saved_kbuild_include_opts) {
0388         zfree(&saved_kbuild_dir);
0389         zfree(&saved_kbuild_include_opts);
0390     }
0391     return;
0392 errout:
0393     saved_kbuild_dir = ERR_PTR(-EINVAL);
0394     saved_kbuild_include_opts = ERR_PTR(-EINVAL);
0395 }
0396 
0397 int llvm__get_nr_cpus(void)
0398 {
0399     static int nr_cpus_avail = 0;
0400     char serr[STRERR_BUFSIZE];
0401 
0402     if (nr_cpus_avail > 0)
0403         return nr_cpus_avail;
0404 
0405     nr_cpus_avail = sysconf(_SC_NPROCESSORS_CONF);
0406     if (nr_cpus_avail <= 0) {
0407         pr_err(
0408 "WARNING:\tunable to get available CPUs in this system: %s\n"
0409 "        \tUse 128 instead.\n", str_error_r(errno, serr, sizeof(serr)));
0410         nr_cpus_avail = 128;
0411     }
0412     return nr_cpus_avail;
0413 }
0414 
0415 void llvm__dump_obj(const char *path, void *obj_buf, size_t size)
0416 {
0417     char *obj_path = strdup(path);
0418     FILE *fp;
0419     char *p;
0420 
0421     if (!obj_path) {
0422         pr_warning("WARNING: Not enough memory, skip object dumping\n");
0423         return;
0424     }
0425 
0426     p = strrchr(obj_path, '.');
0427     if (!p || (strcmp(p, ".c") != 0)) {
0428         pr_warning("WARNING: invalid llvm source path: '%s', skip object dumping\n",
0429                obj_path);
0430         goto out;
0431     }
0432 
0433     p[1] = 'o';
0434     fp = fopen(obj_path, "wb");
0435     if (!fp) {
0436         pr_warning("WARNING: failed to open '%s': %s, skip object dumping\n",
0437                obj_path, strerror(errno));
0438         goto out;
0439     }
0440 
0441     pr_debug("LLVM: dumping %s\n", obj_path);
0442     if (fwrite(obj_buf, size, 1, fp) != 1)
0443         pr_debug("WARNING: failed to write to file '%s': %s, skip object dumping\n", obj_path, strerror(errno));
0444     fclose(fp);
0445 out:
0446     free(obj_path);
0447 }
0448 
0449 int llvm__compile_bpf(const char *path, void **p_obj_buf,
0450               size_t *p_obj_buf_sz)
0451 {
0452     size_t obj_buf_sz;
0453     void *obj_buf = NULL;
0454     int err, nr_cpus_avail;
0455     unsigned int kernel_version;
0456     char linux_version_code_str[64];
0457     const char *clang_opt = llvm_param.clang_opt;
0458     char clang_path[PATH_MAX], llc_path[PATH_MAX], abspath[PATH_MAX], nr_cpus_avail_str[64];
0459     char serr[STRERR_BUFSIZE];
0460     char *kbuild_dir = NULL, *kbuild_include_opts = NULL,
0461          *perf_bpf_include_opts = NULL;
0462     const char *template = llvm_param.clang_bpf_cmd_template;
0463     char *pipe_template = NULL;
0464     const char *opts = llvm_param.opts;
0465     char *command_echo = NULL, *command_out;
0466     char *perf_include_dir = system_path(PERF_INCLUDE_DIR);
0467 
0468     if (path[0] != '-' && realpath(path, abspath) == NULL) {
0469         err = errno;
0470         pr_err("ERROR: problems with path %s: %s\n",
0471                path, str_error_r(err, serr, sizeof(serr)));
0472         return -err;
0473     }
0474 
0475     if (!template)
0476         template = CLANG_BPF_CMD_DEFAULT_TEMPLATE;
0477 
0478     err = search_program_and_warn(llvm_param.clang_path,
0479                  "clang", clang_path);
0480     if (err)
0481         return -ENOENT;
0482 
0483     /*
0484      * This is an optional work. Even it fail we can continue our
0485      * work. Needn't check error return.
0486      */
0487     llvm__get_kbuild_opts(&kbuild_dir, &kbuild_include_opts);
0488 
0489     nr_cpus_avail = llvm__get_nr_cpus();
0490     snprintf(nr_cpus_avail_str, sizeof(nr_cpus_avail_str), "%d",
0491          nr_cpus_avail);
0492 
0493     if (fetch_kernel_version(&kernel_version, NULL, 0))
0494         kernel_version = 0;
0495 
0496     snprintf(linux_version_code_str, sizeof(linux_version_code_str),
0497          "0x%x", kernel_version);
0498     if (asprintf(&perf_bpf_include_opts, "-I%s/bpf", perf_include_dir) < 0)
0499         goto errout;
0500     force_set_env("NR_CPUS", nr_cpus_avail_str);
0501     force_set_env("LINUX_VERSION_CODE", linux_version_code_str);
0502     force_set_env("CLANG_EXEC", clang_path);
0503     force_set_env("CLANG_OPTIONS", clang_opt);
0504     force_set_env("KERNEL_INC_OPTIONS", kbuild_include_opts);
0505     force_set_env("PERF_BPF_INC_OPTIONS", perf_bpf_include_opts);
0506     force_set_env("WORKING_DIR", kbuild_dir ? : ".");
0507 
0508     if (opts) {
0509         err = search_program_and_warn(llvm_param.llc_path, "llc", llc_path);
0510         if (err)
0511             goto errout;
0512 
0513         err = -ENOMEM;
0514         if (asprintf(&pipe_template, "%s -emit-llvm | %s -march=bpf %s -filetype=obj -o -",
0515                   template, llc_path, opts) < 0) {
0516             pr_err("ERROR:\tnot enough memory to setup command line\n");
0517             goto errout;
0518         }
0519 
0520         template = pipe_template;
0521 
0522     }
0523 
0524     /*
0525      * Since we may reset clang's working dir, path of source file
0526      * should be transferred into absolute path, except we want
0527      * stdin to be source file (testing).
0528      */
0529     force_set_env("CLANG_SOURCE",
0530               (path[0] == '-') ? path : abspath);
0531 
0532     pr_debug("llvm compiling command template: %s\n", template);
0533 
0534     err = -ENOMEM;
0535     if (asprintf(&command_echo, "echo -n \"%s\"", template) < 0)
0536         goto errout;
0537 
0538     err = read_from_pipe(command_echo, (void **) &command_out, NULL);
0539     if (err)
0540         goto errout;
0541 
0542     pr_debug("llvm compiling command : %s\n", command_out);
0543 
0544     err = read_from_pipe(template, &obj_buf, &obj_buf_sz);
0545     if (err) {
0546         pr_err("ERROR:\tunable to compile %s\n", path);
0547         pr_err("Hint:\tCheck error message shown above.\n");
0548         pr_err("Hint:\tYou can also pre-compile it into .o using:\n");
0549         pr_err("     \t\tclang -target bpf -O2 -c %s\n", path);
0550         pr_err("     \twith proper -I and -D options.\n");
0551         goto errout;
0552     }
0553 
0554     free(command_echo);
0555     free(command_out);
0556     free(kbuild_dir);
0557     free(kbuild_include_opts);
0558     free(perf_bpf_include_opts);
0559     free(perf_include_dir);
0560 
0561     if (!p_obj_buf)
0562         free(obj_buf);
0563     else
0564         *p_obj_buf = obj_buf;
0565 
0566     if (p_obj_buf_sz)
0567         *p_obj_buf_sz = obj_buf_sz;
0568     return 0;
0569 errout:
0570     free(command_echo);
0571     free(kbuild_dir);
0572     free(kbuild_include_opts);
0573     free(obj_buf);
0574     free(perf_bpf_include_opts);
0575     free(perf_include_dir);
0576     free(pipe_template);
0577     if (p_obj_buf)
0578         *p_obj_buf = NULL;
0579     if (p_obj_buf_sz)
0580         *p_obj_buf_sz = 0;
0581     return err;
0582 }
0583 
0584 int llvm__search_clang(void)
0585 {
0586     char clang_path[PATH_MAX];
0587 
0588     return search_program_and_warn(llvm_param.clang_path, "clang", clang_path);
0589 }