forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNativeNt.h
1706 lines (1389 loc) · 52 KB
/
NativeNt.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#ifndef mozilla_NativeNt_h
#define mozilla_NativeNt_h
#include <stdint.h>
#include <windows.h>
#include <winnt.h>
#include <winternl.h>
#include <algorithm>
#include <utility>
#include "mozilla/ArrayUtils.h"
#include "mozilla/Attributes.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/Maybe.h"
#include "mozilla/Range.h"
#include "mozilla/Span.h"
#include "mozilla/WinHeaderOnlyUtils.h"
#include "mozilla/interceptor/MMPolicies.h"
#include "mozilla/interceptor/TargetFunction.h"
#if defined(MOZILLA_INTERNAL_API)
# include "nsString.h"
#endif // defined(MOZILLA_INTERNAL_API)
// The declarations within this #if block are intended to be used for initial
// process initialization ONLY. You probably don't want to be using these in
// normal Gecko code!
#if !defined(MOZILLA_INTERNAL_API)
extern "C" {
# if !defined(STATUS_ACCESS_DENIED)
# define STATUS_ACCESS_DENIED ((NTSTATUS)0xC0000022L)
# endif // !defined(STATUS_ACCESS_DENIED)
# if !defined(STATUS_DLL_NOT_FOUND)
# define STATUS_DLL_NOT_FOUND ((NTSTATUS)0xC0000135L)
# endif // !defined(STATUS_DLL_NOT_FOUND)
# if !defined(STATUS_UNSUCCESSFUL)
# define STATUS_UNSUCCESSFUL ((NTSTATUS)0xC0000001L)
# endif // !defined(STATUS_UNSUCCESSFUL)
# if !defined(STATUS_INFO_LENGTH_MISMATCH)
# define STATUS_INFO_LENGTH_MISMATCH ((NTSTATUS)0xC0000004L)
# endif
enum SECTION_INHERIT { ViewShare = 1, ViewUnmap = 2 };
NTSTATUS NTAPI NtMapViewOfSection(
HANDLE aSection, HANDLE aProcess, PVOID* aBaseAddress, ULONG_PTR aZeroBits,
SIZE_T aCommitSize, PLARGE_INTEGER aSectionOffset, PSIZE_T aViewSize,
SECTION_INHERIT aInheritDisposition, ULONG aAllocationType,
ULONG aProtectionFlags);
NTSTATUS NTAPI NtUnmapViewOfSection(HANDLE aProcess, PVOID aBaseAddress);
enum MEMORY_INFORMATION_CLASS {
MemoryBasicInformation = 0,
MemorySectionName = 2
};
// NB: When allocating, space for the buffer must also be included
typedef struct _MEMORY_SECTION_NAME {
UNICODE_STRING mSectionFileName;
} MEMORY_SECTION_NAME, *PMEMORY_SECTION_NAME;
NTSTATUS NTAPI NtQueryVirtualMemory(HANDLE aProcess, PVOID aBaseAddress,
MEMORY_INFORMATION_CLASS aMemInfoClass,
PVOID aMemInfo, SIZE_T aMemInfoLen,
PSIZE_T aReturnLen);
LONG NTAPI RtlCompareUnicodeString(PCUNICODE_STRING aStr1,
PCUNICODE_STRING aStr2,
BOOLEAN aCaseInsensitive);
BOOLEAN NTAPI RtlEqualUnicodeString(PCUNICODE_STRING aStr1,
PCUNICODE_STRING aStr2,
BOOLEAN aCaseInsensitive);
NTSTATUS NTAPI RtlGetVersion(PRTL_OSVERSIONINFOW aOutVersionInformation);
VOID NTAPI RtlAcquireSRWLockExclusive(PSRWLOCK aLock);
VOID NTAPI RtlAcquireSRWLockShared(PSRWLOCK aLock);
VOID NTAPI RtlReleaseSRWLockExclusive(PSRWLOCK aLock);
VOID NTAPI RtlReleaseSRWLockShared(PSRWLOCK aLock);
ULONG NTAPI RtlNtStatusToDosError(NTSTATUS aStatus);
VOID NTAPI RtlSetLastWin32Error(DWORD aError);
DWORD NTAPI RtlGetLastWin32Error();
VOID NTAPI RtlRunOnceInitialize(PRTL_RUN_ONCE aRunOnce);
NTSTATUS NTAPI NtReadVirtualMemory(HANDLE aProcessHandle, PVOID aBaseAddress,
PVOID aBuffer, SIZE_T aNumBytesToRead,
PSIZE_T aNumBytesRead);
NTSTATUS NTAPI LdrLoadDll(PWCHAR aDllPath, PULONG aFlags,
PUNICODE_STRING aDllName, PHANDLE aOutHandle);
typedef ULONG(NTAPI* PRTL_RUN_ONCE_INIT_FN)(PRTL_RUN_ONCE, PVOID, PVOID*);
NTSTATUS NTAPI RtlRunOnceExecuteOnce(PRTL_RUN_ONCE aRunOnce,
PRTL_RUN_ONCE_INIT_FN aInitFn,
PVOID aContext, PVOID* aParameter);
} // extern "C"
#endif // !defined(MOZILLA_INTERNAL_API)
extern "C" {
PVOID NTAPI RtlAllocateHeap(PVOID aHeapHandle, ULONG aFlags, SIZE_T aSize);
PVOID NTAPI RtlReAllocateHeap(PVOID aHeapHandle, ULONG aFlags, LPVOID aMem,
SIZE_T aNewSize);
BOOLEAN NTAPI RtlFreeHeap(PVOID aHeapHandle, ULONG aFlags, PVOID aHeapBase);
BOOLEAN NTAPI RtlQueryPerformanceCounter(LARGE_INTEGER* aPerfCount);
#define RTL_DUPLICATE_UNICODE_STRING_NULL_TERMINATE 1
#define RTL_DUPLICATE_UNICODE_STRING_ALLOCATE_NULL_STRING 2
NTSTATUS NTAPI RtlDuplicateUnicodeString(ULONG aFlags, PCUNICODE_STRING aSrc,
PUNICODE_STRING aDest);
VOID NTAPI RtlFreeUnicodeString(PUNICODE_STRING aUnicodeString);
} // extern "C"
namespace mozilla {
namespace nt {
/**
* This class encapsulates a UNICODE_STRING that owns its own buffer. The
* buffer is always NULL terminated, thus allowing us to cast to a wide C-string
* without requiring any mutation.
*
* We only allow creation of this owned buffer from outside XUL.
*/
class AllocatedUnicodeString final {
public:
AllocatedUnicodeString() : mUnicodeString() {}
#if defined(MOZILLA_INTERNAL_API)
AllocatedUnicodeString(const AllocatedUnicodeString& aOther) = delete;
AllocatedUnicodeString& operator=(const AllocatedUnicodeString& aOther) =
delete;
#else
explicit AllocatedUnicodeString(PCUNICODE_STRING aSrc) {
if (!aSrc) {
mUnicodeString = {};
return;
}
Duplicate(aSrc);
}
explicit AllocatedUnicodeString(const char* aSrc) {
if (!aSrc) {
mUnicodeString = {};
return;
}
Duplicate(aSrc);
}
AllocatedUnicodeString(const AllocatedUnicodeString& aOther) {
Duplicate(&aOther.mUnicodeString);
}
AllocatedUnicodeString& operator=(const AllocatedUnicodeString& aOther) {
Clear();
Duplicate(&aOther.mUnicodeString);
return *this;
}
AllocatedUnicodeString& operator=(PCUNICODE_STRING aSrc) {
Clear();
Duplicate(aSrc);
return *this;
}
#endif // defined(MOZILLA_INTERNAL_API)
AllocatedUnicodeString(AllocatedUnicodeString&& aOther)
: mUnicodeString(aOther.mUnicodeString) {
aOther.mUnicodeString = {};
}
AllocatedUnicodeString& operator=(AllocatedUnicodeString&& aOther) {
Clear();
mUnicodeString = aOther.mUnicodeString;
aOther.mUnicodeString = {};
return *this;
}
~AllocatedUnicodeString() { Clear(); }
bool IsEmpty() const {
return !mUnicodeString.Buffer || !mUnicodeString.Length;
}
operator PCUNICODE_STRING() const { return &mUnicodeString; }
operator const WCHAR*() const { return mUnicodeString.Buffer; }
USHORT CharLen() const { return mUnicodeString.Length / sizeof(WCHAR); }
#if defined(MOZILLA_INTERNAL_API)
nsDependentString AsString() const {
if (!mUnicodeString.Buffer) {
return nsDependentString();
}
// We can use nsDependentString here as we guaranteed null termination
// when we allocated the string.
return nsDependentString(mUnicodeString.Buffer, CharLen());
}
#endif // defined(MOZILLA_INTERNAL_API)
private:
#if !defined(MOZILLA_INTERNAL_API)
void Duplicate(PCUNICODE_STRING aSrc) {
MOZ_ASSERT(aSrc);
// We duplicate with null termination so that this string may be used
// as a wide C-string without any further manipulation.
NTSTATUS ntStatus = ::RtlDuplicateUnicodeString(
RTL_DUPLICATE_UNICODE_STRING_NULL_TERMINATE, aSrc, &mUnicodeString);
MOZ_ASSERT(NT_SUCCESS(ntStatus));
if (!NT_SUCCESS(ntStatus)) {
// Make sure that mUnicodeString does not contain bogus data
// (since not all callers zero it out before invoking)
mUnicodeString = {};
}
}
void Duplicate(const char* aSrc) {
MOZ_ASSERT(aSrc);
ANSI_STRING ansiStr;
RtlInitAnsiString(&ansiStr, aSrc);
NTSTATUS ntStatus =
::RtlAnsiStringToUnicodeString(&mUnicodeString, &ansiStr, TRUE);
MOZ_ASSERT(NT_SUCCESS(ntStatus));
if (!NT_SUCCESS(ntStatus)) {
mUnicodeString = {};
}
}
#endif // !defined(MOZILLA_INTERNAL_API)
void Clear() {
if (!mUnicodeString.Buffer) {
return;
}
::RtlFreeUnicodeString(&mUnicodeString);
mUnicodeString = {};
}
UNICODE_STRING mUnicodeString;
};
#if !defined(MOZILLA_INTERNAL_API)
struct MemorySectionNameBuf : public _MEMORY_SECTION_NAME {
MemorySectionNameBuf() {
mSectionFileName.Length = 0;
mSectionFileName.MaximumLength = sizeof(mBuf);
mSectionFileName.Buffer = mBuf;
}
MemorySectionNameBuf(const MemorySectionNameBuf& aOther) { *this = aOther; }
MemorySectionNameBuf(MemorySectionNameBuf&& aOther) {
*this = std::move(aOther);
}
// We cannot use default copy here because mSectionFileName.Buffer needs to
// be updated to point to |this->mBuf|, not |aOther.mBuf|.
MemorySectionNameBuf& operator=(const MemorySectionNameBuf& aOther) {
mSectionFileName.Length = aOther.mSectionFileName.Length;
mSectionFileName.MaximumLength = sizeof(mBuf);
MOZ_ASSERT(mSectionFileName.Length <= mSectionFileName.MaximumLength);
mSectionFileName.Buffer = mBuf;
memcpy(mBuf, aOther.mBuf, aOther.mSectionFileName.Length);
return *this;
}
MemorySectionNameBuf& operator=(MemorySectionNameBuf&& aOther) {
mSectionFileName.Length = aOther.mSectionFileName.Length;
aOther.mSectionFileName.Length = 0;
mSectionFileName.MaximumLength = sizeof(mBuf);
MOZ_ASSERT(mSectionFileName.Length <= mSectionFileName.MaximumLength);
aOther.mSectionFileName.MaximumLength = sizeof(aOther.mBuf);
mSectionFileName.Buffer = mBuf;
memmove(mBuf, aOther.mBuf, mSectionFileName.Length);
return *this;
}
// Native NT paths, so we can't assume MAX_PATH. Use a larger buffer.
WCHAR mBuf[2 * MAX_PATH];
bool IsEmpty() const {
return !mSectionFileName.Buffer || !mSectionFileName.Length;
}
operator PCUNICODE_STRING() const { return &mSectionFileName; }
};
class MemorySectionNameOnHeap {
UniquePtr<uint8_t[]> mBuffer;
MemorySectionNameOnHeap() = default;
explicit MemorySectionNameOnHeap(size_t aBufferLen)
: mBuffer(MakeUnique<uint8_t[]>(aBufferLen)) {}
public:
static MemorySectionNameOnHeap GetBackingFilePath(HANDLE aProcess,
void* aSectionAddr) {
SIZE_T bufferLen = MAX_PATH * 2;
do {
MemorySectionNameOnHeap sectionName(bufferLen);
SIZE_T requiredBytes;
NTSTATUS ntStatus = ::NtQueryVirtualMemory(
aProcess, aSectionAddr, MemorySectionName, sectionName.mBuffer.get(),
bufferLen, &requiredBytes);
if (NT_SUCCESS(ntStatus)) {
return sectionName;
}
if (ntStatus != STATUS_INFO_LENGTH_MISMATCH ||
bufferLen >= requiredBytes) {
break;
}
bufferLen = requiredBytes;
} while (1);
return MemorySectionNameOnHeap();
}
// Allow move & Disallow copy
MemorySectionNameOnHeap(MemorySectionNameOnHeap&&) = default;
MemorySectionNameOnHeap& operator=(MemorySectionNameOnHeap&&) = default;
MemorySectionNameOnHeap(const MemorySectionNameOnHeap&) = delete;
MemorySectionNameOnHeap& operator=(const MemorySectionNameOnHeap&) = delete;
PCUNICODE_STRING AsUnicodeString() const {
return reinterpret_cast<PCUNICODE_STRING>(mBuffer.get());
}
};
inline bool FindCharInUnicodeString(const UNICODE_STRING& aStr, WCHAR aChar,
uint16_t& aPos, uint16_t aStartIndex = 0) {
const uint16_t aMaxIndex = aStr.Length / sizeof(WCHAR);
for (uint16_t curIndex = aStartIndex; curIndex < aMaxIndex; ++curIndex) {
if (aStr.Buffer[curIndex] == aChar) {
aPos = curIndex;
return true;
}
}
return false;
}
inline bool IsHexDigit(WCHAR aChar) {
return (aChar >= L'0' && aChar <= L'9') || (aChar >= L'A' && aChar <= L'F') ||
(aChar >= L'a' && aChar <= L'f');
}
inline bool MatchUnicodeString(const UNICODE_STRING& aStr,
bool (*aPredicate)(WCHAR)) {
WCHAR* cur = aStr.Buffer;
WCHAR* end = &aStr.Buffer[aStr.Length / sizeof(WCHAR)];
while (cur < end) {
if (!aPredicate(*cur)) {
return false;
}
++cur;
}
return true;
}
inline bool Contains12DigitHexString(const UNICODE_STRING& aLeafName) {
// Quick check: If the string is too short, don't bother
// (We need at least 12 hex digits, one char for '.', and 3 for extension)
const USHORT kMinLen = (12 + 1 + 3) * sizeof(wchar_t);
if (aLeafName.Length < kMinLen) {
return false;
}
uint16_t start, end;
if (!FindCharInUnicodeString(aLeafName, L'.', start)) {
return false;
}
++start;
if (!FindCharInUnicodeString(aLeafName, L'.', end, start)) {
return false;
}
if (end - start != 12) {
return false;
}
UNICODE_STRING test;
test.Buffer = &aLeafName.Buffer[start];
test.Length = (end - start) * sizeof(WCHAR);
test.MaximumLength = test.Length;
return MatchUnicodeString(test, &IsHexDigit);
}
inline bool IsFileNameAtLeast16HexDigits(const UNICODE_STRING& aLeafName) {
// Quick check: If the string is too short, don't bother
// (We need 16 hex digits, one char for '.', and 3 for extension)
const USHORT kMinLen = (16 + 1 + 3) * sizeof(wchar_t);
if (aLeafName.Length < kMinLen) {
return false;
}
uint16_t dotIndex;
if (!FindCharInUnicodeString(aLeafName, L'.', dotIndex)) {
return false;
}
if (dotIndex < 16) {
return false;
}
UNICODE_STRING test;
test.Buffer = aLeafName.Buffer;
test.Length = dotIndex * sizeof(WCHAR);
test.MaximumLength = aLeafName.MaximumLength;
return MatchUnicodeString(test, &IsHexDigit);
}
inline void GetLeafName(PUNICODE_STRING aDestString,
PCUNICODE_STRING aSrcString) {
WCHAR* buf = aSrcString->Buffer;
WCHAR* end = &aSrcString->Buffer[(aSrcString->Length / sizeof(WCHAR)) - 1];
WCHAR* cur = end;
while (cur >= buf) {
if (*cur == L'\\') {
break;
}
--cur;
}
// At this point, either cur points to the final backslash, or it points to
// buf - 1. Either way, we're interested in cur + 1 as the desired buffer.
aDestString->Buffer = cur + 1;
aDestString->Length = (end - aDestString->Buffer + 1) * sizeof(WCHAR);
aDestString->MaximumLength = aDestString->Length;
}
#endif // !defined(MOZILLA_INTERNAL_API)
#if defined(MOZILLA_INTERNAL_API)
inline const nsDependentSubstring GetLeafName(const nsAString& aString) {
auto it = aString.EndReading();
size_t pos = aString.Length();
while (it > aString.BeginReading()) {
if (*(it - 1) == u'\\') {
return Substring(aString, pos);
}
MOZ_ASSERT(pos > 0);
--pos;
--it;
}
return Substring(aString, 0); // No backslash in the string
}
#endif // defined(MOZILLA_INTERNAL_API)
inline char EnsureLowerCaseASCII(char aChar) {
if (aChar >= 'A' && aChar <= 'Z') {
aChar -= 'A' - 'a';
}
return aChar;
}
inline int StricmpASCII(const char* aLeft, const char* aRight) {
char curLeft, curRight;
do {
curLeft = EnsureLowerCaseASCII(*(aLeft++));
curRight = EnsureLowerCaseASCII(*(aRight++));
} while (curLeft && curLeft == curRight);
return curLeft - curRight;
}
inline int StrcmpASCII(const char* aLeft, const char* aRight) {
char curLeft, curRight;
do {
curLeft = *(aLeft++);
curRight = *(aRight++);
} while (curLeft && curLeft == curRight);
return curLeft - curRight;
}
inline size_t StrlenASCII(const char* aStr) {
size_t len = 0;
while (*(aStr++)) {
++len;
}
return len;
}
struct CodeViewRecord70 {
uint32_t signature;
GUID pdbSignature;
uint32_t pdbAge;
// A UTF-8 string, according to
// https://github.com/Microsoft/microsoft-pdb/blob/082c5290e5aff028ae84e43affa8be717aa7af73/PDB/dbi/locator.cpp#L785
char pdbFileName[1];
};
class MOZ_RAII PEHeaders final {
/**
* This structure is documented on MSDN as VS_VERSIONINFO, but is not present
* in SDK headers because it cannot be specified as a C struct. The following
* structure contains the fixed-length fields at the beginning of
* VS_VERSIONINFO.
*/
struct VS_VERSIONINFO_HEADER {
WORD wLength;
WORD wValueLength;
WORD wType;
WCHAR szKey[16]; // ArrayLength(L"VS_VERSION_INFO")
// Additional data goes here, aligned on a 4-byte boundary
};
public:
// The lowest two bits of an HMODULE are used as flags. Stripping those bits
// from the HMODULE yields the base address of the binary's memory mapping.
// (See LoadLibraryEx docs on MSDN)
template <typename T>
static T HModuleToBaseAddr(HMODULE aModule) {
return reinterpret_cast<T>(reinterpret_cast<uintptr_t>(aModule) &
~uintptr_t(3));
}
explicit PEHeaders(void* aBaseAddress)
: PEHeaders(reinterpret_cast<PIMAGE_DOS_HEADER>(aBaseAddress)) {}
explicit PEHeaders(HMODULE aModule)
: PEHeaders(HModuleToBaseAddr<PIMAGE_DOS_HEADER>(aModule)) {}
explicit PEHeaders(PIMAGE_DOS_HEADER aMzHeader)
: mMzHeader(aMzHeader),
mPeHeader(nullptr),
mImageLimit(nullptr),
mIsImportDirectoryTampered(false) {
if (!mMzHeader || mMzHeader->e_magic != IMAGE_DOS_SIGNATURE) {
return;
}
mPeHeader = RVAToPtrUnchecked<PIMAGE_NT_HEADERS>(mMzHeader->e_lfanew);
if (!mPeHeader || mPeHeader->Signature != IMAGE_NT_SIGNATURE) {
return;
}
if (mPeHeader->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC) {
return;
}
DWORD imageSize = mPeHeader->OptionalHeader.SizeOfImage;
// This is a coarse-grained check to ensure that the image size is
// reasonable. It we aren't big enough to contain headers, we have a
// problem!
if (imageSize < sizeof(IMAGE_DOS_HEADER) + sizeof(IMAGE_NT_HEADERS)) {
return;
}
mImageLimit = RVAToPtrUnchecked<void*>(imageSize - 1UL);
PIMAGE_DATA_DIRECTORY importDirEntry =
GetImageDirectoryEntryPtr(IMAGE_DIRECTORY_ENTRY_IMPORT);
if (!importDirEntry) {
return;
}
mIsImportDirectoryTampered = (importDirEntry->VirtualAddress >= imageSize);
}
explicit operator bool() const { return !!mImageLimit; }
/**
* This overload computes absolute virtual addresses relative to the base
* address of the binary.
*/
template <typename T, typename R>
T RVAToPtr(R aRva) const {
return RVAToPtr<T>(mMzHeader, aRva);
}
/**
* This overload computes a result by adding aRva to aBase, but also ensures
* that the resulting pointer falls within the bounds of this binary's memory
* mapping.
*/
template <typename T, typename R>
T RVAToPtr(void* aBase, R aRva) const {
if (!mImageLimit) {
return nullptr;
}
char* absAddress = reinterpret_cast<char*>(aBase) + aRva;
if (absAddress < reinterpret_cast<char*>(mMzHeader) ||
absAddress > reinterpret_cast<char*>(mImageLimit)) {
return nullptr;
}
return reinterpret_cast<T>(absAddress);
}
Maybe<Range<const uint8_t>> GetBounds() const {
if (!mImageLimit) {
return Nothing();
}
auto base = reinterpret_cast<const uint8_t*>(mMzHeader);
DWORD imageSize = mPeHeader->OptionalHeader.SizeOfImage;
return Some(Range(base, imageSize));
}
DWORD GetFileCharacteristics() const {
return mPeHeader ? mPeHeader->FileHeader.Characteristics : 0;
}
bool IsWithinImage(const void* aAddress) const {
uintptr_t addr = reinterpret_cast<uintptr_t>(aAddress);
uintptr_t imageBase = reinterpret_cast<uintptr_t>(mMzHeader);
uintptr_t imageLimit = reinterpret_cast<uintptr_t>(mImageLimit);
return addr >= imageBase && addr <= imageLimit;
}
PIMAGE_IMPORT_DESCRIPTOR GetImportDirectory() const {
// If the import directory is already tampered, we skip bounds check
// because it could be located outside the mapped image.
return mIsImportDirectoryTampered
? GetImageDirectoryEntry<PIMAGE_IMPORT_DESCRIPTOR,
BoundsCheckPolicy::Skip>(
IMAGE_DIRECTORY_ENTRY_IMPORT)
: GetImageDirectoryEntry<PIMAGE_IMPORT_DESCRIPTOR>(
IMAGE_DIRECTORY_ENTRY_IMPORT);
}
PIMAGE_RESOURCE_DIRECTORY GetResourceTable() const {
return GetImageDirectoryEntry<PIMAGE_RESOURCE_DIRECTORY>(
IMAGE_DIRECTORY_ENTRY_RESOURCE);
}
PIMAGE_DATA_DIRECTORY GetImageDirectoryEntryPtr(
const uint32_t aDirectoryIndex, uint32_t* aOutRva = nullptr) const {
if (aOutRva) {
*aOutRva = 0;
}
IMAGE_OPTIONAL_HEADER& optionalHeader = mPeHeader->OptionalHeader;
const uint32_t maxIndex = std::min(optionalHeader.NumberOfRvaAndSizes,
DWORD(IMAGE_NUMBEROF_DIRECTORY_ENTRIES));
if (aDirectoryIndex >= maxIndex) {
return nullptr;
}
PIMAGE_DATA_DIRECTORY dirEntry =
&optionalHeader.DataDirectory[aDirectoryIndex];
if (aOutRva) {
*aOutRva = reinterpret_cast<char*>(dirEntry) -
reinterpret_cast<char*>(mMzHeader);
MOZ_ASSERT(*aOutRva);
}
return dirEntry;
}
bool GetVersionInfo(uint64_t& aOutVersion) const {
// RT_VERSION == 16
// Version resources require an id of 1
auto root = FindResourceLeaf<VS_VERSIONINFO_HEADER*>(16, 1);
if (!root) {
return false;
}
VS_FIXEDFILEINFO* fixedInfo = GetFixedFileInfo(root);
if (!fixedInfo) {
return false;
}
aOutVersion = ((static_cast<uint64_t>(fixedInfo->dwFileVersionMS) << 32) |
static_cast<uint64_t>(fixedInfo->dwFileVersionLS));
return true;
}
bool GetTimeStamp(DWORD& aResult) const {
if (!(*this)) {
return false;
}
aResult = mPeHeader->FileHeader.TimeDateStamp;
return true;
}
PIMAGE_IMPORT_DESCRIPTOR
GetImportDescriptor(const char* aModuleNameASCII) const {
for (PIMAGE_IMPORT_DESCRIPTOR curImpDesc = GetImportDirectory();
IsValid(curImpDesc); ++curImpDesc) {
auto curName = mIsImportDirectoryTampered
? RVAToPtrUnchecked<const char*>(curImpDesc->Name)
: RVAToPtr<const char*>(curImpDesc->Name);
if (!curName) {
return nullptr;
}
if (StricmpASCII(aModuleNameASCII, curName)) {
continue;
}
// curImpDesc now points to the IAT for the module we're interested in
return curImpDesc;
}
return nullptr;
}
template <typename CallbackT>
void EnumImportChunks(const CallbackT& aCallback) const {
for (PIMAGE_IMPORT_DESCRIPTOR curImpDesc = GetImportDirectory();
IsValid(curImpDesc); ++curImpDesc) {
auto curName = mIsImportDirectoryTampered
? RVAToPtrUnchecked<const char*>(curImpDesc->Name)
: RVAToPtr<const char*>(curImpDesc->Name);
if (!curName) {
continue;
}
aCallback(curName);
}
}
/**
* If |aBoundaries| is given, this method checks whether each IAT entry is
* within the given range, and if any entry is out of the range, we return
* Nothing().
*/
Maybe<Span<IMAGE_THUNK_DATA>> GetIATThunksForModule(
const char* aModuleNameASCII,
const Range<const uint8_t>* aBoundaries = nullptr) const {
PIMAGE_IMPORT_DESCRIPTOR impDesc = GetImportDescriptor(aModuleNameASCII);
if (!impDesc) {
return Nothing();
}
auto firstIatThunk =
this->template RVAToPtr<PIMAGE_THUNK_DATA>(impDesc->FirstThunk);
if (!firstIatThunk) {
return Nothing();
}
// Find the length by iterating through the table until we find a null entry
PIMAGE_THUNK_DATA curIatThunk = firstIatThunk;
while (IsValid(curIatThunk)) {
if (aBoundaries) {
auto iatEntry =
reinterpret_cast<const uint8_t*>(curIatThunk->u1.Function);
if (iatEntry < aBoundaries->begin().get() ||
iatEntry >= aBoundaries->end().get()) {
return Nothing();
}
}
++curIatThunk;
}
return Some(Span(firstIatThunk, curIatThunk));
}
/**
* Resources are stored in a three-level tree. To locate a particular entry,
* you must supply a resource type, the resource id, and then the language id.
* If aLangId == 0, we just resolve the first entry regardless of language.
*/
template <typename T>
T FindResourceLeaf(WORD aType, WORD aResId, WORD aLangId = 0) const {
PIMAGE_RESOURCE_DIRECTORY topLevel = GetResourceTable();
if (!topLevel) {
return nullptr;
}
PIMAGE_RESOURCE_DIRECTORY_ENTRY typeEntry =
FindResourceEntry(topLevel, aType);
if (!typeEntry || !typeEntry->DataIsDirectory) {
return nullptr;
}
auto idDir = RVAToPtr<PIMAGE_RESOURCE_DIRECTORY>(
topLevel, typeEntry->OffsetToDirectory);
PIMAGE_RESOURCE_DIRECTORY_ENTRY idEntry = FindResourceEntry(idDir, aResId);
if (!idEntry || !idEntry->DataIsDirectory) {
return nullptr;
}
auto langDir = RVAToPtr<PIMAGE_RESOURCE_DIRECTORY>(
topLevel, idEntry->OffsetToDirectory);
PIMAGE_RESOURCE_DIRECTORY_ENTRY langEntry;
if (aLangId) {
langEntry = FindResourceEntry(langDir, aLangId);
} else {
langEntry = FindFirstResourceEntry(langDir);
}
if (!langEntry || langEntry->DataIsDirectory) {
return nullptr;
}
auto dataEntry =
RVAToPtr<PIMAGE_RESOURCE_DATA_ENTRY>(topLevel, langEntry->OffsetToData);
return dataEntry ? RVAToPtr<T>(dataEntry->OffsetToData) : nullptr;
}
template <size_t N>
Maybe<Span<const uint8_t>> FindSection(const char (&aSecName)[N],
DWORD aCharacteristicsMask) const {
static_assert((N - 1) <= IMAGE_SIZEOF_SHORT_NAME,
"Section names must be at most 8 characters excluding null "
"terminator");
if (!(*this)) {
return Nothing();
}
Span<IMAGE_SECTION_HEADER> sectionTable = GetSectionTable();
for (auto&& sectionHeader : sectionTable) {
if (strncmp(reinterpret_cast<const char*>(sectionHeader.Name), aSecName,
IMAGE_SIZEOF_SHORT_NAME)) {
continue;
}
if (!(sectionHeader.Characteristics & aCharacteristicsMask)) {
// We found the section but it does not have the expected
// characteristics
return Nothing();
}
DWORD rva = sectionHeader.VirtualAddress;
if (!rva) {
return Nothing();
}
DWORD size = sectionHeader.Misc.VirtualSize;
if (!size) {
return Nothing();
}
auto base = RVAToPtr<const uint8_t*>(rva);
return Some(Span(base, size));
}
return Nothing();
}
// There may be other code sections in the binary besides .text
Maybe<Span<const uint8_t>> GetTextSectionInfo() const {
return FindSection(".text", IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE |
IMAGE_SCN_MEM_READ);
}
static bool IsValid(PIMAGE_IMPORT_DESCRIPTOR aImpDesc) {
return aImpDesc && aImpDesc->OriginalFirstThunk != 0;
}
static bool IsValid(PIMAGE_THUNK_DATA aImgThunk) {
return aImgThunk && aImgThunk->u1.Ordinal != 0;
}
bool IsImportDirectoryTampered() const { return mIsImportDirectoryTampered; }
FARPROC GetEntryPoint() const {
// Use the unchecked version because the entrypoint may be tampered.
return RVAToPtrUnchecked<FARPROC>(
mPeHeader->OptionalHeader.AddressOfEntryPoint);
}
const CodeViewRecord70* GetPdbInfo() const {
PIMAGE_DEBUG_DIRECTORY debugDirectory =
GetImageDirectoryEntry<PIMAGE_DEBUG_DIRECTORY>(
IMAGE_DIRECTORY_ENTRY_DEBUG);
if (!debugDirectory) {
return nullptr;
}
const CodeViewRecord70* debugInfo =
RVAToPtr<CodeViewRecord70*>(debugDirectory->AddressOfRawData);
return (debugInfo && debugInfo->signature == 'SDSR') ? debugInfo : nullptr;
}
private:
enum class BoundsCheckPolicy { Default, Skip };
template <typename T, BoundsCheckPolicy Policy = BoundsCheckPolicy::Default>
T GetImageDirectoryEntry(const uint32_t aDirectoryIndex) const {
PIMAGE_DATA_DIRECTORY dirEntry = GetImageDirectoryEntryPtr(aDirectoryIndex);
if (!dirEntry) {
return nullptr;
}
return Policy == BoundsCheckPolicy::Skip
? RVAToPtrUnchecked<T>(dirEntry->VirtualAddress)
: RVAToPtr<T>(dirEntry->VirtualAddress);
}
// This private variant does not have bounds checks, because we need to be
// able to resolve the bounds themselves.
template <typename T, typename R>
T RVAToPtrUnchecked(R aRva) const {
return reinterpret_cast<T>(reinterpret_cast<char*>(mMzHeader) + aRva);
}
Span<IMAGE_SECTION_HEADER> GetSectionTable() const {
MOZ_ASSERT(*this);
auto base = RVAToPtr<PIMAGE_SECTION_HEADER>(
&mPeHeader->OptionalHeader, mPeHeader->FileHeader.SizeOfOptionalHeader);
// The Windows loader has an internal limit of 96 sections (per PE spec)
auto numSections =
std::min(mPeHeader->FileHeader.NumberOfSections, WORD(96));
return Span{base, numSections};
}
PIMAGE_RESOURCE_DIRECTORY_ENTRY
FindResourceEntry(PIMAGE_RESOURCE_DIRECTORY aCurLevel, WORD aId) const {
if (!aCurLevel) {
return nullptr;
}
// Immediately after the IMAGE_RESOURCE_DIRECTORY structure is an array
// of IMAGE_RESOURCE_DIRECTORY_ENTRY structures. Since this function
// searches by ID, we need to skip past any named entries before iterating.
auto dirEnt =
reinterpret_cast<PIMAGE_RESOURCE_DIRECTORY_ENTRY>(aCurLevel + 1) +
aCurLevel->NumberOfNamedEntries;
for (WORD i = 0; i < aCurLevel->NumberOfIdEntries; ++i) {
if (dirEnt[i].Id == aId) {
return &dirEnt[i];
}
}
return nullptr;
}
PIMAGE_RESOURCE_DIRECTORY_ENTRY
FindFirstResourceEntry(PIMAGE_RESOURCE_DIRECTORY aCurLevel) const {
// Immediately after the IMAGE_RESOURCE_DIRECTORY structure is an array
// of IMAGE_RESOURCE_DIRECTORY_ENTRY structures. We just return the first
// entry, regardless of whether it is indexed by name or by id.
auto dirEnt =
reinterpret_cast<PIMAGE_RESOURCE_DIRECTORY_ENTRY>(aCurLevel + 1);
WORD numEntries =
aCurLevel->NumberOfNamedEntries + aCurLevel->NumberOfIdEntries;
if (!numEntries) {
return nullptr;
}
return dirEnt;
}
VS_FIXEDFILEINFO* GetFixedFileInfo(VS_VERSIONINFO_HEADER* aVerInfo) const {
WORD length = aVerInfo->wLength;
if (length < sizeof(VS_VERSIONINFO_HEADER)) {
return nullptr;
}
const wchar_t kVersionInfoKey[] = L"VS_VERSION_INFO";
if (::RtlCompareMemory(aVerInfo->szKey, kVersionInfoKey,
ArrayLength(kVersionInfoKey)) !=
ArrayLength(kVersionInfoKey)) {