Skip to main content

mz_prof/
lib.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License in the LICENSE file at the
6// root of this repository, or online at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use std::collections::BTreeMap;
17use std::ffi::c_void;
18use std::sync::atomic::AtomicBool;
19
20use pprof_util::{StackProfile, WeightedStack};
21
22pub mod time;
23
24#[cfg(feature = "jemalloc")]
25pub mod jemalloc;
26
27pub trait StackProfileExt {
28    /// Writes out the `.mzfg` format, which is fully described in flamegraph.js.
29    fn to_mzfg(&self, symbolize: bool, header_extra: &[(&str, &str)]) -> String;
30}
31
32impl StackProfileExt for StackProfile {
33    fn to_mzfg(&self, symbolize: bool, header_extra: &[(&str, &str)]) -> String {
34        // All the unwraps in this function are justified by the fact that
35        // String's fmt::Write impl is infallible.
36        use std::fmt::Write;
37        let mut builder = r#"!!! COMMENT !!!: Open with bin/fgviz /path/to/mzfg
38mz_fg_version: 1
39"#
40        .to_owned();
41        for (k, v) in header_extra {
42            assert!(!(k.contains(':') || k.contains('\n') || v.contains('\n')));
43            writeln!(&mut builder, "{k}: {v}").unwrap();
44        }
45        writeln!(&mut builder, "").unwrap();
46
47        for (WeightedStack { addrs, weight }, anno) in &self.stacks {
48            let anno = anno.map(|i| &self.annotations[i]);
49            for &addr in addrs {
50                write!(&mut builder, "{addr:#x};").unwrap();
51            }
52            write!(&mut builder, " {weight}").unwrap();
53            if let Some(anno) = anno {
54                write!(&mut builder, " {anno}").unwrap()
55            }
56            writeln!(&mut builder, "").unwrap();
57        }
58
59        if symbolize {
60            let symbols = crate::symbolize(self);
61            writeln!(&mut builder, "").unwrap();
62
63            for (addr, names) in symbols {
64                if !names.is_empty() {
65                    write!(&mut builder, "{addr:#x} ").unwrap();
66                    for mut name in names {
67                        // The client splits on semicolons, so
68                        // we have to escape them.
69                        name = name.replace('\\', "\\\\");
70                        name = name.replace(';', "\\;");
71                        write!(&mut builder, "{name};").unwrap();
72                    }
73                    writeln!(&mut builder, "").unwrap();
74                }
75            }
76        }
77
78        builder
79    }
80}
81
82static EVER_SYMBOLIZED: AtomicBool = AtomicBool::new(false);
83
84/// Check whether symbolization has ever been run in this process.
85/// This controls whether we display a warning about increasing RAM usage
86/// due to the backtrace cache on the
87/// profiler page. (Because the RAM hit is one-time, we don't need to warn if it's already happened).
88pub fn ever_symbolized() -> bool {
89    EVER_SYMBOLIZED.load(std::sync::atomic::Ordering::SeqCst)
90}
91
92/// Given some stack traces, generate a map of addresses to their
93/// corresponding symbols.
94///
95/// Each address could correspond to more than one symbol, because
96/// of inlining. (E.g. if 0x1234 comes from "g", which is inlined in "f", the corresponding vec of symbols will be ["f", "g"].)
97pub fn symbolize(profile: &StackProfile) -> BTreeMap<usize, Vec<String>> {
98    EVER_SYMBOLIZED.store(true, std::sync::atomic::Ordering::SeqCst);
99    let mut all_addrs = vec![];
100    for (stack, _annotation) in profile.stacks.iter() {
101        all_addrs.extend(stack.addrs.iter().cloned());
102    }
103    // Sort so addresses from the same images are together,
104    // to avoid thrashing `backtrace::resolve`'s cache of
105    // parsed images.
106    all_addrs.sort_unstable();
107    all_addrs.dedup();
108    all_addrs
109        .into_iter()
110        .map(|addr| {
111            let mut syms = vec![];
112            // No other known way to convert usize to pointer.
113            #[allow(clippy::as_conversions)]
114            let addr_ptr = addr as *mut c_void;
115            backtrace::resolve(addr_ptr, |sym| {
116                let name = sym
117                    .name()
118                    .map(|sn| sn.to_string())
119                    .unwrap_or_else(|| "???".to_string());
120                syms.push(name);
121            });
122            syms.reverse();
123            (addr, syms)
124        })
125        .collect()
126}