Roll src/third_party/WebKit e0eac24:489c548 (svn 193311:193320)
[chromium-blink-merge.git] / sandbox / win / src / handle_closer_agent.cc
blob1fa82553bb05c4677903702162a43e01e1ff2529
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 "sandbox/win/src/handle_closer_agent.h"
7 #include "base/logging.h"
8 #include "sandbox/win/src/nt_internals.h"
9 #include "sandbox/win/src/win_utils.h"
11 namespace {
13 // Returns type infomation for an NT object. This routine is expected to be
14 // called for invalid handles so it catches STATUS_INVALID_HANDLE exceptions
15 // that can be generated when handle tracing is enabled.
16 NTSTATUS QueryObjectTypeInformation(HANDLE handle,
17 void* buffer,
18 ULONG* size) {
19 static NtQueryObject QueryObject = NULL;
20 if (!QueryObject)
21 ResolveNTFunctionPtr("NtQueryObject", &QueryObject);
23 NTSTATUS status = STATUS_UNSUCCESSFUL;
24 __try {
25 status = QueryObject(handle, ObjectTypeInformation, buffer, *size, size);
26 } __except(GetExceptionCode() == STATUS_INVALID_HANDLE ?
27 EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
28 status = STATUS_INVALID_HANDLE;
30 return status;
33 } // namespace
35 namespace sandbox {
37 // Memory buffer mapped from the parent, with the list of handles.
38 SANDBOX_INTERCEPT HandleCloserInfo* g_handles_to_close = NULL;
40 bool HandleCloserAgent::NeedsHandlesClosed() {
41 return g_handles_to_close != NULL;
44 HandleCloserAgent::HandleCloserAgent()
45 : dummy_handle_(::CreateEvent(NULL, FALSE, FALSE, NULL)) {
48 // Attempts to stuff |closed_handle| with a duplicated handle for a dummy Event
49 // with no access. This should allow the handle to be closed, to avoid
50 // generating EXCEPTION_INVALID_HANDLE on shutdown, but nothing else. For now
51 // the only supported |type| is Event or File.
52 bool HandleCloserAgent::AttemptToStuffHandleSlot(HANDLE closed_handle,
53 const base::string16& type) {
54 // Only attempt to stuff Files and Events at the moment.
55 if (type != L"Event" && type != L"File") {
56 return true;
59 if (!dummy_handle_.IsValid())
60 return false;
62 // This should never happen, as g_dummy is created before closing to_stuff.
63 DCHECK(dummy_handle_.Get() != closed_handle);
65 std::vector<HANDLE> to_close;
66 HANDLE dup_dummy = NULL;
67 size_t count = 16;
69 do {
70 if (!::DuplicateHandle(::GetCurrentProcess(), dummy_handle_.Get(),
71 ::GetCurrentProcess(), &dup_dummy, 0, FALSE, 0))
72 break;
73 if (dup_dummy != closed_handle)
74 to_close.push_back(dup_dummy);
75 } while (count-- &&
76 reinterpret_cast<uintptr_t>(dup_dummy) <
77 reinterpret_cast<uintptr_t>(closed_handle));
79 for (auto h : to_close)
80 ::CloseHandle(h);
82 // Useful to know when we're not able to stuff handles.
83 DCHECK(dup_dummy == closed_handle);
85 return dup_dummy == closed_handle;
88 // Reads g_handles_to_close and creates the lookup map.
89 void HandleCloserAgent::InitializeHandlesToClose() {
90 CHECK(g_handles_to_close != NULL);
92 // Grab the header.
93 HandleListEntry* entry = g_handles_to_close->handle_entries;
94 for (size_t i = 0; i < g_handles_to_close->num_handle_types; ++i) {
95 // Set the type name.
96 base::char16* input = entry->handle_type;
97 HandleMap::mapped_type& handle_names = handles_to_close_[input];
98 input = reinterpret_cast<base::char16*>(reinterpret_cast<char*>(entry)
99 + entry->offset_to_names);
100 // Grab all the handle names.
101 for (size_t j = 0; j < entry->name_count; ++j) {
102 std::pair<HandleMap::mapped_type::iterator, bool> name
103 = handle_names.insert(input);
104 CHECK(name.second);
105 input += name.first->size() + 1;
108 // Move on to the next entry.
109 entry = reinterpret_cast<HandleListEntry*>(reinterpret_cast<char*>(entry)
110 + entry->record_bytes);
112 DCHECK(reinterpret_cast<base::char16*>(entry) >= input);
113 DCHECK(reinterpret_cast<base::char16*>(entry) - input <
114 sizeof(size_t) / sizeof(base::char16));
117 // Clean up the memory we copied over.
118 ::VirtualFree(g_handles_to_close, 0, MEM_RELEASE);
119 g_handles_to_close = NULL;
122 bool HandleCloserAgent::CloseHandles() {
123 DWORD handle_count = UINT_MAX;
124 const int kInvalidHandleThreshold = 100;
125 const size_t kHandleOffset = 4; // Handles are always a multiple of 4.
127 if (!::GetProcessHandleCount(::GetCurrentProcess(), &handle_count))
128 return false;
130 // Set up buffers for the type info and the name.
131 std::vector<BYTE> type_info_buffer(sizeof(OBJECT_TYPE_INFORMATION) +
132 32 * sizeof(wchar_t));
133 OBJECT_TYPE_INFORMATION* type_info =
134 reinterpret_cast<OBJECT_TYPE_INFORMATION*>(&(type_info_buffer[0]));
135 base::string16 handle_name;
136 HANDLE handle = NULL;
137 int invalid_count = 0;
139 // Keep incrementing until we hit the number of handles reported by
140 // GetProcessHandleCount(). If we hit a very long sequence of invalid
141 // handles we assume that we've run past the end of the table.
142 while (handle_count && invalid_count < kInvalidHandleThreshold) {
143 reinterpret_cast<size_t&>(handle) += kHandleOffset;
144 NTSTATUS rc;
146 // Get the type name, reusing the buffer.
147 ULONG size = static_cast<ULONG>(type_info_buffer.size());
148 rc = QueryObjectTypeInformation(handle, type_info, &size);
149 while (rc == STATUS_INFO_LENGTH_MISMATCH ||
150 rc == STATUS_BUFFER_OVERFLOW) {
151 type_info_buffer.resize(size + sizeof(wchar_t));
152 type_info = reinterpret_cast<OBJECT_TYPE_INFORMATION*>(
153 &(type_info_buffer[0]));
154 rc = QueryObjectTypeInformation(handle, type_info, &size);
155 // Leave padding for the nul terminator.
156 if (NT_SUCCESS(rc) && size == type_info_buffer.size())
157 rc = STATUS_INFO_LENGTH_MISMATCH;
159 if (!NT_SUCCESS(rc) || !type_info->Name.Buffer) {
160 ++invalid_count;
161 continue;
164 --handle_count;
165 type_info->Name.Buffer[type_info->Name.Length / sizeof(wchar_t)] = L'\0';
167 // Check if we're looking for this type of handle.
168 HandleMap::iterator result =
169 handles_to_close_.find(type_info->Name.Buffer);
170 if (result != handles_to_close_.end()) {
171 HandleMap::mapped_type& names = result->second;
172 // Empty set means close all handles of this type; otherwise check name.
173 if (!names.empty()) {
174 // Move on to the next handle if this name doesn't match.
175 if (!GetHandleName(handle, &handle_name) || !names.count(handle_name))
176 continue;
179 if (!::SetHandleInformation(handle, HANDLE_FLAG_PROTECT_FROM_CLOSE, 0))
180 return false;
181 if (!::CloseHandle(handle))
182 return false;
183 // Attempt to stuff this handle with a new dummy Event.
184 AttemptToStuffHandleSlot(handle, result->first);
188 return true;
191 } // namespace sandbox