llvm-utils.c 14 KB

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