ScriptInstance.cs 45 KB

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