util.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. #include "../perf.h"
  2. #include "util.h"
  3. #include "debug.h"
  4. #include <api/fs/fs.h>
  5. #include <sys/mman.h>
  6. #include <sys/utsname.h>
  7. #ifdef HAVE_BACKTRACE_SUPPORT
  8. #include <execinfo.h>
  9. #endif
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include <errno.h>
  14. #include <limits.h>
  15. #include <byteswap.h>
  16. #include <linux/kernel.h>
  17. #include <linux/log2.h>
  18. #include <linux/time64.h>
  19. #include <unistd.h>
  20. #include "callchain.h"
  21. #include "strlist.h"
  22. #define CALLCHAIN_PARAM_DEFAULT \
  23. .mode = CHAIN_GRAPH_ABS, \
  24. .min_percent = 0.5, \
  25. .order = ORDER_CALLEE, \
  26. .key = CCKEY_FUNCTION, \
  27. .value = CCVAL_PERCENT, \
  28. struct callchain_param callchain_param = {
  29. CALLCHAIN_PARAM_DEFAULT
  30. };
  31. struct callchain_param callchain_param_default = {
  32. CALLCHAIN_PARAM_DEFAULT
  33. };
  34. /*
  35. * XXX We need to find a better place for these things...
  36. */
  37. unsigned int page_size;
  38. int cacheline_size;
  39. int sysctl_perf_event_max_stack = PERF_MAX_STACK_DEPTH;
  40. int sysctl_perf_event_max_contexts_per_stack = PERF_MAX_CONTEXTS_PER_STACK;
  41. bool test_attr__enabled;
  42. bool perf_host = true;
  43. bool perf_guest = false;
  44. void event_attr_init(struct perf_event_attr *attr)
  45. {
  46. if (!perf_host)
  47. attr->exclude_host = 1;
  48. if (!perf_guest)
  49. attr->exclude_guest = 1;
  50. /* to capture ABI version */
  51. attr->size = sizeof(*attr);
  52. }
  53. int mkdir_p(char *path, mode_t mode)
  54. {
  55. struct stat st;
  56. int err;
  57. char *d = path;
  58. if (*d != '/')
  59. return -1;
  60. if (stat(path, &st) == 0)
  61. return 0;
  62. while (*++d == '/');
  63. while ((d = strchr(d, '/'))) {
  64. *d = '\0';
  65. err = stat(path, &st) && mkdir(path, mode);
  66. *d++ = '/';
  67. if (err)
  68. return -1;
  69. while (*d == '/')
  70. ++d;
  71. }
  72. return (stat(path, &st) && mkdir(path, mode)) ? -1 : 0;
  73. }
  74. int rm_rf(char *path)
  75. {
  76. DIR *dir;
  77. int ret = 0;
  78. struct dirent *d;
  79. char namebuf[PATH_MAX];
  80. dir = opendir(path);
  81. if (dir == NULL)
  82. return 0;
  83. while ((d = readdir(dir)) != NULL && !ret) {
  84. struct stat statbuf;
  85. if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
  86. continue;
  87. scnprintf(namebuf, sizeof(namebuf), "%s/%s",
  88. path, d->d_name);
  89. /* We have to check symbolic link itself */
  90. ret = lstat(namebuf, &statbuf);
  91. if (ret < 0) {
  92. pr_debug("stat failed: %s\n", namebuf);
  93. break;
  94. }
  95. if (S_ISDIR(statbuf.st_mode))
  96. ret = rm_rf(namebuf);
  97. else
  98. ret = unlink(namebuf);
  99. }
  100. closedir(dir);
  101. if (ret < 0)
  102. return ret;
  103. return rmdir(path);
  104. }
  105. /* A filter which removes dot files */
  106. bool lsdir_no_dot_filter(const char *name __maybe_unused, struct dirent *d)
  107. {
  108. return d->d_name[0] != '.';
  109. }
  110. /* lsdir reads a directory and store it in strlist */
  111. struct strlist *lsdir(const char *name,
  112. bool (*filter)(const char *, struct dirent *))
  113. {
  114. struct strlist *list = NULL;
  115. DIR *dir;
  116. struct dirent *d;
  117. dir = opendir(name);
  118. if (!dir)
  119. return NULL;
  120. list = strlist__new(NULL, NULL);
  121. if (!list) {
  122. errno = ENOMEM;
  123. goto out;
  124. }
  125. while ((d = readdir(dir)) != NULL) {
  126. if (!filter || filter(name, d))
  127. strlist__add(list, d->d_name);
  128. }
  129. out:
  130. closedir(dir);
  131. return list;
  132. }
  133. static int slow_copyfile(const char *from, const char *to)
  134. {
  135. int err = -1;
  136. char *line = NULL;
  137. size_t n;
  138. FILE *from_fp = fopen(from, "r"), *to_fp;
  139. if (from_fp == NULL)
  140. goto out;
  141. to_fp = fopen(to, "w");
  142. if (to_fp == NULL)
  143. goto out_fclose_from;
  144. while (getline(&line, &n, from_fp) > 0)
  145. if (fputs(line, to_fp) == EOF)
  146. goto out_fclose_to;
  147. err = 0;
  148. out_fclose_to:
  149. fclose(to_fp);
  150. free(line);
  151. out_fclose_from:
  152. fclose(from_fp);
  153. out:
  154. return err;
  155. }
  156. int copyfile_offset(int ifd, loff_t off_in, int ofd, loff_t off_out, u64 size)
  157. {
  158. void *ptr;
  159. loff_t pgoff;
  160. pgoff = off_in & ~(page_size - 1);
  161. off_in -= pgoff;
  162. ptr = mmap(NULL, off_in + size, PROT_READ, MAP_PRIVATE, ifd, pgoff);
  163. if (ptr == MAP_FAILED)
  164. return -1;
  165. while (size) {
  166. ssize_t ret = pwrite(ofd, ptr + off_in, size, off_out);
  167. if (ret < 0 && errno == EINTR)
  168. continue;
  169. if (ret <= 0)
  170. break;
  171. size -= ret;
  172. off_in += ret;
  173. off_out += ret;
  174. }
  175. munmap(ptr, off_in + size);
  176. return size ? -1 : 0;
  177. }
  178. int copyfile_mode(const char *from, const char *to, mode_t mode)
  179. {
  180. int fromfd, tofd;
  181. struct stat st;
  182. int err = -1;
  183. char *tmp = NULL, *ptr = NULL;
  184. if (stat(from, &st))
  185. goto out;
  186. /* extra 'x' at the end is to reserve space for '.' */
  187. if (asprintf(&tmp, "%s.XXXXXXx", to) < 0) {
  188. tmp = NULL;
  189. goto out;
  190. }
  191. ptr = strrchr(tmp, '/');
  192. if (!ptr)
  193. goto out;
  194. ptr = memmove(ptr + 1, ptr, strlen(ptr) - 1);
  195. *ptr = '.';
  196. tofd = mkstemp(tmp);
  197. if (tofd < 0)
  198. goto out;
  199. if (fchmod(tofd, mode))
  200. goto out_close_to;
  201. if (st.st_size == 0) { /* /proc? do it slowly... */
  202. err = slow_copyfile(from, tmp);
  203. goto out_close_to;
  204. }
  205. fromfd = open(from, O_RDONLY);
  206. if (fromfd < 0)
  207. goto out_close_to;
  208. err = copyfile_offset(fromfd, 0, tofd, 0, st.st_size);
  209. close(fromfd);
  210. out_close_to:
  211. close(tofd);
  212. if (!err)
  213. err = link(tmp, to);
  214. unlink(tmp);
  215. out:
  216. free(tmp);
  217. return err;
  218. }
  219. int copyfile(const char *from, const char *to)
  220. {
  221. return copyfile_mode(from, to, 0755);
  222. }
  223. unsigned long convert_unit(unsigned long value, char *unit)
  224. {
  225. *unit = ' ';
  226. if (value > 1000) {
  227. value /= 1000;
  228. *unit = 'K';
  229. }
  230. if (value > 1000) {
  231. value /= 1000;
  232. *unit = 'M';
  233. }
  234. if (value > 1000) {
  235. value /= 1000;
  236. *unit = 'G';
  237. }
  238. return value;
  239. }
  240. static ssize_t ion(bool is_read, int fd, void *buf, size_t n)
  241. {
  242. void *buf_start = buf;
  243. size_t left = n;
  244. while (left) {
  245. ssize_t ret = is_read ? read(fd, buf, left) :
  246. write(fd, buf, left);
  247. if (ret < 0 && errno == EINTR)
  248. continue;
  249. if (ret <= 0)
  250. return ret;
  251. left -= ret;
  252. buf += ret;
  253. }
  254. BUG_ON((size_t)(buf - buf_start) != n);
  255. return n;
  256. }
  257. /*
  258. * Read exactly 'n' bytes or return an error.
  259. */
  260. ssize_t readn(int fd, void *buf, size_t n)
  261. {
  262. return ion(true, fd, buf, n);
  263. }
  264. /*
  265. * Write exactly 'n' bytes or return an error.
  266. */
  267. ssize_t writen(int fd, void *buf, size_t n)
  268. {
  269. return ion(false, fd, buf, n);
  270. }
  271. size_t hex_width(u64 v)
  272. {
  273. size_t n = 1;
  274. while ((v >>= 4))
  275. ++n;
  276. return n;
  277. }
  278. static int hex(char ch)
  279. {
  280. if ((ch >= '0') && (ch <= '9'))
  281. return ch - '0';
  282. if ((ch >= 'a') && (ch <= 'f'))
  283. return ch - 'a' + 10;
  284. if ((ch >= 'A') && (ch <= 'F'))
  285. return ch - 'A' + 10;
  286. return -1;
  287. }
  288. /*
  289. * While we find nice hex chars, build a long_val.
  290. * Return number of chars processed.
  291. */
  292. int hex2u64(const char *ptr, u64 *long_val)
  293. {
  294. const char *p = ptr;
  295. *long_val = 0;
  296. while (*p) {
  297. const int hex_val = hex(*p);
  298. if (hex_val < 0)
  299. break;
  300. *long_val = (*long_val << 4) | hex_val;
  301. p++;
  302. }
  303. return p - ptr;
  304. }
  305. /* Obtain a backtrace and print it to stdout. */
  306. #ifdef HAVE_BACKTRACE_SUPPORT
  307. void dump_stack(void)
  308. {
  309. void *array[16];
  310. size_t size = backtrace(array, ARRAY_SIZE(array));
  311. char **strings = backtrace_symbols(array, size);
  312. size_t i;
  313. printf("Obtained %zd stack frames.\n", size);
  314. for (i = 0; i < size; i++)
  315. printf("%s\n", strings[i]);
  316. free(strings);
  317. }
  318. #else
  319. void dump_stack(void) {}
  320. #endif
  321. void sighandler_dump_stack(int sig)
  322. {
  323. psignal(sig, "perf");
  324. dump_stack();
  325. signal(sig, SIG_DFL);
  326. raise(sig);
  327. }
  328. int parse_nsec_time(const char *str, u64 *ptime)
  329. {
  330. u64 time_sec, time_nsec;
  331. char *end;
  332. time_sec = strtoul(str, &end, 10);
  333. if (*end != '.' && *end != '\0')
  334. return -1;
  335. if (*end == '.') {
  336. int i;
  337. char nsec_buf[10];
  338. if (strlen(++end) > 9)
  339. return -1;
  340. strncpy(nsec_buf, end, 9);
  341. nsec_buf[9] = '\0';
  342. /* make it nsec precision */
  343. for (i = strlen(nsec_buf); i < 9; i++)
  344. nsec_buf[i] = '0';
  345. time_nsec = strtoul(nsec_buf, &end, 10);
  346. if (*end != '\0')
  347. return -1;
  348. } else
  349. time_nsec = 0;
  350. *ptime = time_sec * NSEC_PER_SEC + time_nsec;
  351. return 0;
  352. }
  353. unsigned long parse_tag_value(const char *str, struct parse_tag *tags)
  354. {
  355. struct parse_tag *i = tags;
  356. while (i->tag) {
  357. char *s;
  358. s = strchr(str, i->tag);
  359. if (s) {
  360. unsigned long int value;
  361. char *endptr;
  362. value = strtoul(str, &endptr, 10);
  363. if (s != endptr)
  364. break;
  365. if (value > ULONG_MAX / i->mult)
  366. break;
  367. value *= i->mult;
  368. return value;
  369. }
  370. i++;
  371. }
  372. return (unsigned long) -1;
  373. }
  374. int get_stack_size(const char *str, unsigned long *_size)
  375. {
  376. char *endptr;
  377. unsigned long size;
  378. unsigned long max_size = round_down(USHRT_MAX, sizeof(u64));
  379. size = strtoul(str, &endptr, 0);
  380. do {
  381. if (*endptr)
  382. break;
  383. size = round_up(size, sizeof(u64));
  384. if (!size || size > max_size)
  385. break;
  386. *_size = size;
  387. return 0;
  388. } while (0);
  389. pr_err("callchain: Incorrect stack dump size (max %ld): %s\n",
  390. max_size, str);
  391. return -1;
  392. }
  393. int parse_callchain_record(const char *arg, struct callchain_param *param)
  394. {
  395. char *tok, *name, *saveptr = NULL;
  396. char *buf;
  397. int ret = -1;
  398. /* We need buffer that we know we can write to. */
  399. buf = malloc(strlen(arg) + 1);
  400. if (!buf)
  401. return -ENOMEM;
  402. strcpy(buf, arg);
  403. tok = strtok_r((char *)buf, ",", &saveptr);
  404. name = tok ? : (char *)buf;
  405. do {
  406. /* Framepointer style */
  407. if (!strncmp(name, "fp", sizeof("fp"))) {
  408. if (!strtok_r(NULL, ",", &saveptr)) {
  409. param->record_mode = CALLCHAIN_FP;
  410. ret = 0;
  411. } else
  412. pr_err("callchain: No more arguments "
  413. "needed for --call-graph fp\n");
  414. break;
  415. /* Dwarf style */
  416. } else if (!strncmp(name, "dwarf", sizeof("dwarf"))) {
  417. const unsigned long default_stack_dump_size = 8192;
  418. ret = 0;
  419. param->record_mode = CALLCHAIN_DWARF;
  420. param->dump_size = default_stack_dump_size;
  421. tok = strtok_r(NULL, ",", &saveptr);
  422. if (tok) {
  423. unsigned long size = 0;
  424. ret = get_stack_size(tok, &size);
  425. param->dump_size = size;
  426. }
  427. } else if (!strncmp(name, "lbr", sizeof("lbr"))) {
  428. if (!strtok_r(NULL, ",", &saveptr)) {
  429. param->record_mode = CALLCHAIN_LBR;
  430. ret = 0;
  431. } else
  432. pr_err("callchain: No more arguments "
  433. "needed for --call-graph lbr\n");
  434. break;
  435. } else {
  436. pr_err("callchain: Unknown --call-graph option "
  437. "value: %s\n", arg);
  438. break;
  439. }
  440. } while (0);
  441. free(buf);
  442. return ret;
  443. }
  444. const char *get_filename_for_perf_kvm(void)
  445. {
  446. const char *filename;
  447. if (perf_host && !perf_guest)
  448. filename = strdup("perf.data.host");
  449. else if (!perf_host && perf_guest)
  450. filename = strdup("perf.data.guest");
  451. else
  452. filename = strdup("perf.data.kvm");
  453. return filename;
  454. }
  455. int perf_event_paranoid(void)
  456. {
  457. int value;
  458. if (sysctl__read_int("kernel/perf_event_paranoid", &value))
  459. return INT_MAX;
  460. return value;
  461. }
  462. void mem_bswap_32(void *src, int byte_size)
  463. {
  464. u32 *m = src;
  465. while (byte_size > 0) {
  466. *m = bswap_32(*m);
  467. byte_size -= sizeof(u32);
  468. ++m;
  469. }
  470. }
  471. void mem_bswap_64(void *src, int byte_size)
  472. {
  473. u64 *m = src;
  474. while (byte_size > 0) {
  475. *m = bswap_64(*m);
  476. byte_size -= sizeof(u64);
  477. ++m;
  478. }
  479. }
  480. bool find_process(const char *name)
  481. {
  482. size_t len = strlen(name);
  483. DIR *dir;
  484. struct dirent *d;
  485. int ret = -1;
  486. dir = opendir(procfs__mountpoint());
  487. if (!dir)
  488. return false;
  489. /* Walk through the directory. */
  490. while (ret && (d = readdir(dir)) != NULL) {
  491. char path[PATH_MAX];
  492. char *data;
  493. size_t size;
  494. if ((d->d_type != DT_DIR) ||
  495. !strcmp(".", d->d_name) ||
  496. !strcmp("..", d->d_name))
  497. continue;
  498. scnprintf(path, sizeof(path), "%s/%s/comm",
  499. procfs__mountpoint(), d->d_name);
  500. if (filename__read_str(path, &data, &size))
  501. continue;
  502. ret = strncmp(name, data, len);
  503. free(data);
  504. }
  505. closedir(dir);
  506. return ret ? false : true;
  507. }
  508. int
  509. fetch_kernel_version(unsigned int *puint, char *str,
  510. size_t str_size)
  511. {
  512. struct utsname utsname;
  513. int version, patchlevel, sublevel, err;
  514. if (uname(&utsname))
  515. return -1;
  516. if (str && str_size) {
  517. strncpy(str, utsname.release, str_size);
  518. str[str_size - 1] = '\0';
  519. }
  520. err = sscanf(utsname.release, "%d.%d.%d",
  521. &version, &patchlevel, &sublevel);
  522. if (err != 3) {
  523. pr_debug("Unablt to get kernel version from uname '%s'\n",
  524. utsname.release);
  525. return -1;
  526. }
  527. if (puint)
  528. *puint = (version << 16) + (patchlevel << 8) + sublevel;
  529. return 0;
  530. }
  531. const char *perf_tip(const char *dirpath)
  532. {
  533. struct strlist *tips;
  534. struct str_node *node;
  535. char *tip = NULL;
  536. struct strlist_config conf = {
  537. .dirname = dirpath,
  538. .file_only = true,
  539. };
  540. tips = strlist__new("tips.txt", &conf);
  541. if (tips == NULL)
  542. return errno == ENOENT ? NULL : "Tip: get more memory! ;-p";
  543. if (strlist__nr_entries(tips) == 0)
  544. goto out;
  545. node = strlist__entry(tips, random() % strlist__nr_entries(tips));
  546. if (asprintf(&tip, "Tip: %s", node->s) < 0)
  547. tip = (char *)"Tip: get more memory! ;-)";
  548. out:
  549. strlist__delete(tips);
  550. return tip;
  551. }
  552. bool is_regular_file(const char *file)
  553. {
  554. struct stat st;
  555. if (stat(file, &st))
  556. return false;
  557. return S_ISREG(st.st_mode);
  558. }
  559. int fetch_current_timestamp(char *buf, size_t sz)
  560. {
  561. struct timeval tv;
  562. struct tm tm;
  563. char dt[32];
  564. if (gettimeofday(&tv, NULL) || !localtime_r(&tv.tv_sec, &tm))
  565. return -1;
  566. if (!strftime(dt, sizeof(dt), "%Y%m%d%H%M%S", &tm))
  567. return -1;
  568. scnprintf(buf, sz, "%s%02u", dt, (unsigned)tv.tv_usec / 10000);
  569. return 0;
  570. }
  571. void print_binary(unsigned char *data, size_t len,
  572. size_t bytes_per_line, print_binary_t printer,
  573. void *extra)
  574. {
  575. size_t i, j, mask;
  576. if (!printer)
  577. return;
  578. bytes_per_line = roundup_pow_of_two(bytes_per_line);
  579. mask = bytes_per_line - 1;
  580. printer(BINARY_PRINT_DATA_BEGIN, 0, extra);
  581. for (i = 0; i < len; i++) {
  582. if ((i & mask) == 0) {
  583. printer(BINARY_PRINT_LINE_BEGIN, -1, extra);
  584. printer(BINARY_PRINT_ADDR, i, extra);
  585. }
  586. printer(BINARY_PRINT_NUM_DATA, data[i], extra);
  587. if (((i & mask) == mask) || i == len - 1) {
  588. for (j = 0; j < mask-(i & mask); j++)
  589. printer(BINARY_PRINT_NUM_PAD, -1, extra);
  590. printer(BINARY_PRINT_SEP, i, extra);
  591. for (j = i & ~mask; j <= i; j++)
  592. printer(BINARY_PRINT_CHAR_DATA, data[j], extra);
  593. for (j = 0; j < mask-(i & mask); j++)
  594. printer(BINARY_PRINT_CHAR_PAD, i, extra);
  595. printer(BINARY_PRINT_LINE_END, -1, extra);
  596. }
  597. }
  598. printer(BINARY_PRINT_DATA_END, -1, extra);
  599. }
  600. int is_printable_array(char *p, unsigned int len)
  601. {
  602. unsigned int i;
  603. if (!p || !len || p[len - 1] != 0)
  604. return 0;
  605. len--;
  606. for (i = 0; i < len; i++) {
  607. if (!isprint(p[i]) && !isspace(p[i]))
  608. return 0;
  609. }
  610. return 1;
  611. }