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