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