Debian Codegraph @

mozglue/misc/NativeNt.h

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
6
7 #ifndef mozilla_NativeNt_h
8 #define mozilla_NativeNt_h
9
10 #include <stdint.h>
11 #include <windows.h>
12 #include <winnt.h>
13 #include <winternl.h>
14
15 #include <algorithm>
16 #include <type_traits>
17 #include <utility>
18
19 #include "mozilla/ArrayUtils.h"
20 #include "mozilla/Attributes.h"
21 #include "mozilla/DebugOnly.h"
22 #include "mozilla/Maybe.h"
23 #include "mozilla/Range.h"
24 #include "mozilla/Span.h"
25 #include "mozilla/WinHeaderOnlyUtils.h"
26 #include "mozilla/interceptor/MMPolicies.h"
27 #include "mozilla/interceptor/TargetFunction.h"
28
29 #if defined(MOZILLA_INTERNAL_API)
30 # include "nsString.h"
31 #endif // defined(MOZILLA_INTERNAL_API)
32
33 // The declarations within this #if block are intended to be used for initial
34 // process initialization ONLY. You probably don't want to be using these in
35 // normal Gecko code!
36 #if !defined(MOZILLA_INTERNAL_API)
37
38 extern "C" {
39
40 # if !defined(STATUS_ACCESS_DENIED)
41 # define STATUS_ACCESS_DENIED ((NTSTATUS)0xC0000022L)
42 # endif // !defined(STATUS_ACCESS_DENIED)
43
44 # if !defined(STATUS_DLL_NOT_FOUND)
45 # define STATUS_DLL_NOT_FOUND ((NTSTATUS)0xC0000135L)
46 # endif // !defined(STATUS_DLL_NOT_FOUND)
47
48 # if !defined(STATUS_UNSUCCESSFUL)
49 # define STATUS_UNSUCCESSFUL ((NTSTATUS)0xC0000001L)
50 # endif // !defined(STATUS_UNSUCCESSFUL)
51
52 # if !defined(STATUS_INFO_LENGTH_MISMATCH)
53 # define STATUS_INFO_LENGTH_MISMATCH ((NTSTATUS)0xC0000004L)
54 # endif
55
56 enum SECTION_INHERIT { ViewShare = 1, ViewUnmap = 2 };
57
58 NTSTATUS NTAPI NtMapViewOfSection(
59 HANDLE aSection, HANDLE aProcess, PVOID* aBaseAddress, ULONG_PTR aZeroBits,
60 SIZE_T aCommitSize, PLARGE_INTEGER aSectionOffset, PSIZE_T aViewSize,
61 SECTION_INHERIT aInheritDisposition, ULONG aAllocationType,
62 ULONG aProtectionFlags);
63
64 NTSTATUS NTAPI NtUnmapViewOfSection(HANDLE aProcess, PVOID aBaseAddress);
65
66 enum MEMORY_INFORMATION_CLASS {
67 MemoryBasicInformation = 0,
68 MemorySectionName = 2
69 };
70
71 // NB: When allocating, space for the buffer must also be included
72 typedef struct _MEMORY_SECTION_NAME {
73 UNICODE_STRING mSectionFileName;
74 } MEMORY_SECTION_NAME, *PMEMORY_SECTION_NAME;
75
76 NTSTATUS NTAPI NtQueryVirtualMemory(HANDLE aProcess, PVOID aBaseAddress,
77 MEMORY_INFORMATION_CLASS aMemInfoClass,
78 PVOID aMemInfo, SIZE_T aMemInfoLen,
79 PSIZE_T aReturnLen);
80
81 LONG NTAPI RtlCompareUnicodeString(PCUNICODE_STRING aStr1,
82 PCUNICODE_STRING aStr2,
83 BOOLEAN aCaseInsensitive);
84
85 BOOLEAN NTAPI RtlEqualUnicodeString(PCUNICODE_STRING aStr1,
86 PCUNICODE_STRING aStr2,
87 BOOLEAN aCaseInsensitive);
88
89 NTSTATUS NTAPI RtlGetVersion(PRTL_OSVERSIONINFOW aOutVersionInformation);
90
91 VOID NTAPI RtlAcquireSRWLockExclusive(PSRWLOCK aLock);
92 VOID NTAPI RtlAcquireSRWLockShared(PSRWLOCK aLock);
93
94 VOID NTAPI RtlReleaseSRWLockExclusive(PSRWLOCK aLock);
95 VOID NTAPI RtlReleaseSRWLockShared(PSRWLOCK aLock);
96
97 NTSTATUS NTAPI RtlSleepConditionVariableSRW(
98 PCONDITION_VARIABLE aConditionVariable, PSRWLOCK aSRWLock,
99 PLARGE_INTEGER aTimeOut, ULONG aFlags);
100 VOID NTAPI RtlWakeAllConditionVariable(PCONDITION_VARIABLE aConditionVariable);
101
102 ULONG NTAPI RtlNtStatusToDosError(NTSTATUS aStatus);
103 VOID NTAPI RtlSetLastWin32Error(DWORD aError);
104 DWORD NTAPI RtlGetLastWin32Error();
105
106 VOID NTAPI RtlRunOnceInitialize(PRTL_RUN_ONCE aRunOnce);
107
108 NTSTATUS NTAPI NtReadVirtualMemory(HANDLE aProcessHandle, PVOID aBaseAddress,
109 PVOID aBuffer, SIZE_T aNumBytesToRead,
110 PSIZE_T aNumBytesRead);
111
112 NTSTATUS NTAPI LdrLoadDll(PWCHAR aDllPath, PULONG aFlags,
113 PUNICODE_STRING aDllName, PHANDLE aOutHandle);
114
115 typedef ULONG(NTAPI* PRTL_RUN_ONCE_INIT_FN)(PRTL_RUN_ONCE, PVOID, PVOID*);
116 NTSTATUS NTAPI RtlRunOnceExecuteOnce(PRTL_RUN_ONCE aRunOnce,
117 PRTL_RUN_ONCE_INIT_FN aInitFn,
118 PVOID aContext, PVOID* aParameter);
119
120 } // extern "C"
121
122 #endif // !defined(MOZILLA_INTERNAL_API)
123
124 extern "C" {
125 PVOID NTAPI RtlAllocateHeap(PVOID aHeapHandle, ULONG aFlags, SIZE_T aSize);
126
127 PVOID NTAPI RtlReAllocateHeap(PVOID aHeapHandle, ULONG aFlags, LPVOID aMem,
128 SIZE_T aNewSize);
129
130 BOOLEAN NTAPI RtlFreeHeap(PVOID aHeapHandle, ULONG aFlags, PVOID aHeapBase);
131
132 BOOLEAN NTAPI RtlQueryPerformanceCounter(LARGE_INTEGER* aPerfCount);
133
134 #define RTL_DUPLICATE_UNICODE_STRING_NULL_TERMINATE 1
135 #define RTL_DUPLICATE_UNICODE_STRING_ALLOCATE_NULL_STRING 2
136 NTSTATUS NTAPI RtlDuplicateUnicodeString(ULONG aFlags, PCUNICODE_STRING aSrc,
137 PUNICODE_STRING aDest);
138
139 VOID NTAPI RtlFreeUnicodeString(PUNICODE_STRING aUnicodeString);
140 } // extern "C"
141
142 namespace mozilla {
143 namespace nt {
144
145 /**
146 * This class encapsulates a UNICODE_STRING that owns its own buffer. The
147 * buffer is always NULL terminated, thus allowing us to cast to a wide C-string
148 * without requiring any mutation.
149 *
150 * We only allow creation of this owned buffer from outside XUL.
151 */
152 class AllocatedUnicodeString final {
153 public:
154 AllocatedUnicodeString() : mUnicodeString() {}
155
156 #if defined(MOZILLA_INTERNAL_API)
157 AllocatedUnicodeString(const AllocatedUnicodeString& aOther) = delete;
158
159 AllocatedUnicodeString& operator=(const AllocatedUnicodeString& aOther) =
160 delete;
161 #else
162 explicit AllocatedUnicodeString(PCUNICODE_STRING aSrc) {
163 if (!aSrc) {
164 mUnicodeString = {};
165 return;
166 }
167
168 Duplicate(aSrc);
169 }
170
171 explicit AllocatedUnicodeString(const char* aSrc) {
172 if (!aSrc) {
173 mUnicodeString = {};
174 return;
175 }
176
177 Duplicate(aSrc);
178 }
179
180 AllocatedUnicodeString(const AllocatedUnicodeString& aOther) {
181 Duplicate(&aOther.mUnicodeString);
182 }
183
184 AllocatedUnicodeString& operator=(const AllocatedUnicodeString& aOther) {
185 Clear();
186 Duplicate(&aOther.mUnicodeString);
187 return *this;
188 }
189
190 AllocatedUnicodeString& operator=(PCUNICODE_STRING aSrc) {
191 Clear();
192 Duplicate(aSrc);
193 return *this;
194 }
195 #endif // defined(MOZILLA_INTERNAL_API)
196
197 AllocatedUnicodeString(AllocatedUnicodeString&& aOther)
198 : mUnicodeString(aOther.mUnicodeString) {
199 aOther.mUnicodeString = {};
200 }
201
202 AllocatedUnicodeString& operator=(AllocatedUnicodeString&& aOther) {
203 Clear();
204 mUnicodeString = aOther.mUnicodeString;
205 aOther.mUnicodeString = {};
206 return *this;
207 }
208
209 ~AllocatedUnicodeString() { Clear(); }
210
211 bool IsEmpty() const {
212 return !mUnicodeString.Buffer || !mUnicodeString.Length;
213 }
214
215 operator PCUNICODE_STRING() const { return &mUnicodeString; }
216
217 operator const WCHAR*() const { return mUnicodeString.Buffer; }
218
219 USHORT CharLen() const { return mUnicodeString.Length / sizeof(WCHAR); }
220
221 #if defined(MOZILLA_INTERNAL_API)
222 nsDependentString AsString() const {
223 if (!mUnicodeString.Buffer) {
224 return nsDependentString();
225 }
226
227 // We can use nsDependentString here as we guaranteed null termination
228 // when we allocated the string.
229 return nsDependentString(mUnicodeString.Buffer, CharLen());
230 }
231 #endif // defined(MOZILLA_INTERNAL_API)
232
233 private:
234 #if !defined(MOZILLA_INTERNAL_API)
235 void Duplicate(PCUNICODE_STRING aSrc) {
236 MOZ_ASSERT(aSrc);
237
238 // We duplicate with null termination so that this string may be used
239 // as a wide C-string without any further manipulation.
240 NTSTATUS ntStatus = ::RtlDuplicateUnicodeString(
241 RTL_DUPLICATE_UNICODE_STRING_NULL_TERMINATE, aSrc, &mUnicodeString);
242 MOZ_ASSERT(NT_SUCCESS(ntStatus));
243 if (!NT_SUCCESS(ntStatus)) {
244 // Make sure that mUnicodeString does not contain bogus data
245 // (since not all callers zero it out before invoking)
246 mUnicodeString = {};
247 }
248 }
249
250 void Duplicate(const char* aSrc) {
251 MOZ_ASSERT(aSrc);
252
253 ANSI_STRING ansiStr;
254 RtlInitAnsiString(&ansiStr, aSrc);
255 NTSTATUS ntStatus =
256 ::RtlAnsiStringToUnicodeString(&mUnicodeString, &ansiStr, TRUE);
257 MOZ_ASSERT(NT_SUCCESS(ntStatus));
258 if (!NT_SUCCESS(ntStatus)) {
259 mUnicodeString = {};
260 }
261 }
262 #endif // !defined(MOZILLA_INTERNAL_API)
263
264 void Clear() {
265 if (!mUnicodeString.Buffer) {
266 return;
267 }
268
269 ::RtlFreeUnicodeString(&mUnicodeString);
270 mUnicodeString = {};
271 }
272
273 UNICODE_STRING mUnicodeString;
274 };
275
276 #if !defined(MOZILLA_INTERNAL_API)
277
278 struct MemorySectionNameBuf : public _MEMORY_SECTION_NAME {
279 MemorySectionNameBuf() {
280 mSectionFileName.Length = 0;
281 mSectionFileName.MaximumLength = sizeof(mBuf);
282 mSectionFileName.Buffer = mBuf;
283 }
284
285 MemorySectionNameBuf(const MemorySectionNameBuf& aOther) { *this = aOther; }
286
287 MemorySectionNameBuf(MemorySectionNameBuf&& aOther) {
288 *this = std::move(aOther);
289 }
290
291 // We cannot use default copy here because mSectionFileName.Buffer needs to
292 // be updated to point to |this->mBuf|, not |aOther.mBuf|.
293 MemorySectionNameBuf& operator=(const MemorySectionNameBuf& aOther) {
294 mSectionFileName.Length = aOther.mSectionFileName.Length;
295 mSectionFileName.MaximumLength = sizeof(mBuf);
296 MOZ_ASSERT(mSectionFileName.Length <= mSectionFileName.MaximumLength);
297 mSectionFileName.Buffer = mBuf;
298 memcpy(mBuf, aOther.mBuf, aOther.mSectionFileName.Length);
299 return *this;
300 }
301
302 MemorySectionNameBuf& operator=(MemorySectionNameBuf&& aOther) {
303 mSectionFileName.Length = aOther.mSectionFileName.Length;
304 aOther.mSectionFileName.Length = 0;
305 mSectionFileName.MaximumLength = sizeof(mBuf);
306 MOZ_ASSERT(mSectionFileName.Length <= mSectionFileName.MaximumLength);
307 aOther.mSectionFileName.MaximumLength = sizeof(aOther.mBuf);
308 mSectionFileName.Buffer = mBuf;
309 memmove(mBuf, aOther.mBuf, mSectionFileName.Length);
310 return *this;
311 }
312
313 // Native NT paths, so we can't assume MAX_PATH. Use a larger buffer.
314 WCHAR mBuf[2 * MAX_PATH];
315
316 bool IsEmpty() const {
317 return !mSectionFileName.Buffer || !mSectionFileName.Length;
318 }
319
320 operator PCUNICODE_STRING() const { return &mSectionFileName; }
321 };
322
323 class MemorySectionNameOnHeap {
324 UniquePtr<uint8_t[]> mBuffer;
325
326 MemorySectionNameOnHeap() = default;
327 explicit MemorySectionNameOnHeap(size_t aBufferLen)
328 : mBuffer(MakeUnique<uint8_t[]>(aBufferLen)) {}
329
330 public:
331 static MemorySectionNameOnHeap GetBackingFilePath(HANDLE aProcess,
332 void* aSectionAddr) {
333 SIZE_T bufferLen = MAX_PATH * 2;
334 do {
335 MemorySectionNameOnHeap sectionName(bufferLen);
336
337 SIZE_T requiredBytes;
338 NTSTATUS ntStatus = ::NtQueryVirtualMemory(
339 aProcess, aSectionAddr, MemorySectionName, sectionName.mBuffer.get(),
340 bufferLen, &requiredBytes);
341 if (NT_SUCCESS(ntStatus)) {
342 return sectionName;
343 }
344
345 if (ntStatus != STATUS_INFO_LENGTH_MISMATCH ||
346 bufferLen >= requiredBytes) {
347 break;
348 }
349
350 bufferLen = requiredBytes;
351 } while (1);
352
353 return MemorySectionNameOnHeap();
354 }
355
356 // Allow move & Disallow copy
357 MemorySectionNameOnHeap(MemorySectionNameOnHeap&&) = default;
358 MemorySectionNameOnHeap& operator=(MemorySectionNameOnHeap&&) = default;
359 MemorySectionNameOnHeap(const MemorySectionNameOnHeap&) = delete;
360 MemorySectionNameOnHeap& operator=(const MemorySectionNameOnHeap&) = delete;
361
362 PCUNICODE_STRING AsUnicodeString() const {
363 return reinterpret_cast<PCUNICODE_STRING>(mBuffer.get());
364 }
365 };
366
367 inline bool FindCharInUnicodeString(const UNICODE_STRING& aStr, WCHAR aChar,
368 uint16_t& aPos, uint16_t aStartIndex = 0) {
369 const uint16_t aMaxIndex = aStr.Length / sizeof(WCHAR);
370
371 for (uint16_t curIndex = aStartIndex; curIndex < aMaxIndex; ++curIndex) {
372 if (aStr.Buffer[curIndex] == aChar) {
373 aPos = curIndex;
374 return true;
375 }
376 }
377
378 return false;
379 }
380
381 inline bool IsHexDigit(WCHAR aChar) {
382 return (aChar >= L'0' && aChar <= L'9') || (aChar >= L'A' && aChar <= L'F') ||
383 (aChar >= L'a' && aChar <= L'f');
384 }
385
386 inline bool MatchUnicodeString(const UNICODE_STRING& aStr,
387 bool (*aPredicate)(WCHAR)) {
388 WCHAR* cur = aStr.Buffer;
389 WCHAR* end = &aStr.Buffer[aStr.Length / sizeof(WCHAR)];
390 while (cur < end) {
391 if (!aPredicate(*cur)) {
392 return false;
393 }
394
395 ++cur;
396 }
397
398 return true;
399 }
400
401 inline bool Contains12DigitHexString(const UNICODE_STRING& aLeafName) {
402 // Quick check: If the string is too short, don't bother
403 // (We need at least 12 hex digits, one char for '.', and 3 for extension)
404 const USHORT kMinLen = (12 + 1 + 3) * sizeof(wchar_t);
405 if (aLeafName.Length < kMinLen) {
406 return false;
407 }
408
409 uint16_t start, end;
410 if (!FindCharInUnicodeString(aLeafName, L'.', start)) {
411 return false;
412 }
413
414 ++start;
415 if (!FindCharInUnicodeString(aLeafName, L'.', end, start)) {
416 return false;
417 }
418
419 if (end - start != 12) {
420 return false;
421 }
422
423 UNICODE_STRING test;
424 test.Buffer = &aLeafName.Buffer[start];
425 test.Length = (end - start) * sizeof(WCHAR);
426 test.MaximumLength = test.Length;
427
428 return MatchUnicodeString(test, &IsHexDigit);
429 }
430
431 inline bool IsFileNameAtLeast16HexDigits(const UNICODE_STRING& aLeafName) {
432 // Quick check: If the string is too short, don't bother
433 // (We need 16 hex digits, one char for '.', and 3 for extension)
434 const USHORT kMinLen = (16 + 1 + 3) * sizeof(wchar_t);
435 if (aLeafName.Length < kMinLen) {
436 return false;
437 }
438
439 uint16_t dotIndex;
440 if (!FindCharInUnicodeString(aLeafName, L'.', dotIndex)) {
441 return false;
442 }
443
444 if (dotIndex < 16) {
445 return false;
446 }
447
448 UNICODE_STRING test;
449 test.Buffer = aLeafName.Buffer;
450 test.Length = dotIndex * sizeof(WCHAR);
451 test.MaximumLength = aLeafName.MaximumLength;
452
453 return MatchUnicodeString(test, &IsHexDigit);
454 }
455
456 inline void GetLeafName(PUNICODE_STRING aDestString,
457 PCUNICODE_STRING aSrcString) {
458 WCHAR* buf = aSrcString->Buffer;
459 WCHAR* end = &aSrcString->Buffer[(aSrcString->Length / sizeof(WCHAR)) - 1];
460 WCHAR* cur = end;
461 while (cur >= buf) {
462 if (*cur == L'\\') {
463 break;
464 }
465
466 --cur;
467 }
468
469 // At this point, either cur points to the final backslash, or it points to
470 // buf - 1. Either way, we're interested in cur + 1 as the desired buffer.
471 aDestString->Buffer = cur + 1;
472 aDestString->Length = (end - aDestString->Buffer + 1) * sizeof(WCHAR);
473 aDestString->MaximumLength = aDestString->Length;
474 }
475
476 #endif // !defined(MOZILLA_INTERNAL_API)
477
478 #if defined(MOZILLA_INTERNAL_API)
479
480 inline const nsDependentSubstring GetLeafName(const nsAString& aString) {
481 auto it = aString.EndReading();
482 size_t pos = aString.Length();
483 while (it > aString.BeginReading()) {
484 if (*(it - 1) == u'\\') {
485 return Substring(aString, pos);
486 }
487
488 MOZ_ASSERT(pos > 0);
489 --pos;
490 --it;
491 }
492
493 return Substring(aString, 0); // No backslash in the string
494 }
495
496 #endif // defined(MOZILLA_INTERNAL_API)
497
498 inline char EnsureLowerCaseASCII(char aChar) {
499 if (aChar >= 'A' && aChar <= 'Z') {
500 aChar -= 'A' - 'a';
501 }
502
503 return aChar;
504 }
505
506 inline int StricmpASCII(const char* aLeft, const char* aRight) {
507 char curLeft, curRight;
508
509 do {
510 curLeft = EnsureLowerCaseASCII(*(aLeft++));
511 curRight = EnsureLowerCaseASCII(*(aRight++));
512 } while (curLeft && curLeft == curRight);
513
514 return curLeft - curRight;
515 }
516
517 inline int StrcmpASCII(const char* aLeft, const char* aRight) {
518 char curLeft, curRight;
519
520 do {
521 curLeft = *(aLeft++);
522 curRight = *(aRight++);
523 } while (curLeft && curLeft == curRight);
524
525 return curLeft - curRight;
526 }
527
528 inline size_t StrlenASCII(const char* aStr) {
529 size_t len = 0;
530
531 while (*(aStr++)) {
532 ++len;
533 }
534
535 return len;
536 }
537
538 struct CodeViewRecord70 {
539 uint32_t signature;
540 GUID pdbSignature;
541 uint32_t pdbAge;
542 // A UTF-8 string, according to
543 // https://github.com/Microsoft/microsoft-pdb/blob/082c5290e5aff028ae84e43affa8be717aa7af73/PDB/dbi/locator.cpp#L785
544 char pdbFileName[1];
545 };
546
547 // The size of the object that T points at, used to bounds-check a pointer
548 // against the mapped image.
549 //
550 // void and function pointees have no meaningful compile-time extent (the
551 // former is opaque and the latter is machine code) so they fall back to a
552 // one-byte "this address is inside the image" check, which is all the caller
553 // can meaningfully assert.
554 template <typename T>
555 constexpr size_t PointeeSize() {
556 static_assert(std::is_pointer_v<T>,
557 "RVAToPtr and friends resolve an RVA to a pointer, so T must "
558 "be a pointer type");
559
560 using Pointee = std::remove_pointer_t<T>;
561 if constexpr (std::is_void_v<Pointee> || std::is_function_v<Pointee>) {
562 return 1;
563 } else {
564 return sizeof(Pointee);
565 }
566 }
567
568 class MOZ_RAII PEHeaders final {
569 /**
570 * This structure is documented on MSDN as VS_VERSIONINFO, but is not present
571 * in SDK headers because it cannot be specified as a C struct. The following
572 * structure contains the fixed-length fields at the beginning of
573 * VS_VERSIONINFO.
574 */
575 struct VS_VERSIONINFO_HEADER {
576 WORD wLength;
577 WORD wValueLength;
578 WORD wType;
579 WCHAR szKey[16]; // std::size(L"VS_VERSION_INFO")
580 // Additional data goes here, aligned on a 4-byte boundary
581 };
582
583 public:
584 // The lowest two bits of an HMODULE are used as flags. Stripping those bits
585 // from the HMODULE yields the base address of the binary's memory mapping.
586 // (See LoadLibraryEx docs on MSDN)
587 template <typename T>
588 static T HModuleToBaseAddr(HMODULE aModule) {
589 return reinterpret_cast<T>(reinterpret_cast<uintptr_t>(aModule) &
590 ~uintptr_t(3));
591 }
592
593 explicit PEHeaders(void* aBaseAddress)
594 : PEHeaders(reinterpret_cast<PIMAGE_DOS_HEADER>(aBaseAddress)) {}
595
596 explicit PEHeaders(HMODULE aModule)
597 : PEHeaders(HModuleToBaseAddr<PIMAGE_DOS_HEADER>(aModule)) {}
598
599 explicit PEHeaders(PIMAGE_DOS_HEADER aMzHeader)
600 : mMzHeader(aMzHeader),
601 mPeHeader(nullptr),
602 mImageLimit(nullptr),
603 mIsImportDirectoryTampered(false) {
604 if (!mMzHeader || mMzHeader->e_magic != IMAGE_DOS_SIGNATURE) {
605 return;
606 }
607
608 mPeHeader = RVAToPtrUnchecked<PIMAGE_NT_HEADERS>(mMzHeader->e_lfanew);
609 if (!mPeHeader || mPeHeader->Signature != IMAGE_NT_SIGNATURE) {
610 return;
611 }
612
613 if (mPeHeader->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC) {
614 return;
615 }
616
617 DWORD imageSize = mPeHeader->OptionalHeader.SizeOfImage;
618 // This is a coarse-grained check to ensure that the image size is
619 // reasonable. It we aren't big enough to contain headers, we have a
620 // problem!
621 if (imageSize < sizeof(IMAGE_DOS_HEADER) + sizeof(IMAGE_NT_HEADERS)) {
622 return;
623 }
624
625 mImageLimit = RVAToPtrUnchecked<void*>(imageSize - 1UL);
626
627 PIMAGE_DATA_DIRECTORY importDirEntry =
628 GetImageDirectoryEntryPtr(IMAGE_DIRECTORY_ENTRY_IMPORT);
629 if (!importDirEntry) {
630 return;
631 }
632
633 mIsImportDirectoryTampered = (importDirEntry->VirtualAddress >= imageSize);
634 }
635
636 explicit operator bool() const { return !!mImageLimit; }
637
638 /**
639 * This overload computes absolute virtual addresses relative to the base
640 * address of the binary.
641 */
642 template <typename T, typename R>
643 T RVAToPtr(R aRva) const {
644 return RVAToPtr<T>(mMzHeader, aRva);
645 }
646
647 /**
648 * This overload computes a result by adding aRva to aBase and ensures
649 * that the resulting pointer falls within the bounds of this binary's memory
650 * mapping.
651 */
652 template <typename T, typename R, size_t Size = PointeeSize<T>()>
653 T RVAToPtr(void* aBase, R aRva) const {
654 if (!mImageLimit) {
655 return nullptr;
656 }
657
658 // aBase is not always the image base (some callers resolve offsets that
659 // are relative to a resource directory or to the optional header), so
660 // convert back to an image-relative RVA before bounds checking.
661 char* imageBase = reinterpret_cast<char*>(mMzHeader);
662 char* absAddress = reinterpret_cast<char*>(aBase) + aRva;
663 if (absAddress < imageBase) {
664 return nullptr;
665 }
666
667 return RVAToPtrChecked<T>(static_cast<uintptr_t>(absAddress - imageBase),
668 Size);
669 }
670
671 /**
672 * Like RVAToPtr, but ensures that the whole range [aRva, aRva + aSize) --
673 * not just its first byte -- falls within the bounds of this binary's memory
674 * mapping. Use this whenever the caller is going to dereference more than a
675 * single byte at the resulting address.
676 */
677 template <typename T, typename R>
678 T RVAToPtrChecked(R aRva, size_t aSize) const {
679 if (!mImageLimit || !aSize) {
680 return nullptr;
681 }
682
683 uintptr_t base = reinterpret_cast<uintptr_t>(mMzHeader);
684 // mImageLimit points at the last valid byte of the mapping.
685 uintptr_t available = reinterpret_cast<uintptr_t>(mImageLimit) - base + 1u;
686
687 uintptr_t rva = static_cast<uintptr_t>(aRva);
688 if (rva >= available || aSize > available - rva) {
689 return nullptr;
690 }
691
692 return reinterpret_cast<T>(base + rva);
693 }
694
695 Maybe<Range<const uint8_t>> GetBounds() const {
696 if (!mImageLimit) {
697 return Nothing();
698 }
699
700 auto base = reinterpret_cast<const uint8_t*>(mMzHeader);
701 DWORD imageSize = mPeHeader->OptionalHeader.SizeOfImage;
702 return Some(Range(base, imageSize));
703 }
704
705 DWORD GetFileCharacteristics() const {
706 return mPeHeader ? mPeHeader->FileHeader.Characteristics : 0;
707 }
708
709 bool IsWithinImage(const void* aAddress) const {
710 uintptr_t addr = reinterpret_cast<uintptr_t>(aAddress);
711 uintptr_t imageBase = reinterpret_cast<uintptr_t>(mMzHeader);
712 uintptr_t imageLimit = reinterpret_cast<uintptr_t>(mImageLimit);
713 return addr >= imageBase && addr <= imageLimit;
714 }
715
716 PIMAGE_IMPORT_DESCRIPTOR GetImportDirectory() const {
717 // If the import directory is already tampered, we skip bounds check
718 // because it could be located outside the mapped image.
719 return mIsImportDirectoryTampered
720 ? GetImageDirectoryEntry<PIMAGE_IMPORT_DESCRIPTOR,
721 BoundsCheckPolicy::Skip>(
722 IMAGE_DIRECTORY_ENTRY_IMPORT)
723 : GetImageDirectoryEntry<PIMAGE_IMPORT_DESCRIPTOR>(
724 IMAGE_DIRECTORY_ENTRY_IMPORT);
725 }
726
727 PIMAGE_RESOURCE_DIRECTORY GetResourceTable() const {
728 return GetImageDirectoryEntry<PIMAGE_RESOURCE_DIRECTORY>(
729 IMAGE_DIRECTORY_ENTRY_RESOURCE);
730 }
731
732 PIMAGE_DATA_DIRECTORY GetImageDirectoryEntryPtr(
733 const uint32_t aDirectoryIndex, uint32_t* aOutRva = nullptr) const {
734 if (aOutRva) {
735 *aOutRva = 0;
736 }
737
738 IMAGE_OPTIONAL_HEADER& optionalHeader = mPeHeader->OptionalHeader;
739
740 const uint32_t maxIndex = std::min(optionalHeader.NumberOfRvaAndSizes,
741 DWORD(IMAGE_NUMBEROF_DIRECTORY_ENTRIES));
742 if (aDirectoryIndex >= maxIndex) {
743 return nullptr;
744 }
745
746 PIMAGE_DATA_DIRECTORY dirEntry =
747 &optionalHeader.DataDirectory[aDirectoryIndex];
748 if (aOutRva) {
749 *aOutRva = reinterpret_cast<char*>(dirEntry) -
750 reinterpret_cast<char*>(mMzHeader);
751 MOZ_ASSERT(*aOutRva);
752 }
753
754 return dirEntry;
755 }
756
757 bool GetVersionInfo(uint64_t& aOutVersion) const {
758 // RT_VERSION == 16
759 // Version resources require an id of 1
760 auto root = FindResourceLeaf<VS_VERSIONINFO_HEADER*>(16, 1);
761 if (!root) {
762 return false;
763 }
764
765 VS_FIXEDFILEINFO* fixedInfo = GetFixedFileInfo(root);
766 if (!fixedInfo) {
767 return false;
768 }
769
770 aOutVersion = ((static_cast<uint64_t>(fixedInfo->dwFileVersionMS) << 32) |
771 static_cast<uint64_t>(fixedInfo->dwFileVersionLS));
772 return true;
773 }
774
775 bool GetTimeStamp(DWORD& aResult) const {
776 if (!(*this)) {
777 return false;
778 }
779
780 aResult = mPeHeader->FileHeader.TimeDateStamp;
781 return true;
782 }
783
784 bool GetImageSize(DWORD& aResult) const {
785 if (!(*this)) {
786 return false;
787 }
788
789 aResult = mPeHeader->OptionalHeader.SizeOfImage;
790 return true;
791 }
792
793 bool GetCheckSum(DWORD& aResult) const {
794 if (!(*this)) {
795 return false;
796 }
797
798 aResult = mPeHeader->OptionalHeader.CheckSum;
799 return true;
800 }
801
802 PIMAGE_IMPORT_DESCRIPTOR
803 GetImportDescriptor(const char* aModuleNameASCII) const {
804 for (PIMAGE_IMPORT_DESCRIPTOR curImpDesc = GetImportDirectory();
805 IsValid(curImpDesc); ++curImpDesc) {
806 auto curName = mIsImportDirectoryTampered
807 ? RVAToPtrUnchecked<const char*>(curImpDesc->Name)
808 : RVAToPtr<const char*>(curImpDesc->Name);
809 if (!curName) {
810 return nullptr;
811 }
812
813 if (StricmpASCII(aModuleNameASCII, curName)) {
814 continue;
815 }
816
817 // curImpDesc now points to the IAT for the module we're interested in
818 return curImpDesc;
819 }
820
821 return nullptr;
822 }
823
824 template <typename CallbackT>
825 void EnumImportChunks(const CallbackT& aCallback) const {
826 for (PIMAGE_IMPORT_DESCRIPTOR curImpDesc = GetImportDirectory();
827 IsValid(curImpDesc); ++curImpDesc) {
828 auto curName = mIsImportDirectoryTampered
829 ? RVAToPtrUnchecked<const char*>(curImpDesc->Name)
830 : RVAToPtr<const char*>(curImpDesc->Name);
831 if (!curName) {
832 continue;
833 }
834
835 aCallback(curName);
836 }
837 }
838
839 /**
840 * If |aBoundaries| is given, this method checks whether each IAT entry is
841 * within the given range, and if any entry is out of the range, we return
842 * Nothing().
843 */
844 Maybe<Span<IMAGE_THUNK_DATA>> GetIATThunksForModule(
845 const char* aModuleNameASCII,
846 const Range<const uint8_t>* aBoundaries = nullptr) const {
847 PIMAGE_IMPORT_DESCRIPTOR impDesc = GetImportDescriptor(aModuleNameASCII);
848 if (!impDesc) {
849 return Nothing();
850 }
851
852 auto firstIatThunk =
853 this->template RVAToPtr<PIMAGE_THUNK_DATA>(impDesc->FirstThunk);
854 if (!firstIatThunk) {
855 return Nothing();
856 }
857
858 // Find the length by iterating through the table until we find a null entry
859 PIMAGE_THUNK_DATA curIatThunk = firstIatThunk;
860 while (IsValid(curIatThunk)) {
861 if (aBoundaries) {
862 auto iatEntry =
863 reinterpret_cast<const uint8_t*>(curIatThunk->u1.Function);
864 if (iatEntry < aBoundaries->begin().get() ||
865 iatEntry >= aBoundaries->end().get()) {
866 return Nothing();
867 }
868 }
869
870 ++curIatThunk;
871 }
872
873 return Some(Span(firstIatThunk, curIatThunk));
874 }
875
876 /**
877 * Resources are stored in a three-level tree. To locate a particular entry,
878 * you must supply a resource type, the resource id, and then the language id.
879 * If aLangId == 0, we just resolve the first entry regardless of language.
880 */
881 template <typename T>
882 T FindResourceLeaf(WORD aType, WORD aResId, WORD aLangId = 0) const {
883 PIMAGE_RESOURCE_DIRECTORY topLevel = GetResourceTable();
884 if (!topLevel) {
885 return nullptr;
886 }
887
888 PIMAGE_RESOURCE_DIRECTORY_ENTRY typeEntry =
889 FindResourceEntry(topLevel, aType);
890 if (!typeEntry || !typeEntry->DataIsDirectory) {
891 return nullptr;
892 }
893
894 auto idDir = RVAToPtr<PIMAGE_RESOURCE_DIRECTORY>(
895 topLevel, typeEntry->OffsetToDirectory);
896 PIMAGE_RESOURCE_DIRECTORY_ENTRY idEntry = FindResourceEntry(idDir, aResId);
897 if (!idEntry || !idEntry->DataIsDirectory) {
898 return nullptr;
899 }
900
901 auto langDir = RVAToPtr<PIMAGE_RESOURCE_DIRECTORY>(
902 topLevel, idEntry->OffsetToDirectory);
903 PIMAGE_RESOURCE_DIRECTORY_ENTRY langEntry;
904 if (aLangId) {
905 langEntry = FindResourceEntry(langDir, aLangId);
906 } else {
907 langEntry = FindFirstResourceEntry(langDir);
908 }
909
910 if (!langEntry || langEntry->DataIsDirectory) {
911 return nullptr;
912 }
913
914 auto dataEntry =
915 RVAToPtr<PIMAGE_RESOURCE_DATA_ENTRY>(topLevel, langEntry->OffsetToData);
916 return dataEntry ? RVAToPtr<T>(dataEntry->OffsetToData) : nullptr;
917 }
918
919 template <size_t N>
920 Maybe<Span<const uint8_t>> FindSection(const char (&aSecName)[N],
921 DWORD aCharacteristicsMask) const {
922 static_assert((N - 1) <= IMAGE_SIZEOF_SHORT_NAME,
923 "Section names must be at most 8 characters excluding null "
924 "terminator");
925
926 if (!(*this)) {
927 return Nothing();
928 }
929
930 Span<IMAGE_SECTION_HEADER> sectionTable = GetSectionTable();
931 for (auto&& sectionHeader : sectionTable) {
932 if (strncmp(reinterpret_cast<const char*>(sectionHeader.Name), aSecName,
933 IMAGE_SIZEOF_SHORT_NAME)) {
934 continue;
935 }
936
937 if (!(sectionHeader.Characteristics & aCharacteristicsMask)) {
938 // We found the section but it does not have the expected
939 // characteristics
940 return Nothing();
941 }
942
943 DWORD rva = sectionHeader.VirtualAddress;
944 if (!rva) {
945 return Nothing();
946 }
947
948 DWORD size = sectionHeader.Misc.VirtualSize;
949 if (!size) {
950 return Nothing();
951 }
952
953 auto base = RVAToPtr<const uint8_t*>(rva);
954 return Some(Span(base, size));
955 }
956
957 return Nothing();
958 }
959
960 // There may be other code sections in the binary besides .text
961 Maybe<Span<const uint8_t>> GetTextSectionInfo() const {
962 return FindSection(".text", IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE |
963 IMAGE_SCN_MEM_READ);
964 }
965
966 // There may be other data sections in the binary besides .data
967 Maybe<Span<const uint8_t>> GetDataSectionInfo() const {
968 return FindSection(".data", IMAGE_SCN_CNT_INITIALIZED_DATA |
969 IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE);
970 }
971
972 static bool IsValid(PIMAGE_IMPORT_DESCRIPTOR aImpDesc) {
973 return aImpDesc && aImpDesc->OriginalFirstThunk != 0;
974 }
975
976 static bool IsValid(PIMAGE_THUNK_DATA aImgThunk) {
977 return aImgThunk && aImgThunk->u1.Ordinal != 0;
978 }
979
980 bool IsImportDirectoryTampered() const { return mIsImportDirectoryTampered; }
981
982 FARPROC GetEntryPoint() const {
983 // Use the unchecked version because the entrypoint may be tampered.
984 return RVAToPtrUnchecked<FARPROC>(
985 mPeHeader->OptionalHeader.AddressOfEntryPoint);
986 }
987
988 const CodeViewRecord70* GetPdbInfo() const {
989 PIMAGE_DATA_DIRECTORY dirEntry =
990 GetImageDirectoryEntryPtr(IMAGE_DIRECTORY_ENTRY_DEBUG);
991 if (!dirEntry || dirEntry->Size < sizeof(IMAGE_DEBUG_DIRECTORY)) {
992 return nullptr;
993 }
994
995 auto debugDirectory = RVAToPtrChecked<PIMAGE_DEBUG_DIRECTORY>(
996 dirEntry->VirtualAddress, sizeof(IMAGE_DEBUG_DIRECTORY));
997 if (!debugDirectory) {
998 return nullptr;
999 }
1000
1001 // The record needs to be big enough for the fixed-size fields plus at
1002 // least the null terminator of pdbFileName.
1003 constexpr size_t kMinRecordSize =
1004 offsetof(CodeViewRecord70, pdbFileName) + 1;
1005 if (debugDirectory->SizeOfData < kMinRecordSize) {
1006 return nullptr;
1007 }
1008
1009 auto debugInfo = RVAToPtrChecked<const CodeViewRecord70*>(
1010 debugDirectory->AddressOfRawData, debugDirectory->SizeOfData);
1011 if (!debugInfo || debugInfo->signature != 'SDSR') {
1012 return nullptr;
1013 }
1014
1015 // Callers treat pdbFileName as a C string, so it must be terminated inside
1016 // the record.
1017 const size_t nameCapacity =
1018 debugDirectory->SizeOfData - offsetof(CodeViewRecord70, pdbFileName);
1019 for (size_t i = 0; i < nameCapacity; ++i) {
1020 if (!debugInfo->pdbFileName[i]) {
1021 // terminated, so succeed
1022 return debugInfo;
1023 }
1024 }
1025
1026 // not terminated, so fail
1027 return nullptr;
1028 }
1029
1030 private:
1031 enum class BoundsCheckPolicy { Default, Skip };
1032
1033 template <typename T, BoundsCheckPolicy Policy = BoundsCheckPolicy::Default>
1034 T GetImageDirectoryEntry(const uint32_t aDirectoryIndex) const {
1035 PIMAGE_DATA_DIRECTORY dirEntry = GetImageDirectoryEntryPtr(aDirectoryIndex);
1036 if (!dirEntry) {
1037 return nullptr;
1038 }
1039
1040 return Policy == BoundsCheckPolicy::Skip
1041 ? RVAToPtrUnchecked<T>(dirEntry->VirtualAddress)
1042 : RVAToPtr<T>(dirEntry->VirtualAddress);
1043 }
1044
1045 // This private variant does not have bounds checks, because we need to be
1046 // able to resolve the bounds themselves.
1047 template <typename T, typename R>
1048 T RVAToPtrUnchecked(R aRva) const {
1049 return reinterpret_cast<T>(reinterpret_cast<char*>(mMzHeader) + aRva);
1050 }
1051
1052 Span<IMAGE_SECTION_HEADER> GetSectionTable() const {
1053 MOZ_ASSERT(*this);
1054 auto base = RVAToPtr<PIMAGE_SECTION_HEADER>(
1055 &mPeHeader->OptionalHeader, mPeHeader->FileHeader.SizeOfOptionalHeader);
1056 // The Windows loader has an internal limit of 96 sections (per PE spec)
1057 auto numSections =
1058 std::min(mPeHeader->FileHeader.NumberOfSections, WORD(96));
1059 return Span{base, numSections};
1060 }
1061
1062 PIMAGE_RESOURCE_DIRECTORY_ENTRY
1063 FindResourceEntry(PIMAGE_RESOURCE_DIRECTORY aCurLevel, WORD aId) const {
1064 if (!aCurLevel) {
1065 return nullptr;
1066 }
1067
1068 // Immediately after the IMAGE_RESOURCE_DIRECTORY structure is an array
1069 // of IMAGE_RESOURCE_DIRECTORY_ENTRY structures. Since this function
1070 // searches by ID, we need to skip past any named entries before iterating.
1071 auto dirEnt =
1072 reinterpret_cast<PIMAGE_RESOURCE_DIRECTORY_ENTRY>(aCurLevel + 1) +
1073 aCurLevel->NumberOfNamedEntries;
1074 if (!(IsWithinImage(dirEnt) &&
1075 IsWithinImage(&dirEnt[aCurLevel->NumberOfIdEntries - 1].Id))) {
1076 return nullptr;
1077 }
1078
1079 for (WORD i = 0; i < aCurLevel->NumberOfIdEntries; ++i) {
1080 if (dirEnt[i].Id == aId) {
1081 return &dirEnt[i];
1082 }
1083 }
1084
1085 return nullptr;
1086 }
1087
1088 PIMAGE_RESOURCE_DIRECTORY_ENTRY
1089 FindFirstResourceEntry(PIMAGE_RESOURCE_DIRECTORY aCurLevel) const {
1090 // Immediately after the IMAGE_RESOURCE_DIRECTORY structure is an array
1091 // of IMAGE_RESOURCE_DIRECTORY_ENTRY structures. We just return the first
1092 // entry, regardless of whether it is indexed by name or by id.
1093 auto dirEnt =
1094 reinterpret_cast<PIMAGE_RESOURCE_DIRECTORY_ENTRY>(aCurLevel + 1);
1095 WORD numEntries =
1096 aCurLevel->NumberOfNamedEntries + aCurLevel->NumberOfIdEntries;
1097 if (!numEntries) {
1098 return nullptr;
1099 }
1100
1101 return dirEnt;
1102 }
1103
1104 VS_FIXEDFILEINFO* GetFixedFileInfo(VS_VERSIONINFO_HEADER* aVerInfo) const {
1105 WORD length = aVerInfo->wLength;
1106 if (length < sizeof(VS_VERSIONINFO_HEADER)) {
1107 return nullptr;
1108 }
1109
1110 const wchar_t kVersionInfoKey[] = L"VS_VERSION_INFO";
1111 if (::RtlCompareMemory(aVerInfo->szKey, kVersionInfoKey,
1112 std::size(kVersionInfoKey)) !=
1113 std::size(kVersionInfoKey)) {
1114 return nullptr;
1115 }
1116
1117 if (aVerInfo->wValueLength != sizeof(VS_FIXEDFILEINFO)) {
1118 // Fixed file info does not exist
1119 return nullptr;
1120 }
1121
1122 WORD offset = sizeof(VS_VERSIONINFO_HEADER);
1123
1124 uintptr_t base = reinterpret_cast<uintptr_t>(aVerInfo);
1125 // Align up to 4-byte boundary
1126 #pragma warning(suppress : 4146)
1127 offset += (-(base + offset) & 3);
1128
1129 if (offset >= length) {
1130 return nullptr;
1131 }
1132
1133 auto result = reinterpret_cast<VS_FIXEDFILEINFO*>(base + offset);
1134 if (result->dwSignature != 0xFEEF04BD) {
1135 return nullptr;
1136 }
1137
1138 return result;
1139 }
1140
1141 private:
1142 PIMAGE_DOS_HEADER mMzHeader;
1143 PIMAGE_NT_HEADERS mPeHeader;
1144 void* mImageLimit;
1145 bool mIsImportDirectoryTampered;
1146 };
1147
1148 // This class represents an export section of a local/remote process.
1149 template <typename MMPolicy>
1150 class MOZ_RAII PEExportSection {
1151 const MMPolicy& mMMPolicy;
1152 uintptr_t mImageBase;
1153 DWORD mOrdinalBase;
1154 DWORD mRvaDirStart;
1155 DWORD mRvaDirEnd;
1156 mozilla::interceptor::TargetObjectArray<MMPolicy, DWORD> mExportAddressTable;
1157 mozilla::interceptor::TargetObjectArray<MMPolicy, DWORD> mExportNameTable;
1158 mozilla::interceptor::TargetObjectArray<MMPolicy, WORD> mExportOrdinalTable;
1159
1160 explicit PEExportSection(const MMPolicy& aMMPolicy)
1161 : mMMPolicy(aMMPolicy),
1162 mImageBase(0),
1163 mOrdinalBase(0),
1164 mRvaDirStart(0),
1165 mRvaDirEnd(0),
1166 mExportAddressTable(mMMPolicy),
1167 mExportNameTable(mMMPolicy),
1168 mExportOrdinalTable(mMMPolicy) {}
1169
1170 PEExportSection(const MMPolicy& aMMPolicy, uintptr_t aImageBase,
1171 DWORD aRvaDirStart, DWORD aRvaDirEnd,
1172 const IMAGE_EXPORT_DIRECTORY& exportDir)
1173 : mMMPolicy(aMMPolicy),
1174 mImageBase(aImageBase),
1175 mOrdinalBase(exportDir.Base),
1176 mRvaDirStart(aRvaDirStart),
1177 mRvaDirEnd(aRvaDirEnd),
1178 mExportAddressTable(mMMPolicy,
1179 mImageBase + exportDir.AddressOfFunctions,
1180 exportDir.NumberOfFunctions),
1181 mExportNameTable(mMMPolicy, mImageBase + exportDir.AddressOfNames,
1182 exportDir.NumberOfNames),
1183 mExportOrdinalTable(mMMPolicy,
1184 mImageBase + exportDir.AddressOfNameOrdinals,
1185 exportDir.NumberOfNames) {}
1186
1187 static const PEExportSection Get(uintptr_t aImageBase,
1188 const MMPolicy& aMMPolicy) {
1189 mozilla::interceptor::TargetObject<MMPolicy, IMAGE_DOS_HEADER> mzHeader(
1190 aMMPolicy, aImageBase);
1191 if (!mzHeader || mzHeader->e_magic != IMAGE_DOS_SIGNATURE) {
1192 return PEExportSection(aMMPolicy);
1193 }
1194
1195 mozilla::interceptor::TargetObject<MMPolicy, IMAGE_NT_HEADERS> peHeader(
1196 aMMPolicy, aImageBase + mzHeader->e_lfanew);
1197 if (!peHeader || peHeader->Signature != IMAGE_NT_SIGNATURE) {
1198 return PEExportSection(aMMPolicy);
1199 }
1200
1201 if (peHeader->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC) {
1202 return PEExportSection(aMMPolicy);
1203 }
1204
1205 const IMAGE_OPTIONAL_HEADER& optionalHeader = peHeader->OptionalHeader;
1206
1207 DWORD imageSize = optionalHeader.SizeOfImage;
1208 // This is a coarse-grained check to ensure that the image size is
1209 // reasonable. It we aren't big enough to contain headers, we have a
1210 // problem!
1211 if (imageSize < sizeof(IMAGE_DOS_HEADER) + sizeof(IMAGE_NT_HEADERS)) {
1212 return PEExportSection(aMMPolicy);
1213 }
1214
1215 if (optionalHeader.NumberOfRvaAndSizes <= IMAGE_DIRECTORY_ENTRY_EXPORT) {
1216 return PEExportSection(aMMPolicy);
1217 }
1218
1219 const IMAGE_DATA_DIRECTORY& exportDirectoryEntry =
1220 optionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
1221 if (!exportDirectoryEntry.VirtualAddress || !exportDirectoryEntry.Size) {
1222 return PEExportSection(aMMPolicy);
1223 }
1224
1225 mozilla::interceptor::TargetObject<MMPolicy, IMAGE_EXPORT_DIRECTORY>
1226 exportDirectory(aMMPolicy,
1227 aImageBase + exportDirectoryEntry.VirtualAddress);
1228 if (!exportDirectory || !exportDirectory->NumberOfFunctions) {
1229 return PEExportSection(aMMPolicy);
1230 }
1231
1232 return PEExportSection(
1233 aMMPolicy, aImageBase, exportDirectoryEntry.VirtualAddress,
1234 exportDirectoryEntry.VirtualAddress + exportDirectoryEntry.Size,
1235 *exportDirectory.GetLocalBase());
1236 }
1237
1238 FARPROC GetProcAddressByOrdinal(WORD aOrdinal) const {
1239 if (aOrdinal < mOrdinalBase) {
1240 return nullptr;
1241 }
1242
1243 auto rvaToFunction = mExportAddressTable[aOrdinal - mOrdinalBase];
1244 if (!rvaToFunction) {
1245 return nullptr;
1246 }
1247 return reinterpret_cast<FARPROC>(mImageBase + *rvaToFunction);
1248 }
1249
1250 public:
1251 static const PEExportSection Get(HMODULE aModule, const MMPolicy& aMMPolicy) {
1252 return Get(PEHeaders::HModuleToBaseAddr<uintptr_t>(aModule), aMMPolicy);
1253 }
1254
1255 explicit operator bool() const {
1256 // Because PEExportSection doesn't use MMPolicy::Reserve(), a boolified
1257 // mMMPolicy is expected to be false. We don't check mMMPolicy here.
1258 return mImageBase && mRvaDirStart && mRvaDirEnd && mExportAddressTable &&
1259 mExportNameTable && mExportOrdinalTable;
1260 }
1261
1262 template <typename T>
1263 T RVAToPtr(uint32_t aRva) const {
1264 return reinterpret_cast<T>(mImageBase + aRva);
1265 }
1266
1267 PIMAGE_EXPORT_DIRECTORY GetExportDirectory() const {
1268 if (!*this) {
1269 return nullptr;
1270 }
1271
1272 return RVAToPtr<PIMAGE_EXPORT_DIRECTORY>(mRvaDirStart);
1273 }
1274
1275 /**
1276 * This functions searches the export table for a given string as
1277 * GetProcAddress does, but this returns a matched entry of the Export
1278 * Address Table i.e. a pointer to an RVA of a matched function instead
1279 * of a function address. If the entry is forwarded, this function
1280 * returns nullptr.
1281 */
1282 const DWORD* FindExportAddressTableEntry(
1283 const char* aFunctionNameASCII) const {
1284 if (!*this || !aFunctionNameASCII) {
1285 return nullptr;
1286 }
1287
1288 struct NameTableComparator {
1289 NameTableComparator(const PEExportSection<MMPolicy>& aExportSection,
1290 const char* aTarget)
1291 : mExportSection(aExportSection),
1292 mTargetName(aTarget),
1293 mTargetNamelength(StrlenASCII(aTarget)) {}
1294
1295 int operator()(DWORD aRVAToString) const {
1296 mozilla::interceptor::TargetObjectArray<MMPolicy, char> itemString(
1297 mExportSection.mMMPolicy, mExportSection.mImageBase + aRVAToString,
1298 mTargetNamelength + 1);
1299 return StrcmpASCII(mTargetName, itemString[0]);
1300 }
1301
1302 const PEExportSection<MMPolicy>& mExportSection;
1303 const char* mTargetName;
1304 size_t mTargetNamelength;
1305 };
1306
1307 const NameTableComparator comp(*this, aFunctionNameASCII);
1308
1309 size_t match;
1310 if (!mExportNameTable.BinarySearchIf(comp, &match)) {
1311 return nullptr;
1312 }
1313
1314 const WORD* index = mExportOrdinalTable[match];
1315 if (!index) {
1316 return nullptr;
1317 }
1318
1319 const DWORD* rvaToFunction = mExportAddressTable[*index];
1320 if (!rvaToFunction) {
1321 return nullptr;
1322 }
1323
1324 if (*rvaToFunction >= mRvaDirStart && *rvaToFunction < mRvaDirEnd) {
1325 // If an entry points to an address within the export section, the
1326 // field is a forwarder RVA. We return nullptr because the entry is
1327 // not a function address but a null-terminated string used for export
1328 // forwarding.
1329 return nullptr;
1330 }
1331
1332 return rvaToFunction;
1333 }
1334
1335 /**
1336 * This functions behaves the same as the native ::GetProcAddress except
1337 * the following cases:
1338 * - Returns nullptr if a target entry is forwarded to another dll.
1339 */
1340 FARPROC GetProcAddress(const char* aFunctionNameASCII) const {
1341 uintptr_t maybeOdrinal = reinterpret_cast<uintptr_t>(aFunctionNameASCII);
1342 // When the high-order word of |aFunctionNameASCII| is zero, it's not
1343 // a string but an ordinal value.
1344 if (maybeOdrinal < 0x10000) {
1345 return GetProcAddressByOrdinal(static_cast<WORD>(maybeOdrinal));
1346 }
1347
1348 auto rvaToFunction = FindExportAddressTableEntry(aFunctionNameASCII);
1349 if (!rvaToFunction) {
1350 return nullptr;
1351 }
1352 return reinterpret_cast<FARPROC>(mImageBase + *rvaToFunction);
1353 }
1354 };
1355
1356 inline HANDLE RtlGetProcessHeap() {
1357 PTEB teb = ::NtCurrentTeb();
1358 PPEB peb = teb->ProcessEnvironmentBlock;
1359 return peb->Reserved4[1];
1360 }
1361
1362 inline PVOID RtlGetThreadLocalStoragePointer() {
1363 return ::NtCurrentTeb()->Reserved1[11];
1364 }
1365
1366 inline void RtlSetThreadLocalStoragePointerForTestingOnly(PVOID aNewValue) {
1367 ::NtCurrentTeb()->Reserved1[11] = aNewValue;
1368 }
1369
1370 inline DWORD RtlGetCurrentThreadId() {
1371 PTEB teb = ::NtCurrentTeb();
1372 CLIENT_ID* cid = reinterpret_cast<CLIENT_ID*>(&teb->Reserved1[8]);
1373 return static_cast<DWORD>(reinterpret_cast<uintptr_t>(cid->UniqueThread) &
1374 0xFFFFFFFFUL);
1375 }
1376
1377 inline PVOID RtlGetThreadStackBase() {
1378 return reinterpret_cast<_NT_TIB*>(::NtCurrentTeb())->StackBase;
1379 }
1380
1381 inline PVOID RtlGetThreadStackLimit() {
1382 return reinterpret_cast<_NT_TIB*>(::NtCurrentTeb())->StackLimit;
1383 }
1384
1385 const HANDLE kCurrentProcess = reinterpret_cast<HANDLE>(-1);
1386
1387 inline LauncherResult<DWORD> GetParentProcessId() {
1388 struct PROCESS_BASIC_INFORMATION {
1389 NTSTATUS ExitStatus;
1390 PPEB PebBaseAddress;
1391 ULONG_PTR AffinityMask;
1392 LONG BasePriority;
1393 ULONG_PTR UniqueProcessId;
1394 ULONG_PTR InheritedFromUniqueProcessId;
1395 };
1396
1397 ULONG returnLength;
1398 PROCESS_BASIC_INFORMATION pbi = {};
1399 NTSTATUS status =
1400 ::NtQueryInformationProcess(kCurrentProcess, ProcessBasicInformation,
1401 &pbi, sizeof(pbi), &returnLength);
1402 if (!NT_SUCCESS(status)) {
1403 return LAUNCHER_ERROR_FROM_NTSTATUS(status);
1404 }
1405
1406 return static_cast<DWORD>(pbi.InheritedFromUniqueProcessId & 0xFFFFFFFF);
1407 }
1408
1409 inline SIZE_T WINAPI VirtualQueryEx(HANDLE aProcess, LPCVOID aAddress,
1410 PMEMORY_BASIC_INFORMATION aMemInfo,
1411 SIZE_T aMemInfoLen) {
1412 #if defined(MOZILLA_INTERNAL_API)
1413 return ::VirtualQueryEx(aProcess, aAddress, aMemInfo, aMemInfoLen);
1414 #else
1415 SIZE_T returnedLength;
1416 NTSTATUS status = ::NtQueryVirtualMemory(
1417 aProcess, const_cast<PVOID>(aAddress), MemoryBasicInformation, aMemInfo,
1418 aMemInfoLen, &returnedLength);
1419 if (!NT_SUCCESS(status)) {
1420 ::RtlSetLastWin32Error(::RtlNtStatusToDosError(status));
1421 returnedLength = 0;
1422 }
1423 return returnedLength;
1424 #endif // defined(MOZILLA_INTERNAL_API)
1425 }
1426
1427 inline SIZE_T WINAPI VirtualQuery(LPCVOID aAddress,
1428 PMEMORY_BASIC_INFORMATION aMemInfo,
1429 SIZE_T aMemInfoLen) {
1430 return nt::VirtualQueryEx(kCurrentProcess, aAddress, aMemInfo, aMemInfoLen);
1431 }
1432
1433 struct DataDirectoryEntry : public _IMAGE_DATA_DIRECTORY {
1434 DataDirectoryEntry() : _IMAGE_DATA_DIRECTORY() {}
1435
1436 MOZ_IMPLICIT DataDirectoryEntry(const _IMAGE_DATA_DIRECTORY& aOther)
1437 : _IMAGE_DATA_DIRECTORY(aOther) {}
1438
1439 DataDirectoryEntry(const DataDirectoryEntry& aOther) = default;
1440
1441 bool operator==(const DataDirectoryEntry& aOther) const {
1442 return VirtualAddress == aOther.VirtualAddress && Size == aOther.Size;
1443 }
1444
1445 bool operator!=(const DataDirectoryEntry& aOther) const {
1446 return !(*this == aOther);
1447 }
1448 };
1449
1450 inline LauncherResult<void*> GetProcessPebPtr(HANDLE aProcess) {
1451 ULONG returnLength;
1452 PROCESS_BASIC_INFORMATION pbi;
1453 NTSTATUS status = ::NtQueryInformationProcess(
1454 aProcess, ProcessBasicInformation, &pbi, sizeof(pbi), &returnLength);
1455 if (!NT_SUCCESS(status)) {
1456 return LAUNCHER_ERROR_FROM_NTSTATUS(status);
1457 }
1458
1459 return pbi.PebBaseAddress;
1460 }
1461
1462 /**
1463 * This function relies on a specific offset into the mostly-undocumented PEB
1464 * structure. The risk is reduced thanks to the fact that the Chromium sandbox
1465 * relies on the location of this field. It is unlikely to change at this point.
1466 * To further reduce the risk, we also check for the magic 'MZ' signature that
1467 * should indicate the beginning of a PE image.
1468 */
1469 inline LauncherResult<HMODULE> GetProcessExeModule(HANDLE aProcess) {
1470 LauncherResult<void*> ppeb = GetProcessPebPtr(aProcess);
1471 if (ppeb.isErr()) {
1472 return ppeb.propagateErr();
1473 }
1474
1475 PEB peb;
1476 SIZE_T bytesRead;
1477
1478 #if defined(MOZILLA_INTERNAL_API)
1479 if (!::ReadProcessMemory(aProcess, ppeb.unwrap(), &peb, sizeof(peb),
1480 &bytesRead) ||
1481 bytesRead != sizeof(peb)) {
1482 return LAUNCHER_ERROR_FROM_LAST();
1483 }
1484 #else
1485 NTSTATUS ntStatus = ::NtReadVirtualMemory(aProcess, ppeb.unwrap(), &peb,
1486 sizeof(peb), &bytesRead);
1487 if (!NT_SUCCESS(ntStatus) || bytesRead != sizeof(peb)) {
1488 return LAUNCHER_ERROR_FROM_NTSTATUS(ntStatus);
1489 }
1490 #endif
1491
1492 // peb.ImageBaseAddress
1493 void* baseAddress = peb.Reserved3[1];
1494
1495 char mzMagic[2];
1496 #if defined(MOZILLA_INTERNAL_API)
1497 if (!::ReadProcessMemory(aProcess, baseAddress, mzMagic, sizeof(mzMagic),
1498 &bytesRead) ||
1499 bytesRead != sizeof(mzMagic)) {
1500 return LAUNCHER_ERROR_FROM_LAST();
1501 }
1502 #else
1503 ntStatus = ::NtReadVirtualMemory(aProcess, baseAddress, mzMagic,
1504 sizeof(mzMagic), &bytesRead);
1505 if (!NT_SUCCESS(ntStatus) || bytesRead != sizeof(mzMagic)) {
1506 return LAUNCHER_ERROR_FROM_NTSTATUS(ntStatus);
1507 }
1508 #endif
1509
1510 MOZ_ASSERT(mzMagic[0] == 'M' && mzMagic[1] == 'Z');
1511 if (mzMagic[0] != 'M' || mzMagic[1] != 'Z') {
1512 return LAUNCHER_ERROR_FROM_WIN32(ERROR_BAD_EXE_FORMAT);
1513 }
1514
1515 return static_cast<HMODULE>(baseAddress);
1516 }
1517
1518 #if defined(_MSC_VER)
1519 extern "C" IMAGE_DOS_HEADER __ImageBase;
1520 #endif
1521
1522 // This class manages data transfer from the local process's executable
1523 // to another process's executable via WriteProcessMemory.
1524 // Bug 1662560 told us the same executable may be mapped onto a different
1525 // address in a different process. This means when we transfer data within
1526 // the mapped executable such as a global variable or IAT from the current
1527 // process to another process, we need to shift its address by the difference
1528 // between two executable's mapped imagebase.
1529 class CrossExecTransferManager final {
1530 HANDLE mRemoteProcess;
1531 uint8_t* mLocalImagebase;
1532 PEHeaders mLocalExec;
1533 uint8_t* mRemoteImagebase;
1534
1535 static HMODULE GetLocalExecModule() {
1536 #if defined(_MSC_VER)
1537 return reinterpret_cast<HMODULE>(&__ImageBase);
1538 #else
1539 return ::GetModuleHandleW(nullptr);
1540 #endif
1541 }
1542
1543 LauncherVoidResult EnsureRemoteImagebase() {
1544 if (!mRemoteImagebase) {
1545 LauncherResult<HMODULE> remoteImageBaseResult =
1546 GetProcessExeModule(mRemoteProcess);
1547 if (remoteImageBaseResult.isErr()) {
1548 return remoteImageBaseResult.propagateErr();
1549 }
1550
1551 mRemoteImagebase =
1552 reinterpret_cast<uint8_t*>(remoteImageBaseResult.unwrap());
1553 }
1554 return Ok();
1555 }
1556
1557 template <typename T>
1558 T* LocalExecToRemoteExec(T* aLocalAddress) const {
1559 MOZ_ASSERT(mRemoteImagebase);
1560 MOZ_ASSERT(mLocalExec.IsWithinImage(aLocalAddress));
1561
1562 if (!mRemoteImagebase || !mLocalExec.IsWithinImage(aLocalAddress)) {
1563 return aLocalAddress;
1564 }
1565
1566 uintptr_t offset = reinterpret_cast<uintptr_t>(aLocalAddress) -
1567 reinterpret_cast<uintptr_t>(mLocalImagebase);
1568 return reinterpret_cast<T*>(mRemoteImagebase + offset);
1569 }
1570
1571 public:
1572 explicit CrossExecTransferManager(HANDLE aRemoteProcess)
1573 : mRemoteProcess(aRemoteProcess),
1574 mLocalImagebase(
1575 PEHeaders::HModuleToBaseAddr<uint8_t*>(GetLocalExecModule())),
1576 mLocalExec(mLocalImagebase),
1577 mRemoteImagebase(nullptr) {}
1578
1579 CrossExecTransferManager(HANDLE aRemoteProcess, HMODULE aLocalImagebase)
1580 : mRemoteProcess(aRemoteProcess),
1581 mLocalImagebase(
1582 PEHeaders::HModuleToBaseAddr<uint8_t*>(aLocalImagebase)),
1583 mLocalExec(mLocalImagebase),
1584 mRemoteImagebase(nullptr) {}
1585
1586 explicit operator bool() const { return !!mLocalExec; }
1587 HANDLE RemoteProcess() const { return mRemoteProcess; }
1588 const PEHeaders& LocalPEHeaders() const { return mLocalExec; }
1589
1590 AutoVirtualProtect Protect(void* aLocalAddress, size_t aLength,
1591 DWORD aProtFlags) {
1592 // If EnsureRemoteImagebase() fails, a subsequent operaion will fail.
1593 Unused << EnsureRemoteImagebase();
1594 return AutoVirtualProtect(LocalExecToRemoteExec(aLocalAddress), aLength,
1595 aProtFlags, mRemoteProcess);
1596 }
1597
1598 LauncherVoidResult Transfer(LPVOID aDestinationAddress,
1599 LPCVOID aBufferToWrite, SIZE_T aBufferSize) {
1600 LauncherVoidResult result = EnsureRemoteImagebase();
1601 if (result.isErr()) {
1602 return result.propagateErr();
1603 }
1604
1605 if (!::WriteProcessMemory(mRemoteProcess,
1606 LocalExecToRemoteExec(aDestinationAddress),
1607 aBufferToWrite, aBufferSize, nullptr)) {
1608 return LAUNCHER_ERROR_FROM_LAST();
1609 }
1610
1611 return Ok();
1612 }
1613 };
1614
1615 #if !defined(MOZILLA_INTERNAL_API)
1616
1617 inline LauncherResult<HMODULE> GetModuleHandleFromLeafName(
1618 const UNICODE_STRING& aTarget) {
1619 auto maybePeb = nt::GetProcessPebPtr(kCurrentProcess);
1620 if (maybePeb.isErr()) {
1621 return maybePeb.propagateErr();
1622 }
1623
1624 const PPEB peb = reinterpret_cast<PPEB>(maybePeb.unwrap());
1625 if (!peb->Ldr) {
1626 return LAUNCHER_ERROR_FROM_WIN32(ERROR_BAD_EXE_FORMAT);
1627 }
1628
1629 auto firstItem = &peb->Ldr->InMemoryOrderModuleList;
1630 for (auto p = firstItem->Flink; p != firstItem; p = p->Flink) {
1631 const auto currentTableEntry =
1632 CONTAINING_RECORD(p, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);
1633
1634 UNICODE_STRING leafName;
1635 nt::GetLeafName(&leafName, &currentTableEntry->FullDllName);
1636
1637 if (::RtlCompareUnicodeString(&leafName, &aTarget, TRUE) == 0) {
1638 return reinterpret_cast<HMODULE>(currentTableEntry->DllBase);
1639 }
1640 }
1641
1642 return LAUNCHER_ERROR_FROM_WIN32(ERROR_MOD_NOT_FOUND);
1643 }
1644
1645 class MOZ_ONLY_USED_TO_AVOID_STATIC_CONSTRUCTORS SRWLock final {
1646 public:
1647 constexpr SRWLock() : mLock(SRWLOCK_INIT) {}
1648
1649 void LockShared() { ::RtlAcquireSRWLockShared(&mLock); }
1650
1651 void LockExclusive() { ::RtlAcquireSRWLockExclusive(&mLock); }
1652
1653 void UnlockShared() { ::RtlReleaseSRWLockShared(&mLock); }
1654
1655 void UnlockExclusive() { ::RtlReleaseSRWLockExclusive(&mLock); }
1656
1657 SRWLock(const SRWLock&) = delete;
1658 SRWLock(SRWLock&&) = delete;
1659 SRWLock& operator=(const SRWLock&) = delete;
1660 SRWLock& operator=(SRWLock&&) = delete;
1661
1662 SRWLOCK* operator&() { return &mLock; }
1663
1664 private:
1665 SRWLOCK mLock;
1666 };
1667
1668 class MOZ_RAII AutoExclusiveLock final {
1669 public:
1670 explicit AutoExclusiveLock(SRWLock& aLock) : mLock(aLock) {
1671 aLock.LockExclusive();
1672 }
1673
1674 ~AutoExclusiveLock() { mLock.UnlockExclusive(); }
1675
1676 AutoExclusiveLock(const AutoExclusiveLock&) = delete;
1677 AutoExclusiveLock(AutoExclusiveLock&&) = delete;
1678 AutoExclusiveLock& operator=(const AutoExclusiveLock&) = delete;
1679 AutoExclusiveLock& operator=(AutoExclusiveLock&&) = delete;
1680
1681 private:
1682 SRWLock& mLock;
1683 };
1684
1685 class MOZ_RAII AutoSharedLock final {
1686 public:
1687 explicit AutoSharedLock(SRWLock& aLock) : mLock(aLock) { aLock.LockShared(); }
1688
1689 ~AutoSharedLock() { mLock.UnlockShared(); }
1690
1691 AutoSharedLock(const AutoSharedLock&) = delete;
1692 AutoSharedLock(AutoSharedLock&&) = delete;
1693 AutoSharedLock& operator=(const AutoSharedLock&) = delete;
1694 AutoSharedLock& operator=(AutoSharedLock&&) = delete;
1695
1696 private:
1697 SRWLock& mLock;
1698 };
1699
1700 #endif // !defined(MOZILLA_INTERNAL_API)
1701
1702 class RtlAllocPolicy {
1703 public:
1704 template <typename T>
1705 T* maybe_pod_malloc(size_t aNumElems) {
1706 if (aNumElems & mozilla::tl::MulOverflowMask<sizeof(T)>::value) {
1707 return nullptr;
1708 }
1709
1710 return static_cast<T*>(
1711 ::RtlAllocateHeap(RtlGetProcessHeap(), 0, aNumElems * sizeof(T)));
1712 }
1713
1714 template <typename T>
1715 T* maybe_pod_calloc(size_t aNumElems) {
1716 if (aNumElems & mozilla::tl::MulOverflowMask<sizeof(T)>::value) {
1717 return nullptr;
1718 }
1719
1720 return static_cast<T*>(::RtlAllocateHeap(
1721 RtlGetProcessHeap(), HEAP_ZERO_MEMORY, aNumElems * sizeof(T)));
1722 }
1723
1724 template <typename T>
1725 T* maybe_pod_realloc(T* aPtr, size_t aOldSize, size_t aNewSize) {
1726 if (aNewSize & mozilla::tl::MulOverflowMask<sizeof(T)>::value) {
1727 return nullptr;
1728 }
1729
1730 return static_cast<T*>(::RtlReAllocateHeap(RtlGetProcessHeap(), 0, aPtr,
1731 aNewSize * sizeof(T)));
1732 }
1733
1734 template <typename T>
1735 T* pod_malloc(size_t aNumElems) {
1736 return maybe_pod_malloc<T>(aNumElems);
1737 }
1738
1739 template <typename T>
1740 T* pod_calloc(size_t aNumElems) {
1741 return maybe_pod_calloc<T>(aNumElems);
1742 }
1743
1744 template <typename T>
1745 T* pod_realloc(T* aPtr, size_t aOldSize, size_t aNewSize) {
1746 return maybe_pod_realloc<T>(aPtr, aOldSize, aNewSize);
1747 }
1748
1749 template <typename T>
1750 void free_(T* aPtr, size_t aNumElems = 0) {
1751 ::RtlFreeHeap(RtlGetProcessHeap(), 0, aPtr);
1752 }
1753
1754 void reportAllocOverflow() const {}
1755
1756 [[nodiscard]] bool checkSimulatedOOM() const { return true; }
1757 };
1758
1759 class AutoMappedView final {
1760 void* mView;
1761
1762 void Unmap() {
1763 if (!mView) {
1764 return;
1765 }
1766
1767 #if defined(MOZILLA_INTERNAL_API)
1768 ::UnmapViewOfFile(mView);
1769 #else
1770 NTSTATUS status = ::NtUnmapViewOfSection(nt::kCurrentProcess, mView);
1771 if (!NT_SUCCESS(status)) {
1772 ::RtlSetLastWin32Error(::RtlNtStatusToDosError(status));
1773 }
1774 #endif
1775 mView = nullptr;
1776 }
1777
1778 public:
1779 explicit AutoMappedView(void* aView) : mView(aView) {}
1780
1781 AutoMappedView(HANDLE aSection, ULONG aProtectionFlags) : mView(nullptr) {
1782 #if defined(MOZILLA_INTERNAL_API)
1783 mView = ::MapViewOfFile(aSection, aProtectionFlags, 0, 0, 0);
1784 #else
1785 SIZE_T viewSize = 0;
1786 NTSTATUS status = ::NtMapViewOfSection(aSection, nt::kCurrentProcess,
1787 &mView, 0, 0, nullptr, &viewSize,
1788 ViewUnmap, 0, aProtectionFlags);
1789 if (!NT_SUCCESS(status)) {
1790 ::RtlSetLastWin32Error(::RtlNtStatusToDosError(status));
1791 }
1792 #endif
1793 }
1794 ~AutoMappedView() { Unmap(); }
1795
1796 // Allow move & Disallow copy
1797 AutoMappedView(AutoMappedView&& aOther) : mView(aOther.mView) {
1798 aOther.mView = nullptr;
1799 }
1800 AutoMappedView& operator=(AutoMappedView&& aOther) {
1801 if (this != &aOther) {
1802 Unmap();
1803 mView = aOther.mView;
1804 aOther.mView = nullptr;
1805 }
1806 return *this;
1807 }
1808 AutoMappedView(const AutoMappedView&) = delete;
1809 AutoMappedView& operator=(const AutoMappedView&) = delete;
1810
1811 explicit operator bool() const { return !!mView; }
1812 template <typename T>
1813 T* as() {
1814 return reinterpret_cast<T*>(mView);
1815 }
1816
1817 void* release() {
1818 void* p = mView;
1819 mView = nullptr;
1820 return p;
1821 }
1822 };
1823
1824 #if defined(_M_X64)
1825 // CheckStack ensures that stack memory pages are committed up to a given size
1826 // in bytes from the current stack pointer. It updates the thread stack limit,
1827 // which points to the lowest committed stack address.
1828 MOZ_NEVER_INLINE MOZ_NAKED inline void CheckStack(uint32_t size) {
1829 asm volatile(
1830 "mov %ecx, %eax;"
1831 # if defined(__MINGW32__)
1832 "jmp ___chkstk_ms;"
1833 # else
1834 "jmp __chkstk;"
1835 # endif // __MINGW32__
1836 );
1837 }
1838 #endif // _M_X64
1839
1840 } // namespace nt
1841 } // namespace mozilla
1842
1843 #endif // mozilla_NativeNt_h