Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / base / memory / shared_memory_win.cc
blob5f706fe648598642584903f39a5aa40786acc88d
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"
7 #include <aclapi.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"
15 namespace {
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)))
21 return 0;
22 return memory_info.RegionSize - (static_cast<char*>(address) -
23 static_cast<char*>(memory_info.AllocationBase));
26 } // namespace.
28 namespace base {
30 SharedMemory::SharedMemory()
31 : mapped_file_(NULL),
32 mapped_size_(0),
33 memory_(NULL),
34 read_only_(false),
35 requested_size_(0) {
38 SharedMemory::SharedMemory(const std::wstring& name)
39 : name_(name),
40 mapped_file_(NULL),
41 mapped_size_(0),
42 memory_(NULL),
43 read_only_(false),
44 requested_size_(0) {
47 SharedMemory::SharedMemory(const SharedMemoryHandle& handle, bool read_only)
48 : mapped_file_(handle),
49 mapped_size_(0),
50 memory_(NULL),
51 read_only_(read_only),
52 requested_size_(0) {
55 SharedMemory::SharedMemory(const SharedMemoryHandle& handle,
56 bool read_only,
57 ProcessHandle process)
58 : mapped_file_(NULL),
59 mapped_size_(0),
60 memory_(NULL),
61 read_only_(read_only),
62 requested_size_(0) {
63 ::DuplicateHandle(process, handle,
64 GetCurrentProcess(), &mapped_file_,
65 read_only_ ? FILE_MAP_READ : FILE_MAP_READ |
66 FILE_MAP_WRITE,
67 FALSE, 0);
70 SharedMemory::~SharedMemory() {
71 Unmap();
72 Close();
75 // static
76 bool SharedMemory::IsHandleValid(const SharedMemoryHandle& handle) {
77 return handle != NULL;
80 // static
81 SharedMemoryHandle SharedMemory::NULLHandle() {
82 return NULL;
85 // static
86 void SharedMemory::CloseHandle(const SharedMemoryHandle& handle) {
87 DCHECK(handle != NULL);
88 ::CloseHandle(handle);
91 // static
92 size_t SharedMemory::GetHandleLimit() {
93 // Rounded down from value reported here:
94 // http://blogs.technet.com/b/markrussinovich/archive/2009/09/29/3283844.aspx
95 return static_cast<size_t>(1 << 23);
98 // static
99 SharedMemoryHandle SharedMemory::DuplicateHandle(
100 const SharedMemoryHandle& handle) {
101 ProcessHandle process = GetCurrentProcess();
102 SharedMemoryHandle duped_handle;
103 BOOL success = ::DuplicateHandle(process, handle, process, &duped_handle, 0,
104 FALSE, DUPLICATE_SAME_ACCESS);
105 if (success)
106 return duped_handle;
107 return NULLHandle();
110 bool SharedMemory::CreateAndMapAnonymous(size_t size) {
111 return CreateAnonymous(size) && Map(size);
114 bool SharedMemory::Create(const SharedMemoryCreateOptions& options) {
115 // TODO(bsy,sehr): crbug.com/210609 NaCl forces us to round up 64k here,
116 // wasting 32k per mapping on average.
117 static const size_t kSectionMask = 65536 - 1;
118 DCHECK(!options.executable);
119 DCHECK(!mapped_file_);
120 if (options.size == 0)
121 return false;
123 // Check maximum accounting for overflow.
124 if (options.size >
125 static_cast<size_t>(std::numeric_limits<int>::max()) - kSectionMask)
126 return false;
128 size_t rounded_size = (options.size + kSectionMask) & ~kSectionMask;
129 name_ = options.name_deprecated ?
130 ASCIIToUTF16(*options.name_deprecated) : L"";
131 SECURITY_ATTRIBUTES sa = { sizeof(sa), NULL, FALSE };
132 SECURITY_DESCRIPTOR sd;
133 ACL dacl;
135 if (options.share_read_only && name_.empty()) {
136 // Add an empty DACL to enforce anonymous read-only sections.
137 sa.lpSecurityDescriptor = &sd;
138 if (!InitializeAcl(&dacl, sizeof(dacl), ACL_REVISION))
139 return false;
140 if (!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION))
141 return false;
142 if (!SetSecurityDescriptorDacl(&sd, TRUE, &dacl, FALSE))
143 return false;
145 // Windows ignores DACLs on certain unnamed objects (like shared sections).
146 // So, we generate a random name when we need to enforce read-only.
147 uint64_t rand_values[4];
148 RandBytes(&rand_values, sizeof(rand_values));
149 name_ = StringPrintf(L"CrSharedMem_%016x%016x%016x%016x",
150 rand_values[0], rand_values[1],
151 rand_values[2], rand_values[3]);
153 mapped_file_ = CreateFileMapping(INVALID_HANDLE_VALUE, &sa,
154 PAGE_READWRITE, 0, static_cast<DWORD>(rounded_size),
155 name_.empty() ? nullptr : name_.c_str());
156 if (!mapped_file_)
157 return false;
159 requested_size_ = options.size;
161 // Check if the shared memory pre-exists.
162 if (GetLastError() == ERROR_ALREADY_EXISTS) {
163 // If the file already existed, set requested_size_ to 0 to show that
164 // we don't know the size.
165 requested_size_ = 0;
166 if (!options.open_existing_deprecated) {
167 Close();
168 return false;
172 return true;
175 bool SharedMemory::Delete(const std::string& name) {
176 // intentionally empty -- there is nothing for us to do on Windows.
177 return true;
180 bool SharedMemory::Open(const std::string& name, bool read_only) {
181 DCHECK(!mapped_file_);
183 name_ = ASCIIToUTF16(name);
184 read_only_ = read_only;
185 mapped_file_ = OpenFileMapping(
186 read_only_ ? FILE_MAP_READ : FILE_MAP_READ | FILE_MAP_WRITE,
187 false, name_.empty() ? NULL : name_.c_str());
188 if (mapped_file_ != NULL) {
189 // Note: size_ is not set in this case.
190 return true;
192 return false;
195 bool SharedMemory::MapAt(off_t offset, size_t bytes) {
196 if (mapped_file_ == NULL)
197 return false;
199 if (bytes > static_cast<size_t>(std::numeric_limits<int>::max()))
200 return false;
202 if (memory_)
203 return false;
205 memory_ = MapViewOfFile(mapped_file_,
206 read_only_ ? FILE_MAP_READ : FILE_MAP_READ |
207 FILE_MAP_WRITE,
208 static_cast<uint64>(offset) >> 32,
209 static_cast<DWORD>(offset),
210 bytes);
211 if (memory_ != NULL) {
212 DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_) &
213 (SharedMemory::MAP_MINIMUM_ALIGNMENT - 1));
214 mapped_size_ = GetMemorySectionSize(memory_);
215 return true;
217 return false;
220 bool SharedMemory::Unmap() {
221 if (memory_ == NULL)
222 return false;
224 UnmapViewOfFile(memory_);
225 memory_ = NULL;
226 return true;
229 bool SharedMemory::ShareToProcessCommon(ProcessHandle process,
230 SharedMemoryHandle* new_handle,
231 bool close_self,
232 ShareMode share_mode) {
233 *new_handle = 0;
234 DWORD access = FILE_MAP_READ;
235 DWORD options = 0;
236 HANDLE mapped_file = mapped_file_;
237 HANDLE result;
238 if (share_mode == SHARE_CURRENT_MODE && !read_only_)
239 access |= FILE_MAP_WRITE;
240 if (close_self) {
241 // DUPLICATE_CLOSE_SOURCE causes DuplicateHandle to close mapped_file.
242 options = DUPLICATE_CLOSE_SOURCE;
243 mapped_file_ = NULL;
244 Unmap();
247 if (process == GetCurrentProcess() && close_self) {
248 *new_handle = mapped_file;
249 return true;
252 if (!::DuplicateHandle(GetCurrentProcess(), mapped_file, process, &result,
253 access, FALSE, options)) {
254 return false;
256 *new_handle = result;
257 return true;
261 void SharedMemory::Close() {
262 if (mapped_file_ != NULL) {
263 CloseHandle(mapped_file_);
264 mapped_file_ = NULL;
268 SharedMemoryHandle SharedMemory::handle() const {
269 return mapped_file_;
272 } // namespace base