1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2015, Wang Nan <wangnan0@huawei.com>
4 * Copyright (C) 2015, Huawei Inc.
11 #include <linux/err.h>
13 #include "llvm-utils.h"
18 #define CLANG_BPF_CMD_DEFAULT_TEMPLATE \
19 "$CLANG_EXEC -D__KERNEL__ -D__NR_CPUS__=$NR_CPUS "\
20 "-DLINUX_VERSION_CODE=$LINUX_VERSION_CODE " \
21 "$CLANG_OPTIONS $KERNEL_INC_OPTIONS " \
22 "-Wno-unused-value -Wno-pointer-sign " \
23 "-working-directory $WORKING_DIR " \
24 "-c \"$CLANG_SOURCE\" -target bpf -O2 -o -"
26 struct llvm_param llvm_param = {
27 .clang_path = "clang",
28 .clang_bpf_cmd_template = CLANG_BPF_CMD_DEFAULT_TEMPLATE,
32 .user_set_param = false,
35 int perf_llvm_config(const char *var, const char *value)
37 if (!strstarts(var, "llvm."))
39 var += sizeof("llvm.") - 1;
41 if (!strcmp(var, "clang-path"))
42 llvm_param.clang_path = strdup(value);
43 else if (!strcmp(var, "clang-bpf-cmd-template"))
44 llvm_param.clang_bpf_cmd_template = strdup(value);
45 else if (!strcmp(var, "clang-opt"))
46 llvm_param.clang_opt = strdup(value);
47 else if (!strcmp(var, "kbuild-dir"))
48 llvm_param.kbuild_dir = strdup(value);
49 else if (!strcmp(var, "kbuild-opts"))
50 llvm_param.kbuild_opts = strdup(value);
51 else if (!strcmp(var, "dump-obj"))
52 llvm_param.dump_obj = !!perf_config_bool(var, value);
54 pr_debug("Invalid LLVM config option: %s\n", value);
57 llvm_param.user_set_param = true;
62 search_program(const char *def, const char *name,
65 char *env, *path, *tmp = NULL;
70 if (def && def[0] != '\0') {
72 if (access(def, F_OK) == 0) {
73 strlcpy(output, def, PATH_MAX);
76 } else if (def[0] != '\0')
88 path = strtok_r(env, ":", &tmp);
90 scnprintf(buf, sizeof(buf), "%s/%s", path, name);
91 if (access(buf, F_OK) == 0) {
92 strlcpy(output, buf, PATH_MAX);
96 path = strtok_r(NULL, ":", &tmp);
103 #define READ_SIZE 4096
105 read_from_pipe(const char *cmd, void **p_buf, size_t *p_read_sz)
110 size_t read_sz = 0, buf_sz = 0;
111 char serr[STRERR_BUFSIZE];
113 file = popen(cmd, "r");
115 pr_err("ERROR: unable to popen cmd: %s\n",
116 str_error_r(errno, serr, sizeof(serr)));
120 while (!feof(file) && !ferror(file)) {
122 * Make buf_sz always have obe byte extra space so we
123 * can put '\0' there.
125 if (buf_sz - read_sz < READ_SIZE + 1) {
128 buf_sz = read_sz + READ_SIZE + 1;
129 new_buf = realloc(buf, buf_sz);
132 pr_err("ERROR: failed to realloc memory\n");
139 read_sz += fread(buf + read_sz, 1, READ_SIZE, file);
142 if (buf_sz - read_sz < 1) {
143 pr_err("ERROR: internal error\n");
149 pr_err("ERROR: error occurred when reading from pipe: %s\n",
150 str_error_r(errno, serr, sizeof(serr)));
155 err = WEXITSTATUS(pclose(file));
163 * If buf is string, give it terminal '\0' to make our life
164 * easier. If buf is not string, that '\0' is out of space
165 * indicated by read_sz so caller won't even notice it.
167 ((char *)buf)[read_sz] = '\0';
175 *p_read_sz = read_sz;
190 force_set_env(const char *var, const char *value)
193 setenv(var, value, 1);
194 pr_debug("set env: %s=%s\n", var, value);
197 pr_debug("unset env: %s\n", var);
205 " \tLLVM 3.7 or newer is required. Which can be found from http://llvm.org\n"
206 " \tYou may want to try git trunk:\n"
207 " \t\tgit clone http://llvm.org/git/llvm.git\n"
209 " \t\tgit clone http://llvm.org/git/clang.git\n\n"
210 " \tOr fetch the latest clang/llvm 3.7 from pre-built llvm packages for\n"
211 " \tdebian/ubuntu:\n"
212 " \t\thttp://llvm.org/apt\n\n"
213 " \tIf you are using old version of clang, change 'clang-bpf-cmd-template'\n"
214 " \toption in [llvm] section of ~/.perfconfig to:\n\n"
215 " \t \"$CLANG_EXEC $CLANG_OPTIONS $KERNEL_INC_OPTIONS \\\n"
216 " \t -working-directory $WORKING_DIR -c $CLANG_SOURCE \\\n"
217 " \t -emit-llvm -o - | /path/to/llc -march=bpf -filetype=obj -o -\"\n"
218 " \t(Replace /path/to/llc with path to your llc)\n\n"
222 static int detect_kbuild_dir(char **kbuild_dir)
224 const char *test_dir = llvm_param.kbuild_dir;
225 const char *prefix_dir = "";
226 const char *suffix_dir = "";
233 /* _UTSNAME_LENGTH is 65 */
236 err = fetch_kernel_version(NULL, release,
242 prefix_dir = "/lib/modules/";
243 suffix_dir = "/build";
246 err = asprintf(&autoconf_path, "%s%s%s/include/generated/autoconf.h",
247 prefix_dir, test_dir, suffix_dir);
251 if (access(autoconf_path, R_OK) == 0) {
254 err = asprintf(kbuild_dir, "%s%s%s", prefix_dir, test_dir,
264 static const char *kinc_fetch_script =
265 "#!/usr/bin/env sh\n"
266 "if ! test -d \"$KBUILD_DIR\"\n"
270 "if ! test -f \"$KBUILD_DIR/include/generated/autoconf.h\"\n"
274 "TMPDIR=`mktemp -d`\n"
275 "if test -z \"$TMPDIR\"\n"
279 "cat << EOF > $TMPDIR/Makefile\n"
281 "\\$(obj)/%.o: \\$(src)/%.c\n"
282 "\t@echo -n \"\\$(NOSTDINC_FLAGS) \\$(LINUXINCLUDE) \\$(EXTRA_CFLAGS)\"\n"
284 "touch $TMPDIR/dummy.c\n"
285 "make -s -C $KBUILD_DIR M=$TMPDIR $KBUILD_OPTS dummy.o 2>/dev/null\n"
290 void llvm__get_kbuild_opts(char **kbuild_dir, char **kbuild_include_opts)
292 static char *saved_kbuild_dir;
293 static char *saved_kbuild_include_opts;
296 if (!kbuild_dir || !kbuild_include_opts)
300 *kbuild_include_opts = NULL;
302 if (saved_kbuild_dir && saved_kbuild_include_opts &&
303 !IS_ERR(saved_kbuild_dir) && !IS_ERR(saved_kbuild_include_opts)) {
304 *kbuild_dir = strdup(saved_kbuild_dir);
305 *kbuild_include_opts = strdup(saved_kbuild_include_opts);
307 if (*kbuild_dir && *kbuild_include_opts)
311 zfree(kbuild_include_opts);
313 * Don't fall through: it may breaks saved_kbuild_dir and
314 * saved_kbuild_include_opts if detect them again when
320 if (llvm_param.kbuild_dir && !llvm_param.kbuild_dir[0]) {
321 pr_debug("[llvm.kbuild-dir] is set to \"\" deliberately.\n");
322 pr_debug("Skip kbuild options detection.\n");
326 err = detect_kbuild_dir(kbuild_dir);
329 "WARNING:\tunable to get correct kernel building directory.\n"
330 "Hint:\tSet correct kbuild directory using 'kbuild-dir' option in [llvm]\n"
331 " \tsection of ~/.perfconfig or set it to \"\" to suppress kbuild\n"
332 " \tdetection.\n\n");
336 pr_debug("Kernel build dir is set to %s\n", *kbuild_dir);
337 force_set_env("KBUILD_DIR", *kbuild_dir);
338 force_set_env("KBUILD_OPTS", llvm_param.kbuild_opts);
339 err = read_from_pipe(kinc_fetch_script,
340 (void **)kbuild_include_opts,
344 "WARNING:\tunable to get kernel include directories from '%s'\n"
345 "Hint:\tTry set clang include options using 'clang-bpf-cmd-template'\n"
346 " \toption in [llvm] section of ~/.perfconfig and set 'kbuild-dir'\n"
347 " \toption in [llvm] to \"\" to suppress this detection.\n\n",
355 pr_debug("include option is set to %s\n", *kbuild_include_opts);
357 saved_kbuild_dir = strdup(*kbuild_dir);
358 saved_kbuild_include_opts = strdup(*kbuild_include_opts);
360 if (!saved_kbuild_dir || !saved_kbuild_include_opts) {
361 zfree(&saved_kbuild_dir);
362 zfree(&saved_kbuild_include_opts);
366 saved_kbuild_dir = ERR_PTR(-EINVAL);
367 saved_kbuild_include_opts = ERR_PTR(-EINVAL);
370 int llvm__get_nr_cpus(void)
372 static int nr_cpus_avail = 0;
373 char serr[STRERR_BUFSIZE];
375 if (nr_cpus_avail > 0)
376 return nr_cpus_avail;
378 nr_cpus_avail = sysconf(_SC_NPROCESSORS_CONF);
379 if (nr_cpus_avail <= 0) {
381 "WARNING:\tunable to get available CPUs in this system: %s\n"
382 " \tUse 128 instead.\n", str_error_r(errno, serr, sizeof(serr)));
385 return nr_cpus_avail;
388 void llvm__dump_obj(const char *path, void *obj_buf, size_t size)
390 char *obj_path = strdup(path);
395 pr_warning("WARNING: Not enough memory, skip object dumping\n");
399 p = strrchr(obj_path, '.');
400 if (!p || (strcmp(p, ".c") != 0)) {
401 pr_warning("WARNING: invalid llvm source path: '%s', skip object dumping\n",
407 fp = fopen(obj_path, "wb");
409 pr_warning("WARNING: failed to open '%s': %s, skip object dumping\n",
410 obj_path, strerror(errno));
414 pr_info("LLVM: dumping %s\n", obj_path);
415 if (fwrite(obj_buf, size, 1, fp) != 1)
416 pr_warning("WARNING: failed to write to file '%s': %s, skip object dumping\n",
417 obj_path, strerror(errno));
423 int llvm__compile_bpf(const char *path, void **p_obj_buf,
424 size_t *p_obj_buf_sz)
427 void *obj_buf = NULL;
428 int err, nr_cpus_avail;
429 unsigned int kernel_version;
430 char linux_version_code_str[64];
431 const char *clang_opt = llvm_param.clang_opt;
432 char clang_path[PATH_MAX], abspath[PATH_MAX], nr_cpus_avail_str[64];
433 char serr[STRERR_BUFSIZE];
434 char *kbuild_dir = NULL, *kbuild_include_opts = NULL;
435 const char *template = llvm_param.clang_bpf_cmd_template;
437 if (path[0] != '-' && realpath(path, abspath) == NULL) {
439 pr_err("ERROR: problems with path %s: %s\n",
440 path, str_error_r(err, serr, sizeof(serr)));
445 template = CLANG_BPF_CMD_DEFAULT_TEMPLATE;
447 err = search_program(llvm_param.clang_path,
448 "clang", clang_path);
451 "ERROR:\tunable to find clang.\n"
452 "Hint:\tTry to install latest clang/llvm to support BPF. Check your $PATH\n"
453 " \tand 'clang-path' option in [llvm] section of ~/.perfconfig.\n");
459 * This is an optional work. Even it fail we can continue our
460 * work. Needn't to check error return.
462 llvm__get_kbuild_opts(&kbuild_dir, &kbuild_include_opts);
464 nr_cpus_avail = llvm__get_nr_cpus();
465 snprintf(nr_cpus_avail_str, sizeof(nr_cpus_avail_str), "%d",
468 if (fetch_kernel_version(&kernel_version, NULL, 0))
471 snprintf(linux_version_code_str, sizeof(linux_version_code_str),
472 "0x%x", kernel_version);
474 force_set_env("NR_CPUS", nr_cpus_avail_str);
475 force_set_env("LINUX_VERSION_CODE", linux_version_code_str);
476 force_set_env("CLANG_EXEC", clang_path);
477 force_set_env("CLANG_OPTIONS", clang_opt);
478 force_set_env("KERNEL_INC_OPTIONS", kbuild_include_opts);
479 force_set_env("WORKING_DIR", kbuild_dir ? : ".");
482 * Since we may reset clang's working dir, path of source file
483 * should be transferred into absolute path, except we want
484 * stdin to be source file (testing).
486 force_set_env("CLANG_SOURCE",
487 (path[0] == '-') ? path : abspath);
489 pr_debug("llvm compiling command template: %s\n", template);
490 err = read_from_pipe(template, &obj_buf, &obj_buf_sz);
492 pr_err("ERROR:\tunable to compile %s\n", path);
493 pr_err("Hint:\tCheck error message shown above.\n");
494 pr_err("Hint:\tYou can also pre-compile it into .o using:\n");
495 pr_err(" \t\tclang -target bpf -O2 -c %s\n", path);
496 pr_err(" \twith proper -I and -D options.\n");
501 free(kbuild_include_opts);
506 *p_obj_buf = obj_buf;
509 *p_obj_buf_sz = obj_buf_sz;
513 free(kbuild_include_opts);
522 int llvm__search_clang(void)
524 char clang_path[PATH_MAX];
526 return search_program(llvm_param.clang_path, "clang", clang_path);