6 #include <sys/utsname.h>
7 #ifdef HAVE_BACKTRACE_SUPPORT
17 #include <linux/kernel.h>
18 #include <linux/log2.h>
19 #include <linux/time64.h>
21 #include "callchain.h"
24 #define CALLCHAIN_PARAM_DEFAULT \
25 .mode = CHAIN_GRAPH_ABS, \
27 .order = ORDER_CALLEE, \
28 .key = CCKEY_FUNCTION, \
29 .value = CCVAL_PERCENT, \
31 struct callchain_param callchain_param = {
32 CALLCHAIN_PARAM_DEFAULT
35 struct callchain_param callchain_param_default = {
36 CALLCHAIN_PARAM_DEFAULT
40 * XXX We need to find a better place for these things...
42 unsigned int page_size;
45 int sysctl_perf_event_max_stack = PERF_MAX_STACK_DEPTH;
46 int sysctl_perf_event_max_contexts_per_stack = PERF_MAX_CONTEXTS_PER_STACK;
48 bool test_attr__enabled;
50 bool perf_host = true;
51 bool perf_guest = false;
53 void event_attr_init(struct perf_event_attr *attr)
56 attr->exclude_host = 1;
58 attr->exclude_guest = 1;
59 /* to capture ABI version */
60 attr->size = sizeof(*attr);
63 int mkdir_p(char *path, mode_t mode)
72 if (stat(path, &st) == 0)
77 while ((d = strchr(d, '/'))) {
79 err = stat(path, &st) && mkdir(path, mode);
86 return (stat(path, &st) && mkdir(path, mode)) ? -1 : 0;
89 int rm_rf(const char *path)
94 char namebuf[PATH_MAX];
100 while ((d = readdir(dir)) != NULL && !ret) {
103 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
106 scnprintf(namebuf, sizeof(namebuf), "%s/%s",
109 /* We have to check symbolic link itself */
110 ret = lstat(namebuf, &statbuf);
112 pr_debug("stat failed: %s\n", namebuf);
116 if (S_ISDIR(statbuf.st_mode))
117 ret = rm_rf(namebuf);
119 ret = unlink(namebuf);
129 /* A filter which removes dot files */
130 bool lsdir_no_dot_filter(const char *name __maybe_unused, struct dirent *d)
132 return d->d_name[0] != '.';
135 /* lsdir reads a directory and store it in strlist */
136 struct strlist *lsdir(const char *name,
137 bool (*filter)(const char *, struct dirent *))
139 struct strlist *list = NULL;
147 list = strlist__new(NULL, NULL);
153 while ((d = readdir(dir)) != NULL) {
154 if (!filter || filter(name, d))
155 strlist__add(list, d->d_name);
163 static int slow_copyfile(const char *from, const char *to)
168 FILE *from_fp = fopen(from, "r"), *to_fp;
173 to_fp = fopen(to, "w");
175 goto out_fclose_from;
177 while (getline(&line, &n, from_fp) > 0)
178 if (fputs(line, to_fp) == EOF)
190 int copyfile_offset(int ifd, loff_t off_in, int ofd, loff_t off_out, u64 size)
195 pgoff = off_in & ~(page_size - 1);
198 ptr = mmap(NULL, off_in + size, PROT_READ, MAP_PRIVATE, ifd, pgoff);
199 if (ptr == MAP_FAILED)
203 ssize_t ret = pwrite(ofd, ptr + off_in, size, off_out);
204 if (ret < 0 && errno == EINTR)
213 munmap(ptr, off_in + size);
215 return size ? -1 : 0;
218 int copyfile_mode(const char *from, const char *to, mode_t mode)
223 char *tmp = NULL, *ptr = NULL;
228 /* extra 'x' at the end is to reserve space for '.' */
229 if (asprintf(&tmp, "%s.XXXXXXx", to) < 0) {
233 ptr = strrchr(tmp, '/');
236 ptr = memmove(ptr + 1, ptr, strlen(ptr) - 1);
243 if (fchmod(tofd, mode))
246 if (st.st_size == 0) { /* /proc? do it slowly... */
247 err = slow_copyfile(from, tmp);
251 fromfd = open(from, O_RDONLY);
255 err = copyfile_offset(fromfd, 0, tofd, 0, st.st_size);
268 int copyfile(const char *from, const char *to)
270 return copyfile_mode(from, to, 0755);
273 unsigned long convert_unit(unsigned long value, char *unit)
295 static ssize_t ion(bool is_read, int fd, void *buf, size_t n)
297 void *buf_start = buf;
301 ssize_t ret = is_read ? read(fd, buf, left) :
302 write(fd, buf, left);
304 if (ret < 0 && errno == EINTR)
313 BUG_ON((size_t)(buf - buf_start) != n);
318 * Read exactly 'n' bytes or return an error.
320 ssize_t readn(int fd, void *buf, size_t n)
322 return ion(true, fd, buf, n);
326 * Write exactly 'n' bytes or return an error.
328 ssize_t writen(int fd, void *buf, size_t n)
330 return ion(false, fd, buf, n);
333 size_t hex_width(u64 v)
343 static int hex(char ch)
345 if ((ch >= '0') && (ch <= '9'))
347 if ((ch >= 'a') && (ch <= 'f'))
348 return ch - 'a' + 10;
349 if ((ch >= 'A') && (ch <= 'F'))
350 return ch - 'A' + 10;
355 * While we find nice hex chars, build a long_val.
356 * Return number of chars processed.
358 int hex2u64(const char *ptr, u64 *long_val)
364 const int hex_val = hex(*p);
369 *long_val = (*long_val << 4) | hex_val;
376 /* Obtain a backtrace and print it to stdout. */
377 #ifdef HAVE_BACKTRACE_SUPPORT
378 void dump_stack(void)
381 size_t size = backtrace(array, ARRAY_SIZE(array));
382 char **strings = backtrace_symbols(array, size);
385 printf("Obtained %zd stack frames.\n", size);
387 for (i = 0; i < size; i++)
388 printf("%s\n", strings[i]);
393 void dump_stack(void) {}
396 void sighandler_dump_stack(int sig)
398 psignal(sig, "perf");
400 signal(sig, SIG_DFL);
404 int timestamp__scnprintf_usec(u64 timestamp, char *buf, size_t sz)
406 u64 sec = timestamp / NSEC_PER_SEC;
407 u64 usec = (timestamp % NSEC_PER_SEC) / NSEC_PER_USEC;
409 return scnprintf(buf, sz, "%"PRIu64".%06"PRIu64, sec, usec);
412 unsigned long parse_tag_value(const char *str, struct parse_tag *tags)
414 struct parse_tag *i = tags;
419 s = strchr(str, i->tag);
421 unsigned long int value;
424 value = strtoul(str, &endptr, 10);
428 if (value > ULONG_MAX / i->mult)
436 return (unsigned long) -1;
439 int get_stack_size(const char *str, unsigned long *_size)
443 unsigned long max_size = round_down(USHRT_MAX, sizeof(u64));
445 size = strtoul(str, &endptr, 0);
451 size = round_up(size, sizeof(u64));
452 if (!size || size > max_size)
460 pr_err("callchain: Incorrect stack dump size (max %ld): %s\n",
465 int parse_callchain_record(const char *arg, struct callchain_param *param)
467 char *tok, *name, *saveptr = NULL;
471 /* We need buffer that we know we can write to. */
472 buf = malloc(strlen(arg) + 1);
478 tok = strtok_r((char *)buf, ",", &saveptr);
479 name = tok ? : (char *)buf;
482 /* Framepointer style */
483 if (!strncmp(name, "fp", sizeof("fp"))) {
484 if (!strtok_r(NULL, ",", &saveptr)) {
485 param->record_mode = CALLCHAIN_FP;
488 pr_err("callchain: No more arguments "
489 "needed for --call-graph fp\n");
493 } else if (!strncmp(name, "dwarf", sizeof("dwarf"))) {
494 const unsigned long default_stack_dump_size = 8192;
497 param->record_mode = CALLCHAIN_DWARF;
498 param->dump_size = default_stack_dump_size;
500 tok = strtok_r(NULL, ",", &saveptr);
502 unsigned long size = 0;
504 ret = get_stack_size(tok, &size);
505 param->dump_size = size;
507 } else if (!strncmp(name, "lbr", sizeof("lbr"))) {
508 if (!strtok_r(NULL, ",", &saveptr)) {
509 param->record_mode = CALLCHAIN_LBR;
512 pr_err("callchain: No more arguments "
513 "needed for --call-graph lbr\n");
516 pr_err("callchain: Unknown --call-graph option "
527 const char *get_filename_for_perf_kvm(void)
529 const char *filename;
531 if (perf_host && !perf_guest)
532 filename = strdup("perf.data.host");
533 else if (!perf_host && perf_guest)
534 filename = strdup("perf.data.guest");
536 filename = strdup("perf.data.kvm");
541 int perf_event_paranoid(void)
545 if (sysctl__read_int("kernel/perf_event_paranoid", &value))
551 void mem_bswap_32(void *src, int byte_size)
554 while (byte_size > 0) {
556 byte_size -= sizeof(u32);
561 void mem_bswap_64(void *src, int byte_size)
565 while (byte_size > 0) {
567 byte_size -= sizeof(u64);
572 bool find_process(const char *name)
574 size_t len = strlen(name);
579 dir = opendir(procfs__mountpoint());
583 /* Walk through the directory. */
584 while (ret && (d = readdir(dir)) != NULL) {
589 if ((d->d_type != DT_DIR) ||
590 !strcmp(".", d->d_name) ||
591 !strcmp("..", d->d_name))
594 scnprintf(path, sizeof(path), "%s/%s/comm",
595 procfs__mountpoint(), d->d_name);
597 if (filename__read_str(path, &data, &size))
600 ret = strncmp(name, data, len);
605 return ret ? false : true;
609 fetch_ubuntu_kernel_version(unsigned int *puint)
613 char *ptr, *line = NULL;
614 int version, patchlevel, sublevel, err;
615 FILE *vsig = fopen("/proc/version_signature", "r");
618 pr_debug("Open /proc/version_signature failed: %s\n",
623 len = getline(&line, &line_len, vsig);
627 pr_debug("Reading from /proc/version_signature failed: %s\n",
632 ptr = strrchr(line, ' ');
634 pr_debug("Parsing /proc/version_signature failed: %s\n", line);
638 err = sscanf(ptr + 1, "%d.%d.%d",
639 &version, &patchlevel, &sublevel);
641 pr_debug("Unable to get kernel version from /proc/version_signature '%s'\n",
647 *puint = (version << 16) + (patchlevel << 8) + sublevel;
655 fetch_kernel_version(unsigned int *puint, char *str,
658 struct utsname utsname;
659 int version, patchlevel, sublevel, err;
660 bool int_ver_ready = false;
662 if (access("/proc/version_signature", R_OK) == 0)
663 if (!fetch_ubuntu_kernel_version(puint))
664 int_ver_ready = true;
669 if (str && str_size) {
670 strncpy(str, utsname.release, str_size);
671 str[str_size - 1] = '\0';
674 err = sscanf(utsname.release, "%d.%d.%d",
675 &version, &patchlevel, &sublevel);
678 pr_debug("Unable to get kernel version from uname '%s'\n",
683 if (puint && !int_ver_ready)
684 *puint = (version << 16) + (patchlevel << 8) + sublevel;
688 const char *perf_tip(const char *dirpath)
690 struct strlist *tips;
691 struct str_node *node;
693 struct strlist_config conf = {
698 tips = strlist__new("tips.txt", &conf);
700 return errno == ENOENT ? NULL :
701 "Tip: check path of tips.txt or get more memory! ;-p";
703 if (strlist__nr_entries(tips) == 0)
706 node = strlist__entry(tips, random() % strlist__nr_entries(tips));
707 if (asprintf(&tip, "Tip: %s", node->s) < 0)
708 tip = (char *)"Tip: get more memory! ;-)";
711 strlist__delete(tips);
716 int fetch_current_timestamp(char *buf, size_t sz)
722 if (gettimeofday(&tv, NULL) || !localtime_r(&tv.tv_sec, &tm))
725 if (!strftime(dt, sizeof(dt), "%Y%m%d%H%M%S", &tm))
728 scnprintf(buf, sz, "%s%02u", dt, (unsigned)tv.tv_usec / 10000);
733 int unit_number__scnprintf(char *buf, size_t size, u64 n)
735 char unit[4] = "BKMG";
738 while (((n / 1024) > 1) && (i < 3)) {
743 return scnprintf(buf, size, "%" PRIu64 "%c", n, unit[i]);