-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathutilcode.h
More file actions
3713 lines (3159 loc) · 116 KB
/
Copy pathutilcode.h
File metadata and controls
3713 lines (3159 loc) · 116 KB
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.
//*****************************************************************************
// UtilCode.h
//
// Utility functions implemented in UtilCode.lib.
//
//*****************************************************************************
#ifndef __UtilCode_h__
#define __UtilCode_h__
#include <type_traits>
#include <algorithm>
#include <stdio.h>
#include <limits.h>
#include <new>
using std::nothrow;
#include "crtwrap.h"
#include "winwrap.h"
#include <wchar.h>
#include <ole2.h>
#include "clrtypes.h"
#include "safewrap.h"
#include "volatile.h"
#include <daccess.h>
#include "clrhost.h"
#include "dn_xxhash.h"
#include "debugmacros.h"
#include "corhlprpriv.h"
#include "check.h"
#include "safemath.h"
#include "contract.h"
#include <stddef.h>
#include <minipal/guid.h>
#include <minipal/log.h>
#include <minipal/ospagesize.h>
#include <dn-u16.h>
#include "clrnt.h"
#include "random.h"
#include "cdacdata.h"
#define WINDOWS_KERNEL32_DLLNAME_A "kernel32"
#define WINDOWS_KERNEL32_DLLNAME_W W("kernel32")
#define CoreLibName_W W("System.Private.CoreLib")
#define CoreLibName_IL_W W("System.Private.CoreLib.dll")
#define CoreLibName_A "System.Private.CoreLib"
#define CoreLibName_IL_A "System.Private.CoreLib.dll"
#define CoreLibNameLen 22
#define CoreLibSatelliteName_A "System.Private.CoreLib.resources"
#define CoreLibSatelliteNameLen 32
bool ValidateModuleName(LPCWSTR pwzModuleName);
class StringArrayList;
#if !defined(_DEBUG_IMPL) && defined(_DEBUG) && !defined(DACCESS_COMPILE)
#define _DEBUG_IMPL 1
#endif
#ifdef TARGET_ARM
// Under ARM we generate code only with Thumb encoding. In order to ensure we execute such code in the correct
// mode we must ensure the low-order bit is set in any code address we'll call as a sub-routine. In C++ this
// is handled automatically for us by the compiler. When generating and working with code generated
// dynamically we have to be careful to set or mask-out this bit as appropriate.
#ifndef THUMB_CODE
#define THUMB_CODE 1
#endif
// Given a WORD extract the bitfield [lowbit, highbit] (i.e. BitExtract(0xffff, 15, 0) == 0xffff).
inline WORD BitExtract(WORD wValue, DWORD highbit, DWORD lowbit)
{
_ASSERTE((highbit < 16) && (lowbit < 16) && (highbit >= lowbit));
return (wValue >> lowbit) & ((1 << ((highbit - lowbit) + 1)) - 1);
}
// Determine whether an ARM Thumb mode instruction is 32-bit or 16-bit based on the first WORD of the
// instruction.
inline bool Is32BitInstruction(WORD opcode)
{
return BitExtract(opcode, 15, 11) >= 0x1d;
}
template <typename ResultType, typename SourceType>
inline ResultType DataPointerToThumbCode(SourceType pCode)
{
return (ResultType)(((UINT_PTR)pCode) | THUMB_CODE);
}
template <typename ResultType, typename SourceType>
inline ResultType ThumbCodeToDataPointer(SourceType pCode)
{
return (ResultType)(((UINT_PTR)pCode) & ~THUMB_CODE);
}
#endif // TARGET_ARM
#ifdef TARGET_RISCV64
inline bool Is32BitInstruction(WORD opcode)
{
bool is32 = ((opcode & 0b11) == 0b11);
assert(!is32 || ((opcode & 0b11111) != 0b11111)); // 48-bit and larger instructions unsupported
return is32;
}
#endif
// Convert from a PCODE to the corresponding PINSTR. On many architectures this will be the identity function;
// on ARM, this will mask off the THUMB bit.
inline TADDR PCODEToPINSTR(PCODE pc)
{
#ifdef TARGET_ARM
return ThumbCodeToDataPointer<TADDR,PCODE>(pc);
#else
return dac_cast<PCODE>(pc);
#endif
}
// Convert from a PINSTR to the corresponding PCODE. On many architectures this will be the identity function;
// on ARM, this will raise the THUMB bit.
inline PCODE PINSTRToPCODE(TADDR addr)
{
#ifdef TARGET_ARM
return DataPointerToThumbCode<PCODE,TADDR>(addr);
#else
return dac_cast<PCODE>(addr);
#endif
}
typedef LPCSTR LPCUTF8;
typedef LPSTR LPUTF8;
#include "nsutilpriv.h"
#include "stdmacros.h"
//********** Macros. **********************************************************
#ifndef DEBUG_NOINLINE
#if defined(_DEBUG)
#define DEBUG_NOINLINE NOINLINE
#else
#define DEBUG_NOINLINE
#endif
#endif
#define IS_DIGIT(ch) (((ch) >= W('0')) && ((ch) <= W('9')))
#define DIGIT_TO_INT(ch) ((ch) - W('0'))
#define INT_TO_DIGIT(i) ((WCHAR)(W('0') + (i)))
// Helper will 4 byte align a value, rounding up.
#define ALIGN4BYTE(val) (((val) + 3) & ~0x3)
#ifdef _DEBUG
#define DEBUGARG(x) , x
#else
#define DEBUGARG(x)
#endif
#if defined(FEATURE_READYTORUN)
#define R2RARG(x) , x
#else
#define R2RARG(x)
#endif
#ifndef sizeofmember
// Returns the size of a class or struct member.
#define sizeofmember(c,m) (sizeof(((c*)0)->m))
#endif
//=--------------------------------------------------------------------------=
// Prefast helpers.
//
#include "safemath.h"
//=--------------------------------------------------------------------------=
// string helpers.
//
// given and ANSI String, copy it into a wide buffer.
// be careful about scoping when using this macro!
//
// similarily for MAKE_ANSIPTR_FROMWIDE. note that the first param does not
// have to be declared, and no clean up must be done.
//
// We'll define an upper limit that allows multiplication by 4 (the max
// bytes/char in UTF-8) but still remains positive, and allows some room for pad.
// Under normal circumstances, we should never get anywhere near this limit.
#define MAKE_MAX_LENGTH 0x1fffff00
#ifndef MAKE_TOOLONGACTION
#define MAKE_TOOLONGACTION ThrowHR(COR_E_OVERFLOW)
#endif
#ifndef MAKE_TRANSLATIONFAILED
#define MAKE_TRANSLATIONFAILED ThrowWin32(ERROR_NO_UNICODE_TRANSLATION)
#endif
// This version does best fit character mapping and also allows the use
// of the default char ('?') for any Unicode character that isn't
// representable. This is reasonable for writing to the console, but
// shouldn't be used for most string conversions.
#define MAKE_MULTIBYTE_FROMWIDE_BESTFIT(ptrname, widestr, codepage) \
int __l##ptrname = (int)u16_strlen(widestr); \
if (__l##ptrname > MAKE_MAX_LENGTH) \
MAKE_TOOLONGACTION; \
__l##ptrname = (int)((__l##ptrname + 1) * 2 * sizeof(char)); \
CQuickBytes __CQuickBytes##ptrname; \
__CQuickBytes##ptrname.AllocThrows(__l##ptrname); \
DWORD __cBytes##ptrname = WideCharToMultiByte(codepage, 0, widestr, -1, (LPSTR)__CQuickBytes##ptrname.Ptr(), __l##ptrname, NULL, NULL); \
if (__cBytes##ptrname == 0 && __l##ptrname != 0) { \
MAKE_TRANSLATIONFAILED; \
} \
LPSTR ptrname = (LPSTR)__CQuickBytes##ptrname.Ptr()
// ptrname will be deleted when it goes out of scope.
#define MAKE_UTF8PTR_FROMWIDE(ptrname, widestr) CQuickBytes _##ptrname; _##ptrname.ConvertUnicode_Utf8(widestr); LPSTR ptrname = (LPSTR) _##ptrname.Ptr();
// ptrname will be deleted when it goes out of scope.
#define MAKE_UTF8PTR_FROMWIDE_NOTHROW(ptrname, widestr) \
CQuickBytes __qb##ptrname; \
int __l##ptrname = (int)u16_strlen(widestr); \
LPUTF8 ptrname = NULL; \
if (__l##ptrname <= MAKE_MAX_LENGTH) { \
__l##ptrname = (int)((__l##ptrname + 1) * 2 * sizeof(char)); \
ptrname = (LPUTF8) __qb##ptrname.AllocNoThrow(__l##ptrname); \
} \
if (ptrname) { \
INT32 __lresult##ptrname=WideCharToMultiByte(CP_UTF8, 0, widestr, -1, ptrname, __l##ptrname-1, NULL, NULL); \
DWORD __dwCaptureLastError##ptrname = ::GetLastError(); \
if ((__lresult##ptrname==0) && (((LPCWSTR)widestr)[0] != W('\0'))) { \
if (__dwCaptureLastError##ptrname==ERROR_INSUFFICIENT_BUFFER) { \
INT32 __lsize##ptrname=WideCharToMultiByte(CP_UTF8, 0, widestr, -1, NULL, 0, NULL, NULL); \
ptrname = (LPSTR) __qb##ptrname .AllocNoThrow(__lsize##ptrname); \
if (ptrname) { \
if (WideCharToMultiByte(CP_UTF8, 0, widestr, -1, ptrname, __lsize##ptrname, NULL, NULL) != 0) { \
ptrname[__l##ptrname] = 0; \
} else { \
ptrname = NULL; \
} \
} \
} \
else { \
ptrname = NULL; \
} \
} \
} \
#define MAKE_WIDEPTR_FROMUTF8(ptrname, utf8str) CQuickBytes _##ptrname; _##ptrname.ConvertUtf8_Unicode(utf8str); LPCWSTR ptrname = (LPCWSTR) _##ptrname.Ptr();
#define MAKE_WIDEPTR_FROMUTF8N_NOTHROW(ptrname, utf8str, n8chrs) \
CQuickBytes __qb##ptrname; \
int __l##ptrname; \
LPWSTR ptrname = NULL; \
__l##ptrname = MultiByteToWideChar(CP_UTF8, 0, utf8str, n8chrs, 0, 0); \
if (__l##ptrname <= MAKE_MAX_LENGTH) { \
ptrname = (LPWSTR) __qb##ptrname.AllocNoThrow((__l##ptrname+1)*sizeof(WCHAR)); \
if (ptrname) { \
if (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8str, n8chrs, ptrname, __l##ptrname) != 0) { \
ptrname[__l##ptrname] = 0; \
} else { \
ptrname = NULL; \
} \
} \
}
#define MAKE_WIDEPTR_FROMUTF8_NOTHROW(ptrname, utf8str) MAKE_WIDEPTR_FROMUTF8N_NOTHROW(ptrname, utf8str, -1)
const SIZE_T MaxSigned32BitDecString = ARRAY_SIZE("-2147483648") - 1;
const SIZE_T MaxUnsigned32BitDecString = ARRAY_SIZE("4294967295") - 1;
const SIZE_T MaxIntegerDecHexString = ARRAY_SIZE("-9223372036854775808") - 1;
const SIZE_T Max32BitHexString = ARRAY_SIZE("12345678") - 1;
const SIZE_T Max64BitHexString = ARRAY_SIZE("1234567812345678") - 1;
template <typename I>
inline WCHAR* FormatInteger(WCHAR* str, size_t strCount, const char* fmt, I v)
{
static_assert(std::is_integral<I>::value, "Integral type required.");
assert(str != NULL && fmt != NULL);
// Represents the most amount of space needed to format
// an integral type (i.e., %d or %llx).
char tmp[MaxIntegerDecHexString + 1];
int cnt = sprintf_s(tmp, ARRAY_SIZE(tmp), fmt, v);
assert(0 <= cnt);
WCHAR* end = str + strCount;
for (int i = 0; i < cnt; ++i)
{
if (str == end)
return NULL;
*str++ = (WCHAR)tmp[i];
}
*str = W('\0');
return str;
}
/********************************************************************************/
/* portability helpers */
#ifdef TARGET_64BIT
#define IN_TARGET_64BIT(x) x
#define IN_TARGET_32BIT(x)
#else
#define IN_TARGET_64BIT(x)
#define IN_TARGET_32BIT(x) x
#endif
void * __cdecl
operator new(size_t n);
_Ret_bytecap_(n) void * __cdecl
operator new[](size_t n);
void __cdecl
operator delete(void *p) noexcept;
void __cdecl
operator delete[](void *p) noexcept;
#ifdef _DEBUG_IMPL
HRESULT _OutOfMemory(LPCSTR szFile, int iLine);
#define OutOfMemory() _OutOfMemory(__FILE__, __LINE__)
#else
inline HRESULT OutOfMemory()
{
LIMITED_METHOD_CONTRACT;
return (E_OUTOFMEMORY);
}
#endif
HMODULE CLRLoadLibrary(LPCWSTR lpLibFileName);
HMODULE CLRLoadLibraryEx(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags);
BOOL CLRFreeLibrary(HMODULE hModule);
//*****************************************************************************
// Use this class by privately deriving from noncopyable to disallow copying of
// your class.
//*****************************************************************************
class noncopyable
{
protected:
noncopyable()
{}
~noncopyable()
{}
private:
noncopyable(const noncopyable&);
const noncopyable& operator=(const noncopyable&);
};
//*****************************************************************************
// CCompRC manages string Resource access for CLR.
//*****************************************************************************
class CCompRC
{
public:
static HRESULT LoadString(UINT iResourceID, _Out_writes_ (iMax) LPWSTR szBuffer, int iMax , int *pcwchUsed=NULL);
};
// The HRESULT_FROM_WIN32 macro evaluates its arguments three times.
// <TODO>TODO: All HRESULT_FROM_WIN32(GetLastError()) should be replaced by calls to
// this helper function avoid code bloat</TODO>
inline HRESULT HRESULT_FROM_GetLastError()
{
WRAPPER_NO_CONTRACT;
DWORD dw = GetLastError();
// Make sure we return a failure
if (dw == ERROR_SUCCESS)
{
_ASSERTE(!"We were expecting to get an error code, but a success code is being returned. Check this code path for Everett!");
return E_FAIL;
}
else
return HRESULT_FROM_WIN32(dw);
}
inline HRESULT HRESULT_FROM_GetLastErrorNA()
{
WRAPPER_NO_CONTRACT;
DWORD dw = GetLastError();
// Make sure we return a failure
if (dw == ERROR_SUCCESS)
return E_FAIL;
else
return HRESULT_FROM_WIN32(dw);
}
inline HRESULT BadError(HRESULT hr)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(!"Serious Error");
return (hr);
}
#define TESTANDRETURN(test, hrVal) \
{ \
int ___test = (int)(test); \
if (! ___test) \
return hrVal; \
}
#define TESTANDRETURNPOINTER(pointer) \
TESTANDRETURN((pointer)!=NULL, E_POINTER)
#define TESTANDRETURNMEMORY(pointer) \
TESTANDRETURN((pointer)!=NULL, E_OUTOFMEMORY)
#define TESTANDRETURNHR(hr) \
TESTANDRETURN(SUCCEEDED(hr), hr)
#define TESTANDRETURNARG(argtest) \
TESTANDRETURN(argtest, E_INVALIDARG)
// Quick validity check for HANDLEs that are returned by Win32 APIs that
// use INVALID_HANDLE_VALUE instead of NULL to indicate an error
inline BOOL IsValidHandle(HANDLE h)
{
LIMITED_METHOD_CONTRACT;
return ((h != NULL) && (h != INVALID_HANDLE_VALUE));
}
// Count the bits in a value in order iBits time.
inline int CountBits(int iNum)
{
LIMITED_METHOD_CONTRACT;
int iBits;
for (iBits=0; iNum; iBits++)
iNum = iNum & (iNum - 1);
return (iBits);
}
// Convert the currency to a decimal and canonicalize.
inline void VarDecFromCyCanonicalize(CY cyIn, DECIMAL* dec)
{
WRAPPER_NO_CONTRACT;
(*(ULONG*)dec) = 0;
DECIMAL_HI32(*dec) = 0;
if (cyIn.int64 == 0) // For compatibility, a currency of 0 emits the Decimal "0.0000" (scale set to 4).
{
DECIMAL_SCALE(*dec) = 4;
DECIMAL_LO32(*dec) = 0;
DECIMAL_MID32(*dec) = 0;
return;
}
if (cyIn.int64 < 0) {
DECIMAL_SIGN(*dec) = DECIMAL_NEG;
cyIn.int64 = -cyIn.int64;
}
BYTE scale = 4;
ULONGLONG absoluteCy = (ULONGLONG)cyIn.int64;
while (scale != 0 && ((absoluteCy % 10) == 0))
{
scale--;
absoluteCy /= 10;
}
DECIMAL_SCALE(*dec) = scale;
DECIMAL_LO32(*dec) = (ULONG)absoluteCy;
DECIMAL_MID32(*dec) = (ULONG)(absoluteCy >> 32);
}
//*****************************************************************************
//
// Paths functions. Use these instead of the CRT.
//
//*****************************************************************************
//*******************************************************************************
// Split a path into individual components - points to each section of the string
//*******************************************************************************
void SplitPathInterior(
_In_ LPCWSTR wszPath,
_Out_opt_ LPCWSTR *pwszDrive, _Out_opt_ size_t *pcchDrive,
_Out_opt_ LPCWSTR *pwszDir, _Out_opt_ size_t *pcchDir,
_Out_opt_ LPCWSTR *pwszFileName, _Out_opt_ size_t *pcchFileName,
_Out_opt_ LPCWSTR *pwszExt, _Out_opt_ size_t *pcchExt);
#ifdef HOST_64BIT
inline BOOL RunningInWow64()
{
return FALSE;
}
#else
BOOL RunningInWow64();
#endif
//
// Allocate free memory within the range [pMinAddr..pMaxAddr] using
// ClrVirtualQuery to find free memory and ClrVirtualAlloc to allocate it.
//
BYTE * ClrVirtualAllocWithinRange(const BYTE *pMinAddr,
const BYTE *pMaxAddr,
SIZE_T dwSize,
DWORD flAllocationType,
DWORD flProtect);
#ifdef HOST_WINDOWS
struct CPU_Group_Info
{
DWORD_PTR active_mask;
WORD nr_active; // at most 64
WORD begin;
DWORD groupWeight;
DWORD activeThreadWeight;
};
class CPUGroupInfo
{
private:
static LONG m_initialization;
static WORD m_nGroups;
static WORD m_nProcessors;
static BOOL m_enableGCCPUGroups;
static BOOL m_threadUseAllCpuGroups;
static BOOL m_threadAssignCpuGroups;
static WORD m_initialGroup;
static CPU_Group_Info *m_CPUGroupInfoArray;
static BOOL InitCPUGroupInfoArray();
static void InitCPUGroupInfo();
static BOOL IsInitialized();
public:
static void EnsureInitialized();
static BOOL CanEnableGCCPUGroups();
static BOOL CanEnableThreadUseAllCpuGroups();
static BOOL CanAssignCpuGroupsToThreads();
static WORD GetNumActiveProcessors();
static void GetGroupForProcessor(WORD processor_number,
WORD *group_number, WORD *group_processor_number);
static DWORD CalculateCurrentProcessorNumber();
static bool GetCPUGroupInfo(PUSHORT total_groups, DWORD* max_procs_per_group);
//static void PopulateCPUUsageArray(void * infoBuffer, ULONG infoSize);
public:
static BOOL GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship,
SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *slpiex, PDWORD count);
static BOOL SetThreadGroupAffinity(HANDLE h,
const GROUP_AFFINITY *groupAffinity, GROUP_AFFINITY *previousGroupAffinity);
static BOOL GetThreadGroupAffinity(HANDLE h, GROUP_AFFINITY *groupAffinity);
static BOOL GetSystemTimes(FILETIME *idleTime, FILETIME *kernelTime, FILETIME *userTime);
static void ChooseCPUGroupAffinity(GROUP_AFFINITY *gf);
static void ClearCPUGroupAffinity(GROUP_AFFINITY *gf);
static BOOL GetCPUGroupRange(WORD group_number, WORD* group_begin, WORD* group_size);
};
DWORD_PTR GetCurrentProcessCpuMask();
#endif // HOST_WINDOWS
int GetTotalProcessorCount();
//******************************************************************************
// Returns the number of processors that a process has been configured to run on
//******************************************************************************
int GetCurrentProcessCpuCount();
//*****************************************************************************
// Return != 0 if the bit at the specified index in the array is on and 0 if
// it is off.
//*****************************************************************************
inline int GetBit(PTR_BYTE pcBits,int iBit)
{
LIMITED_METHOD_CONTRACT;
return (pcBits[iBit>>3] & (1 << (iBit & 0x7)));
}
#ifdef DACCESS_COMPILE
inline int GetBit(BYTE const * pcBits,int iBit)
{
WRAPPER_NO_CONTRACT;
return GetBit(dac_cast<PTR_BYTE>(pcBits), iBit);
}
#endif
//*****************************************************************************
// Set the state of the bit at the specified index based on the value of bOn.
//*****************************************************************************
inline void SetBit(PTR_BYTE pcBits,int iBit,int bOn)
{
LIMITED_METHOD_CONTRACT;
if (bOn)
pcBits[iBit>>3] |= (1 << (iBit & 0x7));
else
pcBits[iBit>>3] &= ~(1 << (iBit & 0x7));
}
#ifdef DACCESS_COMPILE
inline void SetBit(BYTE * pcBits,int iBit,int bOn)
{
WRAPPER_NO_CONTRACT;
SetBit(dac_cast<PTR_BYTE>(pcBits), iBit, bOn);
}
#endif
template<typename T>
class SimpleListNode final
{
public:
SimpleListNode(T const& _t)
: data{ _t }
, next{}
{
LIMITED_METHOD_CONTRACT;
}
T data;
SimpleListNode<T>* next;
};
template<typename T>
class SimpleList final
{
public:
typedef SimpleListNode<T> Node;
SimpleList()
: _head{}
{
LIMITED_METHOD_CONTRACT;
}
void LinkHead(Node* pNode)
{
LIMITED_METHOD_CONTRACT;
pNode->next = _head;
_head = pNode;
}
Node* UnlinkHead()
{
LIMITED_METHOD_CONTRACT;
Node* ret = _head;
if (_head)
{
_head = _head->next;
}
return ret;
}
Node* Head()
{
LIMITED_METHOD_CONTRACT;
return _head;
}
private:
Node* _head;
};
//*****************************************************************************
// This class implements a dynamic array of structures for which the order of
// the elements is unimportant. This means that any item placed in the list
// may be swapped to any other location in the list at any time. If the order
// of the items you place in the array is important, then use the CStructArray
// class.
//*****************************************************************************
class CUnorderedArrayBase
{
friend struct ::cdac_data<CUnorderedArrayBase>;
protected:
int m_iCount; // # of elements used in the list.
TADDR m_pTable; // Pointer to the list of elements (opaque address;
// the templated derived class supplies the element type).
CUnorderedArrayBase()
: m_iCount(0), m_pTable((TADDR)NULL)
{
}
};
template<>
struct cdac_data<CUnorderedArrayBase>
{
static constexpr size_t Count = offsetof(CUnorderedArrayBase, m_iCount);
static constexpr size_t Table = offsetof(CUnorderedArrayBase, m_pTable);
};
template <class T,
int iGrowInc,
class ALLOCATOR>
class CUnorderedArrayWithAllocator : public CUnorderedArrayBase
{
int m_iSize; // # of elements allocated in the list.
public:
#ifndef DACCESS_COMPILE
CUnorderedArrayWithAllocator() :
m_iSize(0)
{
LIMITED_METHOD_CONTRACT;
}
~CUnorderedArrayWithAllocator()
{
LIMITED_METHOD_CONTRACT;
// Free the chunk of memory.
if (m_pTable != (TADDR)NULL)
ALLOCATOR::Free(this, reinterpret_cast<T*>(m_pTable));
}
CUnorderedArrayWithAllocator(CUnorderedArrayWithAllocator const&) = delete;
CUnorderedArrayWithAllocator& operator=(CUnorderedArrayWithAllocator const&) = delete;
CUnorderedArrayWithAllocator(CUnorderedArrayWithAllocator&& other)
: m_iSize{ other.m_iSize }
{
LIMITED_METHOD_CONTRACT;
m_iCount = other.m_iCount;
m_pTable = other.m_pTable;
other.m_iCount = 0;
other.m_iSize = 0;
other.m_pTable = (TADDR)NULL;
}
CUnorderedArrayWithAllocator& operator=(CUnorderedArrayWithAllocator&& other)
{
LIMITED_METHOD_CONTRACT;
if (this != &other)
{
if (m_pTable != (TADDR)NULL)
ALLOCATOR::Free(this, reinterpret_cast<T*>(m_pTable));
m_iCount = other.m_iCount;
m_iSize = other.m_iSize;
m_pTable = other.m_pTable;
other.m_iCount = 0;
other.m_iSize = 0;
other.m_pTable = (TADDR)NULL;
}
return *this;
}
void Clear()
{
WRAPPER_NO_CONTRACT;
m_iCount = 0;
if (m_iSize > iGrowInc)
{
T* tmp = ALLOCATOR::AllocNoThrow(this, iGrowInc);
if (tmp) {
ALLOCATOR::Free(this, reinterpret_cast<T*>(m_pTable));
m_pTable = reinterpret_cast<TADDR>(tmp);
m_iSize = iGrowInc;
}
}
}
void Clear(int iFirst, int iCount)
{
WRAPPER_NO_CONTRACT;
int iSize;
T* pTable = reinterpret_cast<T*>(m_pTable);
if (iFirst + iCount < m_iCount)
memmove(&pTable[iFirst], &pTable[iFirst + iCount], sizeof(T) * (m_iCount - (iFirst + iCount)));
m_iCount -= iCount;
iSize = ((m_iCount / iGrowInc) * iGrowInc) + ((m_iCount % iGrowInc != 0) ? iGrowInc : 0);
if (m_iSize > iGrowInc && iSize < m_iSize)
{
T *tmp = ALLOCATOR::AllocNoThrow(this, iSize);
if (tmp) {
memcpy (tmp, pTable, iSize * sizeof(T));
delete [] pTable;
m_pTable = reinterpret_cast<TADDR>(tmp);
m_iSize = iSize;
}
}
_ASSERTE(m_iCount <= m_iSize);
}
T *Table()
{
LIMITED_METHOD_CONTRACT;
return reinterpret_cast<T*>(m_pTable);
}
T *Append()
{
CONTRACTL {
NOTHROW;
} CONTRACTL_END;
// The array should grow, if we can't fit one more element into the array.
if (m_iSize <= m_iCount && GrowNoThrow() == NULL)
return (NULL);
return (&reinterpret_cast<T*>(m_pTable)[m_iCount++]);
}
T *AppendThrowing()
{
CONTRACTL {
THROWS;
} CONTRACTL_END;
// The array should grow, if we can't fit one more element into the array.
if (m_iSize <= m_iCount)
Grow();
return (&reinterpret_cast<T*>(m_pTable)[m_iCount++]);
}
void Delete(const T &Entry)
{
LIMITED_METHOD_CONTRACT;
T* pTable = reinterpret_cast<T*>(m_pTable);
--m_iCount;
for (int i=0; i <= m_iCount; ++i)
if (pTable[i] == Entry)
{
pTable[i] = pTable[m_iCount];
return;
}
// Just in case we didn't find it.
++m_iCount;
}
void DeleteByIndex(int i)
{
LIMITED_METHOD_CONTRACT;
T* pTable = reinterpret_cast<T*>(m_pTable);
--m_iCount;
pTable[i] = pTable[m_iCount];
}
void Swap(int i,int j)
{
LIMITED_METHOD_CONTRACT;
T tmp;
T* pTable = reinterpret_cast<T*>(m_pTable);
if (i == j)
return;
tmp = pTable[i];
pTable[i] = pTable[j];
pTable[j] = tmp;
}
#else
TADDR Table()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
return (m_pTable);
}
void EnumMemoryRegions(void)
{
SUPPORTS_DAC;
DacEnumMemoryRegion(m_pTable, m_iCount * sizeof(T));
}
#endif // #ifndef DACCESS_COMPILE
INT32 Count()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
return m_iCount;
}
private:
T *Grow();
T *GrowNoThrow();
};
#ifndef DACCESS_COMPILE
//*****************************************************************************
// Increase the size of the array.
//*****************************************************************************
template <class T,
int iGrowInc,
class ALLOCATOR>
T *CUnorderedArrayWithAllocator<T,iGrowInc,ALLOCATOR>::GrowNoThrow() // NULL if can't grow.
{
WRAPPER_NO_CONTRACT;
T *pTemp;
T *pTable = reinterpret_cast<T*>(m_pTable);
// try to allocate memory for reallocation.
if ((pTemp = ALLOCATOR::AllocNoThrow(this, m_iSize+iGrowInc)) == NULL)
return (NULL);
memcpy (pTemp, pTable, m_iSize*sizeof(T));
ALLOCATOR::Free(this, pTable);
m_pTable = reinterpret_cast<TADDR>(pTemp);
m_iSize += iGrowInc;
_ASSERTE(m_iSize > 0);
return (pTemp);
}
template <class T,
int iGrowInc,
class ALLOCATOR>
T *CUnorderedArrayWithAllocator<T,iGrowInc,ALLOCATOR>::Grow() // exception if can't grow.
{
WRAPPER_NO_CONTRACT;
T *pTemp;
T *pTable = reinterpret_cast<T*>(m_pTable);
// try to allocate memory for reallocation.
pTemp = ALLOCATOR::AllocThrowing(this, m_iSize+iGrowInc);
if (m_iSize > 0)
memcpy (pTemp, pTable, m_iSize*sizeof(T));
ALLOCATOR::Free(this, pTable);
m_pTable = reinterpret_cast<TADDR>(pTemp);
m_iSize += iGrowInc;
_ASSERTE(m_iSize > 0);
return (pTemp);
}
#endif // #ifndef DACCESS_COMPILE
template <class T>
class CUnorderedArray__Allocator
{
public:
static T *AllocThrowing (void*, int nElements)
{
return new T[nElements];
}
static T *AllocNoThrow (void*, int nElements)
{
return new (nothrow) T[nElements];
}
static void Free (void*, T *pTable)
{
delete [] pTable;
}
};
template <class T,int iGrowInc>
class CUnorderedArray : public CUnorderedArrayWithAllocator<T, iGrowInc, CUnorderedArray__Allocator<T> >
{
public:
CUnorderedArray ()
{
LIMITED_METHOD_CONTRACT;
}
};
//Used by the debugger. Included here in hopes somebody else might, too
typedef CUnorderedArray<SIZE_T, 17> SIZE_T_UNORDERED_ARRAY;
//*****************************************************************************
// This class implements a dynamic array of structures for which the insert
// order is important. Inserts will slide all elements after the location
// down, deletes slide all values over the deleted item. If the order of the
// items in the array is unimportant to you, then CUnorderedArray may provide
// the same feature set at lower cost.
//*****************************************************************************
class CStructArray
{
BYTE *m_pList; // Pointer to the list of elements.
int m_iCount; // # of elements used in the list.
int m_iSize; // # of elements allocated in the list.
int m_iGrowInc; // Growth increment.
short m_iElemSize; // Size of an array element.
bool m_bFree; // true if data is automatically maintained.
public: