summaryrefslogtreecommitdiff
path: root/src/inc/internalunknownimpl.h
blob: 9b561fad64ad5d614d1946d4025564345028224e (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
// 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.
//*****************************************************************************
//
// InternalUnknownImpl.h
//
// Defines utility class ComUtil::IUnknownCommon, which provides default
// implementations for IUnknown's AddRef, Release, and QueryInterface methods.
//
// Use: a class that implements one or more interfaces should derive from
// ComUtil::IUnknownCommon with a template parameter list consisting of the
// list of implemented interfaces.
//
// Example:
//   class MyInterfacesImpl :
//     public IUnknownCommon<MyInterface1, MyInterface2>
//   { ... };
//
// IUnknownCommon will provide base AddRef and Release semantics, and will
// also provide an implementation of QueryInterface that will evaluate the
// arguments against the set of supported interfaces and return the
// appropriate result.
//
// If you need to specify multiple interfaces where one is a base interface
// of another and implementing all of them would result in a compiler error,
// you can use the NoDerive wrapper to tell IUnknownCommon to not derive from
// this interface but just use it for QueryInterface calls.
//
// Example:
//   interface A
//   { ... };
//   interface B : public A
//   { ... };
//   class MyInterfacesImpl : public IUnknownCommon<B, NoDerive<A> >
//   { ... };
//
// If a base type also implements IUnknownCommon, then you must override
// QueryInterface with a method that delegates to your type's
// IUnknownCommon::QueryInterface and then to BaseType::QueryInterface.
//


//
//*****************************************************************************

#ifndef __InternalUnknownImpl_h__
#define __InternalUnknownImpl_h__

#include <winnt.h>
#include "winwrap.h"
#include "contract.h"
#include "ex.h"
#include "volatile.h"
#include "mpl/type_list"
#include "debugmacros.h"

#define COMUTIL_IIDOF(x) __uuidof(x)

namespace ComUtil
{
    //---------------------------------------------------------------------------------------------
    template <typename T>
    struct TypeWrapper
    { typedef T wrapped_type; };

    namespace detail
    {
        typedef char (&_Yes)[1];
        typedef char (&_No)[2];

        static inline _No _IsTypeWrapper(...);

        template <typename T>
        static _Yes _IsTypeWrapper(T *, typename T::wrapped_type * = nullptr);
    }

    //---------------------------------------------------------------------------------------------
    template <typename T>
    struct IsTypeWrapper
    {
        static const bool value = std::integral_constant<
            bool, 
            sizeof(detail::_IsTypeWrapper((T*)0)) == sizeof(detail::_Yes)>::value;
    };

    //-----------------------------------------------------------------------------------------
    // Utility to remove marker type wrappers.
    template <typename T, bool IsWrapper = IsTypeWrapper<T>::value>
    struct UnwrapOne
    { typedef T type; };

    template <typename T>
    struct UnwrapOne<T, true>
    { typedef typename T::wrapped_type type; };

    template <typename T, bool IsWrapper = IsTypeWrapper<T>::value>
    struct Unwrap
    { typedef T type; };

    template <typename T>
    struct Unwrap<T, true>
    { typedef typename Unwrap< typename UnwrapOne<T>::type >::type type; };

    //---------------------------------------------------------------------------------------------
    // Used as a flag to indicate that an interface should not be used as a base class.
    // See DeriveTypeList below.
    template <typename T>
    struct NoDerive : public TypeWrapper<T>
    { };

    //---------------------------------------------------------------------------------------------
    // Used to indicate that a base class contributes implemented interfaces.
    template <typename T>
    struct ItfBase : public TypeWrapper<T>
    { };

    namespace detail
    {
        using namespace mpl;

        //-----------------------------------------------------------------------------------------
        // Exposes a type that derives every type in the given type list, except for those marked
        // with NoDerive.
        template <typename ListT>
        struct DeriveTypeList;

        // Common case. Derive from list head and recursively on list tail.
        template <typename HeadT, typename TailT>
        struct DeriveTypeList< type_list<HeadT, TailT> > :
            public Unwrap<HeadT>::type,
            public DeriveTypeList<TailT>
        {};

        // Non-derived case. Skip this type, continue with tail.
        template <typename HeadT, typename TailT>
        struct DeriveTypeList< type_list< NoDerive< HeadT >, TailT> > :
            public DeriveTypeList<TailT>
        {};

        // Termination case.
        template <>
        struct DeriveTypeList<null_type>
        {};

        //-----------------------------------------------------------------------------------------
        template <typename ItfTypeListT>
        struct GetFirstInterface;

        template <typename HeadT, typename TailT>
        struct GetFirstInterface< type_list<HeadT, TailT> >
        { typedef HeadT type; };
        
        template <typename HeadT, typename TailT>
        struct GetFirstInterface< type_list< ItfBase< HeadT >, TailT> >
        { typedef typename GetFirstInterface<TailT>::type type; };

        template <>
        struct GetFirstInterface< null_type >
        { typedef IUnknown type; };

        //-----------------------------------------------------------------------------------------
        // Uses type lists to implement the helper. Type lists are implemented
        // through templates, and can be best understood if compared to Scheme
        // cdr and cons: each list type has a head type and a tail type. The
        // head type is typically a concrete type, and the tail type is
        // typically another list containing the remainder of the list. Type
        // lists are terminated with a head type of null_type.
        //
        // QueryInterface is implemented using QIHelper, which uses type_lists
        // and partial specialization to recursively walk the type list and
        // look to see if the requested interface is supported. If not, then
        // the termination case is reached and a final test against IUknown
        // is made before returning a failure.
        //-----------------------------------------------------------------------------------------
        template <typename InterfaceTypeList>
        struct QIHelper;

        template <typename HeadT, typename TailT>
        struct QIHelper< type_list< HeadT, TailT > >
        {
            template <typename IUnknownCommonT>
            static inline HRESULT QI(
                REFIID           riid,
                void           **ppvObject,
                IUnknownCommonT *pThis)
            {
                STATIC_CONTRACT_NOTHROW;
                STATIC_CONTRACT_GC_NOTRIGGER;
                STATIC_CONTRACT_ENTRY_POINT;

                HRESULT hr = S_OK;

                typedef typename Unwrap<HeadT>::type ItfT;

                // If the interface type matches that of the head of the list,
                // then cast to it and return success.
                if (riid == COMUTIL_IIDOF(ItfT))
                {
                    ItfT *pItf = static_cast<ItfT *>(pThis);
                    pItf->AddRef();
                    *ppvObject = pItf;
                }
                // If not, recurse on the tail of the list.
                else
                    hr = QIHelper<TailT>::QI(riid, ppvObject, pThis);

                return hr;
            }
        };

        template <typename HeadT, typename TailT>
        struct QIHelper< type_list< ItfBase< HeadT >, TailT> >
        {
            template <typename IUnknownCommonT>
            static inline HRESULT QI(
                REFIID           riid,
                void           **ppvObject,
                IUnknownCommonT *pThis)
            {
                STATIC_CONTRACT_NOTHROW;
                STATIC_CONTRACT_GC_NOTRIGGER;
                STATIC_CONTRACT_ENTRY_POINT;

                HRESULT hr = S_OK;

                hr = pThis->HeadT::QueryInterface(riid, ppvObject);

                if (hr == E_NOINTERFACE)
                    hr = QIHelper<TailT>::QI(riid, ppvObject, pThis);

                return hr;
            }
        };

        // This is the termination case. In this case, we check if the
        // requested interface is IUnknown (which is common to all interfaces).
        template <>
        struct QIHelper< null_type >
        {
            template <typename IUnknownCommonT>
            static inline HRESULT QI(
                REFIID           riid,
                void           **ppvObject,
                IUnknownCommonT *pThis)
            {
                STATIC_CONTRACT_NOTHROW;
                STATIC_CONTRACT_GC_NOTRIGGER;
                STATIC_CONTRACT_ENTRY_POINT;

                HRESULT hr = S_OK;

                // If the request was for IUnknown, cast and return success.
                if (riid == COMUTIL_IIDOF(IUnknown))
                {
                    typedef typename detail::GetFirstInterface<
                        typename IUnknownCommonT::InterfaceListT>::type IUnknownCastHelper;

                    // Cast to first interface type to then cast to IUnknown unambiguously.
                    IUnknown *pItf = static_cast<IUnknown *>(
                        static_cast<IUnknownCastHelper *>(pThis));
                    pItf->AddRef();
                    *ppvObject = pItf;
                }
                // Otherwise none of the interfaces match the requested IID,
                // so return E_NOINTERFACE.
                else
                {
                    *ppvObject = nullptr;
                    hr = E_NOINTERFACE;
                }

                return hr;
            }
        };

        //-----------------------------------------------------------------------------------------
        // Is used as a virtual base to ensure that there is a single reference count field.
        struct IUnknownCommonRef
        {
            inline
            IUnknownCommonRef()
                : m_cRef(0)
            {}

            Volatile<LONG> m_cRef;
        };
    }

    //---------------------------------------------------------------------------------------------
    // IUnknownCommon
    //
    //   T0-T9 - the list of interfaces to implement.
    template
    <
        typename T0 = mpl::null_type,
        typename T1 = mpl::null_type,
        typename T2 = mpl::null_type,
        typename T3 = mpl::null_type,
        typename T4 = mpl::null_type,
        typename T5 = mpl::null_type,
        typename T6 = mpl::null_type,
        typename T7 = mpl::null_type,
        typename T8 = mpl::null_type,
        typename T9 = mpl::null_type
    >
    class IUnknownCommon :
        virtual protected detail::IUnknownCommonRef,
        public detail::DeriveTypeList< typename mpl::make_type_list<
            T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>::type >
    {
    public:
        typedef typename mpl::make_type_list<
            T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>::type InterfaceListT;

        // Add a virtual destructor to force derived types to also have virtual destructors.
        virtual ~IUnknownCommon()
        {
            WRAPPER_NO_CONTRACT;
            clr::dbg::PoisonMem(*this);
        }

        // Standard AddRef implementation
        STDMETHOD_(ULONG, AddRef())
        {
            STATIC_CONTRACT_LIMITED_METHOD;
            STATIC_CONTRACT_ENTRY_POINT;

            return InterlockedIncrement(&m_cRef);
        }

        // Standard Release implementation.
        STDMETHOD_(ULONG, Release())
        {
            STATIC_CONTRACT_LIMITED_METHOD;
            STATIC_CONTRACT_ENTRY_POINT;

            _ASSERTE(m_cRef > 0);

            ULONG cRef = InterlockedDecrement(&m_cRef);
            
            if (cRef == 0)
                delete this; // Relies on virtual dtor to work properly.

            return cRef;
        }

        // Uses detail::QIHelper for implementation.
        STDMETHOD(QueryInterface(REFIID riid, void **ppvObject))
        {
            STATIC_CONTRACT_LIMITED_METHOD;
            STATIC_CONTRACT_ENTRY_POINT;

            if (ppvObject == nullptr)
                return E_INVALIDARG;

            *ppvObject = nullptr;

            return detail::QIHelper<InterfaceListT>::QI(
                riid, ppvObject, this);
        }

        template <typename ItfT>
        HRESULT QueryInterface(ItfT **ppItf)
        {
            return QueryInterface(__uuidof(ItfT), reinterpret_cast<void**>(ppItf));
        }

    protected:
        // May only be constructed as a base type.
        inline IUnknownCommon() :
            IUnknownCommonRef()
        { WRAPPER_NO_CONTRACT; }
    };

    //---------------------------------------------------------------------------------------------
    // IUnknownCommonExternal
    //
    //   T0-T9 - the list of interfaces to implement.
    template
    <
        typename T0 = mpl::null_type,
        typename T1 = mpl::null_type,
        typename T2 = mpl::null_type,
        typename T3 = mpl::null_type,
        typename T4 = mpl::null_type,
        typename T5 = mpl::null_type,
        typename T6 = mpl::null_type,
        typename T7 = mpl::null_type,
        typename T8 = mpl::null_type,
        typename T9 = mpl::null_type
    >
    class IUnknownCommonExternal :
        virtual protected detail::IUnknownCommonRef,
        public detail::DeriveTypeList< typename mpl::make_type_list<
            T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>::type >
    {
    public:
        typedef typename mpl::make_type_list<
            T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>::type InterfaceListT;

        // Standard AddRef implementation
        STDMETHOD_(ULONG, AddRef())
        {
            STATIC_CONTRACT_LIMITED_METHOD;
            STATIC_CONTRACT_ENTRY_POINT;

            return InterlockedIncrement(&m_cRef);
        }

        // Standard Release implementation.
        // Should be called outside VM only
        STDMETHOD_(ULONG, Release())
        {
            STATIC_CONTRACT_LIMITED_METHOD;
            STATIC_CONTRACT_ENTRY_POINT;

            _ASSERTE(m_cRef > 0);

            ULONG cRef = InterlockedDecrement(&m_cRef);
            
            if (cRef == 0)
            {
                Cleanup();          // Cleans up the object
                delete this;
            }
            
            return cRef;
        }

        // Internal release
        // Should be called inside VM only
        STDMETHOD_(ULONG, InternalRelease())
        {
            LIMITED_METHOD_CONTRACT;
            
            _ASSERTE(m_cRef > 0);

            ULONG cRef = InterlockedDecrement(&m_cRef);
            
            if (cRef == 0)
            {
                InternalCleanup();  // Cleans up the object, internal version
                delete this;
            }
            
            return cRef;
        }
        
        // Uses detail::QIHelper for implementation.
        STDMETHOD(QueryInterface(REFIID riid, void **ppvObject))
        {
            STATIC_CONTRACT_LIMITED_METHOD;
            STATIC_CONTRACT_ENTRY_POINT;

            if (ppvObject == nullptr)
                return E_INVALIDARG;

            *ppvObject = nullptr;

            return detail::QIHelper<InterfaceListT>::QI(
                riid, ppvObject, this);
        }

        template <typename ItfT>
        HRESULT QueryInterface(ItfT **ppItf)
        {
            return QueryInterface(__uuidof(ItfT), reinterpret_cast<void**>(ppItf));
        }

    protected:
        // May only be constructed as a base type.
        inline IUnknownCommonExternal() :
            IUnknownCommonRef()
        { WRAPPER_NO_CONTRACT; }

        // Internal version of cleanup
        virtual void InternalCleanup() = 0;

        // External version of cleanup
        // Not surprisingly, this should call InternalCleanup to avoid duplicate code
        // Not implemented here to avoid bringing too much into this header file
        virtual void Cleanup() = 0;
    };
}

#undef COMUTIL_IIDOF

using ComUtil::NoDerive;
using ComUtil::ItfBase;
using ComUtil::IUnknownCommon;
using ComUtil::IUnknownCommonExternal;

#endif // __InternalUnknownImpl_h__