ScriptInstance.cs 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections;
  29. using System.Collections.Generic;
  30. using System.Globalization;
  31. using System.IO;
  32. using System.Reflection;
  33. using System.Runtime.Remoting;
  34. using System.Runtime.Remoting.Lifetime;
  35. using System.Security.Policy;
  36. using System.Text;
  37. using System.Threading;
  38. using System.Xml;
  39. using OpenMetaverse;
  40. using log4net;
  41. using Nini.Config;
  42. using Amib.Threading;
  43. using OpenSim.Framework;
  44. using OpenSim.Region.CoreModules;
  45. using OpenSim.Region.Framework.Scenes;
  46. using OpenSim.Region.Framework.Interfaces;
  47. using OpenSim.Region.ScriptEngine.Shared;
  48. using OpenSim.Region.ScriptEngine.Shared.Api;
  49. using OpenSim.Region.ScriptEngine.Shared.Api.Runtime;
  50. using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
  51. using OpenSim.Region.ScriptEngine.Shared.CodeTools;
  52. using OpenSim.Region.ScriptEngine.Interfaces;
  53. using System.Diagnostics; //for [DebuggerNonUserCode]
  54. namespace OpenSim.Region.ScriptEngine.Shared.Instance
  55. {
  56. public class ScriptInstance : MarshalByRefObject, IScriptInstance
  57. {
  58. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  59. public bool StatePersistedHere { get { return m_AttachedAvatar == UUID.Zero; } }
  60. /// <summary>
  61. /// The current work item if an event for this script is running or waiting to run,
  62. /// </summary>
  63. /// <remarks>
  64. /// Null if there is no running or waiting to run event. Must be changed only under an EventQueue lock.
  65. /// </remarks>
  66. private IScriptWorkItem m_CurrentWorkItem;
  67. private IScript m_Script;
  68. private DetectParams[] m_DetectParams;
  69. private bool m_TimerQueued;
  70. private DateTime m_EventStart;
  71. private bool m_InEvent;
  72. private string m_assemblyPath;
  73. private string m_dataPath;
  74. private string m_CurrentEvent = String.Empty;
  75. private bool m_InSelfDelete;
  76. private int m_MaxScriptQueue;
  77. private bool m_SaveState;
  78. private int m_ControlEventsInQueue;
  79. private int m_LastControlLevel;
  80. private bool m_CollisionInQueue;
  81. private bool m_StateChangeInProgress;
  82. // The following is for setting a minimum delay between events
  83. private double m_minEventDelay;
  84. private long m_eventDelayTicks;
  85. private long m_nextEventTimeTicks;
  86. private bool m_startOnInit = true;
  87. private UUID m_AttachedAvatar;
  88. private StateSource m_stateSource;
  89. private bool m_postOnRez;
  90. private bool m_startedFromSavedState;
  91. private UUID m_CurrentStateHash;
  92. private UUID m_RegionID;
  93. public int DebugLevel { get; set; }
  94. public WaitHandle CoopWaitHandle { get; private set; }
  95. public Stopwatch ExecutionTimer { get; private set; }
  96. public Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> LineMap { get; set; }
  97. private Dictionary<string,IScriptApi> m_Apis = new Dictionary<string,IScriptApi>();
  98. public Object[] PluginData = new Object[0];
  99. /// <summary>
  100. /// Used by llMinEventDelay to suppress events happening any faster than this speed.
  101. /// This currently restricts all events in one go. Not sure if each event type has
  102. /// its own check so take the simple route first.
  103. /// </summary>
  104. public double MinEventDelay
  105. {
  106. get { return m_minEventDelay; }
  107. set
  108. {
  109. if (value > 0.001)
  110. m_minEventDelay = value;
  111. else
  112. m_minEventDelay = 0.0;
  113. m_eventDelayTicks = (long)(m_minEventDelay * 10000000L);
  114. m_nextEventTimeTicks = DateTime.Now.Ticks;
  115. }
  116. }
  117. public bool Running
  118. {
  119. get { return m_running; }
  120. set
  121. {
  122. m_running = value;
  123. if (m_running)
  124. StayStopped = false;
  125. }
  126. }
  127. private bool m_running;
  128. public bool Suspended
  129. {
  130. get { return m_Suspended; }
  131. set
  132. {
  133. // Need to do this inside a lock in order to avoid races with EventProcessor()
  134. lock (m_Script)
  135. {
  136. bool wasSuspended = m_Suspended;
  137. m_Suspended = value;
  138. if (wasSuspended && !m_Suspended)
  139. {
  140. lock (EventQueue)
  141. {
  142. // Need to place ourselves back in a work item if there are events to process
  143. if (EventQueue.Count > 0 && Running && !ShuttingDown)
  144. m_CurrentWorkItem = Engine.QueueEventHandler(this);
  145. }
  146. }
  147. }
  148. }
  149. }
  150. private bool m_Suspended;
  151. public bool ShuttingDown { get; set; }
  152. public string State { get; set; }
  153. public bool StayStopped { get; set; }
  154. public IScriptEngine Engine { get; private set; }
  155. public UUID AppDomain { get; set; }
  156. public SceneObjectPart Part { get; private set; }
  157. public string PrimName { get; private set; }
  158. public string ScriptName { get; private set; }
  159. public UUID ItemID { get; private set; }
  160. public UUID ObjectID { get { return Part.UUID; } }
  161. public uint LocalID { get { return Part.LocalId; } }
  162. public UUID RootObjectID { get { return Part.ParentGroup.UUID; } }
  163. public uint RootLocalID { get { return Part.ParentGroup.LocalId; } }
  164. public UUID AssetID { get; private set; }
  165. public Queue EventQueue { get; private set; }
  166. public long EventsQueued
  167. {
  168. get
  169. {
  170. lock (EventQueue)
  171. return EventQueue.Count;
  172. }
  173. }
  174. public long EventsProcessed { get; private set; }
  175. public int StartParam { get; set; }
  176. public TaskInventoryItem ScriptTask { get; private set; }
  177. public DateTime TimeStarted { get; private set; }
  178. public MetricsCollectorTime ExecutionTime { get; private set; }
  179. private static readonly int MeasurementWindow = 30 * 1000; // show the *recent* time used by the script, to find currently active scripts
  180. private bool m_coopTermination;
  181. private EventWaitHandle m_coopSleepHandle;
  182. public void ClearQueue()
  183. {
  184. m_TimerQueued = false;
  185. m_StateChangeInProgress = false;
  186. EventQueue.Clear();
  187. }
  188. public ScriptInstance(
  189. IScriptEngine engine, SceneObjectPart part, TaskInventoryItem item,
  190. int startParam, bool postOnRez,
  191. int maxScriptQueue)
  192. {
  193. State = "default";
  194. EventQueue = new Queue(32);
  195. ExecutionTimer = new Stopwatch();
  196. Engine = engine;
  197. Part = part;
  198. ScriptTask = item;
  199. // This is currently only here to allow regression tests to get away without specifying any inventory
  200. // item when they are testing script logic that doesn't require an item.
  201. if (ScriptTask != null)
  202. {
  203. ScriptName = ScriptTask.Name;
  204. ItemID = ScriptTask.ItemID;
  205. AssetID = ScriptTask.AssetID;
  206. }
  207. PrimName = part.ParentGroup.Name;
  208. StartParam = startParam;
  209. m_MaxScriptQueue = maxScriptQueue;
  210. m_postOnRez = postOnRez;
  211. m_AttachedAvatar = part.ParentGroup.AttachedAvatar;
  212. m_RegionID = part.ParentGroup.Scene.RegionInfo.RegionID;
  213. m_SaveState = StatePersistedHere;
  214. ExecutionTime = new MetricsCollectorTime(MeasurementWindow, 10);
  215. // m_log.DebugFormat(
  216. // "[SCRIPT INSTANCE]: Instantiated script instance {0} (id {1}) in part {2} (id {3}) in object {4} attached avatar {5} in {6}",
  217. // ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, m_AttachedAvatar, Engine.World.Name);
  218. }
  219. /// <summary>
  220. /// Load the script from an assembly into an AppDomain.
  221. /// </summary>
  222. /// <param name='dom'></param>
  223. /// <param name='assembly'></param>
  224. /// <param name='dataPath'>
  225. /// Path for all script associated data (state, etc.). In a multi-region set up
  226. /// with all scripts loading into the same AppDomain this may not be the same place as the DLL itself.
  227. /// </param>
  228. /// <param name='stateSource'></param>
  229. /// <returns>false if load failed, true if suceeded</returns>
  230. public bool Load(
  231. IScript script, EventWaitHandle coopSleepHandle, string assemblyPath,
  232. string dataPath, StateSource stateSource, bool coopTermination)
  233. {
  234. m_Script = script;
  235. m_coopSleepHandle = coopSleepHandle;
  236. m_assemblyPath = assemblyPath;
  237. m_dataPath = dataPath;
  238. m_stateSource = stateSource;
  239. m_coopTermination = coopTermination;
  240. if (m_coopTermination)
  241. CoopWaitHandle = coopSleepHandle;
  242. else
  243. CoopWaitHandle = null;
  244. ApiManager am = new ApiManager();
  245. foreach (string api in am.GetApis())
  246. {
  247. m_Apis[api] = am.CreateApi(api);
  248. m_Apis[api].Initialize(Engine, Part, ScriptTask);
  249. }
  250. try
  251. {
  252. foreach (KeyValuePair<string,IScriptApi> kv in m_Apis)
  253. {
  254. m_Script.InitApi(kv.Key, kv.Value);
  255. }
  256. }
  257. catch (Exception e)
  258. {
  259. m_log.ErrorFormat(
  260. "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Error initializing script instance. Exception {6}{7}",
  261. ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, e.Message, e.StackTrace);
  262. return false;
  263. }
  264. // For attachments, XEngine saves the state into a .state file when XEngine.SetXMLState() is called.
  265. string savedState = Path.Combine(m_dataPath, ItemID.ToString() + ".state");
  266. if (File.Exists(savedState))
  267. {
  268. // m_log.DebugFormat(
  269. // "[SCRIPT INSTANCE]: Found state for script {0} for {1} ({2}) at {3} in {4}",
  270. // ItemID, savedState, Part.Name, Part.ParentGroup.Name, Part.ParentGroup.Scene.Name);
  271. string xml = String.Empty;
  272. try
  273. {
  274. FileInfo fi = new FileInfo(savedState);
  275. int size = (int)fi.Length;
  276. if (size < 512000)
  277. {
  278. using (FileStream fs = File.Open(savedState,
  279. FileMode.Open, FileAccess.Read, FileShare.None))
  280. {
  281. Byte[] data = new Byte[size];
  282. fs.Read(data, 0, size);
  283. xml = Encoding.UTF8.GetString(data);
  284. ScriptSerializer.Deserialize(xml, this);
  285. AsyncCommandManager.CreateFromData(Engine,
  286. LocalID, ItemID, ObjectID,
  287. PluginData);
  288. // m_log.DebugFormat("[Script] Successfully retrieved state for script {0}.{1}", PrimName, m_ScriptName);
  289. if (!Running)
  290. m_startOnInit = false;
  291. Running = false;
  292. // we get new rez events on sim restart, too
  293. // but if there is state, then we fire the change
  294. // event
  295. // We loaded state, don't force a re-save
  296. m_SaveState = false;
  297. m_startedFromSavedState = true;
  298. }
  299. // If this script is in an attachment then we no longer need the state file.
  300. if (!StatePersistedHere)
  301. RemoveState();
  302. }
  303. // else
  304. // {
  305. // m_log.WarnFormat(
  306. // "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Unable to load script state file {6}. Memory limit exceeded.",
  307. // ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, savedState);
  308. // }
  309. }
  310. catch (Exception e)
  311. {
  312. m_log.ErrorFormat(
  313. "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Unable to load script state file {6}. XML is {7}. Exception {8}{9}",
  314. ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, savedState, xml, e.Message, e.StackTrace);
  315. }
  316. }
  317. // else
  318. // {
  319. // m_log.DebugFormat(
  320. // "[SCRIPT INSTANCE]: Did not find state for script {0} for {1} ({2}) at {3} in {4}",
  321. // ItemID, savedState, Part.Name, Part.ParentGroup.Name, Part.ParentGroup.Scene.Name);
  322. // }
  323. try
  324. {
  325. Part.SetScriptEvents(ItemID, m_Script.GetStateEventFlags(State));
  326. }
  327. catch
  328. {
  329. m_log.ErrorFormat("[SCRIPT INSTANCE]: failed to SetScriptEvents {0}", ItemID);
  330. }
  331. return true;
  332. }
  333. public void Init()
  334. {
  335. if (ShuttingDown)
  336. return;
  337. if (m_startedFromSavedState)
  338. {
  339. if (m_startOnInit)
  340. Start();
  341. if (m_postOnRez)
  342. {
  343. PostEvent(new EventParams("on_rez",
  344. new Object[] {new LSL_Types.LSLInteger(StartParam)}, new DetectParams[0]));
  345. }
  346. if (m_stateSource == StateSource.AttachedRez)
  347. {
  348. PostEvent(new EventParams("attach",
  349. new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0]));
  350. }
  351. else if (m_stateSource == StateSource.RegionStart)
  352. {
  353. //m_log.Debug("[Script] Posted changed(CHANGED_REGION_RESTART) to script");
  354. PostEvent(new EventParams("changed",
  355. new Object[] { new LSL_Types.LSLInteger((int)Changed.REGION_RESTART) }, new DetectParams[0]));
  356. }
  357. else if (m_stateSource == StateSource.PrimCrossing || m_stateSource == StateSource.Teleporting)
  358. {
  359. // CHANGED_REGION
  360. PostEvent(new EventParams("changed",
  361. new Object[] { new LSL_Types.LSLInteger((int)Changed.REGION) }, new DetectParams[0]));
  362. // CHANGED_TELEPORT
  363. if (m_stateSource == StateSource.Teleporting)
  364. PostEvent(new EventParams("changed",
  365. new Object[] { new LSL_Types.LSLInteger((int)Changed.TELEPORT) }, new DetectParams[0]));
  366. }
  367. }
  368. else
  369. {
  370. if (m_startOnInit)
  371. Start();
  372. PostEvent(new EventParams("state_entry",
  373. new Object[0], new DetectParams[0]));
  374. if (m_postOnRez)
  375. {
  376. PostEvent(new EventParams("on_rez",
  377. new Object[] {new LSL_Types.LSLInteger(StartParam)}, new DetectParams[0]));
  378. }
  379. if (m_stateSource == StateSource.AttachedRez)
  380. {
  381. PostEvent(new EventParams("attach",
  382. new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0]));
  383. }
  384. }
  385. }
  386. private void ReleaseControlsorPermissions(bool fullpermissions)
  387. {
  388. SceneObjectPart part = Engine.World.GetSceneObjectPart(LocalID);
  389. if (part != null && part.TaskInventory != null)
  390. {
  391. int permsMask;
  392. UUID permsGranter;
  393. part.TaskInventory.LockItemsForWrite(true);
  394. if (!part.TaskInventory.TryGetValue(ItemID, out TaskInventoryItem item))
  395. {
  396. part.TaskInventory.LockItemsForWrite(false);
  397. return;
  398. }
  399. permsGranter = item.PermsGranter;
  400. permsMask = item.PermsMask;
  401. if(fullpermissions)
  402. {
  403. item.PermsGranter = UUID.Zero;
  404. item.PermsMask = 0;
  405. }
  406. else
  407. item.PermsMask = permsMask & ~(ScriptBaseClass.PERMISSION_TAKE_CONTROLS | ScriptBaseClass.PERMISSION_CONTROL_CAMERA);
  408. part.TaskInventory.LockItemsForWrite(false);
  409. if ((permsMask & ScriptBaseClass.PERMISSION_TAKE_CONTROLS) != 0)
  410. {
  411. ScenePresence presence = Engine.World.GetScenePresence(permsGranter);
  412. if (presence != null)
  413. presence.UnRegisterControlEventsToScript(LocalID, ItemID);
  414. }
  415. }
  416. }
  417. public void DestroyScriptInstance()
  418. {
  419. ReleaseControlsorPermissions(false);
  420. AsyncCommandManager.RemoveScript(Engine, LocalID, ItemID);
  421. SceneObjectPart part = Engine.World.GetSceneObjectPart(LocalID);
  422. if (part != null)
  423. part.RemoveScriptEvents(ItemID);
  424. }
  425. public void RemoveState()
  426. {
  427. string savedState = Path.Combine(m_dataPath, ItemID.ToString() + ".state");
  428. // m_log.DebugFormat(
  429. // "[SCRIPT INSTANCE]: Deleting state {0} for script {1} (id {2}) in part {3} (id {4}) in object {5} in {6}.",
  430. // savedState, ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name);
  431. try
  432. {
  433. File.Delete(savedState);
  434. }
  435. catch (Exception e)
  436. {
  437. m_log.Warn(
  438. string.Format(
  439. "[SCRIPT INSTANCE]: Could not delete script state {0} for script {1} (id {2}) in part {3} (id {4}) in object {5} in {6}. Exception ",
  440. savedState, ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name),
  441. e);
  442. }
  443. }
  444. public void VarDump(Dictionary<string, object> vars)
  445. {
  446. // m_log.Info("Variable dump for script "+ ItemID.ToString());
  447. // foreach (KeyValuePair<string, object> v in vars)
  448. // {
  449. // m_log.Info("Variable: "+v.Key+" = "+v.Value.ToString());
  450. // }
  451. }
  452. public void Start()
  453. {
  454. lock (EventQueue)
  455. {
  456. if (Running)
  457. return;
  458. Running = true;
  459. TimeStarted = DateTime.Now;
  460. // Note: we don't reset ExecutionTime. The reason is that runaway scripts are stopped and restarted
  461. // automatically, and we *do* want to show that they had high CPU in that case. If we had reset
  462. // ExecutionTime here then runaway scripts, paradoxically, would never show up in the "Top Scripts" dialog.
  463. if (EventQueue.Count > 0)
  464. {
  465. if (m_CurrentWorkItem == null)
  466. m_CurrentWorkItem = Engine.QueueEventHandler(this);
  467. // else
  468. // m_log.Error("[Script] Tried to start a script that was already queued");
  469. }
  470. }
  471. }
  472. public bool Stop(int timeout, bool clearEventQueue = false)
  473. {
  474. if (DebugLevel >= 1)
  475. m_log.DebugFormat(
  476. "[SCRIPT INSTANCE]: Stopping script {0} {1} in {2} {3} with timeout {4} {5} {6}",
  477. ScriptName, ItemID, PrimName, ObjectID, timeout, m_InSelfDelete, DateTime.Now.Ticks);
  478. IScriptWorkItem workItem;
  479. lock (EventQueue)
  480. {
  481. if (clearEventQueue)
  482. ClearQueue();
  483. if (!Running)
  484. return true;
  485. // If we're not running or waiting to run an event then we can safely stop.
  486. if (m_CurrentWorkItem == null)
  487. {
  488. Running = false;
  489. return true;
  490. }
  491. // If we are waiting to run an event then we can try to cancel it.
  492. if (m_CurrentWorkItem.Cancel())
  493. {
  494. m_CurrentWorkItem = null;
  495. Running = false;
  496. return true;
  497. }
  498. workItem = m_CurrentWorkItem;
  499. Running = false;
  500. }
  501. // Wait for the current event to complete.
  502. if (!m_InSelfDelete)
  503. {
  504. if (!m_coopTermination)
  505. {
  506. // If we're not co-operative terminating then try and wait for the event to complete before stopping
  507. if (workItem.Wait(timeout))
  508. return true;
  509. }
  510. else
  511. {
  512. if (DebugLevel >= 1)
  513. m_log.DebugFormat(
  514. "[SCRIPT INSTANCE]: Co-operatively stopping script {0} {1} in {2} {3}",
  515. ScriptName, ItemID, PrimName, ObjectID);
  516. // This will terminate the event on next handle check by the script.
  517. m_coopSleepHandle.Set();
  518. // For now, we will wait forever since the event should always cleanly terminate once LSL loop
  519. // checking is implemented. May want to allow a shorter timeout option later.
  520. if (workItem.Wait(Timeout.Infinite))
  521. {
  522. if (DebugLevel >= 1)
  523. m_log.DebugFormat(
  524. "[SCRIPT INSTANCE]: Co-operatively stopped script {0} {1} in {2} {3}",
  525. ScriptName, ItemID, PrimName, ObjectID);
  526. return true;
  527. }
  528. }
  529. }
  530. lock (EventQueue)
  531. {
  532. workItem = m_CurrentWorkItem;
  533. }
  534. if (workItem == null)
  535. return true;
  536. // If the event still hasn't stopped and we the stop isn't the result of script or object removal, then
  537. // forcibly abort the work item (this aborts the underlying thread).
  538. // Co-operative termination should never reach this point.
  539. if (!m_InSelfDelete)
  540. {
  541. m_log.DebugFormat(
  542. "[SCRIPT INSTANCE]: Aborting unstopped script {0} {1} in prim {2}, localID {3}, timeout was {4} ms",
  543. ScriptName, ItemID, PrimName, LocalID, timeout);
  544. workItem.Abort();
  545. }
  546. lock (EventQueue)
  547. {
  548. m_CurrentWorkItem = null;
  549. }
  550. return true;
  551. }
  552. [DebuggerNonUserCode] //Prevents the debugger from farting in this function
  553. public void SetState(string state)
  554. {
  555. if (state == State)
  556. return;
  557. EventParams lastTimerEv = null;
  558. lock (EventQueue)
  559. {
  560. // Remove all queued events, remembering the last timer event
  561. while (EventQueue.Count > 0)
  562. {
  563. EventParams tempv = (EventParams)EventQueue.Dequeue();
  564. if (tempv.EventName == "timer") lastTimerEv = tempv;
  565. }
  566. // Post events
  567. PostEvent(new EventParams("state_exit", new Object[0],
  568. new DetectParams[0]));
  569. PostEvent(new EventParams("state", new Object[] { state },
  570. new DetectParams[0]));
  571. PostEvent(new EventParams("state_entry", new Object[0],
  572. new DetectParams[0]));
  573. // Requeue the timer event after the state changing events
  574. if (lastTimerEv != null) EventQueue.Enqueue(lastTimerEv);
  575. // This will stop events from being queued and processed
  576. // until the new state is started
  577. m_StateChangeInProgress = true;
  578. }
  579. throw new EventAbortException();
  580. }
  581. /// <summary>
  582. /// Post an event to this script instance.
  583. /// </summary>
  584. /// <remarks>
  585. /// The request to run the event is sent
  586. /// </remarks>
  587. /// <param name="data"></param>
  588. public void PostEvent(EventParams data)
  589. {
  590. // m_log.DebugFormat("[Script] Posted event {2} in state {3} to {0}.{1}",
  591. // PrimName, ScriptName, data.EventName, State);
  592. if (!Running)
  593. return;
  594. // If min event delay is set then ignore any events untill the time has expired
  595. // This currently only allows 1 event of any type in the given time period.
  596. // This may need extending to allow for a time for each individual event type.
  597. if (m_eventDelayTicks != 0 &&
  598. data.EventName != "state" && data.EventName != "state_entry" && data.EventName != "state_exit"
  599. && data.EventName != "run_time_permissions" && data.EventName != "http_request" && data.EventName != "link_message")
  600. {
  601. if (DateTime.Now.Ticks < m_nextEventTimeTicks)
  602. return;
  603. m_nextEventTimeTicks = DateTime.Now.Ticks + m_eventDelayTicks;
  604. }
  605. lock (EventQueue)
  606. {
  607. // The only events that persist across state changes are timers
  608. if (m_StateChangeInProgress && data.EventName != "timer")
  609. return;
  610. if (EventQueue.Count >= m_MaxScriptQueue)
  611. return;
  612. if (data.EventName == "timer")
  613. {
  614. if (m_TimerQueued)
  615. return;
  616. m_TimerQueued = true;
  617. }
  618. if (data.EventName == "control")
  619. {
  620. int held = ((LSL_Types.LSLInteger)data.Params[1]).value;
  621. // int changed = ((LSL_Types.LSLInteger)data.Params[2]).value;
  622. // If the last message was a 0 (nothing held)
  623. // and this one is also nothing held, drop it
  624. //
  625. if (m_LastControlLevel == held && held == 0)
  626. return;
  627. // If there is one or more queued, then queue
  628. // only changed ones, else queue unconditionally
  629. //
  630. if (m_ControlEventsInQueue > 0)
  631. {
  632. if (m_LastControlLevel == held)
  633. return;
  634. }
  635. m_LastControlLevel = held;
  636. m_ControlEventsInQueue++;
  637. }
  638. if (data.EventName == "collision")
  639. {
  640. if (m_CollisionInQueue)
  641. return;
  642. if (data.DetectParams == null)
  643. return;
  644. m_CollisionInQueue = true;
  645. }
  646. EventQueue.Enqueue(data);
  647. if (m_CurrentWorkItem == null)
  648. {
  649. m_CurrentWorkItem = Engine.QueueEventHandler(this);
  650. }
  651. }
  652. }
  653. /// <summary>
  654. /// Process the next event queued for this script
  655. /// </summary>
  656. /// <returns></returns>
  657. public object EventProcessor()
  658. {
  659. // We check here as the thread stopping this instance from running may itself hold the m_Script lock.
  660. if (!Running)
  661. return 0;
  662. lock (m_Script)
  663. {
  664. // m_log.DebugFormat("[XEngine]: EventProcessor() invoked for {0}.{1}", PrimName, ScriptName);
  665. if (Suspended)
  666. return 0;
  667. ExecutionTimer.Restart();
  668. try
  669. {
  670. return EventProcessorInt();
  671. }
  672. finally
  673. {
  674. ExecutionTimer.Stop();
  675. ExecutionTime.AddSample(ExecutionTimer);
  676. Part.ParentGroup.Scene.AddScriptExecutionTime(ExecutionTimer.ElapsedTicks);
  677. }
  678. }
  679. }
  680. private object EventProcessorInt()
  681. {
  682. EventParams data = null;
  683. lock (EventQueue)
  684. {
  685. data = (EventParams)EventQueue.Dequeue();
  686. if (data == null)
  687. {
  688. // check if a null event was enqueued or if its really empty
  689. if (EventQueue.Count > 0 && Running && !ShuttingDown && !m_InSelfDelete)
  690. {
  691. m_CurrentWorkItem = Engine.QueueEventHandler(this);
  692. }
  693. else
  694. {
  695. m_CurrentWorkItem = null;
  696. }
  697. return 0;
  698. }
  699. if (data.EventName == "timer")
  700. m_TimerQueued = false;
  701. if (data.EventName == "control")
  702. {
  703. if (m_ControlEventsInQueue > 0)
  704. m_ControlEventsInQueue--;
  705. }
  706. if (data.EventName == "collision")
  707. m_CollisionInQueue = false;
  708. }
  709. if (DebugLevel >= 2)
  710. m_log.DebugFormat(
  711. "[SCRIPT INSTANCE]: Processing event {0} for {1}/{2}({3})/{4}({5}) @ {6}/{7}",
  712. data.EventName,
  713. ScriptName,
  714. Part.Name,
  715. Part.LocalId,
  716. Part.ParentGroup.Name,
  717. Part.ParentGroup.UUID,
  718. Part.AbsolutePosition,
  719. Part.ParentGroup.Scene.Name);
  720. m_DetectParams = data.DetectParams;
  721. if (data.EventName == "state") // Hardcoded state change
  722. {
  723. State = data.Params[0].ToString();
  724. if (DebugLevel >= 1)
  725. m_log.DebugFormat(
  726. "[SCRIPT INSTANCE]: Changing state to {0} for {1}/{2}({3})/{4}({5}) @ {6}/{7}",
  727. State,
  728. ScriptName,
  729. Part.Name,
  730. Part.LocalId,
  731. Part.ParentGroup.Name,
  732. Part.ParentGroup.UUID,
  733. Part.AbsolutePosition,
  734. Part.ParentGroup.Scene.Name);
  735. AsyncCommandManager.StateChange(Engine,
  736. LocalID, ItemID);
  737. // we are effectively in the new state now, so we can resume queueing
  738. // and processing other non-timer events
  739. m_StateChangeInProgress = false;
  740. Part.RemoveScriptTargets(ItemID);
  741. Part.SetScriptEvents(ItemID, m_Script.GetStateEventFlags(State));
  742. }
  743. else
  744. {
  745. Exception e = null;
  746. if (Engine.World.PipeEventsForScript(LocalID) ||
  747. data.EventName == "control") // Don't freeze avies!
  748. {
  749. // m_log.DebugFormat("[Script] Delivered event {2} in state {3} to {0}.{1}",
  750. // PrimName, ScriptName, data.EventName, State);
  751. try
  752. {
  753. m_CurrentEvent = data.EventName;
  754. m_EventStart = DateTime.UtcNow;
  755. m_InEvent = true;
  756. try
  757. {
  758. m_Script.ExecuteEvent(State, data.EventName, data.Params);
  759. }
  760. finally
  761. {
  762. m_InEvent = false;
  763. m_CurrentEvent = String.Empty;
  764. lock (EventQueue)
  765. m_CurrentWorkItem = null; // no longer in a event that can be canceled
  766. }
  767. if (m_SaveState)
  768. {
  769. // This will be the very first event we deliver
  770. // (state_entry) in default state
  771. //
  772. SaveState();
  773. m_SaveState = false;
  774. }
  775. }
  776. catch (Exception exx)
  777. {
  778. e = exx;
  779. }
  780. if(e != null)
  781. {
  782. // m_log.DebugFormat(
  783. // "[SCRIPT] Exception in script {0} {1}: {2}{3}",
  784. // ScriptName, ItemID, e.Message, e.StackTrace);
  785. if ((!(e is TargetInvocationException)
  786. || (!(e.InnerException is SelfDeleteException)
  787. && !(e.InnerException is ScriptDeleteException)
  788. && !(e.InnerException is ScriptCoopStopException)))
  789. && !(e is ThreadAbortException))
  790. {
  791. try
  792. {
  793. if(e.InnerException != null && e.InnerException is ScriptException)
  794. {
  795. bool toowner = false;
  796. string text = e.InnerException.Message;
  797. if(text.StartsWith("(OWNER)"))
  798. {
  799. text = text.Substring(7);
  800. toowner = true;
  801. }
  802. text += "(script: " + ScriptName +
  803. " event: " + data.EventName +
  804. " primID:" + Part.UUID.ToString() +
  805. " at " + Part.AbsolutePosition + ")";
  806. if (text.Length > 1000)
  807. text = text.Substring(0, 1000);
  808. if (toowner)
  809. {
  810. ScenePresence sp = Engine.World.GetScenePresence(Part.OwnerID);
  811. if (sp != null && !sp.IsNPC)
  812. Engine.World.SimChatToAgent(Part.OwnerID, Utils.StringToBytes(text), 0x7FFFFFFF, Part.AbsolutePosition,
  813. Part.Name, Part.UUID, false);
  814. }
  815. else
  816. Engine.World.SimChat(Utils.StringToBytes(text),
  817. ChatTypeEnum.DebugChannel, 2147483647,
  818. Part.AbsolutePosition,
  819. Part.Name, Part.UUID, false);
  820. m_log.Debug(string.Format(
  821. "[SCRIPT ERROR]: {0} (at event {1}, part {2} {3} at {4} in {5}",
  822. e.InnerException.Message,
  823. data.EventName,
  824. PrimName,
  825. Part.UUID,
  826. Part.AbsolutePosition,
  827. Part.ParentGroup.Scene.Name));
  828. }
  829. else
  830. {
  831. // DISPLAY ERROR INWORLD
  832. string text = FormatException(e);
  833. if (text.Length > 1000)
  834. text = text.Substring(0, 1000);
  835. Engine.World.SimChat(Utils.StringToBytes(text),
  836. ChatTypeEnum.DebugChannel, 2147483647,
  837. Part.AbsolutePosition,
  838. Part.Name, Part.UUID, false);
  839. m_log.Debug(string.Format(
  840. "[SCRIPT ERROR]: Runtime error in script {0} (event {1}), part {2} {3} at {4} in {5} ",
  841. ScriptName,
  842. data.EventName,
  843. PrimName,
  844. Part.UUID,
  845. Part.AbsolutePosition,
  846. Part.ParentGroup.Scene.Name),
  847. e);
  848. }
  849. }
  850. catch (Exception)
  851. {
  852. }
  853. }
  854. else if ((e is TargetInvocationException) && (e.InnerException is SelfDeleteException))
  855. {
  856. m_InSelfDelete = true;
  857. Engine.World.DeleteSceneObject(Part.ParentGroup, false);
  858. }
  859. else if ((e is TargetInvocationException) && (e.InnerException is ScriptDeleteException))
  860. {
  861. m_InSelfDelete = true;
  862. Part.Inventory.RemoveInventoryItem(ItemID);
  863. }
  864. else if ((e is TargetInvocationException) && (e.InnerException is ScriptCoopStopException))
  865. {
  866. if (DebugLevel >= 1)
  867. m_log.DebugFormat(
  868. "[SCRIPT INSTANCE]: Script {0}.{1} in event {2}, state {3} stopped co-operatively.",
  869. PrimName, ScriptName, data.EventName, State);
  870. }
  871. }
  872. }
  873. }
  874. // If there are more events and we are currently running and not shutting down, then ask the
  875. // script engine to run the next event.
  876. lock (EventQueue)
  877. {
  878. // Increase processed events counter and prevent wrap;
  879. if (++EventsProcessed == 1000000)
  880. EventsProcessed = 100000;
  881. if ((EventsProcessed % 100000) == 0 && DebugLevel > 0)
  882. {
  883. m_log.DebugFormat("[SCRIPT INSTANCE]: Script \"{0}\" (Object \"{1}\" {2} @ {3}.{4}, Item ID {5}, Asset {6}) in event {7}: processed {8:n0} script events",
  884. ScriptTask.Name,
  885. Part.ParentGroup.Name, Part.ParentGroup.UUID, Part.ParentGroup.AbsolutePosition, Part.ParentGroup.Scene.Name,
  886. ScriptTask.ItemID, ScriptTask.AssetID, data.EventName, EventsProcessed);
  887. }
  888. if (EventQueue.Count > 0 && Running && !ShuttingDown && !m_InSelfDelete)
  889. {
  890. m_CurrentWorkItem = Engine.QueueEventHandler(this);
  891. }
  892. else
  893. {
  894. m_CurrentWorkItem = null;
  895. }
  896. }
  897. m_DetectParams = null;
  898. return 0;
  899. }
  900. public int EventTime()
  901. {
  902. if (!m_InEvent)
  903. return 0;
  904. return (DateTime.UtcNow - m_EventStart).Seconds;
  905. }
  906. public void ResetScript(int timeout)
  907. {
  908. if (m_Script == null)
  909. return;
  910. bool running = Running;
  911. RemoveState();
  912. ReleaseControlsorPermissions(true);
  913. Stop(timeout);
  914. AsyncCommandManager.RemoveScript(Engine, LocalID, ItemID);
  915. m_TimerQueued = false;
  916. m_StateChangeInProgress = false;
  917. EventQueue.Clear();
  918. m_Script.ResetVars();
  919. StartParam = 0;
  920. State = "default";
  921. SceneObjectPart part = Engine.World.GetSceneObjectPart(LocalID);
  922. if (part == null)
  923. return;
  924. part.CollisionSound = UUID.Zero;
  925. part.RemoveScriptTargets(ItemID);
  926. part.SetScriptEvents(ItemID, m_Script.GetStateEventFlags(State));
  927. if (running)
  928. Start();
  929. m_SaveState = StatePersistedHere;
  930. PostEvent(new EventParams("state_entry",
  931. new Object[0], new DetectParams[0]));
  932. }
  933. [DebuggerNonUserCode] //Stops the VS debugger from farting in this function
  934. public void ApiResetScript()
  935. {
  936. // bool running = Running;
  937. RemoveState();
  938. ReleaseControlsorPermissions(true);
  939. AsyncCommandManager.RemoveScript(Engine, LocalID, ItemID);
  940. m_TimerQueued = false;
  941. m_StateChangeInProgress = false;
  942. EventQueue.Clear();
  943. m_Script.ResetVars();
  944. string oldState = State;
  945. StartParam = 0;
  946. State = "default";
  947. SceneObjectPart part = Engine.World.GetSceneObjectPart(LocalID);
  948. if(part != null)
  949. {
  950. part.CollisionSound = UUID.Zero;
  951. part.RemoveScriptTargets(ItemID);
  952. part.SetScriptEvents(ItemID, m_Script.GetStateEventFlags(State));
  953. }
  954. if (m_CurrentEvent != "state_entry" || oldState != "default")
  955. {
  956. m_SaveState = StatePersistedHere;
  957. PostEvent(new EventParams("state_entry",
  958. new Object[0], new DetectParams[0]));
  959. throw new EventAbortException();
  960. }
  961. }
  962. public Dictionary<string, object> GetVars()
  963. {
  964. if (m_Script != null)
  965. return m_Script.GetVars();
  966. else
  967. return new Dictionary<string, object>();
  968. }
  969. public void SetVars(Dictionary<string, object> vars)
  970. {
  971. // foreach (KeyValuePair<string, object> kvp in vars)
  972. // m_log.DebugFormat("[SCRIPT INSTANCE]: Setting var {0}={1}", kvp.Key, kvp.Value);
  973. m_Script.SetVars(vars);
  974. }
  975. public DetectParams GetDetectParams(int idx)
  976. {
  977. if (m_DetectParams == null)
  978. return null;
  979. if (idx < 0 || idx >= m_DetectParams.Length)
  980. return null;
  981. return m_DetectParams[idx];
  982. }
  983. public UUID GetDetectID(int idx)
  984. {
  985. if (m_DetectParams == null)
  986. return UUID.Zero;
  987. if (idx < 0 || idx >= m_DetectParams.Length)
  988. return UUID.Zero;
  989. return m_DetectParams[idx].Key;
  990. }
  991. public void SaveState()
  992. {
  993. if (!Running && !StayStopped)
  994. return;
  995. // We cannot call this inside the EventQueue lock since it will currently take AsyncCommandManager.staticLock.
  996. // This may already be held by AsyncCommandManager.DoOneCmdHandlerPass() which in turn can take EventQueue
  997. // lock via ScriptInstance.PostEvent().
  998. PluginData = AsyncCommandManager.GetSerializationData(Engine, ItemID);
  999. // We need to lock here to avoid any race with a thread that is removing this script.
  1000. lock (EventQueue)
  1001. {
  1002. // Check again to avoid a race with a thread in Stop()
  1003. if (!Running && !StayStopped)
  1004. return;
  1005. // If we're currently in an event, just tell it to save upon return
  1006. //
  1007. if (m_InEvent)
  1008. {
  1009. m_SaveState = true;
  1010. return;
  1011. }
  1012. // m_log.DebugFormat(
  1013. // "[SCRIPT INSTANCE]: Saving state for script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}",
  1014. // ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name);
  1015. string xml = ScriptSerializer.Serialize(this);
  1016. // Compare hash of the state we just just created with the state last written to disk
  1017. // If the state is different, update the disk file.
  1018. UUID hash = UUID.Parse(Utils.MD5String(xml));
  1019. if (hash != m_CurrentStateHash)
  1020. {
  1021. try
  1022. {
  1023. using (FileStream fs = File.Create(Path.Combine(m_dataPath, ItemID.ToString() + ".state")))
  1024. {
  1025. Byte[] buf = Util.UTF8NoBomEncoding.GetBytes(xml);
  1026. fs.Write(buf, 0, buf.Length);
  1027. }
  1028. }
  1029. catch(Exception)
  1030. {
  1031. // m_log.Error("Unable to save xml\n"+e.ToString());
  1032. }
  1033. //if (!File.Exists(Path.Combine(Path.GetDirectoryName(assembly), ItemID.ToString() + ".state")))
  1034. //{
  1035. // throw new Exception("Completed persistence save, but no file was created");
  1036. //}
  1037. m_CurrentStateHash = hash;
  1038. }
  1039. StayStopped = false;
  1040. }
  1041. }
  1042. public IScriptApi GetApi(string name)
  1043. {
  1044. if (m_Apis.ContainsKey(name))
  1045. {
  1046. // m_log.DebugFormat("[SCRIPT INSTANCE]: Found api {0} in {1}@{2}", name, ScriptName, PrimName);
  1047. return m_Apis[name];
  1048. }
  1049. // m_log.DebugFormat("[SCRIPT INSTANCE]: Did not find api {0} in {1}@{2}", name, ScriptName, PrimName);
  1050. return null;
  1051. }
  1052. public override string ToString()
  1053. {
  1054. return String.Format("{0} {1} on {2}", ScriptName, ItemID, PrimName);
  1055. }
  1056. string FormatException(Exception e)
  1057. {
  1058. if (e.InnerException == null) // Not a normal runtime error
  1059. return e.ToString();
  1060. string message = "Runtime error:\n" + e.InnerException.StackTrace;
  1061. string[] lines = message.Split(new char[] {'\n'});
  1062. foreach (string line in lines)
  1063. {
  1064. if (line.Contains("SecondLife.Script"))
  1065. {
  1066. int idx = line.IndexOf(':');
  1067. if (idx != -1)
  1068. {
  1069. string val = line.Substring(idx+1);
  1070. int lineNum = 0;
  1071. if (int.TryParse(val, out lineNum))
  1072. {
  1073. KeyValuePair<int, int> pos =
  1074. Compiler.FindErrorPosition(
  1075. lineNum, 0, LineMap);
  1076. int scriptLine = pos.Key;
  1077. int col = pos.Value;
  1078. if (scriptLine == 0)
  1079. scriptLine++;
  1080. if (col == 0)
  1081. col++;
  1082. message = string.Format("Runtime error:\n" +
  1083. "({0}): {1}", scriptLine - 1,
  1084. e.InnerException.Message);
  1085. return message;
  1086. }
  1087. }
  1088. }
  1089. }
  1090. // m_log.ErrorFormat("Scripting exception:");
  1091. // m_log.ErrorFormat(e.ToString());
  1092. return e.ToString();
  1093. }
  1094. public string GetAssemblyName()
  1095. {
  1096. return m_assemblyPath;
  1097. }
  1098. public string GetXMLState()
  1099. {
  1100. bool run = Running;
  1101. Stop(100);
  1102. Running = run;
  1103. // We should not be doing this, but since we are about to
  1104. // dispose this, it really doesn't make a difference
  1105. // This is meant to work around a Windows only race
  1106. //
  1107. m_InEvent = false;
  1108. // Force an update of the in-memory plugin data
  1109. //
  1110. PluginData = AsyncCommandManager.GetSerializationData(Engine, ItemID);
  1111. return ScriptSerializer.Serialize(this);
  1112. }
  1113. public UUID RegionID
  1114. {
  1115. get { return m_RegionID; }
  1116. }
  1117. public void Suspend()
  1118. {
  1119. Suspended = true;
  1120. }
  1121. public void Resume()
  1122. {
  1123. Suspended = false;
  1124. }
  1125. }
  1126. /// <summary>
  1127. /// Xengine event wait handle.
  1128. /// </summary>
  1129. /// <remarks>
  1130. /// This class exists becase XEngineScriptBase gets a reference to this wait handle. We need to make sure that
  1131. /// when scripts are running in different AppDomains the lease does not expire.
  1132. /// FIXME: Like LSL_Api, etc., this effectively leaks memory since the GC will never collect it. To avoid this,
  1133. /// proper remoting sponsorship needs to be implemented across the board.
  1134. /// </remarks>
  1135. public class XEngineEventWaitHandle : EventWaitHandle
  1136. {
  1137. public XEngineEventWaitHandle(bool initialState, EventResetMode mode) : base(initialState, mode) {}
  1138. public override Object InitializeLifetimeService()
  1139. {
  1140. return null;
  1141. }
  1142. }
  1143. }