summaryrefslogtreecommitdiff
path: root/src/vm/comconnectionpoints.cpp
blob: a92ac2dc2971a1e6bc8e93bfe4a985d87da36ef6 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ===========================================================================
// File: ComConnectionPoints.cpp
//

// ===========================================================================
// Implementation of the classes used to expose connection points to COM.
// ===========================================================================


#include "common.h"

#include "comconnectionpoints.h"
#include "comcallablewrapper.h"

//------------------------------------------------------------------------------------------
//      Implementation of helper class used to expose connection points
//------------------------------------------------------------------------------------------

void ConnectionPoint::Advise_Wrapper(LPVOID ptr)
{
    WRAPPER_NO_CONTRACT;

    Advise_Args *pArgs = (Advise_Args *)ptr;
    pArgs->pThis->AdviseWorker(pArgs->pUnk, pArgs->pdwCookie);
}

void ConnectionPoint::Unadvise_Wrapper(LPVOID ptr)
{
    WRAPPER_NO_CONTRACT;

    Unadvise_Args *pArgs = (Unadvise_Args *)ptr;
    pArgs->pThis->UnadviseWorker(pArgs->dwCookie);
}

void ConnectionPoint::GetConnectionPointContainer_Wrapper(LPVOID ptr)
{
    WRAPPER_NO_CONTRACT;

    GetConnectionPointContainer_Args *pArgs = (GetConnectionPointContainer_Args *)ptr;
    *pArgs->ppCPC = pArgs->pThis->GetConnectionPointContainerWorker();
}

ConnectionPoint::ConnectionPoint(ComCallWrapper *pWrap, MethodTable *pEventMT)
: m_pOwnerWrap(pWrap)
, m_pTCEProviderMT(pWrap->GetSimpleWrapper()->GetMethodTable())
, m_pEventItfMT(pEventMT)
, m_Lock(CrstInterop)
, m_cbRefCount(0)
, m_apEventMethods(NULL)
, m_NumEventMethods(0)
, m_pLastInserted(NULL)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(CheckPointer(pWrap));
        PRECONDITION(CheckPointer(pEventMT));
    }
    CONTRACTL_END;
    
    // Retrieve the connection IID.
    pEventMT->GetGuid(&m_rConnectionIID, TRUE);   

    // Set up the event methods.
    SetupEventMethods();
}

ConnectionPoint::~ConnectionPoint()
{
    WRAPPER_NO_CONTRACT;
    
    if (m_apEventMethods)
        delete []m_apEventMethods;
}

HRESULT __stdcall ConnectionPoint::QueryInterface(REFIID riid, void** ppv)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;
        PRECONDITION(CheckPointer(ppv, NULL_OK));
    }
    CONTRACTL_END;

    // Verify the arguments.
    if (!ppv)
        return E_POINTER;

    // Initialize the out parameters.
    *ppv = NULL;

    SetupForComCallHR();

    if (riid == IID_IConnectionPoint)
    {
        *ppv = static_cast<IConnectionPoint*>(this);
    }
    else if (riid == IID_IUnknown)
    {
        *ppv = static_cast<IUnknown*>(this);
    }
    else 
    {
        return E_NOINTERFACE;
    }

    ULONG cbRef = SafeAddRefPreemp((IUnknown*)*ppv);
    //@TODO(CLE) AddRef logging that doesn't use QI
    
    return S_OK;
}

ULONG __stdcall ConnectionPoint::AddRef()
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    SetupForComCallHR();

    // The connection point objects share the CCW's ref count.
    return m_pOwnerWrap->AddRef();
}

ULONG __stdcall ConnectionPoint::Release()
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    SetupForComCallHR();

    HRESULT hr = S_OK;
    ULONG cbRef = -1;

    BEGIN_EXTERNAL_ENTRYPOINT(&hr)
    {
        // The connection point objects share the CCW's ref count.
        cbRef = m_pOwnerWrap->Release();
    }
    END_EXTERNAL_ENTRYPOINT;

    return cbRef;
}

HRESULT __stdcall ConnectionPoint::GetConnectionInterface(IID *pIID)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;        
        PRECONDITION(CheckPointer(pIID, NULL_OK));
    }
    CONTRACTL_END;

    // Verify the arguments.
    if (!pIID)
        return E_POINTER;

    // Initialize the out parameters.
    *pIID = GUID_NULL;

    SetupForComCallHR();

    *pIID = m_rConnectionIID;
    return S_OK;
}

HRESULT __stdcall ConnectionPoint::GetConnectionPointContainer(IConnectionPointContainer **ppCPC)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;        
        PRECONDITION(CheckPointer(ppCPC, NULL_OK));
    }
    CONTRACTL_END;

    HRESULT hr = S_OK;

    // Verify the arguments.
    if (!ppCPC)
        return E_POINTER;

    // Initialize the out parameters.
    *ppCPC = NULL;

    SetupForComCallHR();

    BEGIN_EXTERNAL_ENTRYPOINT(&hr)
    {
        GCX_COOP_THREAD_EXISTS(GET_THREAD());
        Thread *pThread = GET_THREAD();

        ADID targetADID;
        Context *pTargetContext;
        if (m_pOwnerWrap->NeedToSwitchDomains(pThread, &targetADID, &pTargetContext))
        {
            GetConnectionPointContainer_Args args = {this, ppCPC};
            pThread->DoContextCallBack(targetADID, pTargetContext, GetConnectionPointContainer_Wrapper, &args);
        }
        else
        {
            *ppCPC = GetConnectionPointContainerWorker();
        }
    }
    END_EXTERNAL_ENTRYPOINT;

    return hr;
}

HRESULT __stdcall ConnectionPoint::Advise(IUnknown *pUnk, DWORD *pdwCookie)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;        
        PRECONDITION(CheckPointer(pUnk, NULL_OK));
        PRECONDITION(CheckPointer(pdwCookie, NULL_OK));
    }
    CONTRACTL_END;

    HRESULT hr = S_OK;

    // Verify the arguments.
    if (!pUnk || !pdwCookie)
        return E_POINTER;

    // Initialize the out parameters.
    *pdwCookie = NULL;

    SetupForComCallHR();

    BEGIN_EXTERNAL_ENTRYPOINT(&hr)
    {
        GCX_COOP_THREAD_EXISTS(GET_THREAD());
        Thread *pThread = GET_THREAD();

        ADID targetADID;
        Context *pTargetContext;
        if (m_pOwnerWrap->NeedToSwitchDomains(pThread, &targetADID, &pTargetContext))
        {
            Advise_Args args = {this, pUnk, pdwCookie};
            pThread->DoContextCallBack(targetADID, pTargetContext, Advise_Wrapper, &args); 
        }
        else
        {
            AdviseWorker(pUnk, pdwCookie);
        }
    }
    END_EXTERNAL_ENTRYPOINT;
    
    return hr;
}

HRESULT __stdcall ConnectionPoint::Unadvise(DWORD dwCookie)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;        
    }
    CONTRACTL_END;

    HRESULT hr = S_OK;
    
    // Verify the arguments.
    if (dwCookie == 0)
        return CONNECT_E_NOCONNECTION;

    SetupForComCallHR();

    BEGIN_EXTERNAL_ENTRYPOINT(&hr)
    {
        GCX_COOP_THREAD_EXISTS(GET_THREAD());
        Thread *pThread = GET_THREAD();

        ADID targetADID;
        Context *pTargetContext;
        if (m_pOwnerWrap->NeedToSwitchDomains(pThread, &targetADID, &pTargetContext))
        {
            Unadvise_Args args = {this, dwCookie};
            pThread->DoContextCallBack(targetADID, pTargetContext, Unadvise_Wrapper, &args);
        }
        else
        {
            UnadviseWorker(dwCookie);
        }
    }
    END_EXTERNAL_ENTRYPOINT;

    return hr;
}

HRESULT __stdcall ConnectionPoint::EnumConnections(IEnumConnections **ppEnum)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;        
        PRECONDITION(CheckPointer(ppEnum, NULL_OK));
    }
    CONTRACTL_END;

    // Verify the arguments.
    if (!ppEnum)
        return E_POINTER;

    // Initialize the out parameters.
    *ppEnum = NULL;

    SetupForComCallHR();   
   
    ConnectionEnum *pConEnum = new(nothrow) ConnectionEnum(this);
    if (!pConEnum)
        return E_OUTOFMEMORY;
    
    // Retrieve the IEnumConnections interface. This cannot fail.    
    HRESULT hr = SafeQueryInterfacePreemp((IUnknown*)pConEnum, IID_IEnumConnections, (IUnknown**)ppEnum);
    LogInteropQI((IUnknown*)pConEnum, IID_IEnumConnections, hr, "ConnectionPoint::EnumConnections: QIing for IID_IEnumConnections");    
    _ASSERTE(hr == S_OK);

    return hr;
}

IConnectionPointContainer *ConnectionPoint::GetConnectionPointContainerWorker()
{
    CONTRACT(IConnectionPointContainer*)
    {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        POSTCONDITION(CheckPointer(RETVAL));
    }
    CONTRACT_END;

    // Retrieve the IConnectionPointContainer from the owner wrapper.
    RETURN (IConnectionPointContainer*) 
        ComCallWrapper::GetComIPFromCCW(m_pOwnerWrap, IID_IConnectionPointContainer, NULL);
}

void ConnectionPoint::AdviseWorker(IUnknown *pUnk, DWORD *pdwCookie)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        PRECONDITION(CheckPointer(pUnk));
        PRECONDITION(CheckPointer(pdwCookie));
    }
    CONTRACTL_END;

    SafeComHolder<IUnknown> pEventItf = NULL;
    HRESULT hr;
    
    // Make sure we have a pointer to the interface and not to another IUnknown.
    hr = SafeQueryInterface(pUnk, m_rConnectionIID, &pEventItf );
    LogInteropQI(pUnk, m_rConnectionIID, hr, "ConnectionPoint::AdviseWorker: QIing for correct interface");

    if (FAILED(hr) || !pEventItf) 
        COMPlusThrowHR(CONNECT_E_CANNOTCONNECT);

    COMOBJECTREF pEventItfObj = NULL;
    OBJECTREF pTCEProviderObj = NULL;

    GCPROTECT_BEGIN(pEventItfObj)
    GCPROTECT_BEGIN(pTCEProviderObj)
    {
        // Create a COM+ object ref to wrap the event interface.               
        GetObjectRefFromComIP((OBJECTREF*)&pEventItfObj, pUnk, NULL);
        IfNullThrow(pEventItfObj);

        // Get the TCE provider COM+ object from the wrapper
        pTCEProviderObj = m_pOwnerWrap->GetObjectRef();

        for (int cEventMethod = 0; cEventMethod < m_NumEventMethods; cEventMethod++)
        {
            // If the managed object supports the event that call the AddEventX method.
            if (m_apEventMethods[cEventMethod].m_pEventMethod)
                InvokeProviderMethod( pTCEProviderObj, (OBJECTREF) pEventItfObj, m_apEventMethods[cEventMethod].m_pAddMethod, m_apEventMethods[cEventMethod].m_pEventMethod );
        }

        // Allocate the object handle and the connection cookie.
        OBJECTHANDLEHolder phndEventItfObj = GetAppDomain()->CreateHandle((OBJECTREF)pEventItfObj);
        ConnectionCookieHolder pConCookie = ConnectionCookie::CreateConnectionCookie(phndEventItfObj);

        // pConCookie owns the handle now and will destroy it on exception
        phndEventItfObj.SuppressRelease();

        // Add the connection cookie to the list.
        InsertWithLock(pConCookie);

        // Everything went ok so hand back the cookie id.
        *pdwCookie = pConCookie->m_id;
        
        pConCookie.SuppressRelease();
    }
    GCPROTECT_END();
    GCPROTECT_END();
}

void ConnectionPoint::UnadviseWorker(DWORD dwCookie)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;
       
    COMOBJECTREF pEventItfObj = NULL;
    OBJECTREF pTCEProviderObj = NULL;

    GCPROTECT_BEGIN(pEventItfObj)
    GCPROTECT_BEGIN(pTCEProviderObj)
    {
        // The cookie is actually a connection cookie.
        ConnectionCookieHolder pConCookie = FindWithLock(dwCookie);

        // Retrieve the COM+ object from the cookie which in fact is the object handle.
        pEventItfObj = (COMOBJECTREF) ObjectFromHandle(pConCookie->m_hndEventProvObj); 
        if (!pEventItfObj)
            COMPlusThrowHR(E_INVALIDARG);

        // Get the object from the wrapper
        pTCEProviderObj = m_pOwnerWrap->GetObjectRef();

        for (int cEventMethod = 0; cEventMethod < m_NumEventMethods; cEventMethod++)
        {
            // If the managed object supports the event that call the RemoveEventX method.
            if (m_apEventMethods[cEventMethod].m_pEventMethod)
            {
                InvokeProviderMethod(pTCEProviderObj, (OBJECTREF) pEventItfObj, m_apEventMethods[cEventMethod].m_pRemoveMethod, m_apEventMethods[cEventMethod].m_pEventMethod);
            }
        }

        // Remove the connection cookie from the list.
        FindAndRemoveWithLock(pConCookie);
    }
    GCPROTECT_END();
    GCPROTECT_END();
}

void ConnectionPoint::SetupEventMethods()
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM());
    }
    CONTRACTL_END;

    // Remember the number of not supported events.
    int cNonSupportedEvents = 0;

    // Retrieve the total number of event methods present on the source interface.
    int cMaxNumEventMethods = m_pEventItfMT->GetNumMethods();

    // If there are no methods then there is nothing to do.
    if (cMaxNumEventMethods == 0)
        return;

    // Allocate the event method tables.
    NewArrayHolder<EventMethodInfo> EventMethodInfos = new EventMethodInfo[cMaxNumEventMethods];

    // Find all the real event methods needed to be able to advise on the current connection point.
    int NumEventMethods = 0;
    for (int cEventMethod = 0; cEventMethod < cMaxNumEventMethods; cEventMethod++)
    {
        // Retrieve the method descriptor for the current method on the event interface.
        MethodDesc *pEventMethodDesc = m_pEventItfMT->GetMethodDescForSlot(cEventMethod);
        if (!pEventMethodDesc)
            continue;

        // Store the event method on the source interface.
        EventMethodInfos[NumEventMethods].m_pEventMethod = pEventMethodDesc;

        // Retrieve and store the add and remove methods for the event.
        EventMethodInfos[NumEventMethods].m_pAddMethod = FindProviderMethodDesc(pEventMethodDesc, EventAdd);
        EventMethodInfos[NumEventMethods].m_pRemoveMethod = FindProviderMethodDesc(pEventMethodDesc, EventRemove);

        // Make sure we have found both the add and the remove methods.
        if (!EventMethodInfos[NumEventMethods].m_pAddMethod || !EventMethodInfos[NumEventMethods].m_pRemoveMethod)
        {
            cNonSupportedEvents++;
            continue;
        }

        // Increment the real number of event methods on the source interface.
        NumEventMethods++;
    }

    // If the interface has methods and the object does not support any then we 
    // fail the connection.
    if ((NumEventMethods == 0) && (cNonSupportedEvents > 0))
        COMPlusThrowHR(CONNECT_E_NOCONNECTION);

    // Now that the struct is totally setup, we'll set the members.
    m_NumEventMethods = NumEventMethods;
    m_apEventMethods = EventMethodInfos;
    EventMethodInfos.SuppressRelease();
}

MethodDesc *ConnectionPoint::FindProviderMethodDesc( MethodDesc *pEventMethodDesc, EnumEventMethods Method )
{
    CONTRACT (MethodDesc*)
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(CheckPointer(pEventMethodDesc));
        PRECONDITION(Method == EventAdd || Method == EventRemove);
        POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
    }
    CONTRACT_END

    // Retrieve the event method.
    MethodDesc *pProvMethodDesc = 
        MemberLoader::FindEventMethod(m_pTCEProviderMT, pEventMethodDesc->GetName(), Method, MemberLoader::FM_IgnoreCase);
    if (!pProvMethodDesc)
        RETURN NULL;

    // Validate that the signature of the delegate is the expected signature.
    MetaSig Sig(pProvMethodDesc);
    if (Sig.NextArg() != ELEMENT_TYPE_CLASS)
        RETURN NULL;

    // <TODO>@TODO: this ignores the type of failure - try GetLastTypeHandleThrowing()</TODO>
    TypeHandle DelegateType = Sig.GetLastTypeHandleNT();
    if (DelegateType.IsNull())
        RETURN NULL;

    PCCOR_SIGNATURE pEventMethSig;
    DWORD cEventMethSig;
    pEventMethodDesc->GetSig(&pEventMethSig, &cEventMethSig);
    MethodDesc *pInvokeMD = MemberLoader::FindMethod(DelegateType.GetMethodTable(),
        "Invoke", 
        pEventMethSig, 
        cEventMethSig, 
        pEventMethodDesc->GetModule());
    
    if (!pInvokeMD)
        RETURN NULL;

    // The requested method exists and has the appropriate signature.
    RETURN pProvMethodDesc;
}

void ConnectionPoint::InvokeProviderMethod( OBJECTREF pProvider, OBJECTREF pSubscriber, MethodDesc *pProvMethodDesc, MethodDesc *pEventMethodDesc )
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        INJECT_FAULT(COMPlusThrowOM());
        PRECONDITION(CheckPointer(pProvMethodDesc));
        PRECONDITION(CheckPointer(pEventMethodDesc));
    }
    CONTRACTL_END;

    GCPROTECT_BEGIN (pSubscriber);
    GCPROTECT_BEGIN (pProvider);
    {
        // Create a method signature to extract the type of the delegate.
        MetaSig MethodSig( pProvMethodDesc);
        _ASSERTE( 1 == MethodSig.NumFixedArgs() );

        // Go to the first argument.
        CorElementType ArgType = MethodSig.NextArg();
        _ASSERTE( ELEMENT_TYPE_CLASS == ArgType );

        // Retrieve the EE class representing the argument.
        MethodTable *pDelegateCls = MethodSig.GetLastTypeHandleThrowing().GetMethodTable();

        // Make sure we activate the assembly containing the target method desc
        pEventMethodDesc->EnsureActive();

        // Allocate an object based on the method table of the delegate class.
        OBJECTREF pDelegate = pDelegateCls->Allocate();
            
        GCPROTECT_BEGIN( pDelegate );
        {
            // Initialize the delegate using the arguments structure.
            // <TODO>Generics: ensure we get the right MethodDesc here and in similar places</TODO>
            // Accept both void (object, native int) and void (object, native uint)
            MethodDesc *pDlgCtorMD = MemberLoader::FindConstructor(pDelegateCls, &gsig_IM_Obj_IntPtr_RetVoid);
            if (pDlgCtorMD == NULL)
                pDlgCtorMD = MemberLoader::FindConstructor(pDelegateCls, &gsig_IM_Obj_UIntPtr_RetVoid);
                
            // The loader is responsible for only accepting well-formed delegate classes.
            _ASSERTE(pDlgCtorMD);
                
            MethodDescCallSite dlgCtor(pDlgCtorMD);

            ARG_SLOT CtorArgs[3] = { ObjToArgSlot(pDelegate),
                                     ObjToArgSlot(pSubscriber),
                                     (ARG_SLOT)pEventMethodDesc->GetMultiCallableAddrOfCode()
                                   };
            dlgCtor.Call(CtorArgs);

            MethodDescCallSite prov(pProvMethodDesc, &pProvider);

            // Do the actual invocation of the method method.
            ARG_SLOT Args[2] = { ObjToArgSlot( pProvider ), ObjToArgSlot( pDelegate ) };
            prov.Call(Args);
        }
        GCPROTECT_END();
    }
    GCPROTECT_END();
    GCPROTECT_END();
}

void ConnectionPoint::InsertWithLock(ConnectionCookie* pConCookie)
{
    WRAPPER_NO_CONTRACT;

    LockHolder lh(this);

    bool fDone = false;

    //
    // handle special cases 
    //
    
    if (NULL == m_pLastInserted)
    {
        //
        // Special case 1:  List is empty.
        //
        CONSISTENCY_CHECK(NULL == m_ConnectionList.GetHead());
        
        pConCookie->m_id = 1;
        m_ConnectionList.InsertHead(pConCookie);
        fDone = true;
    }

    if (!fDone && ((NULL != m_pLastInserted->m_Link.m_pNext) || (idUpperLimit == m_pLastInserted->m_id)))
    {
        //
        // Special case 2:  Last inserted is somewhere in the middle of the list or we last 
        //                  inserted the max token id (we've wrapped around) and ID 1 is not 
        //                  taken.
        //
        CONSISTENCY_CHECK(NULL != m_ConnectionList.GetHead());
        
        if (1 != m_ConnectionList.GetHead()->m_id)
        {
            // if ID 1 is not taken, we can just insert there. 
            pConCookie->m_id = 1;
            m_ConnectionList.InsertHead(pConCookie);
            fDone = true;
        }
    }

    //
    // General cases
    //
    if (!fDone)
    {
        ConnectionCookie* pLocationToStartSearchForInsertPoint = NULL;
        ConnectionCookie* pInsertionPoint = NULL;
        
        if (NULL == m_pLastInserted->m_Link.m_pNext)
        {
            if (idUpperLimit == m_pLastInserted->m_id)
            {
                CONSISTENCY_CHECK(1 == m_ConnectionList.GetHead()->m_id);   // should be handled by special case #2
                
                // we need to wrap around
                // scan from head for first hole, insert there
                pLocationToStartSearchForInsertPoint = m_ConnectionList.GetHead();
            }
            else
            {
                // Most common case: insert at tail, incrementing ID
                pInsertionPoint = m_pLastInserted;
                pLocationToStartSearchForInsertPoint = NULL;    // don't do any searching, just append
            }
        }
        else
        {
            // scan from m_pLastInserted for first hole, insert there
            pLocationToStartSearchForInsertPoint = m_pLastInserted;
        }

        if (NULL != pLocationToStartSearchForInsertPoint)
        {
            // Starting from pLocationToStartSearchForInsertPoint, scan list to find a 
            // discontinuity in the IDs.  Insert there.

            ConnectionCookie* pCurrentNode = pLocationToStartSearchForInsertPoint;

            //
            // limit case is where we've wrapped around the whole list and found the initial start point again.
            //
            while (true)
            {
                if (NULL == pCurrentNode->m_Link.m_pNext)
                {
                    if (pCurrentNode->m_id < idUpperLimit)
                    {
                        // if we reach the end of the list and we have free IDs, let's use them.
                        break;
                    }
                    pCurrentNode = m_ConnectionList.GetHead();
                }
                else
                {
                    ConnectionCookie* pNext = CONTAINING_RECORD(pCurrentNode->m_Link.m_pNext, ConnectionCookie, m_Link);
                    if ((pCurrentNode->m_id + 1) < pNext->m_id)
                    {
                        break;
                    }
                    pCurrentNode = pNext;
                }

                if (pCurrentNode == pLocationToStartSearchForInsertPoint)
                {
                    // we came back to the node where we started which means that there's no gap and
                    // all IDs up to idUpperLimit are taken
                    EX_THROW(HRException, (CONNECT_E_ADVISELIMIT));
                }
            }
            
            pInsertionPoint = pCurrentNode;
        }

        
        CONSISTENCY_CHECK(NULL != pInsertionPoint);
        CONSISTENCY_CHECK(idUpperLimit != pInsertionPoint->m_id);

#ifdef _DEBUG
        ConnectionCookie* pNextCookieNode = CONTAINING_RECORD(pInsertionPoint->m_Link.m_pNext, ConnectionCookie, m_Link);
        DWORD idNew = pInsertionPoint->m_id + 1;
        CONSISTENCY_CHECK(NULL == pNextCookieNode || 
            ((pInsertionPoint->m_id < idNew) && 
                                     (idNew < pNextCookieNode->m_id)));
#endif // _DEBUG

        pConCookie->m_id = pInsertionPoint->m_id + 1;
        pInsertionPoint->m_Link.InsertAfter(&pConCookie->m_Link);
    }
    
    m_pLastInserted = pConCookie;
}

ConnectionCookie* ConnectionPoint::FindWithLock(DWORD idOfCookie)
{
    WRAPPER_NO_CONTRACT;

    ConnectionCookie* pCurrentNode;

    {
        LockHolder lh(this);

        pCurrentNode = m_ConnectionList.GetHead();

        while (pCurrentNode && (pCurrentNode->m_id != idOfCookie))
        {
            pCurrentNode = CONTAINING_RECORD(pCurrentNode->m_Link.m_pNext, ConnectionCookie, m_Link);
        }
    }

    if (NULL == pCurrentNode)
    {
        EX_THROW(HRException, (CONNECT_E_NOCONNECTION));
    }

    return pCurrentNode;
}


void ConnectionPoint::FindAndRemoveWithLock(ConnectionCookie* pConCookie)
{
    WRAPPER_NO_CONTRACT;

    LockHolder lh(this);

    m_ConnectionList.FindAndRemove(pConCookie);

    if (pConCookie == m_pLastInserted)
    {
        m_pLastInserted = m_ConnectionList.GetHead();
    }
}

ConnectionPointEnum::ConnectionPointEnum(ComCallWrapper *pOwnerWrap, CQuickArray<ConnectionPoint*> *pCPList)
: m_pOwnerWrap(pOwnerWrap)
, m_pCPList(pCPList)
, m_CurrPos(0)
, m_cbRefCount(0)
, m_Lock(CrstInterop)
{
    WRAPPER_NO_CONTRACT;
    
    m_pOwnerWrap->AddRef();
}

ConnectionPointEnum::~ConnectionPointEnum()
{
    WRAPPER_NO_CONTRACT;
    
    if (m_pOwnerWrap)
        m_pOwnerWrap->Release();
}

HRESULT __stdcall ConnectionPointEnum::QueryInterface(REFIID riid, void** ppv)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;        
        PRECONDITION(CheckPointer(ppv, NULL_OK));
    }
    CONTRACTL_END;

    // Verify the arguments.
    if (!ppv)
        return E_POINTER;

    // Initialize the out parameters.
    *ppv = NULL;

    SetupForComCallHR();
    
    if (riid == IID_IEnumConnectionPoints)
    {
        *ppv = static_cast<IEnumConnectionPoints*>(this);
    }
    else if (riid == IID_IUnknown)
    {
        *ppv = static_cast<IUnknown*>(this);
    }
    else 
    {
        return E_NOINTERFACE;
    }
    
    ULONG cbRef = SafeAddRefPreemp((IUnknown*)*ppv);
    //@TODO(CLE) AddRef logging that doesn't use QI
    
    return S_OK;
}

ULONG __stdcall ConnectionPointEnum::AddRef()
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    SetupForComCallHR();

    LONG i = FastInterlockIncrement((LONG*)&m_cbRefCount );
    return i;
}

ULONG __stdcall ConnectionPointEnum::Release()
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    SetupForComCallHR();

    HRESULT hr = S_OK;
    ULONG cbRef = -1;

    BEGIN_EXTERNAL_ENTRYPOINT(&hr)
    {
        cbRef = FastInterlockDecrement((LONG*)&m_cbRefCount );
        _ASSERTE(cbRef >=0);
        if (cbRef == 0)
            delete this;
    }
    END_EXTERNAL_ENTRYPOINT;

    return cbRef;
}

HRESULT __stdcall ConnectionPointEnum::Next(ULONG cConnections, IConnectionPoint **ppCP, ULONG *pcFetched)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;
        PRECONDITION(CheckPointer(ppCP, NULL_OK));
        PRECONDITION(CheckPointer(pcFetched, NULL_OK));
    }
    CONTRACTL_END;

    // Verify the arguments.
    if (NULL == ppCP)
        return E_POINTER;

    // Initialize the out parameters.
    if (pcFetched)
        *pcFetched = 0;

    SetupForComCallHR();
    
    UINT cFetched;

    // Acquire the lock before we start traversing the connection point list.
    {
        LockHolder lh(this);

        for (cFetched = 0; cFetched < cConnections && m_CurrPos < m_pCPList->Size(); cFetched++, m_CurrPos++)
        {
            ppCP[cFetched] = (*m_pCPList)[m_CurrPos];
            SafeAddRefPreemp(ppCP[cFetched]);
        }

        if (pcFetched)
            *pcFetched = cFetched;
    }

    return cFetched == cConnections ? S_OK : S_FALSE;
}

HRESULT __stdcall ConnectionPointEnum::Skip(ULONG cConnections)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    SetupForComCallHR();

    // Acquire the lock before we start traversing the connection point list.
    {
        LockHolder lh(this);

        if(m_CurrPos + cConnections <= m_pCPList->Size())
        {
            // There are enough connection points left in the list to allow
            // us to skip the required number.
            m_CurrPos += cConnections;
            return S_OK;
        }
        else
        {
            // There aren't enough connection points left so set the current
            // position to the end of the list and return S_FALSE to indicate
            // we couldn't skip the requested number.
            m_CurrPos = (UINT)m_pCPList->Size();
            return S_FALSE;
        }
    }
}

HRESULT __stdcall ConnectionPointEnum::Reset()
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    SetupForComCallHR();

    // Acquire the lock before we start traversing the connection point list.
    {
        LockHolder lh(this);
        m_CurrPos = 0;
    }

    return S_OK;
}

HRESULT __stdcall ConnectionPointEnum::Clone(IEnumConnectionPoints **ppEnum)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;
        PRECONDITION(CheckPointer(ppEnum, NULL_OK));
    }
    CONTRACTL_END;

    // Verify the arguments.
    if (!ppEnum)
        return E_POINTER;

    // Initialize the out parameters.
    *ppEnum = NULL;

    SetupForComCallHR();

    ConnectionPointEnum *pCPEnum;
    {
        CONTRACT_VIOLATION(ThrowsViolation);  //ConnectionPointEnum throws
        pCPEnum = new(nothrow) ConnectionPointEnum(m_pOwnerWrap, m_pCPList);
    }
    if (!pCPEnum)
        return E_OUTOFMEMORY;

    HRESULT hr = SafeQueryInterfacePreemp(pCPEnum, IID_IEnumConnectionPoints, (IUnknown**)ppEnum);
    LogInteropQI(pCPEnum, IID_IEnumConnectionPoints, hr, "ConnectionPointEnum::Clone: QIing for IID_IEnumConnectionPoints");

    return hr;
}

ConnectionEnum::ConnectionEnum(ConnectionPoint *pConnectionPoint)
: m_pConnectionPoint(pConnectionPoint)
, m_CurrCookie(pConnectionPoint->GetCookieList()->GetHead())
, m_cbRefCount(0)
{
    CONTRACTL
    {
        NOTHROW;
        MODE_PREEMPTIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    ULONG cbRef = SafeAddRefPreemp(m_pConnectionPoint);
    //@TODO(CLE) AddRef logging that doesn't use QI
}

ConnectionEnum::~ConnectionEnum()
{
    CONTRACTL
    {
        NOTHROW;
        MODE_PREEMPTIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    ULONG cbRef = SafeReleasePreemp(m_pConnectionPoint);
    LogInteropRelease(m_pConnectionPoint, cbRef, "ConnectionEnum::~ConnectionEnum: Releasing the connection point object");
}

HRESULT __stdcall ConnectionEnum::QueryInterface(REFIID riid, void** ppv)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;
        PRECONDITION(CheckPointer(ppv, NULL_OK));
    }
    CONTRACTL_END;

    // Verify the arguments.
    if (!ppv)
        return E_POINTER;

    // Initialize the out parameters.
    *ppv = NULL;

    SetupForComCallHR();

    if (riid == IID_IEnumConnections)
    {
        *ppv = static_cast<IEnumConnections*>(this);
    }
    else if (riid == IID_IUnknown)
    {
        *ppv = static_cast<IUnknown*>(this);
    }
    else 
    {
        return E_NOINTERFACE;
    }
    
    ULONG cbRef = SafeAddRefPreemp((IUnknown*)*ppv);
    //@TODO(CLE) AddRef logging that doesn't use QI
    
    return S_OK;
}

ULONG __stdcall ConnectionEnum::AddRef()
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        SO_TOLERANT;
        MODE_PREEMPTIVE;
    }
    CONTRACTL_END;

    SetupForComCallHR();

    LONG i = FastInterlockIncrement((LONG*)&m_cbRefCount);
    return i;
}

ULONG __stdcall ConnectionEnum::Release()
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    SetupForComCallHR();

    LONG i = FastInterlockDecrement((LONG*)&m_cbRefCount);
    _ASSERTE(i >=0);
    if (i == 0)
        delete this;

    return i;
}

HRESULT __stdcall ConnectionEnum::Next(ULONG cConnections, CONNECTDATA* rgcd, ULONG *pcFetched)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;
        PRECONDITION(CheckPointer(rgcd, NULL_OK));
        PRECONDITION(CheckPointer(pcFetched, NULL_OK));
    }
    CONTRACTL_END;

    // Verify the arguments.
    if (NULL == rgcd)
        return E_POINTER;

    // Initialize the out parameters.
    if (pcFetched)
        *pcFetched = 0;

    SetupForComCallHR();

    HRESULT hr = S_OK;
    UINT cFetched;
    CONNECTIONCOOKIELIST *pConnectionList = m_pConnectionPoint->GetCookieList();

    // Acquire the connection point's lock before we start traversing the connection list.
    {
        ConnectionPoint::LockHolder lh(m_pConnectionPoint);

        {
            // Switch to cooperative GC mode before we manipulate OBJCETREF's.
            GCX_COOP();

            for (cFetched = 0; cFetched < cConnections && m_CurrCookie; cFetched++)
            {
                {
                    CONTRACT_VIOLATION(ThrowsViolation);
                    rgcd[cFetched].pUnk = GetComIPFromObjectRef((OBJECTREF*)m_CurrCookie->m_hndEventProvObj, ComIpType_Unknown, NULL);
                    rgcd[cFetched].dwCookie = m_CurrCookie->m_id;
                }
                m_CurrCookie = pConnectionList->GetNext(m_CurrCookie);
            }
        }

        // Leave the lock now that we are done traversing the list.
    }

    // Set the count of fetched connections if the caller desires it.
    if (pcFetched)
        *pcFetched = cFetched;

    return cFetched == cConnections ? S_OK : S_FALSE;
}

HRESULT __stdcall ConnectionEnum::Skip(ULONG cConnections)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    SetupForComCallHR();
    
    HRESULT hr = S_FALSE;
    CONNECTIONCOOKIELIST *pConnectionList = m_pConnectionPoint->GetCookieList();

    {
        ConnectionPoint::LockHolder lh(m_pConnectionPoint);

        // Try and skip the requested number of connections.
        while (m_CurrCookie && cConnections)
        {
            m_CurrCookie = pConnectionList->GetNext(m_CurrCookie);
            cConnections--;
        }
        // Leave the lock now that we are done traversing the list.
    }

    // Check to see if we succeeded.
    return cConnections == 0 ? S_OK : S_FALSE;
}

HRESULT __stdcall ConnectionEnum::Reset()
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    SetupForComCallHR();
    
    // Set the current cookie back to the head of the list. We must acquire the
    // connection point lock before we touch the list.
    ConnectionPoint::LockHolder lh(m_pConnectionPoint);

    m_CurrCookie = m_pConnectionPoint->GetCookieList()->GetHead();

    return S_OK;
}

HRESULT __stdcall ConnectionEnum::Clone(IEnumConnections **ppEnum)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;        
        PRECONDITION(CheckPointer(ppEnum, NULL_OK));
    }
    CONTRACTL_END;

    // Verify the arguments.
    if (!ppEnum)
        return E_POINTER;

    // Initialize the out parameters.
    *ppEnum = NULL;

    // This should setup a SO_INTOLERANT region, why isn't it?
    SetupForComCallHR();
    
    ConnectionEnum *pConEnum = new(nothrow) ConnectionEnum(m_pConnectionPoint);
    if (!pConEnum)
        return E_OUTOFMEMORY;

    HRESULT hr = SafeQueryInterfacePreemp(pConEnum, IID_IEnumConnections, (IUnknown**)ppEnum);
    LogInteropQI(pConEnum, IID_IEnumConnections, hr, "ConnectionEnum::Clone: QIing for IID_IEnumConnections");

    return hr;
}