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.
45pub 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};
1011/// 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;
1415const VMO_NAME: zx::Name = zx::Name::new_lossy("heapdump-resources");
1617/// Stores immutable resources in a dedicated VMO.
18pub struct ResourcesTable {
19 vmo: zx::Vmo,
20 writer: ResourcesTableWriter,
21}
2223impl Default for ResourcesTable {
24fn default() -> ResourcesTable {
25let 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");
2728let writer = ResourcesTableWriter::new(&vmo).expect("failed to create writer");
29 ResourcesTable { vmo, writer }
30 }
31}
3233impl ResourcesTable {
34/// Duplicates the handle to the underlying VMO.
35pub fn share_vmo(&self) -> zx::Vmo {
36self.vmo.duplicate_handle(zx::Rights::SAME_RIGHTS).expect("failed to share resources VMO")
37 }
3839/// Inserts a compressed stack trace, or finds a previously-inserted copy.
40pub fn intern_stack_trace(&mut self, compressed_stack_trace: &[u8]) -> ResourceKey {
41let (resource_key, inserted) = self
42.writer
43 .intern_compressed_stack_trace(compressed_stack_trace)
44 .expect("failed to insert stack trace");
4546// If we have just inserted a new stack trace, ensure it's committed to the underlying VMO.
47if inserted {
48 fence(Release);
49 }
5051 resource_key
52 }
5354/// Inserts information about a thread.
55pub fn insert_thread_info(&mut self, koid: zx::Koid, name: &zx::Name) -> ResourceKey {
56self.writer.insert_thread_info(koid.raw_koid(), name).expect("failed to insert thread info")
57 }
58}