blob: 3839f447abb3f98f4b6347ee32ba35f601d29604 [file] [log] [blame]
[email protected]b05df6b2011-12-01 23:19:311// Copyright (c) 2011 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commitd7cae122008-07-26 21:49:384
[email protected]99873aa2013-03-29 17:46:235#include "base/memory/shared_memory.h"
initial.commitd7cae122008-07-26 21:49:386
[email protected]6d6797eb2014-08-07 22:07:437#include <aclapi.h>
avi9beac252015-12-24 08:44:478#include <stddef.h>
9#include <stdint.h>
[email protected]6d6797eb2014-08-07 22:07:4310
initial.commitd7cae122008-07-26 21:49:3811#include "base/logging.h"
erikchen1d7cb7e2016-05-20 23:34:0412#include "base/metrics/histogram_macros.h"
[email protected]dc84fcc2014-07-24 11:42:5913#include "base/rand_util.h"
14#include "base/strings/stringprintf.h"
[email protected]a4ea1f12013-06-07 18:37:0715#include "base/strings/utf_string_conversions.h"
erikchen14525202017-05-06 19:16:5116#include "base/unguessable_token.h"
initial.commitd7cae122008-07-26 21:49:3817
[email protected]67ea5072013-03-28 02:02:1818namespace {
19
erikchen1d7cb7e2016-05-20 23:34:0420// Errors that can occur during Shared Memory construction.
21// These match tools/metrics/histograms/histograms.xml.
22// This enum is append-only.
23enum CreateError {
24 SUCCESS = 0,
25 SIZE_ZERO = 1,
26 SIZE_TOO_LARGE = 2,
27 INITIALIZE_ACL_FAILURE = 3,
28 INITIALIZE_SECURITY_DESC_FAILURE = 4,
29 SET_SECURITY_DESC_FAILURE = 5,
30 CREATE_FILE_MAPPING_FAILURE = 6,
31 REDUCE_PERMISSIONS_FAILURE = 7,
32 ALREADY_EXISTS = 8,
33 CREATE_ERROR_LAST = ALREADY_EXISTS
34};
35
bcwhite8ea07912016-11-09 23:38:2636// Emits UMA metrics about encountered errors. Pass zero (0) for |winerror|
37// if there is no associated Windows error.
38void LogError(CreateError error, DWORD winerror) {
erikchen1d7cb7e2016-05-20 23:34:0439 UMA_HISTOGRAM_ENUMERATION("SharedMemory.CreateError", error,
40 CREATE_ERROR_LAST + 1);
bcwhite8ea07912016-11-09 23:38:2641 static_assert(ERROR_SUCCESS == 0, "Windows error code changed!");
42 if (winerror != ERROR_SUCCESS)
43 UMA_HISTOGRAM_SPARSE_SLOWLY("SharedMemory.CreateWinError", winerror);
erikchen1d7cb7e2016-05-20 23:34:0444}
45
forshaw0474abe2015-12-18 02:16:5946typedef enum _SECTION_INFORMATION_CLASS {
47 SectionBasicInformation,
48} SECTION_INFORMATION_CLASS;
49
50typedef struct _SECTION_BASIC_INFORMATION {
51 PVOID BaseAddress;
52 ULONG Attributes;
53 LARGE_INTEGER Size;
54} SECTION_BASIC_INFORMATION, *PSECTION_BASIC_INFORMATION;
55
56typedef ULONG(__stdcall* NtQuerySectionType)(
57 HANDLE SectionHandle,
58 SECTION_INFORMATION_CLASS SectionInformationClass,
59 PVOID SectionInformation,
60 ULONG SectionInformationLength,
61 PULONG ResultLength);
62
[email protected]67ea5072013-03-28 02:02:1863// Returns the length of the memory section starting at the supplied address.
64size_t GetMemorySectionSize(void* address) {
65 MEMORY_BASIC_INFORMATION memory_info;
66 if (!::VirtualQuery(address, &memory_info, sizeof(memory_info)))
67 return 0;
68 return memory_info.RegionSize - (static_cast<char*>(address) -
69 static_cast<char*>(memory_info.AllocationBase));
70}
71
forshaw0474abe2015-12-18 02:16:5972// Checks if the section object is safe to map. At the moment this just means
73// it's not an image section.
74bool IsSectionSafeToMap(HANDLE handle) {
75 static NtQuerySectionType nt_query_section_func;
76 if (!nt_query_section_func) {
77 nt_query_section_func = reinterpret_cast<NtQuerySectionType>(
78 ::GetProcAddress(::GetModuleHandle(L"ntdll.dll"), "NtQuerySection"));
79 DCHECK(nt_query_section_func);
80 }
81
82 // The handle must have SECTION_QUERY access for this to succeed.
83 SECTION_BASIC_INFORMATION basic_information = {};
84 ULONG status =
85 nt_query_section_func(handle, SectionBasicInformation, &basic_information,
86 sizeof(basic_information), nullptr);
87 if (status)
88 return false;
89 return (basic_information.Attributes & SEC_IMAGE) != SEC_IMAGE;
90}
91
erikchen4b12c0a2016-02-19 03:15:4392// Returns a HANDLE on success and |nullptr| on failure.
93// This function is similar to CreateFileMapping, but removes the permissions
94// WRITE_DAC, WRITE_OWNER, READ_CONTROL, and DELETE.
95//
96// A newly created file mapping has two sets of permissions. It has access
97// control permissions (WRITE_DAC, WRITE_OWNER, READ_CONTROL, and DELETE) and
98// file permissions (FILE_MAP_READ, FILE_MAP_WRITE, etc.). ::DuplicateHandle()
99// with the parameter DUPLICATE_SAME_ACCESS copies both sets of permissions.
100//
101// The Chrome sandbox prevents HANDLEs with the WRITE_DAC permission from being
102// duplicated into unprivileged processes. But the only way to copy file
103// permissions is with the parameter DUPLICATE_SAME_ACCESS. This means that
104// there is no way for a privileged process to duplicate a file mapping into an
105// unprivileged process while maintaining the previous file permissions.
106//
107// By removing all access control permissions of a file mapping immediately
108// after creation, ::DuplicateHandle() effectively only copies the file
109// permissions.
110HANDLE CreateFileMappingWithReducedPermissions(SECURITY_ATTRIBUTES* sa,
111 size_t rounded_size,
112 LPCWSTR name) {
113 HANDLE h = CreateFileMapping(INVALID_HANDLE_VALUE, sa, PAGE_READWRITE, 0,
114 static_cast<DWORD>(rounded_size), name);
erikchen1d7cb7e2016-05-20 23:34:04115 if (!h) {
bcwhite8ea07912016-11-09 23:38:26116 LogError(CREATE_FILE_MAPPING_FAILURE, GetLastError());
erikchen4b12c0a2016-02-19 03:15:43117 return nullptr;
erikchen1d7cb7e2016-05-20 23:34:04118 }
erikchen4b12c0a2016-02-19 03:15:43119
120 HANDLE h2;
121 BOOL success = ::DuplicateHandle(
122 GetCurrentProcess(), h, GetCurrentProcess(), &h2,
123 FILE_MAP_READ | FILE_MAP_WRITE | SECTION_QUERY, FALSE, 0);
124 BOOL rv = ::CloseHandle(h);
125 DCHECK(rv);
erikchen1d7cb7e2016-05-20 23:34:04126
127 if (!success) {
bcwhite8ea07912016-11-09 23:38:26128 LogError(REDUCE_PERMISSIONS_FAILURE, GetLastError());
erikchen1d7cb7e2016-05-20 23:34:04129 return nullptr;
130 }
131
132 return h2;
erikchen4b12c0a2016-02-19 03:15:43133}
134
[email protected]67ea5072013-03-28 02:02:18135} // namespace.
136
[email protected]176aa482008-11-14 03:25:15137namespace base {
138
asvitkine182427f2017-05-10 20:06:18139SharedMemory::SharedMemory() {}
forshaw0474abe2015-12-18 02:16:59140
asvitkine182427f2017-05-10 20:06:18141SharedMemory::SharedMemory(const string16& name) : name_(name) {}
[email protected]8cc41942010-11-05 19:16:07142
scottmgd19b4f72015-06-19 22:51:00143SharedMemory::SharedMemory(const SharedMemoryHandle& handle, bool read_only)
asvitkine182427f2017-05-10 20:06:18144 : external_section_(true), shm_(handle), read_only_(read_only) {}
initial.commitd7cae122008-07-26 21:49:38145
initial.commitd7cae122008-07-26 21:49:38146SharedMemory::~SharedMemory() {
jbauman569918b2014-12-10 22:07:20147 Unmap();
initial.commitd7cae122008-07-26 21:49:38148 Close();
initial.commitd7cae122008-07-26 21:49:38149}
150
[email protected]5fe733de2009-02-11 18:59:20151// static
152bool SharedMemory::IsHandleValid(const SharedMemoryHandle& handle) {
erikchen5ea2ab72015-09-25 22:34:31153 return handle.IsValid();
[email protected]5fe733de2009-02-11 18:59:20154}
155
[email protected]76aac1e2009-03-16 16:45:36156// static
[email protected]b0af04c2009-05-18 17:46:31157void SharedMemory::CloseHandle(const SharedMemoryHandle& handle) {
erikchen5ea2ab72015-09-25 22:34:31158 handle.Close();
[email protected]b0af04c2009-05-18 17:46:31159}
160
[email protected]c14eda92013-05-09 23:15:40161// static
162size_t SharedMemory::GetHandleLimit() {
163 // Rounded down from value reported here:
164 // http://blogs.technet.com/b/markrussinovich/archive/2009/09/29/3283844.aspx
165 return static_cast<size_t>(1 << 23);
166}
167
erikchen2096f622015-06-03 00:26:59168// static
169SharedMemoryHandle SharedMemory::DuplicateHandle(
erikchen8539d852015-05-30 01:49:19170 const SharedMemoryHandle& handle) {
erikchen63840882017-05-02 20:52:31171 return handle.Duplicate();
erikchen8539d852015-05-30 01:49:19172}
173
[email protected]374f1a82013-01-10 02:16:24174bool SharedMemory::CreateAndMapAnonymous(size_t size) {
[email protected]54e3dfa22010-10-27 18:16:06175 return CreateAnonymous(size) && Map(size);
176}
177
[email protected]b05df6b2011-12-01 23:19:31178bool SharedMemory::Create(const SharedMemoryCreateOptions& options) {
[email protected]67ea5072013-03-28 02:02:18179 // TODO(bsy,sehr): crbug.com/210609 NaCl forces us to round up 64k here,
180 // wasting 32k per mapping on average.
181 static const size_t kSectionMask = 65536 - 1;
[email protected]b05df6b2011-12-01 23:19:31182 DCHECK(!options.executable);
erikchen3df1dd52017-05-03 22:53:40183 DCHECK(!shm_.IsValid());
erikchen1d7cb7e2016-05-20 23:34:04184 if (options.size == 0) {
bcwhite8ea07912016-11-09 23:38:26185 LogError(SIZE_ZERO, 0);
[email protected]54e3dfa22010-10-27 18:16:06186 return false;
erikchen1d7cb7e2016-05-20 23:34:04187 }
initial.commitd7cae122008-07-26 21:49:38188
[email protected]67ea5072013-03-28 02:02:18189 // Check maximum accounting for overflow.
190 if (options.size >
erikchen1d7cb7e2016-05-20 23:34:04191 static_cast<size_t>(std::numeric_limits<int>::max()) - kSectionMask) {
bcwhite8ea07912016-11-09 23:38:26192 LogError(SIZE_TOO_LARGE, 0);
[email protected]374f1a82013-01-10 02:16:24193 return false;
erikchen1d7cb7e2016-05-20 23:34:04194 }
[email protected]374f1a82013-01-10 02:16:24195
[email protected]67ea5072013-03-28 02:02:18196 size_t rounded_size = (options.size + kSectionMask) & ~kSectionMask;
thestig8badc792014-12-04 22:14:22197 name_ = options.name_deprecated ?
198 ASCIIToUTF16(*options.name_deprecated) : L"";
[email protected]6d6797eb2014-08-07 22:07:43199 SECURITY_ATTRIBUTES sa = { sizeof(sa), NULL, FALSE };
200 SECURITY_DESCRIPTOR sd;
201 ACL dacl;
202
erikchenb5856b12016-05-24 17:21:59203 if (name_.empty()) {
[email protected]6d6797eb2014-08-07 22:07:43204 // Add an empty DACL to enforce anonymous read-only sections.
205 sa.lpSecurityDescriptor = &sd;
erikchen1d7cb7e2016-05-20 23:34:04206 if (!InitializeAcl(&dacl, sizeof(dacl), ACL_REVISION)) {
bcwhite8ea07912016-11-09 23:38:26207 LogError(INITIALIZE_ACL_FAILURE, GetLastError());
[email protected]6d6797eb2014-08-07 22:07:43208 return false;
erikchen1d7cb7e2016-05-20 23:34:04209 }
210 if (!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) {
bcwhite8ea07912016-11-09 23:38:26211 LogError(INITIALIZE_SECURITY_DESC_FAILURE, GetLastError());
[email protected]6d6797eb2014-08-07 22:07:43212 return false;
erikchen1d7cb7e2016-05-20 23:34:04213 }
214 if (!SetSecurityDescriptorDacl(&sd, TRUE, &dacl, FALSE)) {
bcwhite8ea07912016-11-09 23:38:26215 LogError(SET_SECURITY_DESC_FAILURE, GetLastError());
[email protected]6d6797eb2014-08-07 22:07:43216 return false;
erikchen1d7cb7e2016-05-20 23:34:04217 }
[email protected]6d6797eb2014-08-07 22:07:43218
[email protected]dc84fcc2014-07-24 11:42:59219 // Windows ignores DACLs on certain unnamed objects (like shared sections).
220 // So, we generate a random name when we need to enforce read-only.
221 uint64_t rand_values[4];
thestig8badc792014-12-04 22:14:22222 RandBytes(&rand_values, sizeof(rand_values));
brucedawson5604a11d2015-10-06 19:22:00223 name_ = StringPrintf(L"CrSharedMem_%016llx%016llx%016llx%016llx",
thestig8badc792014-12-04 22:14:22224 rand_values[0], rand_values[1],
225 rand_values[2], rand_values[3]);
[email protected]dc84fcc2014-07-24 11:42:59226 }
hajimehoshidf47edd2017-03-02 16:48:12227 DCHECK(!name_.empty());
erikchen14525202017-05-06 19:16:51228 shm_ = SharedMemoryHandle(
229 CreateFileMappingWithReducedPermissions(&sa, rounded_size, name_.c_str()),
erikchen9d6afd712017-05-18 17:49:06230 rounded_size, UnguessableToken::Create());
erikchen3df1dd52017-05-03 22:53:40231 if (!shm_.IsValid()) {
erikchen1d7cb7e2016-05-20 23:34:04232 // The error is logged within CreateFileMappingWithReducedPermissions().
initial.commitd7cae122008-07-26 21:49:38233 return false;
erikchen1d7cb7e2016-05-20 23:34:04234 }
initial.commitd7cae122008-07-26 21:49:38235
[email protected]67ea5072013-03-28 02:02:18236 requested_size_ = options.size;
[email protected]54e3dfa22010-10-27 18:16:06237
initial.commitd7cae122008-07-26 21:49:38238 // Check if the shared memory pre-exists.
[email protected]54e3dfa22010-10-27 18:16:06239 if (GetLastError() == ERROR_ALREADY_EXISTS) {
[email protected]67ea5072013-03-28 02:02:18240 // If the file already existed, set requested_size_ to 0 to show that
[email protected]54e3dfa22010-10-27 18:16:06241 // we don't know the size.
[email protected]67ea5072013-03-28 02:02:18242 requested_size_ = 0;
forshaw0474abe2015-12-18 02:16:59243 external_section_ = true;
[email protected]ff672b72014-03-05 21:13:52244 if (!options.open_existing_deprecated) {
[email protected]54e3dfa22010-10-27 18:16:06245 Close();
bcwhite8ea07912016-11-09 23:38:26246 // From "if" above: GetLastError() == ERROR_ALREADY_EXISTS.
247 LogError(ALREADY_EXISTS, ERROR_ALREADY_EXISTS);
[email protected]54e3dfa22010-10-27 18:16:06248 return false;
249 }
initial.commitd7cae122008-07-26 21:49:38250 }
[email protected]54e3dfa22010-10-27 18:16:06251
bcwhite8ea07912016-11-09 23:38:26252 LogError(SUCCESS, ERROR_SUCCESS);
initial.commitd7cae122008-07-26 21:49:38253 return true;
254}
255
[email protected]b6413b49b2010-09-29 20:32:22256bool SharedMemory::Delete(const std::string& name) {
[email protected]9e51af92009-02-04 00:58:39257 // intentionally empty -- there is nothing for us to do on Windows.
258 return true;
259}
260
[email protected]b6413b49b2010-09-29 20:32:22261bool SharedMemory::Open(const std::string& name, bool read_only) {
erikchen3df1dd52017-05-03 22:53:40262 DCHECK(!shm_.IsValid());
forshaw0474abe2015-12-18 02:16:59263 DWORD access = FILE_MAP_READ | SECTION_QUERY;
264 if (!read_only)
265 access |= FILE_MAP_WRITE;
thestig8badc792014-12-04 22:14:22266 name_ = ASCIIToUTF16(name);
initial.commitd7cae122008-07-26 21:49:38267 read_only_ = read_only;
erikchen14525202017-05-06 19:16:51268
269 // This form of sharing shared memory is deprecated. https://crbug.com/345734.
270 // However, we can't get rid of it without a significant refactor because its
271 // used to communicate between two versions of the same service process, very
272 // early in the life cycle.
273 // Technically, we should also pass the GUID from the original shared memory
274 // region. We don't do that - this means that we will overcount this memory,
275 // which thankfully isn't relevant since Chrome only communicates with a
276 // single version of the service process.
erikchen9d6afd712017-05-18 17:49:06277 // We pass the size |0|, which is a dummy size and wrong, but otherwise
278 // harmless.
erikchen3df1dd52017-05-03 22:53:40279 shm_ = SharedMemoryHandle(
erikchen14525202017-05-06 19:16:51280 OpenFileMapping(access, false, name_.empty() ? nullptr : name_.c_str()),
erikchen9d6afd712017-05-18 17:49:06281 0u, UnguessableToken::Create());
erikchen3df1dd52017-05-03 22:53:40282 if (!shm_.IsValid())
forshaw0474abe2015-12-18 02:16:59283 return false;
284 // If a name specified assume it's an external section.
285 if (!name_.empty())
286 external_section_ = true;
287 // Note: size_ is not set in this case.
288 return true;
initial.commitd7cae122008-07-26 21:49:38289}
290
[email protected]e29e3f552013-01-16 09:02:34291bool SharedMemory::MapAt(off_t offset, size_t bytes) {
erikchen3df1dd52017-05-03 22:53:40292 if (!shm_.IsValid())
initial.commitd7cae122008-07-26 21:49:38293 return false;
294
[email protected]374f1a82013-01-10 02:16:24295 if (bytes > static_cast<size_t>(std::numeric_limits<int>::max()))
296 return false;
297
[email protected]421c1502014-03-18 22:33:28298 if (memory_)
299 return false;
300
erikchen3df1dd52017-05-03 22:53:40301 if (external_section_ && !IsSectionSafeToMap(shm_.GetHandle()))
forshaw0474abe2015-12-18 02:16:59302 return false;
303
avi9beac252015-12-24 08:44:47304 memory_ = MapViewOfFile(
erikchen3df1dd52017-05-03 22:53:40305 shm_.GetHandle(),
stanisc2660facb2016-06-30 03:47:47306 read_only_ ? FILE_MAP_READ : FILE_MAP_READ | FILE_MAP_WRITE,
avi9beac252015-12-24 08:44:47307 static_cast<uint64_t>(offset) >> 32, static_cast<DWORD>(offset), bytes);
initial.commitd7cae122008-07-26 21:49:38308 if (memory_ != NULL) {
[email protected]404a0582012-08-18 02:17:26309 DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_) &
310 (SharedMemory::MAP_MINIMUM_ALIGNMENT - 1));
[email protected]67ea5072013-03-28 02:02:18311 mapped_size_ = GetMemorySectionSize(memory_);
initial.commitd7cae122008-07-26 21:49:38312 return true;
313 }
314 return false;
315}
316
317bool SharedMemory::Unmap() {
318 if (memory_ == NULL)
319 return false;
320
321 UnmapViewOfFile(memory_);
322 memory_ = NULL;
323 return true;
324}
325
erikchenc87903e2017-05-02 19:05:01326SharedMemoryHandle SharedMemory::GetReadOnlyHandle() {
327 HANDLE result;
328 ProcessHandle process = GetCurrentProcess();
erikchen3df1dd52017-05-03 22:53:40329 if (!::DuplicateHandle(process, shm_.GetHandle(), process, &result,
erikchenc87903e2017-05-02 19:05:01330 FILE_MAP_READ | SECTION_QUERY, FALSE, 0)) {
331 return SharedMemoryHandle();
332 }
erikchen9d6afd712017-05-18 17:49:06333 SharedMemoryHandle handle =
334 SharedMemoryHandle(result, shm_.GetSize(), shm_.GetGUID());
erikchenc87903e2017-05-02 19:05:01335 handle.SetOwnershipPassesToIPC(true);
336 return handle;
337}
338
initial.commitd7cae122008-07-26 21:49:38339void SharedMemory::Close() {
erikchen3df1dd52017-05-03 22:53:40340 if (shm_.IsValid()) {
341 shm_.Close();
342 shm_ = SharedMemoryHandle();
343 }
initial.commitd7cae122008-07-26 21:49:38344}
345
[email protected]5fe733de2009-02-11 18:59:20346SharedMemoryHandle SharedMemory::handle() const {
erikchen3df1dd52017-05-03 22:53:40347 return shm_;
[email protected]5fe733de2009-02-11 18:59:20348}
349
sadrulf08f1e4a2016-11-15 00:40:02350SharedMemoryHandle SharedMemory::TakeHandle() {
erikchen3df1dd52017-05-03 22:53:40351 SharedMemoryHandle handle(shm_);
sadrulf08f1e4a2016-11-15 00:40:02352 handle.SetOwnershipPassesToIPC(true);
erikchen3df1dd52017-05-03 22:53:40353 shm_ = SharedMemoryHandle();
sadrulf08f1e4a2016-11-15 00:40:02354 memory_ = nullptr;
355 mapped_size_ = 0;
356 return handle;
357}
358
[email protected]176aa482008-11-14 03:25:15359} // namespace base