1 // SPDX-License-Identifier: GPL-2.0
2 #include "perf.h"
3 #include "util.h"
4 #include "debug.h"
5 #include "event.h"
6 #include <api/fs/fs.h>
7 #include <sys/stat.h>
8 #include <sys/utsname.h>
9 #include <dirent.h>
10 #include <fcntl.h>
11 #include <inttypes.h>
12 #include <signal.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <errno.h>
17 #include <limits.h>
18 #include <linux/capability.h>
19 #include <linux/kernel.h>
20 #include <linux/log2.h>
21 #include <linux/time64.h>
22 #include <linux/overflow.h>
23 #include <unistd.h>
24 #include "cap.h"
25 #include "strlist.h"
26 #include "string2.h"
27
28 /*
29 * XXX We need to find a better place for these things...
30 */
31
32 const char *input_name;
33
34 bool perf_singlethreaded = true;
35
perf_set_singlethreaded(void)36 void perf_set_singlethreaded(void)
37 {
38 perf_singlethreaded = true;
39 }
40
perf_set_multithreaded(void)41 void perf_set_multithreaded(void)
42 {
43 perf_singlethreaded = false;
44 }
45
46 int sysctl_perf_event_max_stack = PERF_MAX_STACK_DEPTH;
47 int sysctl_perf_event_max_contexts_per_stack = PERF_MAX_CONTEXTS_PER_STACK;
48
sysctl__max_stack(void)49 int sysctl__max_stack(void)
50 {
51 int value;
52
53 if (sysctl__read_int("kernel/perf_event_max_stack", &value) == 0)
54 sysctl_perf_event_max_stack = value;
55
56 if (sysctl__read_int("kernel/perf_event_max_contexts_per_stack", &value) == 0)
57 sysctl_perf_event_max_contexts_per_stack = value;
58
59 return sysctl_perf_event_max_stack;
60 }
61
sysctl__nmi_watchdog_enabled(void)62 bool sysctl__nmi_watchdog_enabled(void)
63 {
64 static bool cached;
65 static bool nmi_watchdog;
66 int value;
67
68 if (cached)
69 return nmi_watchdog;
70
71 if (sysctl__read_int("kernel/nmi_watchdog", &value) < 0)
72 return false;
73
74 nmi_watchdog = (value > 0) ? true : false;
75 cached = true;
76
77 return nmi_watchdog;
78 }
79
80 bool test_attr__enabled;
81
82 bool exclude_GH_default;
83
84 bool perf_host = true;
85 bool perf_guest = false;
86
event_attr_init(struct perf_event_attr * attr)87 void event_attr_init(struct perf_event_attr *attr)
88 {
89 /* to capture ABI version */
90 attr->size = sizeof(*attr);
91
92 if (!exclude_GH_default)
93 return;
94
95 if (!perf_host)
96 attr->exclude_host = 1;
97 if (!perf_guest)
98 attr->exclude_guest = 1;
99 }
100
mkdir_p(char * path,mode_t mode)101 int mkdir_p(char *path, mode_t mode)
102 {
103 struct stat st;
104 int err;
105 char *d = path;
106
107 if (*d != '/')
108 return -1;
109
110 if (stat(path, &st) == 0)
111 return 0;
112
113 while (*++d == '/');
114
115 while ((d = strchr(d, '/'))) {
116 *d = '\0';
117 err = stat(path, &st) && mkdir(path, mode);
118 *d++ = '/';
119 if (err)
120 return -1;
121 while (*d == '/')
122 ++d;
123 }
124 return (stat(path, &st) && mkdir(path, mode)) ? -1 : 0;
125 }
126
match_pat(char * file,const char ** pat)127 static bool match_pat(char *file, const char **pat)
128 {
129 int i = 0;
130
131 if (!pat)
132 return true;
133
134 while (pat[i]) {
135 if (strglobmatch(file, pat[i]))
136 return true;
137
138 i++;
139 }
140
141 return false;
142 }
143
144 /*
145 * The depth specify how deep the removal will go.
146 * 0 - will remove only files under the 'path' directory
147 * 1 .. x - will dive in x-level deep under the 'path' directory
148 *
149 * If specified the pat is array of string patterns ended with NULL,
150 * which are checked upon every file/directory found. Only matching
151 * ones are removed.
152 *
153 * The function returns:
154 * 0 on success
155 * -1 on removal failure with errno set
156 * -2 on pattern failure
157 */
rm_rf_depth_pat(const char * path,int depth,const char ** pat)158 static int rm_rf_depth_pat(const char *path, int depth, const char **pat)
159 {
160 DIR *dir;
161 int ret;
162 struct dirent *d;
163 char namebuf[PATH_MAX];
164 struct stat statbuf;
165
166 /* Do not fail if there's no file. */
167 ret = lstat(path, &statbuf);
168 if (ret)
169 return 0;
170
171 /* Try to remove any file we get. */
172 if (!(statbuf.st_mode & S_IFDIR))
173 return unlink(path);
174
175 /* We have directory in path. */
176 dir = opendir(path);
177 if (dir == NULL)
178 return -1;
179
180 while ((d = readdir(dir)) != NULL && !ret) {
181
182 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
183 continue;
184
185 if (!match_pat(d->d_name, pat)) {
186 ret = -2;
187 break;
188 }
189
190 scnprintf(namebuf, sizeof(namebuf), "%s/%s",
191 path, d->d_name);
192
193 /* We have to check symbolic link itself */
194 ret = lstat(namebuf, &statbuf);
195 if (ret < 0) {
196 pr_debug("stat failed: %s\n", namebuf);
197 break;
198 }
199
200 if (S_ISDIR(statbuf.st_mode))
201 ret = depth ? rm_rf_depth_pat(namebuf, depth - 1, pat) : 0;
202 else
203 ret = unlink(namebuf);
204 }
205 closedir(dir);
206
207 if (ret < 0)
208 return ret;
209
210 return rmdir(path);
211 }
212
rm_rf_a_kcore_dir(const char * path,const char * name)213 static int rm_rf_a_kcore_dir(const char *path, const char *name)
214 {
215 char kcore_dir_path[PATH_MAX];
216 const char *pat[] = {
217 "kcore",
218 "kallsyms",
219 "modules",
220 NULL,
221 };
222
223 snprintf(kcore_dir_path, sizeof(kcore_dir_path), "%s/%s", path, name);
224
225 return rm_rf_depth_pat(kcore_dir_path, 0, pat);
226 }
227
kcore_dir_filter(const char * name __maybe_unused,struct dirent * d)228 static bool kcore_dir_filter(const char *name __maybe_unused, struct dirent *d)
229 {
230 const char *pat[] = {
231 "kcore_dir",
232 "kcore_dir__[1-9]*",
233 NULL,
234 };
235
236 return match_pat(d->d_name, pat);
237 }
238
rm_rf_kcore_dir(const char * path)239 static int rm_rf_kcore_dir(const char *path)
240 {
241 struct strlist *kcore_dirs;
242 struct str_node *nd;
243 int ret;
244
245 kcore_dirs = lsdir(path, kcore_dir_filter);
246
247 if (!kcore_dirs)
248 return 0;
249
250 strlist__for_each_entry(nd, kcore_dirs) {
251 ret = rm_rf_a_kcore_dir(path, nd->s);
252 if (ret)
253 return ret;
254 }
255
256 strlist__delete(kcore_dirs);
257
258 return 0;
259 }
260
cpumask_to_cpulist(char * cpumask,char * cpulist)261 void cpumask_to_cpulist(char *cpumask, char *cpulist)
262 {
263 int i, j, bm_size, nbits;
264 int len = strlen(cpumask);
265 unsigned long *bm;
266 char cpus[MAX_NR_CPUS];
267
268 for (i = 0; i < len; i++) {
269 if (cpumask[i] == ',') {
270 for (j = i; j < len; j++)
271 cpumask[j] = cpumask[j + 1];
272 }
273 }
274
275 len = strlen(cpumask);
276 bm_size = (len + 15) / 16;
277 nbits = bm_size * 64;
278 if (nbits <= 0)
279 return;
280
281 bm = calloc(bm_size, sizeof(unsigned long));
282 if (!bm)
283 goto free_bm;
284
285 for (i = 0; i < bm_size; i++) {
286 char blk[17];
287 int blklen = len > 16 ? 16 : len;
288
289 strncpy(blk, cpumask + len - blklen, blklen);
290 blk[blklen] = '\0';
291 bm[i] = strtoul(blk, NULL, 16);
292 cpumask[len - blklen] = '\0';
293 len = strlen(cpumask);
294 }
295
296 bitmap_scnprintf(bm, nbits, cpus, sizeof(cpus));
297 strcpy(cpulist, cpus);
298
299 free_bm:
300 free(bm);
301 }
302
print_separator2(int pre_dash_cnt,const char * s,int post_dash_cnt)303 void print_separator2(int pre_dash_cnt, const char *s, int post_dash_cnt)
304 {
305 printf("%.*s%s%.*s\n", pre_dash_cnt, graph_dotted_line, s, post_dash_cnt,
306 graph_dotted_line);
307 }
308
rm_rf_perf_data(const char * path)309 int rm_rf_perf_data(const char *path)
310 {
311 const char *pat[] = {
312 "data",
313 "data.*",
314 NULL,
315 };
316
317 rm_rf_kcore_dir(path);
318
319 return rm_rf_depth_pat(path, 0, pat);
320 }
321
rm_rf(const char * path)322 int rm_rf(const char *path)
323 {
324 return rm_rf_depth_pat(path, INT_MAX, NULL);
325 }
326
327 /* A filter which removes dot files */
lsdir_no_dot_filter(const char * name __maybe_unused,struct dirent * d)328 bool lsdir_no_dot_filter(const char *name __maybe_unused, struct dirent *d)
329 {
330 return d->d_name[0] != '.';
331 }
332
333 /* lsdir reads a directory and store it in strlist */
lsdir(const char * name,bool (* filter)(const char *,struct dirent *))334 struct strlist *lsdir(const char *name,
335 bool (*filter)(const char *, struct dirent *))
336 {
337 struct strlist *list = NULL;
338 DIR *dir;
339 struct dirent *d;
340
341 dir = opendir(name);
342 if (!dir)
343 return NULL;
344
345 list = strlist__new(NULL, NULL);
346 if (!list) {
347 errno = ENOMEM;
348 goto out;
349 }
350
351 while ((d = readdir(dir)) != NULL) {
352 if (!filter || filter(name, d))
353 strlist__add(list, d->d_name);
354 }
355
356 out:
357 closedir(dir);
358 return list;
359 }
360
hex_width(u64 v)361 size_t hex_width(u64 v)
362 {
363 size_t n = 1;
364
365 while ((v >>= 4))
366 ++n;
367
368 return n;
369 }
370
perf_event_paranoid(void)371 int perf_event_paranoid(void)
372 {
373 int value;
374
375 if (sysctl__read_int("kernel/perf_event_paranoid", &value))
376 return INT_MAX;
377
378 return value;
379 }
380
perf_event_paranoid_check(int max_level)381 bool perf_event_paranoid_check(int max_level)
382 {
383 bool used_root;
384
385 if (perf_cap__capable(CAP_SYS_ADMIN, &used_root))
386 return true;
387
388 if (!used_root && perf_cap__capable(CAP_PERFMON, &used_root))
389 return true;
390
391 return perf_event_paranoid() <= max_level;
392 }
393
perf_tip(char ** strp,const char * dirpath)394 int perf_tip(char **strp, const char *dirpath)
395 {
396 struct strlist *tips;
397 struct str_node *node;
398 struct strlist_config conf = {
399 .dirname = dirpath,
400 .file_only = true,
401 };
402 int ret = 0;
403
404 *strp = NULL;
405 tips = strlist__new("tips.txt", &conf);
406 if (tips == NULL)
407 return -errno;
408
409 if (strlist__nr_entries(tips) == 0)
410 goto out;
411
412 node = strlist__entry(tips, random() % strlist__nr_entries(tips));
413 if (asprintf(strp, "Tip: %s", node->s) < 0)
414 ret = -ENOMEM;
415
416 out:
417 strlist__delete(tips);
418
419 return ret;
420 }
421
perf_exe(char * buf,int len)422 char *perf_exe(char *buf, int len)
423 {
424 int n = readlink("/proc/self/exe", buf, len);
425 if (n > 0) {
426 buf[n] = 0;
427 return buf;
428 }
429 return strcpy(buf, "perf");
430 }
431
perf_debuginfod_setup(struct perf_debuginfod * di)432 void perf_debuginfod_setup(struct perf_debuginfod *di)
433 {
434 /*
435 * By default '!di->set' we clear DEBUGINFOD_URLS, so debuginfod
436 * processing is not triggered, otherwise we set it to 'di->urls'
437 * value. If 'di->urls' is "system" we keep DEBUGINFOD_URLS value.
438 */
439 if (!di->set)
440 setenv("DEBUGINFOD_URLS", "", 1);
441 else if (di->urls && strcmp(di->urls, "system"))
442 setenv("DEBUGINFOD_URLS", di->urls, 1);
443
444 pr_debug("DEBUGINFOD_URLS=%s\n", getenv("DEBUGINFOD_URLS"));
445
446 #ifndef HAVE_DEBUGINFOD_SUPPORT
447 if (di->set)
448 pr_warning("WARNING: debuginfod support requested, but perf is not built with it\n");
449 #endif
450 }
451
452 /*
453 * Return a new filename prepended with task's root directory if it's in
454 * a chroot. Callers should free the returned string.
455 */
filename_with_chroot(int pid,const char * filename)456 char *filename_with_chroot(int pid, const char *filename)
457 {
458 char buf[PATH_MAX];
459 char proc_root[32];
460 char *new_name = NULL;
461 int ret;
462
463 scnprintf(proc_root, sizeof(proc_root), "/proc/%d/root", pid);
464 ret = readlink(proc_root, buf, sizeof(buf) - 1);
465 if (ret <= 0)
466 return NULL;
467
468 /* readlink(2) does not append a null byte to buf */
469 buf[ret] = '\0';
470
471 if (!strcmp(buf, "/"))
472 return NULL;
473
474 if (strstr(buf, "(deleted)"))
475 return NULL;
476
477 if (asprintf(&new_name, "%s/%s", buf, filename) < 0)
478 return NULL;
479
480 return new_name;
481 }
482
483 /*
484 * Reallocate an array *arr of size *arr_sz so that it is big enough to contain
485 * x elements of size msz, initializing new entries to *init_val or zero if
486 * init_val is NULL
487 */
do_realloc_array_as_needed(void ** arr,size_t * arr_sz,size_t x,size_t msz,const void * init_val)488 int do_realloc_array_as_needed(void **arr, size_t *arr_sz, size_t x, size_t msz, const void *init_val)
489 {
490 size_t new_sz = *arr_sz;
491 void *new_arr;
492 size_t i;
493
494 if (!new_sz)
495 new_sz = msz >= 64 ? 1 : roundup(64, msz); /* Start with at least 64 bytes */
496 while (x >= new_sz) {
497 if (check_mul_overflow(new_sz, (size_t)2, &new_sz))
498 return -ENOMEM;
499 }
500 if (new_sz == *arr_sz)
501 return 0;
502 new_arr = calloc(new_sz, msz);
503 if (!new_arr)
504 return -ENOMEM;
505 if (*arr_sz)
506 memcpy(new_arr, *arr, *arr_sz * msz);
507 if (init_val) {
508 for (i = *arr_sz; i < new_sz; i++)
509 memcpy(new_arr + (i * msz), init_val, msz);
510 }
511 *arr = new_arr;
512 *arr_sz = new_sz;
513 return 0;
514 }
515
516 #ifndef HAVE_SCHED_GETCPU_SUPPORT
sched_getcpu(void)517 int sched_getcpu(void)
518 {
519 #ifdef __NR_getcpu
520 unsigned int cpu;
521 int err = syscall(__NR_getcpu, &cpu, NULL, NULL);
522
523 if (!err)
524 return cpu;
525 #else
526 errno = ENOSYS;
527 #endif
528 return -1;
529 }
530 #endif
531
532 #ifndef HAVE_SCANDIRAT_SUPPORT
scandirat(int dirfd,const char * dirp,struct dirent *** namelist,int (* filter)(const struct dirent *),int (* compar)(const struct dirent **,const struct dirent **))533 int scandirat(int dirfd, const char *dirp,
534 struct dirent ***namelist,
535 int (*filter)(const struct dirent *),
536 int (*compar)(const struct dirent **, const struct dirent **))
537 {
538 char path[PATH_MAX];
539 int err, fd = openat(dirfd, dirp, O_PATH);
540
541 if (fd < 0)
542 return fd;
543
544 snprintf(path, sizeof(path), "/proc/%d/fd/%d", getpid(), fd);
545 err = scandir(path, namelist, filter, compar);
546 close(fd);
547 return err;
548 }
549 #endif
550