util.c 13 KB

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