xref: /linux/tools/perf/util/util.c (revision 20f2be1d48ec293b5a935595bd0c2e2915ffa77c)
1 // SPDX-License-Identifier: GPL-2.0
2 #include "util.h"
3 #include "debug.h"
4 #include "event.h"
5 #include "namespaces.h"
6 #include <internal/lib.h>
7 #include <api/fs/fs.h>
8 #include <sys/mman.h>
9 #include <sys/stat.h>
10 #include <sys/utsname.h>
11 #include <dirent.h>
12 #include <fcntl.h>
13 #include <inttypes.h>
14 #include <signal.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <errno.h>
19 #include <limits.h>
20 #include <linux/capability.h>
21 #include <linux/kernel.h>
22 #include <linux/log2.h>
23 #include <linux/time64.h>
24 #include <unistd.h>
25 #include "cap.h"
26 #include "strlist.h"
27 #include "string2.h"
28 
29 /*
30  * XXX We need to find a better place for these things...
31  */
32 
33 bool perf_singlethreaded = true;
34 
35 void perf_set_singlethreaded(void)
36 {
37 	perf_singlethreaded = true;
38 }
39 
40 void perf_set_multithreaded(void)
41 {
42 	perf_singlethreaded = false;
43 }
44 
45 int sysctl_perf_event_max_stack = PERF_MAX_STACK_DEPTH;
46 int sysctl_perf_event_max_contexts_per_stack = PERF_MAX_CONTEXTS_PER_STACK;
47 
48 int sysctl__max_stack(void)
49 {
50 	int value;
51 
52 	if (sysctl__read_int("kernel/perf_event_max_stack", &value) == 0)
53 		sysctl_perf_event_max_stack = value;
54 
55 	if (sysctl__read_int("kernel/perf_event_max_contexts_per_stack", &value) == 0)
56 		sysctl_perf_event_max_contexts_per_stack = value;
57 
58 	return sysctl_perf_event_max_stack;
59 }
60 
61 bool test_attr__enabled;
62 
63 bool perf_host  = true;
64 bool perf_guest = false;
65 
66 void event_attr_init(struct perf_event_attr *attr)
67 {
68 	if (!perf_host)
69 		attr->exclude_host  = 1;
70 	if (!perf_guest)
71 		attr->exclude_guest = 1;
72 	/* to capture ABI version */
73 	attr->size = sizeof(*attr);
74 }
75 
76 int mkdir_p(char *path, mode_t mode)
77 {
78 	struct stat st;
79 	int err;
80 	char *d = path;
81 
82 	if (*d != '/')
83 		return -1;
84 
85 	if (stat(path, &st) == 0)
86 		return 0;
87 
88 	while (*++d == '/');
89 
90 	while ((d = strchr(d, '/'))) {
91 		*d = '\0';
92 		err = stat(path, &st) && mkdir(path, mode);
93 		*d++ = '/';
94 		if (err)
95 			return -1;
96 		while (*d == '/')
97 			++d;
98 	}
99 	return (stat(path, &st) && mkdir(path, mode)) ? -1 : 0;
100 }
101 
102 static bool match_pat(char *file, const char **pat)
103 {
104 	int i = 0;
105 
106 	if (!pat)
107 		return true;
108 
109 	while (pat[i]) {
110 		if (strglobmatch(file, pat[i]))
111 			return true;
112 
113 		i++;
114 	}
115 
116 	return false;
117 }
118 
119 /*
120  * The depth specify how deep the removal will go.
121  * 0       - will remove only files under the 'path' directory
122  * 1 .. x  - will dive in x-level deep under the 'path' directory
123  *
124  * If specified the pat is array of string patterns ended with NULL,
125  * which are checked upon every file/directory found. Only matching
126  * ones are removed.
127  *
128  * The function returns:
129  *    0 on success
130  *   -1 on removal failure with errno set
131  *   -2 on pattern failure
132  */
133 static int rm_rf_depth_pat(const char *path, int depth, const char **pat)
134 {
135 	DIR *dir;
136 	int ret;
137 	struct dirent *d;
138 	char namebuf[PATH_MAX];
139 	struct stat statbuf;
140 
141 	/* Do not fail if there's no file. */
142 	ret = lstat(path, &statbuf);
143 	if (ret)
144 		return 0;
145 
146 	/* Try to remove any file we get. */
147 	if (!(statbuf.st_mode & S_IFDIR))
148 		return unlink(path);
149 
150 	/* We have directory in path. */
151 	dir = opendir(path);
152 	if (dir == NULL)
153 		return -1;
154 
155 	while ((d = readdir(dir)) != NULL && !ret) {
156 
157 		if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
158 			continue;
159 
160 		if (!match_pat(d->d_name, pat))
161 			return -2;
162 
163 		scnprintf(namebuf, sizeof(namebuf), "%s/%s",
164 			  path, d->d_name);
165 
166 		/* We have to check symbolic link itself */
167 		ret = lstat(namebuf, &statbuf);
168 		if (ret < 0) {
169 			pr_debug("stat failed: %s\n", namebuf);
170 			break;
171 		}
172 
173 		if (S_ISDIR(statbuf.st_mode))
174 			ret = depth ? rm_rf_depth_pat(namebuf, depth - 1, pat) : 0;
175 		else
176 			ret = unlink(namebuf);
177 	}
178 	closedir(dir);
179 
180 	if (ret < 0)
181 		return ret;
182 
183 	return rmdir(path);
184 }
185 
186 int rm_rf_perf_data(const char *path)
187 {
188 	const char *pat[] = {
189 		"header",
190 		"data.*",
191 		NULL,
192 	};
193 
194 	return rm_rf_depth_pat(path, 0, pat);
195 }
196 
197 int rm_rf(const char *path)
198 {
199 	return rm_rf_depth_pat(path, INT_MAX, NULL);
200 }
201 
202 /* A filter which removes dot files */
203 bool lsdir_no_dot_filter(const char *name __maybe_unused, struct dirent *d)
204 {
205 	return d->d_name[0] != '.';
206 }
207 
208 /* lsdir reads a directory and store it in strlist */
209 struct strlist *lsdir(const char *name,
210 		      bool (*filter)(const char *, struct dirent *))
211 {
212 	struct strlist *list = NULL;
213 	DIR *dir;
214 	struct dirent *d;
215 
216 	dir = opendir(name);
217 	if (!dir)
218 		return NULL;
219 
220 	list = strlist__new(NULL, NULL);
221 	if (!list) {
222 		errno = ENOMEM;
223 		goto out;
224 	}
225 
226 	while ((d = readdir(dir)) != NULL) {
227 		if (!filter || filter(name, d))
228 			strlist__add(list, d->d_name);
229 	}
230 
231 out:
232 	closedir(dir);
233 	return list;
234 }
235 
236 static int slow_copyfile(const char *from, const char *to, struct nsinfo *nsi)
237 {
238 	int err = -1;
239 	char *line = NULL;
240 	size_t n;
241 	FILE *from_fp, *to_fp;
242 	struct nscookie nsc;
243 
244 	nsinfo__mountns_enter(nsi, &nsc);
245 	from_fp = fopen(from, "r");
246 	nsinfo__mountns_exit(&nsc);
247 	if (from_fp == NULL)
248 		goto out;
249 
250 	to_fp = fopen(to, "w");
251 	if (to_fp == NULL)
252 		goto out_fclose_from;
253 
254 	while (getline(&line, &n, from_fp) > 0)
255 		if (fputs(line, to_fp) == EOF)
256 			goto out_fclose_to;
257 	err = 0;
258 out_fclose_to:
259 	fclose(to_fp);
260 	free(line);
261 out_fclose_from:
262 	fclose(from_fp);
263 out:
264 	return err;
265 }
266 
267 int copyfile_offset(int ifd, loff_t off_in, int ofd, loff_t off_out, u64 size)
268 {
269 	void *ptr;
270 	loff_t pgoff;
271 
272 	pgoff = off_in & ~(page_size - 1);
273 	off_in -= pgoff;
274 
275 	ptr = mmap(NULL, off_in + size, PROT_READ, MAP_PRIVATE, ifd, pgoff);
276 	if (ptr == MAP_FAILED)
277 		return -1;
278 
279 	while (size) {
280 		ssize_t ret = pwrite(ofd, ptr + off_in, size, off_out);
281 		if (ret < 0 && errno == EINTR)
282 			continue;
283 		if (ret <= 0)
284 			break;
285 
286 		size -= ret;
287 		off_in += ret;
288 		off_out += ret;
289 	}
290 	munmap(ptr, off_in + size);
291 
292 	return size ? -1 : 0;
293 }
294 
295 static int copyfile_mode_ns(const char *from, const char *to, mode_t mode,
296 			    struct nsinfo *nsi)
297 {
298 	int fromfd, tofd;
299 	struct stat st;
300 	int err;
301 	char *tmp = NULL, *ptr = NULL;
302 	struct nscookie nsc;
303 
304 	nsinfo__mountns_enter(nsi, &nsc);
305 	err = stat(from, &st);
306 	nsinfo__mountns_exit(&nsc);
307 	if (err)
308 		goto out;
309 	err = -1;
310 
311 	/* extra 'x' at the end is to reserve space for '.' */
312 	if (asprintf(&tmp, "%s.XXXXXXx", to) < 0) {
313 		tmp = NULL;
314 		goto out;
315 	}
316 	ptr = strrchr(tmp, '/');
317 	if (!ptr)
318 		goto out;
319 	ptr = memmove(ptr + 1, ptr, strlen(ptr) - 1);
320 	*ptr = '.';
321 
322 	tofd = mkstemp(tmp);
323 	if (tofd < 0)
324 		goto out;
325 
326 	if (fchmod(tofd, mode))
327 		goto out_close_to;
328 
329 	if (st.st_size == 0) { /* /proc? do it slowly... */
330 		err = slow_copyfile(from, tmp, nsi);
331 		goto out_close_to;
332 	}
333 
334 	nsinfo__mountns_enter(nsi, &nsc);
335 	fromfd = open(from, O_RDONLY);
336 	nsinfo__mountns_exit(&nsc);
337 	if (fromfd < 0)
338 		goto out_close_to;
339 
340 	err = copyfile_offset(fromfd, 0, tofd, 0, st.st_size);
341 
342 	close(fromfd);
343 out_close_to:
344 	close(tofd);
345 	if (!err)
346 		err = link(tmp, to);
347 	unlink(tmp);
348 out:
349 	free(tmp);
350 	return err;
351 }
352 
353 int copyfile_ns(const char *from, const char *to, struct nsinfo *nsi)
354 {
355 	return copyfile_mode_ns(from, to, 0755, nsi);
356 }
357 
358 int copyfile_mode(const char *from, const char *to, mode_t mode)
359 {
360 	return copyfile_mode_ns(from, to, mode, NULL);
361 }
362 
363 int copyfile(const char *from, const char *to)
364 {
365 	return copyfile_mode(from, to, 0755);
366 }
367 
368 size_t hex_width(u64 v)
369 {
370 	size_t n = 1;
371 
372 	while ((v >>= 4))
373 		++n;
374 
375 	return n;
376 }
377 
378 int perf_event_paranoid(void)
379 {
380 	int value;
381 
382 	if (sysctl__read_int("kernel/perf_event_paranoid", &value))
383 		return INT_MAX;
384 
385 	return value;
386 }
387 
388 bool perf_event_paranoid_check(int max_level)
389 {
390 	return perf_cap__capable(CAP_SYS_ADMIN) ||
391 			perf_event_paranoid() <= max_level;
392 }
393 
394 static int
395 fetch_ubuntu_kernel_version(unsigned int *puint)
396 {
397 	ssize_t len;
398 	size_t line_len = 0;
399 	char *ptr, *line = NULL;
400 	int version, patchlevel, sublevel, err;
401 	FILE *vsig;
402 
403 	if (!puint)
404 		return 0;
405 
406 	vsig = fopen("/proc/version_signature", "r");
407 	if (!vsig) {
408 		pr_debug("Open /proc/version_signature failed: %s\n",
409 			 strerror(errno));
410 		return -1;
411 	}
412 
413 	len = getline(&line, &line_len, vsig);
414 	fclose(vsig);
415 	err = -1;
416 	if (len <= 0) {
417 		pr_debug("Reading from /proc/version_signature failed: %s\n",
418 			 strerror(errno));
419 		goto errout;
420 	}
421 
422 	ptr = strrchr(line, ' ');
423 	if (!ptr) {
424 		pr_debug("Parsing /proc/version_signature failed: %s\n", line);
425 		goto errout;
426 	}
427 
428 	err = sscanf(ptr + 1, "%d.%d.%d",
429 		     &version, &patchlevel, &sublevel);
430 	if (err != 3) {
431 		pr_debug("Unable to get kernel version from /proc/version_signature '%s'\n",
432 			 line);
433 		goto errout;
434 	}
435 
436 	*puint = (version << 16) + (patchlevel << 8) + sublevel;
437 	err = 0;
438 errout:
439 	free(line);
440 	return err;
441 }
442 
443 int
444 fetch_kernel_version(unsigned int *puint, char *str,
445 		     size_t str_size)
446 {
447 	struct utsname utsname;
448 	int version, patchlevel, sublevel, err;
449 	bool int_ver_ready = false;
450 
451 	if (access("/proc/version_signature", R_OK) == 0)
452 		if (!fetch_ubuntu_kernel_version(puint))
453 			int_ver_ready = true;
454 
455 	if (uname(&utsname))
456 		return -1;
457 
458 	if (str && str_size) {
459 		strncpy(str, utsname.release, str_size);
460 		str[str_size - 1] = '\0';
461 	}
462 
463 	if (!puint || int_ver_ready)
464 		return 0;
465 
466 	err = sscanf(utsname.release, "%d.%d.%d",
467 		     &version, &patchlevel, &sublevel);
468 
469 	if (err != 3) {
470 		pr_debug("Unable to get kernel version from uname '%s'\n",
471 			 utsname.release);
472 		return -1;
473 	}
474 
475 	*puint = (version << 16) + (patchlevel << 8) + sublevel;
476 	return 0;
477 }
478 
479 const char *perf_tip(const char *dirpath)
480 {
481 	struct strlist *tips;
482 	struct str_node *node;
483 	char *tip = NULL;
484 	struct strlist_config conf = {
485 		.dirname = dirpath,
486 		.file_only = true,
487 	};
488 
489 	tips = strlist__new("tips.txt", &conf);
490 	if (tips == NULL)
491 		return errno == ENOENT ? NULL :
492 			"Tip: check path of tips.txt or get more memory! ;-p";
493 
494 	if (strlist__nr_entries(tips) == 0)
495 		goto out;
496 
497 	node = strlist__entry(tips, random() % strlist__nr_entries(tips));
498 	if (asprintf(&tip, "Tip: %s", node->s) < 0)
499 		tip = (char *)"Tip: get more memory! ;-)";
500 
501 out:
502 	strlist__delete(tips);
503 
504 	return tip;
505 }
506 
507 char *perf_exe(char *buf, int len)
508 {
509 	int n = readlink("/proc/self/exe", buf, len);
510 	if (n > 0) {
511 		buf[n] = 0;
512 		return buf;
513 	}
514 	return strcpy(buf, "perf");
515 }
516