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