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 #include "base/metrics/histogram_shared_memory.h" 6 7 #include "base/memory/shared_memory_mapping.h" 8 9 namespace base { 10 11 HistogramSharedMemory::HistogramSharedMemory() = default; 12 HistogramSharedMemory::~HistogramSharedMemory() = default; 13 HistogramSharedMemory::HistogramSharedMemory(HistogramSharedMemory&& other) = 14 default; 15 HistogramSharedMemory& HistogramSharedMemory::operator=( 16 HistogramSharedMemory&& other) = default; 17 18 // static Create(int unique_process_id,const HistogramSharedMemoryConfig & config)19absl::optional<HistogramSharedMemory> HistogramSharedMemory::Create( 20 int unique_process_id, 21 const HistogramSharedMemoryConfig& config) { 22 auto shared_memory_region = 23 base::WritableSharedMemoryRegion::Create(config.memory_size_bytes); 24 if (!shared_memory_region.IsValid()) { 25 return absl::nullopt; 26 } 27 28 auto shared_memory_mapping = shared_memory_region.Map(); 29 if (!shared_memory_mapping.IsValid()) { 30 return absl::nullopt; 31 } 32 33 auto metrics_allocator = 34 std::make_unique<base::WritableSharedPersistentMemoryAllocator>( 35 std::move(shared_memory_mapping), 36 static_cast<uint64_t>(unique_process_id), config.allocator_name); 37 38 return HistogramSharedMemory{std::move(shared_memory_region), 39 std::move(metrics_allocator)}; 40 } 41 IsValid() const42bool HistogramSharedMemory::IsValid() const { 43 return region_.IsValid() && allocator_ != nullptr; 44 } 45 TakeRegion()46base::WritableSharedMemoryRegion HistogramSharedMemory::TakeRegion() { 47 return std::move(region_); 48 } 49 50 std::unique_ptr<base::WritableSharedPersistentMemoryAllocator> TakeAllocator()51HistogramSharedMemory::TakeAllocator() { 52 return std::move(allocator_); 53 } 54 HistogramSharedMemory(base::WritableSharedMemoryRegion region,std::unique_ptr<base::WritableSharedPersistentMemoryAllocator> allocator)55HistogramSharedMemory::HistogramSharedMemory( 56 base::WritableSharedMemoryRegion region, 57 std::unique_ptr<base::WritableSharedPersistentMemoryAllocator> allocator) 58 : region_(std::move(region)), allocator_(std::move(allocator)) { 59 CHECK(IsValid()); 60 } 61 62 } // namespace base 63