-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
comutilnative.cpp
2022 lines (1600 loc) · 57.6 KB
/
comutilnative.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.
//
//
/*============================================================
**
** File: COMUtilNative
**
**
**
** Purpose: A dumping ground for classes which aren't large
** enough to get their own file in the EE.
**
**
**
===========================================================*/
#include "common.h"
#include "object.h"
#include "excep.h"
#include "vars.hpp"
#include "comutilnative.h"
#include "utilcode.h"
#include "frames.h"
#include "field.h"
#include "winwrap.h"
#include "gcheaputilities.h"
#include "fcall.h"
#include "invokeutil.h"
#include "eeconfig.h"
#include "typestring.h"
#include "finalizerthread.h"
#include "threadsuspend.h"
#ifdef FEATURE_COMINTEROP
#include "comcallablewrapper.h"
#include "comcache.h"
#endif // FEATURE_COMINTEROP
#include "arraynative.inl"
//
//
// EXCEPTION NATIVE
//
//
FCIMPL1(FC_BOOL_RET, ExceptionNative::IsImmutableAgileException, Object* pExceptionUNSAFE)
{
FCALL_CONTRACT;
ASSERT(pExceptionUNSAFE != NULL);
OBJECTREF pException = (OBJECTREF) pExceptionUNSAFE;
// The preallocated exception objects may be used from multiple AppDomains
// and therefore must remain immutable from the application's perspective.
FC_RETURN_BOOL(CLRException::IsPreallocatedExceptionObject(pException));
}
FCIMPLEND
// This FCall sets a flag against the thread exception state to indicate to
// IL_Throw and the StackTraceInfo implementation to account for the fact
// that we have restored a foreign exception dispatch details.
//
// Refer to the respective methods for details on how they use this flag.
FCIMPL0(VOID, ExceptionNative::PrepareForForeignExceptionRaise)
{
FCALL_CONTRACT;
PTR_ThreadExceptionState pCurTES = GetThread()->GetExceptionState();
// Set a flag against the TES to indicate this is a foreign exception raise.
pCurTES->SetRaisingForeignException();
}
FCIMPLEND
// Given an exception object, this method will extract the stacktrace and dynamic method array and set them up for return to the caller.
FCIMPL3(VOID, ExceptionNative::GetStackTracesDeepCopy, Object* pExceptionObjectUnsafe, Object **pStackTraceUnsafe, Object **pDynamicMethodsUnsafe);
{
CONTRACTL
{
FCALL_CHECK;
}
CONTRACTL_END;
ASSERT(pExceptionObjectUnsafe != NULL);
ASSERT(pStackTraceUnsafe != NULL);
ASSERT(pDynamicMethodsUnsafe != NULL);
struct
{
StackTraceArray stackTrace;
StackTraceArray stackTraceCopy;
EXCEPTIONREF refException;
PTRARRAYREF dynamicMethodsArray; // Object array of Managed Resolvers
PTRARRAYREF dynamicMethodsArrayCopy; // Copy of the object array of Managed Resolvers
} gc;
gc.refException = NULL;
gc.dynamicMethodsArray = NULL;
gc.dynamicMethodsArrayCopy = NULL;
// GC protect the array reference
HELPER_METHOD_FRAME_BEGIN_PROTECT(gc);
// Get the exception object reference
gc.refException = (EXCEPTIONREF)(ObjectToOBJECTREF(pExceptionObjectUnsafe));
// Fetch the stacktrace details from the exception under a lock
gc.refException->GetStackTrace(gc.stackTrace, &gc.dynamicMethodsArray);
bool fHaveStackTrace = false;
bool fHaveDynamicMethodArray = false;
if ((unsigned)gc.stackTrace.Size() > 0)
{
// Deepcopy the array
gc.stackTraceCopy.CopyFrom(gc.stackTrace);
fHaveStackTrace = true;
}
if (gc.dynamicMethodsArray != NULL)
{
// Get the number of elements in the dynamic methods array
unsigned cOrigDynamic = gc.dynamicMethodsArray->GetNumComponents();
// ..and allocate a new array. This can trigger GC or throw under OOM.
gc.dynamicMethodsArrayCopy = (PTRARRAYREF)AllocateObjectArray(cOrigDynamic, g_pObjectClass);
// Deepcopy references to the new array we just allocated
memmoveGCRefs(gc.dynamicMethodsArrayCopy->GetDataPtr(), gc.dynamicMethodsArray->GetDataPtr(),
cOrigDynamic * sizeof(Object *));
fHaveDynamicMethodArray = true;
}
// Prep to return
*pStackTraceUnsafe = fHaveStackTrace?OBJECTREFToObject(gc.stackTraceCopy.Get()):NULL;
*pDynamicMethodsUnsafe = fHaveDynamicMethodArray?OBJECTREFToObject(gc.dynamicMethodsArrayCopy):NULL;
HELPER_METHOD_FRAME_END();
}
FCIMPLEND
// Given an exception object and deep copied instances of a stacktrace and/or dynamic method array, this method will set the latter in the exception object instance.
FCIMPL3(VOID, ExceptionNative::SaveStackTracesFromDeepCopy, Object* pExceptionObjectUnsafe, Object *pStackTraceUnsafe, Object *pDynamicMethodsUnsafe);
{
CONTRACTL
{
FCALL_CHECK;
}
CONTRACTL_END;
ASSERT(pExceptionObjectUnsafe != NULL);
struct
{
StackTraceArray stackTrace;
EXCEPTIONREF refException;
PTRARRAYREF dynamicMethodsArray; // Object array of Managed Resolvers
} gc;
gc.refException = NULL;
gc.dynamicMethodsArray = NULL;
// GC protect the array reference
HELPER_METHOD_FRAME_BEGIN_PROTECT(gc);
// Get the exception object reference
gc.refException = (EXCEPTIONREF)(ObjectToOBJECTREF(pExceptionObjectUnsafe));
if (pStackTraceUnsafe != NULL)
{
// Copy the stacktrace
StackTraceArray stackTraceArray((I1ARRAYREF)ObjectToOBJECTREF(pStackTraceUnsafe));
gc.stackTrace.Swap(stackTraceArray);
}
gc.dynamicMethodsArray = NULL;
if (pDynamicMethodsUnsafe != NULL)
{
gc.dynamicMethodsArray = (PTRARRAYREF)ObjectToOBJECTREF(pDynamicMethodsUnsafe);
}
// If there is no stacktrace, then there cannot be any dynamic method array. Thus,
// save stacktrace only when we have it.
if (gc.stackTrace.Size() > 0)
{
// Save the stacktrace details in the exception under a lock
gc.refException->SetStackTrace(gc.stackTrace.Get(), gc.dynamicMethodsArray);
}
else
{
gc.refException->SetStackTrace(NULL, NULL);
}
HELPER_METHOD_FRAME_END();
}
FCIMPLEND
#ifdef FEATURE_COMINTEROP
BSTR BStrFromString(STRINGREF s)
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
WCHAR *wz;
int cch;
BSTR bstr;
if (s == NULL)
return NULL;
s->RefInterpretGetStringValuesDangerousForGC(&wz, &cch);
bstr = SysAllocString(wz);
if (bstr == NULL)
COMPlusThrowOM();
return bstr;
}
static BSTR GetExceptionDescription(OBJECTREF objException)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION( IsException(objException->GetMethodTable()) );
}
CONTRACTL_END;
BSTR bstrDescription;
STRINGREF MessageString = NULL;
GCPROTECT_BEGIN(MessageString)
GCPROTECT_BEGIN(objException)
{
// read Exception.Message property
MethodDescCallSite getMessage(METHOD__EXCEPTION__GET_MESSAGE, &objException);
ARG_SLOT GetMessageArgs[] = { ObjToArgSlot(objException)};
MessageString = getMessage.Call_RetSTRINGREF(GetMessageArgs);
// if the message string is empty then use the exception classname.
if (MessageString == NULL || MessageString->GetStringLength() == 0) {
// call GetClassName
MethodDescCallSite getClassName(METHOD__EXCEPTION__GET_CLASS_NAME, &objException);
ARG_SLOT GetClassNameArgs[] = { ObjToArgSlot(objException)};
MessageString = getClassName.Call_RetSTRINGREF(GetClassNameArgs);
_ASSERTE(MessageString != NULL && MessageString->GetStringLength() != 0);
}
// Allocate the description BSTR.
int DescriptionLen = MessageString->GetStringLength();
bstrDescription = SysAllocStringLen(MessageString->GetBuffer(), DescriptionLen);
}
GCPROTECT_END();
GCPROTECT_END();
return bstrDescription;
}
static BSTR GetExceptionSource(OBJECTREF objException)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION( IsException(objException->GetMethodTable()) );
}
CONTRACTL_END;
STRINGREF refRetVal;
GCPROTECT_BEGIN(objException)
// read Exception.Source property
MethodDescCallSite getSource(METHOD__EXCEPTION__GET_SOURCE, &objException);
ARG_SLOT GetSourceArgs[] = { ObjToArgSlot(objException)};
refRetVal = getSource.Call_RetSTRINGREF(GetSourceArgs);
GCPROTECT_END();
return BStrFromString(refRetVal);
}
static void GetExceptionHelp(OBJECTREF objException, BSTR *pbstrHelpFile, DWORD *pdwHelpContext)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
INJECT_FAULT(COMPlusThrowOM());
PRECONDITION(IsException(objException->GetMethodTable()));
PRECONDITION(CheckPointer(pbstrHelpFile));
PRECONDITION(CheckPointer(pdwHelpContext));
}
CONTRACTL_END;
*pdwHelpContext = 0;
GCPROTECT_BEGIN(objException);
// call managed code to parse help context
MethodDescCallSite getHelpContext(METHOD__EXCEPTION__GET_HELP_CONTEXT, &objException);
ARG_SLOT GetHelpContextArgs[] =
{
ObjToArgSlot(objException),
PtrToArgSlot(pdwHelpContext)
};
*pbstrHelpFile = BStrFromString(getHelpContext.Call_RetSTRINGREF(GetHelpContextArgs));
GCPROTECT_END();
}
// NOTE: caller cleans up any partially initialized BSTRs in pED
void ExceptionNative::GetExceptionData(OBJECTREF objException, ExceptionData *pED)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(IsException(objException->GetMethodTable()));
PRECONDITION(CheckPointer(pED));
}
CONTRACTL_END;
ZeroMemory(pED, sizeof(ExceptionData));
GCPROTECT_BEGIN(objException);
pED->hr = GetExceptionHResult(objException);
pED->bstrDescription = GetExceptionDescription(objException);
pED->bstrSource = GetExceptionSource(objException);
GetExceptionHelp(objException, &pED->bstrHelpFile, &pED->dwHelpContext);
GCPROTECT_END();
return;
}
HRESULT SimpleComCallWrapper::IErrorInfo_hr()
{
WRAPPER_NO_CONTRACT;
return GetExceptionHResult(this->GetObjectRef());
}
BSTR SimpleComCallWrapper::IErrorInfo_bstrDescription()
{
WRAPPER_NO_CONTRACT;
return GetExceptionDescription(this->GetObjectRef());
}
BSTR SimpleComCallWrapper::IErrorInfo_bstrSource()
{
WRAPPER_NO_CONTRACT;
return GetExceptionSource(this->GetObjectRef());
}
BSTR SimpleComCallWrapper::IErrorInfo_bstrHelpFile()
{
WRAPPER_NO_CONTRACT;
BSTR bstrHelpFile;
DWORD dwHelpContext;
GetExceptionHelp(this->GetObjectRef(), &bstrHelpFile, &dwHelpContext);
return bstrHelpFile;
}
DWORD SimpleComCallWrapper::IErrorInfo_dwHelpContext()
{
WRAPPER_NO_CONTRACT;
BSTR bstrHelpFile;
DWORD dwHelpContext;
GetExceptionHelp(this->GetObjectRef(), &bstrHelpFile, &dwHelpContext);
SysFreeString(bstrHelpFile);
return dwHelpContext;
}
GUID SimpleComCallWrapper::IErrorInfo_guid()
{
LIMITED_METHOD_CONTRACT;
return GUID_NULL;
}
#endif // FEATURE_COMINTEROP
FCIMPL0(EXCEPTION_POINTERS*, ExceptionNative::GetExceptionPointers)
{
FCALL_CONTRACT;
EXCEPTION_POINTERS* retVal = NULL;
Thread *pThread = GetThread();
if (pThread->IsExceptionInProgress())
{
retVal = pThread->GetExceptionState()->GetExceptionPointers();
}
return retVal;
}
FCIMPLEND
FCIMPL0(INT32, ExceptionNative::GetExceptionCode)
{
FCALL_CONTRACT;
INT32 retVal = 0;
Thread *pThread = GetThread();
if (pThread->IsExceptionInProgress())
{
retVal = pThread->GetExceptionState()->GetExceptionCode();
}
return retVal;
}
FCIMPLEND
extern uint32_t g_exceptionCount;
FCIMPL0(UINT32, ExceptionNative::GetExceptionCount)
{
FCALL_CONTRACT;
return g_exceptionCount;
}
FCIMPLEND
//
// This must be implemented as an FCALL because managed code cannot
// swallow a thread abort exception without resetting the abort,
// which we don't want to do. Additionally, we can run into deadlocks
// if we use the ResourceManager to do resource lookups - it requires
// taking managed locks when initializing Globalization & Security,
// but a thread abort on a separate thread initializing those same
// systems would also do a resource lookup via the ResourceManager.
// We've deadlocked in CompareInfo.GetCompareInfo &
// Environment.GetResourceString. It's not practical to take all of
// our locks within CER's to avoid this problem - just use the CLR's
// unmanaged resources.
//
extern "C" void QCALLTYPE ExceptionNative_GetMessageFromNativeResources(ExceptionMessageKind kind, QCall::StringHandleOnStack retMesg)
{
QCALL_CONTRACT;
BEGIN_QCALL;
SString buffer;
HRESULT hr = S_OK;
const WCHAR * wszFallbackString = NULL;
switch(kind) {
case ExceptionMessageKind::ThreadAbort:
hr = buffer.LoadResourceAndReturnHR(CCompRC::Error, IDS_EE_THREAD_ABORT);
if (FAILED(hr)) {
wszFallbackString = W("Thread was being aborted.");
}
break;
case ExceptionMessageKind::ThreadInterrupted:
hr = buffer.LoadResourceAndReturnHR(CCompRC::Error, IDS_EE_THREAD_INTERRUPTED);
if (FAILED(hr)) {
wszFallbackString = W("Thread was interrupted from a waiting state.");
}
break;
case ExceptionMessageKind::OutOfMemory:
hr = buffer.LoadResourceAndReturnHR(CCompRC::Error, IDS_EE_OUT_OF_MEMORY);
if (FAILED(hr)) {
wszFallbackString = W("Insufficient memory to continue the execution of the program.");
}
break;
default:
_ASSERTE(!"Unknown ExceptionMessageKind value!");
}
if (FAILED(hr)) {
STRESS_LOG1(LF_BCL, LL_ALWAYS, "LoadResource error: %x", hr);
_ASSERTE(wszFallbackString != NULL);
retMesg.Set(wszFallbackString);
}
else {
retMesg.Set(buffer);
}
END_QCALL;
}
extern "C" void QCALLTYPE Buffer_Clear(void *dst, size_t length)
{
QCALL_CONTRACT;
#if defined(HOST_X86) || defined(HOST_AMD64)
if (length > 0x100)
{
// memset ends up calling rep stosb if the hardware claims to support it efficiently. rep stosb is up to 2x slower
// on misaligned blocks. Workaround this issue by aligning the blocks passed to memset upfront.
*(uint64_t*)dst = 0;
*((uint64_t*)dst + 1) = 0;
*((uint64_t*)dst + 2) = 0;
*((uint64_t*)dst + 3) = 0;
void* end = (uint8_t*)dst + length;
*((uint64_t*)end - 1) = 0;
*((uint64_t*)end - 2) = 0;
*((uint64_t*)end - 3) = 0;
*((uint64_t*)end - 4) = 0;
dst = ALIGN_UP((uint8_t*)dst + 1, 32);
length = ALIGN_DOWN((uint8_t*)end - 1, 32) - (uint8_t*)dst;
}
#endif
memset(dst, 0, length);
}
FCIMPL3(VOID, Buffer::BulkMoveWithWriteBarrier, void *dst, void *src, size_t byteCount)
{
FCALL_CONTRACT;
if (dst != src && byteCount != 0)
InlinedMemmoveGCRefsHelper(dst, src, byteCount);
FC_GC_POLL();
}
FCIMPLEND
extern "C" void QCALLTYPE Buffer_MemMove(void *dst, void *src, size_t length)
{
QCALL_CONTRACT;
memmove(dst, src, length);
}
//
// GCInterface
//
INT32 GCInterface::m_gc_counts[3] = {0,0,0};
UINT64 GCInterface::m_addPressure[MEM_PRESSURE_COUNT] = {0, 0, 0, 0}; // history of memory pressure additions
UINT64 GCInterface::m_remPressure[MEM_PRESSURE_COUNT] = {0, 0, 0, 0}; // history of memory pressure removals
// incremented after a gen2 GC has been detected,
// (m_iteration % MEM_PRESSURE_COUNT) is used as an index into m_addPressure and m_remPressure
UINT GCInterface::m_iteration = 0;
FCIMPL0(INT64, GCInterface::GetTotalPauseDuration)
{
FCALL_CONTRACT;
FC_GC_POLL_NOT_NEEDED();
return GCHeapUtilities::GetGCHeap()->GetTotalPauseDuration();
}
FCIMPLEND
FCIMPL2(void, GCInterface::GetMemoryInfo, Object* objUNSAFE, int kind)
{
FCALL_CONTRACT;
FC_GC_POLL_NOT_NEEDED();
GCMEMORYINFODATAREF objGCMemoryInfo = (GCMEMORYINFODATAREF)(ObjectToOBJECTREF (objUNSAFE));
UINT64* genInfoRaw = (UINT64*)&(objGCMemoryInfo->generationInfo0);
UINT64* pauseInfoRaw = (UINT64*)&(objGCMemoryInfo->pauseDuration0);
return GCHeapUtilities::GetGCHeap()->GetMemoryInfo(
&(objGCMemoryInfo->highMemLoadThresholdBytes),
&(objGCMemoryInfo->totalAvailableMemoryBytes),
&(objGCMemoryInfo->lastRecordedMemLoadBytes),
&(objGCMemoryInfo->lastRecordedHeapSizeBytes),
&(objGCMemoryInfo->lastRecordedFragmentationBytes),
&(objGCMemoryInfo->totalCommittedBytes),
&(objGCMemoryInfo->promotedBytes),
&(objGCMemoryInfo->pinnedObjectCount),
&(objGCMemoryInfo->finalizationPendingCount),
&(objGCMemoryInfo->index),
&(objGCMemoryInfo->generation),
&(objGCMemoryInfo->pauseTimePercent),
(bool*)&(objGCMemoryInfo->isCompaction),
(bool*)&(objGCMemoryInfo->isConcurrent),
genInfoRaw,
pauseInfoRaw,
kind);
}
FCIMPLEND
FCIMPL0(UINT32, GCInterface::GetMemoryLoad)
{
FCALL_CONTRACT;
FC_GC_POLL_NOT_NEEDED();
int result = (INT32)GCHeapUtilities::GetGCHeap()->GetMemoryLoad();
return result;
}
FCIMPLEND
FCIMPL0(int, GCInterface::GetGcLatencyMode)
{
FCALL_CONTRACT;
FC_GC_POLL_NOT_NEEDED();
int result = (INT32)GCHeapUtilities::GetGCHeap()->GetGcLatencyMode();
return result;
}
FCIMPLEND
FCIMPL1(int, GCInterface::SetGcLatencyMode, int newLatencyMode)
{
FCALL_CONTRACT;
FC_GC_POLL_NOT_NEEDED();
return GCHeapUtilities::GetGCHeap()->SetGcLatencyMode(newLatencyMode);
}
FCIMPLEND
FCIMPL0(int, GCInterface::GetLOHCompactionMode)
{
FCALL_CONTRACT;
FC_GC_POLL_NOT_NEEDED();
int result = (INT32)GCHeapUtilities::GetGCHeap()->GetLOHCompactionMode();
return result;
}
FCIMPLEND
FCIMPL1(void, GCInterface::SetLOHCompactionMode, int newLOHCompactionyMode)
{
FCALL_CONTRACT;
FC_GC_POLL_NOT_NEEDED();
GCHeapUtilities::GetGCHeap()->SetLOHCompactionMode(newLOHCompactionyMode);
}
FCIMPLEND
FCIMPL2(FC_BOOL_RET, GCInterface::RegisterForFullGCNotification, UINT32 gen2Percentage, UINT32 lohPercentage)
{
FCALL_CONTRACT;
FC_GC_POLL_NOT_NEEDED();
FC_RETURN_BOOL(GCHeapUtilities::GetGCHeap()->RegisterForFullGCNotification(gen2Percentage, lohPercentage));
}
FCIMPLEND
FCIMPL0(FC_BOOL_RET, GCInterface::CancelFullGCNotification)
{
FCALL_CONTRACT;
FC_GC_POLL_NOT_NEEDED();
FC_RETURN_BOOL(GCHeapUtilities::GetGCHeap()->CancelFullGCNotification());
}
FCIMPLEND
FCIMPL1(int, GCInterface::WaitForFullGCApproach, int millisecondsTimeout)
{
CONTRACTL
{
THROWS;
MODE_COOPERATIVE;
DISABLED(GC_TRIGGERS); // can't use this in an FCALL because we're in forbid gc mode until we setup a H_M_F.
}
CONTRACTL_END;
int result = 0;
//We don't need to check the top end because the GC will take care of that.
HELPER_METHOD_FRAME_BEGIN_RET_0();
DWORD dwMilliseconds = ((millisecondsTimeout == -1) ? INFINITE : millisecondsTimeout);
result = GCHeapUtilities::GetGCHeap()->WaitForFullGCApproach(dwMilliseconds);
HELPER_METHOD_FRAME_END();
return result;
}
FCIMPLEND
FCIMPL1(int, GCInterface::WaitForFullGCComplete, int millisecondsTimeout)
{
CONTRACTL
{
THROWS;
MODE_COOPERATIVE;
DISABLED(GC_TRIGGERS); // can't use this in an FCALL because we're in forbid gc mode until we setup a H_M_F.
}
CONTRACTL_END;
int result = 0;
//We don't need to check the top end because the GC will take care of that.
HELPER_METHOD_FRAME_BEGIN_RET_0();
DWORD dwMilliseconds = ((millisecondsTimeout == -1) ? INFINITE : millisecondsTimeout);
result = GCHeapUtilities::GetGCHeap()->WaitForFullGCComplete(dwMilliseconds);
HELPER_METHOD_FRAME_END();
return result;
}
FCIMPLEND
/*================================GetGeneration=================================
**Action: Returns the generation in which args->obj is found.
**Returns: The generation in which args->obj is found.
**Arguments: args->obj -- The object to locate.
**Exceptions: ArgumentException if args->obj is null.
==============================================================================*/
FCIMPL1(int, GCInterface::GetGeneration, Object* objUNSAFE)
{
FCALL_CONTRACT;
if (objUNSAFE == NULL)
FCThrowArgumentNull(W("obj"));
int result = (INT32)GCHeapUtilities::GetGCHeap()->WhichGeneration(objUNSAFE);
FC_GC_POLL_RET();
return result;
}
FCIMPLEND
/*================================GetSegmentSize========-=======================
**Action: Returns the maximum GC heap segment size
**Returns: The maximum segment size of either the normal heap or the large object heap, whichever is bigger
==============================================================================*/
FCIMPL0(UINT64, GCInterface::GetSegmentSize)
{
FCALL_CONTRACT;
IGCHeap * pGC = GCHeapUtilities::GetGCHeap();
size_t segment_size = pGC->GetValidSegmentSize(false);
size_t large_segment_size = pGC->GetValidSegmentSize(true);
_ASSERTE(segment_size < SIZE_T_MAX && large_segment_size < SIZE_T_MAX);
if (segment_size < large_segment_size)
segment_size = large_segment_size;
FC_GC_POLL_RET();
return (UINT64) segment_size;
}
FCIMPLEND
/*================================CollectionCount=================================
**Action: Returns the number of collections for this generation since the beginning of the life of the process
**Returns: The collection count.
**Arguments: args->generation -- The generation
**Exceptions: Argument exception if args->generation is < 0 or > GetMaxGeneration();
==============================================================================*/
FCIMPL2(int, GCInterface::CollectionCount, INT32 generation, INT32 getSpecialGCCount)
{
FCALL_CONTRACT;
//We've already checked this in GC.cs, so we'll just assert it here.
_ASSERTE(generation >= 0);
//We don't need to check the top end because the GC will take care of that.
int result = (INT32)GCHeapUtilities::GetGCHeap()->CollectionCount(generation, getSpecialGCCount);
FC_GC_POLL_RET();
return result;
}
FCIMPLEND
extern "C" int QCALLTYPE GCInterface_StartNoGCRegion(INT64 totalSize, BOOL lohSizeKnown, INT64 lohSize, BOOL disallowFullBlockingGC)
{
QCALL_CONTRACT;
int retVal = 0;
BEGIN_QCALL;
GCX_COOP();
retVal = GCHeapUtilities::GetGCHeap()->StartNoGCRegion((ULONGLONG)totalSize,
!!lohSizeKnown,
(ULONGLONG)lohSize,
!!disallowFullBlockingGC);
END_QCALL;
return retVal;
}
extern "C" int QCALLTYPE GCInterface_EndNoGCRegion()
{
QCALL_CONTRACT;
int retVal = FALSE;
BEGIN_QCALL;
retVal = GCHeapUtilities::GetGCHeap()->EndNoGCRegion();
END_QCALL;
return retVal;
}
/*===============================GetGenerationWR================================
**Action: Returns the generation in which the object pointed to by a WeakReference is found.
**Returns:
**Arguments: args->handle -- the OBJECTHANDLE to the object which we're locating.
**Exceptions: ArgumentException if handle points to an object which is not accessible.
==============================================================================*/
FCIMPL1(int, GCInterface::GetGenerationWR, LPVOID handle)
{
FCALL_CONTRACT;
int iRetVal = 0;
HELPER_METHOD_FRAME_BEGIN_RET_0();
OBJECTREF temp;
temp = ObjectFromHandle((OBJECTHANDLE) handle);
if (temp == NULL)
COMPlusThrowArgumentNull(W("wo"));
iRetVal = (INT32)GCHeapUtilities::GetGCHeap()->WhichGeneration(OBJECTREFToObject(temp));
HELPER_METHOD_FRAME_END();
return iRetVal;
}
FCIMPLEND
FCIMPL0(int, GCInterface::GetLastGCPercentTimeInGC)
{
FCALL_CONTRACT;
return GCHeapUtilities::GetGCHeap()->GetLastGCPercentTimeInGC();
}
FCIMPLEND
FCIMPL1(UINT64, GCInterface::GetGenerationSize, int gen)
{
FCALL_CONTRACT;
return (UINT64)(GCHeapUtilities::GetGCHeap()->GetLastGCGenerationSize(gen));
}
FCIMPLEND
/*================================GetTotalMemory================================
**Action: Returns the total number of bytes in use
**Returns: The total number of bytes in use
**Arguments: None
**Exceptions: None
==============================================================================*/
extern "C" INT64 QCALLTYPE GCInterface_GetTotalMemory()
{
QCALL_CONTRACT;
INT64 iRetVal = 0;
BEGIN_QCALL;
GCX_COOP();
iRetVal = (INT64) GCHeapUtilities::GetGCHeap()->GetTotalBytesInUse();
END_QCALL;
return iRetVal;
}
/*==============================Collect=========================================
**Action: Collects all generations <= args->generation
**Returns: void
**Arguments: args->generation: The maximum generation to collect
**Exceptions: Argument exception if args->generation is < 0 or > GetMaxGeneration();
==============================================================================*/
extern "C" void QCALLTYPE GCInterface_Collect(INT32 generation, INT32 mode)
{
QCALL_CONTRACT;
BEGIN_QCALL;
//We've already checked this in GC.cs, so we'll just assert it here.
_ASSERTE(generation >= -1);
//We don't need to check the top end because the GC will take care of that.
GCX_COOP();
GCHeapUtilities::GetGCHeap()->GarbageCollect(generation, false, mode);
END_QCALL;
}
/*==========================WaitForPendingFinalizers============================
**Action: Run all Finalizers that haven't been run.
**Arguments: None
**Exceptions: None
==============================================================================*/
extern "C" void QCALLTYPE GCInterface_WaitForPendingFinalizers()
{
QCALL_CONTRACT;
BEGIN_QCALL;
FinalizerThread::FinalizerThreadWait();
END_QCALL;
}
/*===============================GetMaxGeneration===============================
**Action: Returns the largest GC generation
**Returns: The largest GC Generation
**Arguments: None
**Exceptions: None
==============================================================================*/
FCIMPL0(int, GCInterface::GetMaxGeneration)
{
FCALL_CONTRACT;
return(INT32)GCHeapUtilities::GetGCHeap()->GetMaxGeneration();
}
FCIMPLEND
/*===============================GetAllocatedBytesForCurrentThread===============================
**Action: Computes the allocated bytes so far on the current thread
**Returns: The allocated bytes so far on the current thread
**Arguments: None
**Exceptions: None
==============================================================================*/
FCIMPL0(INT64, GCInterface::GetAllocatedBytesForCurrentThread)
{
FCALL_CONTRACT;
INT64 currentAllocated = 0;
Thread *pThread = GetThread();
gc_alloc_context* ac = pThread->GetAllocContext();
currentAllocated = ac->alloc_bytes + ac->alloc_bytes_uoh - (ac->alloc_limit - ac->alloc_ptr);
return currentAllocated;
}
FCIMPLEND
/*===============================AllocateNewArray===============================
**Action: Allocates a new array object. Allows passing extra flags
**Returns: The allocated array.
**Arguments: elementTypeHandle -> type of the element,
** length -> number of elements,
** zeroingOptional -> whether caller prefers to skip clearing the content of the array, if possible.
**Exceptions: IDS_EE_ARRAY_DIMENSIONS_EXCEEDED when size is too large. OOM if can't allocate.
==============================================================================*/
FCIMPL3(Object*, GCInterface::AllocateNewArray, void* arrayTypeHandle, INT32 length, INT32 flags)
{
CONTRACTL {
FCALL_CHECK;
} CONTRACTL_END;
OBJECTREF pRet = NULL;
TypeHandle arrayType = TypeHandle::FromPtr(arrayTypeHandle);
HELPER_METHOD_FRAME_BEGIN_RET_0();
//Only the following flags are used by GC.cs, so we'll just assert it here.
_ASSERTE((flags & ~(GC_ALLOC_ZEROING_OPTIONAL | GC_ALLOC_PINNED_OBJECT_HEAP)) == 0);
pRet = AllocateSzArray(arrayType, length, (GC_ALLOC_FLAGS)flags);
HELPER_METHOD_FRAME_END();
return OBJECTREFToObject(pRet);
}
FCIMPLEND
FCIMPL1(INT64, GCInterface::GetTotalAllocatedBytes, CLR_BOOL precise)
{
FCALL_CONTRACT;
if (!precise)
{
#ifdef TARGET_64BIT
uint64_t unused_bytes = Thread::dead_threads_non_alloc_bytes;
#else
// As it could be noticed we read 64bit values that may be concurrently updated.
// Such reads are not guaranteed to be atomic on 32bit so extra care should be taken.
uint64_t unused_bytes = InterlockedCompareExchange64((LONG64*)& Thread::dead_threads_non_alloc_bytes, 0, 0);
#endif
uint64_t allocated_bytes = GCHeapUtilities::GetGCHeap()->GetTotalAllocatedBytes() - unused_bytes;
// highest reported allocated_bytes. We do not want to report a value less than that even if unused_bytes has increased.
static uint64_t high_watermark;
uint64_t current_high = high_watermark;
while (allocated_bytes > current_high)