3 * Copyright (C) 2015, Huawei Inc.
10 #include <linux/err.h>
12 #include "llvm-utils.h"
17 #define CLANG_BPF_CMD_DEFAULT_TEMPLATE \
18 "$CLANG_EXEC -D__KERNEL__ -D__NR_CPUS__=$NR_CPUS "\
19 "-DLINUX_VERSION_CODE=$LINUX_VERSION_CODE " \
20 "$CLANG_OPTIONS $KERNEL_INC_OPTIONS " \
21 "-Wno-unused-value -Wno-pointer-sign " \
22 "-working-directory $WORKING_DIR " \
23 "-c \"$CLANG_SOURCE\" -target bpf -O2 -o -"
25 struct llvm_param llvm_param = {
26 .clang_path = "clang",
27 .clang_bpf_cmd_template = CLANG_BPF_CMD_DEFAULT_TEMPLATE,
31 .user_set_param = false,
34 int perf_llvm_config(const char *var, const char *value)
36 if (prefixcmp(var, "llvm."))
38 var += sizeof("llvm.") - 1;
40 if (!strcmp(var, "clang-path"))
41 llvm_param.clang_path = strdup(value);
42 else if (!strcmp(var, "clang-bpf-cmd-template"))
43 llvm_param.clang_bpf_cmd_template = strdup(value);
44 else if (!strcmp(var, "clang-opt"))
45 llvm_param.clang_opt = strdup(value);
46 else if (!strcmp(var, "kbuild-dir"))
47 llvm_param.kbuild_dir = strdup(value);
48 else if (!strcmp(var, "kbuild-opts"))
49 llvm_param.kbuild_opts = strdup(value);
50 else if (!strcmp(var, "dump-obj"))
51 llvm_param.dump_obj = !!perf_config_bool(var, value);
53 pr_debug("Invalid LLVM config option: %s\n", value);
56 llvm_param.user_set_param = true;
61 search_program(const char *def, const char *name,
64 char *env, *path, *tmp = NULL;
69 if (def && def[0] != '\0') {
71 if (access(def, F_OK) == 0) {
72 strlcpy(output, def, PATH_MAX);
75 } else if (def[0] != '\0')
87 path = strtok_r(env, ":", &tmp);
89 scnprintf(buf, sizeof(buf), "%s/%s", path, name);
90 if (access(buf, F_OK) == 0) {
91 strlcpy(output, buf, PATH_MAX);
95 path = strtok_r(NULL, ":", &tmp);
102 #define READ_SIZE 4096
104 read_from_pipe(const char *cmd, void **p_buf, size_t *p_read_sz)
109 size_t read_sz = 0, buf_sz = 0;
110 char serr[STRERR_BUFSIZE];
112 file = popen(cmd, "r");
114 pr_err("ERROR: unable to popen cmd: %s\n",
115 str_error_r(errno, serr, sizeof(serr)));
119 while (!feof(file) && !ferror(file)) {
121 * Make buf_sz always have obe byte extra space so we
122 * can put '\0' there.
124 if (buf_sz - read_sz < READ_SIZE + 1) {
127 buf_sz = read_sz + READ_SIZE + 1;
128 new_buf = realloc(buf, buf_sz);
131 pr_err("ERROR: failed to realloc memory\n");
138 read_sz += fread(buf + read_sz, 1, READ_SIZE, file);
141 if (buf_sz - read_sz < 1) {
142 pr_err("ERROR: internal error\n");
148 pr_err("ERROR: error occurred when reading from pipe: %s\n",
149 str_error_r(errno, serr, sizeof(serr)));
154 err = WEXITSTATUS(pclose(file));
162 * If buf is string, give it terminal '\0' to make our life
163 * easier. If buf is not string, that '\0' is out of space
164 * indicated by read_sz so caller won't even notice it.
166 ((char *)buf)[read_sz] = '\0';
174 *p_read_sz = read_sz;
189 force_set_env(const char *var, const char *value)
192 setenv(var, value, 1);
193 pr_debug("set env: %s=%s\n", var, value);
196 pr_debug("unset env: %s\n", var);
204 " \tLLVM 3.7 or newer is required. Which can be found from http://llvm.org\n"
205 " \tYou may want to try git trunk:\n"
206 " \t\tgit clone http://llvm.org/git/llvm.git\n"
208 " \t\tgit clone http://llvm.org/git/clang.git\n\n"
209 " \tOr fetch the latest clang/llvm 3.7 from pre-built llvm packages for\n"
210 " \tdebian/ubuntu:\n"
211 " \t\thttp://llvm.org/apt\n\n"
212 " \tIf you are using old version of clang, change 'clang-bpf-cmd-template'\n"
213 " \toption in [llvm] section of ~/.perfconfig to:\n\n"
214 " \t \"$CLANG_EXEC $CLANG_OPTIONS $KERNEL_INC_OPTIONS \\\n"
215 " \t -working-directory $WORKING_DIR -c $CLANG_SOURCE \\\n"
216 " \t -emit-llvm -o - | /path/to/llc -march=bpf -filetype=obj -o -\"\n"
217 " \t(Replace /path/to/llc with path to your llc)\n\n"
221 static int detect_kbuild_dir(char **kbuild_dir)
223 const char *test_dir = llvm_param.kbuild_dir;
224 const char *prefix_dir = "";
225 const char *suffix_dir = "";
232 /* _UTSNAME_LENGTH is 65 */
235 err = fetch_kernel_version(NULL, release,
241 prefix_dir = "/lib/modules/";
242 suffix_dir = "/build";
245 err = asprintf(&autoconf_path, "%s%s%s/include/generated/autoconf.h",
246 prefix_dir, test_dir, suffix_dir);
250 if (access(autoconf_path, R_OK) == 0) {
253 err = asprintf(kbuild_dir, "%s%s%s", prefix_dir, test_dir,
263 static const char *kinc_fetch_script =
264 "#!/usr/bin/env sh\n"
265 "if ! test -d \"$KBUILD_DIR\"\n"
269 "if ! test -f \"$KBUILD_DIR/include/generated/autoconf.h\"\n"
273 "TMPDIR=`mktemp -d`\n"
274 "if test -z \"$TMPDIR\"\n"
278 "cat << EOF > $TMPDIR/Makefile\n"
280 "\\$(obj)/%.o: \\$(src)/%.c\n"
281 "\t@echo -n \"\\$(NOSTDINC_FLAGS) \\$(LINUXINCLUDE) \\$(EXTRA_CFLAGS)\"\n"
283 "touch $TMPDIR/dummy.c\n"
284 "make -s -C $KBUILD_DIR M=$TMPDIR $KBUILD_OPTS dummy.o 2>/dev/null\n"
289 void llvm__get_kbuild_opts(char **kbuild_dir, char **kbuild_include_opts)
291 static char *saved_kbuild_dir;
292 static char *saved_kbuild_include_opts;
295 if (!kbuild_dir || !kbuild_include_opts)
299 *kbuild_include_opts = NULL;
301 if (saved_kbuild_dir && saved_kbuild_include_opts &&
302 !IS_ERR(saved_kbuild_dir) && !IS_ERR(saved_kbuild_include_opts)) {
303 *kbuild_dir = strdup(saved_kbuild_dir);
304 *kbuild_include_opts = strdup(saved_kbuild_include_opts);
306 if (*kbuild_dir && *kbuild_include_opts)
310 zfree(kbuild_include_opts);
312 * Don't fall through: it may breaks saved_kbuild_dir and
313 * saved_kbuild_include_opts if detect them again when
319 if (llvm_param.kbuild_dir && !llvm_param.kbuild_dir[0]) {
320 pr_debug("[llvm.kbuild-dir] is set to \"\" deliberately.\n");
321 pr_debug("Skip kbuild options detection.\n");
325 err = detect_kbuild_dir(kbuild_dir);
328 "WARNING:\tunable to get correct kernel building directory.\n"
329 "Hint:\tSet correct kbuild directory using 'kbuild-dir' option in [llvm]\n"
330 " \tsection of ~/.perfconfig or set it to \"\" to suppress kbuild\n"
331 " \tdetection.\n\n");
335 pr_debug("Kernel build dir is set to %s\n", *kbuild_dir);
336 force_set_env("KBUILD_DIR", *kbuild_dir);
337 force_set_env("KBUILD_OPTS", llvm_param.kbuild_opts);
338 err = read_from_pipe(kinc_fetch_script,
339 (void **)kbuild_include_opts,
343 "WARNING:\tunable to get kernel include directories from '%s'\n"
344 "Hint:\tTry set clang include options using 'clang-bpf-cmd-template'\n"
345 " \toption in [llvm] section of ~/.perfconfig and set 'kbuild-dir'\n"
346 " \toption in [llvm] to \"\" to suppress this detection.\n\n",
354 pr_debug("include option is set to %s\n", *kbuild_include_opts);
356 saved_kbuild_dir = strdup(*kbuild_dir);
357 saved_kbuild_include_opts = strdup(*kbuild_include_opts);
359 if (!saved_kbuild_dir || !saved_kbuild_include_opts) {
360 zfree(&saved_kbuild_dir);
361 zfree(&saved_kbuild_include_opts);
365 saved_kbuild_dir = ERR_PTR(-EINVAL);
366 saved_kbuild_include_opts = ERR_PTR(-EINVAL);
369 int llvm__get_nr_cpus(void)
371 static int nr_cpus_avail = 0;
372 char serr[STRERR_BUFSIZE];
374 if (nr_cpus_avail > 0)
375 return nr_cpus_avail;
377 nr_cpus_avail = sysconf(_SC_NPROCESSORS_CONF);
378 if (nr_cpus_avail <= 0) {
380 "WARNING:\tunable to get available CPUs in this system: %s\n"
381 " \tUse 128 instead.\n", str_error_r(errno, serr, sizeof(serr)));
384 return nr_cpus_avail;
387 void llvm__dump_obj(const char *path, void *obj_buf, size_t size)
389 char *obj_path = strdup(path);
394 pr_warning("WARNING: Not enough memory, skip object dumping\n");
398 p = strrchr(obj_path, '.');
399 if (!p || (strcmp(p, ".c") != 0)) {
400 pr_warning("WARNING: invalid llvm source path: '%s', skip object dumping\n",
406 fp = fopen(obj_path, "wb");
408 pr_warning("WARNING: failed to open '%s': %s, skip object dumping\n",
409 obj_path, strerror(errno));
413 pr_info("LLVM: dumping %s\n", obj_path);
414 if (fwrite(obj_buf, size, 1, fp) != 1)
415 pr_warning("WARNING: failed to write to file '%s': %s, skip object dumping\n",
416 obj_path, strerror(errno));
422 int llvm__compile_bpf(const char *path, void **p_obj_buf,
423 size_t *p_obj_buf_sz)
426 void *obj_buf = NULL;
427 int err, nr_cpus_avail;
428 unsigned int kernel_version;
429 char linux_version_code_str[64];
430 const char *clang_opt = llvm_param.clang_opt;
431 char clang_path[PATH_MAX], abspath[PATH_MAX], nr_cpus_avail_str[64];
432 char serr[STRERR_BUFSIZE];
433 char *kbuild_dir = NULL, *kbuild_include_opts = NULL;
434 const char *template = llvm_param.clang_bpf_cmd_template;
436 if (path[0] != '-' && realpath(path, abspath) == NULL) {
438 pr_err("ERROR: problems with path %s: %s\n",
439 path, str_error_r(err, serr, sizeof(serr)));
444 template = CLANG_BPF_CMD_DEFAULT_TEMPLATE;
446 err = search_program(llvm_param.clang_path,
447 "clang", clang_path);
450 "ERROR:\tunable to find clang.\n"
451 "Hint:\tTry to install latest clang/llvm to support BPF. Check your $PATH\n"
452 " \tand 'clang-path' option in [llvm] section of ~/.perfconfig.\n");
458 * This is an optional work. Even it fail we can continue our
459 * work. Needn't to check error return.
461 llvm__get_kbuild_opts(&kbuild_dir, &kbuild_include_opts);
463 nr_cpus_avail = llvm__get_nr_cpus();
464 snprintf(nr_cpus_avail_str, sizeof(nr_cpus_avail_str), "%d",
467 if (fetch_kernel_version(&kernel_version, NULL, 0))
470 snprintf(linux_version_code_str, sizeof(linux_version_code_str),
471 "0x%x", kernel_version);
473 force_set_env("NR_CPUS", nr_cpus_avail_str);
474 force_set_env("LINUX_VERSION_CODE", linux_version_code_str);
475 force_set_env("CLANG_EXEC", clang_path);
476 force_set_env("CLANG_OPTIONS", clang_opt);
477 force_set_env("KERNEL_INC_OPTIONS", kbuild_include_opts);
478 force_set_env("WORKING_DIR", kbuild_dir ? : ".");
481 * Since we may reset clang's working dir, path of source file
482 * should be transferred into absolute path, except we want
483 * stdin to be source file (testing).
485 force_set_env("CLANG_SOURCE",
486 (path[0] == '-') ? path : abspath);
488 pr_debug("llvm compiling command template: %s\n", template);
489 err = read_from_pipe(template, &obj_buf, &obj_buf_sz);
491 pr_err("ERROR:\tunable to compile %s\n", path);
492 pr_err("Hint:\tCheck error message shown above.\n");
493 pr_err("Hint:\tYou can also pre-compile it into .o using:\n");
494 pr_err(" \t\tclang -target bpf -O2 -c %s\n", path);
495 pr_err(" \twith proper -I and -D options.\n");
500 free(kbuild_include_opts);
505 *p_obj_buf = obj_buf;
508 *p_obj_buf_sz = obj_buf_sz;
512 free(kbuild_include_opts);
521 int llvm__search_clang(void)
523 char clang_path[PATH_MAX];
525 return search_program(llvm_param.clang_path, "clang", clang_path);