xref: /linux/tools/perf/util/util.c (revision 5dafea097ac65bd01cc86801c399ae41dce79756)
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 int sysctl_perf_event_max_stack = PERF_MAX_STACK_DEPTH;
37 int sysctl_perf_event_max_contexts_per_stack = PERF_MAX_CONTEXTS_PER_STACK;
38 
39 bool test_attr__enabled;
40 
41 bool perf_host  = true;
42 bool perf_guest = false;
43 
44 void event_attr_init(struct perf_event_attr *attr)
45 {
46 	if (!perf_host)
47 		attr->exclude_host  = 1;
48 	if (!perf_guest)
49 		attr->exclude_guest = 1;
50 	/* to capture ABI version */
51 	attr->size = sizeof(*attr);
52 }
53 
54 int mkdir_p(char *path, mode_t mode)
55 {
56 	struct stat st;
57 	int err;
58 	char *d = path;
59 
60 	if (*d != '/')
61 		return -1;
62 
63 	if (stat(path, &st) == 0)
64 		return 0;
65 
66 	while (*++d == '/');
67 
68 	while ((d = strchr(d, '/'))) {
69 		*d = '\0';
70 		err = stat(path, &st) && mkdir(path, mode);
71 		*d++ = '/';
72 		if (err)
73 			return -1;
74 		while (*d == '/')
75 			++d;
76 	}
77 	return (stat(path, &st) && mkdir(path, mode)) ? -1 : 0;
78 }
79 
80 int rm_rf(char *path)
81 {
82 	DIR *dir;
83 	int ret = 0;
84 	struct dirent *d;
85 	char namebuf[PATH_MAX];
86 
87 	dir = opendir(path);
88 	if (dir == NULL)
89 		return 0;
90 
91 	while ((d = readdir(dir)) != NULL && !ret) {
92 		struct stat statbuf;
93 
94 		if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
95 			continue;
96 
97 		scnprintf(namebuf, sizeof(namebuf), "%s/%s",
98 			  path, d->d_name);
99 
100 		/* We have to check symbolic link itself */
101 		ret = lstat(namebuf, &statbuf);
102 		if (ret < 0) {
103 			pr_debug("stat failed: %s\n", namebuf);
104 			break;
105 		}
106 
107 		if (S_ISDIR(statbuf.st_mode))
108 			ret = rm_rf(namebuf);
109 		else
110 			ret = unlink(namebuf);
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 		/* Dwarf style */
509 		} else if (!strncmp(name, "dwarf", sizeof("dwarf"))) {
510 			const unsigned long default_stack_dump_size = 8192;
511 
512 			ret = 0;
513 			param->record_mode = CALLCHAIN_DWARF;
514 			param->dump_size = default_stack_dump_size;
515 
516 			tok = strtok_r(NULL, ",", &saveptr);
517 			if (tok) {
518 				unsigned long size = 0;
519 
520 				ret = get_stack_size(tok, &size);
521 				param->dump_size = size;
522 			}
523 		} else if (!strncmp(name, "lbr", sizeof("lbr"))) {
524 			if (!strtok_r(NULL, ",", &saveptr)) {
525 				param->record_mode = CALLCHAIN_LBR;
526 				ret = 0;
527 			} else
528 				pr_err("callchain: No more arguments "
529 					"needed for --call-graph lbr\n");
530 			break;
531 		} else {
532 			pr_err("callchain: Unknown --call-graph option "
533 			       "value: %s\n", arg);
534 			break;
535 		}
536 
537 	} while (0);
538 
539 	free(buf);
540 	return ret;
541 }
542 
543 const char *get_filename_for_perf_kvm(void)
544 {
545 	const char *filename;
546 
547 	if (perf_host && !perf_guest)
548 		filename = strdup("perf.data.host");
549 	else if (!perf_host && perf_guest)
550 		filename = strdup("perf.data.guest");
551 	else
552 		filename = strdup("perf.data.kvm");
553 
554 	return filename;
555 }
556 
557 int perf_event_paranoid(void)
558 {
559 	int value;
560 
561 	if (sysctl__read_int("kernel/perf_event_paranoid", &value))
562 		return INT_MAX;
563 
564 	return value;
565 }
566 
567 void mem_bswap_32(void *src, int byte_size)
568 {
569 	u32 *m = src;
570 	while (byte_size > 0) {
571 		*m = bswap_32(*m);
572 		byte_size -= sizeof(u32);
573 		++m;
574 	}
575 }
576 
577 void mem_bswap_64(void *src, int byte_size)
578 {
579 	u64 *m = src;
580 
581 	while (byte_size > 0) {
582 		*m = bswap_64(*m);
583 		byte_size -= sizeof(u64);
584 		++m;
585 	}
586 }
587 
588 bool find_process(const char *name)
589 {
590 	size_t len = strlen(name);
591 	DIR *dir;
592 	struct dirent *d;
593 	int ret = -1;
594 
595 	dir = opendir(procfs__mountpoint());
596 	if (!dir)
597 		return false;
598 
599 	/* Walk through the directory. */
600 	while (ret && (d = readdir(dir)) != NULL) {
601 		char path[PATH_MAX];
602 		char *data;
603 		size_t size;
604 
605 		if ((d->d_type != DT_DIR) ||
606 		     !strcmp(".", d->d_name) ||
607 		     !strcmp("..", d->d_name))
608 			continue;
609 
610 		scnprintf(path, sizeof(path), "%s/%s/comm",
611 			  procfs__mountpoint(), d->d_name);
612 
613 		if (filename__read_str(path, &data, &size))
614 			continue;
615 
616 		ret = strncmp(name, data, len);
617 		free(data);
618 	}
619 
620 	closedir(dir);
621 	return ret ? false : true;
622 }
623 
624 int
625 fetch_kernel_version(unsigned int *puint, char *str,
626 		     size_t str_size)
627 {
628 	struct utsname utsname;
629 	int version, patchlevel, sublevel, err;
630 
631 	if (uname(&utsname))
632 		return -1;
633 
634 	if (str && str_size) {
635 		strncpy(str, utsname.release, str_size);
636 		str[str_size - 1] = '\0';
637 	}
638 
639 	err = sscanf(utsname.release, "%d.%d.%d",
640 		     &version, &patchlevel, &sublevel);
641 
642 	if (err != 3) {
643 		pr_debug("Unablt to get kernel version from uname '%s'\n",
644 			 utsname.release);
645 		return -1;
646 	}
647 
648 	if (puint)
649 		*puint = (version << 16) + (patchlevel << 8) + sublevel;
650 	return 0;
651 }
652 
653 const char *perf_tip(const char *dirpath)
654 {
655 	struct strlist *tips;
656 	struct str_node *node;
657 	char *tip = NULL;
658 	struct strlist_config conf = {
659 		.dirname = dirpath,
660 		.file_only = true,
661 	};
662 
663 	tips = strlist__new("tips.txt", &conf);
664 	if (tips == NULL)
665 		return errno == ENOENT ? NULL : "Tip: get more memory! ;-p";
666 
667 	if (strlist__nr_entries(tips) == 0)
668 		goto out;
669 
670 	node = strlist__entry(tips, random() % strlist__nr_entries(tips));
671 	if (asprintf(&tip, "Tip: %s", node->s) < 0)
672 		tip = (char *)"Tip: get more memory! ;-)";
673 
674 out:
675 	strlist__delete(tips);
676 
677 	return tip;
678 }
679 
680 bool is_regular_file(const char *file)
681 {
682 	struct stat st;
683 
684 	if (stat(file, &st))
685 		return false;
686 
687 	return S_ISREG(st.st_mode);
688 }
689 
690 int fetch_current_timestamp(char *buf, size_t sz)
691 {
692 	struct timeval tv;
693 	struct tm tm;
694 	char dt[32];
695 
696 	if (gettimeofday(&tv, NULL) || !localtime_r(&tv.tv_sec, &tm))
697 		return -1;
698 
699 	if (!strftime(dt, sizeof(dt), "%Y%m%d%H%M%S", &tm))
700 		return -1;
701 
702 	scnprintf(buf, sz, "%s%02u", dt, (unsigned)tv.tv_usec / 10000);
703 
704 	return 0;
705 }
706 
707 void print_binary(unsigned char *data, size_t len,
708 		  size_t bytes_per_line, print_binary_t printer,
709 		  void *extra)
710 {
711 	size_t i, j, mask;
712 
713 	if (!printer)
714 		return;
715 
716 	bytes_per_line = roundup_pow_of_two(bytes_per_line);
717 	mask = bytes_per_line - 1;
718 
719 	printer(BINARY_PRINT_DATA_BEGIN, 0, extra);
720 	for (i = 0; i < len; i++) {
721 		if ((i & mask) == 0) {
722 			printer(BINARY_PRINT_LINE_BEGIN, -1, extra);
723 			printer(BINARY_PRINT_ADDR, i, extra);
724 		}
725 
726 		printer(BINARY_PRINT_NUM_DATA, data[i], extra);
727 
728 		if (((i & mask) == mask) || i == len - 1) {
729 			for (j = 0; j < mask-(i & mask); j++)
730 				printer(BINARY_PRINT_NUM_PAD, -1, extra);
731 
732 			printer(BINARY_PRINT_SEP, i, extra);
733 			for (j = i & ~mask; j <= i; j++)
734 				printer(BINARY_PRINT_CHAR_DATA, data[j], extra);
735 			for (j = 0; j < mask-(i & mask); j++)
736 				printer(BINARY_PRINT_CHAR_PAD, i, extra);
737 			printer(BINARY_PRINT_LINE_END, -1, extra);
738 		}
739 	}
740 	printer(BINARY_PRINT_DATA_END, -1, extra);
741 }
742