6 #include <sys/utsname.h>
7 #ifdef HAVE_BACKTRACE_SUPPORT
18 #include <linux/kernel.h>
19 #include <linux/log2.h>
20 #include <linux/time64.h>
22 #include "callchain.h"
25 #define CALLCHAIN_PARAM_DEFAULT \
26 .mode = CHAIN_GRAPH_ABS, \
28 .order = ORDER_CALLEE, \
29 .key = CCKEY_FUNCTION, \
30 .value = CCVAL_PERCENT, \
32 struct callchain_param callchain_param = {
33 CALLCHAIN_PARAM_DEFAULT
36 struct callchain_param callchain_param_default = {
37 CALLCHAIN_PARAM_DEFAULT
41 * XXX We need to find a better place for these things...
43 unsigned int page_size;
46 int sysctl_perf_event_max_stack = PERF_MAX_STACK_DEPTH;
47 int sysctl_perf_event_max_contexts_per_stack = PERF_MAX_CONTEXTS_PER_STACK;
49 bool test_attr__enabled;
51 bool perf_host = true;
52 bool perf_guest = false;
54 void event_attr_init(struct perf_event_attr *attr)
57 attr->exclude_host = 1;
59 attr->exclude_guest = 1;
60 /* to capture ABI version */
61 attr->size = sizeof(*attr);
64 int mkdir_p(char *path, mode_t mode)
73 if (stat(path, &st) == 0)
78 while ((d = strchr(d, '/'))) {
80 err = stat(path, &st) && mkdir(path, mode);
87 return (stat(path, &st) && mkdir(path, mode)) ? -1 : 0;
90 int rm_rf(const char *path)
95 char namebuf[PATH_MAX];
101 while ((d = readdir(dir)) != NULL && !ret) {
104 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
107 scnprintf(namebuf, sizeof(namebuf), "%s/%s",
110 /* We have to check symbolic link itself */
111 ret = lstat(namebuf, &statbuf);
113 pr_debug("stat failed: %s\n", namebuf);
117 if (S_ISDIR(statbuf.st_mode))
118 ret = rm_rf(namebuf);
120 ret = unlink(namebuf);
130 /* A filter which removes dot files */
131 bool lsdir_no_dot_filter(const char *name __maybe_unused, struct dirent *d)
133 return d->d_name[0] != '.';
136 /* lsdir reads a directory and store it in strlist */
137 struct strlist *lsdir(const char *name,
138 bool (*filter)(const char *, struct dirent *))
140 struct strlist *list = NULL;
148 list = strlist__new(NULL, NULL);
154 while ((d = readdir(dir)) != NULL) {
155 if (!filter || filter(name, d))
156 strlist__add(list, d->d_name);
164 static int slow_copyfile(const char *from, const char *to)
169 FILE *from_fp = fopen(from, "r"), *to_fp;
174 to_fp = fopen(to, "w");
176 goto out_fclose_from;
178 while (getline(&line, &n, from_fp) > 0)
179 if (fputs(line, to_fp) == EOF)
191 int copyfile_offset(int ifd, loff_t off_in, int ofd, loff_t off_out, u64 size)
196 pgoff = off_in & ~(page_size - 1);
199 ptr = mmap(NULL, off_in + size, PROT_READ, MAP_PRIVATE, ifd, pgoff);
200 if (ptr == MAP_FAILED)
204 ssize_t ret = pwrite(ofd, ptr + off_in, size, off_out);
205 if (ret < 0 && errno == EINTR)
214 munmap(ptr, off_in + size);
216 return size ? -1 : 0;
219 int copyfile_mode(const char *from, const char *to, mode_t mode)
224 char *tmp = NULL, *ptr = NULL;
229 /* extra 'x' at the end is to reserve space for '.' */
230 if (asprintf(&tmp, "%s.XXXXXXx", to) < 0) {
234 ptr = strrchr(tmp, '/');
237 ptr = memmove(ptr + 1, ptr, strlen(ptr) - 1);
244 if (fchmod(tofd, mode))
247 if (st.st_size == 0) { /* /proc? do it slowly... */
248 err = slow_copyfile(from, tmp);
252 fromfd = open(from, O_RDONLY);
256 err = copyfile_offset(fromfd, 0, tofd, 0, st.st_size);
269 int copyfile(const char *from, const char *to)
271 return copyfile_mode(from, to, 0755);
274 unsigned long convert_unit(unsigned long value, char *unit)
296 static ssize_t ion(bool is_read, int fd, void *buf, size_t n)
298 void *buf_start = buf;
302 ssize_t ret = is_read ? read(fd, buf, left) :
303 write(fd, buf, left);
305 if (ret < 0 && errno == EINTR)
314 BUG_ON((size_t)(buf - buf_start) != n);
319 * Read exactly 'n' bytes or return an error.
321 ssize_t readn(int fd, void *buf, size_t n)
323 return ion(true, fd, buf, n);
327 * Write exactly 'n' bytes or return an error.
329 ssize_t writen(int fd, void *buf, size_t n)
331 return ion(false, fd, buf, n);
334 size_t hex_width(u64 v)
344 static int hex(char ch)
346 if ((ch >= '0') && (ch <= '9'))
348 if ((ch >= 'a') && (ch <= 'f'))
349 return ch - 'a' + 10;
350 if ((ch >= 'A') && (ch <= 'F'))
351 return ch - 'A' + 10;
356 * While we find nice hex chars, build a long_val.
357 * Return number of chars processed.
359 int hex2u64(const char *ptr, u64 *long_val)
365 const int hex_val = hex(*p);
370 *long_val = (*long_val << 4) | hex_val;
377 /* Obtain a backtrace and print it to stdout. */
378 #ifdef HAVE_BACKTRACE_SUPPORT
379 void dump_stack(void)
382 size_t size = backtrace(array, ARRAY_SIZE(array));
383 char **strings = backtrace_symbols(array, size);
386 printf("Obtained %zd stack frames.\n", size);
388 for (i = 0; i < size; i++)
389 printf("%s\n", strings[i]);
394 void dump_stack(void) {}
397 void sighandler_dump_stack(int sig)
399 psignal(sig, "perf");
401 signal(sig, SIG_DFL);
405 int timestamp__scnprintf_usec(u64 timestamp, char *buf, size_t sz)
407 u64 sec = timestamp / NSEC_PER_SEC;
408 u64 usec = (timestamp % NSEC_PER_SEC) / NSEC_PER_USEC;
410 return scnprintf(buf, sz, "%"PRIu64".%06"PRIu64, sec, usec);
413 unsigned long parse_tag_value(const char *str, struct parse_tag *tags)
415 struct parse_tag *i = tags;
420 s = strchr(str, i->tag);
422 unsigned long int value;
425 value = strtoul(str, &endptr, 10);
429 if (value > ULONG_MAX / i->mult)
437 return (unsigned long) -1;
440 int get_stack_size(const char *str, unsigned long *_size)
444 unsigned long max_size = round_down(USHRT_MAX, sizeof(u64));
446 size = strtoul(str, &endptr, 0);
452 size = round_up(size, sizeof(u64));
453 if (!size || size > max_size)
461 pr_err("callchain: Incorrect stack dump size (max %ld): %s\n",
466 int parse_callchain_record(const char *arg, struct callchain_param *param)
468 char *tok, *name, *saveptr = NULL;
472 /* We need buffer that we know we can write to. */
473 buf = malloc(strlen(arg) + 1);
479 tok = strtok_r((char *)buf, ",", &saveptr);
480 name = tok ? : (char *)buf;
483 /* Framepointer style */
484 if (!strncmp(name, "fp", sizeof("fp"))) {
485 if (!strtok_r(NULL, ",", &saveptr)) {
486 param->record_mode = CALLCHAIN_FP;
489 pr_err("callchain: No more arguments "
490 "needed for --call-graph fp\n");
494 } else if (!strncmp(name, "dwarf", sizeof("dwarf"))) {
495 const unsigned long default_stack_dump_size = 8192;
498 param->record_mode = CALLCHAIN_DWARF;
499 param->dump_size = default_stack_dump_size;
501 tok = strtok_r(NULL, ",", &saveptr);
503 unsigned long size = 0;
505 ret = get_stack_size(tok, &size);
506 param->dump_size = size;
508 } else if (!strncmp(name, "lbr", sizeof("lbr"))) {
509 if (!strtok_r(NULL, ",", &saveptr)) {
510 param->record_mode = CALLCHAIN_LBR;
513 pr_err("callchain: No more arguments "
514 "needed for --call-graph lbr\n");
517 pr_err("callchain: Unknown --call-graph option "
528 const char *get_filename_for_perf_kvm(void)
530 const char *filename;
532 if (perf_host && !perf_guest)
533 filename = strdup("perf.data.host");
534 else if (!perf_host && perf_guest)
535 filename = strdup("perf.data.guest");
537 filename = strdup("perf.data.kvm");
542 int perf_event_paranoid(void)
546 if (sysctl__read_int("kernel/perf_event_paranoid", &value))
552 void mem_bswap_32(void *src, int byte_size)
555 while (byte_size > 0) {
557 byte_size -= sizeof(u32);
562 void mem_bswap_64(void *src, int byte_size)
566 while (byte_size > 0) {
568 byte_size -= sizeof(u64);
573 bool find_process(const char *name)
575 size_t len = strlen(name);
580 dir = opendir(procfs__mountpoint());
584 /* Walk through the directory. */
585 while (ret && (d = readdir(dir)) != NULL) {
590 if ((d->d_type != DT_DIR) ||
591 !strcmp(".", d->d_name) ||
592 !strcmp("..", d->d_name))
595 scnprintf(path, sizeof(path), "%s/%s/comm",
596 procfs__mountpoint(), d->d_name);
598 if (filename__read_str(path, &data, &size))
601 ret = strncmp(name, data, len);
606 return ret ? false : true;
610 fetch_ubuntu_kernel_version(unsigned int *puint)
614 char *ptr, *line = NULL;
615 int version, patchlevel, sublevel, err;
616 FILE *vsig = fopen("/proc/version_signature", "r");
619 pr_debug("Open /proc/version_signature failed: %s\n",
624 len = getline(&line, &line_len, vsig);
628 pr_debug("Reading from /proc/version_signature failed: %s\n",
633 ptr = strrchr(line, ' ');
635 pr_debug("Parsing /proc/version_signature failed: %s\n", line);
639 err = sscanf(ptr + 1, "%d.%d.%d",
640 &version, &patchlevel, &sublevel);
642 pr_debug("Unable to get kernel version from /proc/version_signature '%s'\n",
648 *puint = (version << 16) + (patchlevel << 8) + sublevel;
656 fetch_kernel_version(unsigned int *puint, char *str,
659 struct utsname utsname;
660 int version, patchlevel, sublevel, err;
661 bool int_ver_ready = false;
663 if (access("/proc/version_signature", R_OK) == 0)
664 if (!fetch_ubuntu_kernel_version(puint))
665 int_ver_ready = true;
670 if (str && str_size) {
671 strncpy(str, utsname.release, str_size);
672 str[str_size - 1] = '\0';
675 err = sscanf(utsname.release, "%d.%d.%d",
676 &version, &patchlevel, &sublevel);
679 pr_debug("Unable to get kernel version from uname '%s'\n",
684 if (puint && !int_ver_ready)
685 *puint = (version << 16) + (patchlevel << 8) + sublevel;
689 const char *perf_tip(const char *dirpath)
691 struct strlist *tips;
692 struct str_node *node;
694 struct strlist_config conf = {
699 tips = strlist__new("tips.txt", &conf);
701 return errno == ENOENT ? NULL :
702 "Tip: check path of tips.txt or get more memory! ;-p";
704 if (strlist__nr_entries(tips) == 0)
707 node = strlist__entry(tips, random() % strlist__nr_entries(tips));
708 if (asprintf(&tip, "Tip: %s", node->s) < 0)
709 tip = (char *)"Tip: get more memory! ;-)";
712 strlist__delete(tips);
717 int fetch_current_timestamp(char *buf, size_t sz)
723 if (gettimeofday(&tv, NULL) || !localtime_r(&tv.tv_sec, &tm))
726 if (!strftime(dt, sizeof(dt), "%Y%m%d%H%M%S", &tm))
729 scnprintf(buf, sz, "%s%02u", dt, (unsigned)tv.tv_usec / 10000);
734 int unit_number__scnprintf(char *buf, size_t size, u64 n)
736 char unit[4] = "BKMG";
739 while (((n / 1024) > 1) && (i < 3)) {
744 return scnprintf(buf, size, "%" PRIu64 "%c", n, unit[i]);