util.c 12 KB

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