• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2018 The Chromium 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 
5 #include "base/memory/unsafe_shared_memory_region.h"
6 
7 #include <utility>
8 
9 #include "base/memory/shared_memory.h"
10 
11 namespace base {
12 
13 // static
Create(size_t size)14 UnsafeSharedMemoryRegion UnsafeSharedMemoryRegion::Create(size_t size) {
15   subtle::PlatformSharedMemoryRegion handle =
16       subtle::PlatformSharedMemoryRegion::CreateUnsafe(size);
17 
18   return UnsafeSharedMemoryRegion(std::move(handle));
19 }
20 
21 // static
Deserialize(subtle::PlatformSharedMemoryRegion handle)22 UnsafeSharedMemoryRegion UnsafeSharedMemoryRegion::Deserialize(
23     subtle::PlatformSharedMemoryRegion handle) {
24   return UnsafeSharedMemoryRegion(std::move(handle));
25 }
26 
27 // static
28 subtle::PlatformSharedMemoryRegion
TakeHandleForSerialization(UnsafeSharedMemoryRegion region)29 UnsafeSharedMemoryRegion::TakeHandleForSerialization(
30     UnsafeSharedMemoryRegion region) {
31   return std::move(region.handle_);
32 }
33 
34 UnsafeSharedMemoryRegion::UnsafeSharedMemoryRegion() = default;
35 UnsafeSharedMemoryRegion::UnsafeSharedMemoryRegion(
36     UnsafeSharedMemoryRegion&& region) = default;
37 UnsafeSharedMemoryRegion& UnsafeSharedMemoryRegion::operator=(
38     UnsafeSharedMemoryRegion&& region) = default;
39 UnsafeSharedMemoryRegion::~UnsafeSharedMemoryRegion() = default;
40 
Duplicate() const41 UnsafeSharedMemoryRegion UnsafeSharedMemoryRegion::Duplicate() const {
42   return UnsafeSharedMemoryRegion(handle_.Duplicate());
43 }
44 
Map() const45 WritableSharedMemoryMapping UnsafeSharedMemoryRegion::Map() const {
46   return MapAt(0, handle_.GetSize());
47 }
48 
MapAt(off_t offset,size_t size) const49 WritableSharedMemoryMapping UnsafeSharedMemoryRegion::MapAt(off_t offset,
50                                                             size_t size) const {
51   if (!IsValid())
52     return {};
53 
54   void* memory = nullptr;
55   size_t mapped_size = 0;
56   if (!handle_.MapAt(offset, size, &memory, &mapped_size))
57     return {};
58 
59   return WritableSharedMemoryMapping(memory, size, mapped_size,
60                                      handle_.GetGUID());
61 }
62 
IsValid() const63 bool UnsafeSharedMemoryRegion::IsValid() const {
64   return handle_.IsValid();
65 }
66 
UnsafeSharedMemoryRegion(subtle::PlatformSharedMemoryRegion handle)67 UnsafeSharedMemoryRegion::UnsafeSharedMemoryRegion(
68     subtle::PlatformSharedMemoryRegion handle)
69     : handle_(std::move(handle)) {
70   if (handle_.IsValid()) {
71     CHECK_EQ(handle_.GetMode(),
72              subtle::PlatformSharedMemoryRegion::Mode::kUnsafe);
73   }
74 }
75 
76 }  // namespace base
77