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