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.

4350 lines
106 KiB

  1. /*===================================================================
  2. Microsoft Denali
  3. Microsoft Confidential.
  4. Copyright 1996 Microsoft Corporation. All Rights Reserved.
  5. Component: Script Manager
  6. File: ScrptMgr.cpp
  7. Owner: AndrewS
  8. This file contains the implementation of the Scrip Manager,
  9. ie: siting an ActiveX Scripting engine (in our case VBScript) for Denali.
  10. ===================================================================*/
  11. #include "denpre.h"
  12. #pragma hdrstop
  13. #include "dbgcxt.h"
  14. #include "SMHash.h"
  15. #include "perfdata.h"
  16. #include "debugger.h"
  17. #include "wraptlib.h"
  18. // ATQ Scheduler
  19. #include "issched.hxx"
  20. #include "MemChk.h"
  21. CScriptManager g_ScriptManager;
  22. IWrapTypeLibs *g_pWrapTypelibs = NULL;
  23. #define RESPONSE_END_ERRORCODE ERROR_OPERATION_ABORTED
  24. HRESULT GetProgLangIdOfName(LPCSTR szProgLangName, PROGLANG_ID *pProgLangId);
  25. //*****************************************************************************
  26. // The following macros are used to catch exceptions thrown from the external
  27. // scripting engines.
  28. //
  29. // Use of TRY/CATCH blocks around calls to the script engine is controlled by
  30. // the DBG compile #define. If DBG is 1, then the TRY/CATCH blocks are NOT
  31. // used so that checked builds break into the debugger and we can examine why
  32. // the error occurred. If DBG is 0, then the TRY/CATCH blocks are used and
  33. // exceptions are captured and logged to the browser (if possible) and the NT
  34. // Event log.
  35. //
  36. // The TRYCATCH macros are:
  37. //
  38. // TRYCATCH(_s, _IFStr)
  39. // _s - statement to execute inside of TRY/CATCH block.
  40. // _IFStr - string containing the name of interface invoked
  41. // TRYCATCH_HR(_s, _hr, _IFStr)
  42. // _s - statement to execute inside of TRY/CATCH block.
  43. // _hr - HRESULT to store return from _s
  44. // _IFStr - string containing the name of interface invoked
  45. // TRYCATCH_NOHITOBJ(_s, _IFStr)
  46. // Same as TRYCATCH() except there is no Hitobj in the "this" object
  47. // TRYCATCH_HR_NOHITOBJ(_s, _hr, _IFStr)
  48. // Same as TRYCATCH_HR() except there is no Hitobj in the "this" object
  49. //
  50. // NOTES:
  51. // The macros also expect that there is a local variable defined in the function
  52. // the macros is used of type char * named _pFuncName.
  53. //
  54. // A minimal test capability is included to allow for random errors to be throw.
  55. // The test code is compiled in based on the TEST_TRYCATCH #define.
  56. //
  57. //*****************************************************************************
  58. //*****************************************************************************
  59. // TEST_TRYCATCH definitions
  60. //*****************************************************************************
  61. #define TEST_TRYCATCH 0
  62. #if TEST_TRYCATCH
  63. #define THROW_INTERVAL 57
  64. int g_TryCatchCount = 0;
  65. #define TEST_THROW_ERROR g_TryCatchCount++; if ((g_TryCatchCount % THROW_INTERVAL) == 0) {THROW(0x80070000+g_TryCatchCount);}
  66. #else
  67. #define TEST_THROW_ERROR
  68. #endif
  69. //*****************************************************************************
  70. // The following is the heart of the TRYCATCH macros. The definitions here are
  71. // based on the definition of DBG. Again, note that when DBG is off that the
  72. // TRYCATCH defines are removed.
  73. //*****************************************************************************
  74. #if DBG == 0
  75. #define START_TRYCATCH do { TRY
  76. #define END_TRYCATCH(_hr, _hitobj, _IFStr) \
  77. CATCH(nException) \
  78. HandleErrorMissingFilename(IDE_SCRIPT_ENGINE_GPF, _hitobj,TRUE,nException,_IFStr,_pFuncName); \
  79. _hr = nException; \
  80. END_TRY } while(0)
  81. #else
  82. #define START_TRYCATCH do {
  83. #define END_TRYCATCH(_hr, _hitobj, _IFStr) } while (0)
  84. #endif
  85. //*****************************************************************************
  86. // Definition of TRYCATCH_INT which is used by all of the TRYCATCH macros
  87. // described above.
  88. //*****************************************************************************
  89. #define TRYCATCH_INT(_s, _hr, _hitobj, _IFStr) \
  90. START_TRYCATCH \
  91. TEST_THROW_ERROR \
  92. _hr = _s; \
  93. END_TRYCATCH(_hr, _hitobj, _IFStr)
  94. //*****************************************************************************
  95. // Here are the actual definitions of the TRYCATCH macros described above.
  96. //*****************************************************************************
  97. #define TRYCATCH(_s, _IFStr) \
  98. do { \
  99. HRESULT _tempHR; \
  100. TRYCATCH_INT(_s, _tempHR, m_pHitObj, _IFStr); \
  101. } while (0)
  102. #define TRYCATCH_HR(_s, _hr, _IFStr) TRYCATCH_INT(_s, _hr, m_pHitObj, _IFStr)
  103. #define TRYCATCH_NOHITOBJ(_s, _IFStr) \
  104. do { \
  105. HRESULT _tempHR; \
  106. TRYCATCH_INT(_s, _tempHR, NULL, _IFStr); \
  107. } while (0)
  108. #define TRYCATCH_HR_NOHITOBJ(_s, _hr, _IFStr) TRYCATCH_INT(_s, _hr, NULL, _IFStr)
  109. /*===================================================================
  110. CActiveScriptEngine::CActiveScriptEngine
  111. Constructor for CActiveScriptEngine object
  112. Returns:
  113. Nothing
  114. Side effects:
  115. None.
  116. ===================================================================*/
  117. CActiveScriptEngine::CActiveScriptEngine()
  118. : m_cRef(1), m_fInited(FALSE), m_fZombie(FALSE), m_fScriptLoaded(FALSE),
  119. m_fObjectsLoaded(FALSE), m_fTemplateNameAllocated(FALSE),
  120. m_pAS(NULL), m_pASP(NULL), m_pDisp(NULL), m_pHIUpdate(NULL), m_lcid(LOCALE_SYSTEM_DEFAULT),
  121. m_pHitObj(NULL), m_szTemplateName(NULL), m_fScriptAborted(FALSE), m_fScriptTimedOut(FALSE),
  122. m_fScriptHadError(FALSE), m_fCorrupted(FALSE), m_fBeingDebugged(FALSE), m_pTemplate(NULL),
  123. m_dwInstanceID(0xBADF00D), m_dwSourceContext(0xBADF00D)
  124. {
  125. }
  126. /*===================================================================
  127. CActiveScriptEngine::~CActiveScriptEngine
  128. Destructor for CActiveScriptEngine object
  129. Returns:
  130. Nothing
  131. Side effects:
  132. None.
  133. ===================================================================*/
  134. CActiveScriptEngine::~CActiveScriptEngine()
  135. {
  136. if (m_fTemplateNameAllocated)
  137. delete[] m_szTemplateName;
  138. if (m_pTemplate)
  139. m_pTemplate->Release();
  140. }
  141. /*===================================================================
  142. CActiveScriptEngine::FinalRelease
  143. Call this when we are done with the object - Like release but
  144. it removes all of the interfaces we got, so that the ref.
  145. count can vanish when last external user is done with the engine
  146. Returns:
  147. Nothing
  148. Side effects:
  149. None.
  150. ===================================================================*/
  151. ULONG CActiveScriptEngine::FinalRelease()
  152. {
  153. static const char *_pFuncName = "CActiveScriptEngine::FinalRelease()";
  154. if (m_pDisp)
  155. {
  156. TRYCATCH(m_pDisp->Release(),"IScriptDispatch::Release()");
  157. m_pDisp = NULL;
  158. }
  159. if (m_pASP)
  160. {
  161. TRYCATCH(m_pASP->Release(),"IActiveScriptParse::Release()");
  162. m_pASP = NULL;
  163. }
  164. if (m_pHIUpdate)
  165. {
  166. TRYCATCH(m_pHIUpdate->Release(),"IHostInfoUpdate::Release()");
  167. m_pHIUpdate = NULL;
  168. }
  169. if (m_pAS)
  170. {
  171. HRESULT hr;
  172. // First "close" the engine
  173. TRYCATCH_HR(m_pAS->Close(), hr, "IActiveScript::Close()");
  174. Assert(SUCCEEDED(hr));
  175. // Then we can release it
  176. TRYCATCH(m_pAS->Release(), "IActiveScript::Release()");
  177. m_pAS = NULL;
  178. }
  179. ULONG cRefs = Release();
  180. Assert (cRefs == 0);
  181. return cRefs;
  182. }
  183. /*===================================================================
  184. CActiveScriptEngine::Init
  185. Init the script site object. This must only be called once.
  186. Returns:
  187. HRESULT. S_OK on success.
  188. Side effects:
  189. None.
  190. ===================================================================*/
  191. HRESULT CActiveScriptEngine::Init
  192. (
  193. PROGLANG_ID proglang_id,
  194. LPCTSTR szTemplateName,
  195. LCID lcid,
  196. CHitObj *pHitObj,
  197. CTemplate *pTemplate,
  198. DWORD dwSourceContext
  199. )
  200. {
  201. static const char *_pFuncName = "CActiveScriptEngine::Init()";
  202. HRESULT hr;
  203. UINT cTrys = 0;
  204. if (m_fInited)
  205. {
  206. Assert(FALSE);
  207. return(ERROR_ALREADY_INITIALIZED);
  208. }
  209. // Note: need to init these first, because we will need them if AS calls back into us during init.
  210. m_lcid = lcid;
  211. m_proglang_id = proglang_id;
  212. m_pHitObj = pHitObj;
  213. m_dwSourceContext = dwSourceContext;
  214. m_dwInstanceID = pHitObj->DWInstanceID();
  215. m_pTemplate = pTemplate;
  216. m_pTemplate->AddRef();
  217. lRetry:
  218. // Create an instance of the script engine for the given language
  219. hr = CoCreateInstance(proglang_id, NULL, CLSCTX_INPROC_SERVER, IID_IActiveScript, (void**)&m_pAS);
  220. if (FAILED(hr))
  221. {
  222. /*
  223. * If some control (or other component) does a CoUninitialize on our thread, we will
  224. * never be able to create another object. In this case, we will get back CO_E_NOTINITIALIZED.
  225. * Try (once) to re-initialize and then create the object
  226. */
  227. if (hr == CO_E_NOTINITIALIZED && cTrys++ == 0)
  228. {
  229. MSG_Error(IDS_COUNINITIALIZE);
  230. hr = CoInitialize(NULL);
  231. if (SUCCEEDED(hr))
  232. goto lRetry;
  233. }
  234. goto LFail;
  235. }
  236. // Remember template name
  237. hr = StoreTemplateName(szTemplateName);
  238. if (FAILED(hr))
  239. goto LFail;
  240. // Tell ActiveScripting that this is our script site
  241. TRYCATCH_HR(m_pAS->SetScriptSite((IActiveScriptSite *)this), hr, "IActiveScript::SetScriptSite()");
  242. if (FAILED(hr))
  243. {
  244. goto LFail;
  245. }
  246. // Tell ActiveScripting which exceptions we want caught
  247. IActiveScriptProperty *pScriptProperty;
  248. TRYCATCH_HR(m_pAS->QueryInterface(IID_IActiveScriptProperty, reinterpret_cast<void **>(&pScriptProperty)), hr, "IActiveScript::QueryInterface()");
  249. if (SUCCEEDED(hr))
  250. {
  251. static const int rgnExceptionsToCatch[] =
  252. {
  253. STATUS_GUARD_PAGE_VIOLATION ,
  254. STATUS_DATATYPE_MISALIGNMENT ,
  255. STATUS_ACCESS_VIOLATION ,
  256. STATUS_INVALID_HANDLE ,
  257. STATUS_NO_MEMORY ,
  258. STATUS_ILLEGAL_INSTRUCTION ,
  259. STATUS_INVALID_DISPOSITION , // what's this? Do we need to catch it?
  260. STATUS_ARRAY_BOUNDS_EXCEEDED ,
  261. STATUS_FLOAT_DENORMAL_OPERAND ,
  262. STATUS_FLOAT_DIVIDE_BY_ZERO ,
  263. STATUS_FLOAT_INVALID_OPERATION ,
  264. STATUS_FLOAT_OVERFLOW ,
  265. STATUS_FLOAT_STACK_CHECK ,
  266. STATUS_INTEGER_DIVIDE_BY_ZERO ,
  267. STATUS_INTEGER_OVERFLOW ,
  268. STATUS_PRIVILEGED_INSTRUCTION ,
  269. STATUS_STACK_OVERFLOW
  270. };
  271. VARIANT varBoolTrue;
  272. VARIANT varExceptionType;
  273. V_VT(&varExceptionType) = VT_I4;
  274. V_VT(&varBoolTrue) = VT_BOOL;
  275. V_BOOL(&varBoolTrue) = -1;
  276. for (int i = 0; i < (sizeof rgnExceptionsToCatch) / sizeof(int); ++i)
  277. {
  278. V_I4(&varExceptionType) = rgnExceptionsToCatch[i];
  279. TRYCATCH(pScriptProperty->SetProperty(SCRIPTPROP_CATCHEXCEPTION, &varExceptionType, &varBoolTrue), "IActiveScriptProperty::SetProperty");
  280. }
  281. pScriptProperty->Release();
  282. }
  283. // Get ActiveScriptParse interface
  284. hr = GetASP();
  285. if (FAILED(hr))
  286. goto LFail;
  287. // Tell the script parser to init itself
  288. TRYCATCH_HR(m_pASP->InitNew(), hr, "IActiveScriptParse::InitNew()");
  289. if (FAILED(hr))
  290. goto LFail;
  291. // Get IDisp interface
  292. hr = GetIDisp();
  293. if (FAILED(hr))
  294. goto LFail;
  295. // Get IHostInfoUpdate interface
  296. hr = GetIHostInfoUpdate();
  297. if (FAILED(hr))
  298. goto LFail;
  299. m_fInited = TRUE;
  300. LFail:
  301. if (FAILED(hr))
  302. {
  303. if (m_pAS)
  304. {
  305. TRYCATCH(m_pAS->Release(),"IActiveScript::Release()");
  306. m_pAS = NULL;
  307. }
  308. if (m_pASP)
  309. {
  310. TRYCATCH(m_pASP->Release(),"IActiveScriptParse::Release()");
  311. m_pASP = NULL;
  312. }
  313. if (m_pDisp)
  314. {
  315. TRYCATCH(m_pDisp->Release(),"IScriptDispatch::Release()");
  316. m_pDisp = NULL;
  317. }
  318. if (m_pTemplate)
  319. {
  320. m_pTemplate->Release();
  321. m_pTemplate = NULL;
  322. }
  323. if (m_pHIUpdate)
  324. {
  325. TRYCATCH(m_pHIUpdate->Release(),"IHostInfoUpdate::Release()");
  326. m_pHIUpdate = NULL;
  327. }
  328. }
  329. return(hr);
  330. }
  331. /*===================================================================
  332. CActiveScriptEngine::StoreTemplateName
  333. Stores template name inside CActiveScriptEngine. Allocates
  334. buffer or uses internal one if the name fits.
  335. Returns:
  336. HRESULT. S_OK on success.
  337. Side effects:
  338. Might allocate memory for long template names
  339. ===================================================================*/
  340. HRESULT CActiveScriptEngine::StoreTemplateName
  341. (
  342. LPCTSTR szTemplateName
  343. )
  344. {
  345. DWORD cch = _tcslen(szTemplateName);
  346. if (((cch+1)*sizeof(TCHAR)) <= sizeof(m_szTemplateNameBuf))
  347. {
  348. m_szTemplateName = m_szTemplateNameBuf;
  349. m_fTemplateNameAllocated = FALSE;
  350. }
  351. else
  352. {
  353. m_szTemplateName = new TCHAR[cch+1];
  354. if (!m_szTemplateName)
  355. return E_OUTOFMEMORY;
  356. m_fTemplateNameAllocated = TRUE;
  357. }
  358. _tcscpy(m_szTemplateName, szTemplateName);
  359. return S_OK;
  360. }
  361. /*===================================================================
  362. CActiveScriptEngine::GetASP
  363. Get an ActiveScriptParser interface from ActiveScripting
  364. Returns:
  365. HRESULT. S_OK on success.
  366. Side effects:
  367. Fills in member variables
  368. ===================================================================*/
  369. HRESULT CActiveScriptEngine::GetASP
  370. (
  371. )
  372. {
  373. static const char *_pFuncName = "CActiveScriptEngine::GetASP()";
  374. HRESULT hr;
  375. Assert(m_pASP == NULL);
  376. m_pASP = NULL;
  377. // Get OLE Scripting parser interface, if any
  378. TRYCATCH_HR(m_pAS->QueryInterface(IID_IActiveScriptParse, (void **)&m_pASP), hr, "IActiveScript::QueryInterface()");
  379. if (m_pASP == NULL && SUCCEEDED(hr))
  380. hr = E_FAIL;
  381. if (FAILED(hr))
  382. {
  383. goto LFail;
  384. }
  385. LFail:
  386. if (FAILED(hr))
  387. {
  388. if (m_pASP)
  389. {
  390. TRYCATCH(m_pASP->Release(),"IActiveScriptParse::Release()");
  391. m_pASP = NULL;
  392. }
  393. }
  394. return(hr);
  395. }
  396. /*===================================================================
  397. CActiveScriptEngine::GetIDisp
  398. Get an IDispatch interface from ActiveScripting
  399. Returns:
  400. HRESULT. S_OK on success.
  401. Side effects:
  402. Fills in member variables
  403. ===================================================================*/
  404. HRESULT CActiveScriptEngine::GetIDisp
  405. (
  406. )
  407. {
  408. static const char *_pFuncName = "CActiveScriptEngine::GetIDisp()";
  409. HRESULT hr;
  410. Assert(m_pDisp == NULL);
  411. m_pDisp = NULL;
  412. // Get an IDispatch interface to be able to call functions in the script
  413. TRYCATCH_HR(m_pAS->GetScriptDispatch(NULL, &m_pDisp),hr,"IActiveScript::GetScriptDispatch()");
  414. if (m_pDisp == NULL && SUCCEEDED(hr))
  415. hr = E_FAIL;
  416. if (FAILED(hr))
  417. {
  418. goto LFail;
  419. }
  420. LFail:
  421. if (FAILED(hr))
  422. {
  423. if (m_pDisp)
  424. {
  425. TRYCATCH(m_pDisp->Release(),"IScriptDispatch::Release()");
  426. m_pDisp = NULL;
  427. }
  428. }
  429. return(hr);
  430. }
  431. /*===================================================================
  432. CActiveScriptEngine::GetIHostInfoUpdate
  433. Get an IHostInfoUpdate interface from ActiveScripting.
  434. This interface is used to advise the scripting engine that
  435. we have new information about the host (change in LCID for example)
  436. If we can't find the interface, we exit succesfully anyway.
  437. Returns:
  438. HRESULT. S_OK on success.
  439. Side effects:
  440. Fills in member variables
  441. ===================================================================*/
  442. HRESULT CActiveScriptEngine::GetIHostInfoUpdate
  443. (
  444. )
  445. {
  446. static const char *_pFuncName = "CActiveScriptEngine::GetIHostInfoUpdate()";
  447. HRESULT hr = S_OK;
  448. Assert(m_pHIUpdate == NULL);
  449. m_pHIUpdate = NULL;
  450. // Get an IHostInfoUpdate interface to be able to call functions in the script
  451. TRYCATCH_HR(m_pAS->QueryInterface(IID_IHostInfoUpdate, (void **) &m_pHIUpdate),
  452. hr,
  453. "IActiveScript::QueryInterface()");
  454. Assert(SUCCEEDED(hr) || hr == E_NOINTERFACE);
  455. return(S_OK);
  456. }
  457. /*===================================================================
  458. CActiveScriptEngine::ResetToUninitialized
  459. When we want to reuse and engine, we reset it to an uninited state
  460. before putting it on the FSQ
  461. Returns:
  462. HRESULT. S_OK on success.
  463. Side effects:
  464. None.
  465. ===================================================================*/
  466. HRESULT CActiveScriptEngine::ResetToUninitialized()
  467. {
  468. static const char *_pFuncName = "CActiveScriptEngine::ResetToUninitialized()";
  469. HRESULT hr = S_OK;
  470. // Reset our flags
  471. m_fScriptAborted = FALSE;
  472. m_fScriptTimedOut = FALSE;
  473. m_fScriptHadError = FALSE;
  474. m_fBeingDebugged = FALSE;
  475. // Release interfaces, they will need to be re-gotten when
  476. // the engine is reused
  477. if (m_pASP) {
  478. TRYCATCH(m_pASP->Release(),"IActiveScriptParse::Release()");
  479. m_pASP = NULL;
  480. }
  481. if (m_pDisp) {
  482. TRYCATCH(m_pDisp->Release(),"IScriptDispatch::Release()");
  483. m_pDisp = NULL;
  484. }
  485. if(m_pHIUpdate) {
  486. TRYCATCH(m_pHIUpdate->Release(),"IHostInfoUpdate::Release()");
  487. m_pHIUpdate = NULL;
  488. }
  489. // Hitobj will no longer be valid
  490. m_pHitObj = NULL;
  491. // Set the script state to Uninited
  492. if (m_pAS) {
  493. TRYCATCH_HR(ResetScript(), hr, "IActiveScript::SetScriptState()");
  494. }
  495. return(hr);
  496. }
  497. /*===================================================================
  498. CActiveScriptEngine::ReuseEngine
  499. Reusing an engine from the FSQ. Reset stuff
  500. Returns:
  501. HRESULT. S_OK on success.
  502. Side effects:
  503. Sets member variables.
  504. ===================================================================*/
  505. HRESULT CActiveScriptEngine::ReuseEngine
  506. (
  507. CHitObj *pHitObj,
  508. CTemplate *pTemplate,
  509. DWORD dwSourceContext,
  510. DWORD dwInstanceID
  511. )
  512. {
  513. static const char *_pFuncName = "CActiveScriptEngine::ReuseEngine()";
  514. HRESULT hr = S_OK;
  515. /* NOTE: we must reset the hitobj & other members BEFORE calling
  516. * any Active Scripting methods (esp. SetScriptSite) This is
  517. * because SetScriptSite queries us for the debug application, which
  518. * relies on the hitobj being set.
  519. */
  520. // reset the hitobj
  521. m_pHitObj = pHitObj;
  522. // Reset the debug document
  523. if (pTemplate)
  524. {
  525. if (m_pTemplate)
  526. m_pTemplate->Release();
  527. m_dwSourceContext = dwSourceContext;
  528. m_dwInstanceID = dwInstanceID;
  529. m_pTemplate = pTemplate;
  530. m_pTemplate->AddRef();
  531. }
  532. // If the engine is in the UNITIALIZED state ONLY then tell ActiveScripting
  533. // that this is our script site. (Scripts in the debug cache are already initialized)
  534. SCRIPTSTATE nScriptState;
  535. TRYCATCH_HR(m_pAS->GetScriptState(&nScriptState), hr, "IActiveScript::GetScriptState()");
  536. if (FAILED(hr))
  537. goto LFail;
  538. if (nScriptState == SCRIPTSTATE_UNINITIALIZED)
  539. {
  540. TRYCATCH_HR(m_pAS->SetScriptSite(static_cast<IActiveScriptSite *>(this)),hr, "IActiveScript::SetScriptState()");
  541. if (FAILED(hr))
  542. goto LFail;
  543. }
  544. // Get ActiveScriptParse interface
  545. hr = GetASP();
  546. if (FAILED(hr))
  547. goto LFail;
  548. // Get IDisp interface
  549. hr = GetIDisp();
  550. if (FAILED(hr))
  551. goto LFail;
  552. // Get IHostInfoUpdate interface
  553. hr = GetIHostInfoUpdate();
  554. if (FAILED(hr))
  555. goto LFail;
  556. AssertValid();
  557. LFail:
  558. return(hr);
  559. }
  560. /*===================================================================
  561. CActiveScriptEngine::MakeClone
  562. We are cloning a running script engine. Fill this new ActiveScriptEngine
  563. with the cloned ActiveScript.
  564. Returns:
  565. HRESULT. S_OK on success.
  566. Side effects:
  567. None.
  568. ===================================================================*/
  569. HRESULT CActiveScriptEngine::MakeClone
  570. (
  571. PROGLANG_ID proglang_id,
  572. LPCTSTR szTemplateName,
  573. LCID lcid,
  574. CHitObj *pHitObj,
  575. CTemplate *pTemplate,
  576. DWORD dwSourceContext,
  577. DWORD dwInstanceID,
  578. IActiveScript *pAS // The cloned script engine
  579. )
  580. {
  581. static const char *_pFuncName = "CActiveScriptEngine::MakeClone()";
  582. HRESULT hr;
  583. if (m_fInited)
  584. {
  585. Assert(FALSE);
  586. return(ERROR_ALREADY_INITIALIZED);
  587. }
  588. // Note: need to init these first, because we will need them if AS calls back into us during init.
  589. m_lcid = lcid;
  590. m_proglang_id = proglang_id;
  591. m_pHitObj = pHitObj;
  592. m_pAS = pAS;
  593. StoreTemplateName(szTemplateName);
  594. if (m_pTemplate)
  595. m_pTemplate->Release();
  596. m_dwSourceContext = dwSourceContext;
  597. m_dwInstanceID = dwInstanceID;
  598. m_pTemplate = pTemplate;
  599. m_pTemplate->AddRef();
  600. // We are not yet inited fully but SetScriptSite may call back into us so we must flag inited now.
  601. m_fInited = TRUE;
  602. // Tell ActiveScripting that this is our script site
  603. TRYCATCH_HR(m_pAS->SetScriptSite((IActiveScriptSite *)this), hr, "IActiveScript::SetScriptSite()");
  604. if (FAILED(hr))
  605. {
  606. goto LFail;
  607. }
  608. // Get ActiveScriptParse interface
  609. hr = GetASP();
  610. if (FAILED(hr))
  611. goto LFail;
  612. // Get IDisp interface
  613. hr = GetIDisp();
  614. if (FAILED(hr))
  615. goto LFail;
  616. // Get IHostInfoUpdate interface
  617. hr = GetIHostInfoUpdate();
  618. if (FAILED(hr))
  619. goto LFail;
  620. // Because we are a clone of an already loaded engine, we have script and objects loaded.
  621. m_fScriptLoaded = TRUE;
  622. m_fObjectsLoaded = TRUE;
  623. // We should be valid now.
  624. AssertValid();
  625. LFail:
  626. if (FAILED(hr))
  627. {
  628. m_fInited = FALSE;
  629. if (m_pAS)
  630. {
  631. // dont release the passed in script engine on failure
  632. m_pAS = NULL;
  633. }
  634. if (m_pASP)
  635. {
  636. TRYCATCH(m_pASP->Release(),"IActiveScriptParse::Release()");
  637. m_pASP = NULL;
  638. }
  639. if (m_pDisp)
  640. {
  641. TRYCATCH(m_pDisp->Release(),"IScriptDispatch::Release()");
  642. m_pDisp = NULL;
  643. }
  644. if (m_pTemplate)
  645. {
  646. m_pTemplate->Release();
  647. m_pTemplate = NULL;
  648. }
  649. if (m_pHIUpdate)
  650. {
  651. TRYCATCH(m_pHIUpdate->Release(),"IHostInfoUpdate::Release()");
  652. m_pHIUpdate = NULL;
  653. }
  654. }
  655. return(hr);
  656. }
  657. /*===================================================================
  658. CActiveScriptEngine::InterruptScript
  659. Stop the script from running
  660. Returns:
  661. HRESULT. S_OK on success.
  662. Side effects:
  663. Stops the script from running
  664. ===================================================================*/
  665. HRESULT CActiveScriptEngine::InterruptScript
  666. (
  667. BOOL fAbnormal // = TRUE
  668. )
  669. {
  670. static const char *_pFuncName = "CActiveScriptEngine::InterruptScript()";
  671. HRESULT hr;
  672. EXCEPINFO excepinfo;
  673. AssertValid();
  674. // Fill in the excepinfo. This will be passed to OnScriptError
  675. memset(&excepinfo, 0x0, sizeof(EXCEPINFO));
  676. if (fAbnormal)
  677. {
  678. m_fScriptTimedOut = TRUE;
  679. excepinfo.wCode = ERROR_SERVICE_REQUEST_TIMEOUT;
  680. }
  681. else
  682. {
  683. m_fScriptAborted = TRUE;
  684. excepinfo.wCode = RESPONSE_END_ERRORCODE; // Error code to ourselves - means Response.End was invoked
  685. }
  686. TRYCATCH_HR(m_pAS->InterruptScriptThread(SCRIPTTHREADID_BASE, // The thread in which the engine was instantiated
  687. &excepinfo,
  688. 0),
  689. hr,
  690. "IActiveScript::InterruptScriptThread()");
  691. return(hr);
  692. }
  693. /*===================================================================
  694. CActiveScriptEngine::UpdateLocaleInfo
  695. Advise the script engine that we want to update the lcid or
  696. code page
  697. Returns:
  698. HRESULT. S_OK on success.
  699. ===================================================================*/
  700. HRESULT CActiveScriptEngine::UpdateLocaleInfo
  701. (
  702. hostinfo hiNew
  703. )
  704. {
  705. static const char *_pFuncName = "CActiveScriptEngine::UpdateLocaleInfo()";
  706. HRESULT hr = S_OK;
  707. // If no IUpdateHost ineterface is available
  708. // just skip the call to UpdateInfo;
  709. if (m_pHIUpdate)
  710. TRYCATCH_HR(m_pHIUpdate->UpdateInfo(hiNew), hr, "IHostInfoUpdate::UpdateInfo()");
  711. return hr;
  712. }
  713. #ifdef DBG
  714. /*===================================================================
  715. CActiveScriptEngine::AssertValid
  716. Test to make sure that the CActiveScriptEngine object is currently correctly formed
  717. and assert if it is not.
  718. Returns:
  719. Side effects:
  720. None.
  721. ===================================================================*/
  722. VOID CActiveScriptEngine::AssertValid() const
  723. {
  724. Assert(m_fInited);
  725. Assert(m_pAS != NULL);
  726. Assert(m_pTemplate != NULL);
  727. }
  728. #endif // DBG
  729. /*
  730. *
  731. *
  732. *
  733. * I U n k n o w n M e t h o d s
  734. *
  735. *
  736. *
  737. *
  738. */
  739. /*===================================================================
  740. CActiveScriptEngine::QueryInterface
  741. CActiveScriptEngine::AddRef
  742. CActiveScriptEngine::Release
  743. IUnknown members for CActiveScriptEngine object.
  744. ===================================================================*/
  745. STDMETHODIMP CActiveScriptEngine::QueryInterface
  746. (
  747. REFIID riid,
  748. PVOID *ppvObj
  749. )
  750. {
  751. if (ppvObj == NULL)
  752. {
  753. Assert(FALSE);
  754. return E_POINTER;
  755. }
  756. *ppvObj = NULL;
  757. if (IsEqualIID(riid, IID_IUnknown))
  758. {
  759. // this IS NOT derived directly from IUnknown
  760. // typecast this to something that IS
  761. *ppvObj = static_cast<IActiveScriptSite *>(this);
  762. }
  763. else if (IsEqualIID(riid, IID_IActiveScriptSite))
  764. {
  765. *ppvObj = static_cast<IActiveScriptSite *>(this);
  766. }
  767. else if (IsEqualIID(riid, IID_IActiveScriptSiteDebug))
  768. {
  769. *ppvObj = static_cast<IActiveScriptSiteDebug *>(this);
  770. }
  771. else if (IsEqualIID(riid, IID_IHostInfoProvider))
  772. {
  773. *ppvObj = static_cast<IHostInfoProvider *>(this);
  774. }
  775. if (*ppvObj != NULL)
  776. {
  777. AddRef();
  778. return(S_OK);
  779. }
  780. return(E_NOINTERFACE);
  781. }
  782. STDMETHODIMP_(ULONG) CActiveScriptEngine::AddRef()
  783. {
  784. ++m_cRef;
  785. return(m_cRef);
  786. }
  787. STDMETHODIMP_(ULONG) CActiveScriptEngine::Release()
  788. {
  789. if (--m_cRef)
  790. return(m_cRef);
  791. delete this;
  792. return(0);
  793. }
  794. /*
  795. *
  796. *
  797. *
  798. * I A c t i v e S c r i p t S i t e M e t h o d s
  799. *
  800. *
  801. *
  802. *
  803. */
  804. /*===================================================================
  805. CActiveScriptEngine::GetLCID
  806. Provide the local id for the script to the script engine.
  807. Returns:
  808. HRESULT. Always returns S_OK.
  809. Side effects:
  810. None.
  811. ===================================================================*/
  812. STDMETHODIMP CActiveScriptEngine::GetLCID
  813. (
  814. LCID *plcid
  815. )
  816. {
  817. // It is OK to call this before we are fully inited.
  818. //AssertValid();
  819. *plcid = ((CActiveScriptEngine *)this)->m_lcid;
  820. return(S_OK);
  821. }
  822. /*===================================================================
  823. CActiveScriptEngine::GetItemInfo
  824. Provide requested info for a named item to the script engine. May be
  825. asked for IUnknown, ITypeInfo or both.
  826. Returns:
  827. HRESULT. S_OK on success.
  828. Side effects:
  829. None.
  830. ===================================================================*/
  831. STDMETHODIMP CActiveScriptEngine::GetItemInfo
  832. (
  833. LPCOLESTR pcszName,
  834. DWORD dwReturnMask,IUnknown **ppiunkItem,
  835. ITypeInfo **ppti
  836. )
  837. {
  838. HRESULT hr;
  839. AssertValid();
  840. // Assume none
  841. if (ppti)
  842. *ppti = NULL;
  843. if (ppiunkItem)
  844. *ppiunkItem = NULL;
  845. CHitObj *pHitObj = m_pHitObj;
  846. if (pHitObj == NULL)
  847. {
  848. // could happen when debugging and re-initializing
  849. // the scripting engine when storing it in the template
  850. // in this case GetItemInfo() is called for TYPELIB stuff
  851. ViperGetHitObjFromContext(&pHitObj);
  852. if (pHitObj == NULL)
  853. return TYPE_E_ELEMENTNOTFOUND;
  854. }
  855. // Calculate name length once
  856. DWORD cbName = CbWStr((LPWSTR)pcszName);
  857. // Special case for intrinsics
  858. IUnknown *punkIntrinsic = NULL;
  859. hr = pHitObj->GetIntrinsic((LPWSTR)pcszName, cbName, &punkIntrinsic);
  860. if (hr == S_OK)
  861. {
  862. if (dwReturnMask & SCRIPTINFO_IUNKNOWN)
  863. {
  864. Assert(ppiunkItem);
  865. Assert(punkIntrinsic);
  866. punkIntrinsic->AddRef();
  867. *ppiunkItem = punkIntrinsic;
  868. }
  869. return S_OK;
  870. }
  871. else if (hr == S_FALSE)
  872. {
  873. // Missing intrinsic case
  874. return TYPE_E_ELEMENTNOTFOUND;
  875. }
  876. // It's not an intrinsic -- try component collection
  877. CComponentObject *pObj = NULL;
  878. hr = pHitObj->GetComponent(csUnknown, (LPWSTR)pcszName, cbName, &pObj);
  879. if (hr == S_OK) // object found
  880. {
  881. if (dwReturnMask & SCRIPTINFO_IUNKNOWN)
  882. {
  883. Assert(ppiunkItem != NULL);
  884. hr = pObj->GetAddRefdIUnknown(ppiunkItem);
  885. }
  886. if (SUCCEEDED(hr))
  887. return S_OK;
  888. }
  889. // Could'n find -- output an error
  890. HandleItemNotFound(pcszName);
  891. return hr;
  892. }
  893. /*===================================================================
  894. CActiveScriptEngine::HandleItemNotFound
  895. Error handling due to item not found in GetItemInfo().
  896. Parameters:
  897. pcszName name of the item not found
  898. Returns:
  899. ===================================================================*/
  900. void CActiveScriptEngine::HandleItemNotFound
  901. (
  902. LPCOLESTR pcszName
  903. )
  904. {
  905. HRESULT hr = TYPE_E_ELEMENTNOTFOUND;
  906. CHAR *szErrT = NULL;
  907. CHAR szEngineT[255];
  908. CHAR szErr[255];
  909. TCHAR *szFileNameT = NULL;
  910. CHAR *szFileName = NULL;
  911. CHAR *szLineNum = NULL;
  912. CHAR *szEngine = NULL;
  913. CHAR *szErrCode = NULL;
  914. CHAR *szLongDes = NULL;
  915. ULONG ulLineError = 0;
  916. DWORD dwMask = 0x3;
  917. BOOLB fGuessedLine = FALSE;
  918. UINT ErrId = IDE_OOM;
  919. CWCharToMBCS convName;
  920. m_pTemplate->GetScriptSourceInfo(m_dwSourceContext, ulLineError, &szFileNameT, NULL, &ulLineError, NULL, &fGuessedLine);
  921. //Make a copy for error handling
  922. #if UNICODE
  923. szFileName = StringDupUTF8(szFileNameT);
  924. #else
  925. szFileName = StringDupA(szFileNameT);
  926. #endif
  927. //get line num
  928. if (ulLineError)
  929. {
  930. szLineNum = (CHAR *)malloc(sizeof(CHAR)*10);
  931. if (szLineNum)
  932. _ltoa(ulLineError, szLineNum, 10);
  933. else
  934. {
  935. hr = E_OUTOFMEMORY;
  936. goto lCleanUp;
  937. }
  938. }
  939. //get engine
  940. CchLoadStringOfId(IDS_ENGINE, szEngineT, 255);
  941. szEngine = StringDupA(szEngineT);
  942. //get informative string
  943. if (FAILED(hr = convName.Init((LPWSTR)pcszName))) {
  944. goto lCleanUp;
  945. }
  946. // Error string is: "Failed to create object 'objname'. Error code (code)."
  947. ErrId = IDE_SCRIPT_CANT_LOAD_OBJ;
  948. LoadErrResString(ErrId, &dwMask, NULL, NULL, szErr);
  949. if (szErr)
  950. {
  951. INT cch = strlen(szErr);
  952. szErrT = (CHAR *)malloc((CHAR)(cch + strlen(convName.GetString()) + 1));
  953. if (!szErrT)
  954. {
  955. hr = E_OUTOFMEMORY;
  956. goto lCleanUp;
  957. }
  958. sprintf(szErrT, szErr, convName.GetString());
  959. szErrCode = SzScodeToErrorCode(hr);
  960. }
  961. lCleanUp:
  962. //szErrT is the long description
  963. HandleError(ErrId, szFileName, szLineNum, szEngine, szErrCode, szErrT, NULL, m_pHitObj);
  964. }
  965. /*===================================================================
  966. CActiveScriptEngine::GetDocVersionString
  967. Return a string uniquely identifying the current document version
  968. from Denali's point of view.
  969. I dont think we need this. It is mostly interesting if
  970. the scripting engine is persisting scripts so that it can decide
  971. if a script needs a recompile. Since the scripting engine is
  972. not persisting anything for us, we dont need to do anything here.
  973. Returns:
  974. HRESULT. Always returns E_NOTIMPL.
  975. Side effects:
  976. None.
  977. ===================================================================*/
  978. STDMETHODIMP CActiveScriptEngine::GetDocVersionString
  979. (
  980. BSTR *pbstrVersion
  981. )
  982. {
  983. return(E_NOTIMPL);
  984. }
  985. /*===================================================================
  986. CActiveScriptEngine::RequestItems
  987. If this is called, it means that the Script engine wants us to call
  988. IActiveScript::AddNameItem() for each named item associated with the
  989. script.
  990. Returns:
  991. HRESULT. Always returns S_OK.
  992. Side effects:
  993. None.
  994. ===================================================================*/
  995. STDMETHODIMP CActiveScriptEngine::RequestItems
  996. (
  997. BOOL fPersistNames // = TRUE
  998. )
  999. {
  1000. static const char *_pFuncName = "CActiveScriptEngine::RequestItems()";
  1001. HRESULT hr = S_OK;
  1002. AssertValid();
  1003. Assert (m_pHitObj != NULL);
  1004. DWORD grf = SCRIPTITEM_ISVISIBLE;
  1005. if (fPersistNames)
  1006. grf |= SCRIPTITEM_ISPERSISTENT;
  1007. /*
  1008. * Intrinsics
  1009. */
  1010. START_TRYCATCH
  1011. if (m_pHitObj->FIsBrowserRequest())
  1012. {
  1013. hr = m_pAS->AddNamedItem(WSZ_OBJ_RESPONSE, grf);
  1014. Assert(SUCCEEDED(hr));
  1015. hr = m_pAS->AddNamedItem(WSZ_OBJ_REQUEST, grf);
  1016. Assert(SUCCEEDED(hr));
  1017. }
  1018. hr = m_pAS->AddNamedItem(WSZ_OBJ_SERVER, grf);
  1019. Assert(SUCCEEDED(hr));
  1020. if (m_pHitObj->FHasSession())
  1021. {
  1022. hr = m_pAS->AddNamedItem(WSZ_OBJ_SESSION, grf);
  1023. Assert(SUCCEEDED(hr));
  1024. }
  1025. hr = m_pAS->AddNamedItem(WSZ_OBJ_APPLICATION, grf);
  1026. Assert(SUCCEEDED(hr));
  1027. hr = m_pAS->AddNamedItem(WSZ_OBJ_OBJECTCONTEXT, grf);
  1028. Assert(SUCCEEDED(hr));
  1029. /*
  1030. * Components from different collections
  1031. */
  1032. CComponentIterator CompIter(m_pHitObj);
  1033. LPWSTR strObjName;
  1034. while (strObjName = CompIter.WStrNextComponentName())
  1035. {
  1036. hr = m_pAS->AddNamedItem(strObjName, grf);
  1037. if (FAILED(hr))
  1038. break;
  1039. }
  1040. Assert(SUCCEEDED(hr));
  1041. /*
  1042. * Type library wrappers. (Has to be last in order to be called
  1043. * only when everything else fails.
  1044. */
  1045. // Special flag value for typelib wrappers
  1046. grf |= SCRIPTITEM_GLOBALMEMBERS;
  1047. if (m_pHitObj->PTypeLibWrapper())
  1048. {
  1049. hr = m_pAS->AddNamedItem(WSZ_OBJ_ASPPAGETLB, grf);
  1050. Assert(SUCCEEDED(hr));
  1051. }
  1052. // GLOBAL.ASA typelib wrapper is added always
  1053. // because each page does not pick up changes to
  1054. // GLOBAL.ASA and there's no way to figure out
  1055. // when TYPELIBs get added to GLOBAL.ASA
  1056. hr = m_pAS->AddNamedItem(WSZ_OBJ_ASPGLOBALTLB, grf);
  1057. Assert(SUCCEEDED(hr));
  1058. END_TRYCATCH(hr, m_pHitObj, "IActiveScript::AddNamedItem");
  1059. // We are required to return OK
  1060. return(S_OK);
  1061. }
  1062. /*===================================================================
  1063. CActiveScriptEngine::RequestTypeLibs
  1064. If this is called, it means that the Script engine wants us to call
  1065. IActiveScript::AddTypeLib() for each typelib associated with the
  1066. script. It is unclear to me that this will ever be called in our case.
  1067. Returns:
  1068. HRESULT. Always returns S_OK.
  1069. Side effects:
  1070. None.
  1071. ===================================================================*/
  1072. STDMETHODIMP CActiveScriptEngine::RequestTypeLibs()
  1073. {
  1074. AssertValid();
  1075. // We have no typelibs for the namespace
  1076. return(S_OK);
  1077. }
  1078. /*===================================================================
  1079. CActiveScriptEngine::OnEnterScript
  1080. Host callback to indicate that the script has started executing
  1081. Returns:
  1082. HRESULT. Always returns S_OK.
  1083. Side effects:
  1084. None.
  1085. ===================================================================*/
  1086. STDMETHODIMP CActiveScriptEngine::OnEnterScript()
  1087. {
  1088. return(S_OK);
  1089. }
  1090. /*===================================================================
  1091. CActiveScriptEngine::OnLeaveScript
  1092. Host callback to indicate that the script has stopped executing
  1093. Returns:
  1094. HRESULT. Always returns S_OK.
  1095. Side effects:
  1096. None.
  1097. ===================================================================*/
  1098. STDMETHODIMP CActiveScriptEngine::OnLeaveScript()
  1099. {
  1100. return(S_OK);
  1101. }
  1102. /*===================================================================
  1103. CActiveScriptEngine::GetHostInfo
  1104. Host callback to for furnishing LCID and code page info
  1105. Returns:
  1106. HRESULT. Always returns S_OK.
  1107. Side effects:
  1108. None.
  1109. ===================================================================*/
  1110. STDMETHODIMP CActiveScriptEngine::GetHostInfo(hostinfo hostinfoRequest, void **ppvInfo)
  1111. {
  1112. Assert(hostinfoRequest == hostinfoLocale || hostinfoRequest == hostinfoCodePage);
  1113. HRESULT hr = S_OK;
  1114. if (hostinfoRequest == hostinfoLocale)
  1115. {
  1116. // Allocate an LCID and set it to the current
  1117. // value for the HitObj
  1118. *ppvInfo = CoTaskMemAlloc(sizeof(UINT));
  1119. if (!*ppvInfo)
  1120. hr = E_OUTOFMEMORY;
  1121. else
  1122. (*(UINT *)*ppvInfo) = m_pHitObj->GetLCID();
  1123. }
  1124. else if (hostinfoRequest == hostinfoCodePage)
  1125. {
  1126. // Allocate an code page and set it to the current
  1127. // value for the HitObj
  1128. *ppvInfo = CoTaskMemAlloc(sizeof(UINT));
  1129. if (!*ppvInfo)
  1130. hr = E_OUTOFMEMORY;
  1131. else
  1132. (*(UINT *)*ppvInfo) = m_pHitObj->GetCodePage();
  1133. }
  1134. else
  1135. hr = E_FAIL;
  1136. return(hr);
  1137. }
  1138. /*===================================================================
  1139. CActiveScriptEngine::OnScriptTerminate
  1140. Host callback to indicate that the script has completed.
  1141. Returns:
  1142. HRESULT. Always returns S_OK.
  1143. Side effects:
  1144. None.
  1145. ===================================================================*/
  1146. STDMETHODIMP CActiveScriptEngine::OnScriptTerminate
  1147. (
  1148. const VARIANT *pvarResult,
  1149. const EXCEPINFO *pexcepinfo
  1150. )
  1151. {
  1152. return(S_OK);
  1153. }
  1154. /*===================================================================
  1155. CActiveScriptEngine::OnStateChange
  1156. Host callback to indicate that the script has changed state (e.g. from
  1157. Uninitialized to Loaded.)
  1158. Returns:
  1159. HRESULT. Always returns S_OK.
  1160. Side effects:
  1161. None.
  1162. ===================================================================*/
  1163. STDMETHODIMP CActiveScriptEngine::OnStateChange
  1164. (
  1165. SCRIPTSTATE ssScriptState
  1166. )
  1167. {
  1168. return(S_OK);
  1169. }
  1170. /*===================================================================
  1171. CActiveScriptEngine::OnScriptError
  1172. Host callback to indicate that an error has occured in the script.
  1173. We should handle the error. We will return E_FAIL to indicate that we
  1174. want the script to terminate.
  1175. Returns:
  1176. HRESULT. E_FAIL -- Terminate executing the script.
  1177. Side effects:
  1178. None.
  1179. ===================================================================*/
  1180. STDMETHODIMP CActiveScriptEngine::OnScriptError
  1181. (
  1182. IActiveScriptError __RPC_FAR *pscripterror
  1183. )
  1184. {
  1185. Assert(pscripterror);
  1186. AssertValid();
  1187. // Bug 153: If we terminate the script due to Response.End, dont show an error
  1188. // NOTE: ActiveXScripting was failing to pass us our excepinfo. Use member flags
  1189. // ALSO: ActiveXScripting has fixed the problem of failing to pass us our excepinfo, but the
  1190. // way we are doing this with flags works just fine.
  1191. if (m_fScriptAborted)
  1192. {
  1193. goto LRet;
  1194. }
  1195. if (m_fScriptTimedOut)
  1196. {
  1197. //Load Default Engine from resource
  1198. char szEngine[128];
  1199. DWORD cch;
  1200. cch = CchLoadStringOfId(IDS_ENGINE, szEngine, 128);
  1201. szEngine[cch] = '\0';
  1202. CHAR *szFileName;
  1203. #if UNICODE
  1204. szFileName = StringDupUTF8(m_pHitObj->PSzCurrTemplateVirtPath());
  1205. #else
  1206. szFileName = StringDupA(m_pHitObj->PSzCurrTemplateVirtPath());
  1207. #endif
  1208. HandleError(IDE_SCRIPT_TIMEOUT,
  1209. szFileName,
  1210. NULL,
  1211. StringDupA(szEngine),
  1212. NULL,
  1213. NULL,
  1214. NULL,
  1215. m_pHitObj,
  1216. NULL);
  1217. if(m_pHitObj)
  1218. {
  1219. m_pHitObj->SetExecStatus(eExecTimedOut);
  1220. }
  1221. goto LRet;
  1222. }
  1223. // OnScriptErrorDebug calls OnScriptError. use this test to be sure we don't log error
  1224. // twice if we are called twice. (won't happen with present debugging implementation,
  1225. // but externals may change.)
  1226. if (m_fScriptHadError)
  1227. {
  1228. goto LRet;
  1229. }
  1230. m_fScriptHadError = TRUE; // Note that the script had an error so we can abort transactions (if any)
  1231. if (pscripterror)
  1232. {
  1233. // If there was an error in the script, first see if we should pop up the debugger
  1234. // (ONLY bring up Script Debugger; VID will do the right thing on its own)
  1235. //
  1236. // NEW CHANGE: always bring error description to browser, since VID does not
  1237. // give sufficient description.
  1238. //
  1239. if (FCaesars() && m_pHitObj->PAppln()->FDebuggable())
  1240. DebugError(pscripterror, m_pTemplate, m_dwSourceContext, g_pDebugApp);
  1241. HandleError(pscripterror, m_pTemplate, m_dwSourceContext, NULL, m_pHitObj);
  1242. }
  1243. LRet:
  1244. // Bug 99718 return S_OK to tell the script engine that we handled the error ok.
  1245. // Returning E_FAIL would not stop the scripting engine, this was a doc error.
  1246. return(S_OK);
  1247. }
  1248. /*
  1249. *
  1250. *
  1251. *
  1252. * I A c t i v e S c r i p t S i t e D e b u g M e t h o d s
  1253. *
  1254. *
  1255. *
  1256. *
  1257. */
  1258. /*===================================================================
  1259. CActiveScriptEngine::OnScriptErrorDebug
  1260. Callback for debugger to query host on what to do on exception.
  1261. NOTE: Theoretically, we would set *pfCallOnScriptErrorWhenContinuing
  1262. to TRUE and not call OnScriptError, and set *pfEnterDebugger
  1263. to TRUE or FALSE based on whether debugging is enabled and
  1264. whether user wants to debug.
  1265. However, in practice, *pfCallOnScriptErrorWhenContinuing is
  1266. not honored (OnScriptError is NOT called in any case), and
  1267. the VID team wants us to pretend like we don't implement
  1268. this interface. However, we always need our "OnScriptError"
  1269. code to execute, so we call our OnScriptError function
  1270. explicitly, then fail
  1271. Returns:
  1272. HRESULT. always returns E_NOTIMPL
  1273. Side effects:
  1274. calls OnScriptError
  1275. ===================================================================*/
  1276. STDMETHODIMP CActiveScriptEngine::OnScriptErrorDebug
  1277. (
  1278. IActiveScriptErrorDebug *pscripterror,
  1279. BOOL *pfEnterDebugger,
  1280. BOOL *pfCallOnScriptErrorWhenContinuing
  1281. )
  1282. {
  1283. OnScriptError(pscripterror);
  1284. return E_NOTIMPL;
  1285. }
  1286. /*===================================================================
  1287. CActiveScriptEngine::GetDocumentContextFromPosition
  1288. Create a document context (file + offset + length) from an offset in the
  1289. script.
  1290. Returns:
  1291. HRESULT. S_OK on success.
  1292. ===================================================================*/
  1293. HRESULT CActiveScriptEngine::GetDocumentContextFromPosition
  1294. (
  1295. /* [in] */ DWORD_PTR dwSourceContext,
  1296. /* [in] */ ULONG cchTargetOffset,
  1297. /* [in] */ ULONG cchText,
  1298. /* [out] */ IDebugDocumentContext **ppDocumentContext)
  1299. {
  1300. static const char *_pFuncName = "CActiveScriptEngine::GetDocumentContextFromPosition()";
  1301. TCHAR *szSourceFile;
  1302. ULONG cchSourceOffset;
  1303. ULONG cchSourceText;
  1304. IActiveScriptDebug *pASD;
  1305. // Convert offset in script engine to source location, and get debugging interfaces
  1306. m_pTemplate->GetSourceOffset(m_dwSourceContext, cchTargetOffset, &szSourceFile, &cchSourceOffset, &cchSourceText);
  1307. HRESULT hr;
  1308. TRYCATCH_HR(m_pAS->QueryInterface(IID_IActiveScriptDebug, reinterpret_cast<void **>(&pASD)),
  1309. hr,
  1310. "IActiveScript::QueryInterface()");
  1311. if (FAILED(hr))
  1312. return(E_FAIL);
  1313. // If this is in the main file, create a document context based on the CTemplate compiled source
  1314. if (_tcscmp(szSourceFile, m_pTemplate->GetSourceFileName()) == 0)
  1315. {
  1316. if (
  1317. (*ppDocumentContext = new CTemplateDocumentContext(m_pTemplate, cchSourceOffset, cchSourceText, pASD, m_dwSourceContext, cchTargetOffset))
  1318. == NULL
  1319. )
  1320. {
  1321. pASD->Release();
  1322. return E_OUTOFMEMORY;
  1323. }
  1324. }
  1325. // source refers to an include file, so create a documet context based on cached CIncFile dependency graph
  1326. else
  1327. {
  1328. CIncFile *pIncFile;
  1329. if (FAILED(g_IncFileMap.GetIncFile(szSourceFile, &pIncFile)))
  1330. return E_FAIL;
  1331. if (
  1332. (*ppDocumentContext = new CIncFileDocumentContext(pIncFile, cchSourceOffset, cchSourceText))
  1333. == NULL
  1334. )
  1335. {
  1336. TRYCATCH(pASD->Release(),"IActiveScriptDebug::Release()");
  1337. pIncFile->Release();
  1338. return E_OUTOFMEMORY;
  1339. }
  1340. pIncFile->Release();
  1341. }
  1342. TRYCATCH(pASD->Release(),"IActiveScriptDebug::Release()");
  1343. m_fBeingDebugged = TRUE;
  1344. return S_OK;
  1345. }
  1346. /*===================================================================
  1347. CActiveScriptEngine::GetApplication
  1348. Return a pointer to the application that the script resides in.
  1349. Returns:
  1350. HRESULT. Always succeeds.
  1351. ===================================================================*/
  1352. HRESULT CActiveScriptEngine::GetApplication
  1353. (
  1354. /* [out] */ IDebugApplication **ppDebugApp
  1355. )
  1356. {
  1357. Assert (m_pTemplate != NULL);
  1358. if (m_pTemplate->FDebuggable())
  1359. {
  1360. Assert (g_pDebugApp);
  1361. *ppDebugApp = g_pDebugApp;
  1362. (*ppDebugApp)->AddRef();
  1363. return S_OK;
  1364. }
  1365. else
  1366. {
  1367. *ppDebugApp = NULL;
  1368. return E_FAIL;
  1369. }
  1370. }
  1371. /*===================================================================
  1372. CActiveScriptEngine::GetRootApplicationNode
  1373. Return a pointer to the top level node (for browsing)
  1374. Returns:
  1375. HRESULT. Always succeeds.
  1376. ===================================================================*/
  1377. HRESULT CActiveScriptEngine::GetRootApplicationNode
  1378. (
  1379. /* [out] */ IDebugApplicationNode **ppRootNode
  1380. )
  1381. {
  1382. Assert (m_pTemplate != NULL);
  1383. if (m_pTemplate->FDebuggable())
  1384. {
  1385. Assert (g_pDebugAppRoot);
  1386. *ppRootNode = g_pDebugAppRoot;
  1387. (*ppRootNode)->AddRef();
  1388. return S_OK;
  1389. }
  1390. else
  1391. {
  1392. *ppRootNode = NULL;
  1393. return E_FAIL;
  1394. }
  1395. }
  1396. /*
  1397. *
  1398. *
  1399. *
  1400. * C S c r i p t E n g i n e M e t h o d s
  1401. *
  1402. *
  1403. *
  1404. *
  1405. */
  1406. /*===================================================================
  1407. CActiveScriptEngine::AddScriptlet
  1408. Add a piece of code to the script engine.
  1409. Returns:
  1410. HRESULT. S_OK on success.
  1411. Side effects:
  1412. Adds script code to the engine. Potentially allocates memory.
  1413. ===================================================================*/
  1414. HRESULT CActiveScriptEngine::AddScriptlet
  1415. (
  1416. LPCOLESTR wstrScript // scriptlet text
  1417. )
  1418. {
  1419. static const char *_pFuncName = "CActiveScriptEngine::AddScriptlet()";
  1420. HRESULT hr;
  1421. EXCEPINFO excepinfo;
  1422. AssertValid();
  1423. // Tell ActiveScripting to add the script to the engine
  1424. TRYCATCH_HR(m_pASP->ParseScriptText(
  1425. wstrScript, // the scriptlet text
  1426. NULL, // pstrItemName
  1427. NULL, // punkContext
  1428. L"</SCRIPT>", // End Delimiter -- Engine will never see this, but does tell it to strip comments.
  1429. m_dwSourceContext, // dwSourceContextCookie
  1430. 1, // ulStartingLineNumber
  1431. SCRIPTTEXT_ISPERSISTENT | SCRIPTTEXT_HOSTMANAGESSOURCE,
  1432. NULL, // pvarResult
  1433. &excepinfo), // exception info filled in on error
  1434. hr,
  1435. "IActiveScriptParse::ParseScriptText()");
  1436. if (SUCCEEDED(hr))
  1437. m_fScriptLoaded = TRUE;
  1438. return(hr);
  1439. }
  1440. /*===================================================================
  1441. CActiveScriptEngine::AddObjects
  1442. Add named objects to the script name space
  1443. Returns:
  1444. HRESULT. Always returns S_OK.
  1445. Side effects:
  1446. None.
  1447. ===================================================================*/
  1448. HRESULT CActiveScriptEngine::AddObjects
  1449. (
  1450. BOOL fPersistNames // = TRUE
  1451. )
  1452. {
  1453. HRESULT hr = S_OK;
  1454. AssertValid();
  1455. // There must be a hit object set
  1456. Assert(m_pHitObj != NULL);
  1457. // Leverage RequestItems to give AS all the names
  1458. hr = RequestItems(fPersistNames);
  1459. if (SUCCEEDED(hr))
  1460. m_fObjectsLoaded = TRUE;
  1461. return(hr);
  1462. }
  1463. /*===================================================================
  1464. CActiveScriptEngine::AddAdditionalObject
  1465. Add additional named objects to the script name space beyond the
  1466. names already added with AddObject. Note: the caller MUST have
  1467. added then names to the HitObj before making this call
  1468. Returns:
  1469. HRESULT. S_OK on success
  1470. Side effects:
  1471. None.
  1472. ===================================================================*/
  1473. HRESULT CActiveScriptEngine::AddAdditionalObject
  1474. (
  1475. LPWSTR strObjName,
  1476. BOOL fPersistNames // = TRUE
  1477. )
  1478. {
  1479. static const char *_pFuncName = "CActiveScriptEngine::AddAdditionalObject()";
  1480. HRESULT hr = S_OK;
  1481. DWORD grf;
  1482. AssertValid();
  1483. // There must be a hit object set
  1484. Assert(m_pHitObj != NULL);
  1485. // CONSIDER: It would be nice in debug code to walk the hitobj objlist and make sure
  1486. // that the given name is in there
  1487. /*
  1488. * Give AS the names
  1489. */
  1490. grf = SCRIPTITEM_ISVISIBLE;
  1491. if (fPersistNames)
  1492. grf |= SCRIPTITEM_ISPERSISTENT;
  1493. TRYCATCH_HR(m_pAS->AddNamedItem(strObjName, grf), hr, "IActiveScript::AddNamedItem()");
  1494. Assert(SUCCEEDED(hr)); // Should never fail!
  1495. return(hr);
  1496. }
  1497. /*===================================================================
  1498. CActiveScriptEngine::AddScriptingNamespace
  1499. Add the given scripting namespace object to the engine.
  1500. Note that it is added as GLOBALMEMBERS, and Not as ISPERSISTENT
  1501. Returns:
  1502. HRESULT. S_OK on success
  1503. Side effects:
  1504. None.
  1505. ===================================================================*/
  1506. HRESULT CActiveScriptEngine::AddScriptingNamespace
  1507. (
  1508. )
  1509. {
  1510. static const char *_pFuncName = "CActiveScriptEngine::AddScriptingNamespace()";
  1511. HRESULT hr = S_OK;
  1512. AssertValid();
  1513. Assert(m_pHitObj != NULL);
  1514. /*
  1515. * Give AXS the name and mark it GLOBALMEMBERS so all members are top level names
  1516. * in the namespace
  1517. */
  1518. TRYCATCH_HR(m_pAS->AddNamedItem(WSZ_OBJ_SCRIPTINGNAMESPACE, SCRIPTITEM_ISVISIBLE | SCRIPTITEM_GLOBALMEMBERS),
  1519. hr,
  1520. "IActiveScript::AddNamedItem()");
  1521. Assert(SUCCEEDED(hr)); // Should never fail!
  1522. return(hr);
  1523. }
  1524. /*===================================================================
  1525. CActiveScriptEngine::CheckEntryPoint
  1526. Determines if the specific named entry point exists in the given script.
  1527. Returns:
  1528. S_OK if found
  1529. DISP_E_UNKNOWNNAME if not found
  1530. Other OLE errors may be returned
  1531. Side effects:
  1532. None
  1533. ===================================================================*/
  1534. HRESULT CActiveScriptEngine::CheckEntryPoint
  1535. (
  1536. LPCOLESTR strEntryPoint // The name of the sub/fn to look for
  1537. )
  1538. {
  1539. static const char *_pFuncName = "CActiveScriptEngine::CheckEntryPoint()";
  1540. HRESULT hr;
  1541. DISPID dispid;
  1542. AssertValid();
  1543. if (strEntryPoint == NULL)
  1544. {
  1545. Assert(FALSE);
  1546. hr = DISP_E_UNKNOWNNAME;
  1547. }
  1548. else
  1549. {
  1550. // Get the DISPID of the method to call
  1551. TRYCATCH_HR(m_pDisp->GetIDsOfNames(IID_NULL, // REFIID - Reserved, must be NULL
  1552. (LPOLESTR *)&strEntryPoint, // Array of names to look up
  1553. 1, // Number of names in array
  1554. m_lcid, // Locale id
  1555. &dispid), // returned dispid
  1556. hr,
  1557. "IScriptDispatch::GetIDsOfNames()");
  1558. // Only error we expect is DISP_E_UNKNOWNNAME (or DISP_E_MEMBERNOTFOUND)
  1559. Assert(hr == S_OK || hr == DISP_E_UNKNOWNNAME || hr == DISP_E_MEMBERNOTFOUND);
  1560. }
  1561. return(hr);
  1562. }
  1563. /*===================================================================
  1564. CActiveScriptEngine::Call
  1565. Runs the specified function.
  1566. If a specific named entry point is provided (e.g. Session_OnStart)
  1567. then we will call that by name. Otherwise (e.g. a "main" script),
  1568. pass NULL for the name and we will run just the mainline code.
  1569. Calls TryCall (optionally from under TRY CATCH) to do the job
  1570. Returns:
  1571. HRESULT. S_OK on success.
  1572. Side effects:
  1573. May have various side effects depending on the script run
  1574. ===================================================================*/
  1575. HRESULT CActiveScriptEngine::Call
  1576. (
  1577. LPCOLESTR strEntryPoint // The name of the sub/fn to call (may be NULL for "main")
  1578. )
  1579. {
  1580. HRESULT hr;
  1581. AssertValid();
  1582. if (Glob(fExceptionCatchEnable)) {
  1583. // Catch any GPFs in VBS, OleAut, or external components
  1584. TRY
  1585. hr = TryCall(strEntryPoint);
  1586. CATCH(nExcept)
  1587. /*
  1588. * Catching a GPF or stack overflow
  1589. * Report it to the user, Assert (if debug), and exit with E_UNEXPECTED.
  1590. */
  1591. if (STATUS_STACK_OVERFLOW == nExcept) {
  1592. HandleErrorMissingFilename(IDE_STACK_OVERFLOW, m_pHitObj);
  1593. #if UNICODE
  1594. DBGPRINTF((DBG_CONTEXT, "Invoking the script '%S' overflowed the stack", m_szTemplateName));
  1595. #else
  1596. DBGPRINTF((DBG_CONTEXT, "Invoking the script '%s' overflowed the stack", m_szTemplateName));
  1597. #endif
  1598. }
  1599. else {
  1600. HandleErrorMissingFilename(IDE_SCRIPT_GPF, m_pHitObj, TRUE, nExcept);
  1601. #if UNICODE
  1602. DBGPRINTF((DBG_CONTEXT, "Invoking the script '%S' threw an exception (%x).", m_szTemplateName, nExcept));
  1603. #else
  1604. DBGPRINTF((DBG_CONTEXT, "Invoking the script '%s' threw an exception (%x).", m_szTemplateName, nExcept));
  1605. #endif
  1606. }
  1607. // Dont reuse the engine
  1608. m_fCorrupted = TRUE;
  1609. hr = E_UNEXPECTED;
  1610. END_TRY
  1611. }
  1612. else {
  1613. // Don't catch exceptions
  1614. hr = TryCall(strEntryPoint);
  1615. }
  1616. return(hr);
  1617. }
  1618. /*===================================================================
  1619. CActiveScriptEngine::TryCall
  1620. Runs the specified function.
  1621. If a specific named entry point is provided (e.g. Session_OnStart)
  1622. then we will call that by name. Otherwise (e.g. a "main" script),
  1623. pass NULL for the name and we will run just the mainline code.
  1624. Called from Call (optionally from under TRY CATCH)
  1625. Returns:
  1626. HRESULT. S_OK on success.
  1627. Side effects:
  1628. May have various side effects depending on the script run
  1629. ===================================================================*/
  1630. HRESULT CActiveScriptEngine::TryCall
  1631. (
  1632. LPCOLESTR strEntryPoint // The name of the sub/fn to call (may be NULL for "main")
  1633. )
  1634. {
  1635. HRESULT hr;
  1636. DISPID dispid;
  1637. DISPPARAMS dispparams;
  1638. UINT nArgErr;
  1639. /*
  1640. * Before calling any code we will transition the script to "STARTED" state.
  1641. * This is part of the ActiveXScripting Reset work.
  1642. */
  1643. hr = m_pAS->SetScriptState(SCRIPTSTATE_STARTED);
  1644. if (FAILED(hr))
  1645. {
  1646. Assert(FALSE);
  1647. goto LRet;
  1648. }
  1649. if (strEntryPoint != NULL)
  1650. {
  1651. // Get the DISPID of the method to call
  1652. hr = m_pDisp->GetIDsOfNames(IID_NULL, // REFIID - Reserved, must be NULL
  1653. (LPOLESTR *)&strEntryPoint, // Array of names to look up
  1654. 1, // Number of names in array
  1655. m_lcid, // Locale id
  1656. &dispid); // returned dispid
  1657. if (FAILED(hr))
  1658. {
  1659. // Only error we expect is DISP_E_UNKNOWNNAME (or DISP_E_MEMBERNOTFOUND)
  1660. Assert(hr == DISP_E_UNKNOWNNAME || hr == DISP_E_MEMBERNOTFOUND);
  1661. goto LRet;
  1662. }
  1663. // There are no arguments
  1664. memset(&dispparams, 0, sizeof(dispparams));
  1665. // Invoke it
  1666. hr = m_pDisp->Invoke(dispid, // dispid to invoke
  1667. IID_NULL, // REFIID - Reserved, must be NULL
  1668. m_lcid, // Locale id
  1669. DISPATCH_METHOD, // Calling a method, not a property get/put
  1670. &dispparams, // pass arguments
  1671. NULL, // return value
  1672. NULL, // We aren't interested in the exception info
  1673. &nArgErr); // if there is a Type Mismatch, which argument was the problem
  1674. }
  1675. LRet:
  1676. return(hr);
  1677. }
  1678. /*
  1679. *
  1680. *
  1681. *
  1682. * C S c r i p t M a n a g e r
  1683. *
  1684. *
  1685. *
  1686. *
  1687. */
  1688. /*===================================================================
  1689. CScriptManager::CScriptManager
  1690. Constructor for CScriptManager object
  1691. Returns:
  1692. Nothing
  1693. Side effects:
  1694. None.
  1695. ===================================================================*/
  1696. CScriptManager::CScriptManager()
  1697. : m_fInited(FALSE), m_idScriptKiller(0)
  1698. {
  1699. }
  1700. /*===================================================================
  1701. CScriptManager::~CScriptManager
  1702. Destructor for CScriptManager object
  1703. Returns:
  1704. Nothing
  1705. Side effects:
  1706. None.
  1707. ===================================================================*/
  1708. CScriptManager::~CScriptManager()
  1709. {
  1710. }
  1711. /*===================================================================
  1712. CScriptManager::Init
  1713. Init the script manager. This must only be called once.
  1714. Returns:
  1715. HRESULT. S_OK on success.
  1716. Side effects:
  1717. None.
  1718. ===================================================================*/
  1719. HRESULT CScriptManager::Init
  1720. (
  1721. )
  1722. {
  1723. static const char *_pFuncName = "CScriptManager::Init()";
  1724. HRESULT hr;
  1725. BOOL fPLLInited = FALSE;
  1726. BOOL fcsPLLInited = FALSE;
  1727. BOOL fFSQInited = FALSE;
  1728. BOOL fcsFSQInited = FALSE;
  1729. BOOL fRSLInited = FALSE;
  1730. BOOL fcsRSLInited = FALSE;
  1731. DWORD cBuckets;
  1732. DWORD rgPrime[] = { 3, 11, 23, 57, 89 };
  1733. WORD iP;
  1734. IActiveScript *pAST = NULL;
  1735. static const GUID uid_VBScript = { 0xB54F3741, 0x5B07, 0x11cf, { 0xA4, 0xB0, 0x00, 0xAA, 0x00, 0x4A, 0x55, 0xE8}};
  1736. // Illegal to re-init
  1737. if (m_fInited)
  1738. {
  1739. Assert(FALSE);
  1740. return(ERROR_ALREADY_INITIALIZED);
  1741. }
  1742. // Create the critical sections for serializing access to lists
  1743. ErrInitCriticalSection(&m_cSPLL, hr);
  1744. if (FAILED(hr))
  1745. goto LError;
  1746. fcsPLLInited = TRUE;
  1747. ErrInitCriticalSection(&m_csFSQ, hr);
  1748. if (FAILED(hr))
  1749. goto LError;
  1750. fcsFSQInited = TRUE;
  1751. ErrInitCriticalSection(&m_csRSL, hr);
  1752. if (FAILED(hr))
  1753. goto LError;
  1754. fcsRSLInited = TRUE;
  1755. // List of programming language clsid's
  1756. hr = m_hTPLL.Init();
  1757. if (FAILED(hr))
  1758. goto LError;
  1759. fPLLInited = TRUE;
  1760. // Free Script Queue
  1761. // Init it with a prime # of buckets in relation to script engine cache max
  1762. cBuckets = (Glob(dwScriptEngineCacheMax) / 2) + 1;
  1763. for (iP = (sizeof(rgPrime) / sizeof(DWORD)) - 1; iP > 0; iP--)
  1764. if (rgPrime[iP] < cBuckets)
  1765. {
  1766. cBuckets = rgPrime[iP];
  1767. break;
  1768. }
  1769. if (cBuckets < rgPrime[1])
  1770. cBuckets = rgPrime[0];
  1771. hr = m_htFSQ.Init(cBuckets);
  1772. if (FAILED(hr))
  1773. goto LError;
  1774. fFSQInited = TRUE;
  1775. // Running Script List
  1776. // Init it with a prime # of buckets in relation to max # of threads
  1777. cBuckets = Glob(dwThreadMax) / 2;
  1778. for (iP = (sizeof(rgPrime) / sizeof(DWORD)) - 1; iP > 0; iP--)
  1779. if (rgPrime[iP] < cBuckets)
  1780. {
  1781. cBuckets = rgPrime[iP];
  1782. break;
  1783. }
  1784. if (cBuckets < rgPrime[1])
  1785. cBuckets = rgPrime[0];
  1786. hr = m_htRSL.Init(cBuckets);
  1787. if (FAILED(hr))
  1788. goto LError;
  1789. fRSLInited = TRUE;
  1790. // Schedule script killer
  1791. m_msecScriptKillerTimeout = Glob(dwScriptTimeout) * 500;
  1792. m_idScriptKiller = ScheduleWorkItem
  1793. (
  1794. CScriptManager::ScriptKillerSchedulerCallback, // callback
  1795. this, // context
  1796. m_msecScriptKillerTimeout, // timeout
  1797. TRUE // periodic
  1798. );
  1799. if (!m_idScriptKiller)
  1800. {
  1801. hr = E_FAIL;
  1802. goto LError;
  1803. }
  1804. // TypeLib support: Create a scripting engine and QI it for the TypeLib wrapper support
  1805. hr = CoCreateInstance(uid_VBScript, NULL, CLSCTX_INPROC_SERVER, IID_IActiveScript, (void**)&pAST);
  1806. if (FAILED(hr))
  1807. goto LError;
  1808. TRYCATCH_HR_NOHITOBJ(pAST->QueryInterface(IID_IWrapTypeLibs, (VOID **)&g_pWrapTypelibs),
  1809. hr,
  1810. "IActiveScript::QueryInterface()");
  1811. TRYCATCH_NOHITOBJ(pAST->Release(),"IActiveScript::Release()"); // No longer need the pointer to the engine
  1812. if (FAILED(hr))
  1813. goto LError;
  1814. // All OK. We are inited.
  1815. m_fInited = TRUE;
  1816. goto LExit;
  1817. LError:
  1818. if (m_idScriptKiller)
  1819. RemoveWorkItem(m_idScriptKiller);
  1820. if (fcsPLLInited)
  1821. DeleteCriticalSection(&m_cSPLL);
  1822. if (fcsFSQInited)
  1823. DeleteCriticalSection(&m_csFSQ);
  1824. if (fcsRSLInited)
  1825. DeleteCriticalSection(&m_csRSL);
  1826. if (fPLLInited)
  1827. m_hTPLL.UnInit();
  1828. if (fFSQInited)
  1829. m_htFSQ.UnInit();
  1830. if (fRSLInited)
  1831. m_htRSL.UnInit();
  1832. if (pAST)
  1833. TRYCATCH_NOHITOBJ(pAST->Release(),"IActiveScript::Release()");
  1834. if (g_pWrapTypelibs)
  1835. {
  1836. TRYCATCH_NOHITOBJ(g_pWrapTypelibs->Release(),"IWrapTypeLibs::Release()");
  1837. g_pWrapTypelibs = NULL;
  1838. }
  1839. LExit:
  1840. return(hr);
  1841. }
  1842. /*===================================================================
  1843. CScriptManager::UnInit
  1844. UnInit the script manager. This must only be called once.
  1845. Returns:
  1846. HRESULT. S_OK on success.
  1847. Side effects:
  1848. None.
  1849. ===================================================================*/
  1850. HRESULT CScriptManager::UnInit
  1851. (
  1852. )
  1853. {
  1854. static const char *_pFuncName = "CScriptManager::UnInit()";
  1855. HRESULT hr = S_OK, hrT;
  1856. if (m_fInited)
  1857. {
  1858. // Un-schedule script killer
  1859. if (m_idScriptKiller)
  1860. {
  1861. RemoveWorkItem(m_idScriptKiller);
  1862. m_idScriptKiller = 0;
  1863. }
  1864. // Uninit each of the lists. Attempt to uninit them all, even if we get an error.
  1865. // Dont lose any errors along the way.
  1866. hr = UnInitASEElems();
  1867. hrT = UnInitPLL();
  1868. if (SUCCEEDED(hr))
  1869. hr = hrT;
  1870. hrT = m_hTPLL.UnInit();
  1871. if (SUCCEEDED(hr))
  1872. hr = hrT;
  1873. hrT = m_htFSQ.UnInit();
  1874. if (SUCCEEDED(hr))
  1875. hr = hrT;
  1876. hrT = m_htRSL.UnInit();
  1877. if (SUCCEEDED(hr))
  1878. hr = hrT;
  1879. if (g_pWrapTypelibs)
  1880. {
  1881. TRYCATCH_NOHITOBJ(g_pWrapTypelibs->Release(),"IWrapTypeLibs::Release()");
  1882. g_pWrapTypelibs = NULL;
  1883. }
  1884. // Free the critical sections (bug 1140: do this after freeing everything else)
  1885. DeleteCriticalSection(&m_cSPLL);
  1886. DeleteCriticalSection(&m_csFSQ);
  1887. DeleteCriticalSection(&m_csRSL);
  1888. m_fInited = FALSE;
  1889. }
  1890. return(hr);
  1891. }
  1892. /*===================================================================
  1893. CScriptManager::AdjustScriptKillerTimeout
  1894. Adjust (shorten) script killer timeout when needed.
  1895. The caller should take care of the critical sectioning.
  1896. Parameters:
  1897. msecNewTimeout new suggested timeout value (in ms)
  1898. Returns:
  1899. HRESULT. S_OK on success.
  1900. ===================================================================*/
  1901. HRESULT CScriptManager::AdjustScriptKillerTimeout
  1902. (
  1903. DWORD msecNewTimeout
  1904. )
  1905. {
  1906. const DWORD MSEC_MIN_SCRIPT_TIMEOUT = 5000; // 5 seconds
  1907. if (!m_idScriptKiller)
  1908. return E_FAIL; // no script killer scheduled
  1909. // don't set to < minimum
  1910. if (msecNewTimeout < MSEC_MIN_SCRIPT_TIMEOUT)
  1911. msecNewTimeout = MSEC_MIN_SCRIPT_TIMEOUT;
  1912. if (m_msecScriptKillerTimeout <= msecNewTimeout)
  1913. return S_OK; // the timeout already short enough
  1914. if (ScheduleAdjustTime(
  1915. m_idScriptKiller,
  1916. msecNewTimeout) == S_OK)
  1917. {
  1918. m_msecScriptKillerTimeout = msecNewTimeout;
  1919. return S_OK;
  1920. }
  1921. else
  1922. {
  1923. return E_FAIL;
  1924. }
  1925. }
  1926. /*===================================================================
  1927. CScriptManager::GetEngine
  1928. Return an engine to the caller. Ideally, we will find an engine
  1929. that already has the given script in it in our Free Script Queue
  1930. and will just hand it out. If there isnt one, then we will look
  1931. in the Running Script List and attempt to clone a running script.
  1932. Failing that, we will create a new script
  1933. engine. We return an ENGINESTATE state indicating if the engine
  1934. is filled with script or not.
  1935. Returns:
  1936. HRESULT. S_OK on success.
  1937. Side effects:
  1938. Potentially allocates memory.
  1939. ===================================================================*/
  1940. HRESULT CScriptManager::GetEngine
  1941. (
  1942. LCID lcid, // The system language to use
  1943. PROGLANG_ID& progLangId, // prog lang id of the script
  1944. LPCTSTR szTemplateName, // Template we want an engine for
  1945. CHitObj *pHitObj, // Hit obj to use in this engine
  1946. CScriptEngine **ppSE, // Returned script engine
  1947. ENGINESTATE *pdwState, // Current state of the engine
  1948. CTemplate *pTemplate, // template which engine is based from
  1949. DWORD dwSourceContext // source context cookie (engine ID)
  1950. )
  1951. {
  1952. HRESULT hr = S_OK;
  1953. CActiveScriptEngine *pASE = NULL;
  1954. CASEElem *pASEElem = NULL;
  1955. DWORD dwInstanceID = pHitObj->DWInstanceID();
  1956. AssertValid();
  1957. /* NOTE progLangId must be valid because CTemplate::Compile()
  1958. fails way upstream of this point if it cannot generate a valid progLangId.
  1959. Unfortunately there is no easy way to assert progLangId is valid ...
  1960. */
  1961. /*
  1962. * First try to find the engine in the FSQ
  1963. *
  1964. * Note: We are going to enter our CS now, and keep it until we have
  1965. * secured the engine for ourselves. Otherwise, it might be possible
  1966. * for us to get an engine, and then have another thread get the
  1967. * same engine before we manage to get it off of the FSQ.
  1968. * This makes the code a little hard to read, but is nessecary.
  1969. */
  1970. EnterCriticalSection(&m_csFSQ);
  1971. #ifndef REUSE_ENGINE
  1972. // This will only find fully loaded engines
  1973. hr = FindEngineInList(szTemplateName, progLangId, dwInstanceID, /*fFSQ*/TRUE, &pASEElem);
  1974. #endif
  1975. if (FAILED(hr))
  1976. {
  1977. LeaveCriticalSection(&m_csFSQ);
  1978. goto LFail;
  1979. }
  1980. if (pASEElem == NULL || pASEElem->PASE() == NULL)
  1981. {
  1982. LeaveCriticalSection(&m_csFSQ);
  1983. }
  1984. else
  1985. {
  1986. // We got an engine we want to use, remove it from FSQ
  1987. (VOID)m_htFSQ.RemoveElem(pASEElem);
  1988. #ifndef PERF_DISABLE
  1989. g_PerfData.Decr_SCRIPTFREEENG();
  1990. #endif
  1991. LeaveCriticalSection(&m_csFSQ);
  1992. pASE = pASEElem->PASE();
  1993. Assert(!pASE->FIsZombie());
  1994. Assert(pASE->FFullyLoaded());
  1995. hr = pASE->ReuseEngine(pHitObj, pTemplate, dwSourceContext, dwInstanceID);
  1996. if (FAILED(hr))
  1997. goto LFail;
  1998. }
  1999. /*
  2000. * If not found, try to find the engine in the RSL and clone it
  2001. */
  2002. if (pASE == NULL)
  2003. {
  2004. CASEElem *pASEElemRunning = NULL;
  2005. CActiveScriptEngine *pASERunning = NULL;
  2006. // If we do find an engine to clone, dont let anyone at it until we've cloned it
  2007. EnterCriticalSection(&m_csRSL);
  2008. #ifndef CLONE
  2009. hr = FindEngineInList(szTemplateName, progLangId, dwInstanceID, /*fFSQ*/FALSE, &pASEElemRunning);
  2010. #else // CLONE
  2011. // Clone turned off - pretend one wasnt found
  2012. pASEElemRunning = NULL;
  2013. #endif
  2014. /*
  2015. * If we didnt find an element, or it was null, or (bug 1225) it was corrupted
  2016. * by a GPF running a script, or it was a zombie, then leave the CS and continue.
  2017. */
  2018. if (FAILED(hr) || pASEElemRunning == NULL || pASEElemRunning->PASE() == NULL ||
  2019. pASEElemRunning->PASE()->FIsCorrupted() || pASEElemRunning->PASE()->FIsZombie())
  2020. {
  2021. LeaveCriticalSection(&m_csRSL);
  2022. if (FAILED(hr))
  2023. goto LFail;
  2024. }
  2025. else
  2026. {
  2027. pASERunning = pASEElemRunning->PASE();
  2028. Assert(pASERunning != NULL);
  2029. }
  2030. if (pASERunning != NULL)
  2031. {
  2032. IActiveScript *pAS, *pASClone;
  2033. Assert(!pASERunning->FIsZombie());
  2034. Assert(pASERunning->FFullyLoaded());
  2035. // Found a running engine, clone it
  2036. pAS = pASERunning->GetActiveScript();
  2037. Assert(pAS != NULL);
  2038. hr = pAS->Clone(&pASClone);
  2039. // We've cloned the engine, we can let go of the CS
  2040. LeaveCriticalSection(&m_csRSL);
  2041. // Scripting engines are not required to implement clone. If we get an error,
  2042. // just continue on and create a new engine
  2043. if (FAILED(hr))
  2044. {
  2045. Assert(hr == E_NOTIMPL); // I only expect E_NOTIMPL
  2046. Assert(pASE == NULL); // the ASE should not be filled in
  2047. pASE = NULL;
  2048. hr = S_OK;
  2049. }
  2050. else
  2051. {
  2052. // Got back a cloned IActiveScript. Create a new ASE and fill it in
  2053. pASE = new CActiveScriptEngine;
  2054. if (!pASE)
  2055. {
  2056. hr = E_OUTOFMEMORY;
  2057. pASClone->Release();
  2058. goto LFail;
  2059. }
  2060. hr = pASE->MakeClone(progLangId, szTemplateName, lcid, pHitObj, pTemplate, dwSourceContext, dwInstanceID, pASClone);
  2061. if (FAILED(hr))
  2062. {
  2063. // if we failed, we must release the clone AS
  2064. pASClone->Release();
  2065. goto LFail;
  2066. }
  2067. }
  2068. }
  2069. }
  2070. /*
  2071. * Have an engine that we can reuse
  2072. */
  2073. if (pASE != NULL)
  2074. {
  2075. // Reusing an engine. Let the caller know that it is already initialized
  2076. *pdwState = SCRIPTSTATE_INITIALIZED;
  2077. goto LHaveEngine;
  2078. }
  2079. /*
  2080. * No suitable engine to reuse. Return a new one
  2081. */
  2082. pASE = new CActiveScriptEngine;
  2083. if (!pASE)
  2084. {
  2085. hr = E_OUTOFMEMORY;
  2086. goto LFail;
  2087. }
  2088. hr = pASE->Init(progLangId, szTemplateName, lcid, pHitObj, pTemplate, dwSourceContext);
  2089. if (FAILED(hr))
  2090. goto LFail;
  2091. // This is a new engine, let the caller know it is uninitialized
  2092. *pdwState = SCRIPTSTATE_UNINITIALIZED;
  2093. LHaveEngine:
  2094. // Return the engine as a CScriptEngine -- the caller only needs those interfaces
  2095. pASE->AssertValid(); // The engine we're about to give back should be valid
  2096. *ppSE = (CScriptEngine *)pASE;
  2097. // Put the engine on the Running Scrips List
  2098. // If we got this engine from the FSQ, reuse that elem.
  2099. if (pASEElem == NULL)
  2100. {
  2101. pASEElem = new CASEElem;
  2102. if (!pASEElem)
  2103. {
  2104. hr = E_OUTOFMEMORY;
  2105. goto LFail;
  2106. }
  2107. hr = pASEElem->Init(pASE);
  2108. if (FAILED(hr))
  2109. {
  2110. Assert(FALSE); // Shouldnt fail
  2111. delete pASEElem;
  2112. goto LFail;
  2113. }
  2114. }
  2115. /*
  2116. * Above, we may have gotten an engine from the FSQ or cloned on from the RSL or
  2117. * created a new one. And, we are about to put that engine on the RSL. However,
  2118. * it is possible that the template in question was flushed due to a change notification
  2119. * while this was going on. Regardless of how we got the engine, there is the possibility
  2120. * that the template was flushed while we were holding onto an engine which was not on
  2121. * any list (the FSQ or RSL), and so we have an engine which should be flushed but isnt.
  2122. * We can detect this by seeing if the template is marked as being a Zombie. If it is
  2123. * we must mark this engine as being a zombie too, so it wont be returned to the FSQ when
  2124. * it is done running. Note that once we add this engine to the RSL we are "safe", because
  2125. * any flushes after that point would correctly zombify the engine.
  2126. */
  2127. EnterCriticalSection(&m_csRSL);
  2128. if (pTemplate->FIsZombie())
  2129. {
  2130. // The template asking for this engine is obsolete. Make sure that no
  2131. // one else will use this engine by marking it zombie
  2132. DBGPRINTF((DBG_CONTEXT, "[CScriptManager] Zombie template found.\n"));
  2133. (*ppSE)->Zombify();
  2134. }
  2135. (VOID)m_htRSL.AddElem(pASEElem);
  2136. LeaveCriticalSection(&m_csRSL);
  2137. // Set the time that the engine was handed out so we will know when to kill it
  2138. pASE->SetTimeStarted(time(NULL));
  2139. LFail:
  2140. Assert(SUCCEEDED(hr) || hr == TYPE_E_ELEMENTNOTFOUND);
  2141. return(hr);
  2142. }
  2143. /*===================================================================
  2144. CScriptManager::ReturnEngineToCache
  2145. Caller is done with the engine. Return it to the cache.
  2146. Returns:
  2147. HRESULT. S_OK on success.
  2148. Side effects:
  2149. Potentially allocates memory.
  2150. ===================================================================*/
  2151. HRESULT CScriptManager::ReturnEngineToCache
  2152. (
  2153. CScriptEngine **ppSE,
  2154. CAppln *pAppln
  2155. )
  2156. {
  2157. HRESULT hr = S_OK;
  2158. CASEElem *pASEElem;
  2159. CActiveScriptEngine *pASE;
  2160. Assert(ppSE != NULL);
  2161. Assert(*ppSE != NULL);
  2162. pASE = static_cast<CActiveScriptEngine *>(*ppSE);
  2163. // Remove the engine from the Running Script List
  2164. EnterCriticalSection( &m_csRSL );
  2165. hr = FindASEElemInList(static_cast<CActiveScriptEngine *>(*ppSE), /*fFSQ*/FALSE, &pASEElem);
  2166. if (FAILED(hr)) {
  2167. LeaveCriticalSection( &m_csRSL );
  2168. goto LExit;
  2169. }
  2170. // Note: Sometimes a script will not be in the RSL! This occurs when
  2171. // we are reusing a script that is stored in the CTemplate object.
  2172. // (When the script is reloaded, it is retrieved directly from the
  2173. // template, bypassing our code which places engines on the RSL)
  2174. //
  2175. if (pASEElem != NULL)
  2176. m_htRSL.RemoveElem(pASEElem);
  2177. LeaveCriticalSection( &m_csRSL );
  2178. /*
  2179. * If the engine was zombified while it was running, deallocate it.
  2180. * Or, if there was a GPF while then engine was running, then it might
  2181. * be in a corrupted state (bug 1225). Also remove it in that case.
  2182. */
  2183. pASE = static_cast<CActiveScriptEngine *>(*ppSE);
  2184. if (pASE->FIsZombie() || pASE->FIsCorrupted()) {
  2185. delete pASEElem;
  2186. pASE->FinalRelease();
  2187. goto LExit;
  2188. }
  2189. HRESULT hrT;
  2190. /*
  2191. * We want to reuse this engine. Try to return it to the "Uninitialized"
  2192. * state. Some engine languages arent able to do this. If it fails, deallocate
  2193. * the engine; it cant be reused.
  2194. */
  2195. hrT = pASE->ResetToUninitialized();
  2196. if (FAILED(hrT)) {
  2197. // Engine doesnt support this, sigh. Deallocate and continue.
  2198. delete pASEElem;
  2199. pASE->FinalRelease();
  2200. goto LExit;
  2201. }
  2202. // Get the pTemplate for this engine
  2203. CTemplate *pTemplate;
  2204. DWORD dwEngine;
  2205. pASE->GetDebugDocument(&pTemplate, &dwEngine);
  2206. // CONSIDER: Better strategy for keeping live scripts?
  2207. // Only remember good (no compiler errors) scripts in the template
  2208. if (pAppln->FDebuggable() && pASE->FFullyLoaded() && pTemplate && !pTemplate->FDontAttach()) {
  2209. // Template is marked as incomplete (invalid) when change notification occurs
  2210. // and template is flushed from cache. In this case, don't cache in CTemplate
  2211. // object!
  2212. if (pTemplate->FIsValid())
  2213. pTemplate->AddScript(dwEngine, pASE);
  2214. // NOTE: Always release the scripting engine. Exec code is structured so that it
  2215. // consumes a reference (either through GetEngine() or CTemplate::GetActiveScript())
  2216. // and assumes that ReturnToCache will release its reference.
  2217. // CONSIDER: Bad design. Caller should do the release
  2218. delete pASEElem;
  2219. pASE->Release();
  2220. }
  2221. else {
  2222. // reuse engines, not debugging
  2223. /*
  2224. * We removed the engine from the RSL, put it onto the FSQ for potential reuse.
  2225. *
  2226. * In certain multi-threaded change-notify situations it is possible
  2227. * that the template was flushed (zombied) while we were in the middle
  2228. * of returning this engine to the cache. That is to say, between the time
  2229. * that we took the engine off the RSL and when we are going to put it on the FSQ
  2230. * it might have been flushed. In that case, this engine should
  2231. * not go into the FSQ, but should be deleted instead. Check for that case.
  2232. * Do that inside the FSQ CS so that we are safe from the template getting zombied
  2233. * after we do the test but before the engine goes into the FSQ. Also, do not
  2234. * put template on FSQ during shut down phase, since FSQ may go away soon, and
  2235. * the final destination of the engine is FinalRelease() anyway.
  2236. */
  2237. EnterCriticalSection(&m_csFSQ);
  2238. if (!pTemplate->FIsZombie() && !IsShutDownInProgress()) {
  2239. AddToFSQ(pASEElem);
  2240. }
  2241. else {
  2242. delete pASEElem;
  2243. pASE->FinalRelease();
  2244. }
  2245. LeaveCriticalSection(&m_csFSQ);
  2246. }
  2247. LExit:
  2248. return(hr);
  2249. }
  2250. /*===================================================================
  2251. CScriptManager::FlushCache
  2252. A script has been edited; cached versions must be discarded
  2253. Returns:
  2254. HRESULT. S_OK on success.
  2255. Side effects:
  2256. Potentially allocates memory.
  2257. ===================================================================*/
  2258. HRESULT CScriptManager::FlushCache
  2259. (
  2260. LPCTSTR szTemplateName
  2261. )
  2262. {
  2263. HRESULT hr = S_OK;
  2264. CASEElem *pASEElem;
  2265. CASEElem *pASEElemNext = NULL;
  2266. CActiveScriptEngine *pASE;
  2267. AssertValid();
  2268. EnterCriticalSection(&m_csRSL);
  2269. EnterCriticalSection(&m_csFSQ);
  2270. // First Zombify engines on the RSL of the given name.
  2271. // Note: must explicitly loop through all elements, since the hash table implementation
  2272. // doesnt support FindNext to find subsequent elements of the same name. Repeated
  2273. // calls to find returns the same element over and over
  2274. // CONSIDER: I have written a custom FindElem. Consider using it.
  2275. pASEElem = (CASEElem *)m_htRSL.Head();
  2276. while (pASEElem != NULL)
  2277. {
  2278. pASEElemNext = (CASEElem *)pASEElem->m_pNext;
  2279. pASE = pASEElem->PASE();
  2280. if (_tcsicmp(pASE->SzTemplateName(), szTemplateName) == 0)
  2281. pASE->Zombify();
  2282. pASEElem = pASEElemNext;
  2283. }
  2284. // Now throw out engines on the FSQ of the given name
  2285. // Delete any item with the given name (may be several)
  2286. pASEElem = (CASEElem *)m_htFSQ.Head();
  2287. while (pASEElem != NULL)
  2288. {
  2289. pASEElemNext = (CASEElem *)pASEElem->m_pNext;
  2290. pASE = pASEElem->PASE();
  2291. if (_tcsicmp(pASE->SzTemplateName(), szTemplateName) == 0)
  2292. {
  2293. (VOID)m_htFSQ.RemoveElem(pASEElem);
  2294. #ifndef PERF_DISABLE
  2295. g_PerfData.Decr_SCRIPTFREEENG();
  2296. #endif
  2297. pASE->FinalRelease();
  2298. delete pASEElem;
  2299. }
  2300. pASEElem = pASEElemNext;
  2301. }
  2302. LeaveCriticalSection(&m_csFSQ);
  2303. LeaveCriticalSection(&m_csRSL);
  2304. return(hr);
  2305. }
  2306. /*===================================================================
  2307. CScriptManager::FlushAll
  2308. global.asa changed, everything must go
  2309. Returns:
  2310. HRESULT. S_OK on success.
  2311. Side effects:
  2312. Potentially allocates memory.
  2313. ===================================================================*/
  2314. HRESULT CScriptManager::FlushAll
  2315. (
  2316. )
  2317. {
  2318. HRESULT hr = S_OK;
  2319. CASEElem *pASEElem;
  2320. CASEElem *pASEElemNext = NULL;
  2321. CActiveScriptEngine *pASE;
  2322. AssertValid();
  2323. EnterCriticalSection(&m_csRSL);
  2324. EnterCriticalSection(&m_csFSQ);
  2325. // First Zombify all engines on the RSL
  2326. // Note: must explicitly loop through all elements, since the hash table implementation
  2327. // doesnt support FindNext to find subsequent elements of the same name. Repeated
  2328. // calls to find returns the same element over and over
  2329. // CONSIDER: I have written a custom FindElem. Consider using it.
  2330. pASEElem = (CASEElem *)m_htRSL.Head();
  2331. while (pASEElem != NULL)
  2332. {
  2333. pASEElemNext = (CASEElem *)pASEElem->m_pNext;
  2334. pASEElem->PASE()->Zombify();
  2335. pASEElem = pASEElemNext;
  2336. }
  2337. // Now throw out engines on the FSQ
  2338. pASEElem = (CASEElem *)m_htFSQ.Head();
  2339. while (pASEElem != NULL)
  2340. {
  2341. pASEElemNext = (CASEElem *)pASEElem->m_pNext;
  2342. (VOID)m_htFSQ.RemoveElem(pASEElem);
  2343. #ifndef PERF_DISABLE
  2344. g_PerfData.Decr_SCRIPTFREEENG();
  2345. #endif
  2346. pASEElem->PASE()->FinalRelease();
  2347. delete pASEElem;
  2348. pASEElem = pASEElemNext;
  2349. }
  2350. LeaveCriticalSection(&m_csFSQ);
  2351. LeaveCriticalSection(&m_csRSL);
  2352. return(hr);
  2353. }
  2354. /*===================================================================
  2355. CScriptManager::GetDebugScript
  2356. Try to find an engine via template pointer, and query for IActiveScriptDebug,
  2357. in the RSL.
  2358. Returns:
  2359. An AddRef'ed copy of the script engine if found, or NULL if not.
  2360. ===================================================================*/
  2361. IActiveScriptDebug *
  2362. CScriptManager::GetDebugScript
  2363. (
  2364. CTemplate *pTemplate,
  2365. DWORD dwSourceContext
  2366. )
  2367. {
  2368. EnterCriticalSection(&m_csRSL);
  2369. CASEElem *pASEElem = static_cast<CASEElem *>(m_htRSL.Head());
  2370. while (pASEElem != NULL)
  2371. {
  2372. CTemplate *pScriptTemplate = NULL;
  2373. DWORD dwScriptSourceContext = -1;
  2374. CActiveScriptEngine *pASE = pASEElem->PASE();
  2375. pASE->GetDebugDocument(&pScriptTemplate, &dwScriptSourceContext);
  2376. if (pTemplate == pScriptTemplate && dwSourceContext == dwScriptSourceContext)
  2377. {
  2378. IActiveScript *pActiveScript = pASE->GetActiveScript();
  2379. void *pDebugScript;
  2380. if (SUCCEEDED(pActiveScript->QueryInterface(IID_IActiveScriptDebug, &pDebugScript)))
  2381. {
  2382. pASE->IsBeingDebugged();
  2383. LeaveCriticalSection(&m_csRSL);
  2384. return reinterpret_cast<IActiveScriptDebug *>(pDebugScript);
  2385. }
  2386. else
  2387. {
  2388. LeaveCriticalSection(&m_csRSL);
  2389. return NULL;
  2390. }
  2391. }
  2392. pASEElem = static_cast<CASEElem *>(pASEElem->m_pNext);
  2393. }
  2394. LeaveCriticalSection(&m_csRSL);
  2395. return NULL;
  2396. }
  2397. /*===================================================================
  2398. CScriptManager::FindEngineInList
  2399. Try to find an engine of the given name in the given list (either
  2400. the FSQ or the RSL.)
  2401. Returns:
  2402. HRESULT. S_OK on success.
  2403. ppASEElem contains found engine
  2404. ===================================================================*/
  2405. HRESULT CScriptManager::FindEngineInList
  2406. (
  2407. LPCTSTR szTemplateName, // Template we want an engine for
  2408. PROGLANG_ID progLangId, // what language do we want this engine for
  2409. DWORD dwInstanceID, // which server instance
  2410. BOOL fFSQ, // TRUE -> look in FSQ, FALSE -> look in RSQ
  2411. CASEElem **ppASEElem
  2412. )
  2413. {
  2414. HRESULT hr = S_OK;
  2415. DWORD cb;
  2416. AssertValid();
  2417. Assert(ppASEElem != NULL);
  2418. *ppASEElem = NULL;
  2419. // Key is name
  2420. cb = _tcslen(szTemplateName)*sizeof(TCHAR);
  2421. if (fFSQ)
  2422. {
  2423. EnterCriticalSection(&m_csFSQ);
  2424. *ppASEElem = static_cast<CASEElem *>(m_htFSQ.FindElem((VOID *)szTemplateName, cb,
  2425. progLangId, dwInstanceID, /*fCheckLoaded*/TRUE));
  2426. LeaveCriticalSection(&m_csFSQ);
  2427. }
  2428. else
  2429. {
  2430. EnterCriticalSection(&m_csRSL);
  2431. *ppASEElem = static_cast<CASEElem *>(m_htRSL.FindElem((VOID *)szTemplateName, cb,
  2432. progLangId, dwInstanceID, /*fCheckLoaded*/TRUE));
  2433. LeaveCriticalSection(&m_csRSL);
  2434. }
  2435. return(hr);
  2436. }
  2437. /*===================================================================
  2438. CScriptManager::FindASEElemInList
  2439. Given an ASE, find its corresponding ASEElem in the hash table. Note
  2440. that this is relatively slow because it is doing a linked list traversal
  2441. not a hash table lookup.
  2442. CONSIDER: create second hash table to do this quickly.
  2443. Returns:
  2444. HRESULT. S_OK on success.
  2445. ppASEElem contains found engine
  2446. ===================================================================*/
  2447. HRESULT CScriptManager::FindASEElemInList
  2448. (
  2449. CActiveScriptEngine *pASE,
  2450. BOOL fFSQ, // TRUE -> look in FSQ, FALSE -> look in RSQ
  2451. CASEElem **ppASEElem
  2452. )
  2453. {
  2454. HRESULT hr = S_OK;
  2455. CASEElem *pASEElem;
  2456. AssertValid();
  2457. Assert(pASE != NULL);
  2458. Assert(ppASEElem != NULL);
  2459. *ppASEElem = NULL;
  2460. if (fFSQ)
  2461. {
  2462. EnterCriticalSection(&m_csFSQ);
  2463. pASEElem = static_cast<CASEElem *>(m_htFSQ.Head());
  2464. }
  2465. else
  2466. {
  2467. EnterCriticalSection(&m_csRSL);
  2468. pASEElem = static_cast<CASEElem *>(m_htRSL.Head());
  2469. }
  2470. while (pASEElem != NULL)
  2471. {
  2472. if (pASE == pASEElem->PASE())
  2473. break;
  2474. pASEElem = static_cast<CASEElem *>(pASEElem->m_pNext);
  2475. }
  2476. if (fFSQ)
  2477. LeaveCriticalSection(&m_csFSQ);
  2478. else
  2479. LeaveCriticalSection(&m_csRSL);
  2480. *ppASEElem = pASEElem;
  2481. return(hr);
  2482. }
  2483. /*===================================================================
  2484. CScriptManager::KillOldEngines
  2485. Loops through all running engines and kills any engines which are "old"
  2486. (presumably they are stuck in an infinite loop in VBS.)
  2487. Returns:
  2488. HRESULT. S_OK on success.
  2489. Side effects:
  2490. Potentially kills off engines
  2491. ===================================================================*/
  2492. HRESULT CScriptManager::KillOldEngines
  2493. (
  2494. BOOLB fKillNow // Kill all engines now if TRUE
  2495. )
  2496. {
  2497. HRESULT hr = S_OK;
  2498. CASEElem *pASEElem, *pASEElemNext;
  2499. time_t timeNow;
  2500. time_t timeRunning;
  2501. CActiveScriptEngine *pASE;
  2502. AssertValid();
  2503. timeNow = time(NULL);
  2504. EnterCriticalSection(&m_csRSL);
  2505. pASEElemNext = static_cast<CASEElem *>(m_htRSL.Head());
  2506. /*
  2507. * Loop through each element. Turn it into an ASE.
  2508. * If it is older than cSeconds, then kill it.
  2509. */
  2510. while (pASEElemNext)
  2511. {
  2512. pASEElem = pASEElemNext;
  2513. pASEElemNext = static_cast<CASEElem *>(pASEElemNext->m_pNext);
  2514. pASE = pASEElem->PASE();
  2515. timeRunning = timeNow - pASE->TimeStarted();
  2516. if (TRUE == fKillNow || timeRunning >= pASE->GetTimeout())
  2517. {
  2518. // Too old. Kill it.
  2519. pASE->InterruptScript();
  2520. }
  2521. }
  2522. LeaveCriticalSection(&m_csRSL);
  2523. return(hr);
  2524. }
  2525. /*===================================================================
  2526. CScriptManager::EmptyRunningScriptList
  2527. When we are going to shut down, the RSL must be empty. This routine
  2528. kills off all running engines, then waits up to 5 minutes
  2529. for the engines to leave the RSL. Added for Bug 1140
  2530. Returns:
  2531. HRESULT. S_OK on success.
  2532. Side effects:
  2533. Potentially kills off engines
  2534. ===================================================================*/
  2535. HRESULT CScriptManager::EmptyRunningScriptList
  2536. (
  2537. )
  2538. {
  2539. HRESULT hr;
  2540. UINT cTrys;
  2541. hr = KillOldEngines(TRUE);
  2542. Assert(SUCCEEDED(hr));
  2543. for (cTrys = 0; cTrys < 300; cTrys++)
  2544. {
  2545. if (static_cast<CASEElem *>(m_htRSL.Head()) == NULL)
  2546. break;
  2547. Sleep(1000); // sleep 1 seconds
  2548. }
  2549. return(S_OK);
  2550. }
  2551. /*===================================================================
  2552. CScriptManager::UnInitASEElems
  2553. Free engines in FSQ and RSL
  2554. Returns:
  2555. HRESULT. S_OK on success.
  2556. Side effects:
  2557. Frees memory
  2558. ===================================================================*/
  2559. HRESULT CScriptManager::UnInitASEElems()
  2560. {
  2561. CASEElem *pASEElem = NULL;
  2562. CASEElem *pASEElemNext = NULL;
  2563. // First the FSQ
  2564. EnterCriticalSection(&m_csFSQ);
  2565. pASEElem = static_cast<CASEElem *>(m_htFSQ.Head());
  2566. while (pASEElem != NULL)
  2567. {
  2568. pASEElemNext = static_cast<CASEElem *>(pASEElem->m_pNext);
  2569. pASEElem->PASE()->FinalRelease();
  2570. delete pASEElem;
  2571. pASEElem = pASEElemNext;
  2572. }
  2573. LeaveCriticalSection(&m_csFSQ);
  2574. /*
  2575. * Next the RSL (note: this really should be empty)
  2576. *
  2577. * Bug 1140: This is very dangerous, but we have no choice left at this point
  2578. */
  2579. EnterCriticalSection(&m_csRSL);
  2580. pASEElem = static_cast<CASEElem *>(m_htRSL.Head());
  2581. while (pASEElem != NULL)
  2582. {
  2583. pASEElemNext = static_cast<CASEElem *>(pASEElem->m_pNext);
  2584. pASEElem->PASE()->FinalRelease();
  2585. delete pASEElem;
  2586. pASEElem = pASEElemNext;
  2587. }
  2588. LeaveCriticalSection(&m_csRSL);
  2589. return(S_OK);
  2590. }
  2591. /*===================================================================
  2592. CScriptManager::AddToFSQ
  2593. Add the given ASEElem to the FSQ and to the front of the LRU list
  2594. Returns:
  2595. HRESULT. S_OK on success.
  2596. Side effects:
  2597. None.
  2598. ===================================================================*/
  2599. HRESULT CScriptManager::AddToFSQ
  2600. (
  2601. CASEElem *pASEElem
  2602. )
  2603. {
  2604. HRESULT hr = S_OK;
  2605. Assert(pASEElem != NULL);
  2606. // If CacheMax is 0, this is a NoOp
  2607. if (Glob(dwScriptEngineCacheMax) <= 0)
  2608. {
  2609. // delete the passed in ASEElem because it wont be saved
  2610. pASEElem->PASE()->FinalRelease();
  2611. delete pASEElem;
  2612. return(S_OK);
  2613. }
  2614. EnterCriticalSection(&m_csFSQ);
  2615. // Add the element to the FSQ
  2616. (VOID)m_htFSQ.AddElem(pASEElem);
  2617. #ifndef PERF_DISABLE
  2618. g_PerfData.Incr_SCRIPTFREEENG();
  2619. #endif
  2620. // Check the FSQ LRU too see if it is too long
  2621. CheckFSQLRU();
  2622. LeaveCriticalSection(&m_csFSQ);
  2623. return(hr);
  2624. }
  2625. /*===================================================================
  2626. CScriptManager::CheckFSQLRU
  2627. Check to see if the FSQ is too long, and if so throw out the LRU engine
  2628. WARNING: Caller must enter FSQ critical section before calling
  2629. Returns:
  2630. HRESULT. S_OK on success.
  2631. Side effects:
  2632. None.
  2633. ===================================================================*/
  2634. HRESULT CScriptManager::CheckFSQLRU()
  2635. {
  2636. HRESULT hr = S_OK;
  2637. CASEElem *pASEElemOld;
  2638. CActiveScriptEngine *pASE;
  2639. // If the list isnt too long, noop
  2640. if (m_htFSQ.Count() <= Glob(dwScriptEngineCacheMax) || Glob(dwScriptEngineCacheMax) == 0xFFFFFFFF)
  2641. return(S_OK);
  2642. // FSQLRU list is too long, remove oldest
  2643. Assert (! m_htFSQ.FLruElemIsEmpty( m_htFSQ.End() ));
  2644. pASEElemOld = static_cast<CASEElem *>(m_htFSQ.RemoveElem(m_htFSQ.End()));
  2645. Assert(pASEElemOld != NULL);
  2646. pASE = pASEElemOld->PASE();
  2647. #ifndef PERF_DISABLE
  2648. g_PerfData.Decr_SCRIPTFREEENG();
  2649. #endif
  2650. // Delete the engine
  2651. delete pASEElemOld;
  2652. pASE->FinalRelease();
  2653. return(hr);
  2654. }
  2655. /*===================================================================
  2656. CScriptManager::UnInitPLL
  2657. Free the names of the script engines
  2658. Returns:
  2659. HRESULT. S_OK on success.
  2660. Side effects:
  2661. Frees memory
  2662. ===================================================================*/
  2663. HRESULT CScriptManager::UnInitPLL()
  2664. {
  2665. CPLLElem *pPLLElem = NULL;
  2666. CPLLElem *pPLLElemNext = NULL;
  2667. pPLLElem = (CPLLElem *)m_hTPLL.Head();
  2668. while (pPLLElem != NULL)
  2669. {
  2670. pPLLElemNext = (CPLLElem *)pPLLElem->m_pNext;
  2671. if (pPLLElem->m_pKey != NULL)
  2672. free((CHAR *)(pPLLElem->m_pKey));
  2673. pPLLElem->m_pKey = NULL;
  2674. delete pPLLElem;
  2675. pPLLElem = pPLLElemNext;
  2676. }
  2677. return(S_OK);
  2678. }
  2679. /*===================================================================
  2680. CScriptManager::ProgLangIdOfLangName
  2681. Given a programming language name, get the CLSID of the ActiveX Scripting
  2682. Engine which runs that language.
  2683. WARNING: Needs to look in the registry for this info. Maybe slow
  2684. Returns:
  2685. HRESULT. S_OK on success.
  2686. Side effects:
  2687. None.
  2688. ===================================================================*/
  2689. HRESULT CScriptManager::ProgLangIdOfLangName
  2690. (
  2691. LPCSTR szProgLang, // The programming lang of the script
  2692. PROGLANG_ID *pProgLangId // The programming language id
  2693. )
  2694. {
  2695. HRESULT hr = S_OK;
  2696. CPLLElem *pPLLElem;
  2697. AssertValid();
  2698. EnterCriticalSection(&m_cSPLL);
  2699. pPLLElem = (CPLLElem *) m_hTPLL.FindElem((VOID *)szProgLang, strlen(szProgLang));
  2700. if (pPLLElem != NULL)
  2701. {
  2702. *pProgLangId = pPLLElem->ProgLangId();
  2703. }
  2704. else
  2705. {
  2706. // Not already in list, look in registry
  2707. hr = GetProgLangIdOfName(szProgLang, pProgLangId);
  2708. if (FAILED(hr))
  2709. {
  2710. hr = TYPE_E_ELEMENTNOTFOUND;
  2711. goto LExit;
  2712. }
  2713. // Add it to the list so we dont have to re-look it up
  2714. hr = AddProgLangToPLL((CHAR *)szProgLang, *pProgLangId);
  2715. if (FAILED(hr))
  2716. goto LExit;
  2717. }
  2718. LExit:
  2719. LeaveCriticalSection(&m_cSPLL);
  2720. return(hr);
  2721. }
  2722. /*===================================================================
  2723. CScriptManager::AddProgLangToPLL
  2724. Keep list of programming language CLSIDs so we dont have to look
  2725. them up every time. Add the given programming language name/id pair
  2726. to the Programming Language List.
  2727. Returns:
  2728. HRESULT. S_OK on success.
  2729. Side effects:
  2730. None.
  2731. ===================================================================*/
  2732. HRESULT CScriptManager::AddProgLangToPLL
  2733. (
  2734. CHAR *szProgLangName,
  2735. PROGLANG_ID progLangId
  2736. )
  2737. {
  2738. HRESULT hr;
  2739. CPLLElem *pPLLElem = NULL;
  2740. // Put the language clsid on the Programming Language List
  2741. pPLLElem = new CPLLElem;
  2742. if (!pPLLElem)
  2743. {
  2744. hr = E_OUTOFMEMORY;
  2745. goto LFail;
  2746. }
  2747. hr = pPLLElem->Init(szProgLangName, progLangId);
  2748. if (FAILED(hr))
  2749. {
  2750. Assert(FALSE); // Shouldnt fail
  2751. goto LFail;
  2752. }
  2753. EnterCriticalSection(&m_cSPLL);
  2754. (VOID)m_hTPLL.AddElem(pPLLElem);
  2755. LeaveCriticalSection(&m_cSPLL);
  2756. LFail:
  2757. return(hr);
  2758. }
  2759. /*===================================================================
  2760. CScriptManager::ScriptKillerSchedulerCallback
  2761. Static method implements ATQ scheduler callback functions.
  2762. Replaces script killer thread
  2763. Parameters:
  2764. void *pv context pointer (points to script mgr)
  2765. Returns:
  2766. Side effects:
  2767. None.
  2768. ===================================================================*/
  2769. void WINAPI CScriptManager::ScriptKillerSchedulerCallback
  2770. (
  2771. void *pv
  2772. )
  2773. {
  2774. if (IsShutDownInProgress())
  2775. return;
  2776. Assert(pv);
  2777. CScriptManager *pScriptMgr = reinterpret_cast<CScriptManager *>(pv);
  2778. if (pScriptMgr->m_fInited)
  2779. {
  2780. pScriptMgr->KillOldEngines();
  2781. }
  2782. }
  2783. #ifdef DBG
  2784. /*===================================================================
  2785. CScriptManager::AssertValid
  2786. Test to make sure that the CScriptManager object is currently correctly formed
  2787. and assert if it is not.
  2788. Returns:
  2789. Side effects:
  2790. None.
  2791. ===================================================================*/
  2792. VOID CScriptManager::AssertValid() const
  2793. {
  2794. Assert(m_fInited);
  2795. }
  2796. #endif // DBG
  2797. /*
  2798. *
  2799. *
  2800. *
  2801. * C A S E E l e m
  2802. *
  2803. * Active Script Engine Elements
  2804. *
  2805. *
  2806. *
  2807. */
  2808. /*===================================================================
  2809. CASEElem::~CASEElem
  2810. Destructor for CASEElem object.
  2811. Returns:
  2812. Nothing
  2813. Side effects:
  2814. None
  2815. ===================================================================*/
  2816. CASEElem::~CASEElem()
  2817. {
  2818. }
  2819. /*===================================================================
  2820. CASEElem::Init
  2821. Init the Active Script Engine Elem. This must only be called once.
  2822. Returns:
  2823. HRESULT. S_OK on success.
  2824. Side effects:
  2825. None.
  2826. ===================================================================*/
  2827. HRESULT CASEElem::Init
  2828. (
  2829. CActiveScriptEngine *pASE
  2830. )
  2831. {
  2832. HRESULT hr = S_OK;
  2833. TCHAR *szT = pASE->SzTemplateName();
  2834. if (szT == NULL)
  2835. {
  2836. Assert(FALSE);
  2837. return(E_FAIL);
  2838. }
  2839. // Key is name
  2840. hr = CLinkElem::Init((LPVOID) szT, _tcslen(szT)*sizeof(TCHAR));
  2841. if (FAILED(hr))
  2842. {
  2843. Assert(FALSE); // Shouldnt fail
  2844. return(hr);
  2845. }
  2846. m_pASE = pASE;
  2847. return(hr);
  2848. }
  2849. /*
  2850. *
  2851. *
  2852. *
  2853. * C P L L E l e m
  2854. *
  2855. * Programming Language List Element
  2856. *
  2857. *
  2858. *
  2859. *
  2860. */
  2861. /*===================================================================
  2862. CPLLElem::~CPLLElem
  2863. Destructor for CPLLElem object.
  2864. Returns:
  2865. Nothing
  2866. Side effects:
  2867. Deallocates memory
  2868. ===================================================================*/
  2869. CPLLElem::~CPLLElem()
  2870. {
  2871. CHAR *szT;
  2872. // Free the memory allocated for the key string
  2873. szT = (CHAR *)m_pKey;
  2874. if (szT != NULL)
  2875. free(szT);
  2876. m_pKey = NULL;
  2877. }
  2878. /*===================================================================
  2879. CPLLElem::Init
  2880. Init the Prog Lang Elem. This must only be called once.
  2881. Returns:
  2882. HRESULT. S_OK on success.
  2883. Side effects:
  2884. Allocates memory
  2885. ===================================================================*/
  2886. HRESULT CPLLElem::Init
  2887. (
  2888. CHAR *szProgLangName,
  2889. PROGLANG_ID progLangId
  2890. )
  2891. {
  2892. HRESULT hr = S_OK;
  2893. CHAR *szT;
  2894. UINT cch;
  2895. if (szProgLangName == NULL)
  2896. {
  2897. Assert(FALSE);
  2898. return(E_FAIL);
  2899. }
  2900. cch = strlen(szProgLangName);
  2901. szT = (CHAR *)malloc(cch+1);
  2902. if (!szT)
  2903. {
  2904. return(E_OUTOFMEMORY);
  2905. }
  2906. strcpy(szT, szProgLangName);
  2907. hr = CLinkElem::Init((LPVOID) szT, cch);
  2908. if (FAILED(hr))
  2909. {
  2910. Assert(FALSE); // Shouldnt fail
  2911. free(szT);
  2912. return(hr);
  2913. }
  2914. m_ProgLangId = progLangId;
  2915. return(hr);
  2916. }
  2917. /*===================================================================
  2918. GetProgLangIdOfName
  2919. Given the name of a programming language, get its programming
  2920. language Id from the registry.
  2921. Returns:
  2922. HRESULT. S_OK on success.
  2923. Side effects:
  2924. None.
  2925. ===================================================================*/
  2926. HRESULT GetProgLangIdOfName
  2927. (
  2928. LPCSTR szProgLangName,
  2929. PROGLANG_ID *pProgLangId
  2930. )
  2931. {
  2932. HRESULT hr = S_OK;
  2933. LONG lT;
  2934. HKEY hkeyRoot, hkeyCLSID;
  2935. DWORD dwType;
  2936. CLSID clsid;
  2937. CHAR szClsid[40];
  2938. DWORD cbData;
  2939. LPOLESTR strClsid;
  2940. CMBCSToWChar convStr;
  2941. // The programming language id is really the CLSID of the scripting engine
  2942. // It is in the registry under HKEY_CLASSES_ROOT. Under the script name,
  2943. // there is a key for "CLSID". The CLSID is a value under the
  2944. // engine name. E.g. \HKEY_CLASSES_ROOT\VBScript\CLSID
  2945. lT = RegOpenKeyExA(HKEY_CLASSES_ROOT, szProgLangName, 0,
  2946. KEY_READ, &hkeyRoot);
  2947. if (lT != ERROR_SUCCESS)
  2948. return(HRESULT_FROM_WIN32(lT));
  2949. lT = RegOpenKeyExA(hkeyRoot, "CLSID", 0,
  2950. KEY_READ, &hkeyCLSID);
  2951. RegCloseKey(hkeyRoot);
  2952. if (lT != ERROR_SUCCESS)
  2953. return(HRESULT_FROM_WIN32(lT));
  2954. cbData = sizeof(szClsid);
  2955. lT = RegQueryValueExA(hkeyCLSID, NULL, 0, &dwType, (BYTE *)szClsid, &cbData);
  2956. if (lT != ERROR_SUCCESS)
  2957. {
  2958. hr = HRESULT_FROM_WIN32(lT);
  2959. goto lExit;
  2960. }
  2961. Assert(cbData <= sizeof(szClsid));
  2962. // What we got back was the GUID as a string (e.g. {089999-444....}). Convert to a CLSID
  2963. convStr.Init(szClsid);
  2964. strClsid = convStr.GetString();
  2965. hr = CLSIDFromString(strClsid, &clsid);
  2966. *pProgLangId = clsid;
  2967. lExit:
  2968. RegCloseKey(hkeyCLSID);
  2969. return(hr);
  2970. }
  2971. /*
  2972. *
  2973. *
  2974. *
  2975. * C S c r i p t i n g N a m e s p a c e
  2976. *
  2977. * Scripting namespace object
  2978. *
  2979. *
  2980. *
  2981. */
  2982. /*===================================================================
  2983. CScriptingNamespace::CScriptingNamespace
  2984. Constructor for CScriptingNamespace object.
  2985. Returns:
  2986. Nothing
  2987. Side effects:
  2988. None
  2989. ===================================================================*/
  2990. CScriptingNamespace::CScriptingNamespace()
  2991. : m_fInited(FALSE), m_cRef(1), m_cEngDispMac(0)
  2992. {
  2993. }
  2994. /*===================================================================
  2995. CScriptingNamespace::~CScriptingNamespace
  2996. Destructor for CScriptingNamespace object.
  2997. Returns:
  2998. Nothing
  2999. Side effects:
  3000. Deallocates memory
  3001. ===================================================================*/
  3002. CScriptingNamespace::~CScriptingNamespace()
  3003. {
  3004. UnInit();
  3005. }
  3006. /*===================================================================
  3007. CScriptingNamespace::Init
  3008. Init the CScriptingNamespace object.
  3009. Returns:
  3010. S_OK on success
  3011. ===================================================================*/
  3012. HRESULT CScriptingNamespace::Init()
  3013. {
  3014. Assert(m_fInited == FALSE);
  3015. m_fInited = TRUE;
  3016. AssertValid();
  3017. return(S_OK);
  3018. }
  3019. /*===================================================================
  3020. CScriptingNamespace::UnInit
  3021. Free the script engine dispatch's
  3022. Returns:
  3023. HRESULT. S_OK on success.
  3024. Side effects:
  3025. Frees memory
  3026. ===================================================================*/
  3027. HRESULT CScriptingNamespace::UnInit()
  3028. {
  3029. static const char *_pFuncName = "CScriptingNamespace::UnInit()";
  3030. CEngineDispElem *pElem = NULL;
  3031. ENGDISPBUCKET *pBucket = NULL;
  3032. if (!m_fInited)
  3033. return(S_OK);
  3034. while (!m_listSE.FIsEmpty())
  3035. {
  3036. pElem = static_cast<CEngineDispElem *>(m_listSE.PNext());
  3037. TRYCATCH_NOHITOBJ(pElem->m_pDisp->Release(),"IScriptDispatch::Release()");
  3038. if (pElem->m_pDispEx) {
  3039. TRYCATCH_NOHITOBJ(pElem->m_pDispEx->Release(),"IScriptDispatchEx::Release()");
  3040. }
  3041. delete pElem;
  3042. }
  3043. while (!m_listEngDisp.FIsEmpty())
  3044. {
  3045. pBucket = static_cast<ENGDISPBUCKET *>(m_listEngDisp.PNext());
  3046. delete pBucket;
  3047. }
  3048. m_cEngDispMac = 0;
  3049. m_fInited = FALSE;
  3050. return(S_OK);
  3051. }
  3052. /*===================================================================
  3053. CScriptingNamespace::ReInit
  3054. Reinit the scripting namespace object
  3055. Returns:
  3056. HRESULT. S_OK on success.
  3057. Side effects:
  3058. Frees memory
  3059. ===================================================================*/
  3060. HRESULT CScriptingNamespace::ReInit()
  3061. {
  3062. HRESULT hr;
  3063. hr = UnInit();
  3064. if (SUCCEEDED(hr))
  3065. hr = Init();
  3066. return(hr);
  3067. }
  3068. /*===================================================================
  3069. CScriptingNamespace::AddEngineToNamespace
  3070. Add an engine to the list of engines
  3071. Returns:
  3072. S_OK on success
  3073. ===================================================================*/
  3074. HRESULT CScriptingNamespace::AddEngineToNamespace(CActiveScriptEngine *pASE)
  3075. {
  3076. static const char *_pFuncName = "CScriptingNamespace::AddEngineToNamespace()";
  3077. HRESULT hr;
  3078. IDispatch *pDisp = NULL;
  3079. CEngineDispElem *pElem;
  3080. AssertValid();
  3081. Assert(pASE != NULL);
  3082. pASE->AssertValid();
  3083. TRYCATCH_HR_NOHITOBJ(pASE->GetActiveScript()->GetScriptDispatch(NULL, &pDisp),
  3084. hr,
  3085. "IActiveScript::GetScriptDispatch()"); // FYI - does addref
  3086. if (FAILED(hr))
  3087. {
  3088. goto LFail;
  3089. }
  3090. else
  3091. if (pDisp == NULL)
  3092. {
  3093. hr = E_FAIL;
  3094. goto LFail;
  3095. }
  3096. // Add the engine to the engine hash table.
  3097. pElem = new CEngineDispElem;
  3098. if (pElem == NULL)
  3099. {
  3100. hr = E_OUTOFMEMORY;
  3101. goto LFail;
  3102. }
  3103. pElem->m_pDisp = pDisp;
  3104. pElem->m_pDispEx = NULL;
  3105. // QI for IDispatchEx if available
  3106. TRYCATCH_NOHITOBJ(pDisp->QueryInterface(IID_IDispatchEx, (void **)&pElem->m_pDispEx),"IScriptDispatch::QueryInterface()");
  3107. pElem->AppendTo(m_listSE);
  3108. return(S_OK);
  3109. LFail:
  3110. if (pDisp) {
  3111. TRYCATCH_NOHITOBJ(pDisp->Release(),"IScriptDispatch::Release()");
  3112. }
  3113. return(hr);
  3114. }
  3115. /*===================================================================
  3116. CScriptingNamespace::QueryInterface
  3117. CScriptingNamespace::AddRef
  3118. CScriptingNamespace::Release
  3119. IUnknown members for CScriptingNamespace object.
  3120. ===================================================================*/
  3121. STDMETHODIMP CScriptingNamespace::QueryInterface(REFIID iid, void **ppvObj)
  3122. {
  3123. AssertValid();
  3124. if (iid == IID_IUnknown || iid == IID_IDispatch || iid == IID_IDispatchEx)
  3125. {
  3126. *ppvObj = this;
  3127. AddRef();
  3128. return S_OK;
  3129. }
  3130. *ppvObj = NULL;
  3131. return E_NOINTERFACE;
  3132. }
  3133. STDMETHODIMP_(ULONG) CScriptingNamespace::AddRef(void)
  3134. {
  3135. AssertValid();
  3136. return ++m_cRef;
  3137. }
  3138. STDMETHODIMP_(ULONG) CScriptingNamespace::Release(void)
  3139. {
  3140. if (--m_cRef > 0)
  3141. return m_cRef;
  3142. delete this;
  3143. return 0;
  3144. }
  3145. /*===================================================================
  3146. CScriptingNamespace::GetTypeInfoCount
  3147. We have no typeinfo, so 0.
  3148. Parameters:
  3149. pcInfo UINT * to the location to receive
  3150. the count of interfaces.
  3151. Return Value:
  3152. HRESULT S_OK or a general error code.
  3153. ===================================================================*/
  3154. STDMETHODIMP CScriptingNamespace::GetTypeInfoCount(UINT *pcInfo)
  3155. {
  3156. AssertValid();
  3157. *pcInfo = 0;
  3158. return S_OK;
  3159. }
  3160. /*===================================================================
  3161. CScriptingNamespace::GetTypeInfo
  3162. We dont have a typeinfo
  3163. Parameters:
  3164. itInfo UINT reserved. Must be zero.
  3165. lcid LCID providing the locale for the type
  3166. information. If the object does not support
  3167. localization, this is ignored.
  3168. ppITypeInfo ITypeInfo ** in which to store the ITypeInfo
  3169. interface for the object.
  3170. Return Value:
  3171. HRESULT S_OK or a general error code.
  3172. ===================================================================*/
  3173. STDMETHODIMP CScriptingNamespace::GetTypeInfo
  3174. (
  3175. UINT itInfo,
  3176. LCID lcid,
  3177. ITypeInfo **ppITypeInfo
  3178. )
  3179. {
  3180. AssertValid();
  3181. *ppITypeInfo = NULL;
  3182. return(E_NOTIMPL);
  3183. }
  3184. /*===================================================================
  3185. CScriptingNamespace::GetIDsOfNames
  3186. Looks through all the engines we know about, calling GetIdsOfNames on
  3187. them till we find the requested name.
  3188. Parameters:
  3189. riid REFIID reserved. Must be IID_NULL.
  3190. rgszNames OLECHAR ** pointing to the array of names to be mapped.
  3191. cNames UINT number of names to be mapped.
  3192. lcid LCID of the locale.
  3193. rgDispID DISPID * caller allocated array containing IDs
  3194. corresponging to those names in rgszNames.
  3195. Return Value:
  3196. HRESULT S_OK or a general error code.
  3197. ===================================================================*/
  3198. STDMETHODIMP CScriptingNamespace::GetIDsOfNames
  3199. (
  3200. REFIID riid,
  3201. OLECHAR **rgszNames,
  3202. UINT cNames,
  3203. LCID lcid,
  3204. DISPID *rgDispID
  3205. )
  3206. {
  3207. static const char *_pFuncName = "CScriptingNamespace::GetIDsOfNames()";
  3208. HRESULT hr;
  3209. CEngineDispElem *pElem;
  3210. AssertValid();
  3211. if (IID_NULL != riid)
  3212. return ResultFromScode(DISP_E_UNKNOWNINTERFACE);
  3213. /*
  3214. * Loop through the engines we know about until we find the one that has the requested name
  3215. * (or hit the end of the list, in which case it is not found)
  3216. */
  3217. for (pElem = static_cast<CEngineDispElem *>(m_listSE.PNext());
  3218. pElem != &m_listSE;
  3219. pElem = static_cast<CEngineDispElem *>(pElem->PNext()))
  3220. {
  3221. Assert(pElem->m_pDisp != NULL);
  3222. TRYCATCH_HR_NOHITOBJ(pElem->m_pDisp->GetIDsOfNames(riid, rgszNames, cNames, lcid, rgDispID),
  3223. hr,
  3224. "IScriptDispatch::GetIDsOfNames()");
  3225. if (SUCCEEDED(hr))
  3226. {
  3227. return CacheDispID(pElem, rgDispID[0], rgDispID);
  3228. }
  3229. }
  3230. return DISP_E_UNKNOWNNAME;
  3231. }
  3232. /*===================================================================
  3233. CScriptingNamespace::Invoke
  3234. Map the dispID to the correct engine, and pass the invoke on to that
  3235. engine.
  3236. Parameters:
  3237. dispID DISPID of the method or property of interest.
  3238. riid REFIID reserved, must be IID_NULL.
  3239. lcid LCID of the locale.
  3240. wFlags USHORT describing the context of the invocation.
  3241. pDispParams DISPPARAMS * to the array of arguments.
  3242. pVarResult VARIANT * in which to store the result. Is
  3243. NULL if the caller is not interested.
  3244. pExcepInfo EXCEPINFO * to exception information.
  3245. puArgErr UINT * in which to store the index of an
  3246. invalid parameter if DISP_E_TYPEMISMATCH
  3247. is returned.
  3248. Return Value:
  3249. HRESULT S_OK or a general error code.
  3250. ===================================================================*/
  3251. STDMETHODIMP CScriptingNamespace::Invoke
  3252. (
  3253. DISPID dispID,
  3254. REFIID riid,
  3255. LCID lcid,
  3256. unsigned short wFlags,
  3257. DISPPARAMS *pDispParams,
  3258. VARIANT *pVarResult,
  3259. EXCEPINFO *pExcepInfo,
  3260. UINT *puArgErr
  3261. )
  3262. {
  3263. static const char *_pFuncName = "CScriptingNamespace::Invoke()";
  3264. HRESULT hr;
  3265. ENGDISP *pEngDisp;
  3266. AssertValid();
  3267. // riid is supposed to be IID_NULL always
  3268. if (IID_NULL != riid)
  3269. return ResultFromScode(DISP_E_UNKNOWNINTERFACE);
  3270. // navigate to the correct ENGDISP structure
  3271. hr = FetchDispID(dispID, &pEngDisp);
  3272. if (FAILED(hr))
  3273. return hr;
  3274. Assert(pEngDisp->pDisp != NULL);
  3275. // invoke
  3276. TRYCATCH_HR_NOHITOBJ(pEngDisp->pDisp->Invoke
  3277. (
  3278. pEngDisp->dispid,
  3279. riid,
  3280. lcid,
  3281. wFlags,
  3282. pDispParams,
  3283. pVarResult,
  3284. pExcepInfo,
  3285. puArgErr
  3286. ),
  3287. hr,
  3288. "IScriptDispatch::Invoke()");
  3289. return hr;
  3290. }
  3291. /*===================================================================
  3292. CScriptingNamespace:: IDispatchEx implementation stubs
  3293. ===================================================================*/
  3294. STDMETHODIMP CScriptingNamespace::DeleteMemberByDispID(DISPID id)
  3295. {
  3296. return E_NOTIMPL;
  3297. }
  3298. STDMETHODIMP CScriptingNamespace::DeleteMemberByName(BSTR bstrName, DWORD grfdex)
  3299. {
  3300. return E_NOTIMPL;
  3301. }
  3302. STDMETHODIMP CScriptingNamespace::GetMemberName(DISPID id, BSTR *pbstrName)
  3303. {
  3304. return E_NOTIMPL;
  3305. }
  3306. STDMETHODIMP CScriptingNamespace::GetMemberProperties(DISPID id, DWORD grfdexFetch, DWORD *pgrfdex)
  3307. {
  3308. return E_NOTIMPL;
  3309. }
  3310. STDMETHODIMP CScriptingNamespace::GetNameSpaceParent(IUnknown **ppunk)
  3311. {
  3312. return E_NOTIMPL;
  3313. }
  3314. STDMETHODIMP CScriptingNamespace::GetNextDispID(DWORD grfdex, DISPID id, DISPID *pid)
  3315. {
  3316. return E_NOTIMPL;
  3317. }
  3318. /*===================================================================
  3319. CScriptingNamespace::GetDispID
  3320. IDispatchEx replacement for GetIDsOfNames
  3321. ===================================================================*/
  3322. STDMETHODIMP CScriptingNamespace::GetDispID
  3323. (
  3324. BSTR bstrName,
  3325. DWORD grfdex,
  3326. DISPID *pid
  3327. )
  3328. {
  3329. static const char *_pFuncName = "CScriptingNamespace::GetDispID()";
  3330. HRESULT hr;
  3331. CEngineDispElem *pElem = NULL;
  3332. grfdex &= ~fdexNameEnsure; // engines shouldn't create new names
  3333. // Try IDispatchEx for all engines that have it
  3334. for (pElem = static_cast<CEngineDispElem *>(m_listSE.PNext());
  3335. pElem != &m_listSE;
  3336. pElem = static_cast<CEngineDispElem *>(pElem->PNext()))
  3337. {
  3338. if (pElem->m_pDispEx != NULL)
  3339. {
  3340. TRYCATCH_HR_NOHITOBJ(pElem->m_pDispEx->GetDispID(bstrName, grfdex, pid),
  3341. hr,
  3342. "IScriptDispatchEx::GetDispID()");
  3343. if (SUCCEEDED(hr))
  3344. {
  3345. return CacheDispID(pElem, *pid, pid);
  3346. }
  3347. }
  3348. }
  3349. // Try IDispatch for engines that don't have IDispatchEx
  3350. for (pElem = static_cast<CEngineDispElem *>(m_listSE.PNext());
  3351. pElem != &m_listSE;
  3352. pElem = static_cast<CEngineDispElem *>(pElem->PNext()))
  3353. {
  3354. if (pElem->m_pDispEx == NULL)
  3355. {
  3356. Assert(pElem->m_pDisp != NULL);
  3357. TRYCATCH_HR_NOHITOBJ(pElem->m_pDisp->GetIDsOfNames
  3358. (
  3359. IID_NULL,
  3360. &bstrName,
  3361. 1,
  3362. LOCALE_SYSTEM_DEFAULT,
  3363. pid
  3364. ),
  3365. hr,
  3366. "IScriptDispatch::GetIDsOfNames()");
  3367. if (SUCCEEDED(hr))
  3368. {
  3369. return CacheDispID(pElem, *pid, pid);
  3370. }
  3371. }
  3372. }
  3373. return DISP_E_UNKNOWNNAME;
  3374. }
  3375. /*===================================================================
  3376. CScriptingNamespace::Invoke
  3377. IDispatchEx replacement for Invoke
  3378. ===================================================================*/
  3379. STDMETHODIMP CScriptingNamespace::InvokeEx
  3380. (
  3381. DISPID id,
  3382. LCID lcid,
  3383. WORD wFlags,
  3384. DISPPARAMS *pdp,
  3385. VARIANT *pVarRes,
  3386. EXCEPINFO *pei,
  3387. IServiceProvider *pspCaller
  3388. )
  3389. {
  3390. static const char *_pFuncName = "CScriptingNamespace::InvokeEx()";
  3391. HRESULT hr;
  3392. ENGDISP *pEngDisp;
  3393. // navigate to the correct ENGDISP structure
  3394. hr = FetchDispID(id, &pEngDisp);
  3395. if (FAILED(hr))
  3396. return hr;
  3397. if (pEngDisp->pDispEx != NULL)
  3398. {
  3399. // InvokeEx if the engine supports IDispatchEx
  3400. TRYCATCH_HR_NOHITOBJ(pEngDisp->pDispEx->InvokeEx
  3401. (
  3402. pEngDisp->dispid,
  3403. lcid,
  3404. wFlags,
  3405. pdp,
  3406. pVarRes,
  3407. pei,
  3408. pspCaller
  3409. ),
  3410. hr,
  3411. "IScriptDispatchEx::InvokeEx()");
  3412. }
  3413. else
  3414. {
  3415. // use IDispatch::Invoke if the engine doesn't support IDispatchEx
  3416. Assert(pEngDisp->pDisp != NULL);
  3417. UINT uArgErr;
  3418. TRYCATCH_HR_NOHITOBJ(pEngDisp->pDisp->Invoke
  3419. (
  3420. pEngDisp->dispid,
  3421. IID_NULL,
  3422. lcid,
  3423. wFlags,
  3424. pdp,
  3425. pVarRes,
  3426. pei,
  3427. &uArgErr
  3428. ),
  3429. hr,
  3430. "IScriptDispatch::Invoke()");
  3431. }
  3432. return hr;
  3433. }
  3434. /*===================================================================
  3435. CScriptingNamespace::CacheDispID
  3436. Adds new DISPID to the list
  3437. Parameters
  3438. pEngine -- engine for which disp id found
  3439. dispidEngine -- found dispid
  3440. pdispidCached -- [out] cached dispid (for ScriptingNamespace)
  3441. Returns
  3442. HRESULT
  3443. ===================================================================*/
  3444. HRESULT CScriptingNamespace::CacheDispID
  3445. (
  3446. CEngineDispElem *pEngine,
  3447. DISPID dispidEngine,
  3448. DISPID *pdispidCached
  3449. )
  3450. {
  3451. ENGDISPBUCKET *pEngDispBucket;
  3452. // See if we need to add another bucket
  3453. if ((m_cEngDispMac % ENGDISPMAX) == 0)
  3454. {
  3455. pEngDispBucket = new ENGDISPBUCKET;
  3456. if (pEngDispBucket == NULL)
  3457. return E_OUTOFMEMORY;
  3458. pEngDispBucket->AppendTo(m_listEngDisp);
  3459. }
  3460. // Navigate to the correct bucket
  3461. unsigned iEngDisp = m_cEngDispMac;
  3462. pEngDispBucket = static_cast<ENGDISPBUCKET *>(m_listEngDisp.PNext());
  3463. while (iEngDisp > ENGDISPMAX)
  3464. {
  3465. iEngDisp -= ENGDISPMAX;
  3466. pEngDispBucket = static_cast<ENGDISPBUCKET *>(pEngDispBucket->PNext());
  3467. }
  3468. pEngDispBucket->rgEngDisp[iEngDisp].dispid = dispidEngine;
  3469. pEngDispBucket->rgEngDisp[iEngDisp].pDisp = pEngine->m_pDisp;
  3470. pEngDispBucket->rgEngDisp[iEngDisp].pDispEx = pEngine->m_pDispEx;
  3471. // Return index as the dispid
  3472. *pdispidCached = (DISPID)m_cEngDispMac;
  3473. m_cEngDispMac++;
  3474. return S_OK;
  3475. }
  3476. /*===================================================================
  3477. CScriptingNamespace::FetchDispID
  3478. Find ENGDISP by DISPID
  3479. Parameters
  3480. dispid - in
  3481. ppEngDisp - out
  3482. Returns
  3483. HRESULT
  3484. ===================================================================*/
  3485. HRESULT CScriptingNamespace::FetchDispID
  3486. (
  3487. DISPID dispid,
  3488. ENGDISP **ppEngDisp
  3489. )
  3490. {
  3491. if (dispid >= (DISPID)m_cEngDispMac)
  3492. return E_FAIL;
  3493. unsigned iEngDisp = dispid;
  3494. ENGDISPBUCKET *pEngDispBucket = static_cast<ENGDISPBUCKET *>(m_listEngDisp.PNext());
  3495. while (iEngDisp > ENGDISPMAX)
  3496. {
  3497. iEngDisp -= ENGDISPMAX;
  3498. pEngDispBucket = static_cast<ENGDISPBUCKET *>(pEngDispBucket->PNext());
  3499. }
  3500. *ppEngDisp = &pEngDispBucket->rgEngDisp[iEngDisp];
  3501. return S_OK;
  3502. }
  3503. #ifdef DBG
  3504. /*===================================================================
  3505. CScriptingNamespace::AssertValid
  3506. Test to make sure that the CScriptingNamespace object is currently correctly formed
  3507. and assert if it is not.
  3508. Returns:
  3509. Side effects:
  3510. None.
  3511. ===================================================================*/
  3512. VOID CScriptingNamespace::AssertValid() const
  3513. {
  3514. Assert(m_fInited);
  3515. Assert(m_cRef > 0);
  3516. }
  3517. #endif // DBG
  3518. /*
  3519. *
  3520. *
  3521. * U t i l i t i e s
  3522. *
  3523. * General utility functions
  3524. *
  3525. */
  3526. /*===================================================================
  3527. WrapTypeLibs
  3528. Utility routine to take an array of Typelibs, and return an IDispatch
  3529. implementation that wraps the array of typelibs.
  3530. Parameters:
  3531. ITypeLib **prgpTypeLib - pointer to an array of typelibs
  3532. UINT cTypeLibs - count of typelibs in array
  3533. IDispatch **ppDisp - returned IDispatch
  3534. Return Value:
  3535. HRESULT S_OK or a general error code.
  3536. ===================================================================*/
  3537. HRESULT WrapTypeLibs
  3538. (
  3539. ITypeLib **prgpTypeLib,
  3540. UINT cTypeLibs,
  3541. IDispatch **ppDisp
  3542. )
  3543. {
  3544. HRESULT hr;
  3545. Assert(g_pWrapTypelibs != NULL);
  3546. Assert(prgpTypeLib != NULL);
  3547. Assert(cTypeLibs > 0);
  3548. Assert(ppDisp != NULL);
  3549. hr = g_pWrapTypelibs->WrapTypeLib(prgpTypeLib, cTypeLibs, ppDisp);
  3550. return(hr);
  3551. }