_core_rustc_static/
resources_table.rs

1// Copyright 2023 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5pub use heapdump_vmo::resources_table_v1::ResourceKey;
6use heapdump_vmo::resources_table_v1::ResourcesTableWriter;
7use std::sync::atomic::fence;
8use std::sync::atomic::Ordering::Release;
9use zx::{self as zx, AsHandleRef, HandleBased};
10
11/// We cap the size of our backing VMO at 2 GiB, then preallocate it and map it entirely.
12/// Actual memory for each page will only be committed when we first write to that page.
13const VMO_SIZE: usize = 1 << 31;
14
15const VMO_NAME: zx::Name = zx::Name::new_lossy("heapdump-resources");
16
17/// Stores immutable resources in a dedicated VMO.
18pub struct ResourcesTable {
19    vmo: zx::Vmo,
20    writer: ResourcesTableWriter,
21}
22
23impl Default for ResourcesTable {
24    fn default() -> ResourcesTable {
25        let vmo = zx::Vmo::create(VMO_SIZE as u64).expect("failed to create resources VMO");
26        vmo.set_name(&VMO_NAME).expect("failed to set VMO name");
27
28        let writer = ResourcesTableWriter::new(&vmo).expect("failed to create writer");
29        ResourcesTable { vmo, writer }
30    }
31}
32
33impl ResourcesTable {
34    /// Duplicates the handle to the underlying VMO.
35    pub fn share_vmo(&self) -> zx::Vmo {
36        self.vmo.duplicate_handle(zx::Rights::SAME_RIGHTS).expect("failed to share resources VMO")
37    }
38
39    /// Inserts a compressed stack trace, or finds a previously-inserted copy.
40    pub fn intern_stack_trace(&mut self, compressed_stack_trace: &[u8]) -> ResourceKey {
41        let (resource_key, inserted) = self
42            .writer
43            .intern_compressed_stack_trace(compressed_stack_trace)
44            .expect("failed to insert stack trace");
45
46        // If we have just inserted a new stack trace, ensure it's committed to the underlying VMO.
47        if inserted {
48            fence(Release);
49        }
50
51        resource_key
52    }
53
54    /// Inserts information about a thread.
55    pub fn insert_thread_info(&mut self, koid: zx::Koid, name: &zx::Name) -> ResourceKey {
56        self.writer.insert_thread_info(koid.raw_koid(), name).expect("failed to insert thread info")
57    }
58}