Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5757 lines
168 KiB

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