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
#[macro_use]
extern crate serde_derive;
extern crate threadinfo;
#[cfg(target_os = "linux")]
mod lib_linux;
#[cfg(target_os = "linux")]
pub use lib_linux::*;
#[cfg(target_os = "macos")]
mod lib_mac;
#[cfg(target_os = "macos")]
pub use lib_mac::*;
pub mod output;
pub mod speedscope;
mod module_cache;
pub mod types;
use std::collections::HashMap;
use threadinfo::Thread as ThreadId;
use types::{Frame, Unwinder};
pub struct Profiler {
sampler: Sampler,
}
impl Profiler {
pub fn new() -> Profiler {
Profiler {
sampler: Sampler::new(),
}
}
pub fn session(&self) -> Session {
Session {
profiler: &self,
threads: HashMap::new(),
}
}
}
pub struct Session<'a> {
profiler: &'a Profiler,
threads: HashMap<ThreadId, Vec<Vec<Frame>>>,
}
impl<'a> Session<'a> {
pub fn sample_thread(&mut self, thread: ThreadId) {
let sample = self.sample_once(thread);
self.threads
.entry(thread)
.or_insert_with(|| Vec::new())
.push(sample);
}
fn sample_once(&self, thread: ThreadId) -> Vec<Frame> {
let unwinder = LibunwindUnwinder::new(150);
self.profiler
.sampler
.suspend_and_resume_thread(thread, move |context| {
unwinder.unwind(context).expect("sample succeeded")
})
}
pub fn finish(self) -> Profile {
Profile {
threads: self.threads,
}
}
}
pub struct Profile {
threads: HashMap<ThreadId, Vec<Vec<Frame>>>,
}
#[cfg(test)]
mod tests {
use super::*;
use std::{sync::mpsc::channel, thread::spawn};
#[cfg(target_os = "linux")]
#[test]
fn test_suspend_resume() {
let sampler = Sampler::new();
let (tx, rx) = channel();
let (tx2, rx2) = channel();
let handle = spawn(move || {
tx.send(threadinfo::current_thread().unwrap()).unwrap();
rx2.recv().unwrap();
});
let to = rx.recv().unwrap();
sampler.suspend_and_resume_thread(to, |context| {
assert!(context.uc_stack.ss_size > 0);
tx2.send(()).unwrap();
});
handle.join().unwrap();
}
}