util.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. #include "../perf.h"
  2. #include "util.h"
  3. #include "debug.h"
  4. #include <api/fs/fs.h>
  5. #include <sys/mman.h>
  6. #ifdef HAVE_BACKTRACE_SUPPORT
  7. #include <execinfo.h>
  8. #endif
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <errno.h>
  13. #include <limits.h>
  14. #include <byteswap.h>
  15. #include <linux/kernel.h>
  16. #include <unistd.h>
  17. #include "callchain.h"
  18. struct callchain_param callchain_param = {
  19. .mode = CHAIN_GRAPH_ABS,
  20. .min_percent = 0.5,
  21. .order = ORDER_CALLER,
  22. .key = CCKEY_FUNCTION
  23. };
  24. /*
  25. * XXX We need to find a better place for these things...
  26. */
  27. unsigned int page_size;
  28. int cacheline_size;
  29. bool test_attr__enabled;
  30. bool perf_host = true;
  31. bool perf_guest = false;
  32. void event_attr_init(struct perf_event_attr *attr)
  33. {
  34. if (!perf_host)
  35. attr->exclude_host = 1;
  36. if (!perf_guest)
  37. attr->exclude_guest = 1;
  38. /* to capture ABI version */
  39. attr->size = sizeof(*attr);
  40. }
  41. int mkdir_p(char *path, mode_t mode)
  42. {
  43. struct stat st;
  44. int err;
  45. char *d = path;
  46. if (*d != '/')
  47. return -1;
  48. if (stat(path, &st) == 0)
  49. return 0;
  50. while (*++d == '/');
  51. while ((d = strchr(d, '/'))) {
  52. *d = '\0';
  53. err = stat(path, &st) && mkdir(path, mode);
  54. *d++ = '/';
  55. if (err)
  56. return -1;
  57. while (*d == '/')
  58. ++d;
  59. }
  60. return (stat(path, &st) && mkdir(path, mode)) ? -1 : 0;
  61. }
  62. int rm_rf(char *path)
  63. {
  64. DIR *dir;
  65. int ret = 0;
  66. struct dirent *d;
  67. char namebuf[PATH_MAX];
  68. dir = opendir(path);
  69. if (dir == NULL)
  70. return 0;
  71. while ((d = readdir(dir)) != NULL && !ret) {
  72. struct stat statbuf;
  73. if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
  74. continue;
  75. scnprintf(namebuf, sizeof(namebuf), "%s/%s",
  76. path, d->d_name);
  77. ret = stat(namebuf, &statbuf);
  78. if (ret < 0) {
  79. pr_debug("stat failed: %s\n", namebuf);
  80. break;
  81. }
  82. if (S_ISREG(statbuf.st_mode))
  83. ret = unlink(namebuf);
  84. else if (S_ISDIR(statbuf.st_mode))
  85. ret = rm_rf(namebuf);
  86. else {
  87. pr_debug("unknown file: %s\n", namebuf);
  88. ret = -1;
  89. }
  90. }
  91. closedir(dir);
  92. if (ret < 0)
  93. return ret;
  94. return rmdir(path);
  95. }
  96. static int slow_copyfile(const char *from, const char *to)
  97. {
  98. int err = -1;
  99. char *line = NULL;
  100. size_t n;
  101. FILE *from_fp = fopen(from, "r"), *to_fp;
  102. if (from_fp == NULL)
  103. goto out;
  104. to_fp = fopen(to, "w");
  105. if (to_fp == NULL)
  106. goto out_fclose_from;
  107. while (getline(&line, &n, from_fp) > 0)
  108. if (fputs(line, to_fp) == EOF)
  109. goto out_fclose_to;
  110. err = 0;
  111. out_fclose_to:
  112. fclose(to_fp);
  113. free(line);
  114. out_fclose_from:
  115. fclose(from_fp);
  116. out:
  117. return err;
  118. }
  119. int copyfile_offset(int ifd, loff_t off_in, int ofd, loff_t off_out, u64 size)
  120. {
  121. void *ptr;
  122. loff_t pgoff;
  123. pgoff = off_in & ~(page_size - 1);
  124. off_in -= pgoff;
  125. ptr = mmap(NULL, off_in + size, PROT_READ, MAP_PRIVATE, ifd, pgoff);
  126. if (ptr == MAP_FAILED)
  127. return -1;
  128. while (size) {
  129. ssize_t ret = pwrite(ofd, ptr + off_in, size, off_out);
  130. if (ret < 0 && errno == EINTR)
  131. continue;
  132. if (ret <= 0)
  133. break;
  134. size -= ret;
  135. off_in += ret;
  136. off_out -= ret;
  137. }
  138. munmap(ptr, off_in + size);
  139. return size ? -1 : 0;
  140. }
  141. int copyfile_mode(const char *from, const char *to, mode_t mode)
  142. {
  143. int fromfd, tofd;
  144. struct stat st;
  145. int err = -1;
  146. char *tmp = NULL, *ptr = NULL;
  147. if (stat(from, &st))
  148. goto out;
  149. /* extra 'x' at the end is to reserve space for '.' */
  150. if (asprintf(&tmp, "%s.XXXXXXx", to) < 0) {
  151. tmp = NULL;
  152. goto out;
  153. }
  154. ptr = strrchr(tmp, '/');
  155. if (!ptr)
  156. goto out;
  157. ptr = memmove(ptr + 1, ptr, strlen(ptr) - 1);
  158. *ptr = '.';
  159. tofd = mkstemp(tmp);
  160. if (tofd < 0)
  161. goto out;
  162. if (fchmod(tofd, mode))
  163. goto out_close_to;
  164. if (st.st_size == 0) { /* /proc? do it slowly... */
  165. err = slow_copyfile(from, tmp);
  166. goto out_close_to;
  167. }
  168. fromfd = open(from, O_RDONLY);
  169. if (fromfd < 0)
  170. goto out_close_to;
  171. err = copyfile_offset(fromfd, 0, tofd, 0, st.st_size);
  172. close(fromfd);
  173. out_close_to:
  174. close(tofd);
  175. if (!err)
  176. err = link(tmp, to);
  177. unlink(tmp);
  178. out:
  179. free(tmp);
  180. return err;
  181. }
  182. int copyfile(const char *from, const char *to)
  183. {
  184. return copyfile_mode(from, to, 0755);
  185. }
  186. unsigned long convert_unit(unsigned long value, char *unit)
  187. {
  188. *unit = ' ';
  189. if (value > 1000) {
  190. value /= 1000;
  191. *unit = 'K';
  192. }
  193. if (value > 1000) {
  194. value /= 1000;
  195. *unit = 'M';
  196. }
  197. if (value > 1000) {
  198. value /= 1000;
  199. *unit = 'G';
  200. }
  201. return value;
  202. }
  203. static ssize_t ion(bool is_read, int fd, void *buf, size_t n)
  204. {
  205. void *buf_start = buf;
  206. size_t left = n;
  207. while (left) {
  208. ssize_t ret = is_read ? read(fd, buf, left) :
  209. write(fd, buf, left);
  210. if (ret < 0 && errno == EINTR)
  211. continue;
  212. if (ret <= 0)
  213. return ret;
  214. left -= ret;
  215. buf += ret;
  216. }
  217. BUG_ON((size_t)(buf - buf_start) != n);
  218. return n;
  219. }
  220. /*
  221. * Read exactly 'n' bytes or return an error.
  222. */
  223. ssize_t readn(int fd, void *buf, size_t n)
  224. {
  225. return ion(true, fd, buf, n);
  226. }
  227. /*
  228. * Write exactly 'n' bytes or return an error.
  229. */
  230. ssize_t writen(int fd, void *buf, size_t n)
  231. {
  232. return ion(false, fd, buf, n);
  233. }
  234. size_t hex_width(u64 v)
  235. {
  236. size_t n = 1;
  237. while ((v >>= 4))
  238. ++n;
  239. return n;
  240. }
  241. static int hex(char ch)
  242. {
  243. if ((ch >= '0') && (ch <= '9'))
  244. return ch - '0';
  245. if ((ch >= 'a') && (ch <= 'f'))
  246. return ch - 'a' + 10;
  247. if ((ch >= 'A') && (ch <= 'F'))
  248. return ch - 'A' + 10;
  249. return -1;
  250. }
  251. /*
  252. * While we find nice hex chars, build a long_val.
  253. * Return number of chars processed.
  254. */
  255. int hex2u64(const char *ptr, u64 *long_val)
  256. {
  257. const char *p = ptr;
  258. *long_val = 0;
  259. while (*p) {
  260. const int hex_val = hex(*p);
  261. if (hex_val < 0)
  262. break;
  263. *long_val = (*long_val << 4) | hex_val;
  264. p++;
  265. }
  266. return p - ptr;
  267. }
  268. /* Obtain a backtrace and print it to stdout. */
  269. #ifdef HAVE_BACKTRACE_SUPPORT
  270. void dump_stack(void)
  271. {
  272. void *array[16];
  273. size_t size = backtrace(array, ARRAY_SIZE(array));
  274. char **strings = backtrace_symbols(array, size);
  275. size_t i;
  276. printf("Obtained %zd stack frames.\n", size);
  277. for (i = 0; i < size; i++)
  278. printf("%s\n", strings[i]);
  279. free(strings);
  280. }
  281. #else
  282. void dump_stack(void) {}
  283. #endif
  284. void sighandler_dump_stack(int sig)
  285. {
  286. psignal(sig, "perf");
  287. dump_stack();
  288. exit(sig);
  289. }
  290. void get_term_dimensions(struct winsize *ws)
  291. {
  292. char *s = getenv("LINES");
  293. if (s != NULL) {
  294. ws->ws_row = atoi(s);
  295. s = getenv("COLUMNS");
  296. if (s != NULL) {
  297. ws->ws_col = atoi(s);
  298. if (ws->ws_row && ws->ws_col)
  299. return;
  300. }
  301. }
  302. #ifdef TIOCGWINSZ
  303. if (ioctl(1, TIOCGWINSZ, ws) == 0 &&
  304. ws->ws_row && ws->ws_col)
  305. return;
  306. #endif
  307. ws->ws_row = 25;
  308. ws->ws_col = 80;
  309. }
  310. void set_term_quiet_input(struct termios *old)
  311. {
  312. struct termios tc;
  313. tcgetattr(0, old);
  314. tc = *old;
  315. tc.c_lflag &= ~(ICANON | ECHO);
  316. tc.c_cc[VMIN] = 0;
  317. tc.c_cc[VTIME] = 0;
  318. tcsetattr(0, TCSANOW, &tc);
  319. }
  320. int parse_nsec_time(const char *str, u64 *ptime)
  321. {
  322. u64 time_sec, time_nsec;
  323. char *end;
  324. time_sec = strtoul(str, &end, 10);
  325. if (*end != '.' && *end != '\0')
  326. return -1;
  327. if (*end == '.') {
  328. int i;
  329. char nsec_buf[10];
  330. if (strlen(++end) > 9)
  331. return -1;
  332. strncpy(nsec_buf, end, 9);
  333. nsec_buf[9] = '\0';
  334. /* make it nsec precision */
  335. for (i = strlen(nsec_buf); i < 9; i++)
  336. nsec_buf[i] = '0';
  337. time_nsec = strtoul(nsec_buf, &end, 10);
  338. if (*end != '\0')
  339. return -1;
  340. } else
  341. time_nsec = 0;
  342. *ptime = time_sec * NSEC_PER_SEC + time_nsec;
  343. return 0;
  344. }
  345. unsigned long parse_tag_value(const char *str, struct parse_tag *tags)
  346. {
  347. struct parse_tag *i = tags;
  348. while (i->tag) {
  349. char *s;
  350. s = strchr(str, i->tag);
  351. if (s) {
  352. unsigned long int value;
  353. char *endptr;
  354. value = strtoul(str, &endptr, 10);
  355. if (s != endptr)
  356. break;
  357. if (value > ULONG_MAX / i->mult)
  358. break;
  359. value *= i->mult;
  360. return value;
  361. }
  362. i++;
  363. }
  364. return (unsigned long) -1;
  365. }
  366. int get_stack_size(const char *str, unsigned long *_size)
  367. {
  368. char *endptr;
  369. unsigned long size;
  370. unsigned long max_size = round_down(USHRT_MAX, sizeof(u64));
  371. size = strtoul(str, &endptr, 0);
  372. do {
  373. if (*endptr)
  374. break;
  375. size = round_up(size, sizeof(u64));
  376. if (!size || size > max_size)
  377. break;
  378. *_size = size;
  379. return 0;
  380. } while (0);
  381. pr_err("callchain: Incorrect stack dump size (max %ld): %s\n",
  382. max_size, str);
  383. return -1;
  384. }
  385. int parse_callchain_record(const char *arg, struct callchain_param *param)
  386. {
  387. char *tok, *name, *saveptr = NULL;
  388. char *buf;
  389. int ret = -1;
  390. /* We need buffer that we know we can write to. */
  391. buf = malloc(strlen(arg) + 1);
  392. if (!buf)
  393. return -ENOMEM;
  394. strcpy(buf, arg);
  395. tok = strtok_r((char *)buf, ",", &saveptr);
  396. name = tok ? : (char *)buf;
  397. do {
  398. /* Framepointer style */
  399. if (!strncmp(name, "fp", sizeof("fp"))) {
  400. if (!strtok_r(NULL, ",", &saveptr)) {
  401. param->record_mode = CALLCHAIN_FP;
  402. ret = 0;
  403. } else
  404. pr_err("callchain: No more arguments "
  405. "needed for --call-graph fp\n");
  406. break;
  407. #ifdef HAVE_DWARF_UNWIND_SUPPORT
  408. /* Dwarf style */
  409. } else if (!strncmp(name, "dwarf", sizeof("dwarf"))) {
  410. const unsigned long default_stack_dump_size = 8192;
  411. ret = 0;
  412. param->record_mode = CALLCHAIN_DWARF;
  413. param->dump_size = default_stack_dump_size;
  414. tok = strtok_r(NULL, ",", &saveptr);
  415. if (tok) {
  416. unsigned long size = 0;
  417. ret = get_stack_size(tok, &size);
  418. param->dump_size = size;
  419. }
  420. #endif /* HAVE_DWARF_UNWIND_SUPPORT */
  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. int filename__read_str(const char *filename, char **buf, size_t *sizep)
  439. {
  440. size_t size = 0, alloc_size = 0;
  441. void *bf = NULL, *nbf;
  442. int fd, n, err = 0;
  443. char sbuf[STRERR_BUFSIZE];
  444. fd = open(filename, O_RDONLY);
  445. if (fd < 0)
  446. return -errno;
  447. do {
  448. if (size == alloc_size) {
  449. alloc_size += BUFSIZ;
  450. nbf = realloc(bf, alloc_size);
  451. if (!nbf) {
  452. err = -ENOMEM;
  453. break;
  454. }
  455. bf = nbf;
  456. }
  457. n = read(fd, bf + size, alloc_size - size);
  458. if (n < 0) {
  459. if (size) {
  460. pr_warning("read failed %d: %s\n", errno,
  461. strerror_r(errno, sbuf, sizeof(sbuf)));
  462. err = 0;
  463. } else
  464. err = -errno;
  465. break;
  466. }
  467. size += n;
  468. } while (n > 0);
  469. if (!err) {
  470. *sizep = size;
  471. *buf = bf;
  472. } else
  473. free(bf);
  474. close(fd);
  475. return err;
  476. }
  477. const char *get_filename_for_perf_kvm(void)
  478. {
  479. const char *filename;
  480. if (perf_host && !perf_guest)
  481. filename = strdup("perf.data.host");
  482. else if (!perf_host && perf_guest)
  483. filename = strdup("perf.data.guest");
  484. else
  485. filename = strdup("perf.data.kvm");
  486. return filename;
  487. }
  488. int perf_event_paranoid(void)
  489. {
  490. int value;
  491. if (sysctl__read_int("kernel/perf_event_paranoid", &value))
  492. return INT_MAX;
  493. return value;
  494. }
  495. void mem_bswap_32(void *src, int byte_size)
  496. {
  497. u32 *m = src;
  498. while (byte_size > 0) {
  499. *m = bswap_32(*m);
  500. byte_size -= sizeof(u32);
  501. ++m;
  502. }
  503. }
  504. void mem_bswap_64(void *src, int byte_size)
  505. {
  506. u64 *m = src;
  507. while (byte_size > 0) {
  508. *m = bswap_64(*m);
  509. byte_size -= sizeof(u64);
  510. ++m;
  511. }
  512. }
  513. bool find_process(const char *name)
  514. {
  515. size_t len = strlen(name);
  516. DIR *dir;
  517. struct dirent *d;
  518. int ret = -1;
  519. dir = opendir(procfs__mountpoint());
  520. if (!dir)
  521. return false;
  522. /* Walk through the directory. */
  523. while (ret && (d = readdir(dir)) != NULL) {
  524. char path[PATH_MAX];
  525. char *data;
  526. size_t size;
  527. if ((d->d_type != DT_DIR) ||
  528. !strcmp(".", d->d_name) ||
  529. !strcmp("..", d->d_name))
  530. continue;
  531. scnprintf(path, sizeof(path), "%s/%s/comm",
  532. procfs__mountpoint(), d->d_name);
  533. if (filename__read_str(path, &data, &size))
  534. continue;
  535. ret = strncmp(name, data, len);
  536. free(data);
  537. }
  538. closedir(dir);
  539. return ret ? false : true;
  540. }