-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathinteroplibinterface_comwrappers.cpp
2073 lines (1756 loc) · 65.7 KB
/
interoplibinterface_comwrappers.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.
#ifdef FEATURE_COMWRAPPERS
// Runtime headers
#include "common.h"
#include "simplerwlock.hpp"
#include "rcwrefcache.h"
#ifdef FEATURE_COMINTEROP_APARTMENT_SUPPORT
#include "olecontexthelpers.h"
#endif
#include "finalizerthread.h"
// Interop library header
#include <interoplibimports.h>
#include "interoplibinterface.h"
using CreateObjectFlags = InteropLib::Com::CreateObjectFlags;
using CreateComInterfaceFlags = InteropLib::Com::CreateComInterfaceFlags;
namespace
{
void* GetCurrentCtxCookieWrapper()
{
STATIC_CONTRACT_WRAPPER;
#ifdef FEATURE_COMINTEROP_APARTMENT_SUPPORT
return GetCurrentCtxCookie();
#else
return NULL;
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
}
// This class is used to track the external object within the runtime.
struct ExternalObjectContext : public InteropLibInterface::ExternalObjectContextBase
{
static const DWORD InvalidSyncBlockIndex;
void* ThreadContext;
INT64 WrapperId;
enum
{
Flags_None = 0,
// The EOC has been collected and is no longer visible from managed code.
Flags_Collected = 1,
Flags_ReferenceTracker = 2,
Flags_InCache = 4,
// The EOC is "detached" and no longer used to map between identity and a managed object.
// This will only be set if the EOC was inserted into the cache.
Flags_Detached = 8,
// This EOC is an aggregated instance
Flags_Aggregated = 16
};
DWORD Flags;
static void Construct(
_Out_ ExternalObjectContext* cxt,
_In_ IUnknown* identity,
_In_opt_ void* threadContext,
_In_ DWORD syncBlockIndex,
_In_ INT64 wrapperId,
_In_ DWORD flags)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(cxt != NULL);
PRECONDITION(threadContext != NULL);
PRECONDITION(syncBlockIndex != InvalidSyncBlockIndex);
}
CONTRACTL_END;
cxt->Identity = (void*)identity;
cxt->ThreadContext = threadContext;
cxt->SyncBlockIndex = syncBlockIndex;
cxt->WrapperId = wrapperId;
cxt->Flags = flags;
}
bool IsSet(_In_ DWORD f) const
{
return ((Flags & f) == f);
}
bool IsActive() const
{
return !IsSet(Flags_Collected)
&& (SyncBlockIndex != InvalidSyncBlockIndex);
}
void MarkCollected()
{
_ASSERTE(GCHeapUtilities::IsGCInProgress());
SyncBlockIndex = InvalidSyncBlockIndex;
Flags |= Flags_Collected;
}
void MarkDetached()
{
_ASSERTE(GCHeapUtilities::IsGCInProgress());
Flags |= Flags_Detached;
}
void MarkNotInCache()
{
::InterlockedAnd((LONG*)&Flags, (~Flags_InCache));
}
OBJECTREF GetObjectRef()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
_ASSERTE(IsActive());
return ObjectToOBJECTREF(g_pSyncTable[SyncBlockIndex].m_Object);
}
struct Key
{
public:
Key(void* identity, INT64 wrapperId)
: _identity { identity }
, _wrapperId { wrapperId }
{
_ASSERTE(identity != NULL);
_ASSERTE(wrapperId != ComWrappersNative::InvalidWrapperId);
}
DWORD Hash() const
{
DWORD hash = (_wrapperId >> 32) ^ (_wrapperId & 0xFFFFFFFF);
#if POINTER_BITS == 32
return hash ^ (DWORD)_identity;
#else
INT64 identityInt64 = (INT64)_identity;
return hash ^ (identityInt64 >> 32) ^ (identityInt64 & 0xFFFFFFFF);
#endif
}
bool operator==(const Key & rhs) const { return _identity == rhs._identity && _wrapperId == rhs._wrapperId; }
private:
void* _identity;
INT64 _wrapperId;
};
Key GetKey() const
{
return Key(Identity, WrapperId);
}
};
const DWORD ExternalObjectContext::InvalidSyncBlockIndex = 0; // See syncblk.h
static_assert((sizeof(ExternalObjectContext) % sizeof(void*)) == 0, "Keep context pointer size aligned");
// Holder for a External Wrapper Result
struct ExternalWrapperResultHolder
{
InteropLib::Com::ExternalWrapperResult Result;
ExternalWrapperResultHolder()
: Result{}
{ }
~ExternalWrapperResultHolder()
{
if (Result.Context != NULL)
{
GCX_PREEMP();
// We also request collection notification since this holder is presently
// only used for new activation of wrappers therefore the notification won't occur
// at the typical time of before finalization.
InteropLib::Com::DestroyWrapperForExternal(Result.Context, /* notifyIsBeingCollected */ true);
}
}
InteropLib::Com::ExternalWrapperResult* operator&()
{
return &Result;
}
ExternalObjectContext* GetContext()
{
return static_cast<ExternalObjectContext*>(Result.Context);
}
ExternalObjectContext* DetachContext()
{
ExternalObjectContext* t = GetContext();
Result.Context = NULL;
return t;
}
};
using ExtObjCxtRefCache = RCWRefCache;
class ExtObjCxtCache
{
static Volatile<ExtObjCxtCache*> g_Instance;
public: // static
static ExtObjCxtCache* GetInstanceNoThrow() noexcept
{
CONTRACT(ExtObjCxtCache*)
{
NOTHROW;
GC_NOTRIGGER;
POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
}
CONTRACT_END;
RETURN g_Instance;
}
static ExtObjCxtCache* GetInstance()
{
CONTRACT(ExtObjCxtCache*)
{
THROWS;
GC_NOTRIGGER;
POSTCONDITION(RETVAL != NULL);
}
CONTRACT_END;
if (g_Instance.Load() == NULL)
{
ExtObjCxtCache* instMaybe = new ExtObjCxtCache();
// Attempt to set the global instance.
if (NULL != InterlockedCompareExchangeT(&g_Instance, instMaybe, NULL))
delete instMaybe;
}
RETURN g_Instance;
}
public: // Inner class definitions
class Traits : public DefaultSHashTraits<ExternalObjectContext *>
{
public:
using key_t = ExternalObjectContext::Key;
static const key_t GetKey(_In_ element_t e) { LIMITED_METHOD_CONTRACT; return e->GetKey(); }
static count_t Hash(_In_ key_t key) { LIMITED_METHOD_CONTRACT; return (count_t)key.Hash(); }
static bool Equals(_In_ key_t lhs, _In_ key_t rhs) { LIMITED_METHOD_CONTRACT; return lhs == rhs; }
};
// Alias some useful types
using Element = SHash<Traits>::element_t;
using Iterator = SHash<Traits>::Iterator;
class ReaderLock final
{
SimpleReadLockHolder _lock;
public:
ReaderLock(_In_ ExtObjCxtCache* cache)
: _lock{ &cache->_lock }
{ }
~ReaderLock() = default;
};
class WriterLock final
{
SimpleWriteLockHolder _lock;
public:
WriterLock(_In_ ExtObjCxtCache* cache)
: _lock{ &cache->_lock }
{ }
~WriterLock() = default;
};
private:
friend struct InteropLibImports::RuntimeCallContext;
SHash<Traits> _hashMap;
SimpleRWLock _lock;
ExtObjCxtRefCache* _refCache;
ExtObjCxtCache()
: _lock(COOPERATIVE, LOCK_TYPE_DEFAULT)
, _refCache(GetAppDomain()->GetRCWRefCache())
{ }
~ExtObjCxtCache() = default;
public:
#if _DEBUG
bool IsLockHeld()
{
WRAPPER_NO_CONTRACT;
return (_lock.LockTaken() != FALSE);
}
#endif // _DEBUG
// Get the associated reference cache with this external object cache.
ExtObjCxtRefCache* GetRefCache()
{
WRAPPER_NO_CONTRACT;
return _refCache;
}
// Create a managed IEnumerable instance for this collection.
// The collection should respect the supplied arguments.
// withFlags - If Flag_None, then ignore. Otherwise objects must have these flags.
// threadContext - The object must be associated with the supplied thread context.
OBJECTREF CreateManagedEnumerable(_In_ DWORD withFlags, _In_opt_ void* threadContext)
{
CONTRACT(OBJECTREF)
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(!IsLockHeld());
PRECONDITION(!(withFlags & ExternalObjectContext::Flags_Collected));
PRECONDITION(!(withFlags & ExternalObjectContext::Flags_Detached));
POSTCONDITION(RETVAL != NULL);
}
CONTRACT_END;
struct
{
PTRARRAYREF arrRefTmp;
PTRARRAYREF arrRef;
} gc;
gc.arrRefTmp = NULL;
gc.arrRef = NULL;
GCPROTECT_BEGIN(gc);
// Only add objects that are in the correct thread
// context, haven't been detached from the cache, and have
// the appropriate flags set.
// Define a macro predicate since it used in multiple places.
// If an instance is in the hashmap, it is active. This invariant
// holds because the GC is what marks and removes from the cache.
#define SELECT_OBJECT(XX) XX->ThreadContext == threadContext \
&& !XX->IsSet(ExternalObjectContext::Flags_Detached) \
&& (withFlags == ExternalObjectContext::Flags_None || XX->IsSet(withFlags))
// Determine the count of objects to return.
SIZE_T objCountMax = 0;
{
ReaderLock lock(this);
Iterator end = _hashMap.End();
for (Iterator curr = _hashMap.Begin(); curr != end; ++curr)
{
ExternalObjectContext* inst = *curr;
if (SELECT_OBJECT(inst))
{
objCountMax++;
}
}
}
// Allocate enumerable type to return.
gc.arrRef = (PTRARRAYREF)AllocateObjectArray((DWORD)objCountMax, g_pObjectClass);
CQuickArrayList<ExternalObjectContext*> localList;
// Iterate over the hashmap again while populating the above array
// using the same predicate as before and holding onto context instances.
SIZE_T objCount = 0;
if (0 < objCountMax)
{
ReaderLock lock(this);
Iterator end = _hashMap.End();
for (Iterator curr = _hashMap.Begin(); curr != end; ++curr)
{
ExternalObjectContext* inst = *curr;
if (SELECT_OBJECT(inst))
{
localList.Push(inst);
gc.arrRef->SetAt(objCount, inst->GetObjectRef());
objCount++;
STRESS_LOG1(LF_INTEROP, LL_INFO1000, "Add EOC to Enumerable: 0x%p\n", inst);
}
// There is a chance more objects were added to the hash while the
// lock was released during array allocation. Once we hit the computed max
// we stop to avoid looking longer than needed.
if (objCount == objCountMax)
break;
}
}
#undef SELECT_OBJECT
// During the allocation of the array to return, a GC could have
// occurred and objects detached from this cache. In order to avoid
// having null array elements we will allocate a new array.
// This subsequent allocation is okay because the array we are
// replacing extends all object lifetimes.
if (objCount < objCountMax)
{
gc.arrRefTmp = (PTRARRAYREF)AllocateObjectArray((DWORD)objCount, g_pObjectClass);
void* dest = gc.arrRefTmp->GetDataPtr();
void* src = gc.arrRef->GetDataPtr();
SIZE_T elementSize = gc.arrRef->GetComponentSize();
memmoveGCRefs(dest, src, objCount * elementSize);
gc.arrRef = gc.arrRefTmp;
}
// All objects are now referenced from the array so won't be collected
// at this point. This means we can safely iterate over the ExternalObjectContext
// instances.
{
// Separate the wrapper from the tracker runtime prior to
// passing them onto the caller. This call is okay to make
// even if the instance isn't from the tracker runtime.
// We switch to Preemptive mode since separating a wrapper
// requires us to call out to non-runtime code which could
// call back into the runtime and/or trigger a GC.
GCX_PREEMP();
for (SIZE_T i = 0; i < localList.Size(); i++)
{
ExternalObjectContext* inst = localList[i];
InteropLib::Com::SeparateWrapperFromTrackerRuntime(inst);
}
}
GCPROTECT_END();
RETURN gc.arrRef;
}
ExternalObjectContext* Find(_In_ const ExternalObjectContext::Key& key)
{
CONTRACT(ExternalObjectContext*)
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
PRECONDITION(IsLockHeld());
POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
}
CONTRACT_END;
// Forbid the GC from messing with the hash table.
GCX_FORBID();
RETURN _hashMap.Lookup(key);
}
ExternalObjectContext* Add(_In_ ExternalObjectContext* cxt)
{
CONTRACT(ExternalObjectContext*)
{
THROWS;
GC_NOTRIGGER;
MODE_COOPERATIVE;
PRECONDITION(IsLockHeld());
PRECONDITION(!Traits::IsNull(cxt) && !Traits::IsDeleted(cxt));
PRECONDITION(cxt->Identity != NULL);
PRECONDITION(Find(cxt->GetKey()) == NULL);
POSTCONDITION(RETVAL == cxt);
}
CONTRACT_END;
_hashMap.Add(cxt);
RETURN cxt;
}
ExternalObjectContext* FindOrAdd(_In_ const ExternalObjectContext::Key& key, _In_ ExternalObjectContext* newCxt)
{
CONTRACT(ExternalObjectContext*)
{
THROWS;
GC_NOTRIGGER;
MODE_COOPERATIVE;
PRECONDITION(IsLockHeld());
PRECONDITION(!Traits::IsNull(newCxt) && !Traits::IsDeleted(newCxt));
PRECONDITION(key == newCxt->GetKey());
POSTCONDITION(CheckPointer(RETVAL));
}
CONTRACT_END;
// Forbid the GC from messing with the hash table.
GCX_FORBID();
ExternalObjectContext* cxt = Find(key);
if (cxt == NULL)
cxt = Add(newCxt);
RETURN cxt;
}
void Remove(_In_ ExternalObjectContext* cxt)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(!Traits::IsNull(cxt) && !Traits::IsDeleted(cxt));
PRECONDITION(cxt->Identity != NULL);
// The GC thread doesn't have to take the lock
// since all other threads access in cooperative mode
PRECONDITION(
(IsLockHeld() && GetThread()->PreemptiveGCDisabled())
|| Debug_IsLockedViaThreadSuspension());
}
CONTRACTL_END;
_hashMap.Remove(cxt->GetKey());
}
void DetachNotPromotedEOCs()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(GCHeapUtilities::IsGCInProgress()); // GC is in progress and the runtime is suspended
}
CONTRACTL_END;
Iterator curr = _hashMap.Begin();
Iterator end = _hashMap.End();
ExternalObjectContext* cxt;
for (; curr != end; ++curr)
{
cxt = *curr;
if (!cxt->IsSet(ExternalObjectContext::Flags_Detached)
&& !GCHeapUtilities::GetGCHeap()->IsPromoted(OBJECTREFToObject(cxt->GetObjectRef())))
{
// Indicate the wrapper entry has been detached.
cxt->MarkDetached();
// Notify the wrapper it was not promoted and is being collected.
InteropLib::Com::NotifyWrapperForExternalIsBeingCollected(cxt);
}
}
}
};
// Global instance of the external object cache
Volatile<ExtObjCxtCache*> ExtObjCxtCache::g_Instance;
// Indicator for if a ComWrappers implementation is globally registered
INT64 g_marshallingGlobalInstanceId = ComWrappersNative::InvalidWrapperId;
INT64 g_trackerSupportGlobalInstanceId = ComWrappersNative::InvalidWrapperId;
// Defined handle types for the specific object uses.
const HandleType InstanceHandleType{ HNDTYPE_REFCOUNTED };
// Scenarios for ComWrappers usage.
// These values should match the managed definition in ComWrappers.
enum class ComWrappersScenario
{
Instance = 0,
TrackerSupportGlobalInstance = 1,
MarshallingGlobalInstance = 2,
};
void* CallComputeVTables(
_In_ ComWrappersScenario scenario,
_In_ OBJECTREF* implPROTECTED,
_In_ OBJECTREF* instancePROTECTED,
_In_ INT32 flags,
_Out_ DWORD* vtableCount)
{
CONTRACTL
{
THROWS;
MODE_COOPERATIVE;
PRECONDITION(implPROTECTED != NULL);
PRECONDITION(instancePROTECTED != NULL);
PRECONDITION(vtableCount != NULL);
}
CONTRACTL_END;
void* vtables = NULL;
PREPARE_NONVIRTUAL_CALLSITE(METHOD__COMWRAPPERS__COMPUTE_VTABLES);
DECLARE_ARGHOLDER_ARRAY(args, 5);
args[ARGNUM_0] = DWORD_TO_ARGHOLDER(scenario);
args[ARGNUM_1] = OBJECTREF_TO_ARGHOLDER(*implPROTECTED);
args[ARGNUM_2] = OBJECTREF_TO_ARGHOLDER(*instancePROTECTED);
args[ARGNUM_3] = DWORD_TO_ARGHOLDER(flags);
args[ARGNUM_4] = PTR_TO_ARGHOLDER(vtableCount);
CALL_MANAGED_METHOD(vtables, void*, args);
return vtables;
}
OBJECTREF CallCreateObject(
_In_ ComWrappersScenario scenario,
_In_ OBJECTREF* implPROTECTED,
_In_ IUnknown* externalComObject,
_In_ INT32 flags)
{
CONTRACTL
{
THROWS;
MODE_COOPERATIVE;
PRECONDITION(implPROTECTED != NULL);
PRECONDITION(externalComObject != NULL);
}
CONTRACTL_END;
OBJECTREF retObjRef;
PREPARE_NONVIRTUAL_CALLSITE(METHOD__COMWRAPPERS__CREATE_OBJECT);
DECLARE_ARGHOLDER_ARRAY(args, 4);
args[ARGNUM_0] = DWORD_TO_ARGHOLDER(scenario);
args[ARGNUM_1] = OBJECTREF_TO_ARGHOLDER(*implPROTECTED);
args[ARGNUM_2] = PTR_TO_ARGHOLDER(externalComObject);
args[ARGNUM_3] = DWORD_TO_ARGHOLDER(flags);
CALL_MANAGED_METHOD_RETREF(retObjRef, OBJECTREF, args);
return retObjRef;
}
void CallReleaseObjects(
_In_ OBJECTREF* implPROTECTED,
_In_ OBJECTREF* objsEnumPROTECTED)
{
CONTRACTL
{
THROWS;
MODE_COOPERATIVE;
PRECONDITION(implPROTECTED != NULL);
PRECONDITION(objsEnumPROTECTED != NULL);
}
CONTRACTL_END;
PREPARE_NONVIRTUAL_CALLSITE(METHOD__COMWRAPPERS__RELEASE_OBJECTS);
DECLARE_ARGHOLDER_ARRAY(args, 2);
args[ARGNUM_0] = OBJECTREF_TO_ARGHOLDER(*implPROTECTED);
args[ARGNUM_1] = OBJECTREF_TO_ARGHOLDER(*objsEnumPROTECTED);
CALL_MANAGED_METHOD_NORET(args);
}
int CallICustomQueryInterface(
_In_ OBJECTREF* implPROTECTED,
_In_ REFGUID iid,
_Outptr_result_maybenull_ void** ppObject)
{
CONTRACTL
{
THROWS;
MODE_COOPERATIVE;
PRECONDITION(implPROTECTED != NULL);
PRECONDITION(ppObject != NULL);
}
CONTRACTL_END;
int result;
PREPARE_NONVIRTUAL_CALLSITE(METHOD__COMWRAPPERS__CALL_ICUSTOMQUERYINTERFACE);
DECLARE_ARGHOLDER_ARRAY(args, 3);
args[ARGNUM_0] = OBJECTREF_TO_ARGHOLDER(*implPROTECTED);
args[ARGNUM_1] = PTR_TO_ARGHOLDER(&iid);
args[ARGNUM_2] = PTR_TO_ARGHOLDER(ppObject);
CALL_MANAGED_METHOD(result, int, args);
return result;
}
bool TryGetOrCreateComInterfaceForObjectInternal(
_In_opt_ OBJECTREF impl,
_In_ INT64 wrapperId,
_In_ OBJECTREF instance,
_In_ CreateComInterfaceFlags flags,
_In_ ComWrappersScenario scenario,
_Outptr_ void** wrapperRaw)
{
CONTRACT(bool)
{
THROWS;
MODE_COOPERATIVE;
PRECONDITION(instance != NULL);
PRECONDITION(wrapperRaw != NULL);
PRECONDITION((impl != NULL && scenario == ComWrappersScenario::Instance) || (impl == NULL && scenario != ComWrappersScenario::Instance));
PRECONDITION(wrapperId != ComWrappersNative::InvalidWrapperId);
}
CONTRACT_END;
HRESULT hr;
SafeComHolder<IUnknown> newWrapper;
void* wrapperRawMaybe = NULL;
struct
{
OBJECTREF implRef;
OBJECTREF instRef;
} gc;
gc.implRef = impl;
gc.instRef = instance;
GCPROTECT_BEGIN(gc);
// Check the object's SyncBlock for a managed object wrapper.
SyncBlock* syncBlock = gc.instRef->GetSyncBlock();
InteropSyncBlockInfo* interopInfo = syncBlock->GetInteropInfo();
_ASSERTE(syncBlock->IsPrecious());
// Query the associated InteropSyncBlockInfo for an existing managed object wrapper.
if (!interopInfo->TryGetManagedObjectComWrapper(wrapperId, &wrapperRawMaybe))
{
// Compute VTables for the new existing COM object using the supplied COM Wrappers implementation.
//
// N.B. Calling to compute the associated VTables is perhaps early since no lock
// is taken. However, a key assumption here is that the returned memory will be
// idempotent for the same object.
DWORD vtableCount;
void* vtables = CallComputeVTables(scenario, &gc.implRef, &gc.instRef, flags, &vtableCount);
// Re-query the associated InteropSyncBlockInfo for an existing managed object wrapper.
if (!interopInfo->TryGetManagedObjectComWrapper(wrapperId, &wrapperRawMaybe)
&& ((vtables != nullptr && vtableCount > 0) || (vtableCount == 0)))
{
OBJECTHANDLE instHandle = GetAppDomain()->CreateTypedHandle(gc.instRef, InstanceHandleType);
// Call the InteropLib and create the associated managed object wrapper.
{
GCX_PREEMP();
hr = InteropLib::Com::CreateWrapperForObject(
instHandle,
vtableCount,
vtables,
flags,
&newWrapper);
}
if (FAILED(hr))
{
DestroyHandleCommon(instHandle, InstanceHandleType);
COMPlusThrowHR(hr);
}
_ASSERTE(!newWrapper.IsNull());
// Try setting the newly created managed object wrapper on the InteropSyncBlockInfo.
if (!interopInfo->TrySetManagedObjectComWrapper(wrapperId, newWrapper))
{
// The new wrapper couldn't be set which means a wrapper already exists.
newWrapper.Release();
// If the managed object wrapper couldn't be set, then
// it should be possible to get the current one.
if (!interopInfo->TryGetManagedObjectComWrapper(wrapperId, &wrapperRawMaybe))
{
UNREACHABLE();
}
}
}
}
// Determine what to return.
if (!newWrapper.IsNull())
{
// A new managed object wrapper was created, remove the object from the holder.
// No AddRef() here since the wrapper should be created with a reference.
wrapperRawMaybe = newWrapper.Extract();
STRESS_LOG1(LF_INTEROP, LL_INFO100, "Created MOW: 0x%p\n", wrapperRawMaybe);
}
else if (wrapperRawMaybe != NULL)
{
// AddRef() the existing wrapper.
IUnknown* wrapper = static_cast<IUnknown*>(wrapperRawMaybe);
(void)wrapper->AddRef();
}
GCPROTECT_END();
*wrapperRaw = wrapperRawMaybe;
RETURN (wrapperRawMaybe != NULL);
}
bool TryGetOrCreateObjectForComInstanceInternal(
_In_opt_ OBJECTREF impl,
_In_ INT64 wrapperId,
_In_ IUnknown* identity,
_In_opt_ IUnknown* inner,
_In_ CreateObjectFlags flags,
_In_ ComWrappersScenario scenario,
_In_opt_ OBJECTREF wrapperMaybe,
_Out_ OBJECTREF* objRef)
{
CONTRACT(bool)
{
THROWS;
MODE_COOPERATIVE;
PRECONDITION(identity != NULL);
PRECONDITION(objRef != NULL);
PRECONDITION((impl != NULL && scenario == ComWrappersScenario::Instance) || (impl == NULL && scenario != ComWrappersScenario::Instance));
PRECONDITION(wrapperId != ComWrappersNative::InvalidWrapperId);
}
CONTRACT_END;
HRESULT hr;
ExternalObjectContext* extObjCxt = NULL;
struct
{
OBJECTREF implRef;
OBJECTREF wrapperMaybeRef;
OBJECTREF objRefMaybe;
} gc;
gc.implRef = impl;
gc.wrapperMaybeRef = wrapperMaybe;
gc.objRefMaybe = NULL;
GCPROTECT_BEGIN(gc);
STRESS_LOG4(LF_INTEROP, LL_INFO1000, "Get or Create EOC: (Identity: 0x%p) (Flags: %x) (Maybe: 0x%p) (ID: %lld)\n", identity, flags, OBJECTREFToObject(wrapperMaybe), wrapperId);
ExtObjCxtCache* cache = ExtObjCxtCache::GetInstance();
InteropLib::OBJECTHANDLE handle = NULL;
ExternalObjectContext::Key cacheKey(identity, wrapperId);
// Check if the user requested a unique instance.
bool uniqueInstance = !!(flags & CreateObjectFlags::CreateObjectFlags_UniqueInstance);
if (!uniqueInstance)
{
bool objectFound = false;
bool tryRemove = false;
{
// Perform a quick look up to determine if we know of the object and if
// we need to perform a more expensive cleanup operation below.
ExtObjCxtCache::ReaderLock lock(cache);
extObjCxt = cache->Find(cacheKey);
objectFound = extObjCxt != NULL;
tryRemove = objectFound && extObjCxt->IsSet(ExternalObjectContext::Flags_Detached);
}
if (tryRemove)
{
// Perform the slower cleanup operation that may be appropriate
// if the object still exists and has been detached.
ExtObjCxtCache::WriterLock lock(cache);
extObjCxt = cache->Find(cacheKey);
objectFound = extObjCxt != NULL;
if (objectFound && extObjCxt->IsSet(ExternalObjectContext::Flags_Detached))
{
// If an EOC has been found but is marked detached, then we will remove it from the
// cache here instead of letting the GC do it later and pretend like it wasn't found.
STRESS_LOG1(LF_INTEROP, LL_INFO10, "Detached EOC requested: 0x%p\n", extObjCxt);
cache->Remove(extObjCxt);
extObjCxt->MarkNotInCache();
extObjCxt = NULL;
}
}
// If is no object found in the cache, check if the object COM instance is actually the CCW
// representing a managed object. If the user passed the Unwrap flag, COM instances that are
// actually CCWs should be unwrapped to the original managed object to allow for round
// tripping object -> COM instance -> object.
if (!objectFound && (flags & CreateObjectFlags::CreateObjectFlags_Unwrap))
{
GCX_PREEMP();
// If the COM instance is a CCW that is not COM-activated, use the object of that wrapper object.
InteropLib::OBJECTHANDLE handleLocal;
if (InteropLib::Com::GetObjectForWrapper(identity, &handleLocal) == S_OK
&& InteropLib::Com::IsComActivated(identity) == S_FALSE)
{
handle = handleLocal;
}
}
}
STRESS_LOG2(LF_INTEROP, LL_INFO1000, "EOC: 0x%p or Handle: 0x%p\n", extObjCxt, handle);
if (extObjCxt != NULL)
{
gc.objRefMaybe = extObjCxt->GetObjectRef();
}
else if (handle != NULL)
{
// We have an object handle from the COM instance which is a CCW.
::OBJECTHANDLE objectHandle = static_cast<::OBJECTHANDLE>(handle);
// Now we need to check if this object is a CCW from the same ComWrappers instance
// as the one creating the EOC. If it is not, we need to create a new EOC for it.
// Otherwise, use it. This allows for the round-trip from object -> COM instance -> object.
OBJECTREF objRef = NULL;
GCPROTECT_BEGIN(objRef);
objRef = ObjectFromHandle(objectHandle);
SyncBlock* syncBlock = objRef->GetSyncBlock();
InteropSyncBlockInfo* interopInfo = syncBlock->GetInteropInfo();
// If we found a managed object wrapper in this ComWrappers instance
// and it's the same identity pointer as the one we're creating an EOC for,
// unwrap it. We don't AddRef the wrapper as we don't take a reference to it.
//
// A managed object can have multiple managed object wrappers, with a max of one per context.
// Let's say we have a managed object A and ComWrappers instances C1 and C2. Let B1 and B2 be the
// managed object wrappers for A created with C1 and C2 respectively.
// If we are asked to create an EOC for B1 with the unwrap flag on the C2 ComWrappers instance,
// we will create a new wrapper. In this scenario, we'll only unwrap B2.
void* wrapperRawMaybe = NULL;
if (interopInfo->TryGetManagedObjectComWrapper(wrapperId, &wrapperRawMaybe)
&& wrapperRawMaybe == identity)
{
gc.objRefMaybe = objRef;
}
else
{
STRESS_LOG2(LF_INTEROP, LL_INFO1000, "Not unwrapping handle (0x%p) because the object's MOW in this ComWrappers instance (if any) (0x%p) is not the provided identity\n", handle, wrapperRawMaybe);
}
GCPROTECT_END();
}
if (gc.objRefMaybe == NULL)
{
// Create context instance for the possibly new external object.
ExternalWrapperResultHolder resultHolder;
{
GCX_PREEMP();
hr = InteropLib::Com::CreateWrapperForExternal(
identity,
inner,
flags,
sizeof(ExternalObjectContext),
&resultHolder);
}
if (FAILED(hr))
COMPlusThrowHR(hr);
// The user could have supplied a wrapper so assign that now.
gc.objRefMaybe = gc.wrapperMaybeRef;
// If the wrapper hasn't been set yet, call the implementation to create one.
if (gc.objRefMaybe == NULL)
{
gc.objRefMaybe = CallCreateObject(scenario, &gc.implRef, identity, flags);
}
// The object may be null if the specified ComWrapper implementation returns null
// or there is no registered global instance. It is the caller's responsibility
// to handle this case and error if necessary.
if (gc.objRefMaybe != NULL)
{
// Construct the new context with the object details.
DWORD eocFlags = (resultHolder.Result.FromTrackerRuntime
? ExternalObjectContext::Flags_ReferenceTracker
: ExternalObjectContext::Flags_None) |
(uniqueInstance
? ExternalObjectContext::Flags_None
: ExternalObjectContext::Flags_InCache) |
((flags & CreateObjectFlags::CreateObjectFlags_Aggregated) != 0
? ExternalObjectContext::Flags_Aggregated
: ExternalObjectContext::Flags_None);
ExternalObjectContext::Construct(
resultHolder.GetContext(),
identity,
GetCurrentCtxCookieWrapper(),
gc.objRefMaybe->GetSyncBlockIndex(),
wrapperId,
eocFlags);
if (uniqueInstance)
{
extObjCxt = resultHolder.GetContext();
}
else
{
// Attempt to insert the new context into the cache.
ExtObjCxtCache::WriterLock lock(cache);
extObjCxt = cache->FindOrAdd(cacheKey, resultHolder.GetContext());
}
STRESS_LOG2(LF_INTEROP, LL_INFO100, "EOC cache insert: 0x%p == 0x%p\n", extObjCxt, resultHolder.GetContext());
// If the returned context matches the new context it means the
// new context was inserted or a unique instance was requested.
if (extObjCxt == resultHolder.GetContext())
{
// Update the object's SyncBlock with a handle to the context for runtime cleanup.
SyncBlock* syncBlock = gc.objRefMaybe->GetSyncBlock();
InteropSyncBlockInfo* interopInfo = syncBlock->GetInteropInfo();
_ASSERTE(syncBlock->IsPrecious());
// Since the caller has the option of providing a wrapper, it is
// possible the supplied wrapper already has an associated external
// object and an object can only be associated with one external object.
if (!interopInfo->TrySetExternalComObjectContext((void**)extObjCxt))
{
// Failed to set the context; one must already exist.
// Remove from the cache above as well.
ExtObjCxtCache::WriterLock lock(cache);
cache->Remove(resultHolder.GetContext());