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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
// Copyright (C) 2022 The Perf-tools Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use chrono::{offset::LocalResult, DateTime, Local, NaiveDateTime, TimeZone};
use lazy_static::lazy_static;
use prost::Message;
use regex::Regex;
use std::collections::HashMap;
use std::io;
use std::time::Duration;

pub mod pb {
    include!(concat!(env!("OUT_DIR"), "/perftools.profiles.rs"));
}

#[derive(PartialEq, Hash, std::cmp::Eq)]
struct Stack {
    pc: u64,
    func: String,
    module: String,
}

#[derive(PartialEq, Hash, std::cmp::Eq)]
struct Sample {
    stacks: Vec<Stack>,
}

struct PerfReader {
    sample: HashMap<Sample, u64>,
    captured_time: DateTime<Local>,
    duration: Duration,
    freq: u64,
}

#[derive(Default)]
pub struct PprofConverterBuilder {}

impl PprofConverterBuilder {
    pub fn build(&mut self) -> PprofConverter {
        PprofConverter::new()
    }
}

impl PerfReader {
    fn new<R>(mut reader: R) -> io::Result<Self>
    where
        R: io::BufRead,
    {
        let mut buf = Vec::new();
        let mut is_event_line = true;
        let mut sample = HashMap::default();
        let mut header = Vec::new();
        let mut stack = Vec::new();
        let mut start_usec = 0;
        let mut end_usec = 0;

        lazy_static! {
            static ref RE: Regex = Regex::new(r"\S+\s+\d+\s+(\d+)\.(\d+)").unwrap();
        }

        loop {
            buf.clear();
            if let Ok(n) = reader.read_until(b'\n', &mut buf) {
                if n == 0 {
                    break;
                }
                let line = String::from_utf8_lossy(&buf);
                if line.starts_with('#') {
                    header.push(line.trim().to_string());
                    continue;
                }
                let line = line.trim();
                if line.is_empty() {
                    // return one stack
                    is_event_line = true;
                    if !stack.is_empty() {
                        let count = sample
                            .entry(Sample {
                                stacks: stack.split_off(0),
                            })
                            .or_insert(0);
                        *count += 1;
                    }
                    continue;
                }
                if is_event_line {
                    // event line
                    if let Some(caps) = RE.captures(line) {
                        let sec: u64 = caps.get(1).unwrap().as_str().parse().unwrap();
                        let usec: u64 = caps.get(2).unwrap().as_str().parse().unwrap();
                        if sample.is_empty() {
                            start_usec = sec * 1_000_000 + usec;
                        } else {
                            end_usec = sec * 1_000_000 + usec;
                        }
                    }

                    is_event_line = false;
                    continue;
                } else {
                    // stack line
                    let line = line.splitn(2, ' ').collect::<Vec<&str>>();
                    if let Ok(pc) = u64::from_str_radix(line[0], 16) {
                        let line = line[1].rsplitn(2, ' ').collect::<Vec<&str>>();
                        stack.push(Stack {
                            pc,
                            func: line[1].to_string(),
                            module: line[0].to_string(),
                        });
                    }
                }
            } else {
                break;
            }
        }

        if end_usec == 0 {
            return Err(io::Error::new(io::ErrorKind::Other, "can't find duration"));
        }

        let (captured_time, freq) = PerfReader::verify_header(&header)?;

        Ok(PerfReader {
            sample,
            captured_time,
            duration: Duration::from_micros(end_usec - start_usec),
            freq,
        })
    }

    fn verify_header(header: &[String]) -> io::Result<(DateTime<Local>, u64)> {
        let mut dt = None;
        let mut freq = 0;

        for h in header {
            // sample_freq } = 997
            let re = Regex::new(r"sample_freq\s+}\s+=\s+(\d+)").unwrap();
            // captured on    : Thu Mar 10 10:45:19 2022
            if h.contains("captured on") {
                let line = h.splitn(2, ':').collect::<Vec<&str>>();
                if line.len() == 2 {
                    if let Ok(time) = NaiveDateTime::parse_from_str(line[1].trim(), "%c") {
                        dt = if let LocalResult::Single(t) = Local.from_local_datetime(&time) {
                            Some(t)
                        } else {
                            None
                        };
                    }
                }
            } else if let Some(caps) = re.captures(h) {
                if let Some(v) = caps.get(1) {
                    freq = v
                        .as_str()
                        .parse()
                        .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{}", e)))?;
                }
            }
        }
        let captured_time = dt.ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::Other,
                "captured time isn't found in the header",
            )
        })?;
        if freq == 0 {}

        Ok((captured_time, freq))
    }
}

pub struct PprofConverter {
    str_map: HashMap<String, u64>,

    location: LocationId,
    function: FunctionId,
}

struct FunctionId {
    next_id: u64,
    map: HashMap<String, (u64, u64)>, // name, (id, str_id)
}

struct LocationId {
    next_id: u64,
    map: HashMap<u64, (u64, u64)>, // address, (id, funciton_id)
}

impl PprofConverter {
    fn new() -> Self {
        let mut str_map: HashMap<String, u64> = HashMap::default();
        for (i, s) in vec!["", "samples", "count", "cpu", "nanoseconds"]
            .iter()
            .enumerate()
        {
            str_map.insert(s.to_string(), i as u64);
        }

        PprofConverter {
            str_map,
            location: LocationId {
                next_id: 0,
                map: HashMap::default(),
            },
            function: FunctionId {
                next_id: 0,
                map: HashMap::default(),
            },
        }
    }

    fn location_id(&mut self, addr: u64, name: &str) -> u64 {
        let loc_id = self.location.map.entry(addr).or_insert_with(|| {
            self.location.next_id += 1;
            let func_id = self
                .function
                .map
                .entry(name.to_string())
                .or_insert_with(|| {
                    let s = self.str_map.len() as u64;
                    let str_id = self.str_map.entry(name.to_string()).or_insert(s);
                    self.function.next_id += 1;
                    (self.function.next_id, *str_id)
                });
            (self.location.next_id, func_id.0)
        });
        loc_id.0
    }

    fn finish<R, W>(&mut self, reader: R, mut writer: W) -> io::Result<()>
    where
        R: io::BufRead,
        W: io::Write,
    {
        let perf = PerfReader::new(reader)?;
        let sample: Vec<pb::Sample> = perf
            .sample
            .iter()
            .map(|(s, count)| pb::Sample {
                location_id: s
                    .stacks
                    .iter()
                    .map(|s| self.location_id(s.pc, &s.func))
                    .collect(),
                value: vec![
                    *count as i64,
                    *count as i64 * 1_000_000_000 / perf.freq as i64,
                ],
                label: Vec::new(),
            })
            .collect();

        let mut function: Vec<pb::Function> = self
            .function
            .map
            .iter()
            .map(|(_, v)| pb::Function {
                id: v.0,
                name: v.1 as i64,
                ..Default::default()
            })
            .collect();
        function.sort_by(|a, b| a.id.cmp(&b.id));

        let mut string_table: Vec<(String, u64)> =
            self.str_map.iter().map(|(k, v)| (k.clone(), *v)).collect();
        string_table.sort_by(|a, b| a.1.cmp(&b.1));

        let mut location: Vec<pb::Location> = self
            .location
            .map
            .iter()
            .map(|(k, v)| pb::Location {
                id: v.0,
                address: *k,
                line: vec![pb::Line {
                    function_id: v.1,
                    line: 0,
                }],
                ..Default::default()
            })
            .collect();
        location.sort_by(|a, b| a.id.cmp(&b.id));

        let mut content = Vec::new();
        pb::Profile {
            sample_type: vec![
                pb::ValueType { r#type: 1, unit: 2 },
                pb::ValueType { r#type: 3, unit: 4 },
            ],
            sample,
            location,
            function,
            time_nanos: perf.captured_time.timestamp_nanos(),
            duration_nanos: perf.duration.as_nanos() as i64,
            string_table: string_table.into_iter().map(|(k, _)| k).collect(),
            period: 1_000_000_000 / perf.freq as i64,
            period_type: Some(pb::ValueType { r#type: 3, unit: 4 }),
            ..pb::Profile::default()
        }
        .encode(&mut content)
        .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{}", e)))?;
        writer.write_all(&content)
    }

    pub fn from_reader<R, W>(&mut self, reader: R, writer: W) -> io::Result<()>
    where
        R: io::BufRead,
        W: io::Write,
    {
        self.finish(reader, writer)
    }
}