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/shared_memory.h"
13 #include "base/logging.h"
17 SharedMemory::SharedMemory()
26 SharedMemory::SharedMemory(SharedMemoryHandle handle
, bool read_only
)
27 : 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
),
41 read_only_(read_only
),
46 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";
67 bool SharedMemory::CreateAndMapAnonymous(uint32 size
) {
68 // Untrusted code can't create descriptors or handles.
72 bool SharedMemory::Create(const SharedMemoryCreateOptions
& options
) {
73 // Untrusted code can't create descriptors or handles.
77 bool SharedMemory::Delete(const std::string
& name
) {
81 bool SharedMemory::Open(const std::string
& name
, bool read_only
) {
85 bool SharedMemory::Map(uint32 bytes
) {
86 if (mapped_file_
== -1)
89 memory_
= mmap(NULL
, bytes
, PROT_READ
| (read_only_
? 0 : PROT_WRITE
),
90 MAP_SHARED
, mapped_file_
, 0);
92 bool mmap_succeeded
= memory_
!= MAP_FAILED
&& memory_
!= NULL
;
95 DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_
) &
96 (SharedMemory::MAP_MINIMUM_ALIGNMENT
- 1));
101 return mmap_succeeded
;
104 bool SharedMemory::Unmap() {
108 if (munmap(memory_
, mapped_size_
) < 0)
109 DPLOG(ERROR
) << "munmap";
115 SharedMemoryHandle
SharedMemory::handle() const {
116 return FileDescriptor(mapped_file_
, false);
119 void SharedMemory::Close() {
122 if (mapped_file_
> 0) {
123 if (close(mapped_file_
) < 0)
124 DPLOG(ERROR
) << "close";
129 void SharedMemory::Lock() {
133 void SharedMemory::Unlock() {
137 bool SharedMemory::ShareToProcessCommon(ProcessHandle process
,
138 SharedMemoryHandle
*new_handle
,