llvm-utils.c 13 KB

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