ScriptInstance.cs 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347
  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. // // m_log.Debug("[Script] Script instance created");
  257. Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State));
  258. }
  259. catch (Exception e)
  260. {
  261. m_log.ErrorFormat(
  262. "[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}",
  263. ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, e.Message, e.StackTrace);
  264. return false;
  265. }
  266. // For attachments, XEngine saves the state into a .state file when XEngine.SetXMLState() is called.
  267. string savedState = Path.Combine(m_dataPath, ItemID.ToString() + ".state");
  268. if (File.Exists(savedState))
  269. {
  270. // m_log.DebugFormat(
  271. // "[SCRIPT INSTANCE]: Found state for script {0} for {1} ({2}) at {3} in {4}",
  272. // ItemID, savedState, Part.Name, Part.ParentGroup.Name, Part.ParentGroup.Scene.Name);
  273. string xml = String.Empty;
  274. try
  275. {
  276. FileInfo fi = new FileInfo(savedState);
  277. int size = (int)fi.Length;
  278. if (size < 512000)
  279. {
  280. using (FileStream fs = File.Open(savedState,
  281. FileMode.Open, FileAccess.Read, FileShare.None))
  282. {
  283. Byte[] data = new Byte[size];
  284. fs.Read(data, 0, size);
  285. xml = Encoding.UTF8.GetString(data);
  286. ScriptSerializer.Deserialize(xml, this);
  287. AsyncCommandManager.CreateFromData(Engine,
  288. LocalID, ItemID, ObjectID,
  289. PluginData);
  290. // m_log.DebugFormat("[Script] Successfully retrieved state for script {0}.{1}", PrimName, m_ScriptName);
  291. Part.SetScriptEvents(ItemID,
  292. (int)m_Script.GetStateEventFlags(State));
  293. if (!Running)
  294. m_startOnInit = false;
  295. Running = false;
  296. // we get new rez events on sim restart, too
  297. // but if there is state, then we fire the change
  298. // event
  299. // We loaded state, don't force a re-save
  300. m_SaveState = false;
  301. m_startedFromSavedState = true;
  302. }
  303. // If this script is in an attachment then we no longer need the state file.
  304. if (!StatePersistedHere)
  305. RemoveState();
  306. }
  307. // else
  308. // {
  309. // m_log.WarnFormat(
  310. // "[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.",
  311. // ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, savedState);
  312. // }
  313. }
  314. catch (Exception e)
  315. {
  316. m_log.ErrorFormat(
  317. "[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}",
  318. ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, savedState, xml, e.Message, e.StackTrace);
  319. }
  320. }
  321. // else
  322. // {
  323. // m_log.DebugFormat(
  324. // "[SCRIPT INSTANCE]: Did not find state for script {0} for {1} ({2}) at {3} in {4}",
  325. // ItemID, savedState, Part.Name, Part.ParentGroup.Name, Part.ParentGroup.Scene.Name);
  326. // }
  327. return true;
  328. }
  329. public void Init()
  330. {
  331. if (ShuttingDown)
  332. return;
  333. if (m_startedFromSavedState)
  334. {
  335. if (m_startOnInit)
  336. Start();
  337. if (m_postOnRez)
  338. {
  339. PostEvent(new EventParams("on_rez",
  340. new Object[] {new LSL_Types.LSLInteger(StartParam)}, new DetectParams[0]));
  341. }
  342. if (m_stateSource == StateSource.AttachedRez)
  343. {
  344. PostEvent(new EventParams("attach",
  345. new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0]));
  346. }
  347. else if (m_stateSource == StateSource.RegionStart)
  348. {
  349. //m_log.Debug("[Script] Posted changed(CHANGED_REGION_RESTART) to script");
  350. PostEvent(new EventParams("changed",
  351. new Object[] { new LSL_Types.LSLInteger((int)Changed.REGION_RESTART) }, new DetectParams[0]));
  352. }
  353. else if (m_stateSource == StateSource.PrimCrossing || m_stateSource == StateSource.Teleporting)
  354. {
  355. // CHANGED_REGION
  356. PostEvent(new EventParams("changed",
  357. new Object[] { new LSL_Types.LSLInteger((int)Changed.REGION) }, new DetectParams[0]));
  358. // CHANGED_TELEPORT
  359. if (m_stateSource == StateSource.Teleporting)
  360. PostEvent(new EventParams("changed",
  361. new Object[] { new LSL_Types.LSLInteger((int)Changed.TELEPORT) }, new DetectParams[0]));
  362. }
  363. }
  364. else
  365. {
  366. if (m_startOnInit)
  367. Start();
  368. PostEvent(new EventParams("state_entry",
  369. new Object[0], new DetectParams[0]));
  370. if (m_postOnRez)
  371. {
  372. PostEvent(new EventParams("on_rez",
  373. new Object[] {new LSL_Types.LSLInteger(StartParam)}, new DetectParams[0]));
  374. }
  375. if (m_stateSource == StateSource.AttachedRez)
  376. {
  377. PostEvent(new EventParams("attach",
  378. new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0]));
  379. }
  380. }
  381. }
  382. private void ReleaseControls()
  383. {
  384. SceneObjectPart part = Engine.World.GetSceneObjectPart(LocalID);
  385. if (part != null)
  386. {
  387. int permsMask;
  388. UUID permsGranter;
  389. part.TaskInventory.LockItemsForRead(true);
  390. if (!part.TaskInventory.ContainsKey(ItemID))
  391. {
  392. part.TaskInventory.LockItemsForRead(false);
  393. return;
  394. }
  395. permsGranter = part.TaskInventory[ItemID].PermsGranter;
  396. permsMask = part.TaskInventory[ItemID].PermsMask;
  397. part.TaskInventory.LockItemsForRead(false);
  398. if ((permsMask & ScriptBaseClass.PERMISSION_TAKE_CONTROLS) != 0)
  399. {
  400. ScenePresence presence = Engine.World.GetScenePresence(permsGranter);
  401. if (presence != null)
  402. presence.UnRegisterControlEventsToScript(LocalID, ItemID);
  403. }
  404. }
  405. }
  406. public void DestroyScriptInstance()
  407. {
  408. ReleaseControls();
  409. AsyncCommandManager.RemoveScript(Engine, LocalID, ItemID);
  410. SceneObjectPart part = Engine.World.GetSceneObjectPart(LocalID);
  411. if (part != null)
  412. part.RemoveScriptEvents(ItemID);
  413. }
  414. public void RemoveState()
  415. {
  416. string savedState = Path.Combine(m_dataPath, ItemID.ToString() + ".state");
  417. // m_log.DebugFormat(
  418. // "[SCRIPT INSTANCE]: Deleting state {0} for script {1} (id {2}) in part {3} (id {4}) in object {5} in {6}.",
  419. // savedState, ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name);
  420. try
  421. {
  422. File.Delete(savedState);
  423. }
  424. catch (Exception e)
  425. {
  426. m_log.Warn(
  427. string.Format(
  428. "[SCRIPT INSTANCE]: Could not delete script state {0} for script {1} (id {2}) in part {3} (id {4}) in object {5} in {6}. Exception ",
  429. savedState, ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name),
  430. e);
  431. }
  432. }
  433. public void VarDump(Dictionary<string, object> vars)
  434. {
  435. // m_log.Info("Variable dump for script "+ ItemID.ToString());
  436. // foreach (KeyValuePair<string, object> v in vars)
  437. // {
  438. // m_log.Info("Variable: "+v.Key+" = "+v.Value.ToString());
  439. // }
  440. }
  441. public void Start()
  442. {
  443. lock (EventQueue)
  444. {
  445. if (Running)
  446. return;
  447. Running = true;
  448. TimeStarted = DateTime.Now;
  449. // Note: we don't reset ExecutionTime. The reason is that runaway scripts are stopped and restarted
  450. // automatically, and we *do* want to show that they had high CPU in that case. If we had reset
  451. // ExecutionTime here then runaway scripts, paradoxically, would never show up in the "Top Scripts" dialog.
  452. if (EventQueue.Count > 0)
  453. {
  454. if (m_CurrentWorkItem == null)
  455. m_CurrentWorkItem = Engine.QueueEventHandler(this);
  456. // else
  457. // m_log.Error("[Script] Tried to start a script that was already queued");
  458. }
  459. }
  460. }
  461. public bool Stop(int timeout, bool clearEventQueue = false)
  462. {
  463. if (DebugLevel >= 1)
  464. m_log.DebugFormat(
  465. "[SCRIPT INSTANCE]: Stopping script {0} {1} in {2} {3} with timeout {4} {5} {6}",
  466. ScriptName, ItemID, PrimName, ObjectID, timeout, m_InSelfDelete, DateTime.Now.Ticks);
  467. IScriptWorkItem workItem;
  468. lock (EventQueue)
  469. {
  470. if (clearEventQueue)
  471. ClearQueue();
  472. if (!Running)
  473. return true;
  474. // If we're not running or waiting to run an event then we can safely stop.
  475. if (m_CurrentWorkItem == null)
  476. {
  477. Running = false;
  478. return true;
  479. }
  480. // If we are waiting to run an event then we can try to cancel it.
  481. if (m_CurrentWorkItem.Cancel())
  482. {
  483. m_CurrentWorkItem = null;
  484. Running = false;
  485. return true;
  486. }
  487. workItem = m_CurrentWorkItem;
  488. Running = false;
  489. }
  490. // Wait for the current event to complete.
  491. if (!m_InSelfDelete)
  492. {
  493. if (!m_coopTermination)
  494. {
  495. // If we're not co-operative terminating then try and wait for the event to complete before stopping
  496. if (workItem.Wait(timeout))
  497. return true;
  498. }
  499. else
  500. {
  501. if (DebugLevel >= 1)
  502. m_log.DebugFormat(
  503. "[SCRIPT INSTANCE]: Co-operatively stopping script {0} {1} in {2} {3}",
  504. ScriptName, ItemID, PrimName, ObjectID);
  505. // This will terminate the event on next handle check by the script.
  506. m_coopSleepHandle.Set();
  507. // For now, we will wait forever since the event should always cleanly terminate once LSL loop
  508. // checking is implemented. May want to allow a shorter timeout option later.
  509. if (workItem.Wait(Timeout.Infinite))
  510. {
  511. if (DebugLevel >= 1)
  512. m_log.DebugFormat(
  513. "[SCRIPT INSTANCE]: Co-operatively stopped script {0} {1} in {2} {3}",
  514. ScriptName, ItemID, PrimName, ObjectID);
  515. return true;
  516. }
  517. }
  518. }
  519. lock (EventQueue)
  520. {
  521. workItem = m_CurrentWorkItem;
  522. }
  523. if (workItem == null)
  524. return true;
  525. // If the event still hasn't stopped and we the stop isn't the result of script or object removal, then
  526. // forcibly abort the work item (this aborts the underlying thread).
  527. // Co-operative termination should never reach this point.
  528. if (!m_InSelfDelete)
  529. {
  530. m_log.DebugFormat(
  531. "[SCRIPT INSTANCE]: Aborting unstopped script {0} {1} in prim {2}, localID {3}, timeout was {4} ms",
  532. ScriptName, ItemID, PrimName, LocalID, timeout);
  533. workItem.Abort();
  534. }
  535. lock (EventQueue)
  536. {
  537. m_CurrentWorkItem = null;
  538. }
  539. return true;
  540. }
  541. [DebuggerNonUserCode] //Prevents the debugger from farting in this function
  542. public void SetState(string state)
  543. {
  544. if (state == State)
  545. return;
  546. EventParams lastTimerEv = null;
  547. lock (EventQueue)
  548. {
  549. // Remove all queued events, remembering the last timer event
  550. while (EventQueue.Count > 0)
  551. {
  552. EventParams tempv = (EventParams)EventQueue.Dequeue();
  553. if (tempv.EventName == "timer") lastTimerEv = tempv;
  554. }
  555. // Post events
  556. PostEvent(new EventParams("state_exit", new Object[0],
  557. new DetectParams[0]));
  558. PostEvent(new EventParams("state", new Object[] { state },
  559. new DetectParams[0]));
  560. PostEvent(new EventParams("state_entry", new Object[0],
  561. new DetectParams[0]));
  562. // Requeue the timer event after the state changing events
  563. if (lastTimerEv != null) EventQueue.Enqueue(lastTimerEv);
  564. // This will stop events from being queued and processed
  565. // until the new state is started
  566. m_StateChangeInProgress = true;
  567. }
  568. throw new EventAbortException();
  569. }
  570. /// <summary>
  571. /// Post an event to this script instance.
  572. /// </summary>
  573. /// <remarks>
  574. /// The request to run the event is sent
  575. /// </remarks>
  576. /// <param name="data"></param>
  577. public void PostEvent(EventParams data)
  578. {
  579. // m_log.DebugFormat("[Script] Posted event {2} in state {3} to {0}.{1}",
  580. // PrimName, ScriptName, data.EventName, State);
  581. if (!Running)
  582. return;
  583. // If min event delay is set then ignore any events untill the time has expired
  584. // This currently only allows 1 event of any type in the given time period.
  585. // This may need extending to allow for a time for each individual event type.
  586. if (m_eventDelayTicks != 0 &&
  587. data.EventName != "state" && data.EventName != "state_entry" && data.EventName != "state_exit"
  588. && data.EventName != "run_time_permissions" && data.EventName != "http_request" && data.EventName != "link_message")
  589. {
  590. if (DateTime.Now.Ticks < m_nextEventTimeTicks)
  591. return;
  592. m_nextEventTimeTicks = DateTime.Now.Ticks + m_eventDelayTicks;
  593. }
  594. lock (EventQueue)
  595. {
  596. // The only events that persist across state changes are timers
  597. if (m_StateChangeInProgress && data.EventName != "timer")
  598. return;
  599. if (EventQueue.Count >= m_MaxScriptQueue)
  600. return;
  601. if (data.EventName == "timer")
  602. {
  603. if (m_TimerQueued)
  604. return;
  605. m_TimerQueued = true;
  606. }
  607. if (data.EventName == "control")
  608. {
  609. int held = ((LSL_Types.LSLInteger)data.Params[1]).value;
  610. // int changed = ((LSL_Types.LSLInteger)data.Params[2]).value;
  611. // If the last message was a 0 (nothing held)
  612. // and this one is also nothing held, drop it
  613. //
  614. if (m_LastControlLevel == held && held == 0)
  615. return;
  616. // If there is one or more queued, then queue
  617. // only changed ones, else queue unconditionally
  618. //
  619. if (m_ControlEventsInQueue > 0)
  620. {
  621. if (m_LastControlLevel == held)
  622. return;
  623. }
  624. m_LastControlLevel = held;
  625. m_ControlEventsInQueue++;
  626. }
  627. if (data.EventName == "collision")
  628. {
  629. if (m_CollisionInQueue)
  630. return;
  631. if (data.DetectParams == null)
  632. return;
  633. m_CollisionInQueue = true;
  634. }
  635. EventQueue.Enqueue(data);
  636. if (m_CurrentWorkItem == null)
  637. {
  638. m_CurrentWorkItem = Engine.QueueEventHandler(this);
  639. }
  640. }
  641. }
  642. /// <summary>
  643. /// Process the next event queued for this script
  644. /// </summary>
  645. /// <returns></returns>
  646. public object EventProcessor()
  647. {
  648. // We check here as the thread stopping this instance from running may itself hold the m_Script lock.
  649. if (!Running)
  650. return 0;
  651. lock (m_Script)
  652. {
  653. // m_log.DebugFormat("[XEngine]: EventProcessor() invoked for {0}.{1}", PrimName, ScriptName);
  654. if (Suspended)
  655. return 0;
  656. ExecutionTimer.Restart();
  657. try
  658. {
  659. return EventProcessorInt();
  660. }
  661. finally
  662. {
  663. ExecutionTimer.Stop();
  664. ExecutionTime.AddSample(ExecutionTimer);
  665. Part.ParentGroup.Scene.AddScriptExecutionTime(ExecutionTimer.ElapsedTicks);
  666. }
  667. }
  668. }
  669. private object EventProcessorInt()
  670. {
  671. EventParams data = null;
  672. lock (EventQueue)
  673. {
  674. data = (EventParams)EventQueue.Dequeue();
  675. if (data == null)
  676. {
  677. // check if a null event was enqueued or if its really empty
  678. if (EventQueue.Count > 0 && Running && !ShuttingDown && !m_InSelfDelete)
  679. {
  680. m_CurrentWorkItem = Engine.QueueEventHandler(this);
  681. }
  682. else
  683. {
  684. m_CurrentWorkItem = null;
  685. }
  686. return 0;
  687. }
  688. if (data.EventName == "timer")
  689. m_TimerQueued = false;
  690. if (data.EventName == "control")
  691. {
  692. if (m_ControlEventsInQueue > 0)
  693. m_ControlEventsInQueue--;
  694. }
  695. if (data.EventName == "collision")
  696. m_CollisionInQueue = false;
  697. }
  698. if (DebugLevel >= 2)
  699. m_log.DebugFormat(
  700. "[SCRIPT INSTANCE]: Processing event {0} for {1}/{2}({3})/{4}({5}) @ {6}/{7}",
  701. data.EventName,
  702. ScriptName,
  703. Part.Name,
  704. Part.LocalId,
  705. Part.ParentGroup.Name,
  706. Part.ParentGroup.UUID,
  707. Part.AbsolutePosition,
  708. Part.ParentGroup.Scene.Name);
  709. m_DetectParams = data.DetectParams;
  710. if (data.EventName == "state") // Hardcoded state change
  711. {
  712. State = data.Params[0].ToString();
  713. if (DebugLevel >= 1)
  714. m_log.DebugFormat(
  715. "[SCRIPT INSTANCE]: Changing state to {0} for {1}/{2}({3})/{4}({5}) @ {6}/{7}",
  716. State,
  717. ScriptName,
  718. Part.Name,
  719. Part.LocalId,
  720. Part.ParentGroup.Name,
  721. Part.ParentGroup.UUID,
  722. Part.AbsolutePosition,
  723. Part.ParentGroup.Scene.Name);
  724. AsyncCommandManager.StateChange(Engine,
  725. LocalID, ItemID);
  726. // we are effectively in the new state now, so we can resume queueing
  727. // and processing other non-timer events
  728. m_StateChangeInProgress = false;
  729. Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State));
  730. }
  731. else
  732. {
  733. Exception e = null;
  734. if (Engine.World.PipeEventsForScript(LocalID) ||
  735. data.EventName == "control") // Don't freeze avies!
  736. {
  737. // m_log.DebugFormat("[Script] Delivered event {2} in state {3} to {0}.{1}",
  738. // PrimName, ScriptName, data.EventName, State);
  739. try
  740. {
  741. m_CurrentEvent = data.EventName;
  742. m_EventStart = DateTime.UtcNow;
  743. m_InEvent = true;
  744. try
  745. {
  746. m_Script.ExecuteEvent(State, data.EventName, data.Params);
  747. }
  748. finally
  749. {
  750. m_InEvent = false;
  751. m_CurrentEvent = String.Empty;
  752. lock (EventQueue)
  753. m_CurrentWorkItem = null; // no longer in a event that can be canceled
  754. }
  755. if (m_SaveState)
  756. {
  757. // This will be the very first event we deliver
  758. // (state_entry) in default state
  759. //
  760. SaveState();
  761. m_SaveState = false;
  762. }
  763. }
  764. catch (Exception exx)
  765. {
  766. e = exx;
  767. }
  768. if(e != null)
  769. {
  770. // m_log.DebugFormat(
  771. // "[SCRIPT] Exception in script {0} {1}: {2}{3}",
  772. // ScriptName, ItemID, e.Message, e.StackTrace);
  773. if ((!(e is TargetInvocationException)
  774. || (!(e.InnerException is SelfDeleteException)
  775. && !(e.InnerException is ScriptDeleteException)
  776. && !(e.InnerException is ScriptCoopStopException)))
  777. && !(e is ThreadAbortException))
  778. {
  779. try
  780. {
  781. if(e.InnerException != null && e.InnerException is ScriptException)
  782. {
  783. bool toowner = false;
  784. string text = e.InnerException.Message;
  785. if(text.StartsWith("(OWNER)"))
  786. {
  787. text = text.Substring(7);
  788. toowner = true;
  789. }
  790. text += "(script: " + ScriptName +
  791. " event: " + data.EventName +
  792. " primID:" + Part.UUID.ToString() +
  793. " at " + Part.AbsolutePosition + ")";
  794. if (text.Length > 1000)
  795. text = text.Substring(0, 1000);
  796. if (toowner)
  797. {
  798. ScenePresence sp = Engine.World.GetScenePresence(Part.OwnerID);
  799. if (sp != null && !sp.IsNPC)
  800. Engine.World.SimChatToAgent(Part.OwnerID, Utils.StringToBytes(text), 0x7FFFFFFF, Part.AbsolutePosition,
  801. Part.Name, Part.UUID, false);
  802. }
  803. else
  804. Engine.World.SimChat(Utils.StringToBytes(text),
  805. ChatTypeEnum.DebugChannel, 2147483647,
  806. Part.AbsolutePosition,
  807. Part.Name, Part.UUID, false);
  808. m_log.Debug(string.Format(
  809. "[SCRIPT ERROR]: {0} (at event {1}, part {2} {3} at {4} in {5}",
  810. e.InnerException.Message,
  811. data.EventName,
  812. PrimName,
  813. Part.UUID,
  814. Part.AbsolutePosition,
  815. Part.ParentGroup.Scene.Name));
  816. }
  817. else
  818. {
  819. // DISPLAY ERROR INWORLD
  820. string text = FormatException(e);
  821. if (text.Length > 1000)
  822. text = text.Substring(0, 1000);
  823. Engine.World.SimChat(Utils.StringToBytes(text),
  824. ChatTypeEnum.DebugChannel, 2147483647,
  825. Part.AbsolutePosition,
  826. Part.Name, Part.UUID, false);
  827. m_log.Debug(string.Format(
  828. "[SCRIPT ERROR]: Runtime error in script {0} (event {1}), part {2} {3} at {4} in {5} ",
  829. ScriptName,
  830. data.EventName,
  831. PrimName,
  832. Part.UUID,
  833. Part.AbsolutePosition,
  834. Part.ParentGroup.Scene.Name),
  835. e);
  836. }
  837. }
  838. catch (Exception)
  839. {
  840. }
  841. }
  842. else if ((e is TargetInvocationException) && (e.InnerException is SelfDeleteException))
  843. {
  844. m_InSelfDelete = true;
  845. Engine.World.DeleteSceneObject(Part.ParentGroup, false);
  846. }
  847. else if ((e is TargetInvocationException) && (e.InnerException is ScriptDeleteException))
  848. {
  849. m_InSelfDelete = true;
  850. Part.Inventory.RemoveInventoryItem(ItemID);
  851. }
  852. else if ((e is TargetInvocationException) && (e.InnerException is ScriptCoopStopException))
  853. {
  854. if (DebugLevel >= 1)
  855. m_log.DebugFormat(
  856. "[SCRIPT INSTANCE]: Script {0}.{1} in event {2}, state {3} stopped co-operatively.",
  857. PrimName, ScriptName, data.EventName, State);
  858. }
  859. }
  860. }
  861. }
  862. // If there are more events and we are currently running and not shutting down, then ask the
  863. // script engine to run the next event.
  864. lock (EventQueue)
  865. {
  866. // Increase processed events counter and prevent wrap;
  867. if (++EventsProcessed == 1000000)
  868. EventsProcessed = 100000;
  869. if ((EventsProcessed % 100000) == 0 && DebugLevel > 0)
  870. {
  871. 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",
  872. ScriptTask.Name,
  873. Part.ParentGroup.Name, Part.ParentGroup.UUID, Part.ParentGroup.AbsolutePosition, Part.ParentGroup.Scene.Name,
  874. ScriptTask.ItemID, ScriptTask.AssetID, data.EventName, EventsProcessed);
  875. }
  876. if (EventQueue.Count > 0 && Running && !ShuttingDown && !m_InSelfDelete)
  877. {
  878. m_CurrentWorkItem = Engine.QueueEventHandler(this);
  879. }
  880. else
  881. {
  882. m_CurrentWorkItem = null;
  883. }
  884. }
  885. m_DetectParams = null;
  886. return 0;
  887. }
  888. public int EventTime()
  889. {
  890. if (!m_InEvent)
  891. return 0;
  892. return (DateTime.UtcNow - m_EventStart).Seconds;
  893. }
  894. public void ResetScript(int timeout)
  895. {
  896. if (m_Script == null)
  897. return;
  898. bool running = Running;
  899. RemoveState();
  900. ReleaseControls();
  901. Stop(timeout);
  902. SceneObjectPart part = Engine.World.GetSceneObjectPart(LocalID);
  903. part.Inventory.GetInventoryItem(ItemID).PermsMask = 0;
  904. part.Inventory.GetInventoryItem(ItemID).PermsGranter = UUID.Zero;
  905. part.CollisionSound = UUID.Zero;
  906. AsyncCommandManager.RemoveScript(Engine, LocalID, ItemID);
  907. m_TimerQueued = false;
  908. m_StateChangeInProgress = false;
  909. EventQueue.Clear();
  910. m_Script.ResetVars();
  911. StartParam = 0;
  912. State = "default";
  913. part.SetScriptEvents(ItemID,
  914. (int)m_Script.GetStateEventFlags(State));
  915. if (running)
  916. Start();
  917. m_SaveState = StatePersistedHere;
  918. PostEvent(new EventParams("state_entry",
  919. new Object[0], new DetectParams[0]));
  920. }
  921. [DebuggerNonUserCode] //Stops the VS debugger from farting in this function
  922. public void ApiResetScript()
  923. {
  924. // bool running = Running;
  925. RemoveState();
  926. ReleaseControls();
  927. m_Script.ResetVars();
  928. SceneObjectPart part = Engine.World.GetSceneObjectPart(LocalID);
  929. part.Inventory.GetInventoryItem(ItemID).PermsMask = 0;
  930. part.Inventory.GetInventoryItem(ItemID).PermsGranter = UUID.Zero;
  931. part.CollisionSound = UUID.Zero;
  932. AsyncCommandManager.RemoveScript(Engine, LocalID, ItemID);
  933. m_TimerQueued = false;
  934. m_StateChangeInProgress = false;
  935. EventQueue.Clear();
  936. m_Script.ResetVars();
  937. string oldState = State;
  938. StartParam = 0;
  939. State = "default";
  940. part.SetScriptEvents(ItemID,
  941. (int)m_Script.GetStateEventFlags(State));
  942. if (m_CurrentEvent != "state_entry" || oldState != "default")
  943. {
  944. m_SaveState = StatePersistedHere;
  945. PostEvent(new EventParams("state_entry",
  946. new Object[0], new DetectParams[0]));
  947. throw new EventAbortException();
  948. }
  949. }
  950. public Dictionary<string, object> GetVars()
  951. {
  952. if (m_Script != null)
  953. return m_Script.GetVars();
  954. else
  955. return new Dictionary<string, object>();
  956. }
  957. public void SetVars(Dictionary<string, object> vars)
  958. {
  959. // foreach (KeyValuePair<string, object> kvp in vars)
  960. // m_log.DebugFormat("[SCRIPT INSTANCE]: Setting var {0}={1}", kvp.Key, kvp.Value);
  961. m_Script.SetVars(vars);
  962. }
  963. public DetectParams GetDetectParams(int idx)
  964. {
  965. if (m_DetectParams == null)
  966. return null;
  967. if (idx < 0 || idx >= m_DetectParams.Length)
  968. return null;
  969. return m_DetectParams[idx];
  970. }
  971. public UUID GetDetectID(int idx)
  972. {
  973. if (m_DetectParams == null)
  974. return UUID.Zero;
  975. if (idx < 0 || idx >= m_DetectParams.Length)
  976. return UUID.Zero;
  977. return m_DetectParams[idx].Key;
  978. }
  979. public void SaveState()
  980. {
  981. if (!Running && !StayStopped)
  982. return;
  983. // We cannot call this inside the EventQueue lock since it will currently take AsyncCommandManager.staticLock.
  984. // This may already be held by AsyncCommandManager.DoOneCmdHandlerPass() which in turn can take EventQueue
  985. // lock via ScriptInstance.PostEvent().
  986. PluginData = AsyncCommandManager.GetSerializationData(Engine, ItemID);
  987. // We need to lock here to avoid any race with a thread that is removing this script.
  988. lock (EventQueue)
  989. {
  990. // Check again to avoid a race with a thread in Stop()
  991. if (!Running && !StayStopped)
  992. return;
  993. // If we're currently in an event, just tell it to save upon return
  994. //
  995. if (m_InEvent)
  996. {
  997. m_SaveState = true;
  998. return;
  999. }
  1000. // m_log.DebugFormat(
  1001. // "[SCRIPT INSTANCE]: Saving state for script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}",
  1002. // ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name);
  1003. string xml = ScriptSerializer.Serialize(this);
  1004. // Compare hash of the state we just just created with the state last written to disk
  1005. // If the state is different, update the disk file.
  1006. UUID hash = UUID.Parse(Utils.MD5String(xml));
  1007. if (hash != m_CurrentStateHash)
  1008. {
  1009. try
  1010. {
  1011. using (FileStream fs = File.Create(Path.Combine(m_dataPath, ItemID.ToString() + ".state")))
  1012. {
  1013. Byte[] buf = Util.UTF8NoBomEncoding.GetBytes(xml);
  1014. fs.Write(buf, 0, buf.Length);
  1015. }
  1016. }
  1017. catch(Exception)
  1018. {
  1019. // m_log.Error("Unable to save xml\n"+e.ToString());
  1020. }
  1021. //if (!File.Exists(Path.Combine(Path.GetDirectoryName(assembly), ItemID.ToString() + ".state")))
  1022. //{
  1023. // throw new Exception("Completed persistence save, but no file was created");
  1024. //}
  1025. m_CurrentStateHash = hash;
  1026. }
  1027. StayStopped = false;
  1028. }
  1029. }
  1030. public IScriptApi GetApi(string name)
  1031. {
  1032. if (m_Apis.ContainsKey(name))
  1033. {
  1034. // m_log.DebugFormat("[SCRIPT INSTANCE]: Found api {0} in {1}@{2}", name, ScriptName, PrimName);
  1035. return m_Apis[name];
  1036. }
  1037. // m_log.DebugFormat("[SCRIPT INSTANCE]: Did not find api {0} in {1}@{2}", name, ScriptName, PrimName);
  1038. return null;
  1039. }
  1040. public override string ToString()
  1041. {
  1042. return String.Format("{0} {1} on {2}", ScriptName, ItemID, PrimName);
  1043. }
  1044. string FormatException(Exception e)
  1045. {
  1046. if (e.InnerException == null) // Not a normal runtime error
  1047. return e.ToString();
  1048. string message = "Runtime error:\n" + e.InnerException.StackTrace;
  1049. string[] lines = message.Split(new char[] {'\n'});
  1050. foreach (string line in lines)
  1051. {
  1052. if (line.Contains("SecondLife.Script"))
  1053. {
  1054. int idx = line.IndexOf(':');
  1055. if (idx != -1)
  1056. {
  1057. string val = line.Substring(idx+1);
  1058. int lineNum = 0;
  1059. if (int.TryParse(val, out lineNum))
  1060. {
  1061. KeyValuePair<int, int> pos =
  1062. Compiler.FindErrorPosition(
  1063. lineNum, 0, LineMap);
  1064. int scriptLine = pos.Key;
  1065. int col = pos.Value;
  1066. if (scriptLine == 0)
  1067. scriptLine++;
  1068. if (col == 0)
  1069. col++;
  1070. message = string.Format("Runtime error:\n" +
  1071. "({0}): {1}", scriptLine - 1,
  1072. e.InnerException.Message);
  1073. return message;
  1074. }
  1075. }
  1076. }
  1077. }
  1078. // m_log.ErrorFormat("Scripting exception:");
  1079. // m_log.ErrorFormat(e.ToString());
  1080. return e.ToString();
  1081. }
  1082. public string GetAssemblyName()
  1083. {
  1084. return m_assemblyPath;
  1085. }
  1086. public string GetXMLState()
  1087. {
  1088. bool run = Running;
  1089. Stop(100);
  1090. Running = run;
  1091. // We should not be doing this, but since we are about to
  1092. // dispose this, it really doesn't make a difference
  1093. // This is meant to work around a Windows only race
  1094. //
  1095. m_InEvent = false;
  1096. // Force an update of the in-memory plugin data
  1097. //
  1098. PluginData = AsyncCommandManager.GetSerializationData(Engine, ItemID);
  1099. return ScriptSerializer.Serialize(this);
  1100. }
  1101. public UUID RegionID
  1102. {
  1103. get { return m_RegionID; }
  1104. }
  1105. public void Suspend()
  1106. {
  1107. Suspended = true;
  1108. }
  1109. public void Resume()
  1110. {
  1111. Suspended = false;
  1112. }
  1113. }
  1114. /// <summary>
  1115. /// Xengine event wait handle.
  1116. /// </summary>
  1117. /// <remarks>
  1118. /// This class exists becase XEngineScriptBase gets a reference to this wait handle. We need to make sure that
  1119. /// when scripts are running in different AppDomains the lease does not expire.
  1120. /// FIXME: Like LSL_Api, etc., this effectively leaks memory since the GC will never collect it. To avoid this,
  1121. /// proper remoting sponsorship needs to be implemented across the board.
  1122. /// </remarks>
  1123. public class XEngineEventWaitHandle : EventWaitHandle
  1124. {
  1125. public XEngineEventWaitHandle(bool initialState, EventResetMode mode) : base(initialState, mode) {}
  1126. public override Object InitializeLifetimeService()
  1127. {
  1128. return null;
  1129. }
  1130. }
  1131. }