ScriptInstance.cs 47 KB

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