util.c 14 KB

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