Linux Audio

Check our new training course

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