1 // Copyright (c) 2011 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"
9 #include "base/logging.h"
10 #include "base/memory/scoped_ptr.h"
11 #include "base/rand_util.h"
12 #include "base/strings/stringprintf.h"
13 #include "base/strings/utf_string_conversions.h"
17 // Returns the length of the memory section starting at the supplied address.
18 size_t GetMemorySectionSize(void* address
) {
19 MEMORY_BASIC_INFORMATION memory_info
;
20 if (!::VirtualQuery(address
, &memory_info
, sizeof(memory_info
)))
22 return memory_info
.RegionSize
- (static_cast<char*>(address
) -
23 static_cast<char*>(memory_info
.AllocationBase
));
30 SharedMemory::SharedMemory()
39 SharedMemory::SharedMemory(const std::wstring
& name
)
49 SharedMemory::SharedMemory(SharedMemoryHandle handle
, bool read_only
)
50 : mapped_file_(handle
),
52 read_only_(read_only
),
58 SharedMemory::SharedMemory(SharedMemoryHandle handle
, bool read_only
,
59 ProcessHandle process
)
62 read_only_(read_only
),
66 ::DuplicateHandle(process
, handle
,
67 GetCurrentProcess(), &mapped_file_
,
68 read_only_
? FILE_MAP_READ
: FILE_MAP_READ
|
73 SharedMemory::~SharedMemory() {
81 bool SharedMemory::IsHandleValid(const SharedMemoryHandle
& handle
) {
82 return handle
!= NULL
;
86 SharedMemoryHandle
SharedMemory::NULLHandle() {
91 void SharedMemory::CloseHandle(const SharedMemoryHandle
& handle
) {
92 DCHECK(handle
!= NULL
);
93 ::CloseHandle(handle
);
97 size_t SharedMemory::GetHandleLimit() {
98 // Rounded down from value reported here:
99 // http://blogs.technet.com/b/markrussinovich/archive/2009/09/29/3283844.aspx
100 return static_cast<size_t>(1 << 23);
103 bool SharedMemory::CreateAndMapAnonymous(size_t size
) {
104 return CreateAnonymous(size
) && Map(size
);
107 bool SharedMemory::Create(const SharedMemoryCreateOptions
& options
) {
108 // TODO(bsy,sehr): crbug.com/210609 NaCl forces us to round up 64k here,
109 // wasting 32k per mapping on average.
110 static const size_t kSectionMask
= 65536 - 1;
111 DCHECK(!options
.executable
);
112 DCHECK(!mapped_file_
);
113 if (options
.size
== 0)
116 // Check maximum accounting for overflow.
118 static_cast<size_t>(std::numeric_limits
<int>::max()) - kSectionMask
)
121 size_t rounded_size
= (options
.size
+ kSectionMask
) & ~kSectionMask
;
122 name_
= options
.name_deprecated
?
123 ASCIIToUTF16(*options
.name_deprecated
) : L
"";
124 SECURITY_ATTRIBUTES sa
= { sizeof(sa
), NULL
, FALSE
};
125 SECURITY_DESCRIPTOR sd
;
128 if (options
.share_read_only
&& name_
.empty()) {
129 // Add an empty DACL to enforce anonymous read-only sections.
130 sa
.lpSecurityDescriptor
= &sd
;
131 if (!InitializeAcl(&dacl
, sizeof(dacl
), ACL_REVISION
))
133 if (!InitializeSecurityDescriptor(&sd
, SECURITY_DESCRIPTOR_REVISION
))
135 if (!SetSecurityDescriptorDacl(&sd
, TRUE
, &dacl
, FALSE
))
138 // Windows ignores DACLs on certain unnamed objects (like shared sections).
139 // So, we generate a random name when we need to enforce read-only.
140 uint64_t rand_values
[4];
141 RandBytes(&rand_values
, sizeof(rand_values
));
142 name_
= StringPrintf(L
"CrSharedMem_%016x%016x%016x%016x",
143 rand_values
[0], rand_values
[1],
144 rand_values
[2], rand_values
[3]);
146 mapped_file_
= CreateFileMapping(INVALID_HANDLE_VALUE
, &sa
,
147 PAGE_READWRITE
, 0, static_cast<DWORD
>(rounded_size
), name_
.c_str());
151 requested_size_
= options
.size
;
153 // Check if the shared memory pre-exists.
154 if (GetLastError() == ERROR_ALREADY_EXISTS
) {
155 // If the file already existed, set requested_size_ to 0 to show that
156 // we don't know the size.
158 if (!options
.open_existing_deprecated
) {
167 bool SharedMemory::Delete(const std::string
& name
) {
168 // intentionally empty -- there is nothing for us to do on Windows.
172 bool SharedMemory::Open(const std::string
& name
, bool read_only
) {
173 DCHECK(!mapped_file_
);
175 name_
= ASCIIToUTF16(name
);
176 read_only_
= read_only
;
177 mapped_file_
= OpenFileMapping(
178 read_only_
? FILE_MAP_READ
: FILE_MAP_READ
| FILE_MAP_WRITE
,
179 false, name_
.empty() ? NULL
: name_
.c_str());
180 if (mapped_file_
!= NULL
) {
181 // Note: size_ is not set in this case.
187 bool SharedMemory::MapAt(off_t offset
, size_t bytes
) {
188 if (mapped_file_
== NULL
)
191 if (bytes
> static_cast<size_t>(std::numeric_limits
<int>::max()))
197 memory_
= MapViewOfFile(mapped_file_
,
198 read_only_
? FILE_MAP_READ
: FILE_MAP_READ
|
200 static_cast<uint64
>(offset
) >> 32,
201 static_cast<DWORD
>(offset
),
203 if (memory_
!= NULL
) {
204 DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_
) &
205 (SharedMemory::MAP_MINIMUM_ALIGNMENT
- 1));
206 mapped_size_
= GetMemorySectionSize(memory_
);
212 bool SharedMemory::Unmap() {
216 UnmapViewOfFile(memory_
);
221 bool SharedMemory::ShareToProcessCommon(ProcessHandle process
,
222 SharedMemoryHandle
* new_handle
,
224 ShareMode share_mode
) {
226 DWORD access
= FILE_MAP_READ
;
228 HANDLE mapped_file
= mapped_file_
;
230 if (share_mode
== SHARE_CURRENT_MODE
&& !read_only_
)
231 access
|= FILE_MAP_WRITE
;
233 // DUPLICATE_CLOSE_SOURCE causes DuplicateHandle to close mapped_file.
234 options
= DUPLICATE_CLOSE_SOURCE
;
239 if (process
== GetCurrentProcess() && close_self
) {
240 *new_handle
= mapped_file
;
244 if (!DuplicateHandle(GetCurrentProcess(), mapped_file
, process
,
245 &result
, access
, FALSE
, options
))
247 *new_handle
= result
;
252 void SharedMemory::Close() {
253 if (mapped_file_
!= NULL
) {
254 CloseHandle(mapped_file_
);
259 void SharedMemory::LockDeprecated() {
261 std::wstring name
= name_
;
262 name
.append(L
"lock");
263 lock_
= CreateMutex(NULL
, FALSE
, name
.c_str());
265 DPLOG(ERROR
) << "Could not create mutex.";
267 return; // There is nothing good we can do here.
270 DWORD result
= WaitForSingleObject(lock_
, INFINITE
);
271 DCHECK_EQ(result
, WAIT_OBJECT_0
);
274 void SharedMemory::UnlockDeprecated() {
275 DCHECK(lock_
!= NULL
);
279 SharedMemoryHandle
SharedMemory::handle() const {