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(const SharedMemoryHandle
& handle
, bool read_only
)
28 : mapped_file_(handle
.fd
),
31 read_only_(read_only
),
35 SharedMemory::SharedMemory(const SharedMemoryHandle
& handle
,
37 ProcessHandle process
)
38 : mapped_file_(handle
.fd
),
41 read_only_(read_only
),
46 SharedMemory::~SharedMemory() {
52 bool SharedMemory::IsHandleValid(const SharedMemoryHandle
& handle
) {
53 return handle
.fd
>= 0;
57 SharedMemoryHandle
SharedMemory::NULLHandle() {
58 return SharedMemoryHandle();
62 void SharedMemory::CloseHandle(const SharedMemoryHandle
& handle
) {
63 DCHECK_GE(handle
.fd
, 0);
64 if (close(handle
.fd
) < 0)
65 DPLOG(ERROR
) << "close";
69 SharedMemoryHandle
SharedMemory::DuplicateHandle(
70 const SharedMemoryHandle
& handle
) {
71 int duped_handle
= HANDLE_EINTR(dup(handle
.fd
));
73 return base::SharedMemory::NULLHandle();
74 return base::FileDescriptor(duped_handle
, true);
77 bool SharedMemory::CreateAndMapAnonymous(size_t size
) {
78 // Untrusted code can't create descriptors or handles.
82 bool SharedMemory::Create(const SharedMemoryCreateOptions
& options
) {
83 // Untrusted code can't create descriptors or handles.
87 bool SharedMemory::Delete(const std::string
& name
) {
91 bool SharedMemory::Open(const std::string
& name
, bool read_only
) {
95 bool SharedMemory::MapAt(off_t offset
, size_t bytes
) {
96 if (mapped_file_
== -1)
99 if (bytes
> static_cast<size_t>(std::numeric_limits
<int>::max()))
105 memory_
= mmap(NULL
, bytes
, PROT_READ
| (read_only_
? 0 : PROT_WRITE
),
106 MAP_SHARED
, mapped_file_
, offset
);
108 bool mmap_succeeded
= memory_
!= MAP_FAILED
&& memory_
!= NULL
;
109 if (mmap_succeeded
) {
110 mapped_size_
= bytes
;
111 DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_
) &
112 (SharedMemory::MAP_MINIMUM_ALIGNMENT
- 1));
117 return mmap_succeeded
;
120 bool SharedMemory::Unmap() {
124 if (munmap(memory_
, mapped_size_
) < 0)
125 DPLOG(ERROR
) << "munmap";
131 SharedMemoryHandle
SharedMemory::handle() const {
132 return FileDescriptor(mapped_file_
, false);
135 void SharedMemory::Close() {
136 if (mapped_file_
> 0) {
137 if (close(mapped_file_
) < 0)
138 DPLOG(ERROR
) << "close";
143 bool SharedMemory::ShareToProcessCommon(ProcessHandle process
,
144 SharedMemoryHandle
*new_handle
,
146 ShareMode share_mode
) {
147 if (share_mode
== SHARE_READONLY
) {
148 // Untrusted code can't create descriptors or handles, which is needed to
152 const int new_fd
= dup(mapped_file_
);
154 DPLOG(ERROR
) << "dup() failed.";
158 new_handle
->fd
= new_fd
;
159 new_handle
->auto_close
= true;