6 #include <sys/utsname.h>
7 #ifdef HAVE_BACKTRACE_SUPPORT
19 #include <linux/kernel.h>
20 #include <linux/log2.h>
21 #include <linux/time64.h>
23 #include "callchain.h"
26 #define CALLCHAIN_PARAM_DEFAULT \
27 .mode = CHAIN_GRAPH_ABS, \
29 .order = ORDER_CALLEE, \
30 .key = CCKEY_FUNCTION, \
31 .value = CCVAL_PERCENT, \
33 struct callchain_param callchain_param = {
34 CALLCHAIN_PARAM_DEFAULT
37 struct callchain_param callchain_param_default = {
38 CALLCHAIN_PARAM_DEFAULT
42 * XXX We need to find a better place for these things...
44 unsigned int page_size;
47 int sysctl_perf_event_max_stack = PERF_MAX_STACK_DEPTH;
48 int sysctl_perf_event_max_contexts_per_stack = PERF_MAX_CONTEXTS_PER_STACK;
50 bool test_attr__enabled;
52 bool perf_host = true;
53 bool perf_guest = false;
55 void event_attr_init(struct perf_event_attr *attr)
58 attr->exclude_host = 1;
60 attr->exclude_guest = 1;
61 /* to capture ABI version */
62 attr->size = sizeof(*attr);
65 int mkdir_p(char *path, mode_t mode)
74 if (stat(path, &st) == 0)
79 while ((d = strchr(d, '/'))) {
81 err = stat(path, &st) && mkdir(path, mode);
88 return (stat(path, &st) && mkdir(path, mode)) ? -1 : 0;
91 int rm_rf(const char *path)
96 char namebuf[PATH_MAX];
102 while ((d = readdir(dir)) != NULL && !ret) {
105 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
108 scnprintf(namebuf, sizeof(namebuf), "%s/%s",
111 /* We have to check symbolic link itself */
112 ret = lstat(namebuf, &statbuf);
114 pr_debug("stat failed: %s\n", namebuf);
118 if (S_ISDIR(statbuf.st_mode))
119 ret = rm_rf(namebuf);
121 ret = unlink(namebuf);
131 /* A filter which removes dot files */
132 bool lsdir_no_dot_filter(const char *name __maybe_unused, struct dirent *d)
134 return d->d_name[0] != '.';
137 /* lsdir reads a directory and store it in strlist */
138 struct strlist *lsdir(const char *name,
139 bool (*filter)(const char *, struct dirent *))
141 struct strlist *list = NULL;
149 list = strlist__new(NULL, NULL);
155 while ((d = readdir(dir)) != NULL) {
156 if (!filter || filter(name, d))
157 strlist__add(list, d->d_name);
165 static int slow_copyfile(const char *from, const char *to)
170 FILE *from_fp = fopen(from, "r"), *to_fp;
175 to_fp = fopen(to, "w");
177 goto out_fclose_from;
179 while (getline(&line, &n, from_fp) > 0)
180 if (fputs(line, to_fp) == EOF)
192 int copyfile_offset(int ifd, loff_t off_in, int ofd, loff_t off_out, u64 size)
197 pgoff = off_in & ~(page_size - 1);
200 ptr = mmap(NULL, off_in + size, PROT_READ, MAP_PRIVATE, ifd, pgoff);
201 if (ptr == MAP_FAILED)
205 ssize_t ret = pwrite(ofd, ptr + off_in, size, off_out);
206 if (ret < 0 && errno == EINTR)
215 munmap(ptr, off_in + size);
217 return size ? -1 : 0;
220 int copyfile_mode(const char *from, const char *to, mode_t mode)
225 char *tmp = NULL, *ptr = NULL;
230 /* extra 'x' at the end is to reserve space for '.' */
231 if (asprintf(&tmp, "%s.XXXXXXx", to) < 0) {
235 ptr = strrchr(tmp, '/');
238 ptr = memmove(ptr + 1, ptr, strlen(ptr) - 1);
245 if (fchmod(tofd, mode))
248 if (st.st_size == 0) { /* /proc? do it slowly... */
249 err = slow_copyfile(from, tmp);
253 fromfd = open(from, O_RDONLY);
257 err = copyfile_offset(fromfd, 0, tofd, 0, st.st_size);
270 int copyfile(const char *from, const char *to)
272 return copyfile_mode(from, to, 0755);
275 static ssize_t ion(bool is_read, int fd, void *buf, size_t n)
277 void *buf_start = buf;
281 ssize_t ret = is_read ? read(fd, buf, left) :
282 write(fd, buf, left);
284 if (ret < 0 && errno == EINTR)
293 BUG_ON((size_t)(buf - buf_start) != n);
298 * Read exactly 'n' bytes or return an error.
300 ssize_t readn(int fd, void *buf, size_t n)
302 return ion(true, fd, buf, n);
306 * Write exactly 'n' bytes or return an error.
308 ssize_t writen(int fd, void *buf, size_t n)
310 return ion(false, fd, buf, n);
313 size_t hex_width(u64 v)
323 static int hex(char ch)
325 if ((ch >= '0') && (ch <= '9'))
327 if ((ch >= 'a') && (ch <= 'f'))
328 return ch - 'a' + 10;
329 if ((ch >= 'A') && (ch <= 'F'))
330 return ch - 'A' + 10;
335 * While we find nice hex chars, build a long_val.
336 * Return number of chars processed.
338 int hex2u64(const char *ptr, u64 *long_val)
344 const int hex_val = hex(*p);
349 *long_val = (*long_val << 4) | hex_val;
356 /* Obtain a backtrace and print it to stdout. */
357 #ifdef HAVE_BACKTRACE_SUPPORT
358 void dump_stack(void)
361 size_t size = backtrace(array, ARRAY_SIZE(array));
362 char **strings = backtrace_symbols(array, size);
365 printf("Obtained %zd stack frames.\n", size);
367 for (i = 0; i < size; i++)
368 printf("%s\n", strings[i]);
373 void dump_stack(void) {}
376 void sighandler_dump_stack(int sig)
378 psignal(sig, "perf");
380 signal(sig, SIG_DFL);
384 int timestamp__scnprintf_usec(u64 timestamp, char *buf, size_t sz)
386 u64 sec = timestamp / NSEC_PER_SEC;
387 u64 usec = (timestamp % NSEC_PER_SEC) / NSEC_PER_USEC;
389 return scnprintf(buf, sz, "%"PRIu64".%06"PRIu64, sec, usec);
392 unsigned long parse_tag_value(const char *str, struct parse_tag *tags)
394 struct parse_tag *i = tags;
399 s = strchr(str, i->tag);
401 unsigned long int value;
404 value = strtoul(str, &endptr, 10);
408 if (value > ULONG_MAX / i->mult)
416 return (unsigned long) -1;
419 int get_stack_size(const char *str, unsigned long *_size)
423 unsigned long max_size = round_down(USHRT_MAX, sizeof(u64));
425 size = strtoul(str, &endptr, 0);
431 size = round_up(size, sizeof(u64));
432 if (!size || size > max_size)
440 pr_err("callchain: Incorrect stack dump size (max %ld): %s\n",
445 int parse_callchain_record(const char *arg, struct callchain_param *param)
447 char *tok, *name, *saveptr = NULL;
451 /* We need buffer that we know we can write to. */
452 buf = malloc(strlen(arg) + 1);
458 tok = strtok_r((char *)buf, ",", &saveptr);
459 name = tok ? : (char *)buf;
462 /* Framepointer style */
463 if (!strncmp(name, "fp", sizeof("fp"))) {
464 if (!strtok_r(NULL, ",", &saveptr)) {
465 param->record_mode = CALLCHAIN_FP;
468 pr_err("callchain: No more arguments "
469 "needed for --call-graph fp\n");
473 } else if (!strncmp(name, "dwarf", sizeof("dwarf"))) {
474 const unsigned long default_stack_dump_size = 8192;
477 param->record_mode = CALLCHAIN_DWARF;
478 param->dump_size = default_stack_dump_size;
480 tok = strtok_r(NULL, ",", &saveptr);
482 unsigned long size = 0;
484 ret = get_stack_size(tok, &size);
485 param->dump_size = size;
487 } else if (!strncmp(name, "lbr", sizeof("lbr"))) {
488 if (!strtok_r(NULL, ",", &saveptr)) {
489 param->record_mode = CALLCHAIN_LBR;
492 pr_err("callchain: No more arguments "
493 "needed for --call-graph lbr\n");
496 pr_err("callchain: Unknown --call-graph option "
507 const char *get_filename_for_perf_kvm(void)
509 const char *filename;
511 if (perf_host && !perf_guest)
512 filename = strdup("perf.data.host");
513 else if (!perf_host && perf_guest)
514 filename = strdup("perf.data.guest");
516 filename = strdup("perf.data.kvm");
521 int perf_event_paranoid(void)
525 if (sysctl__read_int("kernel/perf_event_paranoid", &value))
531 void mem_bswap_32(void *src, int byte_size)
534 while (byte_size > 0) {
536 byte_size -= sizeof(u32);
541 void mem_bswap_64(void *src, int byte_size)
545 while (byte_size > 0) {
547 byte_size -= sizeof(u64);
552 bool find_process(const char *name)
554 size_t len = strlen(name);
559 dir = opendir(procfs__mountpoint());
563 /* Walk through the directory. */
564 while (ret && (d = readdir(dir)) != NULL) {
569 if ((d->d_type != DT_DIR) ||
570 !strcmp(".", d->d_name) ||
571 !strcmp("..", d->d_name))
574 scnprintf(path, sizeof(path), "%s/%s/comm",
575 procfs__mountpoint(), d->d_name);
577 if (filename__read_str(path, &data, &size))
580 ret = strncmp(name, data, len);
585 return ret ? false : true;
589 fetch_ubuntu_kernel_version(unsigned int *puint)
593 char *ptr, *line = NULL;
594 int version, patchlevel, sublevel, err;
595 FILE *vsig = fopen("/proc/version_signature", "r");
598 pr_debug("Open /proc/version_signature failed: %s\n",
603 len = getline(&line, &line_len, vsig);
607 pr_debug("Reading from /proc/version_signature failed: %s\n",
612 ptr = strrchr(line, ' ');
614 pr_debug("Parsing /proc/version_signature failed: %s\n", line);
618 err = sscanf(ptr + 1, "%d.%d.%d",
619 &version, &patchlevel, &sublevel);
621 pr_debug("Unable to get kernel version from /proc/version_signature '%s'\n",
627 *puint = (version << 16) + (patchlevel << 8) + sublevel;
635 fetch_kernel_version(unsigned int *puint, char *str,
638 struct utsname utsname;
639 int version, patchlevel, sublevel, err;
640 bool int_ver_ready = false;
642 if (access("/proc/version_signature", R_OK) == 0)
643 if (!fetch_ubuntu_kernel_version(puint))
644 int_ver_ready = true;
649 if (str && str_size) {
650 strncpy(str, utsname.release, str_size);
651 str[str_size - 1] = '\0';
654 err = sscanf(utsname.release, "%d.%d.%d",
655 &version, &patchlevel, &sublevel);
658 pr_debug("Unable to get kernel version from uname '%s'\n",
663 if (puint && !int_ver_ready)
664 *puint = (version << 16) + (patchlevel << 8) + sublevel;
668 const char *perf_tip(const char *dirpath)
670 struct strlist *tips;
671 struct str_node *node;
673 struct strlist_config conf = {
678 tips = strlist__new("tips.txt", &conf);
680 return errno == ENOENT ? NULL :
681 "Tip: check path of tips.txt or get more memory! ;-p";
683 if (strlist__nr_entries(tips) == 0)
686 node = strlist__entry(tips, random() % strlist__nr_entries(tips));
687 if (asprintf(&tip, "Tip: %s", node->s) < 0)
688 tip = (char *)"Tip: get more memory! ;-)";
691 strlist__delete(tips);
696 int fetch_current_timestamp(char *buf, size_t sz)
702 if (gettimeofday(&tv, NULL) || !localtime_r(&tv.tv_sec, &tm))
705 if (!strftime(dt, sizeof(dt), "%Y%m%d%H%M%S", &tm))
708 scnprintf(buf, sz, "%s%02u", dt, (unsigned)tv.tv_usec / 10000);