util.c 12 KB

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