summaryrefslogtreecommitdiffstats
path: root/tools/perf/util/srcline.c
blob: dcff10bed7da47478b5397375387bd18d955fe6a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <linux/kernel.h>

#include "util/dso.h"
#include "util/util.h"
#include "util/debug.h"

static int addr2line(const char *dso_name, unsigned long addr,
		     char **file, unsigned int *line_nr)
{
	FILE *fp;
	char cmd[PATH_MAX];
	char *filename = NULL;
	size_t len;
	char *sep;
	int ret = 0;

	scnprintf(cmd, sizeof(cmd), "addr2line -e %s %016"PRIx64,
		  dso_name, addr);

	fp = popen(cmd, "r");
	if (fp == NULL) {
		pr_warning("popen failed for %s\n", dso_name);
		return 0;
	}

	if (getline(&filename, &len, fp) < 0 || !len) {
		pr_warning("addr2line has no output for %s\n", dso_name);
		goto out;
	}

	sep = strchr(filename, '\n');
	if (sep)
		*sep = '\0';

	if (!strcmp(filename, "??:0")) {
		pr_debug("no debugging info in %s\n", dso_name);
		free(filename);
		goto out;
	}

	sep = strchr(filename, ':');
	if (sep) {
		*sep++ = '\0';
		*file = filename;
		*line_nr = strtoul(sep, NULL, 0);
		ret = 1;
	}
out:
	pclose(fp);
	return ret;
}

char *get_srcline(struct dso *dso, unsigned long addr)
{
	char *file;
	unsigned line;
	char *srcline;
	char *dso_name = dso->long_name;
	size_t size;

	if (!dso->has_srcline)
		return SRCLINE_UNKNOWN;

	if (dso_name[0] == '[')
		goto out;

	if (!strncmp(dso_name, "/tmp/perf-", 10))
		goto out;

	if (!addr2line(dso_name, addr, &file, &line))
		goto out;

	/* just calculate actual length */
	size = snprintf(NULL, 0, "%s:%u", file, line) + 1;

	srcline = malloc(size);
	if (srcline)
		snprintf(srcline, size, "%s:%u", file, line);
	else
		srcline = SRCLINE_UNKNOWN;

	free(file);
	return srcline;

out:
	dso->has_srcline = 0;
	return SRCLINE_UNKNOWN;
}

void free_srcline(char *srcline)
{
	if (srcline && strcmp(srcline, SRCLINE_UNKNOWN) != 0)
		free(srcline);
}