xref: /linux/tools/perf/util/util.c (revision a0d3c7c5c07cfbe00ab89438ddf82482f5a99422)
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 unsigned int sysctl_perf_event_max_stack = PERF_MAX_STACK_DEPTH;
37 
38 bool test_attr__enabled;
39 
40 bool perf_host  = true;
41 bool perf_guest = false;
42 
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 
53 int mkdir_p(char *path, mode_t mode)
54 {
55 	struct stat st;
56 	int err;
57 	char *d = path;
58 
59 	if (*d != '/')
60 		return -1;
61 
62 	if (stat(path, &st) == 0)
63 		return 0;
64 
65 	while (*++d == '/');
66 
67 	while ((d = strchr(d, '/'))) {
68 		*d = '\0';
69 		err = stat(path, &st) && mkdir(path, mode);
70 		*d++ = '/';
71 		if (err)
72 			return -1;
73 		while (*d == '/')
74 			++d;
75 	}
76 	return (stat(path, &st) && mkdir(path, mode)) ? -1 : 0;
77 }
78 
79 int rm_rf(char *path)
80 {
81 	DIR *dir;
82 	int ret = 0;
83 	struct dirent *d;
84 	char namebuf[PATH_MAX];
85 
86 	dir = opendir(path);
87 	if (dir == NULL)
88 		return 0;
89 
90 	while ((d = readdir(dir)) != NULL && !ret) {
91 		struct stat statbuf;
92 
93 		if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
94 			continue;
95 
96 		scnprintf(namebuf, sizeof(namebuf), "%s/%s",
97 			  path, d->d_name);
98 
99 		ret = stat(namebuf, &statbuf);
100 		if (ret < 0) {
101 			pr_debug("stat failed: %s\n", namebuf);
102 			break;
103 		}
104 
105 		if (S_ISREG(statbuf.st_mode))
106 			ret = unlink(namebuf);
107 		else if (S_ISDIR(statbuf.st_mode))
108 			ret = rm_rf(namebuf);
109 		else {
110 			pr_debug("unknown file: %s\n", namebuf);
111 			ret = -1;
112 		}
113 	}
114 	closedir(dir);
115 
116 	if (ret < 0)
117 		return ret;
118 
119 	return rmdir(path);
120 }
121 
122 /* A filter which removes dot files */
123 bool lsdir_no_dot_filter(const char *name __maybe_unused, struct dirent *d)
124 {
125 	return d->d_name[0] != '.';
126 }
127 
128 /* lsdir reads a directory and store it in strlist */
129 struct strlist *lsdir(const char *name,
130 		      bool (*filter)(const char *, struct dirent *))
131 {
132 	struct strlist *list = NULL;
133 	DIR *dir;
134 	struct dirent *d;
135 
136 	dir = opendir(name);
137 	if (!dir)
138 		return NULL;
139 
140 	list = strlist__new(NULL, NULL);
141 	if (!list) {
142 		errno = ENOMEM;
143 		goto out;
144 	}
145 
146 	while ((d = readdir(dir)) != NULL) {
147 		if (!filter || filter(name, d))
148 			strlist__add(list, d->d_name);
149 	}
150 
151 out:
152 	closedir(dir);
153 	return list;
154 }
155 
156 static int slow_copyfile(const char *from, const char *to)
157 {
158 	int err = -1;
159 	char *line = NULL;
160 	size_t n;
161 	FILE *from_fp = fopen(from, "r"), *to_fp;
162 
163 	if (from_fp == NULL)
164 		goto out;
165 
166 	to_fp = fopen(to, "w");
167 	if (to_fp == NULL)
168 		goto out_fclose_from;
169 
170 	while (getline(&line, &n, from_fp) > 0)
171 		if (fputs(line, to_fp) == EOF)
172 			goto out_fclose_to;
173 	err = 0;
174 out_fclose_to:
175 	fclose(to_fp);
176 	free(line);
177 out_fclose_from:
178 	fclose(from_fp);
179 out:
180 	return err;
181 }
182 
183 int copyfile_offset(int ifd, loff_t off_in, int ofd, loff_t off_out, u64 size)
184 {
185 	void *ptr;
186 	loff_t pgoff;
187 
188 	pgoff = off_in & ~(page_size - 1);
189 	off_in -= pgoff;
190 
191 	ptr = mmap(NULL, off_in + size, PROT_READ, MAP_PRIVATE, ifd, pgoff);
192 	if (ptr == MAP_FAILED)
193 		return -1;
194 
195 	while (size) {
196 		ssize_t ret = pwrite(ofd, ptr + off_in, size, off_out);
197 		if (ret < 0 && errno == EINTR)
198 			continue;
199 		if (ret <= 0)
200 			break;
201 
202 		size -= ret;
203 		off_in += ret;
204 		off_out -= ret;
205 	}
206 	munmap(ptr, off_in + size);
207 
208 	return size ? -1 : 0;
209 }
210 
211 int copyfile_mode(const char *from, const char *to, mode_t mode)
212 {
213 	int fromfd, tofd;
214 	struct stat st;
215 	int err = -1;
216 	char *tmp = NULL, *ptr = NULL;
217 
218 	if (stat(from, &st))
219 		goto out;
220 
221 	/* extra 'x' at the end is to reserve space for '.' */
222 	if (asprintf(&tmp, "%s.XXXXXXx", to) < 0) {
223 		tmp = NULL;
224 		goto out;
225 	}
226 	ptr = strrchr(tmp, '/');
227 	if (!ptr)
228 		goto out;
229 	ptr = memmove(ptr + 1, ptr, strlen(ptr) - 1);
230 	*ptr = '.';
231 
232 	tofd = mkstemp(tmp);
233 	if (tofd < 0)
234 		goto out;
235 
236 	if (fchmod(tofd, mode))
237 		goto out_close_to;
238 
239 	if (st.st_size == 0) { /* /proc? do it slowly... */
240 		err = slow_copyfile(from, tmp);
241 		goto out_close_to;
242 	}
243 
244 	fromfd = open(from, O_RDONLY);
245 	if (fromfd < 0)
246 		goto out_close_to;
247 
248 	err = copyfile_offset(fromfd, 0, tofd, 0, st.st_size);
249 
250 	close(fromfd);
251 out_close_to:
252 	close(tofd);
253 	if (!err)
254 		err = link(tmp, to);
255 	unlink(tmp);
256 out:
257 	free(tmp);
258 	return err;
259 }
260 
261 int copyfile(const char *from, const char *to)
262 {
263 	return copyfile_mode(from, to, 0755);
264 }
265 
266 unsigned long convert_unit(unsigned long value, char *unit)
267 {
268 	*unit = ' ';
269 
270 	if (value > 1000) {
271 		value /= 1000;
272 		*unit = 'K';
273 	}
274 
275 	if (value > 1000) {
276 		value /= 1000;
277 		*unit = 'M';
278 	}
279 
280 	if (value > 1000) {
281 		value /= 1000;
282 		*unit = 'G';
283 	}
284 
285 	return value;
286 }
287 
288 static ssize_t ion(bool is_read, int fd, void *buf, size_t n)
289 {
290 	void *buf_start = buf;
291 	size_t left = n;
292 
293 	while (left) {
294 		ssize_t ret = is_read ? read(fd, buf, left) :
295 					write(fd, buf, left);
296 
297 		if (ret < 0 && errno == EINTR)
298 			continue;
299 		if (ret <= 0)
300 			return ret;
301 
302 		left -= ret;
303 		buf  += ret;
304 	}
305 
306 	BUG_ON((size_t)(buf - buf_start) != n);
307 	return n;
308 }
309 
310 /*
311  * Read exactly 'n' bytes or return an error.
312  */
313 ssize_t readn(int fd, void *buf, size_t n)
314 {
315 	return ion(true, fd, buf, n);
316 }
317 
318 /*
319  * Write exactly 'n' bytes or return an error.
320  */
321 ssize_t writen(int fd, void *buf, size_t n)
322 {
323 	return ion(false, fd, buf, n);
324 }
325 
326 size_t hex_width(u64 v)
327 {
328 	size_t n = 1;
329 
330 	while ((v >>= 4))
331 		++n;
332 
333 	return n;
334 }
335 
336 static int hex(char ch)
337 {
338 	if ((ch >= '0') && (ch <= '9'))
339 		return ch - '0';
340 	if ((ch >= 'a') && (ch <= 'f'))
341 		return ch - 'a' + 10;
342 	if ((ch >= 'A') && (ch <= 'F'))
343 		return ch - 'A' + 10;
344 	return -1;
345 }
346 
347 /*
348  * While we find nice hex chars, build a long_val.
349  * Return number of chars processed.
350  */
351 int hex2u64(const char *ptr, u64 *long_val)
352 {
353 	const char *p = ptr;
354 	*long_val = 0;
355 
356 	while (*p) {
357 		const int hex_val = hex(*p);
358 
359 		if (hex_val < 0)
360 			break;
361 
362 		*long_val = (*long_val << 4) | hex_val;
363 		p++;
364 	}
365 
366 	return p - ptr;
367 }
368 
369 /* Obtain a backtrace and print it to stdout. */
370 #ifdef HAVE_BACKTRACE_SUPPORT
371 void dump_stack(void)
372 {
373 	void *array[16];
374 	size_t size = backtrace(array, ARRAY_SIZE(array));
375 	char **strings = backtrace_symbols(array, size);
376 	size_t i;
377 
378 	printf("Obtained %zd stack frames.\n", size);
379 
380 	for (i = 0; i < size; i++)
381 		printf("%s\n", strings[i]);
382 
383 	free(strings);
384 }
385 #else
386 void dump_stack(void) {}
387 #endif
388 
389 void sighandler_dump_stack(int sig)
390 {
391 	psignal(sig, "perf");
392 	dump_stack();
393 	signal(sig, SIG_DFL);
394 	raise(sig);
395 }
396 
397 int parse_nsec_time(const char *str, u64 *ptime)
398 {
399 	u64 time_sec, time_nsec;
400 	char *end;
401 
402 	time_sec = strtoul(str, &end, 10);
403 	if (*end != '.' && *end != '\0')
404 		return -1;
405 
406 	if (*end == '.') {
407 		int i;
408 		char nsec_buf[10];
409 
410 		if (strlen(++end) > 9)
411 			return -1;
412 
413 		strncpy(nsec_buf, end, 9);
414 		nsec_buf[9] = '\0';
415 
416 		/* make it nsec precision */
417 		for (i = strlen(nsec_buf); i < 9; i++)
418 			nsec_buf[i] = '0';
419 
420 		time_nsec = strtoul(nsec_buf, &end, 10);
421 		if (*end != '\0')
422 			return -1;
423 	} else
424 		time_nsec = 0;
425 
426 	*ptime = time_sec * NSEC_PER_SEC + time_nsec;
427 	return 0;
428 }
429 
430 unsigned long parse_tag_value(const char *str, struct parse_tag *tags)
431 {
432 	struct parse_tag *i = tags;
433 
434 	while (i->tag) {
435 		char *s;
436 
437 		s = strchr(str, i->tag);
438 		if (s) {
439 			unsigned long int value;
440 			char *endptr;
441 
442 			value = strtoul(str, &endptr, 10);
443 			if (s != endptr)
444 				break;
445 
446 			if (value > ULONG_MAX / i->mult)
447 				break;
448 			value *= i->mult;
449 			return value;
450 		}
451 		i++;
452 	}
453 
454 	return (unsigned long) -1;
455 }
456 
457 int get_stack_size(const char *str, unsigned long *_size)
458 {
459 	char *endptr;
460 	unsigned long size;
461 	unsigned long max_size = round_down(USHRT_MAX, sizeof(u64));
462 
463 	size = strtoul(str, &endptr, 0);
464 
465 	do {
466 		if (*endptr)
467 			break;
468 
469 		size = round_up(size, sizeof(u64));
470 		if (!size || size > max_size)
471 			break;
472 
473 		*_size = size;
474 		return 0;
475 
476 	} while (0);
477 
478 	pr_err("callchain: Incorrect stack dump size (max %ld): %s\n",
479 	       max_size, str);
480 	return -1;
481 }
482 
483 int parse_callchain_record(const char *arg, struct callchain_param *param)
484 {
485 	char *tok, *name, *saveptr = NULL;
486 	char *buf;
487 	int ret = -1;
488 
489 	/* We need buffer that we know we can write to. */
490 	buf = malloc(strlen(arg) + 1);
491 	if (!buf)
492 		return -ENOMEM;
493 
494 	strcpy(buf, arg);
495 
496 	tok = strtok_r((char *)buf, ",", &saveptr);
497 	name = tok ? : (char *)buf;
498 
499 	do {
500 		/* Framepointer style */
501 		if (!strncmp(name, "fp", sizeof("fp"))) {
502 			if (!strtok_r(NULL, ",", &saveptr)) {
503 				param->record_mode = CALLCHAIN_FP;
504 				ret = 0;
505 			} else
506 				pr_err("callchain: No more arguments "
507 				       "needed for --call-graph fp\n");
508 			break;
509 
510 		/* Dwarf style */
511 		} else if (!strncmp(name, "dwarf", sizeof("dwarf"))) {
512 			const unsigned long default_stack_dump_size = 8192;
513 
514 			ret = 0;
515 			param->record_mode = CALLCHAIN_DWARF;
516 			param->dump_size = default_stack_dump_size;
517 
518 			tok = strtok_r(NULL, ",", &saveptr);
519 			if (tok) {
520 				unsigned long size = 0;
521 
522 				ret = get_stack_size(tok, &size);
523 				param->dump_size = size;
524 			}
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 }
744