-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathutil.cpp
2944 lines (2471 loc) · 93.6 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.
//*****************************************************************************
// 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"
#include "mdfileformat.h"
#include <configuration.h>
#ifndef DACCESS_COMPILE
UINT32 g_nClrInstanceId = 0;
#if defined(TARGET_WINDOWS) && defined(TARGET_ARM64)
// Flag to check if atomics feature is available on
// the machine
bool g_arm64_atomics_present = false;
#endif
#endif //!DACCESS_COMPILE
//*****************************************************************************
// 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.
unsigned int 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)
{
case 1:
*((BYTE *) pResult) = (BYTE) Result;
break;
case 2:
*((WORD *) pResult) = (WORD) Result;
break;
case 4:
*((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;
bool fIsDllPathPrefix = (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)
{
#ifdef HOST_WINDOWS
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 // HOST_WINDOWS
return E_FAIL;
#endif // HOST_WINDOWS
}
_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)
return HRESULT_FROM_GetLastError();
// We've loaded the DLL, so find the DllGetClassObject function.
DLLGETCLASSOBJECT *dllGetClassObject = (DLLGETCLASSOBJECT*)GetProcAddress(hDll, "DllGetClassObject");
if (dllGetClassObject == nullptr)
return HRESULT_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;
}
//
// 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);
#ifdef HOST_WINDOWS
// The VirtualAlloc on Windows ensures 64kB alignment
_ASSERTE(alignment <= 0x10000);
return ClrVirtualAlloc(lpAddress, dwSize, flAllocationType, flProtect);
#else // HOST_WINDOWS
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 // HOST_WINDOWS
}
#ifdef _DEBUG
static DWORD ShouldInjectFaultInRange()
{
static DWORD fInjectFaultInRange = 99;
if (fInjectFaultInRange == 99)
fInjectFaultInRange = (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_InjectFault) & 0x40);
return fInjectFaultInRange;
}
#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;
static unsigned countOfCalls = 0; // We log the number of tims we call this method
countOfCalls++; // increment the call counter
if (dwSize == 0)
{
return nullptr;
}
//
// 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)
{
return nullptr;
}
// 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 HOST_UNIX
pResult = (BYTE *)PAL_VirtualReserveFromExecutableMemoryAllocatorWithinRange(pMinAddr, pMaxAddr, dwSize, TRUE /* fStoreAllocationInfo */);
if (pResult != nullptr)
{
return pResult;
}
#endif // HOST_UNIX
// 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_NATIVEAOT)
/*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);
}
#ifdef HOST_WINDOWS
/*static*/ BOOL NumaNodeInfo::GetNumaProcessorNodeEx(PPROCESSOR_NUMBER proc_no, PUSHORT node_no)
{
return ::GetNumaProcessorNodeEx(proc_no, node_no);
}
/*static*/ bool NumaNodeInfo::GetNumaInfo(PUSHORT total_nodes, DWORD* max_procs_per_node)
{
if (m_enableGCNumaAware)
{
DWORD currentProcsOnNode = 0;
for (uint16_t 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;
return true;
}
return false;
}
#else // HOST_WINDOWS
/*static*/ BOOL NumaNodeInfo::GetNumaProcessorNodeEx(USHORT proc_no, PUSHORT node_no)
{
return PAL_GetNumaProcessorNode(proc_no, node_no);
}
#endif // HOST_WINDOWS
#endif
/*static*/ BOOL NumaNodeInfo::m_enableGCNumaAware = FALSE;
/*static*/ uint16_t NumaNodeInfo::m_nNodes = 0;
/*static*/ BOOL NumaNodeInfo::InitNumaNodeInfoAPI()
{
#if !defined(FEATURE_NATIVEAOT)
//check for numa support if multiple heaps are used
ULONG highest = 0;
if (CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_GCNumaAware) == 0)
return FALSE;
// fail to get the highest numa node number
if (!::GetNumaHighestNodeNumber(&highest) || (highest == 0))
return FALSE;
m_nNodes = (USHORT)(highest + 1);
return TRUE;
#else
return FALSE;
#endif
}
/*static*/ BOOL NumaNodeInfo::CanEnableGCNumaAware()
{
return m_enableGCNumaAware;
}
/*static*/ void NumaNodeInfo::InitNumaNodeInfo()
{
m_enableGCNumaAware = InitNumaNodeInfoAPI();
}
#ifdef HOST_WINDOWS
//******************************************************************************
// CPUGroupInfo
//******************************************************************************
#if !defined(FEATURE_NATIVEAOT)
/*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;
#ifdef HOST_WINDOWS
return ::GetSystemTimes(idleTime, kernelTime, userTime);
#else
return FALSE;
#endif
}
#endif
/*static*/ BOOL CPUGroupInfo::m_enableGCCPUGroups = FALSE;
/*static*/ BOOL CPUGroupInfo::m_threadUseAllCpuGroups = FALSE;
/*static*/ BOOL CPUGroupInfo::m_threadAssignCpuGroups = 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;
#if !defined(FEATURE_NATIVEAOT) && (defined(TARGET_AMD64) || defined(TARGET_ARM64) || defined(TARGET_LOONGARCH64))
// 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_NATIVEAOT) && (defined(TARGET_AMD64) || defined(TARGET_ARM64) || defined(TARGET_LOONGARCH64))
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)
return FALSE;
_ASSERTE(cbSLPIEx);
// Fail to allocate buffer
bBuffer = new (nothrow) BYTE[ cbSLPIEx ];
if (bBuffer == NULL)
return FALSE;
pSLPIEx = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)bBuffer;
if (!::GetLogicalProcessorInformationEx(RelationGroup, pSLPIEx, &cbSLPIEx))
{
delete[] bBuffer;
return FALSE;
}
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;
return FALSE;
}
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_CPUGroupInfoArray[i].begin = m_nProcessors;
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
return TRUE;
#else
return FALSE;
#endif
}
/*static*/ void CPUGroupInfo::InitCPUGroupInfo()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
#if !defined(FEATURE_NATIVEAOT) && (defined(TARGET_AMD64) || defined(TARGET_ARM64) || defined(TARGET_LOONGARCH64))
BOOL enableGCCPUGroups = Configuration::GetKnobBooleanValue(W("System.GC.CpuGroup"), CLRConfig::EXTERNAL_GCCpuGroup);
if (!enableGCCPUGroups)
return;
if (!InitCPUGroupInfoArray())
return;
// Enable processor groups only if more than one group exists
if (m_nGroups > 1)
{
m_enableGCCPUGroups = TRUE;
m_threadUseAllCpuGroups = CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_Thread_UseAllCpuGroups) != 0;
m_threadAssignCpuGroups = CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_Thread_AssignCpuGroups) != 0;
// Save the processor group affinity of the initial thread
GROUP_AFFINITY groupAffinity;
CPUGroupInfo::GetThreadGroupAffinity(GetCurrentThread(), &groupAffinity);
m_initialGroup = groupAffinity.Group;
}
#endif
}
/*static*/ BOOL CPUGroupInfo::IsInitialized()
{
LIMITED_METHOD_CONTRACT;
return VolatileLoad(&m_initialization) == -1;
}
/*static*/ void CPUGroupInfo::EnsureInitialized()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
// CPUGroupInfo needs to be initialized only once. This could happen in three cases
// 1. CLR initialization at beginning of EEStartup, or
// 2. Sometimes, when hosted by ASP.NET, the hosting process may initialize ThreadPool
// before initializing CLR, thus require CPUGroupInfo to be initialized to determine
// if CPU group support should/could be enabled.
// 3. Call into Threadpool functions before Threadpool _and_ CLR is initialized.
// Vast majority of time, CPUGroupInfo is initialized in case 1. or 2.
// The chance of contention will be extremely small, so the following code should be fine
//
if (IsInitialized())
return;
if (InterlockedCompareExchange(&m_initialization, 1, 0) == 0)
{
InitCPUGroupInfo();
VolatileStore(&m_initialization, -1L);
}
else
{
// Some other thread started initialization, just wait until complete
while (VolatileLoad(&m_initialization) != -1)
{
SwitchToThread();
}
}
}
/*static*/ WORD CPUGroupInfo::GetNumActiveProcessors()
{
LIMITED_METHOD_CONTRACT;
return (WORD)m_nProcessors;
}
/*static*/ void CPUGroupInfo::GetGroupForProcessor(WORD processor_number,
WORD* group_number, WORD* group_processor_number)
{
LIMITED_METHOD_CONTRACT;
#if !defined(FEATURE_NATIVEAOT) && (defined(TARGET_AMD64) || defined(TARGET_ARM64) || defined(TARGET_LOONGARCH64))
WORD bTemp = 0;
WORD bDiff = processor_number - bTemp;
for (WORD i=0; i < m_nGroups; i++)
{
bTemp += m_CPUGroupInfoArray[i].nr_active;
if (bTemp > processor_number)
{
*group_number = i;
*group_processor_number = bDiff;
break;
}
bDiff = processor_number - bTemp;
}
#else
*group_number = 0;
*group_processor_number = 0;
#endif
}
/*static*/ DWORD CPUGroupInfo::CalculateCurrentProcessorNumber()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
#if !defined(FEATURE_NATIVEAOT) && (defined(TARGET_AMD64) || defined(TARGET_ARM64) || defined(TARGET_LOONGARCH64))
_ASSERTE(m_enableGCCPUGroups && m_threadUseAllCpuGroups);
PROCESSOR_NUMBER proc_no;
proc_no.Group=0;
proc_no.Number=0;
proc_no.Reserved=0;
::GetCurrentProcessorNumberEx(&proc_no);
DWORD fullNumber = 0;
for (WORD i = 0; i < proc_no.Group; i++)
fullNumber += (DWORD)m_CPUGroupInfoArray[i].nr_active;
fullNumber += (DWORD)(proc_no.Number);
return fullNumber;
#else
return 0;
#endif
}
// There can be different numbers of procs in groups. We take the max.
/*static*/ bool CPUGroupInfo::GetCPUGroupInfo(PUSHORT total_groups, DWORD* max_procs_per_group)
{
if (m_enableGCCPUGroups)
{
*total_groups = m_nGroups;
DWORD currentProcsInGroup = 0;
for (WORD i = 0; i < m_nGroups; i++)
{
currentProcsInGroup = max(currentProcsInGroup, m_CPUGroupInfoArray[i].nr_active);
}
*max_procs_per_group = currentProcsInGroup;
return true;
}
return false;
}
#if !defined(FEATURE_NATIVEAOT)
//Lock ThreadStore before calling this function, so that updates of weights/counts are consistent
/*static*/ void CPUGroupInfo::ChooseCPUGroupAffinity(GROUP_AFFINITY *gf)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
#if (defined(TARGET_AMD64) || defined(TARGET_ARM64) || defined(TARGET_LOONGARCH64))
WORD i, minGroup = 0;
DWORD minWeight = 0;
_ASSERTE(m_enableGCCPUGroups && m_threadUseAllCpuGroups && m_threadAssignCpuGroups);
for (i = 0; i < m_nGroups; i++)
{
minGroup = (m_initialGroup + i) % m_nGroups;
// the group is not filled up, use it
if (m_CPUGroupInfoArray[minGroup].activeThreadWeight / m_CPUGroupInfoArray[minGroup].groupWeight
< (DWORD)m_CPUGroupInfoArray[minGroup].nr_active)
goto found;
}
// all groups filled up, distribute proportionally
minGroup = m_initialGroup;
minWeight = m_CPUGroupInfoArray[m_initialGroup].activeThreadWeight;
for (i = 0; i < m_nGroups; i++)
{
if (m_CPUGroupInfoArray[i].activeThreadWeight < minWeight)
{
minGroup = i;
minWeight = m_CPUGroupInfoArray[i].activeThreadWeight;
}
}
found:
gf->Group = minGroup;
gf->Mask = m_CPUGroupInfoArray[minGroup].active_mask;
gf->Reserved[0] = 0;
gf->Reserved[1] = 0;
gf->Reserved[2] = 0;
m_CPUGroupInfoArray[minGroup].activeThreadWeight += m_CPUGroupInfoArray[minGroup].groupWeight;
#endif
}
//Lock ThreadStore before calling this function, so that updates of weights/counts are consistent
/*static*/ void CPUGroupInfo::ClearCPUGroupAffinity(GROUP_AFFINITY *gf)
{
LIMITED_METHOD_CONTRACT;
#if (defined(TARGET_AMD64) || defined(TARGET_ARM64) || defined(TARGET_LOONGARCH64))
_ASSERTE(m_enableGCCPUGroups && m_threadUseAllCpuGroups && m_threadAssignCpuGroups);
WORD group = gf->Group;
m_CPUGroupInfoArray[group].activeThreadWeight -= m_CPUGroupInfoArray[group].groupWeight;
#endif
}
BOOL CPUGroupInfo::GetCPUGroupRange(WORD group_number, WORD* group_begin, WORD* group_size)
{
if (group_number >= m_nGroups)
{
return FALSE;
}
*group_begin = m_CPUGroupInfoArray[group_number].begin;
*group_size = m_CPUGroupInfoArray[group_number].nr_active;
return TRUE;
}
#endif
/*static*/ BOOL CPUGroupInfo::CanEnableGCCPUGroups()
{
LIMITED_METHOD_CONTRACT;
return m_enableGCCPUGroups;
}
/*static*/ BOOL CPUGroupInfo::CanEnableThreadUseAllCpuGroups()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(m_enableGCCPUGroups || !m_threadUseAllCpuGroups);
return m_threadUseAllCpuGroups;
}
/*static*/ BOOL CPUGroupInfo::CanAssignCpuGroupsToThreads()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(m_enableGCCPUGroups || !m_threadAssignCpuGroups);