forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomcallablewrapper.cpp
More file actions
5018 lines (4200 loc) · 165 KB
/
comcallablewrapper.cpp
File metadata and controls
5018 lines (4200 loc) · 165 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.
//--------------------------------------------------------------------------
// ComCallablewrapper.cpp
//
// Implementation for various Wrapper classes
//
// COMWrapper : COM callable wrappers for CLR interfaces
//
//--------------------------------------------------------------------------
#include "common.h"
#include "clrtypes.h"
#include "comcallablewrapper.h"
#include "object.h"
#include "field.h"
#include "method.hpp"
#include "class.h"
#include "runtimecallablewrapper.h"
#include "olevariant.h"
#include "cachelinealloc.h"
#include "threads.h"
#include "ceemain.h"
#include "excep.h"
#include "stublink.h"
#include "cgensys.h"
#include "comtoclrcall.h"
#include "clrtocomcall.h"
#include "comutilnative.h"
#include "eeconfig.h"
#include "interoputil.h"
#include "dispex.h"
#include "guidfromname.h"
#include "comconnectionpoints.h"
#include <objsafe.h> // IID_IObjctSafe
#include "virtualcallstub.h"
#include "contractimpl.h"
#include "caparser.h"
#include "appdomain.inl"
#include "typestring.h"
// The enum that describes the value of the IDispatchImplAttribute custom attribute.
enum IDispatchImplType
{
SystemDefinedImpl = 0,
InternalImpl = 1,
CompatibleImpl = 2
};
// The enum that describe the value of System.Runtime.InteropServices.CustomQueryInterfaceResult
// It is the return value of the method System.Runtime.InteropServices.ICustomQueryInterface.GetInterface
enum CustomQueryInterfaceResult
{
Handled = 0,
NotHandled = 1,
Failed = 2
};
typedef CQuickArray<MethodTable*> CQuickEEClassPtrs;
// Startup and shutdown lock
CrstStatic g_CreateWrapperTemplateCrst;
// This is the prestub that is used for Com calls entering COM+
extern "C" VOID ComCallPreStub();
class NewCCWHolderBase : public HolderBase<ComCallWrapper *>
{
protected:
NewCCWHolderBase(ComCallWrapper *pValue)
: HolderBase<ComCallWrapper *>(pValue)
{
}
// BaseHolder only initialize BASE with one parameter, so I had to
// use a separate function to set the cache which will be used in the release
void SetCache(ComCallWrapperCache *pCache)
{
m_pCache = pCache;
}
void DoAcquire()
{
// Do nothing
}
void DoRelease()
{
this->m_value->FreeWrapper(m_pCache);
}
private :
ComCallWrapperCache *m_pCache;
};
typedef ComCallWrapper *ComCallWrapperPtr;
// This is used to hold a newly created CCW. It will release the CCW (and linked wrappers)
// upon exit, if SuppressRelease() is not called. It doesn't try to release the SimpleComCallWrapper
// or destroy the handle
// I need to use BaseHolder instead of BaseWrapper because BaseHolder allows me to use a class as BASE
//
class NewCCWHolder : public BaseHolder<ComCallWrapperPtr, NewCCWHolderBase>
{
public :
NewCCWHolder(ComCallWrapperCache *pCache)
{
SetCache(pCache);
}
ComCallWrapperPtr& operator=(ComCallWrapperPtr p)
{
Assign(p);
return m_value;
}
FORCEINLINE const ComCallWrapperPtr &operator->()
{
return this->m_value;
}
operator ComCallWrapperPtr()
{
return m_value;
}
};
// Calls Destruct on ComCallMethodDesc's in an array - used as backout code when laying out ComMethodTable.
void DestructComCallMethodDescs(ArrayList *pDescArray)
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
}
CONTRACTL_END;
ArrayList::Iterator i = pDescArray->Iterate();
while (i.Next())
{
ComCallMethodDesc *pCMD = (ComCallMethodDesc *)i.GetElement();
pCMD->Destruct();
}
}
typedef Wrapper<ArrayList *, DoNothing<ArrayList *>, DestructComCallMethodDescs> ComCallMethodDescArrayHolder;
// Forward declarations
static bool GetComIPFromCCW_HandleCustomQI(ComCallWrapper *pWrap, REFIID riid, MethodTable * pIntfMT, IUnknown **ppUnkOut);
//--------------------------------------------------------------------------
// IsDuplicateClassItfMD(MethodDesc *pMD, unsigned int ix)
// Determines if the specified method desc is a duplicate.
// Note that this method should only be called to determine duplicates on
// the class interface.
//--------------------------------------------------------------------------
bool IsDuplicateClassItfMD(MethodDesc *pMD, unsigned int ix)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(CheckPointer(pMD));
}
CONTRACTL_END;
if (!pMD->IsDuplicate())
return false;
if (pMD->GetSlot() == ix)
return false;
return true;
}
//--------------------------------------------------------------------------
// IsDuplicateClassItfMD(MethodDesc *pMD, unsigned int ix)
// Determines if the specified method desc is a duplicate.
// Note that this method should only be called to determine duplicates on
// the class interface.
//--------------------------------------------------------------------------
bool IsDuplicateClassItfMD(InteropMethodTableSlotData *pInteropMD, unsigned int ix)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(CheckPointer(pInteropMD));
}
CONTRACTL_END;
if (!pInteropMD->IsDuplicate())
return false;
if (pInteropMD->GetSlot() == ix)
return false;
return true;
}
bool IsOverloadedComVisibleMember(MethodDesc *pMD, MethodDesc *pParentMD)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(CheckPointer(pMD));
PRECONDITION(CheckPointer(pParentMD));
}
CONTRACTL_END;
// Array methods should never be exposed to COM.
if (pMD->IsArray())
return FALSE;
// If this is the same MethodDesc, then it is not an overload at all
if (pMD == pParentMD)
return FALSE;
// If the new member is not visible from COM then it isn't an overloaded public member.
if (!IsMethodVisibleFromCom(pMD))
return FALSE;
// If the old member is visible from COM then the new one is not a public overload.
if (IsMethodVisibleFromCom(pParentMD))
return FALSE;
// The new member is a COM visible overload of a non COM visible member.
return TRUE;
}
bool IsNewComVisibleMember(MethodDesc *pMD)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(CheckPointer(pMD));
}
CONTRACTL_END;
// Array methods should never be exposed to COM.
if (pMD->IsArray())
return FALSE;
// Check to see if the member is visible from COM.
return IsMethodVisibleFromCom(pMD) ? true : false;
}
bool IsStrictlyUnboxed(MethodDesc *pMD)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(CheckPointer(pMD));
}
CONTRACTL_END;
MethodTable *pMT = pMD->GetMethodTable();
MethodTable::MethodIterator it(pMT);
for (; it.IsValid(); it.Next()) {
MethodDesc *pCurrMD = it.GetMethodDesc();
if (pCurrMD->GetMemberDef() == pMD->GetMemberDef())
return false;
}
return true;
}
void FillInComVtableSlot(SLOT* pComVtable, // must point to the first slot after the "extra slots" (e.g. IUnknown/IDispatch slots)
UINT uComSlot, // must be relative to pComVtable
ComCallMethodDesc* pMD)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(CheckPointer(pComVtable));
PRECONDITION(CheckPointer(pMD));
}
CONTRACTL_END;
pComVtable[uComSlot] = (SLOT)(((BYTE*)pMD - COMMETHOD_CALL_PRESTUB_SIZE)ARM_ONLY(+THUMB_CODE));
}
ComCallMethodDesc* ComMethodTable::ComCallMethodDescFromSlot(unsigned i)
{
CONTRACT(ComCallMethodDesc*)
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACT_END;
ComCallMethodDesc* pCMD = NULL;
SLOT* rgVtable = (SLOT*)((ComMethodTable *)this+1);
// NOTE: make sure to keep this in sync with FillInComVtableSlot
pCMD = (ComCallMethodDesc*)(((BYTE *)rgVtable[i]) + COMMETHOD_CALL_PRESTUB_SIZE ARM_ONLY(-THUMB_CODE));
RETURN pCMD;
}
//--------------------------------------------------------------------------
// Determines if the Compatible IDispatch implementation is required for
// the specified class.
//--------------------------------------------------------------------------
bool IsOleAutDispImplRequiredForClass(MethodTable *pClass)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(CheckPointer(pClass));
}
CONTRACTL_END;
HRESULT hr;
const BYTE * pVal;
ULONG cbVal;
Assembly * pAssembly = pClass->GetAssembly();
IDispatchImplType DispImplType = SystemDefinedImpl;
// First check for the IDispatchImplType custom attribute first.
hr = pClass->GetCustomAttribute(WellKnownAttribute::IDispatchImpl, (const void**)&pVal, &cbVal);
if (hr == S_OK)
{
CustomAttributeParser cap(pVal, cbVal);
IfFailThrow(cap.SkipProlog());
UINT8 u1;
IfFailThrow(cap.GetU1(&u1));
DispImplType = (IDispatchImplType)u1;
if ((DispImplType > 2) || (DispImplType < 0))
DispImplType = SystemDefinedImpl;
}
// If the custom attribute was set to something other than system defined then we will use that.
if (DispImplType != SystemDefinedImpl)
return (bool) (DispImplType == CompatibleImpl);
// Check to see if the assembly has the IDispatchImplType attribute set.
hr = pAssembly->GetCustomAttribute(pAssembly->GetManifestToken(), WellKnownAttribute::IDispatchImpl, (const void**)&pVal, &cbVal);
if (hr == S_OK)
{
CustomAttributeParser cap(pVal, cbVal);
IfFailThrow(cap.SkipProlog());
UINT8 u1;
IfFailThrow(cap.GetU1(&u1));
DispImplType = (IDispatchImplType)u1;
if ((DispImplType > 2) || (DispImplType < 0))
DispImplType = SystemDefinedImpl;
}
// If the custom attribute was set to something other than system defined then we will use that.
if (DispImplType != SystemDefinedImpl)
return (bool) (DispImplType == CompatibleImpl);
// Removed registry key check per reg cleanup bug 45978
// Effect: Will return false so code cleanup
return false;
}
//--------------------------------------------------------------------------
// This routine is called anytime a com method is invoked for the first time.
// It is responsible for generating the real stub.
//
// This function's only caller is the ComPreStub.
//
// For the duration of the prestub, the current Frame on the stack
// will be a PrestubMethodFrame (which derives from FramedMethodFrame.)
// Hence, things such as exceptions and gc will work normally.
//
// On rare occasions, the ComPrestub may get called twice because two
// threads try to call the same method simultaneously.
//--------------------------------------------------------------------------
extern "C" PCODE ComPreStubWorker(ComPrestubMethodFrame *pPFrame, UINT64 *pErrorReturn)
{
CONTRACT (PCODE)
{
NOTHROW;
GC_TRIGGERS;
MODE_ANY;
ENTRY_POINT;
PRECONDITION(CheckPointer(pPFrame));
PRECONDITION(CheckPointer(pErrorReturn));
}
CONTRACT_END;
HRESULT hr = S_OK;
PCODE retAddr = NULL;
BEGIN_ENTRYPOINT_VOIDRET;
PCODE pStub = NULL;
BOOL fNonTransientExceptionThrown = FALSE;
ComCallMethodDesc *pCMD = pPFrame->GetComCallMethodDesc();
IUnknown *pUnk = *(IUnknown **)pPFrame->GetPointerToArguments();
OBJECTREF pThrowable = NULL;
Thread* pThread = SetupThreadNoThrow();
if (pThread == NULL)
{
hr = E_OUTOFMEMORY;
}
else
{
if (pThread->PreemptiveGCDisabled())
{
EEPOLICY_HANDLE_FATAL_ERROR_WITH_MESSAGE(
COR_E_EXECUTIONENGINE,
W("Invalid Program: attempted to call a COM method from managed code."));
}
// Transition to cooperative GC mode before we start setting up the stub.
GCX_COOP();
// The PreStub allocates memory for the frame, but doesn't link it
// into the chain or fully initialize it. Do so now.
pPFrame->Init();
pPFrame->Push();
ComCallWrapper *pWrap = NULL;
GCPROTECT_BEGIN(pThrowable)
{
// We need a try/catch around the code to enter the domain since entering
// an AppDomain can throw an exception.
EX_TRY
{
// check for invalid wrappers in the debug build
// in the retail all bets are off
pWrap = ComCallWrapper::GetWrapperFromIP(pUnk);
_ASSERTE(pWrap->IsWrapperActive() || pWrap->IsAggregated());
// Make sure we're not trying to call on the class interface of a class with ComVisible(false) members
// in its hierarchy.
if ((pCMD->IsFieldCall()) || (NULL == pCMD->GetInterfaceMethodDesc() && !pCMD->GetMethodDesc()->IsInterface()))
{
// If we have a fieldcall or a null interface MD, we could be dealing with the IClassX interface.
ComMethodTable* pComMT = ComMethodTable::ComMethodTableFromIP(pUnk);
pComMT->CheckParentComVisibility(FALSE);
}
{
OBJECTREF pADThrowable = NULL;
BOOL fExceptionThrown = FALSE;
GCPROTECT_BEGIN(pADThrowable);
{
if (pCMD->IsMethodCall())
{
// We need to ensure all valuetypes are loaded in
// the target domain so that GC can happen later
EX_TRY
{
MethodDesc* pTargetMD = pCMD->GetMethodDesc();
MetaSig::EnsureSigValueTypesLoaded(pTargetMD);
}
EX_CATCH
{
pADThrowable = GET_THROWABLE();
}
EX_END_CATCH(RethrowTerminalExceptions);
}
if (pADThrowable != NULL)
{
// Transform the exception into an HRESULT. This also sets up
// an IErrorInfo on the current thread for the exception.
hr = SetupErrorInfo(pADThrowable);
pADThrowable = NULL;
fExceptionThrown = TRUE;
}
}
GCPROTECT_END();
if(!fExceptionThrown)
{
GCPROTECT_BEGIN(pADThrowable);
{
// We need a try/catch around the call to the worker since we need
// to transform any exceptions into HRESULTs. We want to do this
// inside the AppDomain of the CCW.
EX_TRY
{
GCX_PREEMP();
pStub = ComCall::GetComCallMethodStub(pCMD);
}
EX_CATCH
{
fNonTransientExceptionThrown = !GET_EXCEPTION()->IsTransient();
pADThrowable = GET_THROWABLE();
}
EX_END_CATCH(RethrowTerminalExceptions);
if (pADThrowable != NULL)
{
// Transform the exception into an HRESULT. This also sets up
// an IErrorInfo on the current thread for the exception.
hr = SetupErrorInfo(pADThrowable);
pADThrowable = NULL;
}
}
GCPROTECT_END();
}
}
}
EX_CATCH
{
pThrowable = GET_THROWABLE();
// If an exception was thrown while transitionning back to the original
// AppDomain then can't use the stub and must report an error.
pStub = NULL;
}
EX_END_CATCH(SwallowAllExceptions);
if (pThrowable != NULL)
{
// Transform the exception into an HRESULT. This also sets up
// an IErrorInfo on the current thread for the exception.
hr = SetupErrorInfo(pThrowable);
pThrowable = NULL;
}
}
GCPROTECT_END();
// Unlink the PrestubMethodFrame.
pPFrame->Pop();
if (pStub)
{
// Now, replace the prestub with the new stub.
static_assert((COMMETHOD_CALL_PRESTUB_SIZE - COMMETHOD_CALL_PRESTUB_ADDRESS_OFFSET) % DATA_ALIGNMENT == 0,
"The call target in COM prestub must be aligned so we can guarantee atomicity of updates");
UINT_PTR* ppofs = (UINT_PTR*) (((BYTE*)pCMD) - COMMETHOD_CALL_PRESTUB_SIZE + COMMETHOD_CALL_PRESTUB_ADDRESS_OFFSET);
ExecutableWriterHolder<UINT_PTR> ppofsWriterHolder(ppofs, sizeof(UINT_PTR));
#ifdef TARGET_X86
*ppofsWriterHolder.GetRW() = ((UINT_PTR)pStub - (size_t)pCMD);
#else
*ppofsWriterHolder.GetRW() = ((UINT_PTR)pStub);
#endif
ClrFlushInstructionCache(ppofs, sizeof(UINT_PTR), /* hasCodeExecutedBefore */ true);
// Return the address of the prepad. The prepad will regenerate the hidden parameter and due
// to the update above will execute the new stub code the second time around.
retAddr = (PCODE)(((BYTE*)pCMD - COMMETHOD_CALL_PRESTUB_SIZE)ARM_ONLY(+THUMB_CODE));
goto Exit;
}
}
// We failed to set up the stub so we need to report an error to the caller.
//
// IMPORTANT: No floating point operations can occur after this point!
//
*pErrorReturn = 0;
if (pCMD->IsNativeHResultRetVal())
*pErrorReturn = hr;
else if (pCMD->IsNativeBoolRetVal())
*pErrorReturn = 0;
else if (pCMD->IsNativeR4RetVal())
setFPReturn(4, CLR_NAN_32);
else if (pCMD->IsNativeR8RetVal())
setFPReturn(8, CLR_NAN_64);
else
_ASSERTE(pCMD->IsNativeVoidRetVal());
#ifdef TARGET_X86
// Number of bytes to pop is upper half of the return value on x86
*(((INT32 *)pErrorReturn) + 1) = pCMD->GetNumStackBytes();
#endif
retAddr = NULL;
Exit:
END_ENTRYPOINT_VOIDRET;
RETURN retAddr;
}
FORCEINLINE void CPListRelease(CQuickArray<ConnectionPoint*>* value)
{
WRAPPER_NO_CONTRACT;
if (value)
{
// Delete all the connection points.
for (UINT i = 0; i < value->Size(); i++)
delete (*value)[i];
// Delete the list itself.
delete value;
}
}
typedef CQuickArray<ConnectionPoint*> CPArray;
FORCEINLINE void CPListDoNothing(CPArray*)
{
LIMITED_METHOD_CONTRACT;
}
class CPListHolder : public Wrapper<CPArray*, CPListDoNothing, CPListRelease, NULL>
{
public:
CPListHolder(CPArray* p = NULL)
: Wrapper<CPArray*, CPListDoNothing, CPListRelease, NULL>(p)
{
WRAPPER_NO_CONTRACT;
}
FORCEINLINE void operator=(CPArray* p)
{
WRAPPER_NO_CONTRACT;
Wrapper<CPArray*, CPListDoNothing, CPListRelease, NULL>::operator=(p);
}
};
NOINLINE void LogCCWRefCountChange_BREAKPOINT(ComCallWrapper *pCCW)
{
LIMITED_METHOD_CONTRACT;
// Empty function to put breakpoint on when debugging CCW ref-counting issues.
// At this point *(pCCW->m_ppThis) is the managed object wrapped by the CCW.
// Bogus code so the function is not optimized away.
if (pCCW == NULL)
DebugBreak();
}
void SimpleComCallWrapper::BuildRefCountLogMessage(LPCSTR szOperation, StackSString &ssMessage, ULONG dwEstimatedRefCount)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
// Don't worry about domain unloading in CoreCLR
LPCUTF8 pszClassName;
LPCUTF8 pszNamespace;
if (SUCCEEDED(m_pMT->GetMDImport()->GetNameOfTypeDef(m_pMT->GetCl(), &pszClassName, &pszNamespace)))
{
OBJECTHANDLE handle = GetMainWrapper()->GetObjectHandle();
_UNCHECKED_OBJECTREF obj = NULL;
// Force retrieving the handle without using OBJECTREF and under cooperative mode
// We only need the value in ETW events and it doesn't matter if it is super accurate
if (handle != NULL)
obj = *((_UNCHECKED_OBJECTREF *)(handle));
if (ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PRIVATE_PROVIDER_DOTNET_Context, CCWRefCountChange))
{
EX_TRY
{
SString className;
className.SetUTF8(pszClassName);
SString nameSpace;
nameSpace.SetUTF8(pszNamespace);
SString operation;
nameSpace.SetUTF8(szOperation);
FireEtwCCWRefCountChange(
handle,
(Object *)obj,
this,
dwEstimatedRefCount,
NULL, // domain value is not interesting in CoreCLR
className.GetUnicode(), nameSpace.GetUnicode(), operation.GetUnicode(), GetClrInstanceId());
}
EX_CATCH
{ }
EX_END_CATCH(SwallowAllExceptions);
}
if (g_pConfig->ShouldLogCCWRefCountChange(pszClassName, pszNamespace))
{
EX_TRY
{
ssMessage.Printf("LogCCWRefCountChange[%s]: '%s.%s', Object=poi(%p)",
szOperation,
pszNamespace,
pszClassName,
handle);
}
EX_CATCH
{ }
EX_END_CATCH(SwallowAllExceptions);
}
}
}
// static
void SimpleComCallWrapper::LogRefCount(ComCallWrapper *pWrap, StackSString &ssMessage, ULONG dwRefCountToLog)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
if (!ssMessage.IsEmpty())
{
EX_TRY
{
ssMessage.AppendPrintf(", RefCount=%u\n", dwRefCountToLog);
OutputDebugStringUtf8(ssMessage.GetUTF8());
}
EX_CATCH
{ }
EX_END_CATCH(SwallowAllExceptions);
LogCCWRefCountChange_BREAKPOINT(pWrap);
}
}
LONGLONG SimpleComCallWrapper::ReleaseImplWithLogging(LONGLONG * pRefCount)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
LONGLONG newRefCount;
StackSString ssMessage;
ComCallWrapper *pWrap = GetMainWrapper();
BuildRefCountLogMessage("Release", ssMessage, GET_EXT_COM_REF(READ_REF(*pRefCount)-1));
// Decrement the ref count
newRefCount = ::InterlockedDecrement64(pRefCount);
LogRefCount(pWrap, ssMessage, GET_EXT_COM_REF(newRefCount));
return newRefCount;
}
//--------------------------------------------------------------------------
// simple ComCallWrapper for all simple std interfaces, that are not used very often
// like IProvideClassInfo, ISupportsErrorInfo etc.
//--------------------------------------------------------------------------
SimpleComCallWrapper::SimpleComCallWrapper()
{
WRAPPER_NO_CONTRACT;
memset(this, 0, sizeof(SimpleComCallWrapper));
}
//--------------------------------------------------------------------------
// VOID SimpleComCallWrapper::Cleanup()
//--------------------------------------------------------------------------
VOID SimpleComCallWrapper::Cleanup()
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
// in case the caller stills holds on to the IP
for (int i = 0; i < enum_LastStdVtable; i++)
{
m_rgpVtable[i] = 0;
}
m_pWrap = NULL;
m_pMT = NULL;
if (m_pCPList)
{
for (UINT i = 0; i < m_pCPList->Size(); i++)
delete (*m_pCPList)[i];
delete m_pCPList;
m_pCPList = NULL;
}
if (m_pTemplate)
{
m_pTemplate->Release();
m_pTemplate = NULL;
}
if (m_pAuxData)
{
delete m_pAuxData;
m_pAuxData = NULL;
}
}
VOID SimpleComCallWrapper::Neuter()
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(CheckPointer(m_pSyncBlock));
PRECONDITION(!IsNeutered());
}
CONTRACTL_END;
STRESS_LOG1 (LF_INTEROP, LL_INFO100, "Neutering CCW 0x%p\n", this->GetMainWrapper());
// Disconnect the object from the CCW
// Starting now, if this object gets passed out
// to unmanaged code, it will create a new CCW tied
// to the domain it was passed out from.
InteropSyncBlockInfo* pInteropInfo = m_pSyncBlock->GetInteropInfoNoCreate();
if (pInteropInfo)
pInteropInfo->SetCCW(NULL);
// NULL the syncblock entry - we can't hang onto this anymore as the syncblock will be killed asynchronously to us.
ResetSyncBlock();
// Disconnect the CCW from the object
// Calls made on this CCW will no longer succeed.
// The CCW has been neutered.
// do this for each of the CCWs
m_pWrap->Neuter();
StackSString ssMessage;
ComCallWrapper *pWrap = m_pWrap;
if (g_pConfig->LogCCWRefCountChangeEnabled())
{
BuildRefCountLogMessage("Neuter", ssMessage, GET_EXT_COM_REF(READ_REF(m_llRefCount) | CLEANUP_SENTINEL));
}
// Set the neutered bit on the ref-count.
LONGLONG *pRefCount = &m_llRefCount;
LONGLONG oldRefCount = *pRefCount;
LONGLONG newRefCount = oldRefCount | CLEANUP_SENTINEL;
while (InterlockedCompareExchange64((LONGLONG*)pRefCount, newRefCount, oldRefCount) != oldRefCount)
{
oldRefCount = *pRefCount;
newRefCount = oldRefCount | CLEANUP_SENTINEL;
}
// IMPORTANT: Do not touch instance fields or any other data associated with the CCW beyond this
// point unless newRefCount equals CLEANUP_SENTINEL (it's the only case when we know that Release
// could not swoop in and destroy our data structures).
if (g_pConfig->LogCCWRefCountChangeEnabled())
{
LogRefCount(pWrap, ssMessage, GET_EXT_COM_REF(newRefCount));
}
// If we hit the sentinel value, it's our responsibility to clean up.
if (newRefCount == CLEANUP_SENTINEL)
m_pWrap->Cleanup();
}
//--------------------------------------------------------------------------
//destructor
//--------------------------------------------------------------------------
SimpleComCallWrapper::~SimpleComCallWrapper()
{
WRAPPER_NO_CONTRACT;
Cleanup();
}
//--------------------------------------------------------------------------
// Init, with the MethodTable, pointer to the vtable of the interface
// and the main ComCallWrapper if the interface needs it
//--------------------------------------------------------------------------
void SimpleComCallWrapper::InitNew(OBJECTREF oref, ComCallWrapperCache *pWrapperCache, ComCallWrapper* pWrap,
SyncBlock *pSyncBlock,
ComCallWrapperTemplate* pTemplate)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
PRECONDITION(oref != NULL);
PRECONDITION(CheckPointer(pWrap));
PRECONDITION(CheckPointer(pWrapperCache, NULL_OK));
PRECONDITION(CheckPointer(pSyncBlock, NULL_OK));
PRECONDITION(CheckPointer(pTemplate));
PRECONDITION(m_pSyncBlock == NULL);
PRECONDITION(CheckPointer(g_pExceptionClass));
}
CONTRACTL_END;
MethodTable* pMT = pTemplate->GetClassType().GetMethodTable();
PREFIX_ASSUME(pMT != NULL);
m_pMT = pMT;
m_pWrap = pWrap;
m_pWrapperCache = pWrapperCache;
m_pTemplate = pTemplate;
m_pTemplate->AddRef();
m_pOuter = NULL;
m_pSyncBlock = pSyncBlock;
if (pMT->IsComObjectType())
m_flags |= enum_IsExtendsCom;
#ifdef _DEBUG
for (int i = 0; i < enum_LastStdVtable; i++)
_ASSERTE(GetStdInterfaceKind((IUnknown*)(&g_rgStdVtables[i])) == i);
#endif // _DEBUG
for (int i = 0; i < enum_LastStdVtable; i++)
m_rgpVtable[i] = g_rgStdVtables[i];
// If the managed object extends a COM base class then we need to set IProvideClassInfo
// to NULL until we determine if we need to use the IProvideClassInfo of the base class
// or the one of the managed class.
if (IsExtendsCOMObject())
m_rgpVtable[enum_IProvideClassInfo] = NULL;
// IErrorInfo is valid only for exception classes
m_rgpVtable[enum_IErrorInfo] = NULL;
// IDispatchEx is valid only for classes that have IExpando capabilities - which is no longer supported.
m_rgpVtable[enum_IDispatchEx] = NULL;
}
//--------------------------------------------------------------------------
// ReInit,with the new sync block and the urt context
//--------------------------------------------------------------------------
void SimpleComCallWrapper::ReInit(SyncBlock* pSyncBlock)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(CheckPointer(pSyncBlock));
}
CONTRACTL_END;
m_pSyncBlock = pSyncBlock;
}
//--------------------------------------------------------------------------
// Returns TRUE if the ICustomQI implementation returns Handled or Failed for IID_IMarshal.
//--------------------------------------------------------------------------
BOOL SimpleComCallWrapper::CustomQIRespondsToIMarshal()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(GetComCallWrapperTemplate()->SupportsICustomQueryInterface());
}
CONTRACTL_END;
if ((m_flags & enum_CustomQIRespondsToIMarshal_Inited) == 0)
{
DWORD newFlags = enum_CustomQIRespondsToIMarshal_Inited;
SafeComHolder<IUnknown> pUnk;
if (GetComIPFromCCW_HandleCustomQI(GetMainWrapper(), IID_IMarshal, NULL, &pUnk))
{
newFlags |= enum_CustomQIRespondsToIMarshal;