1 // Copyright (c) 2012 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.
5 #include "base/memory/shared_memory.h"
15 #include "base/logging.h"
19 SharedMemory::SharedMemory()
28 SharedMemory::SharedMemory(SharedMemoryHandle handle
, bool read_only
)
29 : mapped_file_(handle
.fd
),
33 read_only_(read_only
),
37 SharedMemory::SharedMemory(SharedMemoryHandle handle
, bool read_only
,
38 ProcessHandle process
)
39 : mapped_file_(handle
.fd
),
43 read_only_(read_only
),
48 SharedMemory::~SharedMemory() {
53 bool SharedMemory::IsHandleValid(const SharedMemoryHandle
& handle
) {
54 return handle
.fd
>= 0;
58 SharedMemoryHandle
SharedMemory::NULLHandle() {
59 return SharedMemoryHandle();
63 void SharedMemory::CloseHandle(const SharedMemoryHandle
& handle
) {
64 DCHECK_GE(handle
.fd
, 0);
65 if (close(handle
.fd
) < 0)
66 DPLOG(ERROR
) << "close";
69 bool SharedMemory::CreateAndMapAnonymous(size_t size
) {
70 // Untrusted code can't create descriptors or handles.
74 bool SharedMemory::Create(const SharedMemoryCreateOptions
& options
) {
75 // Untrusted code can't create descriptors or handles.
79 bool SharedMemory::Delete(const std::string
& name
) {
83 bool SharedMemory::Open(const std::string
& name
, bool read_only
) {
87 bool SharedMemory::MapAt(off_t offset
, size_t bytes
) {
88 if (mapped_file_
== -1)
91 if (bytes
> static_cast<size_t>(std::numeric_limits
<int>::max()))
94 memory_
= mmap(NULL
, bytes
, PROT_READ
| (read_only_
? 0 : PROT_WRITE
),
95 MAP_SHARED
, mapped_file_
, offset
);
97 bool mmap_succeeded
= memory_
!= MAP_FAILED
&& memory_
!= NULL
;
100 DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_
) &
101 (SharedMemory::MAP_MINIMUM_ALIGNMENT
- 1));
106 return mmap_succeeded
;
109 bool SharedMemory::Unmap() {
113 if (munmap(memory_
, mapped_size_
) < 0)
114 DPLOG(ERROR
) << "munmap";
120 SharedMemoryHandle
SharedMemory::handle() const {
121 return FileDescriptor(mapped_file_
, false);
124 void SharedMemory::Close() {
126 if (mapped_file_
> 0) {
127 if (close(mapped_file_
) < 0)
128 DPLOG(ERROR
) << "close";
133 void SharedMemory::LockDeprecated() {
137 void SharedMemory::UnlockDeprecated() {
141 bool SharedMemory::ShareToProcessCommon(ProcessHandle process
,
142 SharedMemoryHandle
*new_handle
,
144 ShareMode share_mode
) {
145 if (share_mode
== SHARE_READONLY
) {
146 // Untrusted code can't create descriptors or handles, which is needed to
150 const int new_fd
= dup(mapped_file_
);
152 DPLOG(ERROR
) << "dup() failed.";
156 new_handle
->fd
= new_fd
;
157 new_handle
->auto_close
= true;