• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2023 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_METRICS_HISTOGRAM_SHARED_MEMORY_H_
6 #define BASE_METRICS_HISTOGRAM_SHARED_MEMORY_H_
7 
8 #include "base/base_export.h"
9 #include "base/memory/writable_shared_memory_region.h"
10 #include "base/metrics/persistent_memory_allocator.h"
11 #include "third_party/abseil-cpp/absl/types/optional.h"
12 
13 namespace base {
14 
15 // Configuration with which to create a histogram shared memory region and
16 // allocator.
17 struct BASE_EXPORT HistogramSharedMemoryConfig {
18   base::StringPiece allocator_name;
19   size_t memory_size_bytes;
20 };
21 
22 // Helper structure to create and return a shared memory region and a histogram
23 // allocator over top of it. Once returned it is expected that the caller will
24 // move both the memory regions and the allocator out of the struct and into
25 // it's own appropriate state variables. Note that the memory region must
26 // outlive the allocator.
27 class BASE_EXPORT HistogramSharedMemory {
28  public:
29   HistogramSharedMemory();
30   ~HistogramSharedMemory();
31 
32   // Move operations are supported.
33   HistogramSharedMemory(HistogramSharedMemory&& other);
34   HistogramSharedMemory& operator=(HistogramSharedMemory&& other);
35 
36   // Copy operations are NOT supported.
37   HistogramSharedMemory(const HistogramSharedMemory&) = delete;
38   HistogramSharedMemory& operator=(const HistogramSharedMemory&) = delete;
39 
40   // Factory to initialize a shared memory region for |unique_process_id|
41   // based on |config|.
42   static absl::optional<HistogramSharedMemory> Create(
43       int unique_process_id,
44       const HistogramSharedMemoryConfig& config);
45 
46   // Returns true if the memory region and allocator are valid.
47   bool IsValid() const;
48 
49   // Returns, and transfers ownership of, the memory region to the caller.
50   base::WritableSharedMemoryRegion TakeRegion();
51 
52   // Returns, and transfers ownership of, the memory allocator to the caller.
53   std::unique_ptr<base::WritableSharedPersistentMemoryAllocator>
54   TakeAllocator();
55 
56  private:
57   // Internal constructor.
58   HistogramSharedMemory(
59       base::WritableSharedMemoryRegion region,
60       std::unique_ptr<base::WritableSharedPersistentMemoryAllocator> allocator);
61 
62   // The shared memory region.
63   base::WritableSharedMemoryRegion region_;
64 
65   // The shared memory allocator.
66   std::unique_ptr<base::WritableSharedPersistentMemoryAllocator> allocator_;
67 };
68 
69 }  // namespace base
70 #endif  // BASE_METRICS_HISTOGRAM_SHARED_MEMORY_H_
71