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()
27 SharedMemory::SharedMemory(SharedMemoryHandle handle
, bool read_only
)
28 : mapped_file_(handle
.fd
),
31 read_only_(read_only
),
35 SharedMemory::SharedMemory(SharedMemoryHandle handle
, bool read_only
,
36 ProcessHandle process
)
37 : mapped_file_(handle
.fd
),
40 read_only_(read_only
),
45 SharedMemory::~SharedMemory() {
51 bool SharedMemory::IsHandleValid(const SharedMemoryHandle
& handle
) {
52 return handle
.fd
>= 0;
56 SharedMemoryHandle
SharedMemory::NULLHandle() {
57 return SharedMemoryHandle();
61 void SharedMemory::CloseHandle(const SharedMemoryHandle
& handle
) {
62 DCHECK_GE(handle
.fd
, 0);
63 if (close(handle
.fd
) < 0)
64 DPLOG(ERROR
) << "close";
68 SharedMemoryHandle
SharedMemory::DuplicateHandle(
69 const SharedMemoryHandle
& handle
) {
70 int duped_handle
= HANDLE_EINTR(dup(handle
.fd
));
72 return base::SharedMemory::NULLHandle();
73 return base::FileDescriptor(duped_handle
, true);
76 bool SharedMemory::CreateAndMapAnonymous(size_t size
) {
77 // Untrusted code can't create descriptors or handles.
81 bool SharedMemory::Create(const SharedMemoryCreateOptions
& options
) {
82 // Untrusted code can't create descriptors or handles.
86 bool SharedMemory::Delete(const std::string
& name
) {
90 bool SharedMemory::Open(const std::string
& name
, bool read_only
) {
94 bool SharedMemory::MapAt(off_t offset
, size_t bytes
) {
95 if (mapped_file_
== -1)
98 if (bytes
> static_cast<size_t>(std::numeric_limits
<int>::max()))
104 memory_
= mmap(NULL
, bytes
, PROT_READ
| (read_only_
? 0 : PROT_WRITE
),
105 MAP_SHARED
, mapped_file_
, offset
);
107 bool mmap_succeeded
= memory_
!= MAP_FAILED
&& memory_
!= NULL
;
108 if (mmap_succeeded
) {
109 mapped_size_
= bytes
;
110 DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_
) &
111 (SharedMemory::MAP_MINIMUM_ALIGNMENT
- 1));
116 return mmap_succeeded
;
119 bool SharedMemory::Unmap() {
123 if (munmap(memory_
, mapped_size_
) < 0)
124 DPLOG(ERROR
) << "munmap";
130 SharedMemoryHandle
SharedMemory::handle() const {
131 return FileDescriptor(mapped_file_
, false);
134 void SharedMemory::Close() {
135 if (mapped_file_
> 0) {
136 if (close(mapped_file_
) < 0)
137 DPLOG(ERROR
) << "close";
142 void SharedMemory::LockDeprecated() {
146 void SharedMemory::UnlockDeprecated() {
150 bool SharedMemory::ShareToProcessCommon(ProcessHandle process
,
151 SharedMemoryHandle
*new_handle
,
153 ShareMode share_mode
) {
154 if (share_mode
== SHARE_READONLY
) {
155 // Untrusted code can't create descriptors or handles, which is needed to
159 const int new_fd
= dup(mapped_file_
);
161 DPLOG(ERROR
) << "dup() failed.";
165 new_handle
->fd
= new_fd
;
166 new_handle
->auto_close
= true;