-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathntpebldr.hpp
1382 lines (1280 loc) · 53.1 KB
/
ntpebldr.hpp
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
///////////////////////////////////////////////////////////////////////////////
//
// Using the PEB and TEB to navigate loaded modules and such trickery
//
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2021-2023 Oliver Schneider (assarbad.net)
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// [Boost Software License - Version 1.0 - August 17th, 2003]
//
// SPDX-License-Identifier: BSL-1.0
//
///////////////////////////////////////////////////////////////////////////////
#ifndef __NTPEBLDR_H_VER__
#define __NTPEBLDR_H_VER__ 2023111821
#if !NTPEBLDR_NO_PRAGMA_ONCE && ((defined(_MSC_VER) && (_MSC_VER >= 1020)) || defined(__MCPP))
# pragma once
#endif
#if (__cplusplus < 201402L) && (_MSVC_LANG < 201402L)
# error This header expects a C++14 compatible compiler.
#endif
#if defined(WIN32_NO_STATUS)
# undef _NTSTATUS_
# undef WIN32_NO_STATUS
#endif
#pragma warning(push)
#pragma warning(disable : 4005)
#include <ntstatus.h>
#pragma warning(pop)
#pragma push_macro("NTSYSCALLAPI")
#ifdef NTSYSCALLAPI
# undef NTSYSCALLAPI
# define NTSYSCALLAPI
#endif
#pragma warning(push)
#pragma warning(disable : 4201)
#define OBJECT_INFORMATION_CLASS OBJECT_INFORMATION_CLASS_MOCK
#define _OBJECT_INFORMATION_CLASS _OBJECT_INFORMATION_CLASS_MOCK
#define _TEB _TEB_MOCK
#define TEB TEB_MOCK
#define PTEB PTEB_MOCK
#define _PEB _PEB_MOCK
#define PEB PEB_MOCK
#define PPEB PPEB_MOCK
#define ObjectBasicInformation ObjectBasicInformation_Mock
#define ObjectTypeInformation ObjectTypeInformation_Mock
#define NtQueryObject NtQueryObject_Mock
#define NtCurrentTeb NtCurrentTeb_Mock
#include <winternl.h>
#undef OBJECT_INFORMATION_CLASS
#undef _OBJECT_INFORMATION_CLASS
#undef _TEB
#undef TEB
#undef PTEB
#undef _PEB
#undef PEB
#undef PPEB
#undef ObjectBasicInformation
#undef ObjectTypeInformation
#undef NtQueryObject
#undef NtCurrentTeb
#pragma warning(pop)
#pragma pop_macro("NTSYSCALLAPI")
#ifndef NTPEBLDR_LITERAL_UNICODE_STRING
# define NTPEBLDR_LITERAL_UNICODE_STRING(s) \
{ \
sizeof(s) - sizeof(s[0]), sizeof(s), const_cast<PWSTR>(L"" s) \
}
#endif // NTPEBLDR_LITERAL_UNICODE_STRING
// #ifndef NTPEBLDR_LOCAL_PEBTEB_STRUCT
// # define NTPEBLDR_LOCAL_PEBTEB_STRUCT 1
// #endif
#ifndef NTPEBLDR_NAIVE_CRT_INLINES
# define NTPEBLDR_NAIVE_CRT_INLINES 1
#endif
#pragma push_macro("STATIC_INLINE")
#ifdef STATIC_INLINE
# undef STATIC_INLINE
#endif // STATIC_INLINE
#ifdef _MSC_VER
# define STATIC_INLINE static __forceinline
#else
# define STATIC_INLINE static inline
#endif // _MSC_VER
#if !NTPEBLDR_NAIVE_CRT_INLINES
# include <cstdio> // towupper/towlower et. al.
#endif
#include <cstddef> // offsetof etc
#if defined(NTPEBLDR_PRINT_FUNCS) || defined(_DEBUG)
# include <cstdio> // wprintf
# include <tchar.h> // _tprintf
#endif // _DEBUG
#ifndef _countof
# ifdef __crt_countof
# define _countof __crt_countof
# else
# define _countof(x) (sizeof(x) / sizeof((x)[0]))
# endif // __crt_countof
#endif // _countof
namespace NT
{
#if !defined(__NTNATIVE_H_VER__)
// Must correspond to IMAGE_DYNAMIC_RELOCATION_MM_SHARED_USER_DATA_VA from km/ntimage.h
// Kernel mode address is KI_USER_SHARED_DATA (on ARM64 this is relocatable!)
# if defined(_WIN32) && (defined(_M_IX86) || defined(_M_AMD64))
# ifndef MM_SHARED_USER_DATA_VA
# define MM_SHARED_USER_DATA_VA ((unsigned char*)0x7ffe0000)
# define IMAGE_DYNAMIC_RELOCATION_MM_SHARED_USER_DATA_VA MM_SHARED_USER_DATA_VA
# endif
namespace
{ // NB: these are intentionally defined in terms of C++ types rather than "Windows" types
// Modern C++: wchar_t const (&SystemRoot)[260] = (decltype(SystemRoot))(*(wchar_t*)(MM_SHARED_USER_DATA_VA + 0x30));
wchar_t const (&SystemRoot)[260] = (wchar_t const (&)[260])(*(wchar_t*)(MM_SHARED_USER_DATA_VA + 0x30)); //-V542
unsigned short const& NativeProcessorArchitecture = *((unsigned short*)(MM_SHARED_USER_DATA_VA + 0x026a));
unsigned long const& MajorVersion = *((unsigned long*)(MM_SHARED_USER_DATA_VA + 0x026c)); //-V206 //-V126
unsigned long const& MinorVersion = *((unsigned long*)(MM_SHARED_USER_DATA_VA + 0x0270)); //-V206 //-V126
} // namespace
# endif
#endif // !__NTNATIVE_H_VER__
using byte = unsigned char;
typedef struct _LDR_DATA_TABLE_ENTRY
{
LIST_ENTRY InLoadOrderModuleList;
LIST_ENTRY InMemoryOrderModuleList;
LIST_ENTRY InInitializationOrderModuleList;
PVOID DllBase; //-V122
PVOID EntryPoint; //-V122
ULONG SizeOfImage;
UNICODE_STRING FullDllName;
UNICODE_STRING BaseDllName;
ULONG Flags;
USHORT ObsoleteLoadCount;
USHORT TlsIndex;
LIST_ENTRY HashLinks;
ULONG TimeDateStamp;
PVOID EntryPointActivationContext; //-V122
PVOID Lock; //-V122
} LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY;
static_assert(offsetof(LDR_DATA_TABLE_ENTRY, DllBase) == 3 * sizeof(LIST_ENTRY), "DllBase offset has unexpected value");
typedef struct
{ //-V802
PVOID DllBase; //-V122
PVOID EntryPoint; //-V122
ULONG SizeOfImage;
UNICODE_STRING FullDllName;
UNICODE_STRING BaseDllName;
ULONG Flags;
} LDR_DATA_TABLE_ENTRY_CTX, *PLDR_DATA_TABLE_ENTRY_CTX;
namespace Glue
{
typedef struct
{
LIST_ENTRY InLoadOrderModuleList;
LIST_ENTRY InMemoryOrderModuleList;
LIST_ENTRY InInitializationOrderModuleList;
union
{
LDR_DATA_TABLE_ENTRY_CTX context;
struct
{
PVOID DllBase; //-V122
PVOID EntryPoint; //-V122
ULONG SizeOfImage;
UNICODE_STRING FullDllName;
UNICODE_STRING BaseDllName;
ULONG Flags;
USHORT ObsoleteLoadCount;
USHORT TlsIndex;
LIST_ENTRY HashLinks;
ULONG TimeDateStamp;
PVOID EntryPointActivationContext; //-V122
PVOID Lock; //-V122
} real;
} tail;
} LDR_DATA_TABLE_ENTRY;
} // namespace Glue
static_assert(sizeof(Glue::LDR_DATA_TABLE_ENTRY) == sizeof(LDR_DATA_TABLE_ENTRY), "These two must match");
static_assert(offsetof(LDR_DATA_TABLE_ENTRY, Flags) == offsetof(Glue::LDR_DATA_TABLE_ENTRY, tail.real.Flags), "DllBase offset has unexpected value");
static_assert(offsetof(Glue::LDR_DATA_TABLE_ENTRY, tail.context.Flags) == offsetof(Glue::LDR_DATA_TABLE_ENTRY, tail.real.Flags),
"DllBase offset has unexpected value");
typedef struct _PEB_LDR_DATA
{ //-V802
ULONG Length;
BOOLEAN Initialized;
HANDLE SsHandle; //-V122
LIST_ENTRY InLoadOrderModuleList;
LIST_ENTRY InMemoryOrderModuleList;
LIST_ENTRY InInitializationOrderModuleList;
PVOID EntryInProgress; //-V122
BOOLEAN ShutdownInProgress;
HANDLE ShutdownThreadId; //-V122
} PEB_LDR_DATA, *PPEB_LDR_DATA;
#pragma warning(push)
#pragma warning(disable : 4201)
typedef struct _PEB // xref: http://terminus.rewolf.pl/terminus/structures/ntdll/_PEB_combined.html
{
BOOLEAN InheritedAddressSpace;
BOOLEAN ReadImageFileExecOptions;
BOOLEAN BeingDebugged;
union
{
BOOLEAN BitField;
struct
{
BOOLEAN ImageUsesLargePages : 1;
BOOLEAN IsProtectedProcess : 1;
BOOLEAN IsImageDynamicallyRelocated : 1;
BOOLEAN SkipPatchingUser32Forwarders : 1;
BOOLEAN IsPackagedProcess : 1;
BOOLEAN IsAppContainer : 1;
BOOLEAN IsProtectedProcessLight : 1;
BOOLEAN IsLongPathAwareProcess : 1; // xref: https://stackoverflow.com/a/57091811
};
};
HANDLE Mutant; //-V122
PVOID ImageBaseAddress; //-V122
PPEB_LDR_DATA Ldr; //-V122
PRTL_USER_PROCESS_PARAMETERS ProcessParameters; //-V122
PVOID SubSystemData; //-V122
PVOID ProcessHeap; //-V122
PRTL_CRITICAL_SECTION FastPebLock; //-V122
PSLIST_HEADER AtlThunkSListPtr; //-V122
// Everything from here down has been copied from winternl.h for now
PVOID Reserved5; //-V122
ULONG Reserved6;
PVOID Reserved7; //-V122
ULONG Reserved8;
ULONG AtlThunkSListPtr32;
PVOID Reserved9[45]; //-V122
BYTE Reserved10[96];
PPS_POST_PROCESS_INIT_ROUTINE PostProcessInitRoutine; //-V122
BYTE Reserved11[128];
PVOID Reserved12[1]; //-V122
ULONG SessionId;
} PEB, *PPEB;
#pragma warning(pop)
#if !defined(__NTNATIVE_H_VER__)
typedef struct _TEB // xref: http://terminus.rewolf.pl/terminus/structures/ntdll/_TEB_combined.html
{
NT_TIB NtTib;
PVOID EnvironmentPointer; //-V122
struct
{
HANDLE UniqueProcess; //-V122
HANDLE UniqueThread; //-V122
} ClientId;
PVOID ActiveRpcHandle; //-V122
PVOID ThreadLocalStoragePointer; //-V122
struct NT::_PEB* ProcessEnvironmentBlock; //-V122
ULONG LastErrorValue;
ULONG CountOfOwnedCriticalSections;
PVOID CsrClientThread; //-V122
PVOID Win32ThreadInfo; //-V122
ULONG User32Reserved[26];
ULONG UserReserved[5];
PVOID WOW32Reserved; //-V122
LCID CurrentLocale;
ULONG FpSoftwareStatusRegister;
PVOID ReservedForDebuggerInstrumentation[16]; //-V122
PVOID SystemReserved1[38]; //-V122
NTSTATUS ExceptionCode;
# ifdef _M_X64
ULONG UnknownAndDontCare[0x55D];
# elif defined(_M_IX86)
ULONG UnknownAndDontCare[0x396];
# endif // _M_X64
// Padding up to size 0x1838
} TEB, *PTEB;
#endif // !defined(__NTNATIVE_H_VER__)
#ifdef _M_X64
static_assert(sizeof(TEB) == 0x1838, "Expected size to be a fixed, known value");
#elif defined(_M_IX86)
static_assert(sizeof(TEB) == 0x1000, "Expected size to be a fixed, known value");
#endif // _M_X64
template <typename> struct NTSTRING
{
};
template <> struct NTSTRING<WCHAR>
{
typedef UNICODE_STRING string_type;
typedef WCHAR char_type;
};
template <> struct NTSTRING<CHAR>
{
typedef ANSI_STRING string_type;
typedef CHAR char_type;
};
template <> struct NTSTRING<UNICODE_STRING>
{
typedef UNICODE_STRING string_type;
typedef WCHAR char_type;
};
template <> struct NTSTRING<ANSI_STRING>
{
typedef ANSI_STRING string_type;
typedef CHAR char_type;
};
template <typename T> using strchar_t = typename NTSTRING<T>::char_type;
template <typename T> using strtype_t = typename NTSTRING<T>::string_type;
// Just to avoid pulling in type_traits header for this
template <typename, typename> constexpr bool is_same_v = false;
template <typename T> constexpr bool is_same_v<T, T> = true;
inline namespace ntdll
{
STATIC_INLINE TEB* NtCurrentTeb()
{
#if defined(_WIN64) && defined(_M_X64)
return (TEB*)__readgsqword(FIELD_OFFSET(NT_TIB, Self)); //-V202
# ifdef _MSVC_LANG
static_assert(FIELD_OFFSET(NT_TIB, Self) == 0x30, "Something is wrong with the NT_TIB struct"); //-V202
# endif // _MSVC_LANG
#elif defined(_WIN32) && defined(_M_IX86)
return (TEB*)__readfsdword(FIELD_OFFSET(NT_TIB, Self));
# ifdef _MSVC_LANG
static_assert(FIELD_OFFSET(NT_TIB, Self) == 0x18, "Something is wrong with the NT_TIB struct");
# endif // _MSVC_LANG
#else
# error This isn't currently implemented on the current platform, it seems. Review the code, implement it and retry.
#endif
}
STATIC_INLINE PEB* RtlGetCurrentPeb() // officially with winver>=5.1
{
#if defined(_WIN64) && defined(_M_X64)
return (PEB*)__readgsqword(0x60);
#elif defined(_WIN32) && defined(_M_IX86)
return (PEB*)__readfsdword(0x30);
#else
return NtCurrentTeb()->ProcessEnvironmentBlock;
#endif
}
// Reimplementation of a few functions we don't want to import
namespace crt
{
STATIC_INLINE size_t strlen_(char const* str)
{
if (!str)
return 0;
size_t idx;
for (idx = 0; str[idx]; idx++)
;
return idx;
}
STATIC_INLINE size_t wcslen_(wchar_t const* str)
{
if (!str)
return 0;
size_t idx;
for (idx = 0; str[idx]; idx++)
;
return idx;
}
STATIC_INLINE int strncmp_(char const* s1, char const* s2, size_t len)
{
if ((!s1 && !s2) || !len)
{
return 0;
}
else if (!s1 && s2)
{
return -1;
}
else if (s1 && !s2)
{
return 1;
}
byte const* bs1 = (byte*)s1;
byte const* bs2 = (byte*)s2;
for (size_t idx = 0; idx <= len; idx++)
{
auto const& b1 = bs1[idx]; //-V522
auto const& b2 = bs2[idx]; //-V522
if (b1 != b2)
{
return b1 - b2;
}
if (('\0' == b1) || ('\0' == b2))
{
return b1 - b2;
}
}
return 0;
}
STATIC_INLINE int wcsncmp_(wchar_t const* s1, wchar_t const* s2, size_t len)
{
if ((!s1 && !s2) || !len)
{
return 0;
}
else if (!s1 && s2)
{
return -1;
}
else if (s1 && !s2)
{
return 1;
}
unsigned short const* bs1 = (unsigned short*)s1;
unsigned short const* bs2 = (unsigned short*)s2;
for (size_t idx = 0; idx <= len; idx++)
{
auto const& b1 = bs1[idx]; //-V522
auto const& b2 = bs2[idx]; //-V522
if (b1 != b2)
{
return b1 - b2;
}
if ((L'\0' == b1) || (L'\0' == b2))
{
return b1 - b2;
}
}
return 0;
}
#if NTPEBLDR_NAIVE_CRT_INLINES
// Certainly naive and incomplete, but in all likelihood more than sufficient
// for most purposes we're after here
STATIC_INLINE WCHAR towlower_(WCHAR ch)
{
if ((L'A' <= ch) && (ch <= L'Z'))
ch += 0x20; //-V112
return ch;
}
STATIC_INLINE WCHAR towupper_(WCHAR ch)
{
if ((L'a' <= ch) && (ch <= L'z'))
ch -= 0x20; //-V112
return ch;
}
STATIC_INLINE CHAR tolower_(CHAR ch)
{
if (('A' <= ch) && (ch <= 'Z'))
ch += 0x20; //-V112
return ch;
}
STATIC_INLINE CHAR toupper_(CHAR ch)
{
if (('a' <= ch) && (ch <= 'z'))
ch -= 0x20; //-V112
return ch;
}
#else
// The right side is _intentionally_ without namespace, so a preprocessor
// define could still be used to point these elsewhere ...
wint_t (*towlower_)(wint_t) = towlower;
wint_t (*towupper_)(wint_t) = towupper;
int (*tolower_)(int) = tolower;
int (*toupper_)(int) = toupper;
#endif
template <typename CHARTYPE> struct tocasing;
template <> struct tocasing<WCHAR>
{
STATIC_INLINE WCHAR toupper(WCHAR ch)
{
return (WCHAR)towupper_(ch);
}
STATIC_INLINE WCHAR tolower(WCHAR ch)
{
return (WCHAR)towlower_(ch);
}
};
template <> struct tocasing<CHAR>
{
STATIC_INLINE CHAR toupper(CHAR ch)
{
return (CHAR)toupper_(ch);
}
STATIC_INLINE CHAR tolower(CHAR ch)
{
return (CHAR)tolower_(ch);
}
};
template <typename CHARTYPE> STATIC_INLINE CHARTYPE toupper(CHARTYPE ch)
{
return tocasing<CHARTYPE>::toupper(ch);
}
template <typename CHARTYPE> STATIC_INLINE CHARTYPE tolower(CHARTYPE ch)
{
return tocasing<CHARTYPE>::tolower(ch);
}
// This is not exactly optimized, but should be a halfway faithful implementation of the original functionality
template <typename STRTYPE> STATIC_INLINE LONG CompareStringT(STRTYPE const& String1, STRTYPE const& String2, BOOLEAN CaseInSensitive)
{
using CHARTYPE = strchar_t<STRTYPE>;
CHARTYPE* str1 = String1.Buffer;
CHARTYPE* str2 = String2.Buffer;
size_t const len1 = String1.Length / sizeof(CHARTYPE);
size_t const len2 = String2.Length / sizeof(CHARTYPE);
size_t const minlen = (len1 <= len2) ? len1 : len2;
if (CaseInSensitive)
{
for (size_t idx = 0; idx < minlen; idx++)
{
if (str1[idx] != str2[idx])
{
auto const c1 = toupper(str1[idx]);
auto const c2 = toupper(str2[idx]);
if (c1 != c2)
{
return (LONG)c1 - (LONG)c2;
}
}
}
}
else
{
for (size_t idx = 0; idx < minlen; idx++)
{
if (str1[idx] != str2[idx])
{
return (LONG)str1[idx] - (LONG)str2[idx];
}
}
}
return (LONG)(len1 - len2); //-V202
}
} // namespace crt
STATIC_INLINE LONG RtlCompareUnicodeString(PCUNICODE_STRING String1, PCUNICODE_STRING String2, BOOLEAN CaseInSensitive)
{
return crt::CompareStringT(*String1, *String2, CaseInSensitive);
}
typedef STRING* PSTRING;
typedef const STRING* PCSTRING; // winternl.h is missing the const
STATIC_INLINE LONG RtlCompareString(PCSTRING String1, PCSTRING String2, BOOLEAN CaseInSensitive)
{
return crt::CompareStringT(*String1, *String2, CaseInSensitive);
}
// This is not exactly optimized, but should be a halfway faithful implementation of the original functionality
STATIC_INLINE VOID RtlInitUnicodeString(PUNICODE_STRING DestinationString, LPCWSTR SourceString)
{
DestinationString->Buffer = const_cast<LPWSTR>(SourceString);
if (SourceString)
{
size_t const idx = ntdll::crt::wcslen_(SourceString);
// TBD: should we check against 0x8000? Does the actual ntdll implementation do it?
DestinationString->Length = (USHORT)idx * sizeof(SourceString[idx]);
DestinationString->MaximumLength = DestinationString->Length + sizeof(SourceString[idx]);
}
else
{
DestinationString->Length = DestinationString->MaximumLength = 0;
}
}
STATIC_INLINE DWORD RtlGetLastWin32Error()
{
return NtCurrentTeb()->LastErrorValue;
}
#if !defined(__NTNATIVE_H_VER__)
STATIC_INLINE ULONG NTAPI RtlSetLastWin32Error(DWORD dwError)
{
((NT::TEB*)NtCurrentTeb())->LastErrorValue = dwError;
return dwError;
}
STATIC_INLINE DWORD RtlSetLastWin32ErrorAndNtStatusFromNtStatus(NTSTATUS Status)
{
DWORD dwWin32Error = ::RtlNtStatusToDosError(Status); // ERROR_MR_MID_NOT_FOUND if no corresponding Win32 status exists
return RtlSetLastWin32Error(dwWin32Error); // RtlSetLastWin32Error
}
#endif // !defined(__NTNATIVE_H_VER__)
} // namespace ntdll
inline namespace util
{
template <typename CHARTYPE, size_t MaxLength>
STATIC_INLINE constexpr strtype_t<CHARTYPE> const InitString(CHARTYPE const (&str)[MaxLength], USHORT ActualLength)
{
static_assert(MaxLength == sizeof(str) / sizeof(str[0]), "Well, crap ...");
return {ActualLength, sizeof(str), const_cast<CHARTYPE*>(&str[0])};
}
template <typename CHARTYPE, size_t MaxLength> STATIC_INLINE constexpr strtype_t<CHARTYPE> const InitString(CHARTYPE const (&str)[MaxLength])
{
return InitString(str, sizeof(str) - sizeof(str[0]));
}
template <typename STRTYPE> constexpr STATIC_INLINE size_t StringEndsWith(STRTYPE const& String, STRTYPE const& Suffix, BOOLEAN CaseInSensitive = TRUE)
{
size_t const Offset = (String.Length / sizeof(String.Buffer[0])) - (Suffix.Length / sizeof(Suffix.Buffer[0]));
STRTYPE const sSuspectedSuffix = {Suffix.Length, Suffix.MaximumLength, &String.Buffer[Offset]};
return (0 == ntdll::crt::CompareStringT(Suffix, sSuspectedSuffix, CaseInSensitive)) ? Offset : 0;
}
template <typename CHARTYPE, size_t Length, typename STRTYPE = strtype_t<CHARTYPE>>
constexpr STATIC_INLINE size_t StringEndsWith(STRTYPE const& String, CHARTYPE const (&Suffix)[Length], BOOLEAN CaseInSensitive = TRUE)
{
STRTYPE const sSuffix = InitString(Suffix);
return StringEndsWith(String, sSuffix, CaseInSensitive);
}
template <typename STRTYPE>
constexpr STATIC_INLINE STRTYPE TruncateStringAt(STRTYPE const& String, STRTYPE const& Suffix, BOOLEAN CaseInSensitive = TRUE)
{
auto const Offset = StringEndsWith(String, Suffix, CaseInSensitive);
if (!Offset)
{
return String;
}
USHORT const NewLength = (USHORT)((USHORT)Offset * sizeof(String.Buffer[0]));
USHORT const Difference = (String.Length - NewLength);
STRTYPE const sRetVal = {NewLength, (USHORT)(String.MaximumLength - Difference), String.Buffer};
return sRetVal;
}
template <typename CHARTYPE, size_t Length, typename STRTYPE = strtype_t<CHARTYPE>>
constexpr STATIC_INLINE STRTYPE TruncateStringAt(STRTYPE const& String, CHARTYPE const (&Suffix)[Length], BOOLEAN CaseInSensitive = TRUE)
{
STRTYPE const sSuffix = InitString(Suffix);
return TruncateStringAt(String, sSuffix, CaseInSensitive);
}
} // namespace util
STATIC_INLINE PEB_LDR_DATA* GetPebLdr()
{
PEB* peb = ntdll::RtlGetCurrentPeb();
if (peb)
{
return (PEB_LDR_DATA*)peb->Ldr;
}
return nullptr;
}
enum class PebLdrOrder : unsigned char
{
load,
memory,
init,
};
STATIC_INLINE LIST_ENTRY const* GetPebLdrListHead(PEB_LDR_DATA const* ldrdata, PebLdrOrder order)
{
if (!ldrdata)
{
return nullptr;
}
switch (order)
{
case PebLdrOrder::load:
return ldrdata->InLoadOrderModuleList.Flink;
case PebLdrOrder::memory:
return ldrdata->InMemoryOrderModuleList.Flink;
case PebLdrOrder::init:
return ldrdata->InInitializationOrderModuleList.Flink;
}
return nullptr;
}
STATIC_INLINE LIST_ENTRY const* GetPebLdrListHead(PebLdrOrder order)
{
PEB_LDR_DATA const* ldrdata = GetPebLdr();
return GetPebLdrListHead(ldrdata, order);
}
STATIC_INLINE LDR_DATA_TABLE_ENTRY const* GetLdrDataTableEntry(LIST_ENTRY const* current, PebLdrOrder order)
{
switch (order)
{
case PebLdrOrder::load:
return CONTAINING_RECORD(current, LDR_DATA_TABLE_ENTRY, InLoadOrderModuleList);
case PebLdrOrder::memory:
return CONTAINING_RECORD(current, LDR_DATA_TABLE_ENTRY, InMemoryOrderModuleList);
case PebLdrOrder::init:
return CONTAINING_RECORD(current, LDR_DATA_TABLE_ENTRY, InInitializationOrderModuleList);
}
return nullptr;
}
STATIC_INLINE LDR_DATA_TABLE_ENTRY_CTX const* GetLdrDataTableEntryPredicateContext(LIST_ENTRY const* current, PebLdrOrder order)
{
auto const* entry = GetLdrDataTableEntry(current, order);
if (entry)
{
return &((Glue::LDR_DATA_TABLE_ENTRY*)entry)->tail.context;
}
return nullptr;
}
template <typename T, PebLdrOrder order_v> struct callback
{
static PebLdrOrder const order = order_v;
using data_t = T;
using func_t = NTSTATUS(CALLBACK*)(LDR_DATA_TABLE_ENTRY_CTX const&, LDR_DATA_TABLE_ENTRY const*, T&);
};
template <typename T, PebLdrOrder order_v> using cbfunc_t = typename callback<T, order_v>::func_t;
template <typename T, PebLdrOrder order_v> using cbdata_t = typename callback<T, order_v>::data_t;
template <typename T, PebLdrOrder order_v = PebLdrOrder::load>
STATIC_INLINE NTSTATUS IteratePebLdrDataTable(cbfunc_t<T, order_v> predicate, cbdata_t<T, order_v>& context)
{
constexpr PebLdrOrder const order = callback<T, order_v>::order;
auto const* first = GetPebLdrListHead(order);
if (!first)
{
return STATUS_INVALID_HANDLE;
}
auto const* current = first;
do
{
auto const* tblentry = GetLdrDataTableEntryPredicateContext(current, order);
auto const* curr_entry = GetLdrDataTableEntry(current, order);
NTSTATUS Status;
if (STATUS_NOT_FOUND != (Status = predicate(*tblentry, curr_entry, context))) //-V522
{
return Status;
}
current = current->Flink;
} while (current != first);
return STATUS_NO_MORE_ENTRIES; // we've reached the list end
}
#if defined(NTPEBLDR_PRINT_FUNCS) || defined(_DEBUG)
inline namespace print_helpers
{
STATIC_INLINE void print_ldr_entry_ctx(LDR_DATA_TABLE_ENTRY_CTX const& ldrctx, bool skip_terminator = true)
{
if (skip_terminator && !ldrctx.DllBase && !ldrctx.SizeOfImage && !ldrctx.EntryPoint && !ldrctx.Flags && !ldrctx.BaseDllName.Buffer)
{
return;
}
_tprintf(_T(" PVOID DllBase = @%p;\n"), ldrctx.DllBase);
_tprintf(_T(" PVOID EntryPoint = @%p;\n"), ldrctx.EntryPoint);
_tprintf(_T(" ULONG SizeOfImage = %u (0x%08X);\n"), ldrctx.SizeOfImage, ldrctx.SizeOfImage);
_tprintf(_T(" UNICODE_STRING FullDllName = \"%wZ\";\n"), &ldrctx.FullDllName);
_tprintf(_T(" UNICODE_STRING BaseDllName = \"%wZ\";\n"), &ldrctx.BaseDllName);
_tprintf(_T(" ULONG Flags = 0x%08X);\n"), ldrctx.Flags);
}
STATIC_INLINE void print_ldr_entry(LDR_DATA_TABLE_ENTRY const& ldrentry, bool nolinks = false)
{
_tprintf(_T("((LDR_DATA_TABLE_ENTRY*)@%p)\n"), &ldrentry);
if (!nolinks)
{
_tprintf(_T(" LIST_ENTRY InLoadOrderModuleList = {Flink = @%p, Blink = @%p};\n"),
ldrentry.InLoadOrderModuleList.Flink,
ldrentry.InLoadOrderModuleList.Blink);
_tprintf(_T(" LIST_ENTRY InMemoryOrderModuleList = {Flink = @%p, Blink = @%p};\n"),
ldrentry.InMemoryOrderModuleList.Flink,
ldrentry.InMemoryOrderModuleList.Blink);
_tprintf(_T(" LIST_ENTRY InInitializationOrderModuleList = {Flink = @%p, Blink = @%p};\n"),
ldrentry.InInitializationOrderModuleList.Flink,
ldrentry.InInitializationOrderModuleList.Blink);
}
auto const& ldrctx = ((Glue::LDR_DATA_TABLE_ENTRY*)&ldrentry)->tail.context;
print_ldr_entry_ctx(ldrctx);
_tprintf(_T(" ULONG TimeDateStamp = 0x%08X;\n"), ldrentry.TimeDateStamp);
}
STATIC_INLINE void print_linked_list(LIST_ENTRY const* first, PebLdrOrder order, BOOLEAN bShowFullName = FALSE)
{
auto const* current = first;
ULONG idx = 0;
do
{
auto const* e = GetLdrDataTableEntryPredicateContext(current, order);
if (e && e->DllBase && e->SizeOfImage && e->BaseDllName.Buffer && e->FullDllName.Buffer)
{
_tprintf(
_T(" [% 2u] @%p, %wZ: s = %u, f = 0x%08X, ep = @%p\n"), idx, e->DllBase, &e->BaseDllName, e->SizeOfImage, e->Flags, e->EntryPoint);
if (bShowFullName)
{
_tprintf(_T(" %wZ\n"), &e->FullDllName);
}
}
current = current->Flink;
idx++;
} while (current != first);
}
STATIC_INLINE void print_ldr_data(PEB_LDR_DATA const& ldrdata, bool nolinks = false)
{
_tprintf(_T("((PEB_LDR_DATA*)@%p)\n"), &ldrdata);
_tprintf(_T(" ULONG Length = %u (0x%08X);\n"), ldrdata.Length, ldrdata.Length);
_tprintf(_T(" BOOLEAN Initialized = %u;\n"), ldrdata.Initialized);
_tprintf(_T(" HANDLE SsHandle = @%p;\n"), ldrdata.SsHandle);
if (!nolinks)
{
_tprintf(_T(" LIST_ENTRY InLoadOrderModuleList = {Flink = @%p, Blink = @%p};\n"),
ldrdata.InLoadOrderModuleList.Flink,
ldrdata.InLoadOrderModuleList.Blink);
print_linked_list(ldrdata.InLoadOrderModuleList.Flink, PebLdrOrder::load);
_tprintf(_T(" LIST_ENTRY InMemoryOrderModuleList = {Flink = @%p, Blink = @%p};\n"),
ldrdata.InMemoryOrderModuleList.Flink,
ldrdata.InMemoryOrderModuleList.Blink);
print_linked_list(ldrdata.InMemoryOrderModuleList.Flink, PebLdrOrder::memory);
_tprintf(_T(" LIST_ENTRY InInitializationOrderModuleList = {Flink = @%p, Blink = @%p};\n"),
ldrdata.InInitializationOrderModuleList.Flink,
ldrdata.InInitializationOrderModuleList.Blink);
print_linked_list(ldrdata.InInitializationOrderModuleList.Flink, PebLdrOrder::init);
}
}
} // namespace print_helpers
#endif
STATIC_INLINE NT::LDR_DATA_TABLE_ENTRY const* GetNtDllEntry()
{
constexpr PebLdrOrder const order = PebLdrOrder::load;
auto const* head = GetPebLdrListHead(order);
if (head)
{
return GetLdrDataTableEntry(head->Flink, order);
}
return nullptr;
}
STATIC_INLINE HMODULE GetNtDll()
{
auto const* ldrentry = GetNtDllEntry();
if (ldrentry)
{
return (HMODULE)ldrentry->DllBase;
}
return nullptr;
}
STATIC_INLINE UNICODE_STRING GetNtDllDirectory()
{
auto const* ntdll = GetNtDllEntry();
if (ntdll)
{
return TruncateStringAt(ntdll->FullDllName, ntdll->BaseDllName, TRUE);
}
return {};
}
namespace predefined_helpers
{
namespace by_order
{
typedef struct _MapByOrder
{
ULONG IndexToBeIncremented; // incremented inside the callback
ULONG IndexToLookFor;
PVOID DllBase; //-V122
LDR_DATA_TABLE_ENTRY const* LdrDataTableEntry; //-V122
} MapByOrder;
STATIC_INLINE NTSTATUS CALLBACK MapOrderPredicate(LDR_DATA_TABLE_ENTRY_CTX const& ldrctx,
LDR_DATA_TABLE_ENTRY const* ldrdataentry,
MapByOrder& data)
{
if (ldrctx.DllBase && ldrctx.SizeOfImage && (data.IndexToLookFor == data.IndexToBeIncremented))
{
data.DllBase = ldrctx.DllBase;
data.LdrDataTableEntry = ldrdataentry;
return STATUS_SUCCESS;
}
data.IndexToBeIncremented++;
return STATUS_NOT_FOUND;
}
template <PebLdrOrder order_v = PebLdrOrder::load> STATIC_INLINE HMODULE GetModHandleByOrderIndex(ULONG Index)
{
MapByOrder context = {0, Index, nullptr, nullptr};
NTSTATUS Status = IteratePebLdrDataTable<MapByOrder, order_v>(MapOrderPredicate, context);
if (NT_SUCCESS(Status))
{
return (HMODULE)context.DllBase;
}
return nullptr;
}
template <PebLdrOrder order_v = PebLdrOrder::load> STATIC_INLINE LDR_DATA_TABLE_ENTRY const* GetLdrDataEntryByOrderIndex(ULONG Index)
{
MapByOrder context = {0, Index, nullptr, nullptr};
NTSTATUS Status = IteratePebLdrDataTable<MapByOrder, order_v>(MapOrderPredicate, context);
if (NT_SUCCESS(Status))
{
return context.LdrDataTableEntry;
}
return nullptr;
}
} // namespace by_order
namespace by_trait
{
typedef struct _MapByTrait
{ //-V802
NTSTATUS Status;
PVOID Address; //-V122
PVOID DllBase; //-V122
LDR_DATA_TABLE_ENTRY const* LdrDataTableEntry; //-V122
ULONG SizeOfImage;
} MapByTrait;
STATIC_INLINE NTSTATUS CALLBACK MapTraitPredicate(LDR_DATA_TABLE_ENTRY_CTX const& ldrctx,
LDR_DATA_TABLE_ENTRY const* ldrdataentry,
MapByTrait& data)
{
if (ldrctx.DllBase && ldrctx.SizeOfImage && (data.Address || data.DllBase))
{
if ((data.DllBase) && (ldrctx.DllBase == data.DllBase))
{
if (!data.Address) // No address to look for given?
{
data.SizeOfImage = ldrctx.SizeOfImage;
data.LdrDataTableEntry = ldrdataentry;
return data.Status = STATUS_SUCCESS; // Found it!
} // fall through into the other check
}
if (data.Address)
{
if (data.DllBase && (ldrctx.DllBase != data.DllBase)) // If we were passed a module, does it match?
{
return STATUS_NOT_FOUND; // Nope, so return failure early (will proceed to next ldr entry)
}
auto const* needle = (byte*)data.Address;
auto const* haystack_start = (byte*)ldrctx.DllBase;
auto const* haystack_end = haystack_start + ldrctx.SizeOfImage; //-V104
if ((needle >= haystack_start) && (needle <= haystack_end))
{
data.DllBase = ldrctx.DllBase;
data.SizeOfImage = ldrctx.SizeOfImage;
data.LdrDataTableEntry = ldrdataentry;
return data.Status = STATUS_SUCCESS;
}
}
}
return data.Status = STATUS_NOT_FOUND;
}
STATIC_INLINE HMODULE GetModHandleByAddress(PVOID Address)
{
MapByTrait context = {STATUS_UNSUCCESSFUL, Address, nullptr, nullptr, 0};
NTSTATUS Status = IteratePebLdrDataTable<MapByTrait>(MapTraitPredicate, context);
if (NT_SUCCESS(Status))
{
return (HMODULE)context.DllBase;
}
return nullptr;
}
STATIC_INLINE MapByTrait GetModTraits(HMODULE hMod)
{
MapByTrait context = {STATUS_UNSUCCESSFUL, nullptr, hMod, nullptr, 0};
(void)IteratePebLdrDataTable<MapByTrait>(MapTraitPredicate, context);
return context;
}