home *** CD-ROM | disk | FTP | other *** search
/ Tricks of the Windows Gam…ming Gurus (2nd Edition) / Disc2.iso / vc98 / atl / include / atlcom.h < prev    next >
C/C++ Source or Header  |  1998-06-16  |  139KB  |  5,207 lines

  1. // This is a part of the Active Template Library.
  2. // Copyright (C) 1996-1998 Microsoft Corporation
  3. // All rights reserved.
  4. //
  5. // This source code is only intended as a supplement to the
  6. // Active Template Library Reference and related
  7. // electronic documentation provided with the library.
  8. // See these sources for detailed information regarding the
  9. // Active Template Library product.
  10.  
  11. #ifndef __ATLCOM_H__
  12. #define __ATLCOM_H__
  13.  
  14. #ifndef __cplusplus
  15.     #error ATL requires C++ compilation (use a .cpp suffix)
  16. #endif
  17.  
  18. #ifndef __ATLBASE_H__
  19.     #error atlcom.h requires atlbase.h to be included first
  20. #endif
  21.  
  22. #pragma pack(push, _ATL_PACKING)
  23.  
  24. EXTERN_C const IID IID_ITargetFrame;
  25.  
  26. namespace ATL
  27. {
  28.  
  29. #define CComConnectionPointContainerImpl IConnectionPointContainerImpl
  30. #define CComISupportErrorInfoImpl ISupportErrorInfoImpl
  31. #define CComProvideClassInfo2Impl IProvideClassInfoImpl
  32. #define CComDualImpl IDispatchImpl
  33.  
  34. #ifdef _ATL_DEBUG_QI
  35. #ifndef _ATL_DEBUG
  36. #define _ATL_DEBUG
  37. #endif // _ATL_DEBUG
  38. #endif // _ATL_DEBUG_QI
  39.  
  40. #ifdef _ATL_DEBUG_QI
  41. #define _ATLDUMPIID(iid, name, hr) AtlDumpIID(iid, name, hr)
  42. #else
  43. #define _ATLDUMPIID(iid, name, hr) hr
  44. #endif
  45.  
  46. #define _ATL_DEBUG_ADDREF_RELEASE_IMPL(className)\
  47.     virtual ULONG STDMETHODCALLTYPE AddRef(void) = 0;\
  48.     virtual ULONG STDMETHODCALLTYPE Release(void) = 0;
  49.  
  50. /////////////////////////////////////////////////////////////////////////////
  51. // AtlReportError
  52.  
  53. inline HRESULT WINAPI AtlReportError(const CLSID& clsid, UINT nID, const IID& iid,
  54.     HRESULT hRes, HINSTANCE hInst)
  55. {
  56.     return AtlSetErrorInfo(clsid, (LPCOLESTR)MAKEINTRESOURCE(nID), 0, NULL, iid, hRes, hInst);
  57. }
  58.  
  59. inline HRESULT WINAPI AtlReportError(const CLSID& clsid, UINT nID, DWORD dwHelpID,
  60.     LPCOLESTR lpszHelpFile, const IID& iid, HRESULT hRes, HINSTANCE hInst)
  61. {
  62.     return AtlSetErrorInfo(clsid, (LPCOLESTR)MAKEINTRESOURCE(nID), dwHelpID,
  63.         lpszHelpFile, iid, hRes, hInst);
  64. }
  65.  
  66. #ifndef OLE2ANSI
  67. inline HRESULT WINAPI AtlReportError(const CLSID& clsid, LPCSTR lpszDesc,
  68.     DWORD dwHelpID, LPCSTR lpszHelpFile, const IID& iid, HRESULT hRes)
  69. {
  70.     ATLASSERT(lpszDesc != NULL);
  71.     USES_CONVERSION;
  72.     return AtlSetErrorInfo(clsid, A2COLE(lpszDesc), dwHelpID, A2CW(lpszHelpFile),
  73.         iid, hRes, NULL);
  74. }
  75.  
  76. inline HRESULT WINAPI AtlReportError(const CLSID& clsid, LPCSTR lpszDesc,
  77.     const IID& iid, HRESULT hRes)
  78. {
  79.     ATLASSERT(lpszDesc != NULL);
  80.     USES_CONVERSION;
  81.     return AtlSetErrorInfo(clsid, A2COLE(lpszDesc), 0, NULL, iid, hRes, NULL);
  82. }
  83. #endif
  84.  
  85. inline HRESULT WINAPI AtlReportError(const CLSID& clsid, LPCOLESTR lpszDesc,
  86.     const IID& iid, HRESULT hRes)
  87. {
  88.     return AtlSetErrorInfo(clsid, lpszDesc, 0, NULL, iid, hRes, NULL);
  89. }
  90.  
  91. inline HRESULT WINAPI AtlReportError(const CLSID& clsid, LPCOLESTR lpszDesc, DWORD dwHelpID,
  92.     LPCOLESTR lpszHelpFile, const IID& iid, HRESULT hRes)
  93. {
  94.     return AtlSetErrorInfo(clsid, lpszDesc, dwHelpID, lpszHelpFile, iid, hRes, NULL);
  95. }
  96.  
  97. //////////////////////////////////////////////////////////////////////////////
  98. // IPersistImpl
  99. template <class T>
  100. class ATL_NO_VTABLE IPersistImpl : public IPersist
  101. {
  102. public:
  103.     STDMETHOD(GetClassID)(CLSID *pClassID)
  104.     {
  105.         ATLTRACE2(atlTraceCOM, 0, _T("IPersistImpl::GetClassID\n"));
  106.         if (pClassID == NULL)
  107.             return E_FAIL;
  108.         *pClassID = T::GetObjectCLSID();
  109.         return S_OK;
  110.     }
  111. };
  112.  
  113.  
  114. //////////////////////////////////////////////////////////////////////////////
  115. // CComDispatchDriver / Specialization of CComQIPtr<IDispatch, IID_IDispatch>
  116. class CComDispatchDriver
  117. {
  118. public:
  119.     CComDispatchDriver()
  120.     {
  121.         p = NULL;
  122.     }
  123.     CComDispatchDriver(IDispatch* lp)
  124.     {
  125.         if ((p = lp) != NULL)
  126.             p->AddRef();
  127.     }
  128.     CComDispatchDriver(IUnknown* lp)
  129.     {
  130.         p=NULL;
  131.         if (lp != NULL)
  132.             lp->QueryInterface(IID_IDispatch, (void **)&p);
  133.     }
  134.     ~CComDispatchDriver() { if (p) p->Release(); }
  135.     void Release() {if (p) p->Release(); p=NULL;}
  136.     operator IDispatch*() {return p;}
  137.     IDispatch& operator*() {ATLASSERT(p!=NULL); return *p; }
  138.     IDispatch** operator&() {ATLASSERT(p==NULL); return &p; }
  139.     IDispatch* operator->() {ATLASSERT(p!=NULL); return p; }
  140.     IDispatch* operator=(IDispatch* lp){return (IDispatch*)AtlComPtrAssign((IUnknown**)&p, lp);}
  141.     IDispatch* operator=(IUnknown* lp)
  142.     {
  143.         return (IDispatch*)AtlComQIPtrAssign((IUnknown**)&p, lp, IID_IDispatch);
  144.     }
  145.     BOOL operator!(){return (p == NULL) ? TRUE : FALSE;}
  146.  
  147.     HRESULT GetPropertyByName(LPCOLESTR lpsz, VARIANT* pVar)
  148.     {
  149.         ATLASSERT(p);
  150.         ATLASSERT(pVar);
  151.         DISPID dwDispID;
  152.         HRESULT hr = GetIDOfName(lpsz, &dwDispID);
  153.         if (SUCCEEDED(hr))
  154.             hr = GetProperty(p, dwDispID, pVar);
  155.         return hr;
  156.     }
  157.     HRESULT GetProperty(DISPID dwDispID, VARIANT* pVar)
  158.     {
  159.         ATLASSERT(p);
  160.         return GetProperty(p, dwDispID, pVar);
  161.     }
  162.     HRESULT PutPropertyByName(LPCOLESTR lpsz, VARIANT* pVar)
  163.     {
  164.         ATLASSERT(p);
  165.         ATLASSERT(pVar);
  166.         DISPID dwDispID;
  167.         HRESULT hr = GetIDOfName(lpsz, &dwDispID);
  168.         if (SUCCEEDED(hr))
  169.             hr = PutProperty(p, dwDispID, pVar);
  170.         return hr;
  171.     }
  172.     HRESULT PutProperty(DISPID dwDispID, VARIANT* pVar)
  173.     {
  174.         ATLASSERT(p);
  175.         return PutProperty(p, dwDispID, pVar);
  176.     }
  177.     HRESULT GetIDOfName(LPCOLESTR lpsz, DISPID* pdispid)
  178.     {
  179.         return p->GetIDsOfNames(IID_NULL, (LPOLESTR*)&lpsz, 1, LOCALE_USER_DEFAULT, pdispid);
  180.     }
  181.     // Invoke a method by DISPID with no parameters
  182.     HRESULT Invoke0(DISPID dispid, VARIANT* pvarRet = NULL)
  183.     {
  184.         DISPPARAMS dispparams = { NULL, NULL, 0, 0};
  185.         return p->Invoke(dispid, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &dispparams, pvarRet, NULL, NULL);
  186.     }
  187.     // Invoke a method by name with no parameters
  188.     HRESULT Invoke0(LPCOLESTR lpszName, VARIANT* pvarRet = NULL)
  189.     {
  190.         HRESULT hr;
  191.         DISPID dispid;
  192.         hr = GetIDOfName(lpszName, &dispid);
  193.         if (SUCCEEDED(hr))
  194.             hr = Invoke0(dispid, pvarRet);
  195.         return hr;
  196.     }
  197.     // Invoke a method by DISPID with a single parameter
  198.     HRESULT Invoke1(DISPID dispid, VARIANT* pvarParam1, VARIANT* pvarRet = NULL)
  199.     {
  200.         DISPPARAMS dispparams = { pvarParam1, NULL, 1, 0};
  201.         return p->Invoke(dispid, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &dispparams, pvarRet, NULL, NULL);
  202.     }
  203.     // Invoke a method by name with a single parameter
  204.     HRESULT Invoke1(LPCOLESTR lpszName, VARIANT* pvarParam1, VARIANT* pvarRet = NULL)
  205.     {
  206.         HRESULT hr;
  207.         DISPID dispid;
  208.         hr = GetIDOfName(lpszName, &dispid);
  209.         if (SUCCEEDED(hr))
  210.             hr = Invoke1(dispid, pvarParam1, pvarRet);
  211.         return hr;
  212.     }
  213.     // Invoke a method by DISPID with two parameters
  214.     HRESULT Invoke2(DISPID dispid, VARIANT* pvarParam1, VARIANT* pvarParam2, VARIANT* pvarRet = NULL)
  215.     {
  216.         CComVariant varArgs[2] = { *pvarParam2, *pvarParam1 };
  217.         DISPPARAMS dispparams = { &varArgs[0], NULL, 2, 0};
  218.         return p->Invoke(dispid, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &dispparams, pvarRet, NULL, NULL);
  219.     }
  220.     // Invoke a method by name with two parameters
  221.     HRESULT Invoke2(LPCOLESTR lpszName, VARIANT* pvarParam1, VARIANT* pvarParam2, VARIANT* pvarRet = NULL)
  222.     {
  223.         HRESULT hr;
  224.         DISPID dispid;
  225.         hr = GetIDOfName(lpszName, &dispid);
  226.         if (SUCCEEDED(hr))
  227.             hr = Invoke2(dispid, pvarParam1, pvarParam2, pvarRet);
  228.         return hr;
  229.     }
  230.     // Invoke a method by DISPID with N parameters
  231.     HRESULT InvokeN(DISPID dispid, VARIANT* pvarParams, int nParams, VARIANT* pvarRet = NULL)
  232.     {
  233.         DISPPARAMS dispparams = { pvarParams, NULL, nParams, 0};
  234.         return p->Invoke(dispid, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &dispparams, pvarRet, NULL, NULL);
  235.     }
  236.     // Invoke a method by name with Nparameters
  237.     HRESULT InvokeN(LPCOLESTR lpszName, VARIANT* pvarParams, int nParams, VARIANT* pvarRet = NULL)
  238.     {
  239.         HRESULT hr;
  240.         DISPID dispid;
  241.         hr = GetIDOfName(lpszName, &dispid);
  242.         if (SUCCEEDED(hr))
  243.             hr = InvokeN(dispid, pvarParams, nParams, pvarRet);
  244.         return hr;
  245.     }
  246.     static HRESULT GetProperty(IDispatch* pDisp, DISPID dwDispID,
  247.         VARIANT* pVar)
  248.     {
  249.         ATLTRACE2(atlTraceCOM, 0, _T("CPropertyHelper::GetProperty\n"));
  250.         DISPPARAMS dispparamsNoArgs = {NULL, NULL, 0, 0};
  251.         return pDisp->Invoke(dwDispID, IID_NULL,
  252.                 LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET,
  253.                 &dispparamsNoArgs, pVar, NULL, NULL);
  254.     }
  255.  
  256.     static HRESULT PutProperty(IDispatch* pDisp, DISPID dwDispID,
  257.         VARIANT* pVar)
  258.     {
  259.         ATLTRACE2(atlTraceCOM, 0, _T("CPropertyHelper::PutProperty\n"));
  260.         DISPPARAMS dispparams = {NULL, NULL, 1, 1};
  261.         dispparams.rgvarg = pVar;
  262.         DISPID dispidPut = DISPID_PROPERTYPUT;
  263.         dispparams.rgdispidNamedArgs = &dispidPut;
  264.  
  265.         if (pVar->vt == VT_UNKNOWN || pVar->vt == VT_DISPATCH || 
  266.             (pVar->vt & VT_ARRAY) || (pVar->vt & VT_BYREF))
  267.         {
  268.             HRESULT hr = pDisp->Invoke(dwDispID, IID_NULL,
  269.                 LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUTREF,
  270.                 &dispparams, NULL, NULL, NULL);
  271.             if (SUCCEEDED(hr))
  272.                 return hr;
  273.         }
  274.  
  275.         return pDisp->Invoke(dwDispID, IID_NULL,
  276.                 LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUT,
  277.                 &dispparams, NULL, NULL, NULL);
  278.     }
  279.  
  280.     IDispatch* p;
  281. };
  282.  
  283. //////////////////////////////////////////////////////////////////////////////
  284. // CFakeFirePropNotifyEvent
  285. class CFakeFirePropNotifyEvent
  286. {
  287. public:
  288.     static HRESULT FireOnRequestEdit(IUnknown* /*pUnk*/, DISPID /*dispID*/)
  289.     {
  290.         return S_OK;
  291.     }
  292.     static HRESULT FireOnChanged(IUnknown* /*pUnk*/, DISPID /*dispID*/)
  293.     {
  294.         return S_OK;
  295.     }
  296. };
  297. typedef CFakeFirePropNotifyEvent _ATL_PROP_NOTIFY_EVENT_CLASS;
  298.  
  299. //////////////////////////////////////////////////////////////////////////////
  300. // ATL Persistence
  301.  
  302. struct ATL_PROPMAP_ENTRY
  303. {
  304.     LPCOLESTR szDesc;
  305.     DISPID dispid;
  306.     const CLSID* pclsidPropPage;
  307.     const IID* piidDispatch;
  308.     DWORD dwOffsetData;
  309.     DWORD dwSizeData;
  310.     VARTYPE vt;
  311. };
  312.  
  313. // This one is DEPRECATED and is used for ATL 2.X controls
  314. // it includes an implicit m_sizeExtent
  315. #define BEGIN_PROPERTY_MAP(theClass) \
  316.     typedef _ATL_PROP_NOTIFY_EVENT_CLASS __ATL_PROP_NOTIFY_EVENT_CLASS; \
  317.     typedef theClass _PropMapClass; \
  318.     static ATL_PROPMAP_ENTRY* GetPropertyMap()\
  319.     {\
  320.         static ATL_PROPMAP_ENTRY pPropMap[] = \
  321.         { \
  322.             {OLESTR("_cx"), 0, &CLSID_NULL, NULL, offsetof(_PropMapClass, m_sizeExtent.cx), sizeof(long), VT_UI4}, \
  323.             {OLESTR("_cy"), 0, &CLSID_NULL, NULL, offsetof(_PropMapClass, m_sizeExtent.cy), sizeof(long), VT_UI4},
  324.  
  325. // This one can be used on any type of object, but does not
  326. // include the implicit m_sizeExtent
  327. #define BEGIN_PROP_MAP(theClass) \
  328.     typedef _ATL_PROP_NOTIFY_EVENT_CLASS __ATL_PROP_NOTIFY_EVENT_CLASS; \
  329.     typedef theClass _PropMapClass; \
  330.     static ATL_PROPMAP_ENTRY* GetPropertyMap()\
  331.     {\
  332.         static ATL_PROPMAP_ENTRY pPropMap[] = \
  333.         {
  334.  
  335. #define PROP_ENTRY(szDesc, dispid, clsid) \
  336.         {OLESTR(szDesc), dispid, &clsid, &IID_IDispatch, 0, 0, 0},
  337.  
  338. #define PROP_ENTRY_EX(szDesc, dispid, clsid, iidDispatch) \
  339.         {OLESTR(szDesc), dispid, &clsid, &iidDispatch, 0, 0, 0},
  340.  
  341. #define PROP_PAGE(clsid) \
  342.         {NULL, NULL, &clsid, &IID_NULL, 0, 0, 0},
  343.  
  344. #define PROP_DATA_ENTRY(szDesc, member, vt) \
  345.         {OLESTR(szDesc), 0, &CLSID_NULL, NULL, offsetof(_PropMapClass, member), sizeof(((_PropMapClass*)0)->member), vt},
  346.  
  347. #define END_PROPERTY_MAP() \
  348.             {NULL, 0, NULL, &IID_NULL, 0, 0, 0} \
  349.         }; \
  350.         return pPropMap; \
  351.     }
  352.  
  353. #define END_PROP_MAP() \
  354.             {NULL, 0, NULL, &IID_NULL, 0, 0, 0} \
  355.         }; \
  356.         return pPropMap; \
  357.     }
  358.  
  359.  
  360. #ifdef _ATL_DLL
  361. ATLAPI AtlIPersistStreamInit_Load(LPSTREAM pStm, ATL_PROPMAP_ENTRY* pMap, void* pThis, IUnknown* pUnk);
  362. #else
  363. ATLINLINE ATLAPI AtlIPersistStreamInit_Load(LPSTREAM pStm, ATL_PROPMAP_ENTRY* pMap, void* pThis, IUnknown* pUnk)
  364. {
  365.     ATLASSERT(pMap != NULL);
  366.     HRESULT hr = S_OK;
  367.     DWORD dwVer;
  368.     hr = pStm->Read(&dwVer, sizeof(DWORD), NULL);
  369.     if (FAILED(hr))
  370.         return hr;
  371.     if (dwVer > _ATL_VER)
  372.         return E_FAIL;
  373.  
  374.     CComPtr<IDispatch> pDispatch;
  375.     const IID* piidOld = NULL;
  376.     for (int i = 0; pMap[i].pclsidPropPage != NULL; i++)
  377.     {
  378.         if (pMap[i].szDesc == NULL)
  379.             continue;
  380.  
  381.         // check if raw data entry
  382.         if (pMap[i].dwSizeData != 0)
  383.         {
  384.             void* pData = (void*) (pMap[i].dwOffsetData + (DWORD)pThis);
  385.             hr = pStm->Read(pData, pMap[i].dwSizeData, NULL);
  386.             if (FAILED(hr))
  387.                 return hr;
  388.             continue;
  389.         }
  390.  
  391.         CComVariant var;
  392.  
  393.         hr = var.ReadFromStream(pStm);
  394.         if (FAILED(hr))
  395.             break;
  396.  
  397.         if (pMap[i].piidDispatch != piidOld)
  398.         {
  399.             pDispatch.Release();
  400.             if (FAILED(pUnk->QueryInterface(*pMap[i].piidDispatch, (void**)&pDispatch)))
  401.             {
  402.                 ATLTRACE2(atlTraceCOM, 0, _T("Failed to get a dispatch pointer for property #%i\n"), i);
  403.                 hr = E_FAIL;
  404.                 break;
  405.             }
  406.             piidOld = pMap[i].piidDispatch;
  407.         }
  408.  
  409.         if (FAILED(CComDispatchDriver::PutProperty(pDispatch, pMap[i].dispid, &var)))
  410.         {
  411.             ATLTRACE2(atlTraceCOM, 0, _T("Invoked failed on DISPID %x\n"), pMap[i].dispid);
  412.             hr = E_FAIL;
  413.             break;
  414.         }
  415.     }
  416.     return hr;
  417. }
  418. #endif //_ATL_DLL
  419.  
  420. #ifdef _ATL_DLL
  421. ATLAPI AtlIPersistStreamInit_Save(LPSTREAM pStm, BOOL fClearDirty, ATL_PROPMAP_ENTRY* pMap, void* pThis, IUnknown* pUnk);
  422. #else
  423. ATLINLINE ATLAPI AtlIPersistStreamInit_Save(LPSTREAM pStm,
  424.     BOOL /* fClearDirty */, ATL_PROPMAP_ENTRY* pMap,
  425.     void* pThis, IUnknown* pUnk)
  426. {
  427.     ATLASSERT(pMap != NULL);
  428.     DWORD dw = _ATL_VER;
  429.     HRESULT hr = pStm->Write(&dw, sizeof(DWORD), NULL);
  430.     if (FAILED(hr))
  431.         return hr;
  432.  
  433.     CComPtr<IDispatch> pDispatch;
  434.     const IID* piidOld = NULL;
  435.     for (int i = 0; pMap[i].pclsidPropPage != NULL; i++)
  436.     {
  437.         if (pMap[i].szDesc == NULL)
  438.             continue;
  439.  
  440.         // check if raw data entry
  441.         if (pMap[i].dwSizeData != 0)
  442.         {
  443.             void* pData = (void*) (pMap[i].dwOffsetData + (DWORD)pThis);
  444.             hr = pStm->Write(pData, pMap[i].dwSizeData, NULL);
  445.             if (FAILED(hr))
  446.                 return hr;
  447.             continue;
  448.         }
  449.  
  450.         CComVariant var;
  451.         if (pMap[i].piidDispatch != piidOld)
  452.         {
  453.             pDispatch.Release();
  454.             if (FAILED(pUnk->QueryInterface(*pMap[i].piidDispatch, (void**)&pDispatch)))
  455.             {
  456.                 ATLTRACE2(atlTraceCOM, 0, _T("Failed to get a dispatch pointer for property #%i\n"), i);
  457.                 hr = E_FAIL;
  458.                 break;
  459.             }
  460.             piidOld = pMap[i].piidDispatch;
  461.         }
  462.  
  463.         if (FAILED(CComDispatchDriver::GetProperty(pDispatch, pMap[i].dispid, &var)))
  464.         {
  465.             ATLTRACE2(atlTraceCOM, 0, _T("Invoked failed on DISPID %x\n"), pMap[i].dispid);
  466.             hr = E_FAIL;
  467.             break;
  468.         }
  469.  
  470.         hr = var.WriteToStream(pStm);
  471.         if (FAILED(hr))
  472.             break;
  473.     }
  474.     return hr;
  475. }
  476. #endif //_ATL_DLL
  477.  
  478.  
  479. #ifdef _ATL_DLL
  480. ATLAPI AtlIPersistPropertyBag_Load(LPPROPERTYBAG pPropBag, LPERRORLOG pErrorLog, ATL_PROPMAP_ENTRY* pMap, void* pThis, IUnknown* pUnk);
  481. #else
  482. ATLINLINE ATLAPI AtlIPersistPropertyBag_Load(LPPROPERTYBAG pPropBag, LPERRORLOG pErrorLog, ATL_PROPMAP_ENTRY* pMap, void* pThis, IUnknown* pUnk)
  483. {
  484.     USES_CONVERSION;
  485.     CComPtr<IDispatch> pDispatch;
  486.     const IID* piidOld = NULL;
  487.     for (int i = 0; pMap[i].pclsidPropPage != NULL; i++)
  488.     {
  489.         if (pMap[i].szDesc == NULL)
  490.             continue;
  491.  
  492.         CComVariant var;
  493.  
  494.         // If raw entry skip it - we don't handle it for property bags just yet
  495.         if (pMap[i].dwSizeData != 0)
  496.         {
  497.             void* pData = (void*) (pMap[i].dwOffsetData + (DWORD)pThis);
  498.             HRESULT hr = pPropBag->Read(pMap[i].szDesc, &var, pErrorLog);
  499.             if (SUCCEEDED(hr))
  500.             {
  501.                 // check the type - we only deal with limited set
  502.                 switch (pMap[i].vt)
  503.                 {
  504.                 case VT_UI1:
  505.                 case VT_I1:
  506.                     *((BYTE*)pData) = var.bVal;
  507.                     break;
  508.                 case VT_BOOL:
  509.                     *((VARIANT_BOOL*)pData) = var.boolVal;
  510.                     break;
  511.                 case VT_UI2:
  512.                     *((short*)pData) = var.iVal;
  513.                     break;
  514.                 case VT_UI4:
  515.                 case VT_INT:
  516.                 case VT_UINT:
  517.                     *((long*)pData) = var.lVal;
  518.                     break;
  519.                 }
  520.             }
  521.             continue;
  522.         }
  523.  
  524.         if (pMap[i].piidDispatch != piidOld)
  525.         {
  526.             pDispatch.Release();
  527.             if (FAILED(pUnk->QueryInterface(*pMap[i].piidDispatch, (void**)&pDispatch)))
  528.             {
  529.                 ATLTRACE2(atlTraceCOM, 0, _T("Failed to get a dispatch pointer for property #%i\n"), i);
  530.                 return E_FAIL;
  531.             }
  532.             piidOld = pMap[i].piidDispatch;
  533.         }
  534.  
  535.         if (FAILED(CComDispatchDriver::GetProperty(pDispatch, pMap[i].dispid, &var)))
  536.         {
  537.             ATLTRACE2(atlTraceCOM, 0, _T("Invoked failed on DISPID %x\n"), pMap[i].dispid);
  538.             return E_FAIL;
  539.         }
  540.  
  541.         HRESULT hr = pPropBag->Read(pMap[i].szDesc, &var, pErrorLog);
  542.         if (FAILED(hr))
  543.         {
  544.             if (hr == E_INVALIDARG)
  545.             {
  546.                 ATLTRACE2(atlTraceCOM, 0, _T("Property %s not in Bag\n"), OLE2CT(pMap[i].szDesc));
  547.             }
  548.             else
  549.             {
  550.                 // Many containers return different ERROR values for Member not found
  551.                 ATLTRACE2(atlTraceCOM, 0, _T("Error attempting to read Property %s from PropertyBag \n"), OLE2CT(pMap[i].szDesc));
  552.             }
  553.             continue;
  554.         }
  555.  
  556.         if (FAILED(CComDispatchDriver::PutProperty(pDispatch, pMap[i].dispid, &var)))
  557.         {
  558.             ATLTRACE2(atlTraceCOM, 0, _T("Invoked failed on DISPID %x\n"), pMap[i].dispid);
  559.             return E_FAIL;
  560.         }
  561.     }
  562.     return S_OK;
  563. }
  564. #endif //_ATL_DLL
  565.  
  566. #ifdef _ATL_DLL
  567. ATLAPI AtlIPersistPropertyBag_Save(LPPROPERTYBAG pPropBag, BOOL fClearDirty, BOOL fSaveAllProperties, ATL_PROPMAP_ENTRY* pMap, void* pThis, IUnknown* pUnk);
  568. #else
  569. ATLINLINE ATLAPI AtlIPersistPropertyBag_Save(LPPROPERTYBAG pPropBag,
  570.     BOOL /* fClearDirty */, BOOL /* fSaveAllProperties */,
  571.     ATL_PROPMAP_ENTRY* pMap, void* pThis, IUnknown* pUnk)
  572. {
  573.     if (pPropBag == NULL)
  574.     {
  575.         ATLTRACE2(atlTraceCOM, 0, _T("PropBag pointer passed in was invalid\n"));
  576.         return E_POINTER;
  577.     }
  578.  
  579.     CComPtr<IDispatch> pDispatch;
  580.     const IID* piidOld = NULL;
  581.     for (int i = 0; pMap[i].pclsidPropPage != NULL; i++)
  582.     {
  583.         if (pMap[i].szDesc == NULL)
  584.             continue;
  585.  
  586.         CComVariant var;
  587.  
  588.         // If raw entry skip it - we don't handle it for property bags just yet
  589.         if (pMap[i].dwSizeData != 0)
  590.         {
  591.             void* pData = (void*) (pMap[i].dwOffsetData + (DWORD)pThis);
  592.             // check the type - we only deal with limited set
  593.             bool bTypeOK = false;
  594.             switch (pMap[i].vt)
  595.             {
  596.             case VT_UI1:
  597.             case VT_I1:
  598.                 var.bVal = *((BYTE*)pData);
  599.                 bTypeOK = true;
  600.                 break;
  601.             case VT_BOOL:
  602.                 var.boolVal = *((VARIANT_BOOL*)pData);
  603.                 bTypeOK = true;
  604.                 break;
  605.             case VT_UI2:
  606.                 var.iVal = *((short*)pData);
  607.                 bTypeOK = true;
  608.                 break;
  609.             case VT_UI4:
  610.             case VT_INT:
  611.             case VT_UINT:
  612.                 var.lVal = *((long*)pData);
  613.                 bTypeOK = true;
  614.                 break;
  615.             }
  616.             if (bTypeOK)
  617.             {
  618.                 var.vt = pMap[i].vt;
  619.                 HRESULT hr = pPropBag->Write(pMap[i].szDesc, &var);
  620.                 if (FAILED(hr))
  621.                     return hr;
  622.             }
  623.             continue;
  624.         }
  625.  
  626.         if (pMap[i].piidDispatch != piidOld)
  627.         {
  628.             pDispatch.Release();
  629.             if (FAILED(pUnk->QueryInterface(*pMap[i].piidDispatch, (void**)&pDispatch)))
  630.             {
  631.                 ATLTRACE2(atlTraceCOM, 0, _T("Failed to get a dispatch pointer for property #%i\n"), i);
  632.                 return E_FAIL;
  633.             }
  634.             piidOld = pMap[i].piidDispatch;
  635.         }
  636.  
  637.         if (FAILED(CComDispatchDriver::GetProperty(pDispatch, pMap[i].dispid, &var)))
  638.         {
  639.             ATLTRACE2(atlTraceCOM, 0, _T("Invoked failed on DISPID %x\n"), pMap[i].dispid);
  640.             return E_FAIL;
  641.         }
  642.  
  643.         if (var.vt == VT_UNKNOWN || var.vt == VT_DISPATCH)
  644.         {
  645.             if (var.punkVal == NULL)
  646.             {
  647.                 ATLTRACE2(atlTraceCOM, 0, _T("Warning skipping empty IUnknown in Save\n"));
  648.                 continue;
  649.             }
  650.         }
  651.  
  652.         HRESULT hr = pPropBag->Write(pMap[i].szDesc, &var);
  653.         if (FAILED(hr))
  654.             return hr;
  655.     }
  656.     return S_OK;
  657. }
  658. #endif //_ATL_DLL
  659.  
  660.  
  661. //////////////////////////////////////////////////////////////////////////////
  662. // IPersistStreamInitImpl
  663. template <class T>
  664. class ATL_NO_VTABLE IPersistStreamInitImpl : public IPersistStreamInit
  665. {
  666. public:
  667.     // IPersist
  668.     STDMETHOD(GetClassID)(CLSID *pClassID)
  669.     {
  670.         ATLTRACE2(atlTraceCOM, 0, _T("IPersistStreamInitImpl::GetClassID\n"));
  671.         *pClassID = T::GetObjectCLSID();
  672.         return S_OK;
  673.     }
  674.  
  675.     // IPersistStream
  676.     STDMETHOD(IsDirty)()
  677.     {
  678.         ATLTRACE2(atlTraceCOM, 0, _T("IPersistStreamInitImpl::IsDirty\n"));
  679.         T* pT = static_cast<T*>(this);
  680.         return (pT->m_bRequiresSave) ? S_OK : S_FALSE;
  681.     }
  682.     STDMETHOD(Load)(LPSTREAM pStm)
  683.     {
  684.         ATLTRACE2(atlTraceCOM, 0, _T("IPersistStreamInitImpl::Load\n"));
  685.         T* pT = static_cast<T*>(this);
  686.         return pT->IPersistStreamInit_Load(pStm, T::GetPropertyMap());
  687.     }
  688.     STDMETHOD(Save)(LPSTREAM pStm, BOOL fClearDirty)
  689.     {
  690.         T* pT = static_cast<T*>(this);
  691.         ATLTRACE2(atlTraceCOM, 0, _T("IPersistStreamInitImpl::Save\n"));
  692.         return pT->IPersistStreamInit_Save(pStm, fClearDirty, T::GetPropertyMap());
  693.     }
  694.     STDMETHOD(GetSizeMax)(ULARGE_INTEGER FAR* /* pcbSize */)
  695.     {
  696.         ATLTRACENOTIMPL(_T("IPersistStreamInitImpl::GetSizeMax"));
  697.     }
  698.  
  699.     // IPersistStreamInit
  700.     STDMETHOD(InitNew)()
  701.     {
  702.         ATLTRACE2(atlTraceCOM, 0, _T("IPersistStreamInitImpl::InitNew\n"));
  703.         return S_OK;
  704.     }
  705.  
  706.     HRESULT IPersistStreamInit_Load(LPSTREAM pStm, ATL_PROPMAP_ENTRY* pMap)
  707.     {
  708.         T* pT = static_cast<T*>(this);
  709.         HRESULT hr = AtlIPersistStreamInit_Load(pStm, pMap, pT, pT->GetUnknown());
  710.         if (SUCCEEDED(hr))
  711.             pT->m_bRequiresSave = FALSE;
  712.         return hr;
  713.  
  714.     }
  715.     HRESULT IPersistStreamInit_Save(LPSTREAM pStm, BOOL fClearDirty, ATL_PROPMAP_ENTRY* pMap)
  716.     {
  717.         T* pT = static_cast<T*>(this);
  718.         return AtlIPersistStreamInit_Save(pStm, fClearDirty, pMap, pT, pT->GetUnknown());
  719.     }
  720. };
  721.  
  722. //////////////////////////////////////////////////////////////////////////////
  723. // IPersistStorageImpl
  724. template <class T>
  725. class ATL_NO_VTABLE IPersistStorageImpl : public IPersistStorage
  726. {
  727. public:
  728.     // IPersist
  729.     STDMETHOD(GetClassID)(CLSID *pClassID)
  730.     {
  731.         ATLTRACE2(atlTraceCOM, 0, _T("IPersistStorageImpl::GetClassID\n"));
  732.         *pClassID = T::GetObjectCLSID();
  733.         return S_OK;
  734.     }
  735.  
  736.     // IPersistStorage
  737.     STDMETHOD(IsDirty)(void)
  738.     {
  739.         ATLTRACE2(atlTraceCOM, 0, _T("IPersistStorageImpl::IsDirty\n"));
  740.         CComPtr<IPersistStreamInit> p;
  741.         p.p = IPSI_GetIPersistStreamInit();
  742.         return (p != NULL) ? p->IsDirty() : E_FAIL;
  743.     }
  744.     STDMETHOD(InitNew)(IStorage*)
  745.     {
  746.         ATLTRACE2(atlTraceCOM, 0, _T("IPersistStorageImpl::InitNew\n"));
  747.         CComPtr<IPersistStreamInit> p;
  748.         p.p = IPSI_GetIPersistStreamInit();
  749.         return (p != NULL) ? p->InitNew() : E_FAIL;
  750.     }
  751.     STDMETHOD(Load)(IStorage* pStorage)
  752.     {
  753.         ATLTRACE2(atlTraceCOM, 0, _T("IPersistStorageImpl::Load\n"));
  754.         CComPtr<IPersistStreamInit> p;
  755.         p.p = IPSI_GetIPersistStreamInit();
  756.         HRESULT hr = E_FAIL;
  757.         if (p != NULL)
  758.         {
  759.             CComPtr<IStream> spStream;
  760.             hr = pStorage->OpenStream(OLESTR("Contents"), NULL,
  761.                 STGM_DIRECT | STGM_SHARE_EXCLUSIVE, 0, &spStream);
  762.             if (SUCCEEDED(hr))
  763.                 hr = p->Load(spStream);
  764.         }
  765.         return hr;
  766.     }
  767.     STDMETHOD(Save)(IStorage* pStorage, BOOL fSameAsLoad)
  768.     {
  769.         ATLTRACE2(atlTraceCOM, 0, _T("IPersistStorageImpl::Save\n"));
  770.         CComPtr<IPersistStreamInit> p;
  771.         p.p = IPSI_GetIPersistStreamInit();
  772.         HRESULT hr = E_FAIL;
  773.         if (p != NULL)
  774.         {
  775.             CComPtr<IStream> spStream;
  776.             static LPCOLESTR vszContents = OLESTR("Contents");
  777.             hr = pStorage->CreateStream(vszContents,
  778.                 STGM_READWRITE | STGM_SHARE_EXCLUSIVE | STGM_CREATE,
  779.                 0, 0, &spStream);
  780.             if (SUCCEEDED(hr))
  781.                 hr = p->Save(spStream, fSameAsLoad);
  782.         }
  783.         return hr;
  784.     }
  785.     STDMETHOD(SaveCompleted)(IStorage* /* pStorage */)
  786.     {
  787.         ATLTRACE2(atlTraceCOM, 0, _T("IPersistStorageImpl::SaveCompleted\n"));
  788.         return S_OK;
  789.     }
  790.     STDMETHOD(HandsOffStorage)(void)
  791.     {
  792.         ATLTRACE2(atlTraceCOM, 0, _T("IPersistStorageImpl::HandsOffStorage\n"));
  793.         return S_OK;
  794.     }
  795. private:
  796.     IPersistStreamInit* IPSI_GetIPersistStreamInit();
  797. };
  798.  
  799. template <class T>
  800. IPersistStreamInit* IPersistStorageImpl<T>::IPSI_GetIPersistStreamInit()
  801. {
  802.     T* pT = static_cast<T*>(this);
  803.     IPersistStreamInit* p;
  804.     if (FAILED(pT->GetUnknown()->QueryInterface(IID_IPersistStreamInit, (void**)&p)))
  805.         pT->_InternalQueryInterface(IID_IPersistStreamInit, (void**)&p);
  806.     return p;
  807. }
  808.  
  809.  
  810. //////////////////////////////////////////////////////////////////////////////
  811. // IPersistPropertyBagImpl
  812. template <class T>
  813. class ATL_NO_VTABLE IPersistPropertyBagImpl : public IPersistPropertyBag
  814. {
  815. public:
  816.     // IPersist
  817.     STDMETHOD(GetClassID)(CLSID *pClassID)
  818.     {
  819.         ATLTRACE2(atlTraceCOM, 0, _T("IPersistPropertyBagImpl::GetClassID\n"));
  820.         *pClassID = T::GetObjectCLSID();
  821.         return S_OK;
  822.     }
  823.  
  824.     // IPersistPropertyBag
  825.     //
  826.     STDMETHOD(InitNew)()
  827.     {
  828.         ATLTRACE2(atlTraceCOM, 0, _T("IPersistPropertyBagImpl::InitNew\n"));
  829.         return S_OK;
  830.     }
  831.     STDMETHOD(Load)(LPPROPERTYBAG pPropBag, LPERRORLOG pErrorLog)
  832.     {
  833.         ATLTRACE2(atlTraceCOM, 0, _T("IPersistPropertyBagImpl::Load\n"));
  834.         T* pT = static_cast<T*>(this);
  835.         ATL_PROPMAP_ENTRY* pMap = T::GetPropertyMap();
  836.         ATLASSERT(pMap != NULL);
  837.         return pT->IPersistPropertyBag_Load(pPropBag, pErrorLog, pMap);
  838.     }
  839.     STDMETHOD(Save)(LPPROPERTYBAG pPropBag, BOOL fClearDirty, BOOL fSaveAllProperties)
  840.     {
  841.         ATLTRACE2(atlTraceCOM, 0, _T("IPersistPropertyBagImpl::Save\n"));
  842.         T* pT = static_cast<T*>(this);
  843.         ATL_PROPMAP_ENTRY* pMap = T::GetPropertyMap();
  844.         ATLASSERT(pMap != NULL);
  845.         return pT->IPersistPropertyBag_Save(pPropBag, fClearDirty, fSaveAllProperties, pMap);
  846.     }
  847.     HRESULT IPersistPropertyBag_Load(LPPROPERTYBAG pPropBag, LPERRORLOG pErrorLog, ATL_PROPMAP_ENTRY* pMap)
  848.     {
  849.         T* pT = static_cast<T*>(this);
  850.         HRESULT hr = AtlIPersistPropertyBag_Load(pPropBag, pErrorLog, pMap, pT, pT->GetUnknown());
  851.         if (SUCCEEDED(hr))
  852.             pT->m_bRequiresSave = FALSE;
  853.         return hr;
  854.     }
  855.     HRESULT IPersistPropertyBag_Save(LPPROPERTYBAG pPropBag, BOOL fClearDirty, BOOL fSaveAllProperties, ATL_PROPMAP_ENTRY* pMap)
  856.     {
  857.         T* pT = static_cast<T*>(this);
  858.         return AtlIPersistPropertyBag_Save(pPropBag, fClearDirty, fSaveAllProperties, pMap, pT, pT->GetUnknown());
  859.     }
  860. };
  861.  
  862. //////////////////////////////////////////////////////////////////////////////
  863. // CSecurityDescriptor
  864. class CSecurityDescriptor
  865. {
  866. public:
  867.     CSecurityDescriptor();
  868.     ~CSecurityDescriptor();
  869.  
  870. public:
  871.     HRESULT Attach(PSECURITY_DESCRIPTOR pSelfRelativeSD);
  872.     HRESULT AttachObject(HANDLE hObject);
  873.     HRESULT Initialize();
  874.     HRESULT InitializeFromProcessToken(BOOL bDefaulted = FALSE);
  875.     HRESULT InitializeFromThreadToken(BOOL bDefaulted = FALSE, BOOL bRevertToProcessToken = TRUE);
  876.     HRESULT SetOwner(PSID pOwnerSid, BOOL bDefaulted = FALSE);
  877.     HRESULT SetGroup(PSID pGroupSid, BOOL bDefaulted = FALSE);
  878.     HRESULT Allow(LPCTSTR pszPrincipal, DWORD dwAccessMask);
  879.     HRESULT Deny(LPCTSTR pszPrincipal, DWORD dwAccessMask);
  880.     HRESULT Revoke(LPCTSTR pszPrincipal);
  881.  
  882.     // utility functions
  883.     // Any PSID you get from these functions should be free()ed
  884.     static HRESULT SetPrivilege(LPCTSTR Privilege, BOOL bEnable = TRUE, HANDLE hToken = NULL);
  885.     static HRESULT GetTokenSids(HANDLE hToken, PSID* ppUserSid, PSID* ppGroupSid);
  886.     static HRESULT GetProcessSids(PSID* ppUserSid, PSID* ppGroupSid = NULL);
  887.     static HRESULT GetThreadSids(PSID* ppUserSid, PSID* ppGroupSid = NULL, BOOL bOpenAsSelf = FALSE);
  888.     static HRESULT CopyACL(PACL pDest, PACL pSrc);
  889.     static HRESULT GetCurrentUserSID(PSID *ppSid);
  890.     static HRESULT GetPrincipalSID(LPCTSTR pszPrincipal, PSID *ppSid);
  891.     static HRESULT AddAccessAllowedACEToACL(PACL *Acl, LPCTSTR pszPrincipal, DWORD dwAccessMask);
  892.     static HRESULT AddAccessDeniedACEToACL(PACL *Acl, LPCTSTR pszPrincipal, DWORD dwAccessMask);
  893.     static HRESULT RemovePrincipalFromACL(PACL Acl, LPCTSTR pszPrincipal);
  894.  
  895.     operator PSECURITY_DESCRIPTOR()
  896.     {
  897.         return m_pSD;
  898.     }
  899.  
  900. public:
  901.     PSECURITY_DESCRIPTOR m_pSD;
  902.     PSID m_pOwner;
  903.     PSID m_pGroup;
  904.     PACL m_pDACL;
  905.     PACL m_pSACL;
  906. };
  907.  
  908. inline CSecurityDescriptor::CSecurityDescriptor()
  909. {
  910.     m_pSD = NULL;
  911.     m_pOwner = NULL;
  912.     m_pGroup = NULL;
  913.     m_pDACL = NULL;
  914.     m_pSACL= NULL;
  915. }
  916.  
  917. inline CSecurityDescriptor::~CSecurityDescriptor()
  918. {
  919.     if (m_pSD)
  920.         delete m_pSD;
  921.     if (m_pOwner)
  922.         free(m_pOwner);
  923.     if (m_pGroup)
  924.         free(m_pGroup);
  925.     if (m_pDACL)
  926.         free(m_pDACL);
  927.     if (m_pSACL)
  928.         free(m_pSACL);
  929. }
  930.  
  931. inline HRESULT CSecurityDescriptor::Initialize()
  932. {
  933.     if (m_pSD)
  934.     {
  935.         delete m_pSD;
  936.         m_pSD = NULL;
  937.     }
  938.     if (m_pOwner)
  939.     {
  940.         free(m_pOwner);
  941.         m_pOwner = NULL;
  942.     }
  943.     if (m_pGroup)
  944.     {
  945.         free(m_pGroup);
  946.         m_pGroup = NULL;
  947.     }
  948.     if (m_pDACL)
  949.     {
  950.         free(m_pDACL);
  951.         m_pDACL = NULL;
  952.     }
  953.     if (m_pSACL)
  954.     {
  955.         free(m_pSACL);
  956.         m_pSACL = NULL;
  957.     }
  958.  
  959.     ATLTRY(m_pSD = new SECURITY_DESCRIPTOR);
  960.     if (m_pSD == NULL)
  961.         return E_OUTOFMEMORY;
  962.  
  963.     if (!InitializeSecurityDescriptor(m_pSD, SECURITY_DESCRIPTOR_REVISION))
  964.     {
  965.         HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
  966.         delete m_pSD;
  967.         m_pSD = NULL;
  968.         ATLASSERT(FALSE);
  969.         return hr;
  970.     }
  971.     // Set the DACL to allow EVERYONE
  972.     SetSecurityDescriptorDacl(m_pSD, TRUE, NULL, FALSE);
  973.     return S_OK;
  974. }
  975.  
  976. inline HRESULT CSecurityDescriptor::InitializeFromProcessToken(BOOL bDefaulted)
  977. {
  978.     PSID pUserSid = NULL;
  979.     PSID pGroupSid = NULL;
  980.     HRESULT hr;
  981.  
  982.     Initialize();
  983.     hr = GetProcessSids(&pUserSid, &pGroupSid);
  984.     if (SUCCEEDED(hr))
  985.     {
  986.         hr = SetOwner(pUserSid, bDefaulted);
  987.         if (SUCCEEDED(hr))
  988.             hr = SetGroup(pGroupSid, bDefaulted);
  989.     }
  990.     if (pUserSid != NULL)
  991.         free(pUserSid);
  992.     if (pGroupSid != NULL)
  993.         free(pGroupSid);
  994.     return hr;
  995. }
  996.  
  997. inline HRESULT CSecurityDescriptor::InitializeFromThreadToken(BOOL bDefaulted, BOOL bRevertToProcessToken)
  998. {
  999.     PSID pUserSid = NULL;
  1000.     PSID pGroupSid = NULL;
  1001.     HRESULT hr;
  1002.  
  1003.     Initialize();
  1004.     hr = GetThreadSids(&pUserSid, &pGroupSid);
  1005.     if (HRESULT_CODE(hr) == ERROR_NO_TOKEN && bRevertToProcessToken)
  1006.         hr = GetProcessSids(&pUserSid, &pGroupSid);
  1007.     if (SUCCEEDED(hr))
  1008.     {
  1009.         hr = SetOwner(pUserSid, bDefaulted);
  1010.         if (SUCCEEDED(hr))
  1011.             hr = SetGroup(pGroupSid, bDefaulted);
  1012.     }
  1013.     if (pUserSid != NULL)
  1014.         free(pUserSid);
  1015.     if (pGroupSid != NULL)
  1016.         free(pGroupSid);
  1017.     return hr;
  1018. }
  1019.  
  1020. inline HRESULT CSecurityDescriptor::SetOwner(PSID pOwnerSid, BOOL bDefaulted)
  1021. {
  1022.     ATLASSERT(m_pSD);
  1023.  
  1024.     // Mark the SD as having no owner
  1025.     if (!SetSecurityDescriptorOwner(m_pSD, NULL, bDefaulted))
  1026.     {
  1027.         HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
  1028.         ATLASSERT(FALSE);
  1029.         return hr;
  1030.     }
  1031.  
  1032.     if (m_pOwner)
  1033.     {
  1034.         free(m_pOwner);
  1035.         m_pOwner = NULL;
  1036.     }
  1037.  
  1038.     // If they asked for no owner don't do the copy
  1039.     if (pOwnerSid == NULL)
  1040.         return S_OK;
  1041.  
  1042.     // Make a copy of the Sid for the return value
  1043.     DWORD dwSize = GetLengthSid(pOwnerSid);
  1044.  
  1045.     m_pOwner = (PSID) malloc(dwSize);
  1046.     if (m_pOwner == NULL)
  1047.         return E_OUTOFMEMORY;
  1048.     if (!CopySid(dwSize, m_pOwner, pOwnerSid))
  1049.     {
  1050.         HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
  1051.         ATLASSERT(FALSE);
  1052.         free(m_pOwner);
  1053.         m_pOwner = NULL;
  1054.         return hr;
  1055.     }
  1056.  
  1057.     ATLASSERT(IsValidSid(m_pOwner));
  1058.  
  1059.     if (!SetSecurityDescriptorOwner(m_pSD, m_pOwner, bDefaulted))
  1060.     {
  1061.         HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
  1062.         ATLASSERT(FALSE);
  1063.         free(m_pOwner);
  1064.         m_pOwner = NULL;
  1065.         return hr;
  1066.     }
  1067.  
  1068.     return S_OK;
  1069. }
  1070.  
  1071. inline HRESULT CSecurityDescriptor::SetGroup(PSID pGroupSid, BOOL bDefaulted)
  1072. {
  1073.     ATLASSERT(m_pSD);
  1074.  
  1075.     // Mark the SD as having no Group
  1076.     if (!SetSecurityDescriptorGroup(m_pSD, NULL, bDefaulted))
  1077.     {
  1078.         HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
  1079.         ATLASSERT(FALSE);
  1080.         return hr;
  1081.     }
  1082.  
  1083.     if (m_pGroup)
  1084.     {
  1085.         free(m_pGroup);
  1086.         m_pGroup = NULL;
  1087.     }
  1088.  
  1089.     // If they asked for no Group don't do the copy
  1090.     if (pGroupSid == NULL)
  1091.         return S_OK;
  1092.  
  1093.     // Make a copy of the Sid for the return value
  1094.     DWORD dwSize = GetLengthSid(pGroupSid);
  1095.  
  1096.     m_pGroup = (PSID) malloc(dwSize);
  1097.     if (m_pGroup == NULL)
  1098.         return E_OUTOFMEMORY;
  1099.     if (!CopySid(dwSize, m_pGroup, pGroupSid))
  1100.     {
  1101.         HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
  1102.         ATLASSERT(FALSE);
  1103.         free(m_pGroup);
  1104.         m_pGroup = NULL;
  1105.         return hr;
  1106.     }
  1107.  
  1108.     ATLASSERT(IsValidSid(m_pGroup));
  1109.  
  1110.     if (!SetSecurityDescriptorGroup(m_pSD, m_pGroup, bDefaulted))
  1111.     {
  1112.         HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
  1113.         ATLASSERT(FALSE);
  1114.         free(m_pGroup);
  1115.         m_pGroup = NULL;
  1116.         return hr;
  1117.     }
  1118.  
  1119.     return S_OK;
  1120. }
  1121.  
  1122. inline HRESULT CSecurityDescriptor::Allow(LPCTSTR pszPrincipal, DWORD dwAccessMask)
  1123. {
  1124.     HRESULT hr = AddAccessAllowedACEToACL(&m_pDACL, pszPrincipal, dwAccessMask);
  1125.     if (SUCCEEDED(hr))
  1126.         SetSecurityDescriptorDacl(m_pSD, TRUE, m_pDACL, FALSE);
  1127.     return hr;
  1128. }
  1129.  
  1130. inline HRESULT CSecurityDescriptor::Deny(LPCTSTR pszPrincipal, DWORD dwAccessMask)
  1131. {
  1132.     HRESULT hr = AddAccessDeniedACEToACL(&m_pDACL, pszPrincipal, dwAccessMask);
  1133.     if (SUCCEEDED(hr))
  1134.         SetSecurityDescriptorDacl(m_pSD, TRUE, m_pDACL, FALSE);
  1135.     return hr;
  1136. }
  1137.  
  1138. inline HRESULT CSecurityDescriptor::Revoke(LPCTSTR pszPrincipal)
  1139. {
  1140.     HRESULT hr = RemovePrincipalFromACL(m_pDACL, pszPrincipal);
  1141.     if (SUCCEEDED(hr))
  1142.         SetSecurityDescriptorDacl(m_pSD, TRUE, m_pDACL, FALSE);
  1143.     return hr;
  1144. }
  1145.  
  1146. inline HRESULT CSecurityDescriptor::GetProcessSids(PSID* ppUserSid, PSID* ppGroupSid)
  1147. {
  1148.     BOOL bRes;
  1149.     HRESULT hr;
  1150.     HANDLE hToken = NULL;
  1151.     if (ppUserSid)
  1152.         *ppUserSid = NULL;
  1153.     if (ppGroupSid)
  1154.         *ppGroupSid = NULL;
  1155.     bRes = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken);
  1156.     if (!bRes)
  1157.     {
  1158.         // Couldn't open process token
  1159.         hr = HRESULT_FROM_WIN32(GetLastError());
  1160.         ATLASSERT(FALSE);
  1161.         return hr;
  1162.     }
  1163.     hr = GetTokenSids(hToken, ppUserSid, ppGroupSid);
  1164.     CloseHandle(hToken);
  1165.     return hr;
  1166. }
  1167.  
  1168. inline HRESULT CSecurityDescriptor::GetThreadSids(PSID* ppUserSid, PSID* ppGroupSid, BOOL bOpenAsSelf)
  1169. {
  1170.     BOOL bRes;
  1171.     HRESULT hr;
  1172.     HANDLE hToken = NULL;
  1173.     if (ppUserSid)
  1174.         *ppUserSid = NULL;
  1175.     if (ppGroupSid)
  1176.         *ppGroupSid = NULL;
  1177.     bRes = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, bOpenAsSelf, &hToken);
  1178.     if (!bRes)
  1179.     {
  1180.         // Couldn't open thread token
  1181.         hr = HRESULT_FROM_WIN32(GetLastError());
  1182.         return hr;
  1183.     }
  1184.     hr = GetTokenSids(hToken, ppUserSid, ppGroupSid);
  1185.     CloseHandle(hToken);
  1186.     return hr;
  1187. }
  1188.  
  1189. inline HRESULT CSecurityDescriptor::GetTokenSids(HANDLE hToken, PSID* ppUserSid, PSID* ppGroupSid)
  1190. {
  1191.     DWORD dwSize;
  1192.     HRESULT hr;
  1193.     PTOKEN_USER ptkUser = NULL;
  1194.     PTOKEN_PRIMARY_GROUP ptkGroup = NULL;
  1195.  
  1196.     if (ppUserSid)
  1197.         *ppUserSid = NULL;
  1198.     if (ppGroupSid)
  1199.         *ppGroupSid = NULL;
  1200.  
  1201.     if (ppUserSid)
  1202.     {
  1203.         // Get length required for TokenUser by specifying buffer length of 0
  1204.         GetTokenInformation(hToken, TokenUser, NULL, 0, &dwSize);
  1205.         hr = GetLastError();
  1206.         if (hr != ERROR_INSUFFICIENT_BUFFER)
  1207.         {
  1208.             // Expected ERROR_INSUFFICIENT_BUFFER
  1209.             ATLASSERT(FALSE);
  1210.             hr = HRESULT_FROM_WIN32(hr);
  1211.             goto failed;
  1212.         }
  1213.  
  1214.         ptkUser = (TOKEN_USER*) malloc(dwSize);
  1215.         if (ptkUser == NULL)
  1216.         {
  1217.             hr = E_OUTOFMEMORY;
  1218.             goto failed;
  1219.         }
  1220.         // Get Sid of process token.
  1221.         if (!GetTokenInformation(hToken, TokenUser, ptkUser, dwSize, &dwSize))
  1222.         {
  1223.             // Couldn't get user info
  1224.             hr = HRESULT_FROM_WIN32(GetLastError());
  1225.             ATLASSERT(FALSE);
  1226.             goto failed;
  1227.         }
  1228.  
  1229.         // Make a copy of the Sid for the return value
  1230.         dwSize = GetLengthSid(ptkUser->User.Sid);
  1231.  
  1232.         PSID pSid;
  1233.         pSid = (PSID) malloc(dwSize);
  1234.         if (pSid == NULL)
  1235.         {
  1236.             hr = E_OUTOFMEMORY;
  1237.             goto failed;
  1238.         }
  1239.         if (!CopySid(dwSize, pSid, ptkUser->User.Sid))
  1240.         {
  1241.             hr = HRESULT_FROM_WIN32(GetLastError());
  1242.             ATLASSERT(FALSE);
  1243.             goto failed;
  1244.         }
  1245.  
  1246.         ATLASSERT(IsValidSid(pSid));
  1247.         *ppUserSid = pSid;
  1248.         free(ptkUser);
  1249.     }
  1250.     if (ppGroupSid)
  1251.     {
  1252.         // Get length required for TokenPrimaryGroup by specifying buffer length of 0
  1253.         GetTokenInformation(hToken, TokenPrimaryGroup, NULL, 0, &dwSize);
  1254.         hr = GetLastError();
  1255.         if (hr != ERROR_INSUFFICIENT_BUFFER)
  1256.         {
  1257.             // Expected ERROR_INSUFFICIENT_BUFFER
  1258.             ATLASSERT(FALSE);
  1259.             hr = HRESULT_FROM_WIN32(hr);
  1260.             goto failed;
  1261.         }
  1262.  
  1263.         ptkGroup = (TOKEN_PRIMARY_GROUP*) malloc(dwSize);
  1264.         if (ptkGroup == NULL)
  1265.         {
  1266.             hr = E_OUTOFMEMORY;
  1267.             goto failed;
  1268.         }
  1269.         // Get Sid of process token.
  1270.         if (!GetTokenInformation(hToken, TokenPrimaryGroup, ptkGroup, dwSize, &dwSize))
  1271.         {
  1272.             // Couldn't get user info
  1273.             hr = HRESULT_FROM_WIN32(GetLastError());
  1274.             ATLASSERT(FALSE);
  1275.             goto failed;
  1276.         }
  1277.  
  1278.         // Make a copy of the Sid for the return value
  1279.         dwSize = GetLengthSid(ptkGroup->PrimaryGroup);
  1280.  
  1281.         PSID pSid;
  1282.         pSid = (PSID) malloc(dwSize);
  1283.         if (pSid == NULL)
  1284.         {
  1285.             hr = E_OUTOFMEMORY;
  1286.             goto failed;
  1287.         }
  1288.         if (!CopySid(dwSize, pSid, ptkGroup->PrimaryGroup))
  1289.         {
  1290.             hr = HRESULT_FROM_WIN32(GetLastError());
  1291.             ATLASSERT(FALSE);
  1292.             goto failed;
  1293.         }
  1294.  
  1295.         ATLASSERT(IsValidSid(pSid));
  1296.  
  1297.         *ppGroupSid = pSid;
  1298.         free(ptkGroup);
  1299.     }
  1300.  
  1301.     return S_OK;
  1302.  
  1303. failed:
  1304.     if (ptkUser)
  1305.         free(ptkUser);
  1306.     if (ptkGroup)
  1307.         free (ptkGroup);
  1308.     return hr;
  1309. }
  1310.  
  1311.  
  1312. inline HRESULT CSecurityDescriptor::GetCurrentUserSID(PSID *ppSid)
  1313. {
  1314.     HANDLE tkHandle;
  1315.  
  1316.     if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &tkHandle))
  1317.     {
  1318.         TOKEN_USER *tkUser;
  1319.         DWORD tkSize;
  1320.         DWORD sidLength;
  1321.  
  1322.         // Call to get size information for alloc
  1323.         GetTokenInformation(tkHandle, TokenUser, NULL, 0, &tkSize);
  1324.         tkUser = (TOKEN_USER *) malloc(tkSize);
  1325.         if (tkUser == NULL)
  1326.             return E_OUTOFMEMORY;
  1327.  
  1328.         // Now make the real call
  1329.         if (GetTokenInformation(tkHandle, TokenUser, tkUser, tkSize, &tkSize))
  1330.         {
  1331.             sidLength = GetLengthSid(tkUser->User.Sid);
  1332.             *ppSid = (PSID) malloc(sidLength);
  1333.             if (*ppSid == NULL)
  1334.                 return E_OUTOFMEMORY;
  1335.  
  1336.             memcpy(*ppSid, tkUser->User.Sid, sidLength);
  1337.             CloseHandle(tkHandle);
  1338.  
  1339.             free(tkUser);
  1340.             return S_OK;
  1341.         }
  1342.         else
  1343.         {
  1344.             free(tkUser);
  1345.             return HRESULT_FROM_WIN32(GetLastError());
  1346.         }
  1347.     }
  1348.     return HRESULT_FROM_WIN32(GetLastError());
  1349. }
  1350.  
  1351.  
  1352. inline HRESULT CSecurityDescriptor::GetPrincipalSID(LPCTSTR pszPrincipal, PSID *ppSid)
  1353. {
  1354.     HRESULT hr;
  1355.     LPTSTR pszRefDomain = NULL;
  1356.     DWORD dwDomainSize = 0;
  1357.     DWORD dwSidSize = 0;
  1358.     SID_NAME_USE snu;
  1359.  
  1360.     // Call to get size info for alloc
  1361.     LookupAccountName(NULL, pszPrincipal, *ppSid, &dwSidSize, pszRefDomain, &dwDomainSize, &snu);
  1362.  
  1363.     hr = GetLastError();
  1364.     if (hr != ERROR_INSUFFICIENT_BUFFER)
  1365.         return HRESULT_FROM_WIN32(hr);
  1366.  
  1367.     ATLTRY(pszRefDomain = new TCHAR[dwDomainSize]);
  1368.     if (pszRefDomain == NULL)
  1369.         return E_OUTOFMEMORY;
  1370.  
  1371.     *ppSid = (PSID) malloc(dwSidSize);
  1372.     if (*ppSid != NULL)
  1373.     {
  1374.         if (!LookupAccountName(NULL, pszPrincipal, *ppSid, &dwSidSize, pszRefDomain, &dwDomainSize, &snu))
  1375.         {
  1376.             free(*ppSid);
  1377.             *ppSid = NULL;
  1378.             delete[] pszRefDomain;
  1379.             return HRESULT_FROM_WIN32(GetLastError());
  1380.         }
  1381.         delete[] pszRefDomain;
  1382.         return S_OK;
  1383.     }
  1384.     delete[] pszRefDomain;
  1385.     return E_OUTOFMEMORY;
  1386. }
  1387.  
  1388.  
  1389. inline HRESULT CSecurityDescriptor::Attach(PSECURITY_DESCRIPTOR pSelfRelativeSD)
  1390. {
  1391.     PACL    pDACL = NULL;
  1392.     PACL    pSACL = NULL;
  1393.     BOOL    bDACLPresent, bSACLPresent;
  1394.     BOOL    bDefaulted;
  1395.     PACL    m_pDACL = NULL;
  1396.     ACCESS_ALLOWED_ACE* pACE;
  1397.     HRESULT hr;
  1398.     PSID    pUserSid;
  1399.     PSID    pGroupSid;
  1400.  
  1401.     hr = Initialize();
  1402.     if(FAILED(hr))
  1403.         return hr;
  1404.  
  1405.     // get the existing DACL.
  1406.     if (!GetSecurityDescriptorDacl(pSelfRelativeSD, &bDACLPresent, &pDACL, &bDefaulted))
  1407.         goto failed;
  1408.  
  1409.     if (bDACLPresent)
  1410.     {
  1411.         if (pDACL)
  1412.         {
  1413.             // allocate new DACL.
  1414.             m_pDACL = (PACL) malloc(pDACL->AclSize);
  1415.             if (m_pDACL == NULL)
  1416.             {
  1417.                 hr = E_OUTOFMEMORY;
  1418.                 goto failedMemory;
  1419.             }
  1420.  
  1421.             // initialize the DACL
  1422.             if (!InitializeAcl(m_pDACL, pDACL->AclSize, ACL_REVISION))
  1423.                 goto failed;
  1424.  
  1425.             // copy the ACES
  1426.             for (int i = 0; i < pDACL->AceCount; i++)
  1427.             {
  1428.                 if (!GetAce(pDACL, i, (void **)&pACE))
  1429.                     goto failed;
  1430.  
  1431.                 if (!AddAccessAllowedAce(m_pDACL, ACL_REVISION, pACE->Mask, (PSID)&(pACE->SidStart)))
  1432.                     goto failed;
  1433.             }
  1434.  
  1435.             if (!IsValidAcl(m_pDACL))
  1436.                 goto failed;
  1437.         }
  1438.  
  1439.         // set the DACL
  1440.         if (!SetSecurityDescriptorDacl(m_pSD, m_pDACL ? TRUE : FALSE, m_pDACL, bDefaulted))
  1441.             goto failed;
  1442.     }
  1443.  
  1444.     // get the existing SACL.
  1445.     if (!GetSecurityDescriptorSacl(pSelfRelativeSD, &bSACLPresent, &pSACL, &bDefaulted))
  1446.         goto failed;
  1447.  
  1448.     if (bSACLPresent)
  1449.     {
  1450.         if (pSACL)
  1451.         {
  1452.             // allocate new SACL.
  1453.             m_pSACL = (PACL) malloc(pSACL->AclSize);
  1454.             if (m_pSACL == NULL)
  1455.             {
  1456.                 hr = E_OUTOFMEMORY;
  1457.                 goto failedMemory;
  1458.             }
  1459.  
  1460.             // initialize the SACL
  1461.             if (!InitializeAcl(m_pSACL, pSACL->AclSize, ACL_REVISION))
  1462.                 goto failed;
  1463.  
  1464.             // copy the ACES
  1465.             for (int i = 0; i < pSACL->AceCount; i++)
  1466.             {
  1467.                 if (!GetAce(pSACL, i, (void **)&pACE))
  1468.                     goto failed;
  1469.  
  1470.                 if (!AddAccessAllowedAce(m_pSACL, ACL_REVISION, pACE->Mask, (PSID)&(pACE->SidStart)))
  1471.                     goto failed;
  1472.             }
  1473.  
  1474.             if (!IsValidAcl(m_pSACL))
  1475.                 goto failed;
  1476.         }
  1477.  
  1478.         // set the SACL
  1479.         if (!SetSecurityDescriptorSacl(m_pSD, m_pSACL ? TRUE : FALSE, m_pSACL, bDefaulted))
  1480.             goto failed;
  1481.     }
  1482.  
  1483.     if (!GetSecurityDescriptorOwner(m_pSD, &pUserSid, &bDefaulted))
  1484.         goto failed;
  1485.  
  1486.     if (FAILED(SetOwner(pUserSid, bDefaulted)))
  1487.         goto failed;
  1488.  
  1489.     if (!GetSecurityDescriptorGroup(m_pSD, &pGroupSid, &bDefaulted))
  1490.         goto failed;
  1491.  
  1492.     if (FAILED(SetGroup(pGroupSid, bDefaulted)))
  1493.         goto failed;
  1494.  
  1495.     if (!IsValidSecurityDescriptor(m_pSD))
  1496.         goto failed;
  1497.  
  1498.     return hr;
  1499.  
  1500. failed:
  1501.     hr = HRESULT_FROM_WIN32(hr);
  1502.  
  1503. failedMemory:
  1504.     if (m_pDACL)
  1505.     {
  1506.         free(m_pDACL);
  1507.         m_pDACL = NULL;
  1508.     }
  1509.     if (m_pSD)
  1510.     {
  1511.         free(m_pSD);
  1512.         m_pSD = NULL;
  1513.     }
  1514.     return hr;
  1515. }
  1516.  
  1517. inline HRESULT CSecurityDescriptor::AttachObject(HANDLE hObject)
  1518. {
  1519.     HRESULT hr;
  1520.     DWORD dwSize = 0;
  1521.     PSECURITY_DESCRIPTOR pSD = NULL;
  1522.  
  1523.     GetKernelObjectSecurity(hObject, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
  1524.         DACL_SECURITY_INFORMATION, pSD, 0, &dwSize);
  1525.  
  1526.     hr = GetLastError();
  1527.     if (hr != ERROR_INSUFFICIENT_BUFFER)
  1528.         return HRESULT_FROM_WIN32(hr);
  1529.  
  1530.     pSD = (PSECURITY_DESCRIPTOR) malloc(dwSize);
  1531.     if (pSD == NULL)
  1532.         return E_OUTOFMEMORY;
  1533.  
  1534.     if (!GetKernelObjectSecurity(hObject, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
  1535.         DACL_SECURITY_INFORMATION, pSD, dwSize, &dwSize))
  1536.     {
  1537.         hr = HRESULT_FROM_WIN32(GetLastError());
  1538.         free(pSD);
  1539.         return hr;
  1540.     }
  1541.  
  1542.     hr = Attach(pSD);
  1543.     free(pSD);
  1544.     return hr;
  1545. }
  1546.  
  1547.  
  1548. inline HRESULT CSecurityDescriptor::CopyACL(PACL pDest, PACL pSrc)
  1549. {
  1550.     ACL_SIZE_INFORMATION aclSizeInfo;
  1551.     LPVOID pAce;
  1552.     ACE_HEADER *aceHeader;
  1553.  
  1554.     if (pSrc == NULL)
  1555.         return S_OK;
  1556.  
  1557.     if (!GetAclInformation(pSrc, (LPVOID) &aclSizeInfo, sizeof(ACL_SIZE_INFORMATION), AclSizeInformation))
  1558.         return HRESULT_FROM_WIN32(GetLastError());
  1559.  
  1560.     // Copy all of the ACEs to the new ACL
  1561.     for (UINT i = 0; i < aclSizeInfo.AceCount; i++)
  1562.     {
  1563.         if (!GetAce(pSrc, i, &pAce))
  1564.             return HRESULT_FROM_WIN32(GetLastError());
  1565.  
  1566.         aceHeader = (ACE_HEADER *) pAce;
  1567.  
  1568.         if (!AddAce(pDest, ACL_REVISION, 0xffffffff, pAce, aceHeader->AceSize))
  1569.             return HRESULT_FROM_WIN32(GetLastError());
  1570.     }
  1571.  
  1572.     return S_OK;
  1573. }
  1574.  
  1575. inline HRESULT CSecurityDescriptor::AddAccessDeniedACEToACL(PACL *ppAcl, LPCTSTR pszPrincipal, DWORD dwAccessMask)
  1576. {
  1577.     ACL_SIZE_INFORMATION aclSizeInfo;
  1578.     int aclSize;
  1579.     DWORD returnValue;
  1580.     PSID principalSID;
  1581.     PACL oldACL, newACL = NULL;
  1582.  
  1583.     oldACL = *ppAcl;
  1584.  
  1585.     returnValue = GetPrincipalSID(pszPrincipal, &principalSID);
  1586.     if (FAILED(returnValue))
  1587.         return returnValue;
  1588.  
  1589.     aclSizeInfo.AclBytesInUse = 0;
  1590.     if (*ppAcl != NULL)
  1591.         GetAclInformation(oldACL, (LPVOID) &aclSizeInfo, sizeof(ACL_SIZE_INFORMATION), AclSizeInformation);
  1592.  
  1593.     aclSize = aclSizeInfo.AclBytesInUse + sizeof(ACL) + sizeof(ACCESS_DENIED_ACE) + GetLengthSid(principalSID) - sizeof(DWORD);
  1594.  
  1595.     ATLTRY(newACL = (PACL) new BYTE[aclSize]);
  1596.     if (newACL == NULL)
  1597.         return E_OUTOFMEMORY;
  1598.  
  1599.     if (!InitializeAcl(newACL, aclSize, ACL_REVISION))
  1600.     {
  1601.         free(principalSID);
  1602.         return HRESULT_FROM_WIN32(GetLastError());
  1603.     }
  1604.  
  1605.     if (!AddAccessDeniedAce(newACL, ACL_REVISION2, dwAccessMask, principalSID))
  1606.     {
  1607.         free(principalSID);
  1608.         return HRESULT_FROM_WIN32(GetLastError());
  1609.     }
  1610.  
  1611.     returnValue = CopyACL(newACL, oldACL);
  1612.     if (FAILED(returnValue))
  1613.     {
  1614.         free(principalSID);
  1615.         return returnValue;
  1616.     }
  1617.  
  1618.     *ppAcl = newACL;
  1619.  
  1620.     if (oldACL != NULL)
  1621.         free(oldACL);
  1622.     free(principalSID);
  1623.     return S_OK;
  1624. }
  1625.  
  1626.  
  1627. inline HRESULT CSecurityDescriptor::AddAccessAllowedACEToACL(PACL *ppAcl, LPCTSTR pszPrincipal, DWORD dwAccessMask)
  1628. {
  1629.     ACL_SIZE_INFORMATION aclSizeInfo;
  1630.     int aclSize;
  1631.     DWORD returnValue;
  1632.     PSID principalSID;
  1633.     PACL oldACL, newACL = NULL;
  1634.  
  1635.     oldACL = *ppAcl;
  1636.  
  1637.     returnValue = GetPrincipalSID(pszPrincipal, &principalSID);
  1638.     if (FAILED(returnValue))
  1639.         return returnValue;
  1640.  
  1641.     aclSizeInfo.AclBytesInUse = 0;
  1642.     if (*ppAcl != NULL)
  1643.         GetAclInformation(oldACL, (LPVOID) &aclSizeInfo, (DWORD) sizeof(ACL_SIZE_INFORMATION), AclSizeInformation);
  1644.  
  1645.     aclSize = aclSizeInfo.AclBytesInUse + sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(principalSID) - sizeof(DWORD);
  1646.  
  1647.     ATLTRY(newACL = (PACL) new BYTE[aclSize]);
  1648.     if (newACL == NULL)
  1649.         return E_OUTOFMEMORY;
  1650.  
  1651.     if (!InitializeAcl(newACL, aclSize, ACL_REVISION))
  1652.     {
  1653.         free(principalSID);
  1654.         return HRESULT_FROM_WIN32(GetLastError());
  1655.     }
  1656.  
  1657.     returnValue = CopyACL(newACL, oldACL);
  1658.     if (FAILED(returnValue))
  1659.     {
  1660.         free(principalSID);
  1661.         return returnValue;
  1662.     }
  1663.  
  1664.     if (!AddAccessAllowedAce(newACL, ACL_REVISION2, dwAccessMask, principalSID))
  1665.     {
  1666.         free(principalSID);
  1667.         return HRESULT_FROM_WIN32(GetLastError());
  1668.     }
  1669.  
  1670.     *ppAcl = newACL;
  1671.  
  1672.     if (oldACL != NULL)
  1673.         free(oldACL);
  1674.     free(principalSID);
  1675.     return S_OK;
  1676. }
  1677.  
  1678.  
  1679. inline HRESULT CSecurityDescriptor::RemovePrincipalFromACL(PACL pAcl, LPCTSTR pszPrincipal)
  1680. {
  1681.     ACL_SIZE_INFORMATION aclSizeInfo;
  1682.     ULONG i;
  1683.     LPVOID ace;
  1684.     ACCESS_ALLOWED_ACE *accessAllowedAce;
  1685.     ACCESS_DENIED_ACE *accessDeniedAce;
  1686.     SYSTEM_AUDIT_ACE *systemAuditAce;
  1687.     PSID principalSID;
  1688.     DWORD returnValue;
  1689.     ACE_HEADER *aceHeader;
  1690.  
  1691.     returnValue = GetPrincipalSID(pszPrincipal, &principalSID);
  1692.     if (FAILED(returnValue))
  1693.         return returnValue;
  1694.  
  1695.     GetAclInformation(pAcl, (LPVOID) &aclSizeInfo, (DWORD) sizeof(ACL_SIZE_INFORMATION), AclSizeInformation);
  1696.  
  1697.     for (i = 0; i < aclSizeInfo.AceCount; i++)
  1698.     {
  1699.         if (!GetAce(pAcl, i, &ace))
  1700.         {
  1701.             free(principalSID);
  1702.             return HRESULT_FROM_WIN32(GetLastError());
  1703.         }
  1704.  
  1705.         aceHeader = (ACE_HEADER *) ace;
  1706.  
  1707.         if (aceHeader->AceType == ACCESS_ALLOWED_ACE_TYPE)
  1708.         {
  1709.             accessAllowedAce = (ACCESS_ALLOWED_ACE *) ace;
  1710.  
  1711.             if (EqualSid(principalSID, (PSID) &accessAllowedAce->SidStart))
  1712.             {
  1713.                 DeleteAce(pAcl, i);
  1714.                 free(principalSID);
  1715.                 return S_OK;
  1716.             }
  1717.         } else
  1718.  
  1719.         if (aceHeader->AceType == ACCESS_DENIED_ACE_TYPE)
  1720.         {
  1721.             accessDeniedAce = (ACCESS_DENIED_ACE *) ace;
  1722.  
  1723.             if (EqualSid(principalSID, (PSID) &accessDeniedAce->SidStart))
  1724.             {
  1725.                 DeleteAce(pAcl, i);
  1726.                 free(principalSID);
  1727.                 return S_OK;
  1728.             }
  1729.         } else
  1730.  
  1731.         if (aceHeader->AceType == SYSTEM_AUDIT_ACE_TYPE)
  1732.         {
  1733.             systemAuditAce = (SYSTEM_AUDIT_ACE *) ace;
  1734.  
  1735.             if (EqualSid(principalSID, (PSID) &systemAuditAce->SidStart))
  1736.             {
  1737.                 DeleteAce(pAcl, i);
  1738.                 free(principalSID);
  1739.                 return S_OK;
  1740.             }
  1741.         }
  1742.     }
  1743.     free(principalSID);
  1744.     return S_OK;
  1745. }
  1746.  
  1747.  
  1748. inline HRESULT CSecurityDescriptor::SetPrivilege(LPCTSTR privilege, BOOL bEnable, HANDLE hToken)
  1749. {
  1750.     HRESULT hr;
  1751.     TOKEN_PRIVILEGES tpPrevious;
  1752.     TOKEN_PRIVILEGES tp;
  1753.     DWORD  cbPrevious = sizeof(TOKEN_PRIVILEGES);
  1754.     LUID   luid;
  1755.     HANDLE hTokenUsed;
  1756.  
  1757.     // if no token specified open process token
  1758.     if (hToken == 0)
  1759.     {
  1760.         if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hTokenUsed))
  1761.         {
  1762.             hr = HRESULT_FROM_WIN32(GetLastError());
  1763.             ATLASSERT(FALSE);
  1764.             return hr;
  1765.         }
  1766.     }
  1767.     else
  1768.         hTokenUsed = hToken;
  1769.  
  1770.     if (!LookupPrivilegeValue(NULL, privilege, &luid ))
  1771.     {
  1772.         hr = HRESULT_FROM_WIN32(GetLastError());
  1773.         ATLASSERT(FALSE);
  1774.         if (hToken == 0)
  1775.             CloseHandle(hTokenUsed);
  1776.         return hr;
  1777.     }
  1778.  
  1779.     tp.PrivilegeCount = 1;
  1780.     tp.Privileges[0].Luid = luid;
  1781.     tp.Privileges[0].Attributes = 0;
  1782.  
  1783.     if (!AdjustTokenPrivileges(hTokenUsed, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), &tpPrevious, &cbPrevious))
  1784.     {
  1785.         hr = HRESULT_FROM_WIN32(GetLastError());
  1786.         ATLASSERT(FALSE);
  1787.         if (hToken == 0)
  1788.             CloseHandle(hTokenUsed);
  1789.         return hr;
  1790.     }
  1791.  
  1792.     tpPrevious.PrivilegeCount = 1;
  1793.     tpPrevious.Privileges[0].Luid = luid;
  1794.  
  1795.     if (bEnable)
  1796.         tpPrevious.Privileges[0].Attributes |= (SE_PRIVILEGE_ENABLED);
  1797.     else
  1798.         tpPrevious.Privileges[0].Attributes ^= (SE_PRIVILEGE_ENABLED & tpPrevious.Privileges[0].Attributes);
  1799.  
  1800.     if (!AdjustTokenPrivileges(hTokenUsed, FALSE, &tpPrevious, cbPrevious, NULL, NULL))
  1801.     {
  1802.         hr = HRESULT_FROM_WIN32(GetLastError());
  1803.         ATLASSERT(FALSE);
  1804.         if (hToken == 0)
  1805.             CloseHandle(hTokenUsed);
  1806.         return hr;
  1807.     }
  1808.     return S_OK;
  1809. }
  1810.  
  1811. /////////////////////////////////////////////////////////////////////////////
  1812. // COM Objects
  1813.  
  1814. #define DECLARE_PROTECT_FINAL_CONSTRUCT()\
  1815.     void InternalFinalConstructAddRef() {InternalAddRef();}\
  1816.     void InternalFinalConstructRelease() {InternalRelease();}
  1817.  
  1818. template <class T1>
  1819. class CComCreator
  1820. {
  1821. public:
  1822.     static HRESULT WINAPI CreateInstance(void* pv, REFIID riid, LPVOID* ppv)
  1823.     {
  1824.         ATLASSERT(*ppv == NULL);
  1825.         HRESULT hRes = E_OUTOFMEMORY;
  1826.         T1* p = NULL;
  1827.         ATLTRY(p = new T1(pv))
  1828.         if (p != NULL)
  1829.         {
  1830.             p->SetVoid(pv);
  1831.             p->InternalFinalConstructAddRef();
  1832.             hRes = p->FinalConstruct();
  1833.             p->InternalFinalConstructRelease();
  1834.             if (hRes == S_OK)
  1835.                 hRes = p->QueryInterface(riid, ppv);
  1836.             if (hRes != S_OK)
  1837.                 delete p;
  1838.         }
  1839.         return hRes;
  1840.     }
  1841. };
  1842.  
  1843. template <class T1>
  1844. class CComInternalCreator
  1845. {
  1846. public:
  1847.     static HRESULT WINAPI CreateInstance(void* pv, REFIID riid, LPVOID* ppv)
  1848.     {
  1849.         ATLASSERT(*ppv == NULL);
  1850.         HRESULT hRes = E_OUTOFMEMORY;
  1851.         T1* p = NULL;
  1852.         ATLTRY(p = new T1(pv))
  1853.         if (p != NULL)
  1854.         {
  1855.             p->SetVoid(pv);
  1856.             p->InternalFinalConstructAddRef();
  1857.             hRes = p->FinalConstruct();
  1858.             p->InternalFinalConstructRelease();
  1859.             if (hRes == S_OK)
  1860.                 hRes = p->_InternalQueryInterface(riid, ppv);
  1861.             if (hRes != S_OK)
  1862.                 delete p;
  1863.         }
  1864.         return hRes;
  1865.     }
  1866. };
  1867.  
  1868. template <HRESULT hr>
  1869. class CComFailCreator
  1870. {
  1871. public:
  1872.     static HRESULT WINAPI CreateInstance(void*, REFIID, LPVOID*)
  1873.     {
  1874.         return hr;
  1875.     }
  1876. };
  1877.  
  1878. template <class T1, class T2>
  1879. class CComCreator2
  1880. {
  1881. public:
  1882.     static HRESULT WINAPI CreateInstance(void* pv, REFIID riid, LPVOID* ppv)
  1883.     {
  1884.         ATLASSERT(*ppv == NULL);
  1885.         return (pv == NULL) ? 
  1886.             T1::CreateInstance(NULL, riid, ppv) : 
  1887.             T2::CreateInstance(pv, riid, ppv);
  1888.     }
  1889. };
  1890.  
  1891. #define DECLARE_NOT_AGGREGATABLE(x) public:\
  1892.     typedef CComCreator2< CComCreator< CComObject< x > >, CComFailCreator<CLASS_E_NOAGGREGATION> > _CreatorClass;
  1893. #define DECLARE_AGGREGATABLE(x) public:\
  1894.     typedef CComCreator2< CComCreator< CComObject< x > >, CComCreator< CComAggObject< x > > > _CreatorClass;
  1895. #define DECLARE_ONLY_AGGREGATABLE(x) public:\
  1896.     typedef CComCreator2< CComFailCreator<E_FAIL>, CComCreator< CComAggObject< x > > > _CreatorClass;
  1897. #define DECLARE_POLY_AGGREGATABLE(x) public:\
  1898.     typedef CComCreator< CComPolyObject< x > > _CreatorClass;
  1899.  
  1900. struct _ATL_CREATORDATA
  1901. {
  1902.     _ATL_CREATORFUNC* pFunc;
  1903. };
  1904.  
  1905. template <class Creator>
  1906. class _CComCreatorData
  1907. {
  1908. public:
  1909.     static _ATL_CREATORDATA data;
  1910. };
  1911.  
  1912. template <class Creator>
  1913. _ATL_CREATORDATA _CComCreatorData<Creator>::data = {Creator::CreateInstance};
  1914.  
  1915. struct _ATL_CACHEDATA
  1916. {
  1917.     DWORD dwOffsetVar;
  1918.     _ATL_CREATORFUNC* pFunc;
  1919. };
  1920.  
  1921. template <class Creator, DWORD dwVar>
  1922. class _CComCacheData
  1923. {
  1924. public:
  1925.     static _ATL_CACHEDATA data;
  1926. };
  1927.  
  1928. template <class Creator, DWORD dwVar>
  1929. _ATL_CACHEDATA _CComCacheData<Creator, dwVar>::data = {dwVar, Creator::CreateInstance};
  1930.  
  1931. struct _ATL_CHAINDATA
  1932. {
  1933.     DWORD dwOffset;
  1934.     const _ATL_INTMAP_ENTRY* (WINAPI *pFunc)();
  1935. };
  1936.  
  1937. template <class base, class derived>
  1938. class _CComChainData
  1939. {
  1940. public:
  1941.     static _ATL_CHAINDATA data;
  1942. };
  1943.  
  1944. template <class base, class derived>
  1945. _ATL_CHAINDATA _CComChainData<base, derived>::data =
  1946.     {offsetofclass(base, derived), base::_GetEntries};
  1947.  
  1948. template <class T, const CLSID* pclsid>
  1949. class CComAggregateCreator
  1950. {
  1951. public:
  1952.     static HRESULT WINAPI CreateInstance(void* pv, REFIID/*riid*/, LPVOID* ppv)
  1953.     {
  1954.         ATLASSERT(*ppv == NULL);
  1955.         ATLASSERT(pv != NULL);
  1956.         T* p = (T*) pv;
  1957.         // Add the following line to your object if you get a message about
  1958.         // GetControllingUnknown() being undefined
  1959.         // DECLARE_GET_CONTROLLING_UNKNOWN()
  1960.         return CoCreateInstance(*pclsid, p->GetControllingUnknown(), CLSCTX_INPROC, IID_IUnknown, ppv);
  1961.     }
  1962. };
  1963.  
  1964. #ifdef _ATL_DEBUG
  1965. #define DEBUG_QI_ENTRY(x) \
  1966.         {NULL, \
  1967.         (DWORD)_T(#x), \
  1968.         (_ATL_CREATORARGFUNC*)0},
  1969. #else
  1970. #define DEBUG_QI_ENTRY(x)
  1971. #endif //_ATL_DEBUG
  1972.  
  1973. #ifdef _ATL_DEBUG_INTERFACES
  1974. #define _ATL_DECLARE_GET_UNKNOWN(x)\
  1975.     IUnknown* GetUnknown() \
  1976.     { \
  1977.         IUnknown* p; \
  1978.         _Module.AddNonAddRefThunk(_GetRawUnknown(), _T(#x), &p); \
  1979.         return p; \
  1980.     }
  1981. #else
  1982. #define _ATL_DECLARE_GET_UNKNOWN(x) IUnknown* GetUnknown() {return _GetRawUnknown();}
  1983. #endif
  1984.  
  1985. //If you get a message that FinalConstruct is ambiguous then you need to
  1986. // override it in your class and call each base class' version of this
  1987. #define BEGIN_COM_MAP(x) public: \
  1988.     typedef x _ComMapClass; \
  1989.     static HRESULT WINAPI _Cache(void* pv, REFIID iid, void** ppvObject, DWORD dw)\
  1990.     {\
  1991.         _ComMapClass* p = (_ComMapClass*)pv;\
  1992.         p->Lock();\
  1993.         HRESULT hRes = CComObjectRootBase::_Cache(pv, iid, ppvObject, dw);\
  1994.         p->Unlock();\
  1995.         return hRes;\
  1996.     }\
  1997.     IUnknown* _GetRawUnknown() \
  1998.     { ATLASSERT(_GetEntries()[0].pFunc == _ATL_SIMPLEMAPENTRY); return (IUnknown*)((int)this+_GetEntries()->dw); } \
  1999.     _ATL_DECLARE_GET_UNKNOWN(x)\
  2000.     HRESULT _InternalQueryInterface(REFIID iid, void** ppvObject) \
  2001.     { return InternalQueryInterface(this, _GetEntries(), iid, ppvObject); } \
  2002.     const static _ATL_INTMAP_ENTRY* WINAPI _GetEntries() { \
  2003.     static const _ATL_INTMAP_ENTRY _entries[] = { DEBUG_QI_ENTRY(x)
  2004.  
  2005. #define DECLARE_GET_CONTROLLING_UNKNOWN() public:\
  2006.     virtual IUnknown* GetControllingUnknown() {return GetUnknown();}
  2007.  
  2008. #ifndef _ATL_NO_UUIDOF
  2009. #define _ATL_IIDOF(x) __uuidof(x)
  2010. #else
  2011. #define _ATL_IIDOF(x) IID_##x
  2012. #endif
  2013.  
  2014. #define COM_INTERFACE_ENTRY_BREAK(x)\
  2015.     {&_ATL_IIDOF(x), \
  2016.     NULL, \
  2017.     _Break},
  2018.  
  2019. #define COM_INTERFACE_ENTRY_NOINTERFACE(x)\
  2020.     {&_ATL_IIDOF(x), \
  2021.     NULL, \
  2022.     _NoInterface},
  2023.  
  2024. #define COM_INTERFACE_ENTRY(x)\
  2025.     {&_ATL_IIDOF(x), \
  2026.     offsetofclass(x, _ComMapClass), \
  2027.     _ATL_SIMPLEMAPENTRY},
  2028.  
  2029. #define COM_INTERFACE_ENTRY_IID(iid, x)\
  2030.     {&iid,\
  2031.     offsetofclass(x, _ComMapClass),\
  2032.     _ATL_SIMPLEMAPENTRY},
  2033.  
  2034. // The impl macros are now obsolete
  2035. #define COM_INTERFACE_ENTRY_IMPL(x)\
  2036.     COM_INTERFACE_ENTRY_IID(_ATL_IIDOF(x), x##Impl<_ComMapClass>)
  2037.  
  2038. #define COM_INTERFACE_ENTRY_IMPL_IID(iid, x)\
  2039.     COM_INTERFACE_ENTRY_IID(iid, x##Impl<_ComMapClass>)
  2040. //
  2041.  
  2042. #define COM_INTERFACE_ENTRY2(x, x2)\
  2043.     {&_ATL_IIDOF(x),\
  2044.     (DWORD)((x*)(x2*)((_ComMapClass*)8))-8,\
  2045.     _ATL_SIMPLEMAPENTRY},
  2046.  
  2047. #define COM_INTERFACE_ENTRY2_IID(iid, x, x2)\
  2048.     {&iid,\
  2049.     (DWORD)((x*)(x2*)((_ComMapClass*)8))-8,\
  2050.     _ATL_SIMPLEMAPENTRY},
  2051.  
  2052. #define COM_INTERFACE_ENTRY_FUNC(iid, dw, func)\
  2053.     {&iid, \
  2054.     dw, \
  2055.     func},
  2056.  
  2057. #define COM_INTERFACE_ENTRY_FUNC_BLIND(dw, func)\
  2058.     {NULL, \
  2059.     dw, \
  2060.     func},
  2061.  
  2062. #define COM_INTERFACE_ENTRY_TEAR_OFF(iid, x)\
  2063.     {&iid,\
  2064.     (DWORD)&_CComCreatorData<\
  2065.         CComInternalCreator< CComTearOffObject< x > >\
  2066.         >::data,\
  2067.     _Creator},
  2068.  
  2069. #define COM_INTERFACE_ENTRY_CACHED_TEAR_OFF(iid, x, punk)\
  2070.     {&iid,\
  2071.     (DWORD)&_CComCacheData<\
  2072.         CComCreator< CComCachedTearOffObject< x > >,\
  2073.         (DWORD)offsetof(_ComMapClass, punk)\
  2074.         >::data,\
  2075.     _Cache},
  2076.  
  2077. #define COM_INTERFACE_ENTRY_AGGREGATE(iid, punk)\
  2078.     {&iid,\
  2079.     (DWORD)offsetof(_ComMapClass, punk),\
  2080.     _Delegate},
  2081.  
  2082. #define COM_INTERFACE_ENTRY_AGGREGATE_BLIND(punk)\
  2083.     {NULL,\
  2084.     (DWORD)offsetof(_ComMapClass, punk),\
  2085.     _Delegate},
  2086.  
  2087. #define COM_INTERFACE_ENTRY_AUTOAGGREGATE(iid, punk, clsid)\
  2088.     {&iid,\
  2089.     (DWORD)&_CComCacheData<\
  2090.         CComAggregateCreator<_ComMapClass, &clsid>,\
  2091.         (DWORD)offsetof(_ComMapClass, punk)\
  2092.         >::data,\
  2093.     _Cache},
  2094.  
  2095. #define COM_INTERFACE_ENTRY_AUTOAGGREGATE_BLIND(punk, clsid)\
  2096.     {NULL,\
  2097.     (DWORD)&_CComCacheData<\
  2098.         CComAggregateCreator<_ComMapClass, &clsid>,\
  2099.         (DWORD)offsetof(_ComMapClass, punk)\
  2100.         >::data,\
  2101.     _Cache},
  2102.  
  2103. #define COM_INTERFACE_ENTRY_CHAIN(classname)\
  2104.     {NULL,\
  2105.     (DWORD)&_CComChainData<classname, _ComMapClass>::data,\
  2106.     _Chain},
  2107.  
  2108. #ifdef _ATL_DEBUG
  2109. #define END_COM_MAP() {NULL, 0, 0}}; return &_entries[1];} \
  2110.     virtual ULONG STDMETHODCALLTYPE AddRef( void) = 0; \
  2111.     virtual ULONG STDMETHODCALLTYPE Release( void) = 0; \
  2112.     STDMETHOD(QueryInterface)(REFIID, void**) = 0;
  2113. #else
  2114. #define END_COM_MAP() {NULL, 0, 0}}; return _entries;} \
  2115.     virtual ULONG STDMETHODCALLTYPE AddRef( void) = 0; \
  2116.     virtual ULONG STDMETHODCALLTYPE Release( void) = 0; \
  2117.     STDMETHOD(QueryInterface)(REFIID, void**) = 0;
  2118. #endif // _ATL_DEBUG
  2119.  
  2120. #define BEGIN_CATEGORY_MAP(x)\
  2121.    static const struct _ATL_CATMAP_ENTRY* GetCategoryMap() {\
  2122.    static const struct _ATL_CATMAP_ENTRY pMap[] = {
  2123. #define IMPLEMENTED_CATEGORY( catid ) { _ATL_CATMAP_ENTRY_IMPLEMENTED, &catid },
  2124. #define REQUIRED_CATEGORY( catid ) { _ATL_CATMAP_ENTRY_REQUIRED, &catid },
  2125. #define END_CATEGORY_MAP()\
  2126.    { _ATL_CATMAP_ENTRY_END, NULL } };\
  2127.    return( pMap ); }
  2128.  
  2129. #define BEGIN_OBJECT_MAP(x) static _ATL_OBJMAP_ENTRY x[] = {
  2130. #define END_OBJECT_MAP()   {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}};
  2131. #define OBJECT_ENTRY(clsid, class) {&clsid, class::UpdateRegistry, class::_ClassFactoryCreatorClass::CreateInstance, class::_CreatorClass::CreateInstance, NULL, 0, class::GetObjectDescription, class::GetCategoryMap, class::ObjectMain },
  2132. #define OBJECT_ENTRY_NON_CREATEABLE(class) {&CLSID_NULL, class::UpdateRegistry, NULL, NULL, NULL, 0, NULL, class::GetCategoryMap, class::ObjectMain },
  2133.  
  2134. #ifdef _ATL_DEBUG
  2135. extern HRESULT WINAPI AtlDumpIID(REFIID iid, LPCTSTR pszClassName, HRESULT hr);
  2136. #endif // _ATL_DEBUG
  2137.  
  2138.  
  2139. // the functions in this class don't need to be virtual because
  2140. // they are called from CComObject
  2141. class CComObjectRootBase
  2142. {
  2143. public:
  2144.     CComObjectRootBase()
  2145.     {
  2146.         m_dwRef = 0L;
  2147.     }
  2148.     HRESULT FinalConstruct()
  2149.     {
  2150.         return S_OK;
  2151.     }
  2152.     // For library initialization only
  2153.     HRESULT _AtlFinalConstruct()
  2154.     {
  2155.         return S_OK;
  2156.     }
  2157.     void FinalRelease() {}
  2158.     void _AtlFinalRelease() {}
  2159.  
  2160.     //ObjectMain is called during Module::Init and Module::Term
  2161.     static void WINAPI ObjectMain(bool /* bStarting */) {}
  2162.  
  2163.     static HRESULT WINAPI InternalQueryInterface(void* pThis,
  2164.         const _ATL_INTMAP_ENTRY* pEntries, REFIID iid, void** ppvObject)
  2165.     {
  2166.         ATLASSERT(pThis != NULL);
  2167.         // First entry in the com map should be a simple map entry
  2168.         ATLASSERT(pEntries->pFunc == _ATL_SIMPLEMAPENTRY);
  2169.     #if defined(_ATL_DEBUG_INTERFACES) || defined(_ATL_DEBUG_QI)
  2170.         LPCTSTR pszClassName = (LPCTSTR) pEntries[-1].dw;
  2171.     #endif // _ATL_DEBUG_INTERFACES
  2172.         HRESULT hRes = AtlInternalQueryInterface(pThis, pEntries, iid, ppvObject);
  2173.     #ifdef _ATL_DEBUG_INTERFACES
  2174.         _Module.AddThunk((IUnknown**)ppvObject, pszClassName, iid);
  2175.     #endif // _ATL_DEBUG_INTERFACES
  2176.         return _ATLDUMPIID(iid, pszClassName, hRes);
  2177.     }
  2178.  
  2179. //Outer funcs
  2180.     ULONG OuterAddRef()
  2181.     {
  2182.         return m_pOuterUnknown->AddRef();
  2183.     }
  2184.     ULONG OuterRelease()
  2185.     {
  2186.         return m_pOuterUnknown->Release();
  2187.     }
  2188.     HRESULT OuterQueryInterface(REFIID iid, void ** ppvObject)
  2189.     {
  2190.         return m_pOuterUnknown->QueryInterface(iid, ppvObject);
  2191.     }
  2192.  
  2193.     void SetVoid(void*) {}
  2194.     void InternalFinalConstructAddRef() {}
  2195.     void InternalFinalConstructRelease()
  2196.     {
  2197.         ATLASSERT(m_dwRef == 0);
  2198.     }
  2199.     // If this assert occurs, your object has probably been deleted
  2200.     // Try using DECLARE_PROTECT_FINAL_CONSTRUCT()
  2201.  
  2202.  
  2203.     static HRESULT WINAPI _Break(void* /* pv */, REFIID iid, void** /* ppvObject */, DWORD /* dw */)
  2204.     {
  2205.         iid;
  2206.         _ATLDUMPIID(iid, _T("Break due to QI for interface "), S_OK);
  2207.         DebugBreak();
  2208.         return S_FALSE;
  2209.     }
  2210.     static HRESULT WINAPI _NoInterface(void* /* pv */, REFIID /* iid */, void** /* ppvObject */, DWORD /* dw */)
  2211.     {
  2212.         return E_NOINTERFACE;
  2213.     }
  2214.     static HRESULT WINAPI _Creator(void* pv, REFIID iid, void** ppvObject, DWORD dw)
  2215.     {
  2216.         _ATL_CREATORDATA* pcd = (_ATL_CREATORDATA*)dw;
  2217.         return pcd->pFunc(pv, iid, ppvObject);
  2218.     }
  2219.     static HRESULT WINAPI _Delegate(void* pv, REFIID iid, void** ppvObject, DWORD dw)
  2220.     {
  2221.         HRESULT hRes = E_NOINTERFACE;
  2222.         IUnknown* p = *(IUnknown**)((DWORD)pv + dw);
  2223.         if (p != NULL)
  2224.             hRes = p->QueryInterface(iid, ppvObject);
  2225.         return hRes;
  2226.     }
  2227.     static HRESULT WINAPI _Chain(void* pv, REFIID iid, void** ppvObject, DWORD dw)
  2228.     {
  2229.         _ATL_CHAINDATA* pcd = (_ATL_CHAINDATA*)dw;
  2230.         void* p = (void*)((DWORD)pv + pcd->dwOffset);
  2231.         return InternalQueryInterface(p, pcd->pFunc(), iid, ppvObject);
  2232.     }
  2233.     static HRESULT WINAPI _Cache(void* pv, REFIID iid, void** ppvObject, DWORD dw)
  2234.     {
  2235.         HRESULT hRes = E_NOINTERFACE;
  2236.         _ATL_CACHEDATA* pcd = (_ATL_CACHEDATA*)dw;
  2237.         IUnknown** pp = (IUnknown**)((DWORD)pv + pcd->dwOffsetVar);
  2238.         if (*pp == NULL)
  2239.             hRes = pcd->pFunc(pv, IID_IUnknown, (void**)pp);
  2240.         if (*pp != NULL)
  2241.             hRes = (*pp)->QueryInterface(iid, ppvObject);
  2242.         return hRes;
  2243.     }
  2244.  
  2245.     union
  2246.     {
  2247.         long m_dwRef;
  2248.         IUnknown* m_pOuterUnknown;
  2249.     };
  2250. };
  2251.  
  2252. //foward declaration
  2253. template <class ThreadModel>
  2254. class CComObjectRootEx;
  2255.  
  2256. template <class ThreadModel>
  2257. class CComObjectLockT
  2258. {
  2259. public:
  2260.     CComObjectLockT(CComObjectRootEx<ThreadModel>* p)
  2261.     {
  2262.         if (p)
  2263.             p->Lock();
  2264.         m_p = p;
  2265.     }
  2266.  
  2267.     ~CComObjectLockT()
  2268.     {
  2269.         if (m_p)
  2270.             m_p->Unlock();
  2271.     }
  2272.     CComObjectRootEx<ThreadModel>* m_p;
  2273. };
  2274.  
  2275. template <> class CComObjectLockT<CComSingleThreadModel>;
  2276.  
  2277. template <class ThreadModel>
  2278. class CComObjectRootEx : public CComObjectRootBase
  2279. {
  2280. public:
  2281.     typedef ThreadModel _ThreadModel;
  2282.     typedef _ThreadModel::AutoCriticalSection _CritSec;
  2283.     typedef CComObjectLockT<_ThreadModel> ObjectLock;
  2284.  
  2285.     ULONG InternalAddRef()
  2286.     {
  2287.         ATLASSERT(m_dwRef != -1L);
  2288.         return _ThreadModel::Increment(&m_dwRef);
  2289.     }
  2290.     ULONG InternalRelease()
  2291.     {
  2292.         ATLASSERT(m_dwRef > 0);
  2293.         return _ThreadModel::Decrement(&m_dwRef);
  2294.     }
  2295.  
  2296.     void Lock() {m_critsec.Lock();}
  2297.     void Unlock() {m_critsec.Unlock();}
  2298. private:
  2299.     _CritSec m_critsec;
  2300. };
  2301.  
  2302. template <>
  2303. class CComObjectRootEx<CComSingleThreadModel> : public CComObjectRootBase
  2304. {
  2305. public:
  2306.     typedef CComSingleThreadModel _ThreadModel;
  2307.     typedef _ThreadModel::AutoCriticalSection _CritSec;
  2308.     typedef CComObjectLockT<_ThreadModel> ObjectLock;
  2309.  
  2310.     ULONG InternalAddRef()
  2311.     {
  2312.         ATLASSERT(m_dwRef != -1L);
  2313.         return _ThreadModel::Increment(&m_dwRef);
  2314.     }
  2315.     ULONG InternalRelease()
  2316.     {
  2317.         return _ThreadModel::Decrement(&m_dwRef);
  2318.     }
  2319.  
  2320.     void Lock() {}
  2321.     void Unlock() {}
  2322. };
  2323.  
  2324. template <>
  2325. class CComObjectLockT<CComSingleThreadModel>
  2326. {
  2327. public:
  2328.     CComObjectLockT(CComObjectRootEx<CComSingleThreadModel>*) {}
  2329.     ~CComObjectLockT() {}
  2330. };
  2331.  
  2332. typedef CComObjectRootEx<CComObjectThreadModel> CComObjectRoot;
  2333.  
  2334. #if defined(_WINDLL) | defined(_USRDLL)
  2335. #define DECLARE_CLASSFACTORY_EX(cf) typedef CComCreator< CComObjectCached< cf > > _ClassFactoryCreatorClass;
  2336. #else
  2337. // don't let class factory refcount influence lock count
  2338. #define DECLARE_CLASSFACTORY_EX(cf) typedef CComCreator< CComObjectNoLock< cf > > _ClassFactoryCreatorClass;
  2339. #endif
  2340. #define DECLARE_CLASSFACTORY() DECLARE_CLASSFACTORY_EX(CComClassFactory)
  2341. #define DECLARE_CLASSFACTORY2(lic) DECLARE_CLASSFACTORY_EX(CComClassFactory2<lic>)
  2342. #define DECLARE_CLASSFACTORY_AUTO_THREAD() DECLARE_CLASSFACTORY_EX(CComClassFactoryAutoThread)
  2343. #define DECLARE_CLASSFACTORY_SINGLETON(obj) DECLARE_CLASSFACTORY_EX(CComClassFactorySingleton<obj>)
  2344.  
  2345. #define DECLARE_OBJECT_DESCRIPTION(x)\
  2346.     static LPCTSTR WINAPI GetObjectDescription()\
  2347.     {\
  2348.         return _T(x);\
  2349.     }
  2350.  
  2351. #define DECLARE_NO_REGISTRY()\
  2352.     static HRESULT WINAPI UpdateRegistry(BOOL /*bRegister*/)\
  2353.     {return S_OK;}
  2354.  
  2355. #define DECLARE_REGISTRY(class, pid, vpid, nid, flags)\
  2356.     static HRESULT WINAPI UpdateRegistry(BOOL bRegister)\
  2357.     {\
  2358.         return _Module.UpdateRegistryClass(GetObjectCLSID(), pid, vpid, nid,\
  2359.             flags, bRegister);\
  2360.     }
  2361.  
  2362. #define DECLARE_REGISTRY_RESOURCE(x)\
  2363.     static HRESULT WINAPI UpdateRegistry(BOOL bRegister)\
  2364.     {\
  2365.     return _Module.UpdateRegistryFromResource(_T(#x), bRegister);\
  2366.     }
  2367.  
  2368. #define DECLARE_REGISTRY_RESOURCEID(x)\
  2369.     static HRESULT WINAPI UpdateRegistry(BOOL bRegister)\
  2370.     {\
  2371.     return _Module.UpdateRegistryFromResource(x, bRegister);\
  2372.     }
  2373.  
  2374. //DECLARE_STATIC_* provided for backward compatibility
  2375. #ifdef _ATL_STATIC_REGISTRY
  2376. #define DECLARE_STATIC_REGISTRY_RESOURCE(x) DECLARE_REGISTRY_RESOURCE(x)
  2377. #define DECLARE_STATIC_REGISTRY_RESOURCEID(x) DECLARE_REGISTRY_RESOURCEID(x)
  2378. #endif //_ATL_STATIC_REGISTRY
  2379.  
  2380. template<class Base> class CComObject; // fwd decl
  2381.  
  2382. template <class Owner, class ThreadModel = CComObjectThreadModel>
  2383. class CComTearOffObjectBase : public CComObjectRootEx<ThreadModel>
  2384. {
  2385. public:
  2386.     typedef Owner _OwnerClass;
  2387.     CComObject<Owner>* m_pOwner;
  2388.     CComTearOffObjectBase() {m_pOwner = NULL;}
  2389. };
  2390.  
  2391. //Base is the user's class that derives from CComObjectRoot and whatever
  2392. //interfaces the user wants to support on the object
  2393. template <class Base>
  2394. class CComObject : public Base
  2395. {
  2396. public:
  2397.     typedef Base _BaseClass;
  2398.     CComObject(void* = NULL)
  2399.     {
  2400.         _Module.Lock();
  2401.     }
  2402.     // Set refcount to 1 to protect destruction
  2403.     ~CComObject()
  2404.     {
  2405.         m_dwRef = 1L;
  2406.         FinalRelease();
  2407. #ifdef _ATL_DEBUG_INTERFACES
  2408.         _Module.DeleteNonAddRefThunk(_GetRawUnknown());
  2409. #endif
  2410.         _Module.Unlock();
  2411.     }
  2412.     //If InternalAddRef or InternalRelease is undefined then your class
  2413.     //doesn't derive from CComObjectRoot
  2414.     STDMETHOD_(ULONG, AddRef)() {return InternalAddRef();}
  2415.     STDMETHOD_(ULONG, Release)()
  2416.     {
  2417.         ULONG l = InternalRelease();
  2418.         if (l == 0)
  2419.             delete this;
  2420.         return l;
  2421.     }
  2422.     //if _InternalQueryInterface is undefined then you forgot BEGIN_COM_MAP
  2423.     STDMETHOD(QueryInterface)(REFIID iid, void ** ppvObject)
  2424.     {return _InternalQueryInterface(iid, ppvObject);}
  2425.     template <class Q>
  2426.     HRESULT STDMETHODCALLTYPE QueryInterface(Q** pp)
  2427.     {
  2428.         return QueryInterface(__uuidof(Q), (void**)pp);
  2429.     }
  2430.  
  2431.     static HRESULT WINAPI CreateInstance(CComObject<Base>** pp);
  2432. };
  2433.  
  2434. template <class Base>
  2435. HRESULT WINAPI CComObject<Base>::CreateInstance(CComObject<Base>** pp)
  2436. {
  2437.     ATLASSERT(pp != NULL);
  2438.     HRESULT hRes = E_OUTOFMEMORY;
  2439.     CComObject<Base>* p = NULL;
  2440.     ATLTRY(p = new CComObject<Base>())
  2441.     if (p != NULL)
  2442.     {
  2443.         p->SetVoid(NULL);
  2444.         p->InternalFinalConstructAddRef();
  2445.         hRes = p->FinalConstruct();
  2446.         p->InternalFinalConstructRelease();
  2447.         if (hRes != S_OK)
  2448.         {
  2449.             delete p;
  2450.             p = NULL;
  2451.         }
  2452.     }
  2453.     *pp = p;
  2454.     return hRes;
  2455. }
  2456.  
  2457. //Base is the user's class that derives from CComObjectRoot and whatever
  2458. //interfaces the user wants to support on the object
  2459. // CComObjectCached is used primarily for class factories in DLL's
  2460. // but it is useful anytime you want to cache an object
  2461. template <class Base>
  2462. class CComObjectCached : public Base
  2463. {
  2464. public:
  2465.     typedef Base _BaseClass;
  2466.     CComObjectCached(void* = NULL){}
  2467.     // Set refcount to 1 to protect destruction
  2468.     ~CComObjectCached()
  2469.     {
  2470.         m_dwRef = 1L;
  2471.         FinalRelease();
  2472. #ifdef _ATL_DEBUG_INTERFACES
  2473.         _Module.DeleteNonAddRefThunk(_GetRawUnknown());
  2474. #endif
  2475.     }
  2476.     //If InternalAddRef or InternalRelease is undefined then your class
  2477.     //doesn't derive from CComObjectRoot
  2478.     STDMETHOD_(ULONG, AddRef)()
  2479.     {
  2480.         m_csCached.Lock();
  2481.         ULONG l = InternalAddRef();
  2482.         if (m_dwRef == 2)
  2483.             _Module.Lock();
  2484.         m_csCached.Unlock();
  2485.         return l;
  2486.     }
  2487.     STDMETHOD_(ULONG, Release)()
  2488.     {
  2489.         m_csCached.Lock();
  2490.         InternalRelease();
  2491.         ULONG l = m_dwRef;
  2492.         m_csCached.Unlock();
  2493.         if (l == 0)
  2494.             delete this;
  2495.         else if (l == 1)
  2496.             _Module.Unlock();
  2497.         return l;
  2498.     }
  2499.     //if _InternalQueryInterface is undefined then you forgot BEGIN_COM_MAP
  2500.     STDMETHOD(QueryInterface)(REFIID iid, void ** ppvObject)
  2501.     {return _InternalQueryInterface(iid, ppvObject);}
  2502.     CComGlobalsThreadModel::AutoCriticalSection m_csCached;
  2503. };
  2504.  
  2505. //Base is the user's class that derives from CComObjectRoot and whatever
  2506. //interfaces the user wants to support on the object
  2507. template <class Base>
  2508. class CComObjectNoLock : public Base
  2509. {
  2510. public:
  2511.     typedef Base _BaseClass;
  2512.     CComObjectNoLock(void* = NULL){}
  2513.     // Set refcount to 1 to protect destruction
  2514.     ~CComObjectNoLock()
  2515.     {
  2516.         m_dwRef = 1L;
  2517.         FinalRelease();
  2518. #ifdef _ATL_DEBUG_INTERFACES
  2519.         _Module.DeleteNonAddRefThunk(_GetRawUnknown());
  2520. #endif
  2521.     }
  2522.  
  2523.     //If InternalAddRef or InternalRelease is undefined then your class
  2524.     //doesn't derive from CComObjectRoot
  2525.     STDMETHOD_(ULONG, AddRef)() {return InternalAddRef();}
  2526.     STDMETHOD_(ULONG, Release)()
  2527.     {
  2528.         ULONG l = InternalRelease();
  2529.         if (l == 0)
  2530.             delete this;
  2531.         return l;
  2532.     }
  2533.     //if _InternalQueryInterface is undefined then you forgot BEGIN_COM_MAP
  2534.     STDMETHOD(QueryInterface)(REFIID iid, void ** ppvObject)
  2535.     {return _InternalQueryInterface(iid, ppvObject);}
  2536. };
  2537.  
  2538. // It is possible for Base not to derive from CComObjectRoot
  2539. // However, you will need to provide FinalConstruct and InternalQueryInterface
  2540. template <class Base>
  2541. class CComObjectGlobal : public Base
  2542. {
  2543. public:
  2544.     typedef Base _BaseClass;
  2545.     CComObjectGlobal(void* = NULL){m_hResFinalConstruct = FinalConstruct();}
  2546.     ~CComObjectGlobal()
  2547.     {
  2548.         FinalRelease();
  2549. #ifdef _ATL_DEBUG_INTERFACES
  2550.         _Module.DeleteNonAddRefThunk(_GetRawUnknown());
  2551. #endif
  2552.     }
  2553.  
  2554.     STDMETHOD_(ULONG, AddRef)() {return _Module.Lock();}
  2555.     STDMETHOD_(ULONG, Release)(){return _Module.Unlock();}
  2556.     STDMETHOD(QueryInterface)(REFIID iid, void ** ppvObject)
  2557.     {return _InternalQueryInterface(iid, ppvObject);}
  2558.     HRESULT m_hResFinalConstruct;
  2559. };
  2560.  
  2561. // It is possible for Base not to derive from CComObjectRoot
  2562. // However, you will need to provide FinalConstruct and InternalQueryInterface
  2563. template <class Base>
  2564. class CComObjectStack : public Base
  2565. {
  2566. public:
  2567.     typedef Base _BaseClass;
  2568.     CComObjectStack(void* = NULL){m_hResFinalConstruct = FinalConstruct();}
  2569.     ~CComObjectStack()
  2570.     {
  2571.         FinalRelease();
  2572. #ifdef _ATL_DEBUG_INTERFACES
  2573.         _Module.DeleteNonAddRefThunk(_GetRawUnknown());
  2574. #endif
  2575.     }
  2576.  
  2577.  
  2578.     STDMETHOD_(ULONG, AddRef)() {ATLASSERT(FALSE);return 0;}
  2579.     STDMETHOD_(ULONG, Release)(){ATLASSERT(FALSE);return 0;}
  2580.     STDMETHOD(QueryInterface)(REFIID iid, void ** ppvObject)
  2581.     {ATLASSERT(FALSE);return E_NOINTERFACE;}
  2582.     HRESULT m_hResFinalConstruct;
  2583. };
  2584.  
  2585. template <class Base> //Base must be derived from CComObjectRoot
  2586. class CComContainedObject : public Base
  2587. {
  2588. public:
  2589.     typedef Base _BaseClass;
  2590.     CComContainedObject(void* pv) {m_pOuterUnknown = (IUnknown*)pv;}
  2591. #ifdef _ATL_DEBUG_INTERFACES
  2592.     ~CComContainedObject()
  2593.     {
  2594.         _Module.DeleteNonAddRefThunk(_GetRawUnknown());
  2595.         _Module.DeleteNonAddRefThunk(m_pOuterUnknown);
  2596.     }
  2597. #endif
  2598.  
  2599.     STDMETHOD_(ULONG, AddRef)() {return OuterAddRef();}
  2600.     STDMETHOD_(ULONG, Release)() {return OuterRelease();}
  2601.     STDMETHOD(QueryInterface)(REFIID iid, void ** ppvObject)
  2602.     {
  2603.         HRESULT hr = OuterQueryInterface(iid, ppvObject);
  2604.         if (FAILED(hr) && _GetRawUnknown() != m_pOuterUnknown)
  2605.             hr = _InternalQueryInterface(iid, ppvObject);
  2606.         return hr;
  2607.     }
  2608.     template <class Q>
  2609.     HRESULT STDMETHODCALLTYPE QueryInterface(Q** pp)
  2610.     {
  2611.         return QueryInterface(__uuidof(Q), (void**)pp);
  2612.     }
  2613.     //GetControllingUnknown may be virtual if the Base class has declared
  2614.     //DECLARE_GET_CONTROLLING_UNKNOWN()
  2615.     IUnknown* GetControllingUnknown()
  2616.     {
  2617. #ifdef _ATL_DEBUG_INTERFACES
  2618.         IUnknown* p;
  2619.         _Module.AddNonAddRefThunk(m_pOuterUnknown, _T("CComContainedObject"), &p);
  2620.         return p;
  2621. #else
  2622.         return m_pOuterUnknown;
  2623. #endif
  2624.     }
  2625. };
  2626.  
  2627. //contained is the user's class that derives from CComObjectRoot and whatever
  2628. //interfaces the user wants to support on the object
  2629. template <class contained>
  2630. class CComAggObject :
  2631.     public IUnknown,
  2632.     public CComObjectRootEx< contained::_ThreadModel::ThreadModelNoCS >
  2633. {
  2634. public:
  2635.     typedef contained _BaseClass;
  2636.     CComAggObject(void* pv) : m_contained(pv)
  2637.     {
  2638.         _Module.Lock();
  2639.     }
  2640.     //If you get a message that this call is ambiguous then you need to
  2641.     // override it in your class and call each base class' version of this
  2642.     HRESULT FinalConstruct()
  2643.     {
  2644.         CComObjectRootEx<contained::_ThreadModel::ThreadModelNoCS>::FinalConstruct();
  2645.         return m_contained.FinalConstruct();
  2646.     }
  2647.     void FinalRelease()
  2648.     {
  2649.         CComObjectRootEx<contained::_ThreadModel::ThreadModelNoCS>::FinalRelease();
  2650.         m_contained.FinalRelease();
  2651.     }
  2652.     // Set refcount to 1 to protect destruction
  2653.     ~CComAggObject()
  2654.     {
  2655.         m_dwRef = 1L;
  2656.         FinalRelease();
  2657. #ifdef _ATL_DEBUG_INTERFACES
  2658.         _Module.DeleteNonAddRefThunk(this);
  2659. #endif
  2660.         _Module.Unlock();
  2661.     }
  2662.  
  2663.     STDMETHOD_(ULONG, AddRef)() {return InternalAddRef();}
  2664.     STDMETHOD_(ULONG, Release)()
  2665.     {
  2666.         ULONG l = InternalRelease();
  2667.         if (l == 0)
  2668.             delete this;
  2669.         return l;
  2670.     }
  2671.     STDMETHOD(QueryInterface)(REFIID iid, void ** ppvObject)
  2672.     {
  2673.         HRESULT hRes = S_OK;
  2674.         if (InlineIsEqualUnknown(iid))
  2675.         {
  2676.             if (ppvObject == NULL)
  2677.                 return E_POINTER;
  2678.             *ppvObject = (void*)(IUnknown*)this;
  2679.             AddRef();
  2680. #ifdef _ATL_DEBUG_INTERFACES
  2681.             _Module.AddThunk((IUnknown**)ppvObject, (LPCTSTR)contained::_GetEntries()[-1].dw, iid);
  2682. #endif // _ATL_DEBUG_INTERFACES
  2683.         }
  2684.         else
  2685.             hRes = m_contained._InternalQueryInterface(iid, ppvObject);
  2686.         return hRes;
  2687.     }
  2688.     template <class Q>
  2689.     HRESULT STDMETHODCALLTYPE QueryInterface(Q** pp)
  2690.     {
  2691.         return QueryInterface(__uuidof(Q), (void**)pp);
  2692.     }
  2693.     static HRESULT WINAPI CreateInstance(LPUNKNOWN pUnkOuter, CComAggObject<contained>** pp)
  2694.     {
  2695.         ATLASSERT(pp != NULL);
  2696.         HRESULT hRes = E_OUTOFMEMORY;
  2697.         CComAggObject<contained>* p = NULL;
  2698.         ATLTRY(p = new CComAggObject<contained>(pUnkOuter))
  2699.         if (p != NULL)
  2700.         {
  2701.             p->SetVoid(NULL);
  2702.             p->InternalFinalConstructAddRef();
  2703.             hRes = p->FinalConstruct();
  2704.             p->InternalFinalConstructRelease();
  2705.             if (hRes != S_OK)
  2706.             {
  2707.                 delete p;
  2708.                 p = NULL;
  2709.             }
  2710.         }
  2711.         *pp = p;
  2712.         return hRes;
  2713.     }
  2714.  
  2715.     CComContainedObject<contained> m_contained;
  2716. };
  2717.  
  2718. ///////////////////////////////////////////////////////////////////////////////
  2719. // CComPolyObject can be either aggregated or not aggregated
  2720.  
  2721. template <class contained>
  2722. class CComPolyObject :
  2723.     public IUnknown,
  2724.     public CComObjectRootEx< contained::_ThreadModel::ThreadModelNoCS >
  2725. {
  2726. public:
  2727.     typedef contained _BaseClass;
  2728.     CComPolyObject(void* pv) : m_contained(pv ? pv : this)
  2729.     {
  2730.         _Module.Lock();
  2731.     }
  2732.     //If you get a message that this call is ambiguous then you need to
  2733.     // override it in your class and call each base class' version of this
  2734.     HRESULT FinalConstruct()
  2735.     {
  2736.         InternalAddRef();
  2737.         CComObjectRootEx<contained::_ThreadModel::ThreadModelNoCS>::FinalConstruct();
  2738.         HRESULT hr = m_contained.FinalConstruct();
  2739.         InternalRelease();
  2740.         return hr;
  2741.     }
  2742.     void FinalRelease()
  2743.     {
  2744.         CComObjectRootEx<contained::_ThreadModel::ThreadModelNoCS>::FinalRelease();
  2745.         m_contained.FinalRelease();
  2746.     }
  2747.     // Set refcount to 1 to protect destruction
  2748.     ~CComPolyObject()
  2749.     {
  2750.         m_dwRef = 1L;
  2751.         FinalRelease();
  2752. #ifdef _ATL_DEBUG_INTERFACES
  2753.         _Module.DeleteNonAddRefThunk(this);
  2754. #endif
  2755.         _Module.Unlock();
  2756.     }
  2757.  
  2758.     STDMETHOD_(ULONG, AddRef)() {return InternalAddRef();}
  2759.     STDMETHOD_(ULONG, Release)()
  2760.     {
  2761.         ULONG l = InternalRelease();
  2762.         if (l == 0)
  2763.             delete this;
  2764.         return l;
  2765.     }
  2766.     STDMETHOD(QueryInterface)(REFIID iid, void ** ppvObject)
  2767.     {
  2768.         HRESULT hRes = S_OK;
  2769.         if (InlineIsEqualUnknown(iid))
  2770.         {
  2771.             if (ppvObject == NULL)
  2772.                 return E_POINTER;
  2773.             *ppvObject = (void*)(IUnknown*)this;
  2774.             AddRef();
  2775. #ifdef _ATL_DEBUG_INTERFACES
  2776.             _Module.AddThunk((IUnknown**)ppvObject, (LPCTSTR)contained::_GetEntries()[-1].dw, iid);
  2777. #endif // _ATL_DEBUG_INTERFACES
  2778.         }
  2779.         else
  2780.             hRes = m_contained._InternalQueryInterface(iid, ppvObject);
  2781.         return hRes;
  2782.     }
  2783.     template <class Q>
  2784.     HRESULT STDMETHODCALLTYPE QueryInterface(Q** pp)
  2785.     {
  2786.         return QueryInterface(__uuidof(Q), (void**)pp);
  2787.     }
  2788.     static HRESULT WINAPI CreateInstance(LPUNKNOWN pUnkOuter, CComPolyObject<contained>** pp)
  2789.     {
  2790.         ATLASSERT(pp != NULL);
  2791.         HRESULT hRes = E_OUTOFMEMORY;
  2792.         CComPolyObject<contained>* p = NULL;
  2793.         ATLTRY(p = new CComPolyObject<contained>(pUnkOuter))
  2794.         if (p != NULL)
  2795.         {
  2796.             p->SetVoid(NULL);
  2797.             p->InternalFinalConstructAddRef();
  2798.             hRes = p->FinalConstruct();
  2799.             p->InternalFinalConstructRelease();
  2800.             if (hRes != S_OK)
  2801.             {
  2802.                 delete p;
  2803.                 p = NULL;
  2804.             }
  2805.         }
  2806.         *pp = p;
  2807.         return hRes;
  2808.     }
  2809.  
  2810.     CComContainedObject<contained> m_contained;
  2811. };
  2812.  
  2813. template <class Base>
  2814. class CComTearOffObject : public Base
  2815. {
  2816. public:
  2817.     CComTearOffObject(void* pv)
  2818.     {
  2819.         ATLASSERT(m_pOwner == NULL);
  2820.         m_pOwner = reinterpret_cast<CComObject<Base::_OwnerClass>*>(pv);
  2821.         m_pOwner->AddRef();
  2822.     }
  2823.     // Set refcount to 1 to protect destruction
  2824.     ~CComTearOffObject()
  2825.     {
  2826.         m_dwRef = 1L;
  2827.         FinalRelease();
  2828. #ifdef _ATL_DEBUG_INTERFACES
  2829.         _Module.DeleteNonAddRefThunk(_GetRawUnknown());
  2830. #endif
  2831.         m_pOwner->Release();
  2832.     }
  2833.  
  2834.     STDMETHOD_(ULONG, AddRef)() {return InternalAddRef();}
  2835.     STDMETHOD_(ULONG, Release)()
  2836.     {
  2837.         ULONG l = InternalRelease();
  2838.         if (l == 0)
  2839.             delete this;
  2840.         return l;
  2841.     }
  2842.     STDMETHOD(QueryInterface)(REFIID iid, void ** ppvObject)
  2843.     {
  2844.         return m_pOwner->QueryInterface(iid, ppvObject);
  2845.     }
  2846. };
  2847.  
  2848. template <class contained>
  2849. class CComCachedTearOffObject :
  2850.     public IUnknown,
  2851.     public CComObjectRootEx<contained::_ThreadModel::ThreadModelNoCS>
  2852. {
  2853. public:
  2854.     typedef contained _BaseClass;
  2855.     CComCachedTearOffObject(void* pv) :
  2856.         m_contained(((contained::_OwnerClass*)pv)->GetControllingUnknown())
  2857.     {
  2858.         ATLASSERT(m_contained.m_pOwner == NULL);
  2859.         m_contained.m_pOwner = reinterpret_cast<CComObject<contained::_OwnerClass>*>(pv);
  2860.     }
  2861.     //If you get a message that this call is ambiguous then you need to
  2862.     // override it in your class and call each base class' version of this
  2863.     HRESULT FinalConstruct()
  2864.     {
  2865.         CComObjectRootEx<contained::_ThreadModel::ThreadModelNoCS>::FinalConstruct();
  2866.         return m_contained.FinalConstruct();
  2867.     }
  2868.     void FinalRelease()
  2869.     {
  2870.         CComObjectRootEx<contained::_ThreadModel::ThreadModelNoCS>::FinalRelease();
  2871.         m_contained.FinalRelease();
  2872.     }
  2873.     // Set refcount to 1 to protect destruction
  2874.     ~CComCachedTearOffObject()
  2875.     {
  2876.         m_dwRef = 1L;
  2877.         FinalRelease();
  2878. #ifdef _ATL_DEBUG_INTERFACES
  2879.         _Module.DeleteNonAddRefThunk(this);
  2880. #endif
  2881.     }
  2882.  
  2883.  
  2884.     STDMETHOD_(ULONG, AddRef)() {return InternalAddRef();}
  2885.     STDMETHOD_(ULONG, Release)()
  2886.     {
  2887.         ULONG l = InternalRelease();
  2888.         if (l == 0)
  2889.             delete this;
  2890.         return l;
  2891.     }
  2892.     STDMETHOD(QueryInterface)(REFIID iid, void ** ppvObject)
  2893.     {
  2894.         HRESULT hRes = S_OK;
  2895.         if (InlineIsEqualUnknown(iid))
  2896.         {
  2897.             if (ppvObject == NULL)
  2898.                 return E_POINTER;
  2899.             *ppvObject = (void*)(IUnknown*)this;
  2900.             AddRef();
  2901. #ifdef _ATL_DEBUG_INTERFACES
  2902.             _Module.AddThunk((IUnknown**)ppvObject, (LPCTSTR)contained::_GetEntries()[-1].dw, iid);
  2903. #endif // _ATL_DEBUG_INTERFACES
  2904.         }
  2905.         else
  2906.             hRes = m_contained._InternalQueryInterface(iid, ppvObject);
  2907.         return hRes;
  2908.     }
  2909.     CComContainedObject<contained> m_contained;
  2910. };
  2911.  
  2912. class CComClassFactory :
  2913.     public IClassFactory,
  2914.     public CComObjectRootEx<CComGlobalsThreadModel>
  2915. {
  2916. public:
  2917.     BEGIN_COM_MAP(CComClassFactory)
  2918.         COM_INTERFACE_ENTRY(IClassFactory)
  2919.     END_COM_MAP()
  2920.  
  2921.     // IClassFactory
  2922.     STDMETHOD(CreateInstance)(LPUNKNOWN pUnkOuter, REFIID riid, void** ppvObj)
  2923.     {
  2924.         ATLASSERT(m_pfnCreateInstance != NULL);
  2925.         HRESULT hRes = E_POINTER;
  2926.         if (ppvObj != NULL)
  2927.         {
  2928.             *ppvObj = NULL;
  2929.             // can't ask for anything other than IUnknown when aggregating
  2930.             
  2931.             if ((pUnkOuter != NULL) && !InlineIsEqualUnknown(riid))
  2932.             {
  2933.                 ATLTRACE2(atlTraceCOM, 0, _T("CComClassFactory: asked for non IUnknown interface while creating an aggregated object"));
  2934.                 hRes = CLASS_E_NOAGGREGATION;
  2935.             }
  2936.             else
  2937.                 hRes = m_pfnCreateInstance(pUnkOuter, riid, ppvObj);
  2938.         }
  2939.         return hRes;
  2940.     }
  2941.  
  2942.     STDMETHOD(LockServer)(BOOL fLock)
  2943.     {
  2944.         if (fLock)
  2945.             _Module.Lock();
  2946.         else
  2947.             _Module.Unlock();
  2948.         return S_OK;
  2949.     }
  2950.     // helper
  2951.     void SetVoid(void* pv)
  2952.     {
  2953.         m_pfnCreateInstance = (_ATL_CREATORFUNC*)pv;
  2954.     }
  2955.     _ATL_CREATORFUNC* m_pfnCreateInstance;
  2956. };
  2957.  
  2958. template <class license>
  2959. class CComClassFactory2 : 
  2960.     public IClassFactory2,
  2961.     public CComObjectRootEx<CComGlobalsThreadModel>,
  2962.     public license
  2963. {
  2964. public:
  2965.     typedef license _LicenseClass;
  2966.     typedef CComClassFactory2<license> _ComMapClass;
  2967. BEGIN_COM_MAP(CComClassFactory2<license>)
  2968.     COM_INTERFACE_ENTRY(IClassFactory)
  2969.     COM_INTERFACE_ENTRY(IClassFactory2)
  2970. END_COM_MAP()
  2971.     // IClassFactory
  2972.     STDMETHOD(LockServer)(BOOL fLock)
  2973.     {
  2974.         if (fLock)
  2975.             _Module.Lock();
  2976.         else
  2977.             _Module.Unlock();
  2978.         return S_OK;
  2979.     }
  2980.     STDMETHOD(CreateInstance)(LPUNKNOWN pUnkOuter,
  2981.         REFIID riid, void** ppvObj)
  2982.     {
  2983.         ATLASSERT(m_pfnCreateInstance != NULL);
  2984.         if (ppvObj == NULL)
  2985.             return E_POINTER;
  2986.         *ppvObj = NULL;
  2987.         if (!IsLicenseValid())
  2988.             return CLASS_E_NOTLICENSED;
  2989.  
  2990.         if ((pUnkOuter != NULL) && !InlineIsEqualUnknown(riid))
  2991.             return CLASS_E_NOAGGREGATION;
  2992.         else
  2993.             return m_pfnCreateInstance(pUnkOuter, riid, ppvObj);
  2994.     }
  2995.     // IClassFactory2
  2996.     STDMETHOD(CreateInstanceLic)(IUnknown* pUnkOuter, IUnknown* pUnkReserved,
  2997.                 REFIID riid, BSTR bstrKey, void** ppvObject)
  2998.     {
  2999.         ATLASSERT(m_pfnCreateInstance != NULL);
  3000.         if (ppvObject == NULL)
  3001.             return E_POINTER;
  3002.         *ppvObject = NULL;
  3003.         if ( ((bstrKey != NULL) && !VerifyLicenseKey(bstrKey)) ||
  3004.              ((bstrKey == NULL) && !IsLicenseValid()) )
  3005.             return CLASS_E_NOTLICENSED;
  3006.         if ((pUnkOuter != NULL) && !InlineIsEqualUnknown(riid))
  3007.             return CLASS_E_NOAGGREGATION;
  3008.         else
  3009.             return m_pfnCreateInstance(pUnkOuter, riid, ppvObject);
  3010.     }
  3011.     STDMETHOD(RequestLicKey)(DWORD dwReserved, BSTR* pbstrKey)
  3012.     {
  3013.         if (pbstrKey == NULL)
  3014.             return E_POINTER;
  3015.         *pbstrKey = NULL;
  3016.  
  3017.         if (!IsLicenseValid())
  3018.             return CLASS_E_NOTLICENSED;
  3019.         return GetLicenseKey(dwReserved,pbstrKey) ? S_OK : E_FAIL;
  3020.     }
  3021.     STDMETHOD(GetLicInfo)(LICINFO* pLicInfo)
  3022.     {
  3023.         if (pLicInfo == NULL)
  3024.             return E_POINTER;
  3025.         pLicInfo->cbLicInfo = sizeof(LICINFO);
  3026.         pLicInfo->fLicVerified = IsLicenseValid();
  3027.         BSTR bstr = NULL;
  3028.         pLicInfo->fRuntimeKeyAvail = GetLicenseKey(0,&bstr);
  3029.         ::SysFreeString(bstr);
  3030.         return S_OK;
  3031.     }
  3032.     void SetVoid(void* pv)
  3033.     {
  3034.         m_pfnCreateInstance = (_ATL_CREATORFUNC*)pv;
  3035.     }
  3036.     _ATL_CREATORFUNC* m_pfnCreateInstance;
  3037. };
  3038.  
  3039. /////////////////////////////////////////////////////////////////////////////////////////////
  3040. // Thread Pooling class factory
  3041.  
  3042. class CComClassFactoryAutoThread :
  3043.     public IClassFactory,
  3044.     public CComObjectRootEx<CComGlobalsThreadModel>
  3045. {
  3046. public:
  3047.     BEGIN_COM_MAP(CComClassFactoryAutoThread)
  3048.         COM_INTERFACE_ENTRY(IClassFactory)
  3049.     END_COM_MAP()
  3050.  
  3051.     // helper
  3052.     void SetVoid(void* pv)
  3053.     {
  3054.         m_pfnCreateInstance = (_ATL_CREATORFUNC*)pv;
  3055.     }
  3056.     STDMETHODIMP CreateInstance(LPUNKNOWN pUnkOuter,
  3057.         REFIID riid, void** ppvObj)
  3058.     {
  3059.         ATLASSERT(m_pfnCreateInstance != NULL);
  3060.         HRESULT hRes = E_POINTER;
  3061.         if (ppvObj != NULL)
  3062.         {
  3063.             *ppvObj = NULL;
  3064.             // cannot aggregate across apartments
  3065.             ATLASSERT(pUnkOuter == NULL);
  3066.             if (pUnkOuter != NULL)
  3067.                 hRes = CLASS_E_NOAGGREGATION;
  3068.             else
  3069.                 hRes = _Module.CreateInstance(m_pfnCreateInstance, riid, ppvObj);
  3070.         }
  3071.         return hRes;
  3072.     }
  3073.     STDMETHODIMP LockServer(BOOL fLock)
  3074.     {
  3075.         if (fLock)
  3076.             _Module.Lock();
  3077.         else
  3078.             _Module.Unlock();
  3079.         return S_OK;
  3080.     }
  3081.     _ATL_CREATORFUNC* m_pfnCreateInstance;
  3082. };
  3083.  
  3084. /////////////////////////////////////////////////////////////////////////////////////////////
  3085. // Singleton Class Factory
  3086. template <class T>
  3087. class CComClassFactorySingleton : public CComClassFactory
  3088. {
  3089. public:
  3090.     void FinalRelease()
  3091.     {
  3092.         CoDisconnectObject(m_Obj.GetUnknown(), 0);
  3093.     }
  3094.  
  3095.     // IClassFactory
  3096.     STDMETHOD(CreateInstance)(LPUNKNOWN pUnkOuter, REFIID riid, void** ppvObj)
  3097.     {
  3098.         HRESULT hRes = E_POINTER;
  3099.         if (ppvObj != NULL)
  3100.         {
  3101.             *ppvObj = NULL;
  3102.             // aggregation is not supported in Singletons
  3103.             ATLASSERT(pUnkOuter == NULL);
  3104.             if (pUnkOuter != NULL)
  3105.                 hRes = CLASS_E_NOAGGREGATION;
  3106.             else
  3107.             {
  3108.                 if (m_Obj.m_hResFinalConstruct != S_OK)
  3109.                     hRes = m_Obj.m_hResFinalConstruct;
  3110.                 else
  3111.                     hRes = m_Obj.QueryInterface(riid, ppvObj);
  3112.             }
  3113.         }
  3114.         return hRes;
  3115.     }
  3116.     CComObjectGlobal<T> m_Obj;
  3117. };
  3118.  
  3119. template <class T, const CLSID* pclsid = &CLSID_NULL>
  3120. class CComCoClass
  3121. {
  3122. public:
  3123.     DECLARE_CLASSFACTORY()
  3124.     DECLARE_AGGREGATABLE(T)
  3125.     typedef T _CoClass;
  3126.     static const CLSID& WINAPI GetObjectCLSID() {return *pclsid;}
  3127.     static LPCTSTR WINAPI GetObjectDescription() {return NULL;}
  3128.     static const struct _ATL_CATMAP_ENTRY* GetCategoryMap() {return NULL;};
  3129.     static HRESULT WINAPI Error(LPCOLESTR lpszDesc,
  3130.         const IID& iid = GUID_NULL, HRESULT hRes = 0)
  3131.     {
  3132.         return AtlReportError(GetObjectCLSID(), lpszDesc, iid, hRes);
  3133.     }
  3134.     static HRESULT WINAPI Error(LPCOLESTR lpszDesc, DWORD dwHelpID,
  3135.         LPCOLESTR lpszHelpFile, const IID& iid = GUID_NULL, HRESULT hRes = 0)
  3136.     {
  3137.         return AtlReportError(GetObjectCLSID(), lpszDesc, dwHelpID, lpszHelpFile,
  3138.             iid, hRes);
  3139.     }
  3140.     static HRESULT WINAPI Error(UINT nID, const IID& iid = GUID_NULL,
  3141.         HRESULT hRes = 0, HINSTANCE hInst = _Module.GetResourceInstance())
  3142.     {
  3143.         return AtlReportError(GetObjectCLSID(), nID, iid, hRes, hInst);
  3144.     }
  3145.     static HRESULT WINAPI Error(UINT nID, DWORD dwHelpID,
  3146.         LPCOLESTR lpszHelpFile, const IID& iid = GUID_NULL,
  3147.         HRESULT hRes = 0, HINSTANCE hInst = _Module.GetResourceInstance())
  3148.     {
  3149.         return AtlReportError(GetObjectCLSID(), nID, dwHelpID, lpszHelpFile,
  3150.             iid, hRes, hInst);
  3151.     }
  3152. #ifndef OLE2ANSI
  3153.     static HRESULT WINAPI Error(LPCSTR lpszDesc,
  3154.         const IID& iid = GUID_NULL, HRESULT hRes = 0)
  3155.     {
  3156.         return AtlReportError(GetObjectCLSID(), lpszDesc, iid, hRes);
  3157.     }
  3158.     static HRESULT WINAPI Error(LPCSTR lpszDesc, DWORD dwHelpID,
  3159.         LPCSTR lpszHelpFile, const IID& iid = GUID_NULL, HRESULT hRes = 0)
  3160.     {
  3161.         return AtlReportError(GetObjectCLSID(), lpszDesc, dwHelpID,
  3162.             lpszHelpFile, iid, hRes);
  3163.     }
  3164. #endif
  3165.     template <class Q>
  3166.     static HRESULT CreateInstance(IUnknown* punkOuter, Q** pp)
  3167.     {
  3168.         return T::_CreatorClass::CreateInstance(punkOuter, __uuidof(Q), (void**) pp);
  3169.     }
  3170.     template <class Q>
  3171.     static HRESULT CreateInstance(Q** pp)
  3172.     {
  3173.         return T::_CreatorClass::CreateInstance(NULL, __uuidof(Q), (void**) pp);
  3174.     }
  3175. };
  3176.  
  3177. // ATL doesn't support multiple LCID's at the same time
  3178. // Whatever LCID is queried for first is the one that is used.
  3179. class CComTypeInfoHolder
  3180. {
  3181. // Should be 'protected' but can cause compiler to generate fat code.
  3182. public:
  3183.     const GUID* m_pguid;
  3184.     const GUID* m_plibid;
  3185.     WORD m_wMajor;
  3186.     WORD m_wMinor;
  3187.  
  3188.     ITypeInfo* m_pInfo;
  3189.     long m_dwRef;
  3190.     struct stringdispid
  3191.     {
  3192.         CComBSTR bstr;
  3193.         int nLen;
  3194.         DISPID id;
  3195.     };
  3196.     stringdispid* m_pMap;
  3197.     int m_nCount;
  3198.  
  3199. public:
  3200.     HRESULT GetTI(LCID lcid, ITypeInfo** ppInfo)
  3201.     {
  3202.         HRESULT hr = S_OK;
  3203.         if (m_pInfo == NULL)
  3204.             hr = GetTI(lcid);
  3205.         *ppInfo = m_pInfo;
  3206.         if (m_pInfo != NULL)
  3207.         {
  3208.             m_pInfo->AddRef();
  3209.             hr = S_OK;
  3210.         }
  3211.         return hr;
  3212.     }
  3213.     HRESULT GetTI(LCID lcid);
  3214.     HRESULT EnsureTI(LCID lcid)
  3215.     {
  3216.         HRESULT hr = S_OK;
  3217.         if (m_pInfo == NULL)
  3218.             hr = GetTI(lcid);
  3219.         return hr;
  3220.     }
  3221.  
  3222.     // This function is called by the module on exit
  3223.     // It is registered through _Module.AddTermFunc()
  3224.     static void __stdcall Cleanup(DWORD dw)
  3225.     {
  3226.         CComTypeInfoHolder* p = (CComTypeInfoHolder*) dw;
  3227.         if (p->m_pInfo != NULL)
  3228.             p->m_pInfo->Release();
  3229.         p->m_pInfo = NULL;
  3230.         delete [] p->m_pMap;
  3231.         p->m_pMap = NULL;
  3232.     }
  3233.  
  3234.     HRESULT GetTypeInfo(UINT /* itinfo */, LCID lcid, ITypeInfo** pptinfo)
  3235.     {
  3236.         HRESULT hRes = E_POINTER;
  3237.         if (pptinfo != NULL)
  3238.             hRes = GetTI(lcid, pptinfo);
  3239.         return hRes;
  3240.     }
  3241.     HRESULT GetIDsOfNames(REFIID /* riid */, LPOLESTR* rgszNames, UINT cNames,
  3242.         LCID lcid, DISPID* rgdispid)
  3243.     {
  3244.         HRESULT hRes = EnsureTI(lcid);
  3245.         if (m_pInfo != NULL)
  3246.         {
  3247.             for (int i=0; i<(int)cNames; i++)
  3248.             {
  3249.                 int n = ocslen(rgszNames[i]);
  3250.                 for (int j=m_nCount-1; j>=0; j--)
  3251.                 {
  3252.                     if ((n == m_pMap[j].nLen) &&
  3253.                         (memcmp(m_pMap[j].bstr, rgszNames[i], m_pMap[j].nLen * sizeof(OLECHAR)) == 0))
  3254.                     {
  3255.                         rgdispid[i] = m_pMap[j].id;
  3256.                         break;
  3257.                     }
  3258.                 }
  3259.                 if (j < 0)
  3260.                 {
  3261.                     hRes = m_pInfo->GetIDsOfNames(rgszNames + i, 1, &rgdispid[i]);
  3262.                     if (FAILED(hRes))
  3263.                         break;
  3264.                 }
  3265.             }
  3266.         }
  3267.         return hRes;
  3268.     }
  3269.  
  3270.     HRESULT Invoke(IDispatch* p, DISPID dispidMember, REFIID /* riid */,
  3271.         LCID lcid, WORD wFlags, DISPPARAMS* pdispparams, VARIANT* pvarResult,
  3272.         EXCEPINFO* pexcepinfo, UINT* puArgErr)
  3273.     {
  3274.         HRESULT hRes = EnsureTI(lcid);
  3275.         if (m_pInfo != NULL)
  3276.             hRes = m_pInfo->Invoke(p, dispidMember, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr);
  3277.         return hRes;
  3278.     }
  3279.     HRESULT LoadNameCache(ITypeInfo* pTypeInfo)
  3280.     {
  3281.         TYPEATTR* pta;
  3282.         HRESULT hr = pTypeInfo->GetTypeAttr(&pta);
  3283.         if (SUCCEEDED(hr))
  3284.         {
  3285.             m_nCount = pta->cFuncs;
  3286.             m_pMap = m_nCount == 0 ? 0 : new stringdispid[m_nCount];
  3287.             for (int i=0; i<m_nCount; i++)
  3288.             {
  3289.                 FUNCDESC* pfd;
  3290.                 if (SUCCEEDED(pTypeInfo->GetFuncDesc(i, &pfd)))
  3291.                 {
  3292.                     CComBSTR bstrName;
  3293.                     if (SUCCEEDED(pTypeInfo->GetDocumentation(pfd->memid, &bstrName, NULL, NULL, NULL)))
  3294.                     {
  3295.                         m_pMap[i].bstr.Attach(bstrName.Detach());
  3296.                         m_pMap[i].nLen = SysStringLen(m_pMap[i].bstr);
  3297.                         m_pMap[i].id = pfd->memid;
  3298.                     }
  3299.                     pTypeInfo->ReleaseFuncDesc(pfd);
  3300.                 }
  3301.             }
  3302.             pTypeInfo->ReleaseTypeAttr(pta);
  3303.         }
  3304.         return S_OK;
  3305.     }
  3306. };
  3307.  
  3308.  
  3309. inline HRESULT CComTypeInfoHolder::GetTI(LCID lcid)
  3310. {
  3311.     //If this assert occurs then most likely didn't initialize properly
  3312.     ATLASSERT(m_plibid != NULL && m_pguid != NULL);
  3313.     ATLASSERT(!InlineIsEqualGUID(*m_plibid, GUID_NULL) && "Did you forget to pass the LIBID to CComModule::Init?");
  3314.  
  3315.     if (m_pInfo != NULL)
  3316.         return S_OK;
  3317.     HRESULT hRes = E_FAIL;
  3318.     EnterCriticalSection(&_Module.m_csTypeInfoHolder);
  3319.     if (m_pInfo == NULL)
  3320.     {
  3321.         ITypeLib* pTypeLib;
  3322.         hRes = LoadRegTypeLib(*m_plibid, m_wMajor, m_wMinor, lcid, &pTypeLib);
  3323.         if (SUCCEEDED(hRes))
  3324.         {
  3325.             CComPtr<ITypeInfo> spTypeInfo;
  3326.             hRes = pTypeLib->GetTypeInfoOfGuid(*m_pguid, &spTypeInfo);
  3327.             if (SUCCEEDED(hRes))
  3328.             {
  3329.                 CComPtr<ITypeInfo> spInfo(spTypeInfo);
  3330.                 CComPtr<ITypeInfo2> spTypeInfo2;
  3331.                 if (SUCCEEDED(spTypeInfo->QueryInterface(&spTypeInfo2)))
  3332.                     spInfo = spTypeInfo2;
  3333.  
  3334.                 LoadNameCache(spInfo);
  3335.                 m_pInfo = spInfo.Detach();
  3336.             }
  3337.             pTypeLib->Release();
  3338.         }
  3339.     }
  3340.     LeaveCriticalSection(&_Module.m_csTypeInfoHolder);
  3341.     _Module.AddTermFunc(Cleanup, (DWORD)this);
  3342.     return hRes;
  3343. }
  3344.  
  3345. //////////////////////////////////////////////////////////////////////////////
  3346. // IObjectWithSite
  3347. //
  3348. template <class T>
  3349. class ATL_NO_VTABLE IObjectWithSiteImpl : public IObjectWithSite
  3350. {
  3351. public:
  3352.     STDMETHOD(SetSite)(IUnknown *pUnkSite)
  3353.     {
  3354.         ATLTRACE2(atlTraceCOM, 0, _T("IObjectWithSiteImpl::SetSite\n"));
  3355.         T* pT = static_cast<T*>(this);
  3356.         pT->m_spUnkSite = pUnkSite;
  3357.         return S_OK;
  3358.     }
  3359.     STDMETHOD(GetSite)(REFIID riid, void **ppvSite)
  3360.     {
  3361.         ATLTRACE2(atlTraceCOM, 0, _T("IObjectWithSiteImpl::GetSite\n"));
  3362.         T* pT = static_cast<T*>(this);
  3363.         ATLASSERT(ppvSite);
  3364.         HRESULT hRes = E_POINTER;
  3365.         if (ppvSite != NULL)
  3366.         {
  3367.             if (pT->m_spUnkSite)
  3368.                 hRes = pT->m_spUnkSite->QueryInterface(riid, ppvSite);
  3369.             else
  3370.             {
  3371.                 *ppvSite = NULL;
  3372.                 hRes = E_FAIL;
  3373.             }
  3374.         }
  3375.         return hRes;
  3376.     }
  3377.  
  3378.     HRESULT SetChildSite(IUnknown* punkChild)
  3379.     {
  3380.         if (punkChild == NULL)
  3381.             return E_POINTER;
  3382.  
  3383.         HRESULT hr;
  3384.         CComPtr<IObjectWithSite> spChildSite;
  3385.         hr = punkChild->QueryInterface(IID_IObjectWithSite, (void**)&spChildSite);
  3386.         if (SUCCEEDED(hr))
  3387.             hr = spChildSite->SetSite((IUnknown*)this);
  3388.  
  3389.         return hr;
  3390.     }
  3391.  
  3392.     static HRESULT SetChildSite(IUnknown* punkChild, IUnknown* punkParent)
  3393.     {
  3394.         return AtlSetChildSite(punkChild, punkParent);
  3395.     }
  3396.  
  3397.     CComPtr<IUnknown> m_spUnkSite;
  3398. };
  3399.  
  3400. //////////////////////////////////////////////////////////////////////////////
  3401. // IServiceProvider
  3402. //
  3403. template <class T>
  3404. class ATL_NO_VTABLE IServiceProviderImpl : public IServiceProvider
  3405. {
  3406. public:
  3407.     STDMETHOD(QueryService)(REFGUID guidService, REFIID riid, void** ppvObject)
  3408.     {
  3409.         ATLTRACE2(atlTraceCOM, 0, _T("IServiceProviderImpl::QueryService\n"));
  3410.         T* pT = static_cast<T*>(this);
  3411.         return pT->_InternalQueryService(guidService, riid, ppvObject);
  3412.     }
  3413. };
  3414.  
  3415. #define BEGIN_SERVICE_MAP(x) public: \
  3416.     HRESULT _InternalQueryService(REFGUID guidService, REFIID riid, void** ppvObject) \
  3417.     {
  3418.  
  3419. #define SERVICE_ENTRY(x) \
  3420.         if (InlineIsEqualGUID(guidService, x)) \
  3421.             return QueryInterface(riid, ppvObject);
  3422.  
  3423. #define SERVICE_ENTRY_CHAIN(x) \
  3424.         CComQIPtr<IServiceProvider, &IID_IServiceProvider> spProvider(x); \
  3425.         if (spProvider != NULL) \
  3426.             return spProvider->QueryService(guidService, riid, ppvObject);
  3427.  
  3428. #define END_SERVICE_MAP() \
  3429.         return E_NOINTERFACE; \
  3430.     }
  3431.  
  3432.  
  3433. /////////////////////////////////////////////////////////////////////////////
  3434. // IDispEventImpl
  3435.  
  3436. #ifdef _ATL_DLL
  3437. ATLAPI AtlGetObjectSourceInterface(IUnknown* punkObj, GUID* plibid, IID* piid, unsigned short* pdwMajor, unsigned short* pdwMinor);
  3438. #else
  3439. ATLINLINE ATLAPI AtlGetObjectSourceInterface(IUnknown* punkObj, GUID* plibid, IID* piid, unsigned short* pdwMajor, unsigned short* pdwMinor)
  3440. {
  3441.     HRESULT hr = E_FAIL;
  3442.     if (punkObj != NULL)
  3443.     {
  3444.         CComPtr<IDispatch> spDispatch;
  3445.         hr = punkObj->QueryInterface(IID_IDispatch, (void**)&spDispatch);
  3446.         if (SUCCEEDED(hr))
  3447.         {
  3448.             CComPtr<ITypeInfo> spTypeInfo;
  3449.             hr = spDispatch->GetTypeInfo(0, 0, &spTypeInfo);
  3450.             if (SUCCEEDED(hr))
  3451.             {
  3452.                 CComPtr<ITypeLib> spTypeLib;
  3453.                 hr = spTypeInfo->GetContainingTypeLib(&spTypeLib, 0);
  3454.                 if (SUCCEEDED(hr))
  3455.                 {
  3456.                     TLIBATTR* plibAttr;
  3457.                     hr = spTypeLib->GetLibAttr(&plibAttr);
  3458.                     if (SUCCEEDED(hr))
  3459.                     {
  3460.                         memcpy(plibid, &plibAttr->guid, sizeof(GUID));
  3461.                         *pdwMajor = plibAttr->wMajorVerNum;
  3462.                         *pdwMinor = plibAttr->wMinorVerNum;
  3463.                         spTypeLib->ReleaseTLibAttr(plibAttr);
  3464.                         // First see if the object is willing to tell us about the
  3465.                         // default source interface via IProvideClassInfo2
  3466.                         CComPtr<IProvideClassInfo2> spInfo;
  3467.                         hr = punkObj->QueryInterface(IID_IProvideClassInfo2, (void**)&spInfo);
  3468.                         if (SUCCEEDED(hr) && spInfo != NULL)
  3469.                             hr = spInfo->GetGUID(GUIDKIND_DEFAULT_SOURCE_DISP_IID, piid);
  3470.                         else
  3471.                         {
  3472.                             // No, we have to go hunt for it
  3473.                             CComPtr<ITypeInfo> spInfoCoClass;
  3474.                             // If we have a clsid, use that
  3475.                             // Otherwise, try to locate the clsid from IPersist
  3476.                             CComPtr<IPersist> spPersist;
  3477.                             CLSID clsid;
  3478.                             hr = punkObj->QueryInterface(IID_IPersist, (void**)&spPersist);
  3479.                             if (SUCCEEDED(hr))
  3480.                             {
  3481.                                 hr = spPersist->GetClassID(&clsid);
  3482.                                 if (SUCCEEDED(hr))
  3483.                                 {
  3484.                                     hr = spTypeLib->GetTypeInfoOfGuid(clsid, &spInfoCoClass);
  3485.                                     if (SUCCEEDED(hr))
  3486.                                     {
  3487.                                         TYPEATTR* pAttr=NULL;
  3488.                                         spInfoCoClass->GetTypeAttr(&pAttr);
  3489.                                         if (pAttr != NULL)
  3490.                                         {
  3491.                                             HREFTYPE hRef;
  3492.                                             for (int i = 0; i < pAttr->cImplTypes; i++)
  3493.                                             {
  3494.                                                 int nType;
  3495.                                                 hr = spInfoCoClass->GetImplTypeFlags(i, &nType);
  3496.                                                 if (SUCCEEDED(hr))
  3497.                                                 {
  3498.                                                     if (nType == (IMPLTYPEFLAG_FDEFAULT | IMPLTYPEFLAG_FSOURCE))
  3499.                                                     {
  3500.                                                         // we found it
  3501.                                                         hr = spInfoCoClass->GetRefTypeOfImplType(i, &hRef);
  3502.                                                         if (SUCCEEDED(hr))
  3503.                                                         {
  3504.                                                             CComPtr<ITypeInfo> spInfo;
  3505.                                                             hr = spInfoCoClass->GetRefTypeInfo(hRef, &spInfo);
  3506.                                                             if (SUCCEEDED(hr))
  3507.                                                             {
  3508.                                                                 TYPEATTR* pAttrIF;
  3509.                                                                 spInfo->GetTypeAttr(&pAttrIF);
  3510.                                                                 if (pAttrIF != NULL)
  3511.                                                                 {
  3512.                                                                     memcpy(piid, &pAttrIF->guid, sizeof(GUID));
  3513.                                                                 }
  3514.                                                                 spInfo->ReleaseTypeAttr(pAttrIF);
  3515.                                                             }
  3516.                                                         }
  3517.                                                         break;
  3518.                                                     }
  3519.                                                 }
  3520.                                             }
  3521.                                             spInfoCoClass->ReleaseTypeAttr(pAttr);
  3522.                                         }
  3523.                                     }
  3524.                                 }
  3525.                             }
  3526.                         }
  3527.                     }
  3528.                 }
  3529.             }
  3530.         }
  3531.     }
  3532.     return hr;
  3533. }
  3534. #endif // _ATL_DLL
  3535.  
  3536.  
  3537. #if defined(_M_ALPHA)
  3538.     #pragma message("ALPHA code for CComStdCallThunk needs to be verified!")
  3539.     #pragma pack(push,4)
  3540.     template <class T>
  3541.     class CComStdCallThunk
  3542.     {
  3543.     public:
  3544.         typedef void (__stdcall T::*TMFP)();
  3545.  
  3546.         void* pVtable;
  3547.         void* pFunc;
  3548.         DWORD ldah_at;      //  ldah    at, HIWORD(func)
  3549.         DWORD ldah_a0;      //  ldah    a0, HIWORD(this)
  3550.         DWORD lda_at;       //  lda     at, LOWORD(func)(at)
  3551.         DWORD lda_a0;       //  lda     a0, LOWORD(this)(a0)
  3552.         DWORD jmp;          //  jmp     zero,(at),0
  3553.         void Init(TMFP dw, void* pThis)
  3554.         {
  3555.             union {
  3556.                 DWORD dwFunc;
  3557.                 TMFP pfn;
  3558.             } pfn;
  3559.             pfn.pfn = dw;
  3560.             pVtable = &pFunc;
  3561.             pFunc = &m_mov;
  3562.             thunk.ldah_at = (0x279f0000 | HIWORD(pFunc)) + (LOWORD(pFunc)>>15);
  3563.             thunk.ldah_a0 = (0x261f0000 | HIWORD(pThis)) + (LOWORD(pThis)>>15);
  3564.             thunk.lda_at = 0x239c0000 | LOWORD(pFunc);
  3565.             thunk.lda_a0 = 0x22100000 | LOWORD(pThis);
  3566.             thunk.jmp = 0x6bfc0000;
  3567.             FlushInstructionCache(GetCurrentProcess(), this, sizeof(CComStdCallThunk));
  3568.         }
  3569.     };
  3570.     #pragma pack(pop)
  3571. #elif defined (_M_IX86)
  3572.     #pragma pack(push,1)
  3573.     template <class T>
  3574.     class CComStdCallThunk
  3575.     {
  3576.     public:
  3577.         typedef void (__stdcall T::*TMFP)();
  3578.  
  3579.         void* pVtable;
  3580.         void* pFunc;
  3581.         DWORD    m_mov;          // mov dword ptr [esp+4], pThis
  3582.         DWORD   m_this;         //
  3583.         BYTE    m_jmp;          // jmp func
  3584.         DWORD   m_relproc;      // relative jmp
  3585.         void Init(TMFP dw, void* pThis)
  3586.         {
  3587.             union {
  3588.                 DWORD dwFunc;
  3589.                 TMFP pfn;
  3590.             } pfn;
  3591.             pfn.pfn = dw;
  3592.             pVtable = &pFunc;
  3593.             pFunc = &m_mov;
  3594.             m_mov = 0x042444C7;
  3595.             m_this = (DWORD)pThis;
  3596.             m_jmp = 0xE9;
  3597.             m_relproc = (int)pfn.dwFunc - ((int)this+sizeof(CComStdCallThunk));
  3598.             FlushInstructionCache(GetCurrentProcess(), this, sizeof(CComStdCallThunk));
  3599.         }
  3600.     };
  3601.     #pragma pack(pop)
  3602. #else
  3603.     #error Only ALPHA and X86 supported
  3604. #endif
  3605.  
  3606. #ifndef _ATL_MAX_VARTYPES
  3607. #define _ATL_MAX_VARTYPES 8
  3608. #endif
  3609.  
  3610. struct _ATL_FUNC_INFO
  3611. {
  3612.     CALLCONV cc;
  3613.     VARTYPE vtReturn;
  3614.     SHORT nParams;
  3615.     VARTYPE pVarTypes[_ATL_MAX_VARTYPES];
  3616. };
  3617.  
  3618. class ATL_NO_VTABLE _IDispEvent
  3619. {
  3620. public:
  3621.     _IDispEvent() {m_dwEventCookie = 0xFEFEFEFE;}
  3622.     //this method needs a different name than QueryInterface
  3623.     STDMETHOD(_LocDEQueryInterface)(REFIID riid, void ** ppvObject) = 0;
  3624.     virtual ULONG STDMETHODCALLTYPE AddRef(void) = 0;
  3625.     virtual ULONG STDMETHODCALLTYPE Release(void) = 0;
  3626.     GUID m_libid; // used for dynamic case
  3627.     IID m_iid; // used for dynamic case
  3628.     unsigned short m_wMajorVerNum;    // Major version number. used for dynamic case
  3629.     unsigned short m_wMinorVerNum;    // Minor version number. used for dynamic case
  3630.     DWORD m_dwEventCookie;
  3631.     HRESULT DispEventAdvise(IUnknown* pUnk, const IID* piid)
  3632.     {
  3633.         ATLASSERT(m_dwEventCookie == 0xFEFEFEFE);
  3634.         return AtlAdvise(pUnk, (IUnknown*)this, *piid, &m_dwEventCookie);
  3635.     }
  3636.     HRESULT DispEventUnadvise(IUnknown* pUnk, const IID* piid)
  3637.     {
  3638.         HRESULT hr = AtlUnadvise(pUnk, *piid, m_dwEventCookie);
  3639.         m_dwEventCookie = 0xFEFEFEFE;
  3640.         return hr;
  3641.     }
  3642. };
  3643.  
  3644. template <UINT nID, const IID* piid>
  3645. class ATL_NO_VTABLE _IDispEventLocator : public _IDispEvent
  3646. {
  3647. public:
  3648. };
  3649.  
  3650. template <UINT nID, class T, const IID* pdiid>
  3651. class ATL_NO_VTABLE IDispEventSimpleImpl : public _IDispEventLocator<nID, pdiid>
  3652. {
  3653. public:
  3654.     STDMETHOD(_LocDEQueryInterface)(REFIID riid, void ** ppvObject)
  3655.     {
  3656.         if (InlineIsEqualGUID(riid, *pdiid) || 
  3657.             InlineIsEqualUnknown(riid) ||
  3658.             InlineIsEqualGUID(riid, IID_IDispatch) ||
  3659.             InlineIsEqualGUID(riid, m_iid))
  3660.         {
  3661.             if (ppvObject == NULL)
  3662.                 return E_POINTER;
  3663.             *ppvObject = this;
  3664.             AddRef();
  3665. #ifdef _ATL_DEBUG_INTERFACES
  3666.             _Module.AddThunk((IUnknown**)ppvObject, _T("IDispEventImpl"), riid);
  3667. #endif // _ATL_DEBUG_INTERFACES
  3668.             return S_OK;
  3669.         }
  3670.         else
  3671.             return E_NOINTERFACE;
  3672.     }
  3673.  
  3674.     // These are here only to support use in non-COM objects    
  3675.     virtual ULONG STDMETHODCALLTYPE AddRef()
  3676.     {
  3677.         return 1;
  3678.     }
  3679.     virtual ULONG STDMETHODCALLTYPE Release()
  3680.     {
  3681.         return 1;
  3682.     }
  3683.  
  3684.     STDMETHOD(GetTypeInfoCount)(UINT* pctinfo)
  3685.     {return E_NOTIMPL;}
  3686.  
  3687.     STDMETHOD(GetTypeInfo)(UINT itinfo, LCID lcid, ITypeInfo** pptinfo)
  3688.     {return E_NOTIMPL;}
  3689.  
  3690.     STDMETHOD(GetIDsOfNames)(REFIID riid, LPOLESTR* rgszNames, UINT cNames,
  3691.         LCID lcid, DISPID* rgdispid)
  3692.     {return E_NOTIMPL;}
  3693.  
  3694.     STDMETHOD(Invoke)(DISPID dispidMember, REFIID riid,
  3695.         LCID lcid, WORD /*wFlags*/, DISPPARAMS* pdispparams, VARIANT* pvarResult,
  3696.         EXCEPINFO* /*pexcepinfo*/, UINT* /*puArgErr*/)
  3697.     {
  3698.         T* pT = static_cast<T*>(this);
  3699.         const _ATL_EVENT_ENTRY<T>* pMap = T::_GetSinkMap();
  3700.         const _ATL_EVENT_ENTRY<T>* pFound = NULL;
  3701.         void (__stdcall T::*pEvent)() = NULL;
  3702.         while (pMap->piid != NULL)
  3703.         {
  3704.             if ((pMap->nControlID == nID) && (pMap->dispid == dispidMember) && 
  3705.                 (pMap->piid == pdiid)) //comparing pointers here should be adequate
  3706.             {
  3707.                 pFound = pMap;
  3708.                 break;
  3709.             }
  3710.             pMap++;
  3711.         }
  3712.         if (pFound == NULL)
  3713.             return S_OK;
  3714.         
  3715.  
  3716.         _ATL_FUNC_INFO info;
  3717.         _ATL_FUNC_INFO* pInfo;
  3718.         if (pFound->pInfo != NULL)
  3719.             pInfo = pFound->pInfo;
  3720.         else
  3721.         {
  3722.             pInfo = &info;
  3723.             HRESULT hr = GetFuncInfoFromId(*pdiid, dispidMember, lcid, info);
  3724.             if (FAILED(hr))
  3725.                 return S_OK;
  3726.         }
  3727.         InvokeFromFuncInfo(pFound->pfn, *pInfo, pdispparams, pvarResult);
  3728.         return S_OK;
  3729.     }
  3730.  
  3731.     //Helper for invoking the event
  3732.     HRESULT InvokeFromFuncInfo(void (__stdcall T::*pEvent)(), _ATL_FUNC_INFO& info, DISPPARAMS* pdispparams, VARIANT* pvarResult)
  3733.     {
  3734.         T* pT = static_cast<T*>(this);
  3735.         VARIANTARG** pVarArgs = info.nParams ? (VARIANTARG**)alloca(sizeof(VARIANTARG*)*info.nParams) : 0;
  3736.         for (int i=0; i<info.nParams; i++)
  3737.             pVarArgs[i] = &pdispparams->rgvarg[info.nParams - i - 1];
  3738.  
  3739.         CComStdCallThunk<T> thunk;
  3740.         thunk.Init(pEvent, pT);
  3741.         CComVariant tmpResult;
  3742.         if (pvarResult == NULL)
  3743.             pvarResult = &tmpResult;
  3744.  
  3745.         HRESULT hr = DispCallFunc(
  3746.             &thunk,
  3747.             0,
  3748.             info.cc,
  3749.             info.vtReturn,
  3750.             info.nParams,
  3751.             info.pVarTypes,
  3752.             pVarArgs,
  3753.             pvarResult);
  3754.         ATLASSERT(SUCCEEDED(hr));
  3755.         return hr;
  3756.     }
  3757.  
  3758.     //Helper for finding the function index for a DISPID
  3759.     virtual HRESULT GetFuncInfoFromId(const IID& iid, DISPID dispidMember, LCID lcid, _ATL_FUNC_INFO& info)
  3760.     {
  3761.         return E_NOTIMPL;
  3762.     }
  3763.     //Helpers for sinking events on random IUnknown*
  3764.     HRESULT DispEventAdvise(IUnknown* pUnk, const IID* piid)
  3765.     {
  3766.         ATLASSERT(m_dwEventCookie == 0xFEFEFEFE);
  3767.         return AtlAdvise(pUnk, (IUnknown*)this, *piid, &m_dwEventCookie);
  3768.     }
  3769.     HRESULT DispEventUnadvise(IUnknown* pUnk, const IID* piid)
  3770.     {
  3771.         HRESULT hr = AtlUnadvise(pUnk, *piid, m_dwEventCookie);
  3772.         m_dwEventCookie = 0xFEFEFEFE;
  3773.         return hr;
  3774.     }
  3775.     HRESULT DispEventAdvise(IUnknown* pUnk)
  3776.     {
  3777.         return _IDispEvent::DispEventAdvise(pUnk, pdiid);
  3778.     }
  3779.     HRESULT DispEventUnadvise(IUnknown* pUnk)
  3780.     {
  3781.         return _IDispEvent::DispEventUnadvise(pUnk, pdiid);
  3782.     }
  3783. };
  3784.  
  3785. //Helper for advising connections points from a sink map
  3786. template <class T>
  3787. inline HRESULT AtlAdviseSinkMap(T* pT, bool bAdvise)
  3788. {
  3789.     ATLASSERT(::IsWindow(pT->m_hWnd));
  3790.     const _ATL_EVENT_ENTRY<T>* pEntries = T::_GetSinkMap();
  3791.     if (pEntries == NULL)
  3792.         return S_OK;
  3793.     HRESULT hr = S_OK;
  3794.     while (pEntries->piid != NULL)
  3795.     {
  3796.         _IDispEvent* pDE = (_IDispEvent*)((DWORD)pT+pEntries->nOffset);
  3797.         bool bNotAdvised = pDE->m_dwEventCookie == 0xFEFEFEFE;
  3798.         if (bAdvise ^ bNotAdvised)
  3799.         {
  3800.             pEntries++;
  3801.             continue;
  3802.         }
  3803.         hr = E_FAIL;
  3804.         HWND h = pT->GetDlgItem(pEntries->nControlID);
  3805.         ATLASSERT(h != NULL);
  3806.         if (h != NULL)
  3807.         {
  3808.             CComPtr<IUnknown> spUnk;
  3809.             AtlAxGetControl(h, &spUnk);
  3810.             ATLASSERT(spUnk != NULL);
  3811.             if (spUnk != NULL)
  3812.             {
  3813.                 if (bAdvise)
  3814.                 {
  3815.                     if (!InlineIsEqualGUID(IID_NULL, *pEntries->piid))
  3816.                         hr = pDE->DispEventAdvise(spUnk, pEntries->piid);
  3817.                     else
  3818.                     {
  3819.                         AtlGetObjectSourceInterface(spUnk, &pDE->m_libid, &pDE->m_iid, &pDE->m_wMajorVerNum, &pDE->m_wMinorVerNum);
  3820.                         hr = pDE->DispEventAdvise(spUnk, &pDE->m_iid);
  3821.                     }
  3822.                 }
  3823.                 else
  3824.                 {
  3825.                     if (!InlineIsEqualGUID(IID_NULL, *pEntries->piid))
  3826.                         hr = pDE->DispEventUnadvise(spUnk, pEntries->piid);
  3827.                     else
  3828.                         hr = pDE->DispEventUnadvise(spUnk, &pDE->m_iid);
  3829.                 }
  3830.                 ATLASSERT(hr == S_OK);
  3831.             }
  3832.         }
  3833.         if (FAILED(hr))
  3834.             break;
  3835.         pEntries++;
  3836.     }
  3837.     return hr;
  3838. }
  3839.  
  3840. template <UINT nID, class T, const IID* pdiid = &IID_NULL, const GUID* plibid = &GUID_NULL, 
  3841.     WORD wMajor = 0, WORD wMinor = 0, class tihclass = CComTypeInfoHolder>
  3842. class ATL_NO_VTABLE IDispEventImpl : public IDispEventSimpleImpl<nID, T, pdiid>
  3843. {
  3844. public:
  3845.     typedef tihclass _tihclass;
  3846.  
  3847.     IDispEventImpl()
  3848.     {
  3849.         m_libid = *plibid;
  3850.         m_iid = *pdiid;
  3851.         m_wMajorVerNum = wMajor;
  3852.         m_wMinorVerNum = wMinor;
  3853.     }
  3854.  
  3855.     STDMETHOD(GetTypeInfoCount)(UINT* pctinfo)
  3856.     {*pctinfo = 1; return S_OK;}
  3857.  
  3858.     STDMETHOD(GetTypeInfo)(UINT itinfo, LCID lcid, ITypeInfo** pptinfo)
  3859.     {return _tih.GetTypeInfo(itinfo, lcid, pptinfo);}
  3860.  
  3861.     STDMETHOD(GetIDsOfNames)(REFIID riid, LPOLESTR* rgszNames, UINT cNames,
  3862.         LCID lcid, DISPID* rgdispid)
  3863.     {return _tih.GetIDsOfNames(riid, rgszNames, cNames, lcid, rgdispid);}
  3864.  
  3865.     //Helper for finding the function index for a DISPID
  3866.     HRESULT GetFuncInfoFromId(const IID& /*iid*/, DISPID dispidMember, LCID lcid, _ATL_FUNC_INFO& info)
  3867.     {
  3868.         CComPtr<ITypeInfo> spTypeInfo;
  3869.         if (InlineIsEqualGUID(*_tih.m_plibid, GUID_NULL))
  3870.         {
  3871.             _tih.m_plibid = &m_libid;
  3872.             _tih.m_pguid = &m_iid;
  3873.             _tih.m_wMajor = m_wMajorVerNum;
  3874.             _tih.m_wMinor = m_wMinorVerNum;
  3875.         }
  3876.         HRESULT hr = _tih.GetTI(lcid, &spTypeInfo);
  3877.         if (FAILED(hr))
  3878.             return hr;
  3879.         CComQIPtr<ITypeInfo2, &IID_ITypeInfo2> spTypeInfo2 = spTypeInfo;
  3880.         FUNCDESC* pFuncDesc = NULL;
  3881.         if (spTypeInfo2 != NULL)
  3882.         {
  3883.             UINT nIndex;
  3884.             hr = spTypeInfo2->GetFuncIndexOfMemId(dispidMember, INVOKE_FUNC, &nIndex);
  3885.             if (FAILED(hr))
  3886.                 return hr;
  3887.             hr = spTypeInfo->GetFuncDesc(nIndex, &pFuncDesc);
  3888.             if (FAILED(hr))
  3889.                 return hr;
  3890.         }
  3891.         else // search for funcdesc
  3892.         {
  3893.             TYPEATTR* pAttr;
  3894.             hr = spTypeInfo->GetTypeAttr(&pAttr);
  3895.             if (FAILED(hr))
  3896.                 return hr;
  3897.             for (int i=0;i<pAttr->cFuncs;i++)
  3898.             {
  3899.                 hr = spTypeInfo->GetFuncDesc(i, &pFuncDesc);
  3900.                 if (FAILED(hr))
  3901.                     return hr;
  3902.                 if (pFuncDesc->memid == dispidMember)
  3903.                     break;
  3904.                 spTypeInfo->ReleaseFuncDesc(pFuncDesc);
  3905.                 pFuncDesc = NULL;
  3906.             }
  3907.             spTypeInfo->ReleaseTypeAttr(pAttr);
  3908.             if (pFuncDesc == NULL)
  3909.                 return E_FAIL;
  3910.         }
  3911.  
  3912.         // If this assert occurs, then add a #define _ATL_MAX_VARTYPES nnnn
  3913.         // before including atlcom.h
  3914.         ATLASSERT(pFuncDesc->cParams <= _ATL_MAX_VARTYPES);
  3915.         if (pFuncDesc->cParams > _ATL_MAX_VARTYPES)
  3916.             return E_FAIL;
  3917.  
  3918.         for (int i=0; i<pFuncDesc->cParams; i++)
  3919.         {
  3920.             info.pVarTypes[i] = pFuncDesc->lprgelemdescParam[pFuncDesc->cParams - i - 1].tdesc.vt;
  3921.             if (info.pVarTypes[i] == VT_PTR)
  3922.                 info.pVarTypes[i] = pFuncDesc->lprgelemdescParam[pFuncDesc->cParams - i - 1].tdesc.lptdesc->vt | VT_BYREF;
  3923.             if (info.pVarTypes[i] == VT_USERDEFINED)
  3924.                 info.pVarTypes[i] = GetUserDefinedType(spTypeInfo,pFuncDesc->lprgelemdescParam[pFuncDesc->cParams-i-1].tdesc.hreftype);
  3925.         }
  3926.  
  3927.         VARTYPE vtReturn = pFuncDesc->elemdescFunc.tdesc.vt;
  3928.         switch(vtReturn)
  3929.         {
  3930.         case VT_INT:
  3931.             vtReturn = VT_I4;
  3932.             break;
  3933.         case VT_UINT:
  3934.             vtReturn = VT_UI4;
  3935.             break;
  3936.         case VT_VOID:
  3937.             vtReturn = VT_EMPTY; // this is how DispCallFunc() represents void
  3938.             break;
  3939.         case VT_HRESULT:
  3940.             vtReturn = VT_ERROR;
  3941.             break;
  3942.         }
  3943.         info.vtReturn = vtReturn;
  3944.         info.cc = pFuncDesc->callconv;
  3945.         info.nParams = pFuncDesc->cParams;
  3946.         spTypeInfo->ReleaseFuncDesc(pFuncDesc);
  3947.         return S_OK;
  3948.     }
  3949.     VARTYPE GetUserDefinedType(ITypeInfo *pTI, HREFTYPE hrt)
  3950.     {
  3951.         CComPtr<ITypeInfo> spTypeInfo;
  3952.         VARTYPE vt = VT_USERDEFINED;
  3953.         HRESULT hr = E_FAIL;
  3954.         hr = pTI->GetRefTypeInfo(hrt, &spTypeInfo);
  3955.         if(FAILED(hr))
  3956.             return vt;
  3957.         TYPEATTR *pta=NULL;
  3958.  
  3959.         spTypeInfo->GetTypeAttr(&pta);
  3960.         if(pta && pta->typekind == TKIND_ALIAS)
  3961.         {
  3962.             if (pta->tdescAlias.vt == VT_USERDEFINED)
  3963.                 GetUserDefinedType(spTypeInfo,pta->tdescAlias.hreftype);
  3964.             else
  3965.                 vt = pta->tdescAlias.vt;
  3966.         }
  3967.     
  3968.         if(pta)
  3969.             spTypeInfo->ReleaseTypeAttr(pta);
  3970.         return vt;
  3971.  
  3972.     }
  3973. protected:
  3974.     static _tihclass _tih;
  3975.     static HRESULT GetTI(LCID lcid, ITypeInfo** ppInfo)
  3976.     {return _tih.GetTI(lcid, ppInfo);}
  3977. };
  3978.  
  3979.  
  3980. template <UINT nID, class T, const IID* piid, const GUID* plibid, WORD wMajor, WORD wMinor, class tihclass>
  3981. IDispEventImpl<nID, T, piid, plibid, wMajor, wMinor, tihclass>::_tihclass
  3982. IDispEventImpl<nID, T, piid, plibid, wMajor, wMinor, tihclass>::_tih =
  3983.     {piid, plibid, wMajor, wMinor, NULL, 0, NULL, 0};
  3984.  
  3985. template <class T>
  3986. struct _ATL_EVENT_ENTRY
  3987. {
  3988.     UINT nControlID;            //ID identifying object instance
  3989.     const IID* piid;            //dispinterface IID
  3990.     int nOffset;                //offset of dispinterface from this pointer
  3991.     DISPID dispid;                //DISPID of method/property
  3992.     void (__stdcall T::*pfn)();    //method to invoke
  3993.     _ATL_FUNC_INFO* pInfo;
  3994. };
  3995.  
  3996.  
  3997.  
  3998. //Sink map is used to set up event handling
  3999. #define BEGIN_SINK_MAP(_class)\
  4000.     static const _ATL_EVENT_ENTRY<_class>* _GetSinkMap()\
  4001.     {\
  4002.         typedef _class _atl_event_classtype;\
  4003.         static const _ATL_EVENT_ENTRY<_class> map[] = {
  4004.  
  4005.  
  4006. #define SINK_ENTRY_INFO(id, iid, dispid, fn, info) {id, &iid, (int)(static_cast<_IDispEventLocator<id, &iid>*>((_atl_event_classtype*)8))-8, dispid, (void (__stdcall _atl_event_classtype::*)())fn, info},
  4007. #define SINK_ENTRY_EX(id, iid, dispid, fn) SINK_ENTRY_INFO(id, iid, dispid, fn, NULL)
  4008. #define SINK_ENTRY(id, dispid, fn) SINK_ENTRY_EX(id, IID_NULL, dispid, fn)
  4009. #define END_SINK_MAP() {0, NULL, 0, 0, NULL, NULL} }; return map;}
  4010.  
  4011. /////////////////////////////////////////////////////////////////////////////
  4012. // IDispatchImpl
  4013.  
  4014. template <class T, const IID* piid, const GUID* plibid = &CComModule::m_libid, WORD wMajor = 1,
  4015. WORD wMinor = 0, class tihclass = CComTypeInfoHolder>
  4016. class ATL_NO_VTABLE IDispatchImpl : public T
  4017. {
  4018. public:
  4019.     typedef tihclass _tihclass;
  4020. // IDispatch
  4021.     STDMETHOD(GetTypeInfoCount)(UINT* pctinfo)
  4022.     {
  4023.         *pctinfo = 1;
  4024.         return S_OK;
  4025.     }
  4026.     STDMETHOD(GetTypeInfo)(UINT itinfo, LCID lcid, ITypeInfo** pptinfo)
  4027.     {
  4028.         return _tih.GetTypeInfo(itinfo, lcid, pptinfo);
  4029.     }
  4030.     STDMETHOD(GetIDsOfNames)(REFIID riid, LPOLESTR* rgszNames, UINT cNames,
  4031.         LCID lcid, DISPID* rgdispid)
  4032.     {
  4033.         return _tih.GetIDsOfNames(riid, rgszNames, cNames, lcid, rgdispid);
  4034.     }
  4035.     STDMETHOD(Invoke)(DISPID dispidMember, REFIID riid,
  4036.         LCID lcid, WORD wFlags, DISPPARAMS* pdispparams, VARIANT* pvarResult,
  4037.         EXCEPINFO* pexcepinfo, UINT* puArgErr)
  4038.     {
  4039.         return _tih.Invoke((IDispatch*)this, dispidMember, riid, lcid,
  4040.         wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr);
  4041.     }
  4042. protected:
  4043.     static _tihclass _tih;
  4044.     static HRESULT GetTI(LCID lcid, ITypeInfo** ppInfo)
  4045.     {
  4046.         return _tih.GetTI(lcid, ppInfo);
  4047.     }
  4048. };
  4049.  
  4050. template <class T, const IID* piid, const GUID* plibid, WORD wMajor, WORD wMinor, class tihclass>
  4051. IDispatchImpl<T, piid, plibid, wMajor, wMinor, tihclass>::_tihclass
  4052. IDispatchImpl<T, piid, plibid, wMajor, wMinor, tihclass>::_tih =
  4053. {piid, plibid, wMajor, wMinor, NULL, 0, NULL, 0};
  4054.  
  4055.  
  4056. /////////////////////////////////////////////////////////////////////////////
  4057. // IProvideClassInfoImpl
  4058. template <const CLSID* pcoclsid, const GUID* plibid = &CComModule::m_libid,
  4059. WORD wMajor = 1, WORD wMinor = 0, class tihclass = CComTypeInfoHolder>
  4060. class ATL_NO_VTABLE IProvideClassInfoImpl : public IProvideClassInfo
  4061. {
  4062. public:
  4063.     typedef tihclass _tihclass;
  4064.  
  4065.     STDMETHOD(GetClassInfo)(ITypeInfo** pptinfo)
  4066.     {
  4067.         return _tih.GetTypeInfo(0, LANG_NEUTRAL, pptinfo);
  4068.     }
  4069.  
  4070. protected:
  4071.     static _tihclass _tih;
  4072. };
  4073.  
  4074. template <const CLSID* pcoclsid, const GUID* plibid, WORD wMajor, WORD wMinor, class tihclass>
  4075. IProvideClassInfoImpl<pcoclsid, plibid, wMajor, wMinor, tihclass>::_tihclass
  4076. IProvideClassInfoImpl<pcoclsid, plibid, wMajor, wMinor, tihclass>::_tih =
  4077. {pcoclsid,plibid, wMajor, wMinor, NULL, 0, NULL, 0};
  4078.  
  4079. /////////////////////////////////////////////////////////////////////////////
  4080. // IProvideClassInfo2Impl
  4081. template <const CLSID* pcoclsid, const IID* psrcid, const GUID* plibid = &CComModule::m_libid,
  4082. WORD wMajor = 1, WORD wMinor = 0, class tihclass = CComTypeInfoHolder>
  4083. class ATL_NO_VTABLE IProvideClassInfo2Impl : public IProvideClassInfo2
  4084. {
  4085. public:
  4086.     typedef tihclass _tihclass;
  4087.  
  4088.     STDMETHOD(GetClassInfo)(ITypeInfo** pptinfo)
  4089.     {
  4090.         return _tih.GetTypeInfo(0, LANG_NEUTRAL, pptinfo);
  4091.     }
  4092.     STDMETHOD(GetGUID)(DWORD dwGuidKind, GUID* pGUID)
  4093.     {
  4094.         if (pGUID == NULL)
  4095.             return E_POINTER;
  4096.  
  4097.         if (dwGuidKind == GUIDKIND_DEFAULT_SOURCE_DISP_IID && psrcid)
  4098.         {
  4099.             *pGUID = *psrcid;
  4100.             return S_OK;
  4101.         }
  4102.         *pGUID = GUID_NULL;
  4103.         return E_FAIL;
  4104.     }
  4105.  
  4106. protected:
  4107.     static _tihclass _tih;
  4108. };
  4109.  
  4110.  
  4111. template <const CLSID* pcoclsid, const IID* psrcid, const GUID* plibid, WORD wMajor, WORD wMinor, class tihclass>
  4112. IProvideClassInfo2Impl<pcoclsid, psrcid, plibid, wMajor, wMinor, tihclass>::_tihclass
  4113. IProvideClassInfo2Impl<pcoclsid, psrcid, plibid, wMajor, wMinor, tihclass>::_tih =
  4114. {pcoclsid,plibid, wMajor, wMinor, NULL, 0, NULL, 0};
  4115.  
  4116.  
  4117. /////////////////////////////////////////////////////////////////////////////
  4118. // ISupportErrorInfoImpl
  4119.  
  4120. template <const IID* piid>
  4121. class ATL_NO_VTABLE ISupportErrorInfoImpl : public ISupportErrorInfo
  4122. {
  4123. public:
  4124.     STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid)
  4125.     {
  4126.         return (InlineIsEqualGUID(riid,*piid)) ? S_OK : S_FALSE;
  4127.     }
  4128. };
  4129.  
  4130.  
  4131. /////////////////////////////////////////////////////////////////////////////
  4132. // CComEnumImpl
  4133.  
  4134. // These _CopyXXX classes are used with enumerators in order to control
  4135. // how enumerated items are initialized, copied, and deleted
  4136.  
  4137. // Default is shallow copy with no special init or cleanup
  4138. template <class T>
  4139. class _Copy
  4140. {
  4141. public:
  4142.     static HRESULT copy(T* p1, T* p2) {memcpy(p1, p2, sizeof(T)); return S_OK;}
  4143.     static void init(T*) {}
  4144.     static void destroy(T*) {}
  4145. };
  4146.  
  4147. template<>
  4148. class _Copy<VARIANT>
  4149. {
  4150. public:
  4151.     static HRESULT copy(VARIANT* p1, VARIANT* p2) {return VariantCopy(p1, p2);}
  4152.     static void init(VARIANT* p) {p->vt = VT_EMPTY;}
  4153.     static void destroy(VARIANT* p) {VariantClear(p);}
  4154. };
  4155.  
  4156. template<>
  4157. class _Copy<LPOLESTR>
  4158. {
  4159. public:
  4160.     static HRESULT copy(LPOLESTR* p1, LPOLESTR* p2)
  4161.     {
  4162.         HRESULT hr = S_OK;
  4163.         (*p1) = (LPOLESTR)CoTaskMemAlloc(sizeof(OLECHAR)*(ocslen(*p2)+1));
  4164.         if (*p1 == NULL)
  4165.             hr = E_OUTOFMEMORY;
  4166.         else
  4167.             ocscpy(*p1,*p2);
  4168.         return hr;
  4169.     }
  4170.     static void init(LPOLESTR* p) {*p = NULL;}
  4171.     static void destroy(LPOLESTR* p) { CoTaskMemFree(*p);}
  4172. };
  4173.  
  4174. template<>
  4175. class _Copy<OLEVERB>
  4176. {
  4177. public:
  4178.     static HRESULT copy(OLEVERB* p1, OLEVERB* p2)
  4179.     {
  4180.         HRESULT hr = S_OK;
  4181.         *p1 = *p2;
  4182.         if (p2->lpszVerbName == NULL)
  4183.             return S_OK;
  4184.         p1->lpszVerbName = (LPOLESTR)CoTaskMemAlloc(sizeof(OLECHAR)*(ocslen(p2->lpszVerbName)+1));
  4185.         if (p1->lpszVerbName == NULL)
  4186.             hr = E_OUTOFMEMORY;
  4187.         else
  4188.             ocscpy(p1->lpszVerbName,p2->lpszVerbName);
  4189.         return hr;
  4190.     }
  4191.     static void init(OLEVERB* p) { p->lpszVerbName = NULL;}
  4192.     static void destroy(OLEVERB* p) { if (p->lpszVerbName) CoTaskMemFree(p->lpszVerbName);}
  4193. };
  4194.  
  4195. template<>
  4196. class _Copy<CONNECTDATA>
  4197. {
  4198. public:
  4199.     static HRESULT copy(CONNECTDATA* p1, CONNECTDATA* p2)
  4200.     {
  4201.         *p1 = *p2;
  4202.         if (p1->pUnk)
  4203.             p1->pUnk->AddRef();
  4204.         return S_OK;
  4205.     }
  4206.     static void init(CONNECTDATA* ) {}
  4207.     static void destroy(CONNECTDATA* p) {if (p->pUnk) p->pUnk->Release();}
  4208. };
  4209.  
  4210. template <class T>
  4211. class _CopyInterface
  4212. {
  4213. public:
  4214.     static HRESULT copy(T** p1, T** p2)
  4215.     {
  4216.         *p1 = *p2;
  4217.         if (*p1)
  4218.             (*p1)->AddRef();
  4219.         return S_OK;
  4220.     }
  4221.     static void init(T** ) {}
  4222.     static void destroy(T** p) {if (*p) (*p)->Release();}
  4223. };
  4224.  
  4225. template<class T>
  4226. class ATL_NO_VTABLE CComIEnum : public IUnknown
  4227. {
  4228. public:
  4229.     STDMETHOD(Next)(ULONG celt, T* rgelt, ULONG* pceltFetched) = 0;
  4230.     STDMETHOD(Skip)(ULONG celt) = 0;
  4231.     STDMETHOD(Reset)(void) = 0;
  4232.     STDMETHOD(Clone)(CComIEnum<T>** ppEnum) = 0;
  4233. };
  4234.  
  4235.  
  4236. enum CComEnumFlags
  4237. {
  4238.     //see FlagBits in CComEnumImpl
  4239.     AtlFlagNoCopy = 0,
  4240.     AtlFlagTakeOwnership = 2,
  4241.     AtlFlagCopy = 3 // copy implies ownership
  4242. };
  4243.  
  4244. template <class Base, const IID* piid, class T, class Copy>
  4245. class ATL_NO_VTABLE CComEnumImpl : public Base
  4246. {
  4247. public:
  4248.     CComEnumImpl() {m_begin = m_end = m_iter = NULL; m_dwFlags = 0;}
  4249.     ~CComEnumImpl();
  4250.     STDMETHOD(Next)(ULONG celt, T* rgelt, ULONG* pceltFetched);
  4251.     STDMETHOD(Skip)(ULONG celt);
  4252.     STDMETHOD(Reset)(void){m_iter = m_begin;return S_OK;}
  4253.     STDMETHOD(Clone)(Base** ppEnum);
  4254.     HRESULT Init(T* begin, T* end, IUnknown* pUnk,
  4255.         CComEnumFlags flags = AtlFlagNoCopy);
  4256.     CComPtr<IUnknown> m_spUnk;
  4257.     T* m_begin;
  4258.     T* m_end;
  4259.     T* m_iter;
  4260.     DWORD m_dwFlags;
  4261. protected:
  4262.     enum FlagBits
  4263.     {
  4264.         BitCopy=1,
  4265.         BitOwn=2
  4266.     };
  4267. };
  4268.  
  4269. template <class Base, const IID* piid, class T, class Copy>
  4270. CComEnumImpl<Base, piid, T, Copy>::~CComEnumImpl()
  4271. {
  4272.     if (m_dwFlags & BitOwn)
  4273.     {
  4274.         for (T* p = m_begin; p != m_end; p++)
  4275.             Copy::destroy(p);
  4276.         delete [] m_begin;
  4277.     }
  4278. }
  4279.  
  4280. template <class Base, const IID* piid, class T, class Copy>
  4281. STDMETHODIMP CComEnumImpl<Base, piid, T, Copy>::Next(ULONG celt, T* rgelt,
  4282.     ULONG* pceltFetched)
  4283. {
  4284.     if (rgelt == NULL || (celt != 1 && pceltFetched == NULL))
  4285.         return E_POINTER;
  4286.     if (m_begin == NULL || m_end == NULL || m_iter == NULL)
  4287.         return E_FAIL;
  4288.     ULONG nRem = (ULONG)(m_end - m_iter);
  4289.     HRESULT hRes = S_OK;
  4290.     if (nRem < celt)
  4291.         hRes = S_FALSE;
  4292.     ULONG nMin = min(celt, nRem);
  4293.     if (pceltFetched != NULL)
  4294.         *pceltFetched = nMin;
  4295.     T* pelt = rgelt;
  4296.     while(nMin--)
  4297.     {
  4298.         HRESULT hr = Copy::copy(pelt, m_iter);
  4299.         if (FAILED(hr))
  4300.         {
  4301.             while (rgelt < pelt)
  4302.                 Copy::destroy(rgelt++);
  4303.             if (pceltFetched != NULL)
  4304.                 *pceltFetched = 0;
  4305.             return hr;
  4306.         }
  4307.         pelt++;
  4308.         m_iter++;
  4309.     }
  4310.     return hRes;
  4311. }
  4312.  
  4313. template <class Base, const IID* piid, class T, class Copy>
  4314. STDMETHODIMP CComEnumImpl<Base, piid, T, Copy>::Skip(ULONG celt)
  4315. {
  4316.     m_iter += celt;
  4317.     if (m_iter <= m_end)
  4318.         return S_OK;
  4319.     m_iter = m_end;
  4320.     return S_FALSE;
  4321. }
  4322.  
  4323. template <class Base, const IID* piid, class T, class Copy>
  4324. STDMETHODIMP CComEnumImpl<Base, piid, T, Copy>::Clone(Base** ppEnum)
  4325. {
  4326.     typedef CComObject<CComEnum<Base, piid, T, Copy> > _class;
  4327.     HRESULT hRes = E_POINTER;
  4328.     if (ppEnum != NULL)
  4329.     {
  4330.         *ppEnum = NULL;
  4331.         _class* p;
  4332.         hRes = _class::CreateInstance(&p);
  4333.         if (SUCCEEDED(hRes))
  4334.         {
  4335.             // If the data is a copy then we need to keep "this" object around
  4336.             hRes = p->Init(m_begin, m_end, (m_dwFlags & BitCopy) ? this : m_spUnk);
  4337.             if (SUCCEEDED(hRes))
  4338.             {
  4339.                 p->m_iter = m_iter;
  4340.                 hRes = p->_InternalQueryInterface(*piid, (void**)ppEnum);
  4341.             }
  4342.             if (FAILED(hRes))
  4343.                 delete p;
  4344.         }
  4345.     }
  4346.     return hRes;
  4347. }
  4348.  
  4349. template <class Base, const IID* piid, class T, class Copy>
  4350. HRESULT CComEnumImpl<Base, piid, T, Copy>::Init(T* begin, T* end, IUnknown* pUnk,
  4351.     CComEnumFlags flags)
  4352. {
  4353.     if (flags == AtlFlagCopy)
  4354.     {
  4355.         ATLASSERT(m_begin == NULL); //Init called twice?
  4356.         ATLTRY(m_begin = new T[end-begin])
  4357.         m_iter = m_begin;
  4358.         if (m_begin == NULL)
  4359.             return E_OUTOFMEMORY;
  4360.         for (T* i=begin; i != end; i++)
  4361.         {
  4362.             Copy::init(m_iter);
  4363.             HRESULT hr = Copy::copy(m_iter, i);
  4364.             if (FAILED(hr))
  4365.             {
  4366.                 T* p = m_begin;
  4367.                 while (p < m_iter)
  4368.                     Copy::destroy(p++);
  4369.                 delete [] m_begin;
  4370.                 m_begin = m_end = m_iter = NULL;
  4371.                 return hr;
  4372.             }
  4373.             m_iter++;
  4374.         }
  4375.         m_end = m_begin + (end-begin);
  4376.     }
  4377.     else
  4378.     {
  4379.         m_begin = begin;
  4380.         m_end = end;
  4381.     }
  4382.     m_spUnk = pUnk;
  4383.     m_iter = m_begin;
  4384.     m_dwFlags = flags;
  4385.     return S_OK;
  4386. }
  4387.  
  4388. template <class Base, const IID* piid, class T, class Copy, class ThreadModel = CComObjectThreadModel>
  4389. class ATL_NO_VTABLE CComEnum :
  4390.     public CComEnumImpl<Base, piid, T, Copy>,
  4391.     public CComObjectRootEx< ThreadModel >
  4392. {
  4393. public:
  4394.     typedef CComEnum<Base, piid, T, Copy > _CComEnum;
  4395.     typedef CComEnumImpl<Base, piid, T, Copy > _CComEnumBase;
  4396.     BEGIN_COM_MAP(_CComEnum)
  4397.         COM_INTERFACE_ENTRY_IID(*piid, _CComEnumBase)
  4398.     END_COM_MAP()
  4399. };
  4400.  
  4401. template <class Base, const IID* piid, class T, class Copy, class CollType>
  4402. class ATL_NO_VTABLE IEnumOnSTLImpl : public Base
  4403. {
  4404. public:
  4405.     HRESULT Init(IUnknown *pUnkForRelease, CollType& collection)
  4406.     {
  4407.         m_spUnk = pUnkForRelease;
  4408.         m_pcollection = &collection;
  4409.         m_iter = m_pcollection->begin();
  4410.         return S_OK;
  4411.     }
  4412.     STDMETHOD(Next)(ULONG celt, T* rgelt, ULONG* pceltFetched);
  4413.     STDMETHOD(Skip)(ULONG celt);
  4414.     STDMETHOD(Reset)(void)
  4415.     {
  4416.         if (m_pcollection == NULL)
  4417.             return E_FAIL;
  4418.         m_iter = m_pcollection->begin();
  4419.         return S_OK;
  4420.     }
  4421.     STDMETHOD(Clone)(Base** ppEnum);
  4422. //Data
  4423.     CComPtr<IUnknown> m_spUnk;
  4424.     CollType* m_pcollection;
  4425.     CollType::iterator m_iter;
  4426. };
  4427.  
  4428. template <class Base, const IID* piid, class T, class Copy, class CollType>
  4429. STDMETHODIMP IEnumOnSTLImpl<Base, piid, T, Copy, CollType>::Next(ULONG celt, T* rgelt,
  4430.     ULONG* pceltFetched)
  4431. {
  4432.     if (rgelt == NULL || (celt != 1 && pceltFetched == NULL))
  4433.         return E_POINTER;
  4434.     if (m_pcollection == NULL)
  4435.         return E_FAIL;
  4436.  
  4437.     ULONG nActual = 0;
  4438.     HRESULT hr = S_OK;
  4439.     T* pelt = rgelt;
  4440.     while (SUCCEEDED(hr) && m_iter != m_pcollection->end() && nActual < celt)
  4441.     {
  4442.         hr = Copy::copy(pelt, &*m_iter);
  4443.         if (FAILED(hr))
  4444.         {
  4445.             while (rgelt < pelt)
  4446.                 Copy::destroy(rgelt++);
  4447.             nActual = 0;
  4448.         }
  4449.         else
  4450.         {
  4451.             pelt++;
  4452.             m_iter++;
  4453.             nActual++;
  4454.         }
  4455.     }
  4456.     if (pceltFetched)
  4457.         *pceltFetched = nActual;
  4458.     if (SUCCEEDED(hr) && (nActual < celt))
  4459.         hr = S_FALSE;
  4460.     return hr;
  4461. }
  4462.  
  4463. template <class Base, const IID* piid, class T, class Copy, class CollType>
  4464. STDMETHODIMP IEnumOnSTLImpl<Base, piid, T, Copy, CollType>::Skip(ULONG celt)
  4465. {
  4466.     HRESULT hr = S_OK;
  4467.     while (celt--)
  4468.     {
  4469.         if (m_iter != m_pcollection->end())
  4470.             m_iter++;
  4471.         else
  4472.         {
  4473.             hr = S_FALSE;
  4474.             break;
  4475.         }
  4476.     }
  4477.     return hr;
  4478. }
  4479.  
  4480. template <class Base, const IID* piid, class T, class Copy, class CollType>
  4481. STDMETHODIMP IEnumOnSTLImpl<Base, piid, T, Copy, CollType>::Clone(Base** ppEnum)
  4482. {
  4483.     typedef CComObject<CComEnumOnSTL<Base, piid, T, Copy, CollType> > _class;
  4484.     HRESULT hRes = E_POINTER;
  4485.     if (ppEnum != NULL)
  4486.     {
  4487.         *ppEnum = NULL;
  4488.         _class* p;
  4489.         hRes = _class::CreateInstance(&p);
  4490.         if (SUCCEEDED(hRes))
  4491.         {
  4492.             hRes = p->Init(m_spUnk, *m_pcollection);
  4493.             if (SUCCEEDED(hRes))
  4494.             {
  4495.                 p->m_iter = m_iter;
  4496.                 hRes = p->_InternalQueryInterface(*piid, (void**)ppEnum);
  4497.             }
  4498.             if (FAILED(hRes))
  4499.                 delete p;
  4500.         }
  4501.     }
  4502.     return hRes;
  4503. }
  4504.  
  4505. template <class Base, const IID* piid, class T, class Copy, class CollType, class ThreadModel = CComObjectThreadModel>
  4506. class ATL_NO_VTABLE CComEnumOnSTL :
  4507.     public IEnumOnSTLImpl<Base, piid, T, Copy, CollType>,
  4508.     public CComObjectRootEx< ThreadModel >
  4509. {
  4510. public:
  4511.     typedef CComEnumOnSTL<Base, piid, T, Copy, CollType, ThreadModel > _CComEnum;
  4512.     typedef IEnumOnSTLImpl<Base, piid, T, Copy, CollType > _CComEnumBase;
  4513.     BEGIN_COM_MAP(_CComEnum)
  4514.         COM_INTERFACE_ENTRY_IID(*piid, _CComEnumBase)
  4515.     END_COM_MAP()
  4516. };
  4517.  
  4518. template <class T, class CollType, class ItemType, class CopyItem, class EnumType>
  4519. class ICollectionOnSTLImpl : public T
  4520. {
  4521. public:
  4522.     STDMETHOD(get_Count)(long* pcount)
  4523.     {
  4524.         if (pcount == NULL)
  4525.             return E_POINTER;
  4526.         *pcount = m_coll.size();
  4527.         return S_OK;
  4528.     }
  4529.     STDMETHOD(get_Item)(long Index, ItemType* pvar)
  4530.     {
  4531.         //Index is 1-based
  4532.         if (pvar == NULL)
  4533.             return E_POINTER;
  4534.         HRESULT hr = E_FAIL;
  4535.         Index--;
  4536.         CollType::iterator iter = m_coll.begin();
  4537.         while (iter != m_coll.end() && Index > 0)
  4538.         {
  4539.             iter++;
  4540.             Index--;
  4541.         }
  4542.         if (iter != m_coll.end())
  4543.             hr = CopyItem::copy(pvar, &*iter);
  4544.         return hr;
  4545.     }
  4546.     STDMETHOD(get__NewEnum)(IUnknown** ppUnk)
  4547.     {
  4548.         if (ppUnk == NULL)
  4549.             return E_POINTER;
  4550.         *ppUnk = NULL;
  4551.         HRESULT hRes = S_OK;
  4552.         CComObject<EnumType>* p;
  4553.         hRes = CComObject<EnumType>::CreateInstance(&p);
  4554.         if (SUCCEEDED(hRes))
  4555.         {
  4556.             hRes = p->Init(this, m_coll);
  4557.             if (hRes == S_OK)
  4558.                 hRes = p->QueryInterface(IID_IUnknown, (void**)ppUnk);
  4559.         }
  4560.         if (hRes != S_OK)
  4561.             delete p;
  4562.         return hRes;
  4563.     }
  4564.     CollType m_coll;
  4565. };
  4566.  
  4567. //////////////////////////////////////////////////////////////////////////////
  4568. // ISpecifyPropertyPagesImpl
  4569. template <class T>
  4570. class ATL_NO_VTABLE ISpecifyPropertyPagesImpl : public ISpecifyPropertyPages
  4571. {
  4572. public:
  4573.     // ISpecifyPropertyPages
  4574.     //
  4575.     STDMETHOD(GetPages)(CAUUID* pPages)
  4576.     {
  4577.         ATLTRACE2(atlTraceCOM, 0, _T("ISpecifyPropertyPagesImpl::GetPages\n"));
  4578.         ATL_PROPMAP_ENTRY* pMap = T::GetPropertyMap();
  4579.         return GetPagesHelper(pPages, pMap);
  4580.     }
  4581. protected:
  4582.     HRESULT GetPagesHelper(CAUUID* pPages, ATL_PROPMAP_ENTRY* pMap)
  4583.     {
  4584.         ATLASSERT(pMap != NULL);
  4585.         if (pMap == NULL)
  4586.             return E_POINTER;
  4587.  
  4588.         int nCnt = 0;
  4589.         // Get count of unique pages to alloc the array
  4590.         for (int i = 0; pMap[i].pclsidPropPage != NULL; i++)
  4591.         {
  4592.             // only allow non data entry types
  4593.             if (pMap[i].vt == 0)
  4594.             {
  4595.                 // Does this property have a page?  CLSID_NULL means it does not
  4596.                 if (!InlineIsEqualGUID(*pMap[i].pclsidPropPage, CLSID_NULL))
  4597.                     nCnt++;
  4598.             }
  4599.         }
  4600.         pPages->pElems = (GUID*) CoTaskMemAlloc(sizeof(CLSID)*nCnt);
  4601.         if (pPages->pElems == NULL)
  4602.             return E_OUTOFMEMORY;
  4603.         // reset count of items we have added to the array
  4604.         nCnt = 0;
  4605.         for (i = 0; pMap[i].pclsidPropPage != NULL; i++)
  4606.         {
  4607.             // only allow non data entry types
  4608.             if (pMap[i].vt == 0)
  4609.             {
  4610.                 // Does this property have a page?  CLSID_NULL means it does not
  4611.                 if (!InlineIsEqualGUID(*pMap[i].pclsidPropPage, CLSID_NULL))
  4612.                 {
  4613.                     BOOL bFound = FALSE;
  4614.                     // Search through array we are building up to see
  4615.                     // if it is already in there
  4616.                     for (int j=0; j<nCnt; j++)
  4617.                     {
  4618.                         if (InlineIsEqualGUID(*(pMap[i].pclsidPropPage), pPages->pElems[j]))
  4619.                         {
  4620.                             // It's already there, so no need to add it again
  4621.                             bFound = TRUE;
  4622.                             break;
  4623.                         }
  4624.                     }
  4625.                     // If we didn't find it in there then add it
  4626.                     if (!bFound)
  4627.                         pPages->pElems[nCnt++] = *pMap[i].pclsidPropPage;
  4628.                 }
  4629.             }
  4630.         }
  4631.         pPages->cElems = nCnt;
  4632.         return S_OK;
  4633.     }
  4634.  
  4635. };
  4636.  
  4637. #ifndef _ATL_NO_CONNECTION_POINTS
  4638. /////////////////////////////////////////////////////////////////////////////
  4639. // Connection Points
  4640.  
  4641. struct _ATL_CONNMAP_ENTRY
  4642. {
  4643.     DWORD dwOffset;
  4644. };
  4645.  
  4646.  
  4647. // We want the offset of the connection point relative to the connection
  4648. // point container base class
  4649. #define BEGIN_CONNECTION_POINT_MAP(x)\
  4650.     typedef x _atl_conn_classtype;\
  4651.     static const _ATL_CONNMAP_ENTRY* GetConnMap(int* pnEntries) {\
  4652.     static const _ATL_CONNMAP_ENTRY _entries[] = {
  4653. // CONNECTION_POINT_ENTRY computes the offset of the connection point to the
  4654. // IConnectionPointContainer interface
  4655. #define CONNECTION_POINT_ENTRY(iid){offsetofclass(_ICPLocator<&iid>, _atl_conn_classtype)-\
  4656.     offsetofclass(IConnectionPointContainerImpl<_atl_conn_classtype>, _atl_conn_classtype)},
  4657. #define END_CONNECTION_POINT_MAP() {(DWORD)-1} }; \
  4658.     if (pnEntries) *pnEntries = sizeof(_entries)/sizeof(_ATL_CONNMAP_ENTRY) - 1; \
  4659.     return _entries;}
  4660.  
  4661.  
  4662. #ifndef _DEFAULT_VECTORLENGTH
  4663. #define _DEFAULT_VECTORLENGTH 4
  4664. #endif
  4665.  
  4666. template <unsigned int nMaxSize>
  4667. class CComUnkArray
  4668. {
  4669. public:
  4670.     CComUnkArray()
  4671.     {
  4672.         memset(m_arr, 0, sizeof(IUnknown*)*nMaxSize);
  4673.     }
  4674.     DWORD Add(IUnknown* pUnk);
  4675.     BOOL Remove(DWORD dwCookie);
  4676.     static DWORD WINAPI GetCookie(IUnknown** pp)
  4677.     {
  4678.         return (DWORD)pp;
  4679.     }
  4680.     static IUnknown* WINAPI GetUnknown(DWORD dwCookie)
  4681.     {
  4682.         return dwCookie ? *(IUnknown**)dwCookie : 0;
  4683.     }
  4684.     IUnknown** begin()
  4685.     {
  4686.         return &m_arr[0];
  4687.     }
  4688.     IUnknown** end()
  4689.     {
  4690.         return &m_arr[nMaxSize];
  4691.     }
  4692. protected:
  4693.     IUnknown* m_arr[nMaxSize];
  4694. };
  4695.  
  4696. template <unsigned int nMaxSize>
  4697. inline DWORD CComUnkArray<nMaxSize>::Add(IUnknown* pUnk)
  4698. {
  4699.     for (IUnknown** pp = begin();pp<end();pp++)
  4700.     {
  4701.         if (*pp == NULL)
  4702.         {
  4703.             *pp = pUnk;
  4704.             return (DWORD)pp; // return cookie
  4705.         }
  4706.     }
  4707.     // If this fires then you need a larger array
  4708.     ATLASSERT(0);
  4709.     return 0;
  4710. }
  4711.  
  4712. template <unsigned int nMaxSize>
  4713. inline BOOL CComUnkArray<nMaxSize>::Remove(DWORD dwCookie)
  4714. {
  4715.     IUnknown** pp = (IUnknown**)dwCookie;
  4716.     BOOL b = ((pp >= begin()) && (pp < end()));
  4717.     if (b)
  4718.         *pp = NULL;
  4719.     return b;
  4720. }
  4721.  
  4722. template<>
  4723. class CComUnkArray<1>
  4724. {
  4725. public:
  4726.     CComUnkArray()
  4727.     {
  4728.         m_arr[0] = NULL;
  4729.     }
  4730.     DWORD Add(IUnknown* pUnk)
  4731.     {
  4732.         if (m_arr[0] != NULL)
  4733.         {
  4734.             // If this fires then you need a larger array
  4735.             ATLASSERT(0);
  4736.             return 0;
  4737.         }
  4738.         m_arr[0] = pUnk;
  4739.         return (DWORD)&m_arr[0];
  4740.     }
  4741.     BOOL Remove(DWORD dwCookie)
  4742.     {
  4743.         if (dwCookie != (DWORD)&m_arr[0])
  4744.             return FALSE;
  4745.         m_arr[0] = NULL;
  4746.         return TRUE;
  4747.     }
  4748.     static DWORD WINAPI GetCookie(IUnknown** pp)
  4749.     {
  4750.         return (DWORD)pp;
  4751.     }
  4752.     static IUnknown* WINAPI GetUnknown(DWORD dwCookie)
  4753.     {
  4754.         return dwCookie ? *(IUnknown**)dwCookie : 0;
  4755.     }
  4756.     IUnknown** begin()
  4757.     {
  4758.         return &m_arr[0];
  4759.     }
  4760.     IUnknown** end()
  4761.     {
  4762.         return (&m_arr[0])+1;
  4763.     }
  4764. protected:
  4765.     IUnknown* m_arr[1];
  4766. };
  4767.  
  4768. class CComDynamicUnkArray
  4769. {
  4770. public:
  4771.     CComDynamicUnkArray()
  4772.     {
  4773.         m_nSize = 0;
  4774.         m_ppUnk = NULL;
  4775.     }
  4776.  
  4777.     ~CComDynamicUnkArray()
  4778.     {
  4779.         if (m_nSize > 1)
  4780.             free(m_ppUnk);
  4781.     }
  4782.     DWORD Add(IUnknown* pUnk);
  4783.     BOOL Remove(DWORD dwCookie);
  4784.     static DWORD WINAPI GetCookie(IUnknown** pp)
  4785.     {
  4786.         return (DWORD)*pp;
  4787.     }
  4788.     static IUnknown* WINAPI GetUnknown(DWORD dwCookie)
  4789.     {
  4790.         return (IUnknown*)dwCookie;
  4791.     }
  4792.     IUnknown** begin()
  4793.     {
  4794.         return (m_nSize < 2) ? &m_pUnk : m_ppUnk;
  4795.     }
  4796.     IUnknown** end()
  4797.     {
  4798.         return (m_nSize < 2) ? (&m_pUnk)+m_nSize : &m_ppUnk[m_nSize];
  4799.     }
  4800.  
  4801.     IUnknown* GetAt(int nIndex)
  4802.     {
  4803.         if (nIndex < 0 || nIndex >= m_nSize)
  4804.             return NULL;
  4805.  
  4806.         return (m_nSize < 2) ? m_pUnk : m_ppUnk[nIndex];
  4807.     }
  4808.     int GetSize() const
  4809.     {
  4810.         return m_nSize;
  4811.     }
  4812.  
  4813.     void clear()
  4814.     {
  4815.         if (m_nSize > 1)
  4816.             free(m_ppUnk);
  4817.         m_nSize = 0;
  4818.     }
  4819. protected:
  4820.     union
  4821.     {
  4822.         IUnknown** m_ppUnk;
  4823.         IUnknown* m_pUnk;
  4824.     };
  4825.     int m_nSize;
  4826. };
  4827.  
  4828. inline DWORD CComDynamicUnkArray::Add(IUnknown* pUnk)
  4829. {
  4830.     IUnknown** pp = NULL;
  4831.     if (m_nSize == 0) // no connections
  4832.     {
  4833.         m_pUnk = pUnk;
  4834.         m_nSize = 1;
  4835.         return (DWORD)m_pUnk;
  4836.     }
  4837.     else if (m_nSize == 1)
  4838.     {
  4839.         //create array
  4840.         pp = (IUnknown**)malloc(sizeof(IUnknown*)*_DEFAULT_VECTORLENGTH);
  4841.         if (pp == NULL)
  4842.             return 0;
  4843.         memset(pp, 0, sizeof(IUnknown*)*_DEFAULT_VECTORLENGTH);
  4844.         *pp = m_pUnk;
  4845.         m_ppUnk = pp;
  4846.         m_nSize = _DEFAULT_VECTORLENGTH;
  4847.     }
  4848.     for (pp = begin();pp<end();pp++)
  4849.     {
  4850.         if (*pp == NULL)
  4851.         {
  4852.             *pp = pUnk;
  4853.             return (DWORD)pUnk;
  4854.         }
  4855.     }
  4856.     int nAlloc = m_nSize*2;
  4857.     pp = (IUnknown**)realloc(m_ppUnk, sizeof(IUnknown*)*nAlloc);
  4858.     if (pp == NULL)
  4859.         return 0;
  4860.     m_ppUnk = pp;
  4861.     memset(&m_ppUnk[m_nSize], 0, sizeof(IUnknown*)*m_nSize);
  4862.     m_ppUnk[m_nSize] = pUnk;
  4863.     m_nSize = nAlloc;
  4864.     return (DWORD)pUnk;
  4865. }
  4866.  
  4867. inline BOOL CComDynamicUnkArray::Remove(DWORD dwCookie)
  4868. {
  4869.     IUnknown** pp;
  4870.     if (dwCookie == NULL)
  4871.         return FALSE;
  4872.     if (m_nSize == 0)
  4873.         return FALSE;
  4874.     if (m_nSize == 1)
  4875.     {
  4876.         if ((DWORD)m_pUnk == dwCookie)
  4877.         {
  4878.             m_nSize = 0;
  4879.             return TRUE;
  4880.         }
  4881.         return FALSE;
  4882.     }
  4883.     for (pp=begin();pp<end();pp++)
  4884.     {
  4885.         if ((DWORD)*pp == dwCookie)
  4886.         {
  4887.             *pp = NULL;
  4888.             return TRUE;
  4889.         }
  4890.     }
  4891.     return FALSE;
  4892. }
  4893.  
  4894. template <const IID* piid>
  4895. class ATL_NO_VTABLE _ICPLocator
  4896. {
  4897. public:
  4898.     //this method needs a different name than QueryInterface
  4899.     STDMETHOD(_LocCPQueryInterface)(REFIID riid, void ** ppvObject) = 0;
  4900.     virtual ULONG STDMETHODCALLTYPE AddRef(void) = 0;\
  4901.     virtual ULONG STDMETHODCALLTYPE Release(void) = 0;
  4902. };
  4903.  
  4904. template <class T, const IID* piid, class CDV = CComDynamicUnkArray >
  4905. class ATL_NO_VTABLE IConnectionPointImpl : public _ICPLocator<piid>
  4906. {
  4907.     typedef CComEnum<IEnumConnections, &IID_IEnumConnections, CONNECTDATA,
  4908.         _Copy<CONNECTDATA> > CComEnumConnections;
  4909.     typedef CDV _CDV;
  4910. public:
  4911.     ~IConnectionPointImpl();
  4912.     STDMETHOD(_LocCPQueryInterface)(REFIID riid, void ** ppvObject)
  4913.     {
  4914.         if (InlineIsEqualGUID(riid, IID_IConnectionPoint) || InlineIsEqualUnknown(riid))
  4915.         {
  4916.             if (ppvObject == NULL)
  4917.                 return E_POINTER;
  4918.             *ppvObject = this;
  4919.             AddRef();
  4920. #ifdef _ATL_DEBUG_INTERFACES
  4921.             _Module.AddThunk((IUnknown**)ppvObject, _T("IConnectionPointImpl"), riid);
  4922. #endif // _ATL_DEBUG_INTERFACES
  4923.             return S_OK;
  4924.         }
  4925.         else
  4926.             return E_NOINTERFACE;
  4927.     }
  4928.  
  4929.     STDMETHOD(GetConnectionInterface)(IID* piid2)
  4930.     {
  4931.         if (piid2 == NULL)
  4932.             return E_POINTER;
  4933.         *piid2 = *piid;
  4934.         return S_OK;
  4935.     }
  4936.     STDMETHOD(GetConnectionPointContainer)(IConnectionPointContainer** ppCPC)
  4937.     {
  4938.         T* pT = static_cast<T*>(this);
  4939.         // No need to check ppCPC for NULL since QI will do that for us
  4940.         return pT->QueryInterface(IID_IConnectionPointContainer, (void**)ppCPC);
  4941.     }
  4942.     STDMETHOD(Advise)(IUnknown* pUnkSink, DWORD* pdwCookie);
  4943.     STDMETHOD(Unadvise)(DWORD dwCookie);
  4944.     STDMETHOD(EnumConnections)(IEnumConnections** ppEnum);
  4945.     CDV m_vec;
  4946. };
  4947.  
  4948. template <class T, const IID* piid, class CDV>
  4949. IConnectionPointImpl<T, piid, CDV>::~IConnectionPointImpl()
  4950. {
  4951.     IUnknown** pp = m_vec.begin();
  4952.     while (pp < m_vec.end())
  4953.     {
  4954.         if (*pp != NULL)
  4955.             (*pp)->Release();
  4956.         pp++;
  4957.     }
  4958. }
  4959.  
  4960. template <class T, const IID* piid, class CDV>
  4961. STDMETHODIMP IConnectionPointImpl<T, piid, CDV>::Advise(IUnknown* pUnkSink,
  4962.     DWORD* pdwCookie)
  4963. {
  4964.     T* pT = static_cast<T*>(this);
  4965.     IUnknown* p;
  4966.     HRESULT hRes = S_OK;
  4967.     if (pUnkSink == NULL || pdwCookie == NULL)
  4968.         return E_POINTER;
  4969.     IID iid;
  4970.     GetConnectionInterface(&iid);
  4971.     hRes = pUnkSink->QueryInterface(iid, (void**)&p);
  4972.     if (SUCCEEDED(hRes))
  4973.     {
  4974.         pT->Lock();
  4975.         *pdwCookie = m_vec.Add(p);
  4976.         hRes = (*pdwCookie != NULL) ? S_OK : CONNECT_E_ADVISELIMIT;
  4977.         pT->Unlock();
  4978.         if (hRes != S_OK)
  4979.             p->Release();
  4980.     }
  4981.     else if (hRes == E_NOINTERFACE)
  4982.         hRes = CONNECT_E_CANNOTCONNECT;
  4983.     if (FAILED(hRes))
  4984.         *pdwCookie = 0;
  4985.     return hRes;
  4986. }
  4987.  
  4988. template <class T, const IID* piid, class CDV>
  4989. STDMETHODIMP IConnectionPointImpl<T, piid, CDV>::Unadvise(DWORD dwCookie)
  4990. {
  4991.     T* pT = static_cast<T*>(this);
  4992.     pT->Lock();
  4993.     IUnknown* p = _CDV::GetUnknown(dwCookie);
  4994.     HRESULT hRes = m_vec.Remove(dwCookie) ? S_OK : CONNECT_E_NOCONNECTION;
  4995.     pT->Unlock();
  4996.     if (hRes == S_OK && p != NULL)
  4997.         p->Release();
  4998.     return hRes;
  4999. }
  5000.  
  5001. template <class T, const IID* piid, class CDV>
  5002. STDMETHODIMP IConnectionPointImpl<T, piid, CDV>::EnumConnections(
  5003.     IEnumConnections** ppEnum)
  5004. {
  5005.     if (ppEnum == NULL)
  5006.         return E_POINTER;
  5007.     *ppEnum = NULL;
  5008.     CComObject<CComEnumConnections>* pEnum = NULL;
  5009.     ATLTRY(pEnum = new CComObject<CComEnumConnections>)
  5010.     if (pEnum == NULL)
  5011.         return E_OUTOFMEMORY;
  5012.     T* pT = static_cast<T*>(this);
  5013.     pT->Lock();
  5014.     CONNECTDATA* pcd = NULL;
  5015.     ATLTRY(pcd = new CONNECTDATA[m_vec.end()-m_vec.begin()])
  5016.     if (pcd == NULL)
  5017.     {
  5018.         delete pEnum;
  5019.         pT->Unlock();
  5020.         return E_OUTOFMEMORY;
  5021.     }
  5022.     CONNECTDATA* pend = pcd;
  5023.     // Copy the valid CONNECTDATA's
  5024.     for (IUnknown** pp = m_vec.begin();pp<m_vec.end();pp++)
  5025.     {
  5026.         if (*pp != NULL)
  5027.         {
  5028.             (*pp)->AddRef();
  5029.             pend->pUnk = *pp;
  5030.             pend->dwCookie = _CDV::GetCookie(pp);
  5031.             pend++;
  5032.         }
  5033.     }
  5034.     // don't copy the data, but transfer ownership to it
  5035.     pEnum->Init(pcd, pend, NULL, AtlFlagTakeOwnership);
  5036.     pT->Unlock();
  5037.     HRESULT hRes = pEnum->_InternalQueryInterface(IID_IEnumConnections, (void**)ppEnum);
  5038.     if (FAILED(hRes))
  5039.         delete pEnum;
  5040.     return hRes;
  5041. }
  5042.  
  5043. /////////////////////////////////////////////////////////////////////////////
  5044. // IConnectionPointContainerImpl
  5045.  
  5046. template <class T>
  5047. class ATL_NO_VTABLE IConnectionPointContainerImpl : public IConnectionPointContainer
  5048. {
  5049.     typedef CComEnum<IEnumConnectionPoints,
  5050.         &IID_IEnumConnectionPoints, IConnectionPoint*,
  5051.         _CopyInterface<IConnectionPoint> >
  5052.         CComEnumConnectionPoints;
  5053. public:
  5054.     STDMETHOD(EnumConnectionPoints)(IEnumConnectionPoints** ppEnum)
  5055.     {
  5056.         if (ppEnum == NULL)
  5057.             return E_POINTER;
  5058.         *ppEnum = NULL;
  5059.         CComEnumConnectionPoints* pEnum = NULL;
  5060.         ATLTRY(pEnum = new CComObject<CComEnumConnectionPoints>)
  5061.         if (pEnum == NULL)
  5062.             return E_OUTOFMEMORY;
  5063.  
  5064.         int nCPCount;
  5065.         const _ATL_CONNMAP_ENTRY* pEntry = T::GetConnMap(&nCPCount);
  5066.  
  5067.         // allocate an initialize a vector of connection point object pointers
  5068.         IConnectionPoint** ppCP = (IConnectionPoint**)alloca(sizeof(IConnectionPoint*)*nCPCount);
  5069.  
  5070.         int i = 0;
  5071.         while (pEntry->dwOffset != (DWORD)-1)
  5072.         {
  5073.             ppCP[i++] = (IConnectionPoint*)((int)this+pEntry->dwOffset);
  5074.             pEntry++;
  5075.         }
  5076.  
  5077.         // copy the pointers: they will AddRef this object
  5078.         HRESULT hRes = pEnum->Init((IConnectionPoint**)&ppCP[0],
  5079.             (IConnectionPoint**)&ppCP[nCPCount],
  5080.             reinterpret_cast<IConnectionPointContainer*>(this), AtlFlagCopy);
  5081.         if (FAILED(hRes))
  5082.         {
  5083.             delete pEnum;
  5084.             return hRes;
  5085.         }
  5086.         hRes = pEnum->QueryInterface(IID_IEnumConnectionPoints, (void**)ppEnum);
  5087.         if (FAILED(hRes))
  5088.             delete pEnum;
  5089.         return hRes;
  5090.     }
  5091.     STDMETHOD(FindConnectionPoint)(REFIID riid, IConnectionPoint** ppCP)
  5092.     {
  5093.         if (ppCP == NULL)
  5094.             return E_POINTER;
  5095.         *ppCP = NULL;
  5096.         HRESULT hRes = CONNECT_E_NOCONNECTION;
  5097.         const _ATL_CONNMAP_ENTRY* pEntry = T::GetConnMap(NULL);
  5098.         IID iid;
  5099.         while (pEntry->dwOffset != (DWORD)-1)
  5100.         {
  5101.             IConnectionPoint* pCP =
  5102.                 (IConnectionPoint*)((int)this+pEntry->dwOffset);
  5103.             if (SUCCEEDED(pCP->GetConnectionInterface(&iid)) &&
  5104.                 InlineIsEqualGUID(riid, iid))
  5105.             {
  5106.                 *ppCP = pCP;
  5107.                 pCP->AddRef();
  5108.                 hRes = S_OK;
  5109.                 break;
  5110.             }
  5111.             pEntry++;
  5112.         }
  5113.         return hRes;
  5114.     }
  5115. };
  5116.  
  5117.  
  5118. #endif //!_ATL_NO_CONNECTION_POINTS
  5119.  
  5120. #pragma pack(pop)
  5121.  
  5122. /////////////////////////////////////////////////////////////////////////////
  5123. // CComAutoThreadModule
  5124.  
  5125. template <class ThreadAllocator>
  5126. inline HRESULT CComAutoThreadModule<ThreadAllocator>::Init(_ATL_OBJMAP_ENTRY* p, HINSTANCE h, const GUID* plibid, int nThreads)
  5127. {
  5128.     m_nThreads = nThreads;
  5129.     m_pApartments = NULL;
  5130.     ATLTRY(m_pApartments = new CComApartment[m_nThreads]);
  5131.     ATLASSERT(m_pApartments != NULL);
  5132.     if(m_pApartments == NULL)
  5133.         return E_OUTOFMEMORY;
  5134.     for (int i = 0; i < nThreads; i++)
  5135.         m_pApartments[i].m_hThread = CreateThread(NULL, 0, CComApartment::_Apartment, (void*)&m_pApartments[i], 0, &m_pApartments[i].m_dwThreadID);
  5136.     CComApartment::ATL_CREATE_OBJECT = RegisterWindowMessage(_T("ATL_CREATE_OBJECT"));
  5137.     return CComModule::Init(p, h, plibid);
  5138. }
  5139.  
  5140. template <class ThreadAllocator>
  5141. inline LONG CComAutoThreadModule<ThreadAllocator>::Lock()
  5142. {
  5143.     LONG l = CComModule::Lock();
  5144.     DWORD dwThreadID = GetCurrentThreadId();
  5145.     for (int i=0; i < m_nThreads; i++)
  5146.     {
  5147.         if (m_pApartments[i].m_dwThreadID == dwThreadID)
  5148.         {
  5149.             m_pApartments[i].Lock();
  5150.             break;
  5151.         }
  5152.     }
  5153.     return l;
  5154. }
  5155.  
  5156. template <class ThreadAllocator>
  5157. inline LONG CComAutoThreadModule<ThreadAllocator>::Unlock()
  5158. {
  5159.     LONG l = CComModule::Unlock();
  5160.     DWORD dwThreadID = GetCurrentThreadId();
  5161.     for (int i=0; i < m_nThreads; i++)
  5162.     {
  5163.         if (m_pApartments[i].m_dwThreadID == dwThreadID)
  5164.         {
  5165.             m_pApartments[i].Unlock();
  5166.             break;
  5167.         }
  5168.     }
  5169.     return l;
  5170. }
  5171.  
  5172. template <class ThreadAllocator>
  5173. HRESULT CComAutoThreadModule<ThreadAllocator>::CreateInstance(void* pfnCreateInstance, REFIID riid, void** ppvObj)
  5174. {
  5175.     _ATL_CREATORFUNC* pFunc = (_ATL_CREATORFUNC*) pfnCreateInstance;
  5176.     _AtlAptCreateObjData data;
  5177.     data.pfnCreateInstance = pFunc;
  5178.     data.piid = &riid;
  5179.     data.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
  5180.     data.hRes = S_OK;
  5181.     int nThread = m_Allocator.GetThread(m_pApartments, m_nThreads);
  5182.     ::PostThreadMessage(m_pApartments[nThread].m_dwThreadID, CComApartment::ATL_CREATE_OBJECT, 0, (LPARAM)&data);
  5183.     AtlWaitWithMessageLoop(data.hEvent);
  5184.     CloseHandle(data.hEvent);
  5185.     if (SUCCEEDED(data.hRes))
  5186.         data.hRes = CoGetInterfaceAndReleaseStream(data.pStream, riid, ppvObj);
  5187.     return data.hRes;
  5188. }
  5189.  
  5190. template <class ThreadAllocator>
  5191. CComAutoThreadModule<ThreadAllocator>::~CComAutoThreadModule()
  5192. {
  5193.     for (int i=0; i < m_nThreads; i++)
  5194.     {
  5195.         ::PostThreadMessage(m_pApartments[i].m_dwThreadID, WM_QUIT, 0, 0);
  5196.         ::WaitForSingleObject(m_pApartments[i].m_hThread, INFINITE);
  5197.     }
  5198.     delete[] m_pApartments;
  5199. }
  5200.  
  5201.  
  5202. }; //namespace ATL
  5203.  
  5204. #endif // __ATLCOM_H__
  5205.  
  5206. /////////////////////////////////////////////////////////////////////////////
  5207.