Welcome to mirror list, hosted at ThFree Co, Russian Federation.

interopconverter.cpp « vm « coreclr « src - github.com/dotnet/runtime.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: fa49b2f41791250c565dcc9772a8b577dbf6a1f9 (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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.


#include "common.h"
#include "vars.hpp"
#include "excep.h"
#include "interoputil.h"
#include "interopconverter.h"
#include "olevariant.h"
#include "comcallablewrapper.h"

#ifdef FEATURE_COMINTEROP

#include "stdinterfaces.h"
#include "runtimecallablewrapper.h"
#include "cominterfacemarshaler.h"
#include "binder.h"
#include <interoplibinterface.h>
#include "typestring.h"

namespace
{
    bool TryGetComIPFromObjectRefUsingComWrappers(
        _In_ OBJECTREF instance,
        _Outptr_ IUnknown** wrapperRaw)
    {
#ifdef FEATURE_COMWRAPPERS
        return GlobalComWrappersForMarshalling::TryGetOrCreateComInterfaceForObject(instance, (void**)wrapperRaw);
#else
        return false;
#endif // FEATURE_COMWRAPPERS
    }

    bool TryGetObjectRefFromComIPUsingComWrappers(
        _In_ IUnknown* pUnknown,
        _In_ DWORD dwFlags,
        _Out_ OBJECTREF *pObjOut)
    {
#ifdef FEATURE_COMWRAPPERS
        return GlobalComWrappersForMarshalling::TryGetOrCreateObjectForComInstance(pUnknown, dwFlags, pObjOut);
#else
        return false;
#endif // FEATURE_COMWRAPPERS
    }

    void EnsureObjectRefIsValidForSpecifiedClass(
        _In_ OBJECTREF *obj,
        _In_ DWORD dwFlags,
        _In_ MethodTable *pMTClass)
    {
        _ASSERTE(*obj != NULL);
        _ASSERTE(pMTClass != NULL);

        if ((dwFlags & ObjFromComIP::CLASS_IS_HINT) != 0)
            return;

        // make sure we can cast to the specified class
        FAULT_NOT_FATAL();

        // Bad format exception thrown for backward compatibility
        THROW_BAD_FORMAT_MAYBE(pMTClass->IsArray() == FALSE, BFA_UNEXPECTED_ARRAY_TYPE, pMTClass);

        if (CanCastComObject(*obj, pMTClass))
            return;

        StackSString ssObjClsName;
        StackSString ssDestClsName;

        (*obj)->GetMethodTable()->_GetFullyQualifiedNameForClass(ssObjClsName);
        pMTClass->_GetFullyQualifiedNameForClass(ssDestClsName);

        COMPlusThrow(kInvalidCastException, IDS_EE_CANNOTCAST,
            ssObjClsName.GetUnicode(), ssDestClsName.GetUnicode());
    }
}

//--------------------------------------------------------------------------------
// IUnknown *GetComIPFromObjectRef(OBJECTREF *poref, MethodTable *pMT, ...)
// Convert ObjectRef to a COM IP, based on MethodTable* pMT.
IUnknown *GetComIPFromObjectRef(OBJECTREF *poref, MethodTable *pMT, BOOL bEnableCustomizedQueryInterface)
{
    CONTRACT (IUnknown*)
    {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        PRECONDITION(CheckPointer(poref));
        PRECONDITION(CheckPointer(pMT));
        PRECONDITION(g_fComStarted && "COM has not been started up, make sure EnsureComStarted is called before any COM objects are used!");
        POSTCONDITION((*poref) != NULL ? CheckPointer(RETVAL) : CheckPointer(RETVAL, NULL_OK));
    }
    CONTRACT_END;

    BOOL        fReleaseWrapper     = false;
    HRESULT     hr                  = E_NOINTERFACE;
    SafeComHolder<IUnknown> pUnk    = NULL;
    size_t      ul                  = 0;

    if (*poref == NULL)
        RETURN NULL;

    if (TryGetComIPFromObjectRefUsingComWrappers(*poref, &pUnk))
    {
        GUID iid;
        pMT->GetGuid(&iid, /*bGenerateIfNotFound*/ FALSE, /*bClassic*/ FALSE);

        IUnknown* pvObj;
        hr = SafeQueryInterface(pUnk, iid, &pvObj);
        if (FAILED(hr))
            COMPlusThrowHR(hr);

        RETURN pvObj;
    }

    if (!g_pConfig->IsBuiltInCOMSupported())
        COMPlusThrow(kNotSupportedException, W("NotSupported_COM"));

    SyncBlock* pBlock = (*poref)->GetSyncBlock();

    InteropSyncBlockInfo* pInteropInfo = pBlock->GetInteropInfo();

    // If we have a CCW, or a NULL CCW but the RCW field was never used,
    //  get the pUnk from the ComCallWrapper, otherwise from the RCW
    if ((NULL != pInteropInfo->GetCCW()) || (!pInteropInfo->RCWWasUsed()))
    {
        CCWHolder pCCWHold = ComCallWrapper::InlineGetWrapper(poref);

        GetComIPFromCCW::flags flags = GetComIPFromCCW::None;
        if (!bEnableCustomizedQueryInterface)   { flags |= GetComIPFromCCW::SuppressCustomizedQueryInterface; }

        pUnk = ComCallWrapper::GetComIPFromCCW(pCCWHold, GUID_NULL, pMT, flags);
    }
    else
    {
        RCWHolder pRCW(GetThread());
        RCWPROTECT_BEGIN(pRCW, pBlock);

        // The interface will be returned addref'ed.
        pUnk = pRCW->GetComIPFromRCW(pMT);

        RCWPROTECT_END(pRCW);
    }

    // If we failed to retrieve an IP then throw an exception.
    if (pUnk == NULL)
        COMPlusThrowHR(hr);

    pUnk.SuppressRelease();
    RETURN pUnk;
}


//--------------------------------------------------------------------------------
// IUnknown *GetComIPFromObjectRef(OBJECTREF *poref, ComIpType ReqIpType, ComIpType *pFetchedIpType);
// Convert ObjectRef to a COM IP of the requested type.
IUnknown *GetComIPFromObjectRef(OBJECTREF *poref, ComIpType ReqIpType, ComIpType *pFetchedIpType)
{
    CONTRACT (IUnknown*)
    {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        PRECONDITION((ReqIpType & (ComIpType_Dispatch | ComIpType_Unknown)) != 0);
        PRECONDITION(CheckPointer(poref));
        PRECONDITION(ReqIpType != 0);
        POSTCONDITION((*poref) != NULL ? CheckPointer(RETVAL) : CheckPointer(RETVAL, NULL_OK));
    }
    CONTRACT_END;

    // COM had better be started up at this point.
    _ASSERTE(g_fComStarted && "COM has not been started up, make sure EnsureComStarted is called before any COM objects are used!");

    BOOL        fReleaseWrapper = false;
    HRESULT     hr              = E_NOINTERFACE;
    IUnknown*   pUnk            = NULL;
    size_t      ul              = 0;
    ComIpType   FetchedIpType   = ComIpType_None;

    if (*poref == NULL)
        RETURN NULL;

    if (TryGetComIPFromObjectRefUsingComWrappers(*poref, &pUnk))
    {
        hr = S_OK;

        IUnknown* pvObj;
        if (ReqIpType & ComIpType_Dispatch)
        {
            hr = SafeQueryInterface(pUnk, IID_IDispatch, &pvObj);
            if (SUCCEEDED(hr))
            {
                pUnk->Release();
                FetchedIpType = ComIpType_Dispatch;
            }
            else if (ReqIpType & ComIpType_Unknown)
            {
                hr = S_OK;
                pvObj = pUnk;
                FetchedIpType = ComIpType_Unknown;
            }
        }
        else
        {
            pvObj = pUnk;
            FetchedIpType = ComIpType_Unknown;
        }

        if (FAILED(hr))
            COMPlusThrowHR(hr);

        if (pFetchedIpType != NULL)
            *pFetchedIpType = FetchedIpType;

        RETURN pvObj;
    }

    if (!g_pConfig->IsBuiltInCOMSupported())
        COMPlusThrow(kNotSupportedException, W("NotSupported_COM"));

    MethodTable *pMT = (*poref)->GetMethodTable();

    SyncBlock* pBlock = (*poref)->GetSyncBlock();

    InteropSyncBlockInfo* pInteropInfo = pBlock->GetInteropInfo();

    if ( (NULL != pInteropInfo->GetCCW()) || (!pInteropInfo->RCWWasUsed()) )
    {
        CCWHolder pCCWHold = ComCallWrapper::InlineGetWrapper(poref);

        // If the user requested IDispatch, then check for IDispatch first.
        if (ReqIpType & ComIpType_Dispatch)
        {
            pUnk = ComCallWrapper::GetComIPFromCCW(pCCWHold, IID_IDispatch, NULL);
            if (pUnk)
                FetchedIpType = ComIpType_Dispatch;
        }

        // If the ObjectRef doesn't support IDispatch and the caller also accepts
        // an IUnknown pointer, then check for IUnknown.
        if (!pUnk && (ReqIpType & ComIpType_Unknown))
        {
            if (ReqIpType & ComIpType_OuterUnknown)
            {
                // check if the object is aggregated
                SimpleComCallWrapper* pSimpleWrap = pCCWHold->GetSimpleWrapper();
                if (pSimpleWrap)
                {
                    pUnk = pSimpleWrap->GetOuter();
                    if (pUnk)
                        SafeAddRef(pUnk);
                }
            }
            if (!pUnk)
                pUnk = ComCallWrapper::GetComIPFromCCW(pCCWHold, IID_IUnknown, NULL);
            if (pUnk)
                FetchedIpType = ComIpType_Unknown;
        }
    }
    else
    {
        RCWHolder pRCW(GetThread());

        // This code is hot, use a simple RCWHolder check (i.e. don't increment the use count on the RCW).
        // @TODO: Cache IDispatch so we don't have to QI every time we come here.
        pRCW.InitFastCheck(pBlock);

        // If the user requested IDispatch, then check for IDispatch first.
        if (ReqIpType & ComIpType_Dispatch)
        {
            pUnk = pRCW->GetIDispatch();
            if (pUnk)
                FetchedIpType = ComIpType_Dispatch;
        }

        // If the ObjectRef doesn't support IDispatch and the caller also accepts
        // an IUnknown pointer, then check for IUnknown.
        if (!pUnk && (ReqIpType & ComIpType_Unknown))
        {
            pUnk = pRCW->GetIUnknown();
            if (pUnk)
                FetchedIpType = ComIpType_Unknown;
        }
    }

    // If we failed to retrieve an IP then throw an exception.
    if (pUnk == NULL)
        COMPlusThrowHR(hr);

    // If the caller wants to know the fetched IP type, then set pFetchedIpType
    // to the type of the IP.
    if (pFetchedIpType)
        *pFetchedIpType = FetchedIpType;

    RETURN pUnk;
}


//+----------------------------------------------------------------------------
// IUnknown *GetComIPFromObjectRef(OBJECTREF *poref, REFIID iid);
// convert ComIP to an ObjectRef, based on riid
//+----------------------------------------------------------------------------
IUnknown *GetComIPFromObjectRef(OBJECTREF *poref, REFIID iid, bool throwIfNoComIP /* = true */)
{
    CONTRACT (IUnknown*)
    {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        PRECONDITION(CheckPointer(poref));
        POSTCONDITION((*poref) != NULL ? CheckPointer(RETVAL, throwIfNoComIP ? NULL_NOT_OK : NULL_OK) : CheckPointer(RETVAL, NULL_OK));
    }
    CONTRACT_END;

    ASSERT_PROTECTED(poref);

    // COM had better be started up at this point.
    _ASSERTE(g_fComStarted && "COM has not been started up, make sure EnsureComStarted is called before any COM objects are used!");

    BOOL        fReleaseWrapper = false;
    HRESULT     hr              = E_NOINTERFACE;
    IUnknown*   pUnk            = NULL;
    size_t      ul              = 0;

    if (*poref == NULL)
        RETURN NULL;

    if (TryGetComIPFromObjectRefUsingComWrappers(*poref, &pUnk))
    {
        IUnknown* pvObj;
        hr = SafeQueryInterface(pUnk, iid, &pvObj);
        pUnk->Release();
        if (FAILED(hr))
            COMPlusThrowHR(hr);

        RETURN pvObj;
    }

    MethodTable *pMT = (*poref)->GetMethodTable();

    SyncBlock* pBlock = (*poref)->GetSyncBlock();

    InteropSyncBlockInfo* pInteropInfo = pBlock->GetInteropInfo();

    if ((NULL != pInteropInfo->GetCCW()) || (!pInteropInfo->RCWWasUsed()))
    {
        CCWHolder pCCWHold = ComCallWrapper::InlineGetWrapper(poref);
        pUnk = ComCallWrapper::GetComIPFromCCW(pCCWHold, iid, NULL);
    }
    else
    {
        SafeComHolder<IUnknown> pUnkHolder;

        RCWHolder pRCW(GetThread());
        RCWPROTECT_BEGIN(pRCW, pBlock);

        // The interface will be returned addref'ed.
        pUnkHolder = pRCW->GetComIPFromRCW(iid);

        RCWPROTECT_END(pRCW);

        pUnk = pUnkHolder.Extract();
    }

    if (throwIfNoComIP && pUnk == NULL)
        COMPlusThrowHR(hr);

    RETURN pUnk;
}


//+----------------------------------------------------------------------------
// GetObjectRefFromComIP
// pUnk : input IUnknown
// pMTClass : specifies the type of instance to be returned
// NOTE:**  As per COM Rules, the IUnknown passed in shouldn't be AddRef'ed
//+----------------------------------------------------------------------------
void GetObjectRefFromComIP(OBJECTREF* pObjOut, IUnknown **ppUnk, MethodTable *pMTClass, MethodTable *pItfMT, DWORD dwFlags)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        PRECONDITION(CheckPointer(ppUnk));
        PRECONDITION(CheckPointer(*ppUnk, NULL_OK));
        PRECONDITION(CheckPointer(pMTClass, NULL_OK));
        PRECONDITION(IsProtectedByGCFrame(pObjOut));
        PRECONDITION(pItfMT == NULL || pItfMT->IsInterface());
    }
    CONTRACTL_END;

    // COM had better be started up at this point.
    _ASSERTE(g_fComStarted && "COM has not been started up, make sure EnsureComStarted is called before any COM objects are used!");

    IUnknown *pUnk = *ppUnk;
    *pObjOut = NULL;

    if (TryGetObjectRefFromComIPUsingComWrappers(pUnk, dwFlags, pObjOut))
    {
        if (pMTClass != NULL)
            EnsureObjectRefIsValidForSpecifiedClass(pObjOut, dwFlags, pMTClass);

        return;
    }

    if (!g_pConfig->IsBuiltInCOMSupported())
        COMPlusThrow(kNotSupportedException, W("NotSupported_COM"));

    Thread * pThread = GetThread();

    IUnknown* pOuter = pUnk;
    SafeComHolder<IUnknown> pAutoOuterUnk = NULL;

    if (pUnk != NULL)
    {
        // get CCW for IUnknown
        ComCallWrapper *ccw = GetCCWFromIUnknown(pUnk);
        if (ccw == NULL)
        {
            // could be aggregated scenario
            HRESULT hr = SafeQueryInterface(pUnk, IID_IUnknown, &pOuter);
            LogInteropQI(pUnk, IID_IUnknown, hr, "GetObjectRefFromComIP: QI for Outer");
            IfFailThrow(hr);

            // store the outer in the auto pointer
            pAutoOuterUnk = pOuter;
            ccw = GetCCWFromIUnknown(pOuter);
        }

        // If the CCW was activated via COM, do not unwrap it.
        // Unwrapping a CCW would deliver the underlying OBJECTREF,
        // but when a managed class is activated via COM it should
        // remain a COM object and adhere to COM rules.
        if (ccw != NULL
            && !ccw->IsComActivated())
        {
            *pObjOut = ccw->GetObjectRef();
        }

        if (*pObjOut == NULL)
        {
            // Only pass in the class method table to the interface marshaler if
            // it is a COM import (or COM import derived) class.
            MethodTable *pComClassMT = NULL;
            if (pMTClass)
            {
                if (pMTClass->IsComObjectType())
                {
                    pComClassMT = pMTClass;
                }
            }

            DWORD flags = RCW::CreationFlagsFromObjForComIPFlags((ObjFromComIP::flags)dwFlags);

            // Convert the IP to an OBJECTREF.
            COMInterfaceMarshaler marshaler;

            marshaler.Init(pOuter, pComClassMT, pThread, flags);
            *pObjOut = marshaler.FindOrCreateObjectRef(pUnk, pItfMT);
        }
    }


    if ((0 == (dwFlags & ObjFromComIP::CLASS_IS_HINT)) && (*pObjOut != NULL))
    {
        // make sure we can cast to the specified class
        if (pMTClass != NULL)
        {
            EnsureObjectRefIsValidForSpecifiedClass(pObjOut, dwFlags, pMTClass);
        }
    }
}
#endif // FEATURE_COMINTEROP