Source code of Windows XP (NT5)
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.

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