This repository was archived by the owner on Jan 23, 2023. It is now read-only.
- Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathutil.cpp
3339 lines (2803 loc) · 106 KB
/
util.cpp
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//*****************************************************************************
// util.cpp
//
//
// This contains a bunch of C++ utility classes.
//
//*****************************************************************************
#include"stdafx.h"// Precompiled header key.
#include"utilcode.h"
#include"metadata.h"
#include"ex.h"
#include"pedecoder.h"
#include"loaderheap.h"
#include"sigparser.h"
#include"cor.h"
#include"corinfo.h"
#include"volatile.h"
#ifndef DACCESS_COMPILE
UINT32 g_nClrInstanceId = 0;
#endif//!DACCESS_COMPILE
//********** Code. ************************************************************
#if defined(FEATURE_COMINTEROP) && !defined(FEATURE_CORESYSTEM)
extern WinRTStatusEnum gWinRTStatus = WINRT_STATUS_UNINITED;
#endif// FEATURE_COMINTEROP && !FEATURE_CORESYSTEM
#if defined(FEATURE_COMINTEROP) && !defined(FEATURE_CORESYSTEM)
//------------------------------------------------------------------------------
//
// Attempt to detect the presense of Windows Runtime support on the current OS.
// Our algorithm to do this is to ensure that:
// 1. combase.dll exists
// 2. combase.dll contains a RoInitialize export
//
voidInitWinRTStatus()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_CANNOT_TAKE_LOCK;
WinRTStatusEnum winRTStatus = WINRT_STATUS_UNSUPPORTED;
const WCHAR wszComBaseDll[] = W("\\combase.dll");
const SIZE_T cchComBaseDll = _countof(wszComBaseDll);
WCHAR wszComBasePath[MAX_LONGPATH + 1];
const SIZE_T cchComBasePath = _countof(wszComBasePath);
ZeroMemory(wszComBasePath, cchComBasePath * sizeof(wszComBasePath[0]));
UINT cchSystemDirectory = WszGetSystemDirectory(wszComBasePath, MAX_LONGPATH);
// Make sure that we're only probing in the system directory. If we can't find the system directory, or
// we find it but combase.dll doesn't fit into it, we'll fall back to a safe default of saying that WinRT
// is simply not present.
if (cchSystemDirectory > 0 && cchComBasePath - cchSystemDirectory >= cchComBaseDll)
{
if (wcscat_s(wszComBasePath, wszComBaseDll) == 0)
{
HModuleHolder hComBase(WszLoadLibrary(wszComBasePath));
if (hComBase != NULL)
{
FARPROC activateInstace = GetProcAddress(hComBase, "RoInitialize");
if (activateInstace != NULL)
{
winRTStatus = WINRT_STATUS_SUPPORTED;
}
}
}
}
gWinRTStatus = winRTStatus;
}
#endif// FEATURE_COMINTEROP && !FEATURE_CORESYSTEM
//*****************************************************************************
// Convert a string of hex digits into a hex value of the specified # of bytes.
//*****************************************************************************
HRESULT GetHex( // Return status.
LPCSTR szStr, // String to convert.
int size, // # of bytes in pResult.
void *pResult) // Buffer for result.
{
CONTRACTL
{
NOTHROW;
}
CONTRACTL_END;
int count = size * 2; // # of bytes to take from string.
unsignedint Result = 0; // Result value.
char ch;
_ASSERTE(size == 1 || size == 2 || size == 4);
while (count-- && (ch = *szStr++) != '\0')
{
switch (ch)
{
case'0': case'1': case'2': case'3': case'4':
case'5': case'6': case'7': case'8': case'9':
Result = 16 * Result + (ch - '0');
break;
case'A': case'B': case'C': case'D': case'E': case'F':
Result = 16 * Result + 10 + (ch - 'A');
break;
case'a': case'b': case'c': case'd': case'e': case'f':
Result = 16 * Result + 10 + (ch - 'a');
break;
default:
return (E_FAIL);
}
}
// Set the output.
switch (size)
{
case1:
*((BYTE *) pResult) = (BYTE) Result;
break;
case2:
*((WORD *) pResult) = (WORD) Result;
break;
case4:
*((DWORD *) pResult) = Result;
break;
default:
_ASSERTE(0);
break;
}
return (S_OK);
}
//*****************************************************************************
// Convert a pointer to a string into a GUID.
//*****************************************************************************
HRESULT LPCSTRToGuid( // Return status.
LPCSTR szGuid, // String to convert.
GUID *psGuid) // Buffer for converted GUID.
{
CONTRACTL
{
NOTHROW;
}
CONTRACTL_END;
int i;
// Verify the surrounding syntax.
if (strlen(szGuid) != 38 || szGuid[0] != '{' || szGuid[9] != '-' ||
szGuid[14] != '-' || szGuid[19] != '-' || szGuid[24] != '-' || szGuid[37] != '}')
{
return (E_FAIL);
}
// Parse the first 3 fields.
if (FAILED(GetHex(szGuid + 1, 4, &psGuid->Data1)))
return E_FAIL;
if (FAILED(GetHex(szGuid + 10, 2, &psGuid->Data2)))
return E_FAIL;
if (FAILED(GetHex(szGuid + 15, 2, &psGuid->Data3)))
return E_FAIL;
// Get the last two fields (which are byte arrays).
for (i = 0; i < 2; ++i)
{
if (FAILED(GetHex(szGuid + 20 + (i * 2), 1, &psGuid->Data4[i])))
{
return E_FAIL;
}
}
for (i=0; i < 6; ++i)
{
if (FAILED(GetHex(szGuid + 25 + (i * 2), 1, &psGuid->Data4[i+2])))
{
return E_FAIL;
}
}
return S_OK;
}
//
//
// Global utility functions.
//
//
typedef HRESULT __stdcall DLLGETCLASSOBJECT(REFCLSID rclsid,
REFIID riid,
void **ppv);
EXTERN_C const IID _IID_IClassFactory =
{0x00000001, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};
namespace
{
HRESULT FakeCoCallDllGetClassObject(
REFCLSID rclsid,
LPCWSTR wszDllPath,
REFIID riid,
void **ppv,
HMODULE *phmodDll)
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
_ASSERTE(ppv != nullptr);
HRESULT hr = S_OK;
// Initialize [out] HMODULE (if it was requested)
if (phmodDll != nullptr)
*phmodDll = nullptr;
boolfIsDllPathPrefix = (wszDllPath != nullptr) && (wcslen(wszDllPath) > 0) && (wszDllPath[wcslen(wszDllPath) - 1] == W('\\'));
// - An empty string will be treated as NULL.
// - A string ending will a backslash will be treated as a prefix for where to look for the DLL
// if the InProcServer32 value is just a DLL name and not a full path.
StackSString ssDllName;
if ((wszDllPath == nullptr) || (wszDllPath[0] == W('\0')) || fIsDllPathPrefix)
{
#ifndef FEATURE_PAL
IfFailRet(Clr::Util::Com::FindInprocServer32UsingCLSID(rclsid, ssDllName));
EX_TRY
{
if (fIsDllPathPrefix)
{
SString::Iterator i = ssDllName.Begin();
if (!ssDllName.Find(i, W('\\')))
{ // If the InprocServer32 is just a DLL name (not a fully qualified path), then
// prefix wszFilePath with wszDllPath.
ssDllName.Insert(i, wszDllPath);
}
}
}
EX_CATCH_HRESULT(hr);
IfFailRet(hr);
wszDllPath = ssDllName.GetUnicode();
#else// !FEATURE_PAL
return E_FAIL;
#endif// !FEATURE_PAL
}
_ASSERTE(wszDllPath != nullptr);
// We've got the name of the DLL to load, so load it.
HModuleHolder hDll = WszLoadLibraryEx(wszDllPath, nullptr, GetLoadWithAlteredSearchPathFlag());
if (hDll == nullptr)
returnHRESULT_FROM_GetLastError();
// We've loaded the DLL, so find the DllGetClassObject function.
DLLGETCLASSOBJECT *dllGetClassObject = (DLLGETCLASSOBJECT*)GetProcAddress(hDll, "DllGetClassObject");
if (dllGetClassObject == nullptr)
returnHRESULT_FROM_GetLastError();
// Call the function to get a class object for the rclsid and riid passed in.
IfFailRet(dllGetClassObject(rclsid, riid, ppv));
hDll.SuppressRelease();
if (phmodDll != nullptr)
*phmodDll = hDll.GetValue();
return hr;
}
}
// ----------------------------------------------------------------------------
// FakeCoCreateInstanceEx
//
// Description:
// A private function to do the equivalent of a CoCreateInstance in cases where we
// can't make the real call. Use this when, for instance, you need to create a symbol
// reader in the Runtime but we're not CoInitialized. Obviously, this is only good
// for COM objects for which CoCreateInstance is just a glorified find-and-load-me
// operation.
//
// Arguments:
// * rclsid - [in] CLSID of object to instantiate
// * wszDllPath [in] - Path to profiler DLL. If wszDllPath is NULL, FakeCoCreateInstanceEx
// will look up the registry to find the path of the COM dll associated with rclsid.
// If the path ends in a backslash, FakeCoCreateInstanceEx will treat this as a prefix
// if the InprocServer32 found in the registry is a simple filename (not a full path).
// This allows the caller to specify the directory in which the InprocServer32 should
// be found.
// * riid - [in] IID of interface on object to return in ppv
// * ppv - [out] Pointer to implementation of requested interface
// * phmodDll - [out] HMODULE of DLL that was loaded to instantiate the COM object.
// The caller may eventually call FreeLibrary() on this if it can be determined
// that we no longer reference the generated COM object or dependencies. Else, the
// caller may ignore this and the DLL will stay loaded forever. If caller
// specifies phmodDll==NULL, then this parameter is ignored and the HMODULE is not
// returned.
//
// Return Value:
// HRESULT indicating success or failure.
//
// Notes:
// * (*phmodDll) on [out] may always be trusted, even if this function returns an
// error. Therefore, even if creation of the COM object failed, if (*phmodDll !=
// NULL), then the DLL was actually loaded. The caller may wish to call
// FreeLibrary on (*phmodDll) in such a case.
HRESULT FakeCoCreateInstanceEx(REFCLSID rclsid,
LPCWSTR wszDllPath,
REFIID riid,
void ** ppv,
HMODULE * phmodDll)
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
HRESULT hr = S_OK;
// Call the function to get a class factory for the rclsid passed in.
HModuleHolder hDll;
ReleaseHolder<IClassFactory> classFactory;
IfFailRet(FakeCoCallDllGetClassObject(rclsid, wszDllPath, _IID_IClassFactory, (void**)&classFactory, &hDll));
// Ask the class factory to create an instance of the
// necessary object.
IfFailRet(classFactory->CreateInstance(NULL, riid, ppv));
hDll.SuppressRelease();
if (phmodDll != NULL)
{
*phmodDll = hDll.GetValue();
}
return hr;
}
#if USE_UPPER_ADDRESS
static BYTE * s_CodeMinAddr; // Preferred region to allocate the code in.
static BYTE * s_CodeMaxAddr;
static BYTE * s_CodeAllocStart;
static BYTE * s_CodeAllocHint; // Next address to try to allocate for code in the preferred region.
#endif
//
// Use this function to initialize the s_CodeAllocHint
// during startup. base is runtime .dll base address,
// size is runtime .dll virtual size.
//
voidInitCodeAllocHint(SIZE_T base, SIZE_T size, int randomPageOffset)
{
#if USE_UPPER_ADDRESS
#ifdef _DEBUG
// If GetForceRelocs is enabled we don't constrain the pMinAddr
if (PEDecoder::GetForceRelocs())
return;
#endif
//
// If we are using the UPPER_ADDRESS space (on Win64)
// then for any code heap that doesn't specify an address
// range using [pMinAddr..pMaxAddr] we place it in the
// upper address space
// This enables us to avoid having to use long JumpStubs
// to reach the code for our ngen-ed images.
// Which are also placed in the UPPER_ADDRESS space.
//
SIZE_T reach = 0x7FFF0000u;
// We will choose the preferred code region based on the address of clr.dll. The JIT helpers
// in clr.dll are the most heavily called functions.
s_CodeMinAddr = (base + size > reach) ? (BYTE *)(base + size - reach) : (BYTE *)0;
s_CodeMaxAddr = (base + reach > base) ? (BYTE *)(base + reach) : (BYTE *)-1;
BYTE * pStart;
if (s_CodeMinAddr <= (BYTE *)CODEHEAP_START_ADDRESS &&
(BYTE *)CODEHEAP_START_ADDRESS < s_CodeMaxAddr)
{
// clr.dll got loaded at its preferred base address? (OS without ASLR - pre-Vista)
// Use the code head start address that does not cause collisions with NGen images.
// This logic is coupled with scripts that we use to assign base addresses.
pStart = (BYTE *)CODEHEAP_START_ADDRESS;
}
else
if (base > UINT32_MAX)
{
// clr.dll got address assigned by ASLR?
// Try to occupy the space as far as possible to minimize collisions with other ASLR assigned
// addresses. Do not start at s_CodeMinAddr exactly so that we can also reach common native images
// that can be placed at higher addresses than clr.dll.
pStart = s_CodeMinAddr + (s_CodeMaxAddr - s_CodeMinAddr) / 8;
}
else
{
// clr.dll missed the base address?
// Try to occupy the space right after it.
pStart = (BYTE *)(base + size);
}
// Randomize the adddress space
pStart += GetOsPageSize() * randomPageOffset;
s_CodeAllocStart = pStart;
s_CodeAllocHint = pStart;
#endif
}
//
// Use this function to reset the s_CodeAllocHint
// after unloading an AppDomain
//
voidResetCodeAllocHint()
{
LIMITED_METHOD_CONTRACT;
#if USE_UPPER_ADDRESS
s_CodeAllocHint = s_CodeAllocStart;
#endif
}
//
// Returns TRUE if p is located in near clr.dll that allows us
// to use rel32 IP-relative addressing modes.
//
BOOL IsPreferredExecutableRange(void * p)
{
LIMITED_METHOD_CONTRACT;
#if USE_UPPER_ADDRESS
if (s_CodeMinAddr <= (BYTE *)p && (BYTE *)p < s_CodeMaxAddr)
returnTRUE;
#endif
returnFALSE;
}
//
// Allocate free memory that will be used for executable code
// Handles the special requirements that we have on 64-bit platforms
// where we want the executable memory to be located near clr.dll
//
BYTE * ClrVirtualAllocExecutable(SIZE_T dwSize,
DWORD flAllocationType,
DWORD flProtect)
{
CONTRACTL
{
NOTHROW;
}
CONTRACTL_END;
#if USE_UPPER_ADDRESS
//
// If we are using the UPPER_ADDRESS space (on Win64)
// then for any heap that will contain executable code
// we will place it in the upper address space
//
// This enables us to avoid having to use JumpStubs
// to reach the code for our ngen-ed images on x64,
// since they are also placed in the UPPER_ADDRESS space.
//
BYTE * pHint = s_CodeAllocHint;
if (dwSize <= (SIZE_T)(s_CodeMaxAddr - s_CodeMinAddr) && pHint != NULL)
{
// Try to allocate in the preferred region after the hint
BYTE * pResult = ClrVirtualAllocWithinRange(pHint, s_CodeMaxAddr, dwSize, flAllocationType, flProtect);
if (pResult != NULL)
{
s_CodeAllocHint = pResult + dwSize;
return pResult;
}
// Try to allocate in the preferred region before the hint
pResult = ClrVirtualAllocWithinRange(s_CodeMinAddr, pHint + dwSize, dwSize, flAllocationType, flProtect);
if (pResult != NULL)
{
s_CodeAllocHint = pResult + dwSize;
return pResult;
}
s_CodeAllocHint = NULL;
}
// Fall through to
#endif// USE_UPPER_ADDRESS
#ifdef FEATURE_PAL
// Tell PAL to use the executable memory allocator to satisfy this request for virtual memory.
// This will allow us to place JIT'ed code close to the coreclr library
// and thus improve performance by avoiding jump stubs in managed code.
flAllocationType |= MEM_RESERVE_EXECUTABLE;
#endif// FEATURE_PAL
return (BYTE *) ClrVirtualAlloc (NULL, dwSize, flAllocationType, flProtect);
}
//
// Allocate free memory with specific alignment.
//
LPVOID ClrVirtualAllocAligned(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect, SIZE_T alignment)
{
// Verify that the alignment is a power of 2
_ASSERTE(alignment != 0);
_ASSERTE((alignment & (alignment - 1)) == 0);
#ifndef FEATURE_PAL
// The VirtualAlloc on Windows ensures 64kB alignment
_ASSERTE(alignment <= 0x10000);
returnClrVirtualAlloc(lpAddress, dwSize, flAllocationType, flProtect);
#else// !FEATURE_PAL
if(alignment < GetOsPageSize()) alignment = GetOsPageSize();
// UNIXTODO: Add a specialized function to PAL so that we don't have to waste memory
dwSize += alignment;
SIZE_T addr = (SIZE_T)ClrVirtualAlloc(lpAddress, dwSize, flAllocationType, flProtect);
return (LPVOID)((addr + (alignment - 1)) & ~(alignment - 1));
#endif// !FEATURE_PAL
}
#ifdef _DEBUG
static DWORD ShouldInjectFaultInRange()
{
static DWORD fInjectFaultInRange = 99;
if (fInjectFaultInRange == 99)
fInjectFaultInRange = (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_InjectFault) & 0x40);
returnfInjectFaultInRange;
}
#endif
// Reserves free memory within the range [pMinAddr..pMaxAddr] using
// ClrVirtualQuery to find free memory and ClrVirtualAlloc to reserve it.
//
// This method only supports the flAllocationType of MEM_RESERVE, and expects that the memory
// is being reserved for the purpose of eventually storing executable code.
//
// Callers also should set dwSize to a multiple of sysInfo.dwAllocationGranularity (64k).
// That way they can reserve a large region and commit smaller sized pages
// from that region until it fills up.
//
// This functions returns the reserved memory block upon success
//
// It returns NULL when it fails to find any memory that satisfies
// the range.
//
BYTE * ClrVirtualAllocWithinRange(const BYTE *pMinAddr,
const BYTE *pMaxAddr,
SIZE_T dwSize,
DWORD flAllocationType,
DWORD flProtect)
{
CONTRACTL
{
NOTHROW;
PRECONDITION(dwSize != 0);
PRECONDITION(flAllocationType == MEM_RESERVE);
}
CONTRACTL_END;
BYTE *pResult = nullptr; // our return value;
staticunsigned countOfCalls = 0; // We log the number of tims we call this method
countOfCalls++; // increment the call counter
if (dwSize == 0)
{
returnnullptr;
}
//
// First lets normalize the pMinAddr and pMaxAddr values
//
// If pMinAddr is NULL then set it to BOT_MEMORY
if ((pMinAddr == 0) || (pMinAddr < (BYTE *) BOT_MEMORY))
{
pMinAddr = (BYTE *) BOT_MEMORY;
}
// If pMaxAddr is NULL then set it to TOP_MEMORY
if ((pMaxAddr == 0) || (pMaxAddr > (BYTE *) TOP_MEMORY))
{
pMaxAddr = (BYTE *) TOP_MEMORY;
}
// If pMaxAddr is not greater than pMinAddr we can not make an allocation
if (pMaxAddr <= pMinAddr)
{
returnnullptr;
}
// If pMinAddr is BOT_MEMORY and pMaxAddr is TOP_MEMORY
// then we can call ClrVirtualAlloc instead
if ((pMinAddr == (BYTE *) BOT_MEMORY) && (pMaxAddr == (BYTE *) TOP_MEMORY))
{
return (BYTE*) ClrVirtualAlloc(nullptr, dwSize, flAllocationType, flProtect);
}
#ifdef FEATURE_PAL
pResult = (BYTE *)PAL_VirtualReserveFromExecutableMemoryAllocatorWithinRange(pMinAddr, pMaxAddr, dwSize);
if (pResult != nullptr)
{
return pResult;
}
#endif// FEATURE_PAL
// We will do one scan from [pMinAddr .. pMaxAddr]
// First align the tryAddr up to next 64k base address.
// See docs for VirtualAllocEx and lpAddress and 64k alignment for reasons.
//
BYTE * tryAddr = (BYTE *)ALIGN_UP((BYTE *)pMinAddr, VIRTUAL_ALLOC_RESERVE_GRANULARITY);
bool virtualQueryFailed = false;
bool faultInjected = false;
unsigned virtualQueryCount = 0;
// Now scan memory and try to find a free block of the size requested.
while ((tryAddr + dwSize) <= (BYTE *) pMaxAddr)
{
MEMORY_BASIC_INFORMATION mbInfo;
// Use VirtualQuery to find out if this address is MEM_FREE
//
virtualQueryCount++;
if (!ClrVirtualQuery((LPCVOID)tryAddr, &mbInfo, sizeof(mbInfo)))
{
// Exit and return nullptr if the VirtualQuery call fails.
virtualQueryFailed = true;
break;
}
// Is there enough memory free from this start location?
// Note that for most versions of UNIX the mbInfo.RegionSize returned will always be 0
if ((mbInfo.State == MEM_FREE) &&
(mbInfo.RegionSize >= (SIZE_T) dwSize || mbInfo.RegionSize == 0))
{
// Try reserving the memory using VirtualAlloc now
pResult = (BYTE*)ClrVirtualAlloc(tryAddr, dwSize, MEM_RESERVE, flProtect);
// Normally this will be successful
//
if (pResult != nullptr)
{
// return pResult
break;
}
#ifdef _DEBUG
if (ShouldInjectFaultInRange())
{
// return nullptr (failure)
faultInjected = true;
break;
}
#endif// _DEBUG
// On UNIX we can also fail if our request size 'dwSize' is larger than 64K and
// and our tryAddr is pointing at a small MEM_FREE region (smaller than 'dwSize')
// However we can't distinguish between this and the race case.
// We might fail in a race. So just move on to next region and continue trying
tryAddr = tryAddr + VIRTUAL_ALLOC_RESERVE_GRANULARITY;
}
else
{
// Try another section of memory
tryAddr = max(tryAddr + VIRTUAL_ALLOC_RESERVE_GRANULARITY,
(BYTE*) mbInfo.BaseAddress + mbInfo.RegionSize);
}
}
STRESS_LOG7(LF_JIT, LL_INFO100,
"ClrVirtualAllocWithinRange request #%u for %08x bytes in [ %p .. %p ], query count was %u - returned %s: %p\n",
countOfCalls, (DWORD)dwSize, pMinAddr, pMaxAddr,
virtualQueryCount, (pResult != nullptr) ? "success" : "failure", pResult);
// If we failed this call the process will typically be terminated
// so we log any additional reason for failing this call.
//
if (pResult == nullptr)
{
if ((tryAddr + dwSize) > (BYTE *)pMaxAddr)
{
// Our tryAddr reached pMaxAddr
STRESS_LOG0(LF_JIT, LL_INFO100, "Additional reason: Address space exhausted.\n");
}
if (virtualQueryFailed)
{
STRESS_LOG0(LF_JIT, LL_INFO100, "Additional reason: VirtualQuery operation failed.\n");
}
if (faultInjected)
{
STRESS_LOG0(LF_JIT, LL_INFO100, "Additional reason: fault injected.\n");
}
}
return pResult;
}
//******************************************************************************
// NumaNodeInfo
//******************************************************************************
#if !defined(FEATURE_REDHAWK)
/*static*/ LPVOID NumaNodeInfo::VirtualAllocExNuma(HANDLE hProc, LPVOID lpAddr, SIZE_T dwSize,
DWORD allocType, DWORD prot, DWORD node)
{
return ::VirtualAllocExNuma(hProc, lpAddr, dwSize, allocType, prot, node);
}
#ifndef FEATURE_PAL
/*static*/ BOOL NumaNodeInfo::GetNumaProcessorNodeEx(PPROCESSOR_NUMBER proc_no, PUSHORT node_no)
{
return ::GetNumaProcessorNodeEx(proc_no, node_no);
}
/*static*/boolNumaNodeInfo::GetNumaInfo(PUSHORT total_nodes, DWORD* max_procs_per_node)
{
if (m_enableGCNumaAware)
{
DWORD currentProcsOnNode = 0;
for (int i = 0; i < m_nNodes; i++)
{
GROUP_AFFINITY processorMask;
if (GetNumaNodeProcessorMaskEx(i, &processorMask))
{
DWORD procsOnNode = 0;
uintptr_t mask = (uintptr_t)processorMask.Mask;
while (mask)
{
procsOnNode++;
mask &= mask - 1;
}
currentProcsOnNode = max(currentProcsOnNode, procsOnNode);
}
}
*max_procs_per_node = currentProcsOnNode;
*total_nodes = m_nNodes;
returntrue;
}
returnfalse;
}
#else// !FEATURE_PAL
/*static*/ BOOL NumaNodeInfo::GetNumaProcessorNodeEx(USHORT proc_no, PUSHORT node_no)
{
returnPAL_GetNumaProcessorNode(proc_no, node_no);
}
#endif// !FEATURE_PAL
#endif
/*static*/ BOOL NumaNodeInfo::m_enableGCNumaAware = FALSE;
/*static*/uint16_t NumaNodeInfo::m_nNodes = 0;
/*static*/ BOOL NumaNodeInfo::InitNumaNodeInfoAPI()
{
#if !defined(FEATURE_REDHAWK)
//check for numa support if multiple heaps are used
ULONG highest = 0;
if (CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_GCNumaAware) == 0)
returnFALSE;
// fail to get the highest numa node number
if (!::GetNumaHighestNodeNumber(&highest) || (highest == 0))
returnFALSE;
m_nNodes = (USHORT)(highest + 1);
returnTRUE;
#else
returnFALSE;
#endif
}
/*static*/ BOOL NumaNodeInfo::CanEnableGCNumaAware()
{
return m_enableGCNumaAware;
}
/*static*/voidNumaNodeInfo::InitNumaNodeInfo()
{
m_enableGCNumaAware = InitNumaNodeInfoAPI();
}
#ifndef FEATURE_PAL
//******************************************************************************
// CPUGroupInfo
//******************************************************************************
#if !defined(FEATURE_REDHAWK)
/*static*///CPUGroupInfo::PNTQSIEx CPUGroupInfo::m_pNtQuerySystemInformationEx = NULL;
/*static*/ BOOL CPUGroupInfo::GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship,
SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *slpiex, PDWORD count)
{
LIMITED_METHOD_CONTRACT;
return ::GetLogicalProcessorInformationEx(relationship, slpiex, count);
}
/*static*/ BOOL CPUGroupInfo::SetThreadGroupAffinity(HANDLE h,
const GROUP_AFFINITY *groupAffinity, GROUP_AFFINITY *previousGroupAffinity)
{
LIMITED_METHOD_CONTRACT;
return ::SetThreadGroupAffinity(h, groupAffinity, previousGroupAffinity);
}
/*static*/ BOOL CPUGroupInfo::GetThreadGroupAffinity(HANDLE h, GROUP_AFFINITY *groupAffinity)
{
LIMITED_METHOD_CONTRACT;
return ::GetThreadGroupAffinity(h, groupAffinity);
}
/*static*/ BOOL CPUGroupInfo::GetSystemTimes(FILETIME *idleTime, FILETIME *kernelTime, FILETIME *userTime)
{
LIMITED_METHOD_CONTRACT;
#ifndef FEATURE_PAL
return ::GetSystemTimes(idleTime, kernelTime, userTime);
#else
returnFALSE;
#endif
}
#endif
/*static*/ BOOL CPUGroupInfo::m_enableGCCPUGroups = FALSE;
/*static*/ BOOL CPUGroupInfo::m_threadUseAllCpuGroups = FALSE;
/*static*/ WORD CPUGroupInfo::m_nGroups = 0;
/*static*/ WORD CPUGroupInfo::m_nProcessors = 0;
/*static*/ WORD CPUGroupInfo::m_initialGroup = 0;
/*static*/ CPU_Group_Info *CPUGroupInfo::m_CPUGroupInfoArray = NULL;
/*static*/ LONG CPUGroupInfo::m_initialization = 0;
/*static*/bool CPUGroupInfo::s_hadSingleProcessorAtStartup = false;
#if !defined(FEATURE_REDHAWK) && (defined(_TARGET_AMD64_) || defined(_TARGET_ARM64_))
// Calculate greatest common divisor
DWORD GCD(DWORD u, DWORD v)
{
while (v != 0)
{
DWORD dwTemp = v;
v = u % v;
u = dwTemp;
}
return u;
}
// Calculate least common multiple
DWORD LCM(DWORD u, DWORD v)
{
return u / GCD(u, v) * v;
}
#endif
/*static*/ BOOL CPUGroupInfo::InitCPUGroupInfoArray()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
#if !defined(FEATURE_REDHAWK) && (defined(_TARGET_AMD64_) || defined(_TARGET_ARM64_))
BYTE *bBuffer = NULL;
SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *pSLPIEx = NULL;
SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *pRecord = NULL;
DWORD cbSLPIEx = 0;
DWORD byteOffset = 0;
DWORD dwNumElements = 0;
DWORD dwWeight = 1;
if (CPUGroupInfo::GetLogicalProcessorInformationEx(RelationGroup, pSLPIEx, &cbSLPIEx) &&
GetLastError() != ERROR_INSUFFICIENT_BUFFER)
returnFALSE;
_ASSERTE(cbSLPIEx);
// Fail to allocate buffer
bBuffer = new (nothrow) BYTE[ cbSLPIEx ];
if (bBuffer == NULL)
returnFALSE;
pSLPIEx = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)bBuffer;
if (!::GetLogicalProcessorInformationEx(RelationGroup, pSLPIEx, &cbSLPIEx))
{
delete[] bBuffer;
returnFALSE;
}
pRecord = pSLPIEx;
while (byteOffset < cbSLPIEx)
{
if (pRecord->Relationship == RelationGroup)
{
m_nGroups = pRecord->Group.ActiveGroupCount;
break;
}
byteOffset += pRecord->Size;
pRecord = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)(bBuffer + byteOffset);
}
m_CPUGroupInfoArray = new (nothrow) CPU_Group_Info[m_nGroups];
if (m_CPUGroupInfoArray == NULL)
{
delete[] bBuffer;
returnFALSE;
}
for (DWORD i = 0; i < m_nGroups; i++)
{
m_CPUGroupInfoArray[i].nr_active = (WORD)pRecord->Group.GroupInfo[i].ActiveProcessorCount;
m_CPUGroupInfoArray[i].active_mask = pRecord->Group.GroupInfo[i].ActiveProcessorMask;
m_nProcessors += m_CPUGroupInfoArray[i].nr_active;
dwWeight = LCM(dwWeight, (DWORD)m_CPUGroupInfoArray[i].nr_active);
}
// The number of threads per group that can be supported will depend on the number of CPU groups
// and the number of LPs within each processor group. For example, when the number of LPs in
// CPU groups is the same and is 64, the number of threads per group before weight overflow
// would be 2^32/2^6 = 2^26 (64M threads)
for (DWORD i = 0; i < m_nGroups; i++)
{
m_CPUGroupInfoArray[i].groupWeight = dwWeight / (DWORD)m_CPUGroupInfoArray[i].nr_active;
m_CPUGroupInfoArray[i].activeThreadWeight = 0;
}
delete[] bBuffer; // done with it; free it
returnTRUE;
#else
returnFALSE;
#endif
}
/*static*/ BOOL CPUGroupInfo::InitCPUGroupInfoRange()
{
LIMITED_METHOD_CONTRACT;
#if !defined(FEATURE_REDHAWK) && (defined(_TARGET_AMD64_) || defined(_TARGET_ARM64_))
WORD begin = 0;
WORD nr_proc = 0;
for (WORD i = 0; i < m_nGroups; i++)
{
nr_proc += m_CPUGroupInfoArray[i].nr_active;
m_CPUGroupInfoArray[i].begin = begin;
m_CPUGroupInfoArray[i].end = nr_proc - 1;
begin = nr_proc;
}
returnTRUE;
#else
returnFALSE;
#endif
}
/*static*/voidCPUGroupInfo::InitCPUGroupInfo()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
#if !defined(FEATURE_REDHAWK) && (defined(_TARGET_AMD64_) || defined(_TARGET_ARM64_))
BOOL enableGCCPUGroups = CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_GCCpuGroup) != 0;
BOOL threadUseAllCpuGroups = CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_Thread_UseAllCpuGroups) != 0;
if (!enableGCCPUGroups)
return;
if (!InitCPUGroupInfoArray())
return;