ScriptInstance.cs 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222
  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. namespace OpenSim.Region.ScriptEngine.Shared.Instance
  54. {
  55. public class ScriptInstance : MarshalByRefObject, IScriptInstance
  56. {
  57. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  58. /// <summary>
  59. /// The current work item if an event for this script is running or waiting to run,
  60. /// </summary>
  61. /// <remarks>
  62. /// Null if there is no running or waiting to run event. Must be changed only under an EventQueue lock.
  63. /// </remarks>
  64. private IScriptWorkItem m_CurrentWorkItem;
  65. private IScript m_Script;
  66. private DetectParams[] m_DetectParams;
  67. private bool m_TimerQueued;
  68. private DateTime m_EventStart;
  69. private bool m_InEvent;
  70. private string m_Assembly;
  71. private string m_CurrentEvent = String.Empty;
  72. private bool m_InSelfDelete;
  73. private int m_MaxScriptQueue;
  74. private bool m_SaveState = true;
  75. private int m_ControlEventsInQueue;
  76. private int m_LastControlLevel;
  77. private bool m_CollisionInQueue;
  78. // The following is for setting a minimum delay between events
  79. private double m_minEventDelay;
  80. private long m_eventDelayTicks;
  81. private long m_nextEventTimeTicks;
  82. private bool m_startOnInit = true;
  83. private UUID m_AttachedAvatar;
  84. private StateSource m_stateSource;
  85. private bool m_postOnRez;
  86. private bool m_startedFromSavedState;
  87. private UUID m_CurrentStateHash;
  88. private UUID m_RegionID;
  89. public int DebugLevel { get; set; }
  90. public Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> LineMap { get; set; }
  91. private Dictionary<string,IScriptApi> m_Apis = new Dictionary<string,IScriptApi>();
  92. public Object[] PluginData = new Object[0];
  93. /// <summary>
  94. /// Used by llMinEventDelay to suppress events happening any faster than this speed.
  95. /// This currently restricts all events in one go. Not sure if each event type has
  96. /// its own check so take the simple route first.
  97. /// </summary>
  98. public double MinEventDelay
  99. {
  100. get { return m_minEventDelay; }
  101. set
  102. {
  103. if (value > 0.001)
  104. m_minEventDelay = value;
  105. else
  106. m_minEventDelay = 0.0;
  107. m_eventDelayTicks = (long)(m_minEventDelay * 10000000L);
  108. m_nextEventTimeTicks = DateTime.Now.Ticks;
  109. }
  110. }
  111. public bool Running { get; set; }
  112. public bool Suspended
  113. {
  114. get { return m_Suspended; }
  115. set
  116. {
  117. // Need to do this inside a lock in order to avoid races with EventProcessor()
  118. lock (m_Script)
  119. {
  120. bool wasSuspended = m_Suspended;
  121. m_Suspended = value;
  122. if (wasSuspended && !m_Suspended)
  123. {
  124. lock (EventQueue)
  125. {
  126. // Need to place ourselves back in a work item if there are events to process
  127. if (EventQueue.Count > 0 && Running && !ShuttingDown)
  128. m_CurrentWorkItem = Engine.QueueEventHandler(this);
  129. }
  130. }
  131. }
  132. }
  133. }
  134. private bool m_Suspended;
  135. public bool ShuttingDown { get; set; }
  136. public string State { get; set; }
  137. public IScriptEngine Engine { get; private set; }
  138. public UUID AppDomain { get; set; }
  139. public SceneObjectPart Part { get; private set; }
  140. public string PrimName { get; private set; }
  141. public string ScriptName { get; private set; }
  142. public UUID ItemID { get; private set; }
  143. public UUID ObjectID { get { return Part.UUID; } }
  144. public uint LocalID { get { return Part.LocalId; } }
  145. public UUID RootObjectID { get { return Part.ParentGroup.UUID; } }
  146. public uint RootLocalID { get { return Part.ParentGroup.LocalId; } }
  147. public UUID AssetID { get; private set; }
  148. public Queue EventQueue { get; private set; }
  149. public long EventsQueued
  150. {
  151. get
  152. {
  153. lock (EventQueue)
  154. return EventQueue.Count;
  155. }
  156. }
  157. public long EventsProcessed { get; private set; }
  158. public int StartParam { get; set; }
  159. public TaskInventoryItem ScriptTask { get; private set; }
  160. public DateTime TimeStarted { get; private set; }
  161. public long MeasurementPeriodTickStart { get; private set; }
  162. public long MeasurementPeriodExecutionTime { get; private set; }
  163. public static readonly long MaxMeasurementPeriod = 30 * TimeSpan.TicksPerMinute;
  164. private bool m_coopTermination;
  165. private EventWaitHandle m_coopSleepHandle;
  166. public void ClearQueue()
  167. {
  168. m_TimerQueued = false;
  169. EventQueue.Clear();
  170. }
  171. public ScriptInstance(
  172. IScriptEngine engine, SceneObjectPart part, TaskInventoryItem item,
  173. int startParam, bool postOnRez,
  174. int maxScriptQueue)
  175. {
  176. State = "default";
  177. EventQueue = new Queue(32);
  178. Engine = engine;
  179. Part = part;
  180. ScriptTask = item;
  181. // This is currently only here to allow regression tests to get away without specifying any inventory
  182. // item when they are testing script logic that doesn't require an item.
  183. if (ScriptTask != null)
  184. {
  185. ScriptName = ScriptTask.Name;
  186. ItemID = ScriptTask.ItemID;
  187. AssetID = ScriptTask.AssetID;
  188. }
  189. PrimName = part.ParentGroup.Name;
  190. StartParam = startParam;
  191. m_MaxScriptQueue = maxScriptQueue;
  192. m_postOnRez = postOnRez;
  193. m_AttachedAvatar = Part.ParentGroup.AttachedAvatar;
  194. m_RegionID = Part.ParentGroup.Scene.RegionInfo.RegionID;
  195. if (Engine.Config.GetString("ScriptStopStrategy", "abort") == "co-op")
  196. {
  197. m_coopTermination = true;
  198. m_coopSleepHandle = new XEngineEventWaitHandle(false, EventResetMode.AutoReset);
  199. }
  200. }
  201. /// <summary>
  202. /// Load the script from an assembly into an AppDomain.
  203. /// </summary>
  204. /// <param name='dom'></param>
  205. /// <param name='assembly'></param>
  206. /// <param name='stateSource'></param>
  207. /// <returns>false if load failed, true if suceeded</returns>
  208. public bool Load(AppDomain dom, string assembly, StateSource stateSource)
  209. {
  210. m_Assembly = assembly;
  211. m_stateSource = stateSource;
  212. ApiManager am = new ApiManager();
  213. foreach (string api in am.GetApis())
  214. {
  215. m_Apis[api] = am.CreateApi(api);
  216. m_Apis[api].Initialize(Engine, Part, ScriptTask, m_coopSleepHandle);
  217. }
  218. try
  219. {
  220. object[] constructorParams;
  221. Assembly scriptAssembly = dom.Load(Path.GetFileNameWithoutExtension(assembly));
  222. Type scriptType = scriptAssembly.GetType("SecondLife.XEngineScript");
  223. if (scriptType != null)
  224. {
  225. constructorParams = new object[] { m_coopSleepHandle };
  226. }
  227. else if (!m_coopTermination)
  228. {
  229. scriptType = scriptAssembly.GetType("SecondLife.Script");
  230. constructorParams = null;
  231. }
  232. else
  233. {
  234. m_log.ErrorFormat(
  235. "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. You must remove all existing {6}* script DLL files before using enabling co-op termination"
  236. + ", either by setting DeleteScriptsOnStartup = true in [XEngine] for one run"
  237. + " or by deleting these files manually.",
  238. ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, assembly);
  239. return false;
  240. }
  241. // m_log.DebugFormat(
  242. // "[SCRIPT INSTANCE]: Looking to load {0} from assembly {1} in {2}",
  243. // scriptType.FullName, Path.GetFileNameWithoutExtension(assembly), Engine.World.Name);
  244. if (dom != System.AppDomain.CurrentDomain)
  245. m_Script
  246. = (IScript)dom.CreateInstanceAndUnwrap(
  247. Path.GetFileNameWithoutExtension(assembly),
  248. scriptType.FullName,
  249. false,
  250. BindingFlags.Default,
  251. null,
  252. constructorParams,
  253. null,
  254. null,
  255. null);
  256. else
  257. m_Script
  258. = (IScript)scriptAssembly.CreateInstance(
  259. scriptType.FullName,
  260. false,
  261. BindingFlags.Default,
  262. null,
  263. constructorParams,
  264. null,
  265. null);
  266. //ILease lease = (ILease)RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass);
  267. //RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass);
  268. // lease.Register(this);
  269. }
  270. catch (Exception e)
  271. {
  272. m_log.ErrorFormat(
  273. "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Error loading assembly {6}. Exception {7}{8}",
  274. ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, assembly, e.Message, e.StackTrace);
  275. return false;
  276. }
  277. try
  278. {
  279. foreach (KeyValuePair<string,IScriptApi> kv in m_Apis)
  280. {
  281. m_Script.InitApi(kv.Key, kv.Value);
  282. }
  283. // // m_log.Debug("[Script] Script instance created");
  284. Part.SetScriptEvents(ItemID,
  285. (int)m_Script.GetStateEventFlags(State));
  286. }
  287. catch (Exception e)
  288. {
  289. m_log.ErrorFormat(
  290. "[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}",
  291. ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, e.Message, e.StackTrace);
  292. return false;
  293. }
  294. m_SaveState = true;
  295. string savedState = Path.Combine(Path.GetDirectoryName(assembly),
  296. ItemID.ToString() + ".state");
  297. if (File.Exists(savedState))
  298. {
  299. string xml = String.Empty;
  300. try
  301. {
  302. FileInfo fi = new FileInfo(savedState);
  303. int size = (int)fi.Length;
  304. if (size < 512000)
  305. {
  306. using (FileStream fs = File.Open(savedState,
  307. FileMode.Open, FileAccess.Read, FileShare.None))
  308. {
  309. Byte[] data = new Byte[size];
  310. fs.Read(data, 0, size);
  311. xml = Encoding.UTF8.GetString(data);
  312. ScriptSerializer.Deserialize(xml, this);
  313. AsyncCommandManager.CreateFromData(Engine,
  314. LocalID, ItemID, ObjectID,
  315. PluginData);
  316. // m_log.DebugFormat("[Script] Successfully retrieved state for script {0}.{1}", PrimName, m_ScriptName);
  317. Part.SetScriptEvents(ItemID,
  318. (int)m_Script.GetStateEventFlags(State));
  319. if (!Running)
  320. m_startOnInit = false;
  321. Running = false;
  322. // we get new rez events on sim restart, too
  323. // but if there is state, then we fire the change
  324. // event
  325. // We loaded state, don't force a re-save
  326. m_SaveState = false;
  327. m_startedFromSavedState = true;
  328. }
  329. }
  330. else
  331. {
  332. m_log.WarnFormat(
  333. "[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.",
  334. ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, savedState);
  335. }
  336. }
  337. catch (Exception e)
  338. {
  339. m_log.ErrorFormat(
  340. "[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}",
  341. ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, savedState, xml, e.Message, e.StackTrace);
  342. }
  343. }
  344. // else
  345. // {
  346. // ScenePresence presence = Engine.World.GetScenePresence(part.OwnerID);
  347. // if (presence != null && (!postOnRez))
  348. // presence.ControllingClient.SendAgentAlertMessage("Compile successful", false);
  349. // }
  350. return true;
  351. }
  352. public void Init()
  353. {
  354. if (ShuttingDown)
  355. return;
  356. if (m_startedFromSavedState)
  357. {
  358. if (m_startOnInit)
  359. Start();
  360. if (m_postOnRez)
  361. {
  362. PostEvent(new EventParams("on_rez",
  363. new Object[] {new LSL_Types.LSLInteger(StartParam)}, new DetectParams[0]));
  364. }
  365. if (m_stateSource == StateSource.AttachedRez)
  366. {
  367. PostEvent(new EventParams("attach",
  368. new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0]));
  369. }
  370. else if (m_stateSource == StateSource.RegionStart)
  371. {
  372. //m_log.Debug("[Script] Posted changed(CHANGED_REGION_RESTART) to script");
  373. PostEvent(new EventParams("changed",
  374. new Object[] { new LSL_Types.LSLInteger((int)Changed.REGION_RESTART) }, new DetectParams[0]));
  375. }
  376. else if (m_stateSource == StateSource.PrimCrossing || m_stateSource == StateSource.Teleporting)
  377. {
  378. // CHANGED_REGION
  379. PostEvent(new EventParams("changed",
  380. new Object[] { new LSL_Types.LSLInteger((int)Changed.REGION) }, new DetectParams[0]));
  381. // CHANGED_TELEPORT
  382. if (m_stateSource == StateSource.Teleporting)
  383. PostEvent(new EventParams("changed",
  384. new Object[] { new LSL_Types.LSLInteger((int)Changed.TELEPORT) }, new DetectParams[0]));
  385. }
  386. }
  387. else
  388. {
  389. if (m_startOnInit)
  390. Start();
  391. PostEvent(new EventParams("state_entry",
  392. new Object[0], new DetectParams[0]));
  393. if (m_postOnRez)
  394. {
  395. PostEvent(new EventParams("on_rez",
  396. new Object[] {new LSL_Types.LSLInteger(StartParam)}, new DetectParams[0]));
  397. }
  398. if (m_stateSource == StateSource.AttachedRez)
  399. {
  400. PostEvent(new EventParams("attach",
  401. new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0]));
  402. }
  403. }
  404. }
  405. private void ReleaseControls()
  406. {
  407. int permsMask;
  408. UUID permsGranter;
  409. lock (Part.TaskInventory)
  410. {
  411. if (!Part.TaskInventory.ContainsKey(ItemID))
  412. return;
  413. permsGranter = Part.TaskInventory[ItemID].PermsGranter;
  414. permsMask = Part.TaskInventory[ItemID].PermsMask;
  415. }
  416. if ((permsMask & ScriptBaseClass.PERMISSION_TAKE_CONTROLS) != 0)
  417. {
  418. ScenePresence presence = Engine.World.GetScenePresence(permsGranter);
  419. if (presence != null)
  420. presence.UnRegisterControlEventsToScript(LocalID, ItemID);
  421. }
  422. }
  423. public void DestroyScriptInstance()
  424. {
  425. ReleaseControls();
  426. AsyncCommandManager.RemoveScript(Engine, LocalID, ItemID);
  427. }
  428. public void RemoveState()
  429. {
  430. string savedState = Path.Combine(Path.GetDirectoryName(m_Assembly),
  431. ItemID.ToString() + ".state");
  432. try
  433. {
  434. File.Delete(savedState);
  435. }
  436. catch (Exception e)
  437. {
  438. m_log.Warn(
  439. string.Format(
  440. "[SCRIPT INSTANCE]: Could not delete script state {0} for script {1} (id {2}) in part {3} (id {4}) in object {5} in {6}. Exception ",
  441. savedState, ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name),
  442. e);
  443. }
  444. }
  445. public void VarDump(Dictionary<string, object> vars)
  446. {
  447. // m_log.Info("Variable dump for script "+ ItemID.ToString());
  448. // foreach (KeyValuePair<string, object> v in vars)
  449. // {
  450. // m_log.Info("Variable: "+v.Key+" = "+v.Value.ToString());
  451. // }
  452. }
  453. public void Start()
  454. {
  455. lock (EventQueue)
  456. {
  457. if (Running)
  458. return;
  459. Running = true;
  460. TimeStarted = DateTime.Now;
  461. MeasurementPeriodTickStart = Util.EnvironmentTickCount();
  462. MeasurementPeriodExecutionTime = 0;
  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)
  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 (!Running)
  482. return true;
  483. // If we're not running or waiting to run an event then we can safely stop.
  484. if (m_CurrentWorkItem == null)
  485. {
  486. Running = false;
  487. return true;
  488. }
  489. // If we are waiting to run an event then we can try to cancel it.
  490. if (m_CurrentWorkItem.Cancel())
  491. {
  492. m_CurrentWorkItem = null;
  493. Running = false;
  494. return true;
  495. }
  496. workItem = m_CurrentWorkItem;
  497. Running = false;
  498. }
  499. // Wait for the current event to complete.
  500. if (!m_InSelfDelete)
  501. {
  502. if (!m_coopTermination)
  503. {
  504. // If we're not co-operative terminating then try and wait for the event to complete before stopping
  505. if (workItem.Wait(timeout))
  506. return true;
  507. }
  508. else
  509. {
  510. if (DebugLevel >= 1)
  511. m_log.DebugFormat(
  512. "[SCRIPT INSTANCE]: Co-operatively stopping script {0} {1} in {2} {3}",
  513. ScriptName, ItemID, PrimName, ObjectID);
  514. // This will terminate the event on next handle check by the script.
  515. m_coopSleepHandle.Set();
  516. // For now, we will wait forever since the event should always cleanly terminate once LSL loop
  517. // checking is implemented. May want to allow a shorter timeout option later.
  518. if (workItem.Wait(Timeout.Infinite))
  519. {
  520. if (DebugLevel >= 1)
  521. m_log.DebugFormat(
  522. "[SCRIPT INSTANCE]: Co-operatively stopped script {0} {1} in {2} {3}",
  523. ScriptName, ItemID, PrimName, ObjectID);
  524. return true;
  525. }
  526. }
  527. }
  528. lock (EventQueue)
  529. {
  530. workItem = m_CurrentWorkItem;
  531. }
  532. if (workItem == null)
  533. return true;
  534. // If the event still hasn't stopped and we the stop isn't the result of script or object removal, then
  535. // forcibly abort the work item (this aborts the underlying thread).
  536. // Co-operative termination should never reach this point.
  537. if (!m_InSelfDelete)
  538. {
  539. m_log.DebugFormat(
  540. "[SCRIPT INSTANCE]: Aborting unstopped script {0} {1} in prim {2}, localID {3}, timeout was {4} ms",
  541. ScriptName, ItemID, PrimName, LocalID, timeout);
  542. workItem.Abort();
  543. }
  544. lock (EventQueue)
  545. {
  546. m_CurrentWorkItem = null;
  547. }
  548. return true;
  549. }
  550. public void SetState(string state)
  551. {
  552. if (state == State)
  553. return;
  554. PostEvent(new EventParams("state_exit", new Object[0],
  555. new DetectParams[0]));
  556. PostEvent(new EventParams("state", new Object[] { state },
  557. new DetectParams[0]));
  558. PostEvent(new EventParams("state_entry", new Object[0],
  559. new DetectParams[0]));
  560. throw new EventAbortException();
  561. }
  562. /// <summary>
  563. /// Post an event to this script instance.
  564. /// </summary>
  565. /// <remarks>
  566. /// The request to run the event is sent
  567. /// </remarks>
  568. /// <param name="data"></param>
  569. public void PostEvent(EventParams data)
  570. {
  571. // m_log.DebugFormat("[Script] Posted event {2} in state {3} to {0}.{1}",
  572. // PrimName, ScriptName, data.EventName, State);
  573. if (!Running)
  574. return;
  575. // If min event delay is set then ignore any events untill the time has expired
  576. // This currently only allows 1 event of any type in the given time period.
  577. // This may need extending to allow for a time for each individual event type.
  578. if (m_eventDelayTicks != 0)
  579. {
  580. if (DateTime.Now.Ticks < m_nextEventTimeTicks)
  581. return;
  582. m_nextEventTimeTicks = DateTime.Now.Ticks + m_eventDelayTicks;
  583. }
  584. lock (EventQueue)
  585. {
  586. if (EventQueue.Count >= m_MaxScriptQueue)
  587. return;
  588. if (data.EventName == "timer")
  589. {
  590. if (m_TimerQueued)
  591. return;
  592. m_TimerQueued = true;
  593. }
  594. if (data.EventName == "control")
  595. {
  596. int held = ((LSL_Types.LSLInteger)data.Params[1]).value;
  597. // int changed = ((LSL_Types.LSLInteger)data.Params[2]).value;
  598. // If the last message was a 0 (nothing held)
  599. // and this one is also nothing held, drop it
  600. //
  601. if (m_LastControlLevel == held && held == 0)
  602. return;
  603. // If there is one or more queued, then queue
  604. // only changed ones, else queue unconditionally
  605. //
  606. if (m_ControlEventsInQueue > 0)
  607. {
  608. if (m_LastControlLevel == held)
  609. return;
  610. }
  611. m_LastControlLevel = held;
  612. m_ControlEventsInQueue++;
  613. }
  614. if (data.EventName == "collision")
  615. {
  616. if (m_CollisionInQueue)
  617. return;
  618. if (data.DetectParams == null)
  619. return;
  620. m_CollisionInQueue = true;
  621. }
  622. EventQueue.Enqueue(data);
  623. if (m_CurrentWorkItem == null)
  624. {
  625. m_CurrentWorkItem = Engine.QueueEventHandler(this);
  626. }
  627. }
  628. }
  629. /// <summary>
  630. /// Process the next event queued for this script
  631. /// </summary>
  632. /// <returns></returns>
  633. public object EventProcessor()
  634. {
  635. // We check here as the thread stopping this instance from running may itself hold the m_Script lock.
  636. if (!Running)
  637. return 0;
  638. lock (m_Script)
  639. {
  640. // m_log.DebugFormat("[XEngine]: EventProcessor() invoked for {0}.{1}", PrimName, ScriptName);
  641. if (Suspended)
  642. return 0;
  643. EventParams data = null;
  644. lock (EventQueue)
  645. {
  646. data = (EventParams)EventQueue.Dequeue();
  647. if (data == null) // Shouldn't happen
  648. {
  649. if (EventQueue.Count > 0 && Running && !ShuttingDown)
  650. {
  651. m_CurrentWorkItem = Engine.QueueEventHandler(this);
  652. }
  653. else
  654. {
  655. m_CurrentWorkItem = null;
  656. }
  657. return 0;
  658. }
  659. if (data.EventName == "timer")
  660. m_TimerQueued = false;
  661. if (data.EventName == "control")
  662. {
  663. if (m_ControlEventsInQueue > 0)
  664. m_ControlEventsInQueue--;
  665. }
  666. if (data.EventName == "collision")
  667. m_CollisionInQueue = false;
  668. }
  669. if (DebugLevel >= 2)
  670. m_log.DebugFormat(
  671. "[SCRIPT INSTANCE]: Processing event {0} for {1}/{2}({3})/{4}({5}) @ {6}/{7}",
  672. data.EventName,
  673. ScriptName,
  674. Part.Name,
  675. Part.LocalId,
  676. Part.ParentGroup.Name,
  677. Part.ParentGroup.UUID,
  678. Part.AbsolutePosition,
  679. Part.ParentGroup.Scene.Name);
  680. m_DetectParams = data.DetectParams;
  681. if (data.EventName == "state") // Hardcoded state change
  682. {
  683. State = data.Params[0].ToString();
  684. if (DebugLevel >= 1)
  685. m_log.DebugFormat(
  686. "[SCRIPT INSTANCE]: Changing state to {0} for {1}/{2}({3})/{4}({5}) @ {6}/{7}",
  687. State,
  688. ScriptName,
  689. Part.Name,
  690. Part.LocalId,
  691. Part.ParentGroup.Name,
  692. Part.ParentGroup.UUID,
  693. Part.AbsolutePosition,
  694. Part.ParentGroup.Scene.Name);
  695. AsyncCommandManager.RemoveScript(Engine,
  696. LocalID, ItemID);
  697. Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State));
  698. }
  699. else
  700. {
  701. if (Engine.World.PipeEventsForScript(LocalID) ||
  702. data.EventName == "control") // Don't freeze avies!
  703. {
  704. // m_log.DebugFormat("[Script] Delivered event {2} in state {3} to {0}.{1}",
  705. // PrimName, ScriptName, data.EventName, State);
  706. try
  707. {
  708. m_CurrentEvent = data.EventName;
  709. m_EventStart = DateTime.Now;
  710. m_InEvent = true;
  711. int start = Util.EnvironmentTickCount();
  712. // Reset the measurement period when we reach the end of the current one.
  713. if (start - MeasurementPeriodTickStart > MaxMeasurementPeriod)
  714. MeasurementPeriodTickStart = start;
  715. m_Script.ExecuteEvent(State, data.EventName, data.Params);
  716. MeasurementPeriodExecutionTime += Util.EnvironmentTickCount() - start;
  717. m_InEvent = false;
  718. m_CurrentEvent = String.Empty;
  719. if (m_SaveState)
  720. {
  721. // This will be the very first event we deliver
  722. // (state_entry) in default state
  723. //
  724. SaveState(m_Assembly);
  725. m_SaveState = false;
  726. }
  727. }
  728. catch (Exception e)
  729. {
  730. // m_log.DebugFormat(
  731. // "[SCRIPT] Exception in script {0} {1}: {2}{3}",
  732. // ScriptName, ItemID, e.Message, e.StackTrace);
  733. m_InEvent = false;
  734. m_CurrentEvent = String.Empty;
  735. if ((!(e is TargetInvocationException)
  736. || (!(e.InnerException is SelfDeleteException)
  737. && !(e.InnerException is ScriptDeleteException)
  738. && !(e.InnerException is ScriptCoopStopException)))
  739. && !(e is ThreadAbortException))
  740. {
  741. try
  742. {
  743. // DISPLAY ERROR INWORLD
  744. string text = FormatException(e);
  745. if (text.Length > 1000)
  746. text = text.Substring(0, 1000);
  747. Engine.World.SimChat(Utils.StringToBytes(text),
  748. ChatTypeEnum.DebugChannel, 2147483647,
  749. Part.AbsolutePosition,
  750. Part.Name, Part.UUID, false);
  751. m_log.Debug(string.Format(
  752. "[SCRIPT INSTANCE]: Runtime error in script {0}, part {1} {2} at {3} in {4} ",
  753. ScriptName,
  754. PrimName,
  755. Part.UUID,
  756. Part.AbsolutePosition,
  757. Part.ParentGroup.Scene.Name),
  758. e);
  759. }
  760. catch (Exception)
  761. {
  762. }
  763. // catch (Exception e2) // LEGIT: User Scripting
  764. // {
  765. // m_log.Error("[SCRIPT]: "+
  766. // "Error displaying error in-world: " +
  767. // e2.ToString());
  768. // m_log.Error("[SCRIPT]: " +
  769. // "Errormessage: Error compiling script:\r\n" +
  770. // e.ToString());
  771. // }
  772. }
  773. else if ((e is TargetInvocationException) && (e.InnerException is SelfDeleteException))
  774. {
  775. m_InSelfDelete = true;
  776. Engine.World.DeleteSceneObject(Part.ParentGroup, false);
  777. }
  778. else if ((e is TargetInvocationException) && (e.InnerException is ScriptDeleteException))
  779. {
  780. m_InSelfDelete = true;
  781. Part.Inventory.RemoveInventoryItem(ItemID);
  782. }
  783. else if ((e is TargetInvocationException) && (e.InnerException is ScriptCoopStopException))
  784. {
  785. if (DebugLevel >= 1)
  786. m_log.DebugFormat(
  787. "[SCRIPT INSTANCE]: Script {0}.{1} in event {2}, state {3} stopped co-operatively.",
  788. PrimName, ScriptName, data.EventName, State);
  789. }
  790. }
  791. }
  792. }
  793. // If there are more events and we are currently running and not shutting down, then ask the
  794. // script engine to run the next event.
  795. lock (EventQueue)
  796. {
  797. EventsProcessed++;
  798. if (EventQueue.Count > 0 && Running && !ShuttingDown)
  799. {
  800. m_CurrentWorkItem = Engine.QueueEventHandler(this);
  801. }
  802. else
  803. {
  804. m_CurrentWorkItem = null;
  805. }
  806. }
  807. m_DetectParams = null;
  808. return 0;
  809. }
  810. }
  811. public int EventTime()
  812. {
  813. if (!m_InEvent)
  814. return 0;
  815. return (DateTime.Now - m_EventStart).Seconds;
  816. }
  817. public void ResetScript(int timeout)
  818. {
  819. if (m_Script == null)
  820. return;
  821. bool running = Running;
  822. RemoveState();
  823. ReleaseControls();
  824. Stop(timeout);
  825. Part.Inventory.GetInventoryItem(ItemID).PermsMask = 0;
  826. Part.Inventory.GetInventoryItem(ItemID).PermsGranter = UUID.Zero;
  827. AsyncCommandManager.RemoveScript(Engine, LocalID, ItemID);
  828. EventQueue.Clear();
  829. m_Script.ResetVars();
  830. State = "default";
  831. Part.SetScriptEvents(ItemID,
  832. (int)m_Script.GetStateEventFlags(State));
  833. if (running)
  834. Start();
  835. m_SaveState = true;
  836. PostEvent(new EventParams("state_entry",
  837. new Object[0], new DetectParams[0]));
  838. }
  839. public void ApiResetScript()
  840. {
  841. // bool running = Running;
  842. RemoveState();
  843. ReleaseControls();
  844. m_Script.ResetVars();
  845. Part.Inventory.GetInventoryItem(ItemID).PermsMask = 0;
  846. Part.Inventory.GetInventoryItem(ItemID).PermsGranter = UUID.Zero;
  847. AsyncCommandManager.RemoveScript(Engine, LocalID, ItemID);
  848. EventQueue.Clear();
  849. m_Script.ResetVars();
  850. State = "default";
  851. Part.SetScriptEvents(ItemID,
  852. (int)m_Script.GetStateEventFlags(State));
  853. if (m_CurrentEvent != "state_entry")
  854. {
  855. m_SaveState = true;
  856. PostEvent(new EventParams("state_entry",
  857. new Object[0], new DetectParams[0]));
  858. throw new EventAbortException();
  859. }
  860. }
  861. public Dictionary<string, object> GetVars()
  862. {
  863. if (m_Script != null)
  864. return m_Script.GetVars();
  865. else
  866. return new Dictionary<string, object>();
  867. }
  868. public void SetVars(Dictionary<string, object> vars)
  869. {
  870. m_Script.SetVars(vars);
  871. }
  872. public DetectParams GetDetectParams(int idx)
  873. {
  874. if (m_DetectParams == null)
  875. return null;
  876. if (idx < 0 || idx >= m_DetectParams.Length)
  877. return null;
  878. return m_DetectParams[idx];
  879. }
  880. public UUID GetDetectID(int idx)
  881. {
  882. if (m_DetectParams == null)
  883. return UUID.Zero;
  884. if (idx < 0 || idx >= m_DetectParams.Length)
  885. return UUID.Zero;
  886. return m_DetectParams[idx].Key;
  887. }
  888. public void SaveState(string assembly)
  889. {
  890. // If we're currently in an event, just tell it to save upon return
  891. //
  892. if (m_InEvent)
  893. {
  894. m_SaveState = true;
  895. return;
  896. }
  897. PluginData = AsyncCommandManager.GetSerializationData(Engine, ItemID);
  898. string xml = ScriptSerializer.Serialize(this);
  899. // Compare hash of the state we just just created with the state last written to disk
  900. // If the state is different, update the disk file.
  901. UUID hash = UUID.Parse(Utils.MD5String(xml));
  902. if (hash != m_CurrentStateHash)
  903. {
  904. try
  905. {
  906. FileStream fs = File.Create(Path.Combine(Path.GetDirectoryName(assembly), ItemID.ToString() + ".state"));
  907. Byte[] buf = Util.UTF8NoBomEncoding.GetBytes(xml);
  908. fs.Write(buf, 0, buf.Length);
  909. fs.Close();
  910. }
  911. catch(Exception)
  912. {
  913. // m_log.Error("Unable to save xml\n"+e.ToString());
  914. }
  915. //if (!File.Exists(Path.Combine(Path.GetDirectoryName(assembly), ItemID.ToString() + ".state")))
  916. //{
  917. // throw new Exception("Completed persistence save, but no file was created");
  918. //}
  919. m_CurrentStateHash = hash;
  920. }
  921. }
  922. public IScriptApi GetApi(string name)
  923. {
  924. if (m_Apis.ContainsKey(name))
  925. {
  926. // m_log.DebugFormat("[SCRIPT INSTANCE]: Found api {0} in {1}@{2}", name, ScriptName, PrimName);
  927. return m_Apis[name];
  928. }
  929. // m_log.DebugFormat("[SCRIPT INSTANCE]: Did not find api {0} in {1}@{2}", name, ScriptName, PrimName);
  930. return null;
  931. }
  932. public override string ToString()
  933. {
  934. return String.Format("{0} {1} on {2}", ScriptName, ItemID, PrimName);
  935. }
  936. string FormatException(Exception e)
  937. {
  938. if (e.InnerException == null) // Not a normal runtime error
  939. return e.ToString();
  940. string message = "Runtime error:\n" + e.InnerException.StackTrace;
  941. string[] lines = message.Split(new char[] {'\n'});
  942. foreach (string line in lines)
  943. {
  944. if (line.Contains("SecondLife.Script"))
  945. {
  946. int idx = line.IndexOf(':');
  947. if (idx != -1)
  948. {
  949. string val = line.Substring(idx+1);
  950. int lineNum = 0;
  951. if (int.TryParse(val, out lineNum))
  952. {
  953. KeyValuePair<int, int> pos =
  954. Compiler.FindErrorPosition(
  955. lineNum, 0, LineMap);
  956. int scriptLine = pos.Key;
  957. int col = pos.Value;
  958. if (scriptLine == 0)
  959. scriptLine++;
  960. if (col == 0)
  961. col++;
  962. message = string.Format("Runtime error:\n" +
  963. "({0}): {1}", scriptLine - 1,
  964. e.InnerException.Message);
  965. return message;
  966. }
  967. }
  968. }
  969. }
  970. // m_log.ErrorFormat("Scripting exception:");
  971. // m_log.ErrorFormat(e.ToString());
  972. return e.ToString();
  973. }
  974. public string GetAssemblyName()
  975. {
  976. return m_Assembly;
  977. }
  978. public string GetXMLState()
  979. {
  980. bool run = Running;
  981. Stop(100);
  982. Running = run;
  983. // We should not be doing this, but since we are about to
  984. // dispose this, it really doesn't make a difference
  985. // This is meant to work around a Windows only race
  986. //
  987. m_InEvent = false;
  988. // Force an update of the in-memory plugin data
  989. //
  990. PluginData = AsyncCommandManager.GetSerializationData(Engine, ItemID);
  991. return ScriptSerializer.Serialize(this);
  992. }
  993. public UUID RegionID
  994. {
  995. get { return m_RegionID; }
  996. }
  997. public void Suspend()
  998. {
  999. Suspended = true;
  1000. }
  1001. public void Resume()
  1002. {
  1003. Suspended = false;
  1004. }
  1005. }
  1006. /// <summary>
  1007. /// Xengine event wait handle.
  1008. /// </summary>
  1009. /// <remarks>
  1010. /// This class exists becase XEngineScriptBase gets a reference to this wait handle. We need to make sure that
  1011. /// when scripts are running in different AppDomains the lease does not expire.
  1012. /// FIXME: Like LSL_Api, etc., this effectively leaks memory since the GC will never collect it. To avoid this,
  1013. /// proper remoting sponsorship needs to be implemented across the board.
  1014. /// </remarks>
  1015. public class XEngineEventWaitHandle : EventWaitHandle
  1016. {
  1017. public XEngineEventWaitHandle(bool initialState, EventResetMode mode) : base(initialState, mode) {}
  1018. public override Object InitializeLifetimeService()
  1019. {
  1020. return null;
  1021. }
  1022. }
  1023. }