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.
4
5#include "sandbox/win/src/handle_table.h"
6
7#include <algorithm>
8#include <cstdlib>
9
10#include "base/logging.h"
11#include "base/memory/scoped_ptr.h"
12#include "sandbox/win/src/win_utils.h"
13
14namespace {
15
16bool CompareHandleEntries(const SYSTEM_HANDLE_INFORMATION& a,
17                          const SYSTEM_HANDLE_INFORMATION& b) {
18  return a.ProcessId < b.ProcessId;
19}
20
21}  // namespace
22
23namespace sandbox {
24
25const base::char16* HandleTable::kTypeProcess = L"Process";
26const base::char16* HandleTable::kTypeThread = L"Thread";
27const base::char16* HandleTable::kTypeFile = L"File";
28const base::char16* HandleTable::kTypeDirectory = L"Directory";
29const base::char16* HandleTable::kTypeKey = L"Key";
30const base::char16* HandleTable::kTypeWindowStation = L"WindowStation";
31const base::char16* HandleTable::kTypeDesktop = L"Desktop";
32const base::char16* HandleTable::kTypeService = L"Service";
33const base::char16* HandleTable::kTypeMutex = L"Mutex";
34const base::char16* HandleTable::kTypeSemaphore = L"Semaphore";
35const base::char16* HandleTable::kTypeEvent = L"Event";
36const base::char16* HandleTable::kTypeTimer = L"Timer";
37const base::char16* HandleTable::kTypeNamedPipe = L"NamedPipe";
38const base::char16* HandleTable::kTypeJobObject = L"JobObject";
39const base::char16* HandleTable::kTypeFileMap = L"FileMap";
40const base::char16* HandleTable::kTypeAlpcPort = L"ALPC Port";
41
42HandleTable::HandleTable() {
43  static NtQuerySystemInformation QuerySystemInformation = NULL;
44  if (!QuerySystemInformation)
45    ResolveNTFunctionPtr("NtQuerySystemInformation", &QuerySystemInformation);
46
47  ULONG size = 0x15000;
48  NTSTATUS result;
49  do {
50    handle_info_buffer_.resize(size);
51    result = QuerySystemInformation(SystemHandleInformation,
52        handle_info_internal(), size, &size);
53  } while (result == STATUS_INFO_LENGTH_MISMATCH);
54
55  // We failed, so make an empty table.
56  if (!NT_SUCCESS(result)) {
57    handle_info_buffer_.resize(0);
58    return;
59  }
60
61  // Sort it to make process lookups faster.
62  std::sort(handle_info_internal()->Information,
63      handle_info_internal()->Information +
64      handle_info_internal()->NumberOfHandles, CompareHandleEntries);
65}
66
67HandleTable::Iterator HandleTable::HandlesForProcess(ULONG process_id) const {
68  SYSTEM_HANDLE_INFORMATION key;
69  key.ProcessId = process_id;
70
71  const SYSTEM_HANDLE_INFORMATION* start = handle_info()->Information;
72  const SYSTEM_HANDLE_INFORMATION* finish =
73      &handle_info()->Information[handle_info()->NumberOfHandles];
74
75  start = std::lower_bound(start, finish, key, CompareHandleEntries);
76  if (start->ProcessId != process_id)
77    return Iterator(*this, finish, finish);
78  finish = std::upper_bound(start, finish, key, CompareHandleEntries);
79  return Iterator(*this, start, finish);
80}
81
82HandleTable::HandleEntry::HandleEntry(
83    const SYSTEM_HANDLE_INFORMATION* handle_info_entry)
84    : handle_entry_(handle_info_entry), last_entry_(0) {
85}
86
87void HandleTable::HandleEntry::UpdateInfo(UpdateType flag) {
88  static NtQueryObject QueryObject = NULL;
89  if (!QueryObject)
90    ResolveNTFunctionPtr("NtQueryObject", &QueryObject);
91
92  NTSTATUS result;
93
94  // Always update the basic type info, but grab the names as needed.
95  if (needs_info_update()) {
96    handle_name_.clear();
97    type_name_.clear();
98    last_entry_ = handle_entry_;
99
100    // Most handle names are very short, so start small and reuse this buffer.
101    if (type_info_buffer_.empty())
102      type_info_buffer_.resize(sizeof(OBJECT_TYPE_INFORMATION)
103          + (32 * sizeof(wchar_t)));
104    ULONG size = static_cast<ULONG>(type_info_buffer_.size());
105    result = QueryObject(reinterpret_cast<HANDLE>(handle_entry_->Handle),
106        ObjectTypeInformation, type_info_internal(), size, &size);
107    while (result == STATUS_INFO_LENGTH_MISMATCH) {
108      type_info_buffer_.resize(size);
109      result = QueryObject(reinterpret_cast<HANDLE>(handle_entry_->Handle),
110          ObjectTypeInformation, type_info_internal(), size, &size);
111    }
112
113    if (!NT_SUCCESS(result)) {
114      type_info_buffer_.clear();
115      return;
116    }
117  }
118
119  // Don't bother copying out names until we ask for them, and then cache them.
120  switch (flag) {
121    case UPDATE_INFO_AND_NAME:
122      if (type_info_buffer_.size() && handle_name_.empty()) {
123        ULONG size = MAX_PATH;
124        scoped_ptr<UNICODE_STRING, base::FreeDeleter> name;
125        do {
126          name.reset(static_cast<UNICODE_STRING*>(malloc(size)));
127          DCHECK(name.get());
128          result = QueryObject(reinterpret_cast<HANDLE>(
129              handle_entry_->Handle), ObjectNameInformation, name.get(),
130              size, &size);
131        } while (result == STATUS_INFO_LENGTH_MISMATCH);
132
133        if (NT_SUCCESS(result)) {
134          handle_name_.assign(name->Buffer, name->Length / sizeof(wchar_t));
135        }
136      }
137      break;
138
139    case UPDATE_INFO_AND_TYPE_NAME:
140      if (!type_info_buffer_.empty() && type_info_internal()->Name.Buffer &&
141          type_name_.empty()) {
142        type_name_.assign(type_info_internal()->Name.Buffer,
143            type_info_internal()->Name.Length / sizeof(wchar_t));
144      }
145      break;
146  }
147}
148
149const OBJECT_TYPE_INFORMATION* HandleTable::HandleEntry::TypeInfo() {
150  UpdateInfo(UPDATE_INFO_ONLY);
151  return type_info_buffer_.empty() ? NULL : type_info_internal();
152}
153
154const base::string16& HandleTable::HandleEntry::Name() {
155  UpdateInfo(UPDATE_INFO_AND_NAME);
156  return handle_name_;
157}
158
159const base::string16& HandleTable::HandleEntry::Type() {
160  UpdateInfo(UPDATE_INFO_AND_TYPE_NAME);
161  return type_name_;
162}
163
164bool HandleTable::HandleEntry::IsType(const base::string16& type_string) {
165  UpdateInfo(UPDATE_INFO_ONLY);
166  if (type_info_buffer_.empty())
167    return false;
168  return type_string.compare(0,
169      type_info_internal()->Name.Length / sizeof(wchar_t),
170      type_info_internal()->Name.Buffer) == 0;
171}
172
173HandleTable::Iterator::Iterator(const HandleTable& table,
174                                const SYSTEM_HANDLE_INFORMATION* start,
175                                const SYSTEM_HANDLE_INFORMATION* end)
176    : table_(table), current_(start), end_(end) {
177}
178
179HandleTable::Iterator::Iterator(const Iterator& it)
180    : table_(it.table_), current_(it.current_.handle_entry_), end_(it.end_) {
181}
182
183}  // namespace sandbox
184