win_utils.cc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  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. #include "sandbox/win/src/win_utils.h"
  5. #include <windows.h>
  6. #include <psapi.h>
  7. #include <stddef.h>
  8. #include <stdint.h>
  9. #include <limits>
  10. #include <map>
  11. #include <memory>
  12. #include <string>
  13. #include <vector>
  14. #include "base/numerics/safe_math.h"
  15. #include "base/strings/string_util.h"
  16. #include "base/win/pe_image.h"
  17. #include "base/win/scoped_handle.h"
  18. #include "base/win/win_util.h"
  19. #include "sandbox/win/src/internal_types.h"
  20. #include "sandbox/win/src/nt_internals.h"
  21. #include "sandbox/win/src/sandbox_nt_util.h"
  22. namespace {
  23. const size_t kDriveLetterLen = 3;
  24. constexpr wchar_t kNTDotPrefix[] = L"\\\\.\\";
  25. const size_t kNTDotPrefixLen = std::size(kNTDotPrefix) - 1;
  26. // Holds the information about a known registry key.
  27. struct KnownReservedKey {
  28. const wchar_t* name;
  29. HKEY key;
  30. };
  31. // Contains all the known registry key by name and by handle.
  32. const KnownReservedKey kKnownKey[] = {
  33. {L"HKEY_CLASSES_ROOT", HKEY_CLASSES_ROOT},
  34. {L"HKEY_CURRENT_USER", HKEY_CURRENT_USER},
  35. {L"HKEY_LOCAL_MACHINE", HKEY_LOCAL_MACHINE},
  36. {L"HKEY_USERS", HKEY_USERS},
  37. {L"HKEY_PERFORMANCE_DATA", HKEY_PERFORMANCE_DATA},
  38. {L"HKEY_PERFORMANCE_TEXT", HKEY_PERFORMANCE_TEXT},
  39. {L"HKEY_PERFORMANCE_NLSTEXT", HKEY_PERFORMANCE_NLSTEXT},
  40. {L"HKEY_CURRENT_CONFIG", HKEY_CURRENT_CONFIG},
  41. {L"HKEY_DYN_DATA", HKEY_DYN_DATA}};
  42. // These functions perform case independent path comparisons.
  43. bool EqualPath(const std::wstring& first, const std::wstring& second) {
  44. return _wcsicmp(first.c_str(), second.c_str()) == 0;
  45. }
  46. bool EqualPath(const std::wstring& first,
  47. size_t first_offset,
  48. const std::wstring& second,
  49. size_t second_offset) {
  50. return _wcsicmp(first.c_str() + first_offset,
  51. second.c_str() + second_offset) == 0;
  52. }
  53. bool EqualPath(const std::wstring& first,
  54. const wchar_t* second,
  55. size_t second_len) {
  56. return _wcsnicmp(first.c_str(), second, second_len) == 0;
  57. }
  58. bool EqualPath(const std::wstring& first,
  59. size_t first_offset,
  60. const wchar_t* second,
  61. size_t second_len) {
  62. return _wcsnicmp(first.c_str() + first_offset, second, second_len) == 0;
  63. }
  64. // Returns true if |path| starts with "\??\" and returns a path without that
  65. // component.
  66. bool IsNTPath(const std::wstring& path, std::wstring* trimmed_path) {
  67. if ((path.size() < sandbox::kNTPrefixLen) ||
  68. !EqualPath(path, sandbox::kNTPrefix, sandbox::kNTPrefixLen)) {
  69. *trimmed_path = path;
  70. return false;
  71. }
  72. *trimmed_path = path.substr(sandbox::kNTPrefixLen);
  73. return true;
  74. }
  75. // Returns true if |path| starts with "\Device\" and returns a path without that
  76. // component.
  77. bool IsDevicePath(const std::wstring& path, std::wstring* trimmed_path) {
  78. if ((path.size() < sandbox::kNTDevicePrefixLen) ||
  79. (!EqualPath(path, sandbox::kNTDevicePrefix,
  80. sandbox::kNTDevicePrefixLen))) {
  81. *trimmed_path = path;
  82. return false;
  83. }
  84. *trimmed_path = path.substr(sandbox::kNTDevicePrefixLen);
  85. return true;
  86. }
  87. // Returns the offset to the path seperator following
  88. // "\Device\HarddiskVolumeX" in |path|.
  89. size_t PassHarddiskVolume(const std::wstring& path) {
  90. static constexpr wchar_t pattern[] = L"\\Device\\HarddiskVolume";
  91. const size_t patternLen = std::size(pattern) - 1;
  92. // First, check for |pattern|.
  93. if ((path.size() < patternLen) || (!EqualPath(path, pattern, patternLen)))
  94. return std::wstring::npos;
  95. // Find the next path separator, after the pattern match.
  96. return path.find_first_of(L'\\', patternLen - 1);
  97. }
  98. // Returns true if |path| starts with "\Device\HarddiskVolumeX\" and returns a
  99. // path without that component. |removed| will hold the prefix removed.
  100. bool IsDeviceHarddiskPath(const std::wstring& path,
  101. std::wstring* trimmed_path,
  102. std::wstring* removed) {
  103. size_t offset = PassHarddiskVolume(path);
  104. if (offset == std::wstring::npos)
  105. return false;
  106. // Remove up to and including the path separator.
  107. *removed = path.substr(0, offset + 1);
  108. // Remaining path starts after the path separator.
  109. *trimmed_path = path.substr(offset + 1);
  110. return true;
  111. }
  112. bool StartsWithDriveLetter(const std::wstring& path) {
  113. if (path.size() < kDriveLetterLen)
  114. return false;
  115. if (path[1] != L':' || path[2] != L'\\')
  116. return false;
  117. return base::IsAsciiAlpha(path[0]);
  118. }
  119. // Removes "\\\\.\\" from the path.
  120. void RemoveImpliedDevice(std::wstring* path) {
  121. if (EqualPath(*path, kNTDotPrefix, kNTDotPrefixLen))
  122. *path = path->substr(kNTDotPrefixLen);
  123. }
  124. bool QueryObjectInformation(HANDLE handle,
  125. OBJECT_INFORMATION_CLASS info_class,
  126. std::vector<char>& buffer) {
  127. NtQueryObjectFunction NtQueryObject = sandbox::GetNtExports()->QueryObject;
  128. ULONG size = static_cast<ULONG>(buffer.size());
  129. __try {
  130. return NT_SUCCESS(
  131. NtQueryObject(handle, info_class, buffer.data(), size, &size));
  132. } __except (GetExceptionCode() == STATUS_INVALID_HANDLE
  133. ? EXCEPTION_EXECUTE_HANDLER
  134. : EXCEPTION_CONTINUE_SEARCH) {
  135. return false;
  136. }
  137. }
  138. } // namespace
  139. namespace sandbox {
  140. // Returns true if the provided path points to a pipe.
  141. bool IsPipe(const std::wstring& path) {
  142. size_t start = 0;
  143. if (EqualPath(path, sandbox::kNTPrefix, sandbox::kNTPrefixLen))
  144. start = sandbox::kNTPrefixLen;
  145. const wchar_t kPipe[] = L"pipe\\";
  146. if (path.size() < start + std::size(kPipe) - 1)
  147. return false;
  148. return EqualPath(path, start, kPipe, std::size(kPipe) - 1);
  149. }
  150. bool ResolveRegistryName(std::wstring name, std::wstring* resolved_name) {
  151. for (size_t i = 0; i < std::size(kKnownKey); ++i) {
  152. if (name.find(kKnownKey[i].name) == 0) {
  153. HKEY key;
  154. DWORD disposition;
  155. if (ERROR_SUCCESS != ::RegCreateKeyEx(kKnownKey[i].key, L"", 0, nullptr,
  156. 0, MAXIMUM_ALLOWED, nullptr, &key,
  157. &disposition))
  158. return false;
  159. bool result = GetPathFromHandle(key, resolved_name);
  160. ::RegCloseKey(key);
  161. if (!result)
  162. return false;
  163. *resolved_name += name.substr(wcslen(kKnownKey[i].name));
  164. return true;
  165. }
  166. }
  167. return false;
  168. }
  169. // |full_path| can have any of the following forms:
  170. // \??\c:\some\foo\bar
  171. // \Device\HarddiskVolume0\some\foo\bar
  172. // \??\HarddiskVolume0\some\foo\bar
  173. DWORD IsReparsePoint(const std::wstring& full_path) {
  174. // Check if it's a pipe. We can't query the attributes of a pipe.
  175. if (IsPipe(full_path))
  176. return ERROR_NOT_A_REPARSE_POINT;
  177. std::wstring path;
  178. bool nt_path = IsNTPath(full_path, &path);
  179. bool has_drive = StartsWithDriveLetter(path);
  180. bool is_device_path = IsDevicePath(path, &path);
  181. if (!has_drive && !is_device_path && !nt_path)
  182. return ERROR_INVALID_NAME;
  183. bool added_implied_device = false;
  184. if (!has_drive) {
  185. path = std::wstring(kNTDotPrefix) + path;
  186. added_implied_device = true;
  187. }
  188. std::wstring::size_type last_pos = std::wstring::npos;
  189. bool passed_once = false;
  190. do {
  191. path = path.substr(0, last_pos);
  192. DWORD attributes = ::GetFileAttributes(path.c_str());
  193. if (INVALID_FILE_ATTRIBUTES == attributes) {
  194. DWORD error = ::GetLastError();
  195. if (error != ERROR_FILE_NOT_FOUND && error != ERROR_PATH_NOT_FOUND &&
  196. error != ERROR_INVALID_NAME) {
  197. // Unexpected error.
  198. if (passed_once && added_implied_device &&
  199. (path.rfind(L'\\') == kNTDotPrefixLen - 1)) {
  200. break;
  201. }
  202. return error;
  203. }
  204. } else if (FILE_ATTRIBUTE_REPARSE_POINT & attributes) {
  205. // This is a reparse point.
  206. return ERROR_SUCCESS;
  207. }
  208. passed_once = true;
  209. last_pos = path.rfind(L'\\');
  210. } while (last_pos > 2); // Skip root dir.
  211. return ERROR_NOT_A_REPARSE_POINT;
  212. }
  213. // We get a |full_path| of the forms accepted by IsReparsePoint(), and the name
  214. // we'll get from |handle| will be \device\harddiskvolume1\some\foo\bar.
  215. bool SameObject(HANDLE handle, const wchar_t* full_path) {
  216. // Check if it's a pipe.
  217. if (IsPipe(full_path))
  218. return true;
  219. std::wstring actual_path;
  220. if (!GetPathFromHandle(handle, &actual_path))
  221. return false;
  222. std::wstring path(full_path);
  223. DCHECK_NT(!path.empty());
  224. // This may end with a backslash.
  225. const wchar_t kBackslash = '\\';
  226. if (path.back() == kBackslash)
  227. path = path.substr(0, path.length() - 1);
  228. // Perfect match (case-insesitive check).
  229. if (EqualPath(actual_path, path))
  230. return true;
  231. bool nt_path = IsNTPath(path, &path);
  232. bool has_drive = StartsWithDriveLetter(path);
  233. if (!has_drive && nt_path) {
  234. std::wstring simple_actual_path;
  235. if (!IsDevicePath(actual_path, &simple_actual_path))
  236. return false;
  237. // Perfect match (case-insesitive check).
  238. return (EqualPath(simple_actual_path, path));
  239. }
  240. if (!has_drive)
  241. return false;
  242. // We only need 3 chars, but let's alloc a buffer for four.
  243. wchar_t drive[4] = {0};
  244. wchar_t vol_name[MAX_PATH];
  245. memcpy(drive, &path[0], 2 * sizeof(*drive));
  246. // We'll get a double null terminated string.
  247. DWORD vol_length = ::QueryDosDeviceW(drive, vol_name, MAX_PATH);
  248. if (vol_length < 2 || vol_length == MAX_PATH)
  249. return false;
  250. // Ignore the nulls at the end.
  251. vol_length = static_cast<DWORD>(wcslen(vol_name));
  252. // The two paths should be the same length.
  253. if (vol_length + path.size() - 2 != actual_path.size())
  254. return false;
  255. // Check up to the drive letter.
  256. if (!EqualPath(actual_path, vol_name, vol_length))
  257. return false;
  258. // Check the path after the drive letter.
  259. if (!EqualPath(actual_path, vol_length, path, 2))
  260. return false;
  261. return true;
  262. }
  263. // Just make a best effort here. There are lots of corner cases that we're
  264. // not expecting - and will fail to make long.
  265. bool ConvertToLongPath(std::wstring* native_path,
  266. const std::wstring* drive_letter) {
  267. if (IsPipe(*native_path))
  268. return true;
  269. bool is_device_harddisk_path = false;
  270. bool is_nt_path = false;
  271. bool added_implied_device = false;
  272. std::wstring temp_path;
  273. std::wstring to_restore;
  274. // Process a few prefix types.
  275. if (IsNTPath(*native_path, &temp_path)) {
  276. // "\??\"
  277. if (!StartsWithDriveLetter(temp_path)) {
  278. // Prepend with "\\.\".
  279. temp_path = std::wstring(kNTDotPrefix) + temp_path;
  280. added_implied_device = true;
  281. }
  282. is_nt_path = true;
  283. } else if (IsDeviceHarddiskPath(*native_path, &temp_path, &to_restore)) {
  284. // "\Device\HarddiskVolumeX\" - hacky attempt making ::GetLongPathName
  285. // work for native device paths. Remove "\Device\HarddiskVolumeX\" and
  286. // replace with drive letter.
  287. // Nothing we can do if we don't have a drive letter. Leave |native_path|
  288. // as is.
  289. if (!drive_letter || drive_letter->empty())
  290. return false;
  291. temp_path = *drive_letter + temp_path;
  292. is_device_harddisk_path = true;
  293. } else if (IsDevicePath(*native_path, &temp_path)) {
  294. // "\Device\" - there's nothing we can do to convert to long here.
  295. return false;
  296. }
  297. DWORD size = MAX_PATH;
  298. std::unique_ptr<wchar_t[]> long_path_buf(new wchar_t[size]);
  299. DWORD return_value =
  300. ::GetLongPathName(temp_path.c_str(), long_path_buf.get(), size);
  301. while (return_value >= size) {
  302. size *= 2;
  303. long_path_buf.reset(new wchar_t[size]);
  304. return_value =
  305. ::GetLongPathName(temp_path.c_str(), long_path_buf.get(), size);
  306. }
  307. DWORD last_error = ::GetLastError();
  308. if (0 == return_value && (ERROR_FILE_NOT_FOUND == last_error ||
  309. ERROR_PATH_NOT_FOUND == last_error ||
  310. ERROR_INVALID_NAME == last_error)) {
  311. // The file does not exist, but maybe a sub path needs to be expanded.
  312. std::wstring::size_type last_slash = temp_path.rfind(L'\\');
  313. if (std::wstring::npos == last_slash)
  314. return false;
  315. std::wstring begin = temp_path.substr(0, last_slash);
  316. std::wstring end = temp_path.substr(last_slash);
  317. if (!ConvertToLongPath(&begin))
  318. return false;
  319. // Ok, it worked. Let's reset the return value.
  320. temp_path = begin + end;
  321. return_value = 1;
  322. } else if (0 != return_value) {
  323. temp_path = long_path_buf.get();
  324. }
  325. // If successful, re-apply original namespace prefix before returning.
  326. if (return_value != 0) {
  327. if (added_implied_device)
  328. RemoveImpliedDevice(&temp_path);
  329. if (is_nt_path) {
  330. *native_path = kNTPrefix;
  331. *native_path += temp_path;
  332. } else if (is_device_harddisk_path) {
  333. // Remove the added drive letter.
  334. temp_path = temp_path.substr(kDriveLetterLen);
  335. *native_path = to_restore;
  336. *native_path += temp_path;
  337. } else {
  338. *native_path = temp_path;
  339. }
  340. return true;
  341. }
  342. return false;
  343. }
  344. bool GetPathFromHandle(HANDLE handle, std::wstring* path) {
  345. using LengthType = decltype(OBJECT_NAME_INFORMATION::ObjectName.Length);
  346. std::vector<char> buffer(sizeof(OBJECT_NAME_INFORMATION) +
  347. std::numeric_limits<LengthType>::max());
  348. if (!QueryObjectInformation(handle, ObjectNameInformation, buffer))
  349. return false;
  350. OBJECT_NAME_INFORMATION* name =
  351. reinterpret_cast<OBJECT_NAME_INFORMATION*>(buffer.data());
  352. path->assign(name->ObjectName.Buffer,
  353. name->ObjectName.Length / sizeof(name->ObjectName.Buffer[0]));
  354. return true;
  355. }
  356. bool GetNtPathFromWin32Path(const std::wstring& path, std::wstring* nt_path) {
  357. base::win::ScopedHandle file(::CreateFileW(
  358. path.c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
  359. nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr));
  360. if (!file.IsValid())
  361. return false;
  362. return GetPathFromHandle(file.Get(), nt_path);
  363. }
  364. bool GetTypeNameFromHandle(HANDLE handle, std::wstring* type_name) {
  365. // No typename is currently longer than 32 characters on Windows 11, so use an
  366. // upper bound of 128 characters.
  367. std::vector<char> buffer(sizeof(OBJECT_TYPE_INFORMATION) +
  368. 128 * sizeof(WCHAR));
  369. if (!QueryObjectInformation(handle, ObjectTypeInformation, buffer))
  370. return false;
  371. OBJECT_TYPE_INFORMATION* name =
  372. reinterpret_cast<OBJECT_TYPE_INFORMATION*>(buffer.data());
  373. type_name->assign(name->Name.Buffer,
  374. name->Name.Length / sizeof(name->Name.Buffer[0]));
  375. return true;
  376. }
  377. bool WriteProtectedChildMemory(HANDLE child_process,
  378. void* address,
  379. const void* buffer,
  380. size_t length) {
  381. // First, remove the protections.
  382. DWORD old_protection;
  383. if (!::VirtualProtectEx(child_process, address, length, PAGE_WRITECOPY,
  384. &old_protection))
  385. return false;
  386. SIZE_T written;
  387. bool ok =
  388. ::WriteProcessMemory(child_process, address, buffer, length, &written) &&
  389. (length == written);
  390. // Always attempt to restore the original protection.
  391. if (!::VirtualProtectEx(child_process, address, length, old_protection,
  392. &old_protection))
  393. return false;
  394. return ok;
  395. }
  396. bool CopyToChildMemory(HANDLE child,
  397. const void* local_buffer,
  398. size_t buffer_bytes,
  399. void** remote_buffer) {
  400. DCHECK(remote_buffer);
  401. if (0 == buffer_bytes) {
  402. *remote_buffer = nullptr;
  403. return true;
  404. }
  405. // Allocate memory in the target process without specifying the address
  406. void* remote_data = ::VirtualAllocEx(child, nullptr, buffer_bytes, MEM_COMMIT,
  407. PAGE_READWRITE);
  408. if (!remote_data)
  409. return false;
  410. SIZE_T bytes_written;
  411. bool success = ::WriteProcessMemory(child, remote_data, local_buffer,
  412. buffer_bytes, &bytes_written);
  413. if (!success || bytes_written != buffer_bytes) {
  414. ::VirtualFreeEx(child, remote_data, 0, MEM_RELEASE);
  415. return false;
  416. }
  417. *remote_buffer = remote_data;
  418. return true;
  419. }
  420. DWORD GetLastErrorFromNtStatus(NTSTATUS status) {
  421. return GetNtExports()->RtlNtStatusToDosError(status);
  422. }
  423. // This function uses the undocumented PEB ImageBaseAddress field to extract
  424. // the base address of the new process.
  425. void* GetProcessBaseAddress(HANDLE process) {
  426. PROCESS_BASIC_INFORMATION process_basic_info = {};
  427. NTSTATUS status = GetNtExports()->QueryInformationProcess(
  428. process, ProcessBasicInformation, &process_basic_info,
  429. sizeof(process_basic_info), nullptr);
  430. if (STATUS_SUCCESS != status)
  431. return nullptr;
  432. PEB peb = {};
  433. SIZE_T bytes_read = 0;
  434. if (!::ReadProcessMemory(process, process_basic_info.PebBaseAddress, &peb,
  435. sizeof(peb), &bytes_read) ||
  436. (sizeof(peb) != bytes_read)) {
  437. return nullptr;
  438. }
  439. void* base_address = peb.ImageBaseAddress;
  440. char magic[2] = {};
  441. if (!::ReadProcessMemory(process, base_address, magic, sizeof(magic),
  442. &bytes_read) ||
  443. (sizeof(magic) != bytes_read)) {
  444. return nullptr;
  445. }
  446. if (magic[0] != 'M' || magic[1] != 'Z')
  447. return nullptr;
  448. return base_address;
  449. }
  450. absl::optional<ProcessHandleMap> GetCurrentProcessHandles() {
  451. DWORD handle_count;
  452. if (!::GetProcessHandleCount(::GetCurrentProcess(), &handle_count))
  453. return absl::nullopt;
  454. // The system call will return only handles up to the buffer size so add a
  455. // margin of error of an additional 1000 handles.
  456. std::vector<char> buffer((handle_count + 1000) * sizeof(uint32_t));
  457. DWORD return_length;
  458. NTSTATUS status = GetNtExports()->QueryInformationProcess(
  459. ::GetCurrentProcess(), ProcessHandleTable, buffer.data(),
  460. static_cast<ULONG>(buffer.size()), &return_length);
  461. if (!NT_SUCCESS(status)) {
  462. ::SetLastError(GetLastErrorFromNtStatus(status));
  463. return absl::nullopt;
  464. }
  465. DCHECK(buffer.size() >= return_length);
  466. DCHECK((buffer.size() % sizeof(uint32_t)) == 0);
  467. ProcessHandleMap handle_map;
  468. const uint32_t* handle_values = reinterpret_cast<uint32_t*>(buffer.data());
  469. size_t count = return_length / sizeof(uint32_t);
  470. for (size_t index = 0; index < count; ++index) {
  471. HANDLE handle = base::win::Uint32ToHandle(handle_values[index]);
  472. std::wstring type_name;
  473. if (GetTypeNameFromHandle(handle, &type_name))
  474. handle_map[type_name].push_back(handle);
  475. }
  476. return handle_map;
  477. }
  478. absl::optional<ProcessHandleMap> GetCurrentProcessHandlesWin7() {
  479. DWORD handle_count = UINT_MAX;
  480. const int kInvalidHandleThreshold = 100;
  481. const size_t kHandleOffset = 4; // Handles are always a multiple of 4.
  482. if (!::GetProcessHandleCount(::GetCurrentProcess(), &handle_count))
  483. return absl::nullopt;
  484. ProcessHandleMap handle_map;
  485. uint32_t handle_value = 0;
  486. int invalid_count = 0;
  487. // Keep incrementing until we hit the number of handles reported by
  488. // GetProcessHandleCount(). If we hit a very long sequence of invalid
  489. // handles we assume that we've run past the end of the table.
  490. while (handle_count && invalid_count < kInvalidHandleThreshold) {
  491. handle_value += kHandleOffset;
  492. HANDLE handle = base::win::Uint32ToHandle(handle_value);
  493. std::wstring type_name;
  494. if (!GetTypeNameFromHandle(handle, &type_name)) {
  495. ++invalid_count;
  496. continue;
  497. }
  498. --handle_count;
  499. handle_map[type_name].push_back(handle);
  500. }
  501. return handle_map;
  502. }
  503. } // namespace sandbox
  504. void ResolveNTFunctionPtr(const char* name, void* ptr) {
  505. static volatile HMODULE ntdll = nullptr;
  506. if (!ntdll) {
  507. HMODULE ntdll_local = ::GetModuleHandle(sandbox::kNtdllName);
  508. // Use PEImage to sanity-check that we have a valid ntdll handle.
  509. base::win::PEImage ntdll_peimage(ntdll_local);
  510. CHECK_NT(ntdll_peimage.VerifyMagic());
  511. // Race-safe way to set static ntdll.
  512. ::InterlockedCompareExchangePointer(
  513. reinterpret_cast<PVOID volatile*>(&ntdll), ntdll_local, nullptr);
  514. }
  515. CHECK_NT(ntdll);
  516. FARPROC* function_ptr = reinterpret_cast<FARPROC*>(ptr);
  517. *function_ptr = ::GetProcAddress(ntdll, name);
  518. CHECK_NT(*function_ptr);
  519. }