ScriptInstance.cs 46 KB

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