util.c 13 KB

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