xref: /openbmc/linux/tools/perf/util/path.c (revision e00a844a)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * I'm tired of doing "vsnprintf()" etc just to open a
4  * file, so here's a "return static buffer with printf"
5  * interface for paths.
6  *
7  * It's obviously not thread-safe. Sue me. But it's quite
8  * useful for doing things like
9  *
10  *   f = open(mkpath("%s/%s.perf", base, name), O_RDONLY);
11  *
12  * which is what it's designed for.
13  */
14 #include "cache.h"
15 #include "path.h"
16 #include <linux/kernel.h>
17 #include <limits.h>
18 #include <stdio.h>
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <unistd.h>
22 
23 static char bad_path[] = "/bad-path/";
24 /*
25  * One hack:
26  */
27 static char *get_pathname(void)
28 {
29 	static char pathname_array[4][PATH_MAX];
30 	static int idx;
31 
32 	return pathname_array[3 & ++idx];
33 }
34 
35 static char *cleanup_path(char *path)
36 {
37 	/* Clean it up */
38 	if (!memcmp(path, "./", 2)) {
39 		path += 2;
40 		while (*path == '/')
41 			path++;
42 	}
43 	return path;
44 }
45 
46 char *mkpath(const char *fmt, ...)
47 {
48 	va_list args;
49 	unsigned len;
50 	char *pathname = get_pathname();
51 
52 	va_start(args, fmt);
53 	len = vsnprintf(pathname, PATH_MAX, fmt, args);
54 	va_end(args);
55 	if (len >= PATH_MAX)
56 		return bad_path;
57 	return cleanup_path(pathname);
58 }
59 
60 int path__join(char *bf, size_t size, const char *path1, const char *path2)
61 {
62 	return scnprintf(bf, size, "%s%s%s", path1, path1[0] ? "/" : "", path2);
63 }
64 
65 int path__join3(char *bf, size_t size, const char *path1, const char *path2, const char *path3)
66 {
67 	return scnprintf(bf, size, "%s%s%s%s%s", path1, path1[0] ? "/" : "",
68 			 path2, path2[0] ? "/" : "", path3);
69 }
70 
71 bool is_regular_file(const char *file)
72 {
73 	struct stat st;
74 
75 	if (stat(file, &st))
76 		return false;
77 
78 	return S_ISREG(st.st_mode);
79 }
80