XEngine.cs 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878
  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 OpenSim 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.IO;
  29. using System.Threading;
  30. using System.Collections;
  31. using System.Collections.Generic;
  32. using System.Security.Policy;
  33. using System.Reflection;
  34. using System.Globalization;
  35. using System.Xml;
  36. using libsecondlife;
  37. using log4net;
  38. using Nini.Config;
  39. using Amib.Threading;
  40. using OpenSim.Framework;
  41. using OpenSim.Region.Environment;
  42. using OpenSim.Region.Environment.Scenes;
  43. using OpenSim.Region.Environment.Interfaces;
  44. using OpenSim.Region.ScriptEngine.Shared;
  45. using OpenSim.Region.ScriptEngine.Shared.Api;
  46. using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
  47. using OpenSim.Region.ScriptEngine.Shared.CodeTools;
  48. using OpenSim.Region.ScriptEngine.Interfaces;
  49. namespace OpenSim.Region.ScriptEngine.XEngine
  50. {
  51. public class XEngine : IScriptModule, IScriptEngine
  52. {
  53. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  54. private SmartThreadPool m_ThreadPool;
  55. private int m_MaxScriptQueue;
  56. private Scene m_Scene;
  57. private IConfig m_ScriptConfig;
  58. private Compiler m_Compiler;
  59. // disable warning: need to keep a reference to XEngine.EventManager
  60. // alive to avoid it being garbage collected
  61. #pragma warning disable 414
  62. private EventManager m_EventManager;
  63. #pragma warning restore 414
  64. private int m_EventLimit;
  65. private bool m_KillTimedOutScripts;
  66. public AsyncCommandManager m_AsyncCommands;
  67. bool m_firstStart = true;
  68. private static List<XEngine> m_ScriptEngines =
  69. new List<XEngine>();
  70. // Maps the local id to the script inventory items in it
  71. private Dictionary<uint, List<LLUUID> > m_PrimObjects =
  72. new Dictionary<uint, List<LLUUID> >();
  73. // Maps the LLUUID above to the script instance
  74. private Dictionary<LLUUID, XScriptInstance> m_Scripts =
  75. new Dictionary<LLUUID, XScriptInstance>();
  76. // Maps the asset ID to the assembly
  77. private Dictionary<LLUUID, string> m_Assemblies =
  78. new Dictionary<LLUUID, string>();
  79. // This will list AppDomains by script asset
  80. private Dictionary<LLUUID, AppDomain> m_AppDomains =
  81. new Dictionary<LLUUID, AppDomain>();
  82. // List the scripts running in each appdomain
  83. private Dictionary<LLUUID, List<LLUUID> > m_DomainScripts =
  84. new Dictionary<LLUUID, List<LLUUID> >();
  85. private Queue m_CompileQueue = new Queue(100);
  86. IWorkItemResult m_CurrentCompile = null;
  87. public string ScriptEngineName
  88. {
  89. get { return "XEngine"; }
  90. }
  91. public Scene World
  92. {
  93. get { return m_Scene; }
  94. }
  95. public ILog Log
  96. {
  97. get { return m_log; }
  98. }
  99. public static List<XEngine> ScriptEngines
  100. {
  101. get { return m_ScriptEngines; }
  102. }
  103. // private struct RezScriptParms
  104. // {
  105. // uint LocalID;
  106. // LLUUID ItemID;
  107. // string Script;
  108. // }
  109. public IConfig Config
  110. {
  111. get { return m_ScriptConfig; }
  112. }
  113. public Object AsyncCommands
  114. {
  115. get { return (Object)m_AsyncCommands; }
  116. }
  117. //
  118. // IRegionModule functions
  119. //
  120. public void Initialise(Scene scene, IConfigSource configSource)
  121. {
  122. AppDomain.CurrentDomain.AssemblyResolve +=
  123. OnAssemblyResolve;
  124. m_log.InfoFormat("[XEngine] Initializing scripts in region {0}",
  125. scene.RegionInfo.RegionName);
  126. m_Scene=scene;
  127. m_ScriptConfig = configSource.Configs["XEngine"];
  128. if (m_ScriptConfig == null)
  129. {
  130. m_log.ErrorFormat("[XEngine] No script configuration found. Scripts disabled");
  131. return;
  132. }
  133. int minThreads = m_ScriptConfig.GetInt("MinThreads", 2);
  134. int maxThreads = m_ScriptConfig.GetInt("MaxThreads", 2);
  135. int idleTimeout = m_ScriptConfig.GetInt("IdleTimeout", 60);
  136. string priority = m_ScriptConfig.GetString("Priority", "BelowNormal");
  137. int maxScriptQueue = m_ScriptConfig.GetInt("MaxScriptEventQueue",300);
  138. int stackSize = m_ScriptConfig.GetInt("ThreadStackSize", 262144);
  139. int sleepTime = m_ScriptConfig.GetInt("MaintenanceInterval",
  140. 10)*1000;
  141. m_EventLimit = m_ScriptConfig.GetInt("EventLimit", 30);
  142. m_KillTimedOutScripts = m_ScriptConfig.GetBoolean(
  143. "KillTimedOutScripts", false);
  144. int saveTime = m_ScriptConfig.GetInt("SaveInterval", 300)*1000;
  145. ThreadPriority prio = ThreadPriority.BelowNormal;
  146. switch (priority)
  147. {
  148. case "Lowest":
  149. prio=ThreadPriority.Lowest;
  150. break;
  151. case "BelowNormal":
  152. prio=ThreadPriority.BelowNormal;
  153. break;
  154. case "Normal":
  155. prio=ThreadPriority.Normal;
  156. break;
  157. case "AboveNormal":
  158. prio=ThreadPriority.AboveNormal;
  159. break;
  160. case "Highest":
  161. prio=ThreadPriority.Highest;
  162. break;
  163. default:
  164. m_log.ErrorFormat("[XEngine] Invalid thread priority: '"+
  165. priority+"'. Assuming BelowNormal");
  166. break;
  167. }
  168. lock (m_ScriptEngines)
  169. {
  170. m_ScriptEngines.Add(this);
  171. }
  172. m_EventManager = new EventManager(this);
  173. StartEngine(minThreads, maxThreads, idleTimeout, prio,
  174. maxScriptQueue, stackSize);
  175. m_Compiler = new Compiler(this);
  176. m_Scene.EventManager.OnRezScript += OnRezScript;
  177. m_Scene.EventManager.OnRemoveScript += OnRemoveScript;
  178. m_Scene.EventManager.OnScriptReset += OnScriptReset;
  179. m_Scene.EventManager.OnStartScript += OnStartScript;
  180. m_Scene.EventManager.OnStopScript += OnStopScript;
  181. m_AsyncCommands = new AsyncCommandManager(this);
  182. if (sleepTime > 0)
  183. {
  184. m_ThreadPool.QueueWorkItem(new WorkItemCallback(
  185. this.DoMaintenance), new Object[]
  186. { sleepTime });
  187. }
  188. if (saveTime > 0)
  189. {
  190. m_ThreadPool.QueueWorkItem(new WorkItemCallback(
  191. this.DoBackup), new Object[] { saveTime });
  192. }
  193. scene.RegisterModuleInterface<IScriptModule>(this);
  194. }
  195. public void PostInitialise()
  196. {
  197. m_ThreadPool.Start();
  198. }
  199. public void Close()
  200. {
  201. lock (m_ScriptEngines)
  202. {
  203. if (m_ScriptEngines.Contains(this))
  204. m_ScriptEngines.Remove(this);
  205. }
  206. }
  207. public object DoBackup(object o)
  208. {
  209. Object[] p = (Object[])o;
  210. int saveTime = (int)p[0];
  211. System.Threading.Thread.Sleep(saveTime);
  212. // m_log.Debug("[XEngine] Backing up script states");
  213. List<XScriptInstance> instances = new List<XScriptInstance>();
  214. lock (m_Scripts)
  215. {
  216. foreach (XScriptInstance instance in m_Scripts.Values)
  217. instances.Add(instance);
  218. }
  219. foreach (XScriptInstance i in instances)
  220. {
  221. string assembly = String.Empty;
  222. lock (m_Scripts)
  223. {
  224. if (!m_Assemblies.ContainsKey(i.AssetID))
  225. continue;
  226. assembly = m_Assemblies[i.AssetID];
  227. }
  228. i.SaveState(assembly);
  229. }
  230. instances.Clear();
  231. m_ThreadPool.QueueWorkItem(new WorkItemCallback(
  232. this.DoBackup), new Object[] { saveTime });
  233. return 0;
  234. }
  235. public object DoMaintenance(object p)
  236. {
  237. object[] parms = (object[])p;
  238. int sleepTime = (int)parms[0];
  239. foreach (XScriptInstance inst in m_Scripts.Values)
  240. {
  241. if (inst.EventTime() > m_EventLimit)
  242. {
  243. inst.Stop(100);
  244. if (!m_KillTimedOutScripts)
  245. inst.Start();
  246. }
  247. }
  248. System.Threading.Thread.Sleep(sleepTime);
  249. m_ThreadPool.QueueWorkItem(new WorkItemCallback(
  250. this.DoMaintenance), new Object[]
  251. { sleepTime });
  252. return 0;
  253. }
  254. public string Name
  255. {
  256. get { return "XEngine"; }
  257. }
  258. public bool IsSharedModule
  259. {
  260. get { return false; }
  261. }
  262. //
  263. // XEngine functions
  264. //
  265. public int MaxScriptQueue
  266. {
  267. get { return m_MaxScriptQueue; }
  268. }
  269. public void OnRezScript(uint localID, LLUUID itemID, string script, int startParam, bool postOnRez)
  270. {
  271. Object[] parms = new Object[]
  272. { localID, itemID, script, startParam, postOnRez};
  273. lock (m_CompileQueue)
  274. {
  275. m_CompileQueue.Enqueue(parms);
  276. if (m_CurrentCompile == null)
  277. {
  278. if (m_firstStart)
  279. {
  280. m_firstStart = false;
  281. m_CurrentCompile = m_ThreadPool.QueueWorkItem(
  282. new WorkItemCallback(
  283. this.DoScriptWait), new Object[0]);
  284. return;
  285. }
  286. m_CurrentCompile = m_ThreadPool.QueueWorkItem(
  287. new WorkItemCallback(
  288. this.DoOnRezScriptQueue), new Object[0]);
  289. }
  290. }
  291. }
  292. public Object DoScriptWait(Object dummy)
  293. {
  294. Thread.Sleep(30000);
  295. lock (m_CompileQueue)
  296. {
  297. if (m_CompileQueue.Count > 0)
  298. {
  299. m_CurrentCompile = m_ThreadPool.QueueWorkItem(
  300. new WorkItemCallback(
  301. this.DoOnRezScriptQueue), new Object[0]);
  302. }
  303. else
  304. {
  305. m_CurrentCompile = null;
  306. }
  307. }
  308. return null;
  309. }
  310. public Object DoOnRezScriptQueue(Object dummy)
  311. {
  312. Object o;
  313. lock (m_CompileQueue)
  314. {
  315. o = m_CompileQueue.Dequeue();
  316. if (o == null)
  317. {
  318. m_CurrentCompile = null;
  319. return null;
  320. }
  321. }
  322. DoOnRezScript(o);
  323. lock (m_CompileQueue)
  324. {
  325. if (m_CompileQueue.Count > 0)
  326. {
  327. m_CurrentCompile = m_ThreadPool.QueueWorkItem(
  328. new WorkItemCallback(
  329. this.DoOnRezScriptQueue), new Object[0]);
  330. }
  331. else
  332. {
  333. m_CurrentCompile = null;
  334. }
  335. }
  336. return null;
  337. }
  338. private bool DoOnRezScript(object parm)
  339. {
  340. Object[] p = (Object[])parm;
  341. uint localID = (uint)p[0];
  342. LLUUID itemID = (LLUUID)p[1];
  343. string script =(string)p[2];
  344. int startParam = (int)p[3];
  345. bool postOnRez = (bool)p[4];
  346. // Get the asset ID of the script, so we can check if we
  347. // already have it.
  348. SceneObjectPart part = m_Scene.GetSceneObjectPart(localID);
  349. if (part == null)
  350. return false;
  351. TaskInventoryItem item = part.GetInventoryItem(itemID);
  352. if (item == null)
  353. return false;
  354. LLUUID assetID = item.AssetID;
  355. // m_log.DebugFormat("[XEngine] Compiling script {0} ({1})",
  356. // item.Name, itemID.ToString());
  357. string assembly = "";
  358. try
  359. {
  360. assembly = m_Compiler.PerformScriptCompile(script,
  361. assetID.ToString());
  362. }
  363. catch (Exception e)
  364. {
  365. try
  366. {
  367. // DISPLAY ERROR INWORLD
  368. string text = "Error compiling script:\r\n" + e.Message.ToString();
  369. if (text.Length > 1400)
  370. text = text.Substring(0, 1400);
  371. World.SimChat(Helpers.StringToField(text),
  372. ChatTypeEnum.DebugChannel, 2147483647,
  373. part.AbsolutePosition,
  374. part.Name, part.UUID, false);
  375. }
  376. catch (Exception e2) // LEGIT: User Scripting
  377. {
  378. m_log.Error("[XEngine]: "+
  379. "Error displaying error in-world: " +
  380. e2.ToString());
  381. m_log.Error("[XEngine]: " +
  382. "Errormessage: Error compiling script:\r\n" +
  383. e.Message.ToString());
  384. }
  385. return false;
  386. }
  387. lock (m_Scripts)
  388. {
  389. // Create the object record
  390. if ((!m_Scripts.ContainsKey(itemID)) ||
  391. (m_Scripts[itemID].AssetID != assetID))
  392. {
  393. LLUUID appDomain=assetID;
  394. if (part.ParentGroup.RootPart.m_IsAttachment)
  395. appDomain = part.ParentGroup.RootPart.UUID;
  396. if (!m_AppDomains.ContainsKey(appDomain))
  397. {
  398. try
  399. {
  400. AppDomainSetup appSetup = new AppDomainSetup();
  401. // appSetup.ApplicationBase = Path.Combine(
  402. // "ScriptEngines",
  403. // m_Scene.RegionInfo.RegionID.ToString());
  404. Evidence baseEvidence =
  405. AppDomain.CurrentDomain.Evidence;
  406. Evidence evidence = new Evidence(baseEvidence);
  407. m_AppDomains[appDomain] =
  408. AppDomain.CreateDomain(
  409. m_Scene.RegionInfo.RegionID.ToString(),
  410. evidence, appSetup);
  411. m_AppDomains[appDomain].AssemblyResolve +=
  412. new ResolveEventHandler(
  413. AssemblyResolver.OnAssemblyResolve);
  414. m_DomainScripts[appDomain] = new List<LLUUID>();
  415. }
  416. catch (Exception e)
  417. {
  418. m_log.Error("[XEngine] Exception creating app domain:\n"+e.ToString());
  419. return false;
  420. }
  421. }
  422. m_DomainScripts[appDomain].Add(itemID);
  423. XScriptInstance instance = new XScriptInstance(this,localID,
  424. part.UUID, itemID, assetID, assembly,
  425. m_AppDomains[appDomain],
  426. part.ParentGroup.RootPart.Name,
  427. item.Name, startParam, postOnRez,
  428. XScriptInstance.StateSource.NewRez);
  429. m_log.DebugFormat("[XEngine] Loaded script {0}.{1}",
  430. part.ParentGroup.RootPart.Name, item.Name);
  431. instance.AppDomain = appDomain;
  432. m_Scripts[itemID] = instance;
  433. }
  434. if (!m_PrimObjects.ContainsKey(localID))
  435. m_PrimObjects[localID] = new List<LLUUID>();
  436. if (!m_PrimObjects[localID].Contains(itemID))
  437. m_PrimObjects[localID].Add(itemID);
  438. if (!m_Assemblies.ContainsKey(assetID))
  439. m_Assemblies[assetID] = assembly;
  440. }
  441. return true;
  442. }
  443. public void OnRemoveScript(uint localID, LLUUID itemID)
  444. {
  445. lock (m_Scripts)
  446. {
  447. // Do we even have it?
  448. if (!m_Scripts.ContainsKey(itemID))
  449. return;
  450. m_AsyncCommands.RemoveScript(localID, itemID);
  451. XScriptInstance instance=m_Scripts[itemID];
  452. m_Scripts.Remove(itemID);
  453. instance.ClearQueue();
  454. instance.Stop(0);
  455. SceneObjectPart part =
  456. m_Scene.GetSceneObjectPart(localID);
  457. if (part != null)
  458. part.RemoveScriptEvents(itemID);
  459. // Remove the script from it's prim
  460. if (m_PrimObjects.ContainsKey(localID))
  461. {
  462. // Remove inventory item record
  463. if (m_PrimObjects[localID].Contains(itemID))
  464. m_PrimObjects[localID].Remove(itemID);
  465. // If there are no more scripts, remove prim
  466. if (m_PrimObjects[localID].Count == 0)
  467. {
  468. m_PrimObjects.Remove(localID);
  469. }
  470. }
  471. m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
  472. if (m_DomainScripts[instance.AppDomain].Count == 0)
  473. {
  474. m_DomainScripts.Remove(instance.AppDomain);
  475. UnloadAppDomain(instance.AppDomain);
  476. }
  477. instance.RemoveState();
  478. instance = null;
  479. CleanAssemblies();
  480. }
  481. }
  482. public void OnScriptReset(uint localID, LLUUID itemID)
  483. {
  484. ResetScript(itemID);
  485. }
  486. public void OnStartScript(uint localID, LLUUID itemID)
  487. {
  488. StartScript(itemID);
  489. }
  490. public void OnStopScript(uint localID, LLUUID itemID)
  491. {
  492. StopScript(itemID);
  493. }
  494. private void CleanAssemblies()
  495. {
  496. List<LLUUID> assetIDList = new List<LLUUID>(m_Assemblies.Keys);
  497. foreach (XScriptInstance i in m_Scripts.Values)
  498. {
  499. if (assetIDList.Contains(i.AssetID))
  500. assetIDList.Remove(i.AssetID);
  501. }
  502. foreach (LLUUID assetID in assetIDList)
  503. {
  504. // m_log.DebugFormat("[XEngine] Removing unreferenced assembly {0}", m_Assemblies[assetID]);
  505. try
  506. {
  507. if (File.Exists(m_Assemblies[assetID]))
  508. File.Delete(m_Assemblies[assetID]);
  509. if (File.Exists(m_Assemblies[assetID]+".state"))
  510. File.Delete(m_Assemblies[assetID]+".state");
  511. if (File.Exists(m_Assemblies[assetID]+".mdb"))
  512. File.Delete(m_Assemblies[assetID]+".mdb");
  513. }
  514. catch (Exception)
  515. {
  516. }
  517. m_Assemblies.Remove(assetID);
  518. }
  519. }
  520. private void UnloadAppDomain(LLUUID id)
  521. {
  522. if (m_AppDomains.ContainsKey(id))
  523. {
  524. AppDomain domain = m_AppDomains[id];
  525. m_AppDomains.Remove(id);
  526. AppDomain.Unload(domain);
  527. domain = null;
  528. // m_log.DebugFormat("[XEngine] Unloaded app domain {0}", id.ToString());
  529. }
  530. }
  531. //
  532. // Start processing
  533. //
  534. private void StartEngine(int minThreads, int maxThreads,
  535. int idleTimeout, ThreadPriority threadPriority,
  536. int maxScriptQueue, int stackSize)
  537. {
  538. m_MaxScriptQueue = maxScriptQueue;
  539. STPStartInfo startInfo = new STPStartInfo();
  540. startInfo.IdleTimeout = idleTimeout;
  541. startInfo.MaxWorkerThreads = maxThreads;
  542. startInfo.MinWorkerThreads = minThreads;
  543. startInfo.ThreadPriority = threadPriority;
  544. startInfo.StackSize = stackSize;
  545. startInfo.StartSuspended = true;
  546. m_ThreadPool = new SmartThreadPool(startInfo);
  547. }
  548. //
  549. // Used by script instances to queue event handler jobs
  550. //
  551. public IWorkItemResult QueueEventHandler(object parms)
  552. {
  553. return m_ThreadPool.QueueWorkItem(new WorkItemCallback(
  554. this.ProcessEventHandler), parms);
  555. }
  556. //
  557. // The main script engine worker
  558. //
  559. private object ProcessEventHandler(object parms)
  560. {
  561. CultureInfo USCulture = new CultureInfo("en-US");
  562. Thread.CurrentThread.CurrentCulture = USCulture;
  563. XScriptInstance instance = (XScriptInstance) parms;
  564. return instance.EventProcessor();
  565. }
  566. //
  567. // Post event to an entire prim
  568. //
  569. public bool PostObjectEvent(uint localID, EventParams p)
  570. {
  571. bool result = false;
  572. if (!m_PrimObjects.ContainsKey(localID))
  573. return false;
  574. foreach (LLUUID itemID in m_PrimObjects[localID])
  575. {
  576. if (m_Scripts.ContainsKey(itemID))
  577. {
  578. XScriptInstance instance = m_Scripts[itemID];
  579. if (instance != null)
  580. {
  581. instance.PostEvent(p);
  582. result = true;
  583. }
  584. }
  585. }
  586. return result;
  587. }
  588. //
  589. // Post an event to a single script
  590. //
  591. public bool PostScriptEvent(LLUUID itemID, EventParams p)
  592. {
  593. if (m_Scripts.ContainsKey(itemID))
  594. {
  595. XScriptInstance instance = m_Scripts[itemID];
  596. if (instance != null)
  597. instance.PostEvent(p);
  598. return true;
  599. }
  600. return false;
  601. }
  602. public Assembly OnAssemblyResolve(object sender,
  603. ResolveEventArgs args)
  604. {
  605. if (!(sender is System.AppDomain))
  606. return null;
  607. string[] pathList = new string[] {"bin", "ScriptEngines",
  608. Path.Combine("ScriptEngines",
  609. m_Scene.RegionInfo.RegionID.ToString())};
  610. string assemblyName = args.Name;
  611. if (assemblyName.IndexOf(",") != -1)
  612. assemblyName = args.Name.Substring(0, args.Name.IndexOf(","));
  613. foreach (string s in pathList)
  614. {
  615. string path = Path.Combine(Directory.GetCurrentDirectory(),
  616. Path.Combine(s, assemblyName))+".dll";
  617. if (File.Exists(path))
  618. return Assembly.LoadFrom(path);
  619. }
  620. return null;
  621. }
  622. private XScriptInstance GetInstance(LLUUID itemID)
  623. {
  624. XScriptInstance instance;
  625. lock (m_Scripts)
  626. {
  627. if (!m_Scripts.ContainsKey(itemID))
  628. return null;
  629. instance = m_Scripts[itemID];
  630. }
  631. return instance;
  632. }
  633. public void SetScriptState(LLUUID itemID, bool running)
  634. {
  635. XScriptInstance instance = GetInstance(itemID);
  636. if (instance != null)
  637. {
  638. if (running)
  639. instance.Start();
  640. else
  641. instance.Stop(100);
  642. }
  643. }
  644. public bool GetScriptState(LLUUID itemID)
  645. {
  646. XScriptInstance instance = GetInstance(itemID);
  647. if (instance != null)
  648. return instance.Running;
  649. return false;
  650. }
  651. public void ApiResetScript(LLUUID itemID)
  652. {
  653. XScriptInstance instance = GetInstance(itemID);
  654. if (instance != null)
  655. instance.ApiResetScript();
  656. }
  657. public void ResetScript(LLUUID itemID)
  658. {
  659. XScriptInstance instance = GetInstance(itemID);
  660. if (instance != null)
  661. instance.ResetScript();
  662. }
  663. public void StartScript(LLUUID itemID)
  664. {
  665. XScriptInstance instance = GetInstance(itemID);
  666. if (instance != null)
  667. instance.Start();
  668. }
  669. public void StopScript(LLUUID itemID)
  670. {
  671. XScriptInstance instance = GetInstance(itemID);
  672. if (instance != null)
  673. instance.Stop(0);
  674. }
  675. public DetectParams GetDetectParams(LLUUID itemID, int idx)
  676. {
  677. XScriptInstance instance = GetInstance(itemID);
  678. if (instance != null)
  679. return instance.GetDetectParams(idx);
  680. return null;
  681. }
  682. public LLUUID GetDetectID(LLUUID itemID, int idx)
  683. {
  684. XScriptInstance instance = GetInstance(itemID);
  685. if (instance != null)
  686. return instance.GetDetectID(idx);
  687. return LLUUID.Zero;
  688. }
  689. public void SetState(LLUUID itemID, string newState)
  690. {
  691. XScriptInstance instance = GetInstance(itemID);
  692. if (instance == null)
  693. return;
  694. instance.SetState(newState);
  695. }
  696. public string GetState(LLUUID itemID)
  697. {
  698. XScriptInstance instance = GetInstance(itemID);
  699. if (instance == null)
  700. return "default";
  701. return instance.State;
  702. }
  703. public int GetStartParameter(LLUUID itemID)
  704. {
  705. XScriptInstance instance = GetInstance(itemID);
  706. if (instance == null)
  707. return 0;
  708. return instance.StartParam;
  709. }
  710. public bool GetScriptRunning(LLUUID objectID, LLUUID itemID)
  711. {
  712. return GetScriptState(itemID);
  713. }
  714. }
  715. public class XScriptInstance
  716. {
  717. private XEngine m_Engine;
  718. private IWorkItemResult m_CurrentResult=null;
  719. private Queue m_EventQueue = new Queue(32);
  720. private bool m_RunEvents = false;
  721. private LLUUID m_ItemID;
  722. private uint m_LocalID;
  723. private LLUUID m_ObjectID;
  724. private LLUUID m_AssetID;
  725. private IScript m_Script;
  726. private Executor m_Executor;
  727. private LLUUID m_AppDomain;
  728. private DetectParams[] m_DetectParams;
  729. private bool m_TimerQueued;
  730. private DateTime m_EventStart;
  731. private bool m_InEvent;
  732. private string m_PrimName;
  733. private string m_ScriptName;
  734. private string m_Assembly;
  735. private int m_StartParam = 0;
  736. private string m_CurrentEvent = String.Empty;
  737. private bool m_InSelfDelete = false;
  738. private Dictionary<string,IScriptApi> m_Apis = new Dictionary<string,IScriptApi>();
  739. public enum StateSource
  740. {
  741. NewRez = 0,
  742. PrimCrossing = 1,
  743. AttachmentCrossing = 2
  744. }
  745. // Script state
  746. private string m_State="default";
  747. public Object[] PluginData = new Object[0];
  748. public bool Running
  749. {
  750. get { return m_RunEvents; }
  751. set { m_RunEvents = value; }
  752. }
  753. public string State
  754. {
  755. get { return m_State; }
  756. set { m_State = value; }
  757. }
  758. public XEngine Engine
  759. {
  760. get { return m_Engine; }
  761. }
  762. public LLUUID AppDomain
  763. {
  764. get { return m_AppDomain; }
  765. set { m_AppDomain = value; }
  766. }
  767. public string PrimName
  768. {
  769. get { return m_PrimName; }
  770. }
  771. public string ScriptName
  772. {
  773. get { return m_ScriptName; }
  774. }
  775. public LLUUID ItemID
  776. {
  777. get { return m_ItemID; }
  778. }
  779. public LLUUID ObjectID
  780. {
  781. get { return m_ObjectID; }
  782. }
  783. public uint LocalID
  784. {
  785. get { return m_LocalID; }
  786. }
  787. public LLUUID AssetID
  788. {
  789. get { return m_AssetID; }
  790. }
  791. public Queue EventQueue
  792. {
  793. get { return m_EventQueue; }
  794. }
  795. public void ClearQueue()
  796. {
  797. m_TimerQueued = false;
  798. m_EventQueue.Clear();
  799. }
  800. public int StartParam
  801. {
  802. get { return m_StartParam; }
  803. set { m_StartParam = value; }
  804. }
  805. public XScriptInstance(XEngine engine, uint localID, LLUUID objectID,
  806. LLUUID itemID, LLUUID assetID, string assembly, AppDomain dom,
  807. string primName, string scriptName, int startParam,
  808. bool postOnRez, StateSource stateSource)
  809. {
  810. m_Engine = engine;
  811. m_LocalID = localID;
  812. m_ObjectID = objectID;
  813. m_ItemID = itemID;
  814. m_AssetID = assetID;
  815. m_PrimName = primName;
  816. m_ScriptName = scriptName;
  817. m_Assembly = assembly;
  818. m_StartParam = startParam;
  819. ApiManager am = new ApiManager();
  820. SceneObjectPart part=engine.World.GetSceneObjectPart(localID);
  821. if (part == null)
  822. {
  823. engine.Log.Error("[XEngine] SceneObjectPart unavailable. Script NOT started.");
  824. return;
  825. }
  826. foreach (string api in am.GetApis())
  827. {
  828. m_Apis[api] = am.CreateApi(api);
  829. m_Apis[api].Initialize(engine, part, localID, itemID);
  830. }
  831. try
  832. {
  833. m_Script = (IScript)dom.CreateInstanceAndUnwrap(
  834. Path.GetFileNameWithoutExtension(assembly),
  835. "SecondLife.Script");
  836. }
  837. catch (Exception e)
  838. {
  839. m_Engine.Log.ErrorFormat("[XEngine] Error loading assembly {0}\n"+e.ToString(), assembly);
  840. }
  841. try
  842. {
  843. foreach (KeyValuePair<string,IScriptApi> kv in m_Apis)
  844. {
  845. m_Script.InitApi(kv.Key, kv.Value);
  846. }
  847. m_Executor = new Executor(m_Script);
  848. // m_Engine.Log.Debug("[XEngine] Script instance created");
  849. part.SetScriptEvents(m_ItemID,
  850. (int)m_Executor.GetStateEventFlags(State));
  851. }
  852. catch (Exception e)
  853. {
  854. m_Engine.Log.Error("[XEngine] Error loading script instance\n"+e.ToString());
  855. return;
  856. }
  857. string savedState = Path.Combine(Path.GetDirectoryName(assembly),
  858. m_ItemID.ToString() + ".state");
  859. if (File.Exists(savedState))
  860. {
  861. string xml = String.Empty;
  862. try
  863. {
  864. FileInfo fi = new FileInfo(savedState);
  865. int size=(int)fi.Length;
  866. if (size < 512000)
  867. {
  868. using (FileStream fs = File.Open(savedState,
  869. FileMode.Open, FileAccess.Read, FileShare.None))
  870. {
  871. System.Text.ASCIIEncoding enc =
  872. new System.Text.ASCIIEncoding();
  873. Byte[] data = new Byte[size];
  874. fs.Read(data, 0, size);
  875. xml = enc.GetString(data);
  876. ScriptSerializer.Deserialize(xml, this);
  877. m_Engine.m_AsyncCommands.CreateFromData(
  878. m_LocalID, m_ItemID, m_ObjectID,
  879. PluginData);
  880. m_Engine.Log.DebugFormat("[XEngine] Successfully retrieved state for script {0}.{1}", m_PrimName, m_ScriptName);
  881. if (m_RunEvents)
  882. {
  883. m_RunEvents = false;
  884. Start();
  885. if (postOnRez)
  886. PostEvent(new EventParams("on_rez",
  887. new Object[] {new LSL_Types.LSLInteger(startParam)}, new DetectParams[0]));
  888. }
  889. // we get new rez events on sim restart, too
  890. // but if there is state, then we fire the change
  891. // event
  892. if (stateSource == StateSource.NewRez)
  893. {
  894. // m_Engine.Log.Debug("[XEngine] Posted changed(CHANGED_REGION_RESTART) to script");
  895. PostEvent(new EventParams("changed",
  896. new Object[] {new LSL_Types.LSLInteger(256)}, new DetectParams[0]));
  897. }
  898. }
  899. }
  900. else
  901. {
  902. m_Engine.Log.Error("[XEngine] Unable to load script state: Memory limit exceeded");
  903. Start();
  904. PostEvent(new EventParams("state_entry",
  905. new Object[0], new DetectParams[0]));
  906. if (postOnRez)
  907. PostEvent(new EventParams("on_rez",
  908. new Object[] {new LSL_Types.LSLInteger(startParam)}, new DetectParams[0]));
  909. }
  910. }
  911. catch (Exception e)
  912. {
  913. m_Engine.Log.ErrorFormat("[XEngine] Unable to load script state from xml: {0}\n"+e.ToString(), xml);
  914. Start();
  915. PostEvent(new EventParams("state_entry",
  916. new Object[0], new DetectParams[0]));
  917. if (postOnRez)
  918. PostEvent(new EventParams("on_rez",
  919. new Object[] {new LSL_Types.LSLInteger(startParam)}, new DetectParams[0]));
  920. }
  921. }
  922. else
  923. {
  924. // m_Engine.Log.ErrorFormat("[XEngine] Unable to load script state, file not found");
  925. Start();
  926. PostEvent(new EventParams("state_entry",
  927. new Object[0], new DetectParams[0]));
  928. if (postOnRez)
  929. PostEvent(new EventParams("on_rez",
  930. new Object[] {new LSL_Types.LSLInteger(startParam)}, new DetectParams[0]));
  931. }
  932. }
  933. public void RemoveState()
  934. {
  935. string savedState = Path.Combine(Path.GetDirectoryName(m_Assembly),
  936. m_ItemID.ToString() + ".state");
  937. try
  938. {
  939. File.Delete(savedState);
  940. }
  941. catch(Exception)
  942. {
  943. }
  944. }
  945. public void VarDump(Dictionary<string, object> vars)
  946. {
  947. Console.WriteLine("Variable dump for script {0}", m_ItemID.ToString());
  948. foreach (KeyValuePair<string, object> v in vars)
  949. {
  950. Console.WriteLine("Variable: {0} = '{1}'", v. Key,
  951. v.Value.ToString());
  952. }
  953. }
  954. public void Start()
  955. {
  956. lock (m_EventQueue)
  957. {
  958. if (Running)
  959. return;
  960. m_RunEvents = true;
  961. if (m_EventQueue.Count > 0)
  962. {
  963. if (m_CurrentResult == null)
  964. m_CurrentResult = m_Engine.QueueEventHandler(this);
  965. else
  966. m_Engine.Log.Error("[XEngine] Tried to start a script that was already queued");
  967. }
  968. }
  969. }
  970. public bool Stop(int timeout)
  971. {
  972. IWorkItemResult result;
  973. lock (m_EventQueue)
  974. {
  975. if (!Running)
  976. return true;
  977. if (m_CurrentResult == null)
  978. {
  979. m_RunEvents = false;
  980. return true;
  981. }
  982. if (m_CurrentResult.Cancel())
  983. {
  984. m_CurrentResult = null;
  985. m_RunEvents = false;
  986. return true;
  987. }
  988. result = m_CurrentResult;
  989. m_RunEvents = false;
  990. }
  991. if (SmartThreadPool.WaitAll(new IWorkItemResult[] {result}, new TimeSpan((long)timeout * 100000), false))
  992. {
  993. return true;
  994. }
  995. lock (m_EventQueue)
  996. {
  997. result = m_CurrentResult;
  998. }
  999. if (result == null)
  1000. return true;
  1001. if(!m_InSelfDelete)
  1002. result.Abort();
  1003. lock (m_EventQueue)
  1004. {
  1005. m_CurrentResult = null;
  1006. }
  1007. return true;
  1008. }
  1009. public void SetState(string state)
  1010. {
  1011. PostEvent(new EventParams("state_exit", new Object[0],
  1012. new DetectParams[0]));
  1013. PostEvent(new EventParams("state", new Object[] { state },
  1014. new DetectParams[0]));
  1015. PostEvent(new EventParams("state_entry", new Object[0],
  1016. new DetectParams[0]));
  1017. }
  1018. public void PostEvent(EventParams data)
  1019. {
  1020. // m_Engine.Log.DebugFormat("[XEngine] Posted event {2} in state {3} to {0}.{1}",
  1021. // m_PrimName, m_ScriptName, data.EventName, m_State);
  1022. if (!Running)
  1023. return;
  1024. lock (m_EventQueue)
  1025. {
  1026. if (m_EventQueue.Count >= m_Engine.MaxScriptQueue)
  1027. return;
  1028. m_EventQueue.Enqueue(data);
  1029. if (data.EventName == "timer")
  1030. {
  1031. if (m_TimerQueued)
  1032. return;
  1033. m_TimerQueued = true;
  1034. }
  1035. if (!m_RunEvents)
  1036. return;
  1037. if (m_CurrentResult == null)
  1038. {
  1039. m_CurrentResult = m_Engine.QueueEventHandler(this);
  1040. }
  1041. }
  1042. }
  1043. public object EventProcessor()
  1044. {
  1045. EventParams data = null;
  1046. lock (m_EventQueue)
  1047. {
  1048. data = (EventParams) m_EventQueue.Dequeue();
  1049. if (data == null) // Shouldn't happen
  1050. {
  1051. m_CurrentResult = null;
  1052. return 0;
  1053. }
  1054. if (data.EventName == "timer")
  1055. m_TimerQueued = false;
  1056. }
  1057. m_DetectParams = data.DetectParams;
  1058. if (data.EventName == "state") // Hardcoded state change
  1059. {
  1060. // m_Engine.Log.DebugFormat("[XEngine] Script {0}.{1} state set to {2}",
  1061. // m_PrimName, m_ScriptName, data.Params[0].ToString());
  1062. m_State=data.Params[0].ToString();
  1063. m_Engine.m_AsyncCommands.RemoveScript(
  1064. m_LocalID, m_ItemID);
  1065. SceneObjectPart part = m_Engine.World.GetSceneObjectPart(
  1066. m_LocalID);
  1067. if (part != null)
  1068. {
  1069. part.SetScriptEvents(m_ItemID,
  1070. (int)m_Executor.GetStateEventFlags(State));
  1071. }
  1072. }
  1073. else
  1074. {
  1075. SceneObjectPart part = m_Engine.World.GetSceneObjectPart(
  1076. m_LocalID);
  1077. // m_Engine.Log.DebugFormat("[XEngine] Delivered event {2} in state {3} to {0}.{1}",
  1078. // m_PrimName, m_ScriptName, data.EventName, m_State);
  1079. try
  1080. {
  1081. m_CurrentEvent = data.EventName;
  1082. m_EventStart = DateTime.Now;
  1083. m_InEvent = true;
  1084. m_Executor.ExecuteEvent(State, data.EventName, data.Params);
  1085. m_InEvent = false;
  1086. m_CurrentEvent = String.Empty;
  1087. }
  1088. catch (Exception e)
  1089. {
  1090. m_InEvent = false;
  1091. m_CurrentEvent = String.Empty;
  1092. if (!(e is TargetInvocationException) || (!(e.InnerException is EventAbortException) && (!(e.InnerException is SelfDeleteException))))
  1093. {
  1094. if (e is System.Threading.ThreadAbortException)
  1095. {
  1096. lock (m_EventQueue)
  1097. {
  1098. if ((m_EventQueue.Count > 0) && m_RunEvents)
  1099. {
  1100. m_CurrentResult=m_Engine.QueueEventHandler(this);
  1101. }
  1102. else
  1103. {
  1104. m_CurrentResult = null;
  1105. }
  1106. }
  1107. m_DetectParams = null;
  1108. return 0;
  1109. }
  1110. try
  1111. {
  1112. // DISPLAY ERROR INWORLD
  1113. string text = "Runtime error:\n" + e.ToString();
  1114. if (text.Length > 1400)
  1115. text = text.Substring(0, 1400);
  1116. m_Engine.World.SimChat(Helpers.StringToField(text),
  1117. ChatTypeEnum.DebugChannel, 2147483647,
  1118. part.AbsolutePosition,
  1119. part.Name, part.UUID, false);
  1120. }
  1121. catch (Exception e2) // LEGIT: User Scripting
  1122. {
  1123. m_Engine.Log.Error("[XEngine]: "+
  1124. "Error displaying error in-world: " +
  1125. e2.ToString());
  1126. m_Engine.Log.Error("[XEngine]: " +
  1127. "Errormessage: Error compiling script:\r\n" +
  1128. e.ToString());
  1129. }
  1130. }
  1131. else if((e is TargetInvocationException) && (e.InnerException is SelfDeleteException))
  1132. {
  1133. m_InSelfDelete = true;
  1134. if(part != null && part.ParentGroup != null)
  1135. m_Engine.World.DeleteSceneObject(part.ParentGroup);
  1136. }
  1137. }
  1138. }
  1139. lock (m_EventQueue)
  1140. {
  1141. if ((m_EventQueue.Count > 0) && m_RunEvents)
  1142. {
  1143. m_CurrentResult = m_Engine.QueueEventHandler(this);
  1144. }
  1145. else
  1146. {
  1147. m_CurrentResult = null;
  1148. }
  1149. }
  1150. m_DetectParams = null;
  1151. return 0;
  1152. }
  1153. public int EventTime()
  1154. {
  1155. if (!m_InEvent)
  1156. return 0;
  1157. return (DateTime.Now - m_EventStart).Seconds;
  1158. }
  1159. public void ResetScript()
  1160. {
  1161. bool running = Running;
  1162. RemoveState();
  1163. Stop(0);
  1164. SceneObjectPart part=m_Engine.World.GetSceneObjectPart(m_LocalID);
  1165. part.GetInventoryItem(m_ItemID).PermsMask = 0;
  1166. part.GetInventoryItem(m_ItemID).PermsGranter = LLUUID.Zero;
  1167. m_Engine.m_AsyncCommands.RemoveScript(m_LocalID, m_ItemID);
  1168. m_EventQueue.Clear();
  1169. m_Script.ResetVars();
  1170. m_State = "default";
  1171. if (running)
  1172. Start();
  1173. PostEvent(new EventParams("state_entry",
  1174. new Object[0], new DetectParams[0]));
  1175. }
  1176. public void ApiResetScript()
  1177. {
  1178. // bool running = Running;
  1179. RemoveState();
  1180. m_Script.ResetVars();
  1181. SceneObjectPart part=m_Engine.World.GetSceneObjectPart(m_LocalID);
  1182. part.GetInventoryItem(m_ItemID).PermsMask = 0;
  1183. part.GetInventoryItem(m_ItemID).PermsGranter = LLUUID.Zero;
  1184. m_Engine.m_AsyncCommands.RemoveScript(m_LocalID, m_ItemID);
  1185. if (m_CurrentEvent != "state_entry")
  1186. {
  1187. PostEvent(new EventParams("state_entry",
  1188. new Object[0], new DetectParams[0]));
  1189. }
  1190. }
  1191. public Dictionary<string, object> GetVars()
  1192. {
  1193. return m_Script.GetVars();
  1194. }
  1195. public void SetVars(Dictionary<string, object> vars)
  1196. {
  1197. m_Script.SetVars(vars);
  1198. }
  1199. public DetectParams GetDetectParams(int idx)
  1200. {
  1201. if (idx < 0 || idx >= m_DetectParams.Length)
  1202. return null;
  1203. return m_DetectParams[idx];
  1204. }
  1205. public LLUUID GetDetectID(int idx)
  1206. {
  1207. if (idx < 0 || idx >= m_DetectParams.Length)
  1208. return LLUUID.Zero;
  1209. return m_DetectParams[idx].Key;
  1210. }
  1211. public void SaveState(string assembly)
  1212. {
  1213. PluginData =
  1214. m_Engine.m_AsyncCommands.GetSerializationData(
  1215. m_ItemID);
  1216. string xml = ScriptSerializer.Serialize(this);
  1217. try
  1218. {
  1219. FileStream fs = File.Create(Path.Combine(Path.GetDirectoryName(assembly), m_ItemID.ToString() + ".state"));
  1220. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  1221. Byte[] buf = enc.GetBytes(xml);
  1222. fs.Write(buf, 0, buf.Length);
  1223. fs.Close();
  1224. }
  1225. catch(Exception e)
  1226. {
  1227. Console.WriteLine("Unable to save xml\n"+e.ToString());
  1228. }
  1229. if (!File.Exists(Path.Combine(Path.GetDirectoryName(assembly), m_ItemID.ToString() + ".state")))
  1230. {
  1231. throw new Exception("Completed persistence save, but no file was created");
  1232. }
  1233. }
  1234. }
  1235. public class ScriptSerializer
  1236. {
  1237. public static string Serialize(XScriptInstance instance)
  1238. {
  1239. bool running = instance.Running;
  1240. if (running)
  1241. instance.Stop(50);
  1242. XmlDocument xmldoc = new XmlDocument();
  1243. XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
  1244. "", "");
  1245. xmldoc.AppendChild(xmlnode);
  1246. XmlElement rootElement = xmldoc.CreateElement("", "ScriptState",
  1247. "");
  1248. xmldoc.AppendChild(rootElement);
  1249. XmlElement state = xmldoc.CreateElement("", "State", "");
  1250. state.AppendChild(xmldoc.CreateTextNode(instance.State));
  1251. rootElement.AppendChild(state);
  1252. XmlElement run = xmldoc.CreateElement("", "Running", "");
  1253. run.AppendChild(xmldoc.CreateTextNode(
  1254. running.ToString()));
  1255. rootElement.AppendChild(run);
  1256. Dictionary<string, Object> vars = instance.GetVars();
  1257. XmlElement variables = xmldoc.CreateElement("", "Variables", "");
  1258. foreach (KeyValuePair<string, Object> var in vars)
  1259. WriteTypedValue(xmldoc, variables, "Variable", var.Key,
  1260. var.Value);
  1261. rootElement.AppendChild(variables);
  1262. XmlElement queue = xmldoc.CreateElement("", "Queue", "");
  1263. int count = instance.EventQueue.Count;
  1264. while (count > 0)
  1265. {
  1266. EventParams ep = (EventParams)instance.EventQueue.Dequeue();
  1267. instance.EventQueue.Enqueue(ep);
  1268. count--;
  1269. XmlElement item = xmldoc.CreateElement("", "Item", "");
  1270. XmlAttribute itemEvent = xmldoc.CreateAttribute("", "event",
  1271. "");
  1272. itemEvent.Value = ep.EventName;
  1273. item.Attributes.Append(itemEvent);
  1274. XmlElement parms = xmldoc.CreateElement("", "Params", "");
  1275. foreach (Object o in ep.Params)
  1276. WriteTypedValue(xmldoc, parms, "Param", String.Empty, o);
  1277. item.AppendChild(parms);
  1278. XmlElement detect = xmldoc.CreateElement("", "Detected", "");
  1279. foreach (DetectParams det in ep.DetectParams)
  1280. {
  1281. XmlElement objectElem = xmldoc.CreateElement("", "Object",
  1282. "");
  1283. XmlAttribute pos = xmldoc.CreateAttribute("", "pos", "");
  1284. pos.Value = det.OffsetPos.ToString();
  1285. objectElem.Attributes.Append(pos);
  1286. XmlAttribute d_linkNum = xmldoc.CreateAttribute("",
  1287. "linkNum", "");
  1288. d_linkNum.Value = det.LinkNum.ToString();
  1289. objectElem.Attributes.Append(d_linkNum);
  1290. XmlAttribute d_group = xmldoc.CreateAttribute("",
  1291. "group", "");
  1292. d_group.Value = det.Group.ToString();
  1293. objectElem.Attributes.Append(d_group);
  1294. XmlAttribute d_name = xmldoc.CreateAttribute("",
  1295. "name", "");
  1296. d_name.Value = det.Name.ToString();
  1297. objectElem.Attributes.Append(d_name);
  1298. XmlAttribute d_owner = xmldoc.CreateAttribute("",
  1299. "owner", "");
  1300. d_owner.Value = det.Owner.ToString();
  1301. objectElem.Attributes.Append(d_owner);
  1302. XmlAttribute d_position = xmldoc.CreateAttribute("",
  1303. "position", "");
  1304. d_position.Value = det.Position.ToString();
  1305. objectElem.Attributes.Append(d_position);
  1306. XmlAttribute d_rotation = xmldoc.CreateAttribute("",
  1307. "rotation", "");
  1308. d_rotation.Value = det.Rotation.ToString();
  1309. objectElem.Attributes.Append(d_rotation);
  1310. XmlAttribute d_type = xmldoc.CreateAttribute("",
  1311. "type", "");
  1312. d_type.Value = det.Type.ToString();
  1313. objectElem.Attributes.Append(d_type);
  1314. XmlAttribute d_velocity = xmldoc.CreateAttribute("",
  1315. "velocity", "");
  1316. d_velocity.Value = det.Velocity.ToString();
  1317. objectElem.Attributes.Append(d_velocity);
  1318. objectElem.AppendChild(
  1319. xmldoc.CreateTextNode(det.Key.ToString()));
  1320. detect.AppendChild(objectElem);
  1321. }
  1322. item.AppendChild(detect);
  1323. queue.AppendChild(item);
  1324. }
  1325. rootElement.AppendChild(queue);
  1326. XmlNode plugins = xmldoc.CreateElement("", "Plugins", "");
  1327. DumpList(xmldoc, plugins,
  1328. new LSL_Types.list(instance.PluginData));
  1329. rootElement.AppendChild(plugins);
  1330. if (running)
  1331. instance.Start();
  1332. return xmldoc.InnerXml;
  1333. }
  1334. public static void Deserialize(string xml, XScriptInstance instance)
  1335. {
  1336. XmlDocument doc = new XmlDocument();
  1337. Dictionary<string, object> vars = instance.GetVars();
  1338. instance.PluginData = new Object[0];
  1339. doc.LoadXml(xml);
  1340. XmlNodeList rootL = doc.GetElementsByTagName("ScriptState");
  1341. if (rootL.Count != 1)
  1342. {
  1343. return;
  1344. }
  1345. XmlNode rootNode = rootL[0];
  1346. if (rootNode != null)
  1347. {
  1348. object varValue;
  1349. XmlNodeList partL = rootNode.ChildNodes;
  1350. foreach (XmlNode part in partL)
  1351. {
  1352. switch (part.Name)
  1353. {
  1354. case "State":
  1355. instance.State=part.InnerText;
  1356. break;
  1357. case "Running":
  1358. instance.Running=bool.Parse(part.InnerText);
  1359. break;
  1360. case "Variables":
  1361. XmlNodeList varL = part.ChildNodes;
  1362. foreach (XmlNode var in varL)
  1363. {
  1364. string varName;
  1365. varValue=ReadTypedValue(var, out varName);
  1366. if (vars.ContainsKey(varName))
  1367. vars[varName] = varValue;
  1368. }
  1369. instance.SetVars(vars);
  1370. break;
  1371. case "Queue":
  1372. XmlNodeList itemL = part.ChildNodes;
  1373. foreach (XmlNode item in itemL)
  1374. {
  1375. List<Object> parms = new List<Object>();
  1376. List<DetectParams> detected =
  1377. new List<DetectParams>();
  1378. string eventName =
  1379. item.Attributes.GetNamedItem("event").Value;
  1380. XmlNodeList eventL = item.ChildNodes;
  1381. foreach (XmlNode evt in eventL)
  1382. {
  1383. switch (evt.Name)
  1384. {
  1385. case "Params":
  1386. XmlNodeList prms = evt.ChildNodes;
  1387. foreach (XmlNode pm in prms)
  1388. parms.Add(ReadTypedValue(pm));
  1389. break;
  1390. case "Detected":
  1391. XmlNodeList detL = evt.ChildNodes;
  1392. foreach (XmlNode det in detL)
  1393. {
  1394. string vect =
  1395. det.Attributes.GetNamedItem(
  1396. "pos").Value;
  1397. LSL_Types.Vector3 v =
  1398. new LSL_Types.Vector3(vect);
  1399. int d_linkNum=0;
  1400. LLUUID d_group = LLUUID.Zero;
  1401. string d_name = String.Empty;
  1402. LLUUID d_owner = LLUUID.Zero;
  1403. LSL_Types.Vector3 d_position =
  1404. new LSL_Types.Vector3();
  1405. LSL_Types.Quaternion d_rotation =
  1406. new LSL_Types.Quaternion();
  1407. int d_type = 0;
  1408. LSL_Types.Vector3 d_velocity =
  1409. new LSL_Types.Vector3();
  1410. try
  1411. {
  1412. string tmp;
  1413. tmp = det.Attributes.GetNamedItem(
  1414. "linkNum").Value;
  1415. int.TryParse(tmp, out d_linkNum);
  1416. tmp = det.Attributes.GetNamedItem(
  1417. "group").Value;
  1418. LLUUID.TryParse(tmp, out d_group);
  1419. d_name = det.Attributes.GetNamedItem(
  1420. "name").Value;
  1421. tmp = det.Attributes.GetNamedItem(
  1422. "owner").Value;
  1423. LLUUID.TryParse(tmp, out d_owner);
  1424. tmp = det.Attributes.GetNamedItem(
  1425. "position").Value;
  1426. d_position =
  1427. new LSL_Types.Vector3(tmp);
  1428. tmp = det.Attributes.GetNamedItem(
  1429. "rotation").Value;
  1430. d_rotation =
  1431. new LSL_Types.Quaternion(tmp);
  1432. tmp = det.Attributes.GetNamedItem(
  1433. "type").Value;
  1434. int.TryParse(tmp, out d_type);
  1435. tmp = det.Attributes.GetNamedItem(
  1436. "velocity").Value;
  1437. d_velocity =
  1438. new LSL_Types.Vector3(tmp);
  1439. }
  1440. catch (Exception) // Old version XML
  1441. {
  1442. }
  1443. LLUUID uuid = new LLUUID();
  1444. LLUUID.TryParse(det.InnerText,
  1445. out uuid);
  1446. DetectParams d = new DetectParams();
  1447. d.Key = uuid;
  1448. d.OffsetPos = v;
  1449. d.LinkNum = d_linkNum;
  1450. d.Group = d_group;
  1451. d.Name = d_name;
  1452. d.Owner = d_owner;
  1453. d.Position = d_position;
  1454. d.Rotation = d_rotation;
  1455. d.Type = d_type;
  1456. d.Velocity = d_velocity;
  1457. detected.Add(d);
  1458. }
  1459. break;
  1460. }
  1461. }
  1462. EventParams ep = new EventParams(
  1463. eventName, parms.ToArray(),
  1464. detected.ToArray());
  1465. instance.EventQueue.Enqueue(ep);
  1466. }
  1467. break;
  1468. case "Plugins":
  1469. instance.PluginData = ReadList(part).Data;
  1470. break;
  1471. }
  1472. }
  1473. }
  1474. }
  1475. private static void DumpList(XmlDocument doc, XmlNode parent,
  1476. LSL_Types.list l)
  1477. {
  1478. foreach (Object o in l.Data)
  1479. WriteTypedValue(doc, parent, "ListItem", "", o);
  1480. }
  1481. private static LSL_Types.list ReadList(XmlNode parent)
  1482. {
  1483. List<Object> olist = new List<Object>();
  1484. XmlNodeList itemL = parent.ChildNodes;
  1485. foreach (XmlNode item in itemL)
  1486. olist.Add(ReadTypedValue(item));
  1487. return new LSL_Types.list(olist.ToArray());
  1488. }
  1489. private static void WriteTypedValue(XmlDocument doc, XmlNode parent,
  1490. string tag, string name, object value)
  1491. {
  1492. Type t=value.GetType();
  1493. XmlAttribute typ = doc.CreateAttribute("", "type", "");
  1494. XmlNode n = doc.CreateElement("", tag, "");
  1495. if (value is LSL_Types.list)
  1496. {
  1497. typ.Value = "list";
  1498. n.Attributes.Append(typ);
  1499. DumpList(doc, n, (LSL_Types.list) value);
  1500. if (name != String.Empty)
  1501. {
  1502. XmlAttribute nam = doc.CreateAttribute("", "name", "");
  1503. nam.Value = name;
  1504. n.Attributes.Append(nam);
  1505. }
  1506. parent.AppendChild(n);
  1507. return;
  1508. }
  1509. n.AppendChild(doc.CreateTextNode(value.ToString()));
  1510. typ.Value = t.ToString();
  1511. n.Attributes.Append(typ);
  1512. if (name != String.Empty)
  1513. {
  1514. XmlAttribute nam = doc.CreateAttribute("", "name", "");
  1515. nam.Value = name;
  1516. n.Attributes.Append(nam);
  1517. }
  1518. parent.AppendChild(n);
  1519. }
  1520. private static object ReadTypedValue(XmlNode tag, out string name)
  1521. {
  1522. name = tag.Attributes.GetNamedItem("name").Value;
  1523. return ReadTypedValue(tag);
  1524. }
  1525. private static object ReadTypedValue(XmlNode tag)
  1526. {
  1527. Object varValue;
  1528. string assembly;
  1529. string itemType = tag.Attributes.GetNamedItem("type").Value;
  1530. if (itemType == "list")
  1531. return ReadList(tag);
  1532. if (itemType == "libsecondlife.LLUUID")
  1533. {
  1534. LLUUID val = new LLUUID();
  1535. LLUUID.TryParse(tag.InnerText, out val);
  1536. return val;
  1537. }
  1538. Type itemT = Type.GetType(itemType);
  1539. if (itemT == null)
  1540. {
  1541. Object[] args =
  1542. new Object[] { tag.InnerText };
  1543. assembly = itemType+", OpenSim.Region.ScriptEngine.Shared";
  1544. itemT = Type.GetType(assembly);
  1545. if (itemT == null)
  1546. return null;
  1547. varValue = Activator.CreateInstance(itemT, args);
  1548. if (varValue == null)
  1549. return null;
  1550. }
  1551. else
  1552. {
  1553. varValue = Convert.ChangeType(tag.InnerText, itemT);
  1554. }
  1555. return varValue;
  1556. }
  1557. }
  1558. }