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
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

use std::os::raw::c_int;

use anyhow::bail;
use pprof::ProfilerGuard;
use tokio::time::{self, Duration};

use crate::{StackProfile, WeightedStack};

/// # Safety
///
/// Nothing else must be attempting to unwind backtraces while this is called.
/// In particular, jemalloc memory profiling must be off.
pub async unsafe fn prof_time(
    total_time: Duration,
    sample_freq: u32,
    merge_threads: bool,
) -> anyhow::Result<StackProfile> {
    if sample_freq > (1e6 as u32) {
        bail!("Sub-microsecond intervals are not supported.");
    }
    let pg = ProfilerGuard::new(sample_freq as c_int)?;
    time::sleep(total_time).await;
    let builder = pg.report();
    let report = builder.build_unresolved()?;
    let mut profile = <StackProfile as Default>::default();
    for (f, weight) in report.data {
        let thread_name;
        let mut addrs: Vec<_> = f.frames.iter().map(|f| f.ip() as usize).collect();
        addrs.reverse();
        let weight = weight as f64;
        let anno = if merge_threads {
            None
        } else {
            thread_name = String::from_utf8_lossy(&f.thread_name[0..f.thread_name_length]);
            Some(thread_name.as_ref())
        };
        let stack = WeightedStack { addrs, weight };
        profile.push(stack, anno);
    }

    Ok(profile)
}