xref: /linux/tools/perf/util/path.c (revision f3a8b6645dc2e60d11f20c1c23afd964ff4e55ae)
1 /*
2  * I'm tired of doing "vsnprintf()" etc just to open a
3  * file, so here's a "return static buffer with printf"
4  * interface for paths.
5  *
6  * It's obviously not thread-safe. Sue me. But it's quite
7  * useful for doing things like
8  *
9  *   f = open(mkpath("%s/%s.perf", base, name), O_RDONLY);
10  *
11  * which is what it's designed for.
12  */
13 #include "cache.h"
14 #include "util.h"
15 #include <limits.h>
16 
17 static char bad_path[] = "/bad-path/";
18 /*
19  * One hack:
20  */
21 static char *get_pathname(void)
22 {
23 	static char pathname_array[4][PATH_MAX];
24 	static int idx;
25 
26 	return pathname_array[3 & ++idx];
27 }
28 
29 static char *cleanup_path(char *path)
30 {
31 	/* Clean it up */
32 	if (!memcmp(path, "./", 2)) {
33 		path += 2;
34 		while (*path == '/')
35 			path++;
36 	}
37 	return path;
38 }
39 
40 char *mkpath(const char *fmt, ...)
41 {
42 	va_list args;
43 	unsigned len;
44 	char *pathname = get_pathname();
45 
46 	va_start(args, fmt);
47 	len = vsnprintf(pathname, PATH_MAX, fmt, args);
48 	va_end(args);
49 	if (len >= PATH_MAX)
50 		return bad_path;
51 	return cleanup_path(pathname);
52 }
53