util.c 10 KB

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