llvm-utils.c 13 KB

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