-
Notifications
You must be signed in to change notification settings - Fork 114
/
dtrace.rs
205 lines (180 loc) · 6 KB
/
dtrace.rs
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
use super::Collapse;
use std::collections::{HashMap, VecDeque};
use std::io;
use std::io::prelude::*;
/// Settings that change how frames are named from the incoming stack traces.
///
/// All options default to off.
#[derive(Clone, Debug, Default)]
pub struct Options {
/// include function offset (except leafs)
pub includeoffset: bool,
}
/// A stack collapser for the output of dtrace `ustrace()`.
///
/// To construct one, either use `dtrace::Folder::default()` or create an [`Options`] and use
/// `dtrace::Folder::from(options)`.
#[derive(Default)]
pub struct Folder {
/// Function entries on the stack in this entry thus far.
stack: VecDeque<String>,
/// Number of times each call stack has been seen.
occurrences: HashMap<String, usize>,
/// Keep track of stack string size while we consume a stack
stack_str_size: usize,
/// vecotr for processing java stuff
cache_inlines: Vec<String>,
opt: Options,
}
impl Collapse for Folder {
fn collapse<R, W>(&mut self, mut reader: R, writer: W) -> io::Result<()>
where
R: BufRead,
W: Write,
{
let mut line = String::new();
// skip header lines -- first empty line marks start of data
loop {
line.clear();
if reader.read_line(&mut line)? == 0 {
// We reached the end :( this should not happen.
warn!("File ended while skipping headers");
return Ok(());
};
if line.trim().is_empty() {
break;
}
}
loop {
line.clear();
if reader.read_line(&mut line)? == 0 {
break;
}
let line = line.trim();
if line.is_empty() {
continue;
} else if let Ok(count) = line.parse::<usize>() {
self.on_stack_end(count);
} else {
self.on_stack_line(line);
}
}
self.finish(writer)
}
}
impl From<Options> for Folder {
fn from(opt: Options) -> Self {
Self {
stack: VecDeque::default(),
occurrences: HashMap::default(),
cache_inlines: Vec::new(),
opt,
stack_str_size: 0,
}
}
}
impl Folder {
// This function approximates the Perl regex s/(::.*)[(<].*/$1/
// from https://github.com/brendangregg/FlameGraph/blob/1b1c6deede9c33c5134c920bdb7a44cc5528e9a7/stackcollapse.pl#L88
fn uncpp(probe: &str) -> &str {
if let Some(scope) = probe.find("::") {
if let Some(open) = probe[scope + 2..].rfind(|c| c == '(' || c == '<') {
&probe[..scope + 2 + open]
} else {
probe
}
} else {
probe
}
}
fn remove_offset(line: &str) -> &str {
let mut line = line.rsplitn(2, '+');
// at least one element will be returned
let second = line.next().unwrap();
if let Some(first) = line.next() {
first
} else {
second
}
}
// we have a stack line that shows one stack entry from the preceeding event, like:
//
// unix`tsc_gethrtimeunscaled+0x21
// genunix`gethrtime_unscaled+0xa
// genunix`syscall_mstate+0x5d
// unix`sys_syscall+0x10e
// 1
fn on_stack_line(&mut self, line: &str) {
let line = line.trim_start();
let frame = if self.opt.includeoffset {
line
} else {
Self::remove_offset(line)
};
let mut frame = Self::uncpp(frame);
if frame.is_empty() {
frame = "-";
};
let mut inline = false;
for func in frame.split("->") {
let mut func = func.trim_start_matches('L').replace(';', ":");
if inline {
func.push_str("_[i]")
};
inline = true;
self.stack_str_size += func.len() + 1;
self.cache_inlines.push(func);
}
while let Some(func) = self.cache_inlines.pop() {
self.stack.push_front(func);
}
}
fn on_stack_end(&mut self, count: usize) {
// allocate a string that is long enough to hold the entire stack string
let mut stack_str = String::with_capacity(self.stack_str_size);
let mut first = true;
// add the other stack entries (if any)
let last = self.stack.len() - 1;
for (i, e) in self.stack.drain(..).enumerate() {
if first {
first = false
} else {
stack_str.push_str(";");
}
//trim leaf offset if these were retained:
if self.opt.includeoffset && i == last {
stack_str.push_str(Self::remove_offset(&e));
} else {
stack_str.push_str(&e);
}
}
// count it!
*self.occurrences.entry(stack_str).or_insert(0) += count;
// reset for the next event
self.stack_str_size = 0;
self.stack.clear();
}
fn finish<W: Write>(&self, mut writer: W) -> io::Result<()> {
let mut keys: Vec<_> = self.occurrences.keys().collect();
keys.sort();
for key in keys {
writeln!(writer, "{} {}", key, self.occurrences[key])?;
}
Ok(())
}
}
#[cfg(test)]
#[test]
fn cpp_test() {
let probe = "TestClass::TestClass2(const char*)[__1cJTestClass2t6Mpkc_v_]";
assert_eq!("TestClass::TestClass2", Folder::uncpp(probe));
let probe = "TestClass::TestClass2::TestClass3(const char*)[__1cJTestClass2t6Mpkc_v_]";
assert_eq!("TestClass::TestClass2::TestClass3", Folder::uncpp(probe));
let probe = "TestClass::TestClass2<blargh>(const char*)[__1cJTestClass2t6Mpkc_v_]";
assert_eq!("TestClass::TestClass2<blargh>", Folder::uncpp(probe));
let probe = "TestClass::TestClass2::TestClass3<blargh>(const char*)[__1cJTestClass2t6Mpkc_v_]";
assert_eq!(
"TestClass::TestClass2::TestClass3<blargh>",
Folder::uncpp(probe)
);
}