XEngine.cs 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870
  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 Dictionary<string,IScriptApi> m_Apis = new Dictionary<string,IScriptApi>();
  738. public enum StateSource
  739. {
  740. NewRez = 0,
  741. PrimCrossing = 1,
  742. AttachmentCrossing = 2
  743. }
  744. // Script state
  745. private string m_State="default";
  746. public Object[] PluginData = new Object[0];
  747. public bool Running
  748. {
  749. get { return m_RunEvents; }
  750. set { m_RunEvents = value; }
  751. }
  752. public string State
  753. {
  754. get { return m_State; }
  755. set { m_State = value; }
  756. }
  757. public XEngine Engine
  758. {
  759. get { return m_Engine; }
  760. }
  761. public LLUUID AppDomain
  762. {
  763. get { return m_AppDomain; }
  764. set { m_AppDomain = value; }
  765. }
  766. public string PrimName
  767. {
  768. get { return m_PrimName; }
  769. }
  770. public string ScriptName
  771. {
  772. get { return m_ScriptName; }
  773. }
  774. public LLUUID ItemID
  775. {
  776. get { return m_ItemID; }
  777. }
  778. public LLUUID ObjectID
  779. {
  780. get { return m_ObjectID; }
  781. }
  782. public uint LocalID
  783. {
  784. get { return m_LocalID; }
  785. }
  786. public LLUUID AssetID
  787. {
  788. get { return m_AssetID; }
  789. }
  790. public Queue EventQueue
  791. {
  792. get { return m_EventQueue; }
  793. }
  794. public void ClearQueue()
  795. {
  796. m_TimerQueued = false;
  797. m_EventQueue.Clear();
  798. }
  799. public int StartParam
  800. {
  801. get { return m_StartParam; }
  802. set { m_StartParam = value; }
  803. }
  804. public XScriptInstance(XEngine engine, uint localID, LLUUID objectID,
  805. LLUUID itemID, LLUUID assetID, string assembly, AppDomain dom,
  806. string primName, string scriptName, int startParam,
  807. bool postOnRez, StateSource stateSource)
  808. {
  809. m_Engine = engine;
  810. m_LocalID = localID;
  811. m_ObjectID = objectID;
  812. m_ItemID = itemID;
  813. m_AssetID = assetID;
  814. m_PrimName = primName;
  815. m_ScriptName = scriptName;
  816. m_Assembly = assembly;
  817. m_StartParam = startParam;
  818. ApiManager am = new ApiManager();
  819. SceneObjectPart part=engine.World.GetSceneObjectPart(localID);
  820. if (part == null)
  821. {
  822. engine.Log.Error("[XEngine] SceneObjectPart unavailable. Script NOT started.");
  823. return;
  824. }
  825. foreach (string api in am.GetApis())
  826. {
  827. m_Apis[api] = am.CreateApi(api);
  828. m_Apis[api].Initialize(engine, part, localID, itemID);
  829. }
  830. try
  831. {
  832. m_Script = (IScript)dom.CreateInstanceAndUnwrap(
  833. Path.GetFileNameWithoutExtension(assembly),
  834. "SecondLife.Script");
  835. }
  836. catch (Exception e)
  837. {
  838. m_Engine.Log.ErrorFormat("[XEngine] Error loading assembly {0}\n"+e.ToString(), assembly);
  839. }
  840. try
  841. {
  842. foreach (KeyValuePair<string,IScriptApi> kv in m_Apis)
  843. {
  844. m_Script.InitApi(kv.Key, kv.Value);
  845. }
  846. m_Executor = new Executor(m_Script);
  847. // m_Engine.Log.Debug("[XEngine] Script instance created");
  848. part.SetScriptEvents(m_ItemID,
  849. (int)m_Executor.GetStateEventFlags(State));
  850. }
  851. catch (Exception e)
  852. {
  853. m_Engine.Log.Error("[XEngine] Error loading script instance\n"+e.ToString());
  854. return;
  855. }
  856. string savedState = Path.Combine(Path.GetDirectoryName(assembly),
  857. m_ItemID.ToString() + ".state");
  858. if (File.Exists(savedState))
  859. {
  860. string xml = String.Empty;
  861. try
  862. {
  863. FileInfo fi = new FileInfo(savedState);
  864. int size=(int)fi.Length;
  865. if (size < 512000)
  866. {
  867. using (FileStream fs = File.Open(savedState,
  868. FileMode.Open, FileAccess.Read, FileShare.None))
  869. {
  870. System.Text.ASCIIEncoding enc =
  871. new System.Text.ASCIIEncoding();
  872. Byte[] data = new Byte[size];
  873. fs.Read(data, 0, size);
  874. xml = enc.GetString(data);
  875. ScriptSerializer.Deserialize(xml, this);
  876. m_Engine.m_AsyncCommands.CreateFromData(
  877. m_LocalID, m_ItemID, m_ObjectID,
  878. PluginData);
  879. m_Engine.Log.DebugFormat("[XEngine] Successfully retrieved state for script {0}.{1}", m_PrimName, m_ScriptName);
  880. if (m_RunEvents)
  881. {
  882. m_RunEvents = false;
  883. Start();
  884. if (postOnRez)
  885. PostEvent(new EventParams("on_rez",
  886. new Object[] {new LSL_Types.LSLInteger(startParam)}, new DetectParams[0]));
  887. }
  888. // we get new rez events on sim restart, too
  889. // but if there is state, then we fire the change
  890. // event
  891. if (stateSource == StateSource.NewRez)
  892. {
  893. // m_Engine.Log.Debug("[XEngine] Posted changed(CHANGED_REGION_RESTART) to script");
  894. PostEvent(new EventParams("changed",
  895. new Object[] {new LSL_Types.LSLInteger(256)}, new DetectParams[0]));
  896. }
  897. }
  898. }
  899. else
  900. {
  901. m_Engine.Log.Error("[XEngine] Unable to load script state: Memory limit exceeded");
  902. Start();
  903. PostEvent(new EventParams("state_entry",
  904. new Object[0], new DetectParams[0]));
  905. if (postOnRez)
  906. PostEvent(new EventParams("on_rez",
  907. new Object[] {new LSL_Types.LSLInteger(startParam)}, new DetectParams[0]));
  908. }
  909. }
  910. catch (Exception e)
  911. {
  912. m_Engine.Log.ErrorFormat("[XEngine] Unable to load script state from xml: {0}\n"+e.ToString(), xml);
  913. Start();
  914. PostEvent(new EventParams("state_entry",
  915. new Object[0], new DetectParams[0]));
  916. if (postOnRez)
  917. PostEvent(new EventParams("on_rez",
  918. new Object[] {new LSL_Types.LSLInteger(startParam)}, new DetectParams[0]));
  919. }
  920. }
  921. else
  922. {
  923. // m_Engine.Log.ErrorFormat("[XEngine] Unable to load script state, file not found");
  924. Start();
  925. PostEvent(new EventParams("state_entry",
  926. new Object[0], new DetectParams[0]));
  927. if (postOnRez)
  928. PostEvent(new EventParams("on_rez",
  929. new Object[] {new LSL_Types.LSLInteger(startParam)}, new DetectParams[0]));
  930. }
  931. }
  932. public void RemoveState()
  933. {
  934. string savedState = Path.Combine(Path.GetDirectoryName(m_Assembly),
  935. m_ItemID.ToString() + ".state");
  936. try
  937. {
  938. File.Delete(savedState);
  939. }
  940. catch(Exception)
  941. {
  942. }
  943. }
  944. public void VarDump(Dictionary<string, object> vars)
  945. {
  946. Console.WriteLine("Variable dump for script {0}", m_ItemID.ToString());
  947. foreach (KeyValuePair<string, object> v in vars)
  948. {
  949. Console.WriteLine("Variable: {0} = '{1}'", v. Key,
  950. v.Value.ToString());
  951. }
  952. }
  953. public void Start()
  954. {
  955. lock (m_EventQueue)
  956. {
  957. if (Running)
  958. return;
  959. m_RunEvents = true;
  960. if (m_EventQueue.Count > 0)
  961. {
  962. if (m_CurrentResult == null)
  963. m_CurrentResult = m_Engine.QueueEventHandler(this);
  964. else
  965. m_Engine.Log.Error("[XEngine] Tried to start a script that was already queued");
  966. }
  967. }
  968. }
  969. public bool Stop(int timeout)
  970. {
  971. IWorkItemResult result;
  972. lock (m_EventQueue)
  973. {
  974. if (!Running)
  975. return true;
  976. if (m_CurrentResult == null)
  977. {
  978. m_RunEvents = false;
  979. return true;
  980. }
  981. if (m_CurrentResult.Cancel())
  982. {
  983. m_CurrentResult = null;
  984. m_RunEvents = false;
  985. return true;
  986. }
  987. result = m_CurrentResult;
  988. m_RunEvents = false;
  989. }
  990. if (SmartThreadPool.WaitAll(new IWorkItemResult[] {result}, new TimeSpan((long)timeout * 100000), false))
  991. {
  992. return true;
  993. }
  994. lock (m_EventQueue)
  995. {
  996. result = m_CurrentResult;
  997. }
  998. if (result == null)
  999. return true;
  1000. result.Abort();
  1001. lock (m_EventQueue)
  1002. {
  1003. m_CurrentResult = null;
  1004. }
  1005. return true;
  1006. }
  1007. public void SetState(string state)
  1008. {
  1009. PostEvent(new EventParams("state_exit", new Object[0],
  1010. new DetectParams[0]));
  1011. PostEvent(new EventParams("state", new Object[] { state },
  1012. new DetectParams[0]));
  1013. PostEvent(new EventParams("state_entry", new Object[0],
  1014. new DetectParams[0]));
  1015. }
  1016. public void PostEvent(EventParams data)
  1017. {
  1018. // m_Engine.Log.DebugFormat("[XEngine] Posted event {2} in state {3} to {0}.{1}",
  1019. // m_PrimName, m_ScriptName, data.EventName, m_State);
  1020. if (!Running)
  1021. return;
  1022. lock (m_EventQueue)
  1023. {
  1024. if (m_EventQueue.Count >= m_Engine.MaxScriptQueue)
  1025. return;
  1026. m_EventQueue.Enqueue(data);
  1027. if (data.EventName == "timer")
  1028. {
  1029. if (m_TimerQueued)
  1030. return;
  1031. m_TimerQueued = true;
  1032. }
  1033. if (!m_RunEvents)
  1034. return;
  1035. if (m_CurrentResult == null)
  1036. {
  1037. m_CurrentResult = m_Engine.QueueEventHandler(this);
  1038. }
  1039. }
  1040. }
  1041. public object EventProcessor()
  1042. {
  1043. EventParams data = null;
  1044. lock (m_EventQueue)
  1045. {
  1046. data = (EventParams) m_EventQueue.Dequeue();
  1047. if (data == null) // Shouldn't happen
  1048. {
  1049. m_CurrentResult = null;
  1050. return 0;
  1051. }
  1052. if (data.EventName == "timer")
  1053. m_TimerQueued = false;
  1054. }
  1055. m_DetectParams = data.DetectParams;
  1056. if (data.EventName == "state") // Hardcoded state change
  1057. {
  1058. // m_Engine.Log.DebugFormat("[XEngine] Script {0}.{1} state set to {2}",
  1059. // m_PrimName, m_ScriptName, data.Params[0].ToString());
  1060. m_State=data.Params[0].ToString();
  1061. m_Engine.m_AsyncCommands.RemoveScript(
  1062. m_LocalID, m_ItemID);
  1063. SceneObjectPart part = m_Engine.World.GetSceneObjectPart(
  1064. m_LocalID);
  1065. if (part != null)
  1066. {
  1067. part.SetScriptEvents(m_ItemID,
  1068. (int)m_Executor.GetStateEventFlags(State));
  1069. }
  1070. }
  1071. else
  1072. {
  1073. SceneObjectPart part = m_Engine.World.GetSceneObjectPart(
  1074. m_LocalID);
  1075. // m_Engine.Log.DebugFormat("[XEngine] Delivered event {2} in state {3} to {0}.{1}",
  1076. // m_PrimName, m_ScriptName, data.EventName, m_State);
  1077. try
  1078. {
  1079. m_CurrentEvent = data.EventName;
  1080. m_EventStart = DateTime.Now;
  1081. m_InEvent = true;
  1082. m_Executor.ExecuteEvent(State, data.EventName, data.Params);
  1083. m_InEvent = false;
  1084. m_CurrentEvent = String.Empty;
  1085. }
  1086. catch (Exception e)
  1087. {
  1088. m_InEvent = false;
  1089. m_CurrentEvent = String.Empty;
  1090. if (!(e is TargetInvocationException) || !(e.InnerException is EventAbortException))
  1091. {
  1092. if (e is System.Threading.ThreadAbortException)
  1093. {
  1094. lock (m_EventQueue)
  1095. {
  1096. if ((m_EventQueue.Count > 0) && m_RunEvents)
  1097. {
  1098. m_CurrentResult=m_Engine.QueueEventHandler(this);
  1099. }
  1100. else
  1101. {
  1102. m_CurrentResult = null;
  1103. }
  1104. }
  1105. m_DetectParams = null;
  1106. return 0;
  1107. }
  1108. try
  1109. {
  1110. // DISPLAY ERROR INWORLD
  1111. string text = "Runtime error:\n" + e.ToString();
  1112. if (text.Length > 1400)
  1113. text = text.Substring(0, 1400);
  1114. m_Engine.World.SimChat(Helpers.StringToField(text),
  1115. ChatTypeEnum.DebugChannel, 2147483647,
  1116. part.AbsolutePosition,
  1117. part.Name, part.UUID, false);
  1118. }
  1119. catch (Exception e2) // LEGIT: User Scripting
  1120. {
  1121. m_Engine.Log.Error("[XEngine]: "+
  1122. "Error displaying error in-world: " +
  1123. e2.ToString());
  1124. m_Engine.Log.Error("[XEngine]: " +
  1125. "Errormessage: Error compiling script:\r\n" +
  1126. e.ToString());
  1127. }
  1128. }
  1129. }
  1130. }
  1131. lock (m_EventQueue)
  1132. {
  1133. if ((m_EventQueue.Count > 0) && m_RunEvents)
  1134. {
  1135. m_CurrentResult = m_Engine.QueueEventHandler(this);
  1136. }
  1137. else
  1138. {
  1139. m_CurrentResult = null;
  1140. }
  1141. }
  1142. m_DetectParams = null;
  1143. return 0;
  1144. }
  1145. public int EventTime()
  1146. {
  1147. if (!m_InEvent)
  1148. return 0;
  1149. return (DateTime.Now - m_EventStart).Seconds;
  1150. }
  1151. public void ResetScript()
  1152. {
  1153. bool running = Running;
  1154. RemoveState();
  1155. Stop(0);
  1156. SceneObjectPart part=m_Engine.World.GetSceneObjectPart(m_LocalID);
  1157. part.GetInventoryItem(m_ItemID).PermsMask = 0;
  1158. part.GetInventoryItem(m_ItemID).PermsGranter = LLUUID.Zero;
  1159. m_Engine.m_AsyncCommands.RemoveScript(m_LocalID, m_ItemID);
  1160. m_EventQueue.Clear();
  1161. m_Script.ResetVars();
  1162. m_State = "default";
  1163. if (running)
  1164. Start();
  1165. PostEvent(new EventParams("state_entry",
  1166. new Object[0], new DetectParams[0]));
  1167. }
  1168. public void ApiResetScript()
  1169. {
  1170. // bool running = Running;
  1171. RemoveState();
  1172. m_Script.ResetVars();
  1173. SceneObjectPart part=m_Engine.World.GetSceneObjectPart(m_LocalID);
  1174. part.GetInventoryItem(m_ItemID).PermsMask = 0;
  1175. part.GetInventoryItem(m_ItemID).PermsGranter = LLUUID.Zero;
  1176. m_Engine.m_AsyncCommands.RemoveScript(m_LocalID, m_ItemID);
  1177. if (m_CurrentEvent != "state_entry")
  1178. {
  1179. PostEvent(new EventParams("state_entry",
  1180. new Object[0], new DetectParams[0]));
  1181. }
  1182. }
  1183. public Dictionary<string, object> GetVars()
  1184. {
  1185. return m_Script.GetVars();
  1186. }
  1187. public void SetVars(Dictionary<string, object> vars)
  1188. {
  1189. m_Script.SetVars(vars);
  1190. }
  1191. public DetectParams GetDetectParams(int idx)
  1192. {
  1193. if (idx < 0 || idx >= m_DetectParams.Length)
  1194. return null;
  1195. return m_DetectParams[idx];
  1196. }
  1197. public LLUUID GetDetectID(int idx)
  1198. {
  1199. if (idx < 0 || idx >= m_DetectParams.Length)
  1200. return LLUUID.Zero;
  1201. return m_DetectParams[idx].Key;
  1202. }
  1203. public void SaveState(string assembly)
  1204. {
  1205. PluginData =
  1206. m_Engine.m_AsyncCommands.GetSerializationData(
  1207. m_ItemID);
  1208. string xml = ScriptSerializer.Serialize(this);
  1209. try
  1210. {
  1211. FileStream fs = File.Create(Path.Combine(Path.GetDirectoryName(assembly), m_ItemID.ToString() + ".state"));
  1212. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  1213. Byte[] buf = enc.GetBytes(xml);
  1214. fs.Write(buf, 0, buf.Length);
  1215. fs.Close();
  1216. }
  1217. catch(Exception e)
  1218. {
  1219. Console.WriteLine("Unable to save xml\n"+e.ToString());
  1220. }
  1221. if (!File.Exists(Path.Combine(Path.GetDirectoryName(assembly), m_ItemID.ToString() + ".state")))
  1222. {
  1223. throw new Exception("Completed persistence save, but no file was created");
  1224. }
  1225. }
  1226. }
  1227. public class ScriptSerializer
  1228. {
  1229. public static string Serialize(XScriptInstance instance)
  1230. {
  1231. bool running = instance.Running;
  1232. if (running)
  1233. instance.Stop(50);
  1234. XmlDocument xmldoc = new XmlDocument();
  1235. XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
  1236. "", "");
  1237. xmldoc.AppendChild(xmlnode);
  1238. XmlElement rootElement = xmldoc.CreateElement("", "ScriptState",
  1239. "");
  1240. xmldoc.AppendChild(rootElement);
  1241. XmlElement state = xmldoc.CreateElement("", "State", "");
  1242. state.AppendChild(xmldoc.CreateTextNode(instance.State));
  1243. rootElement.AppendChild(state);
  1244. XmlElement run = xmldoc.CreateElement("", "Running", "");
  1245. run.AppendChild(xmldoc.CreateTextNode(
  1246. running.ToString()));
  1247. rootElement.AppendChild(run);
  1248. Dictionary<string, Object> vars = instance.GetVars();
  1249. XmlElement variables = xmldoc.CreateElement("", "Variables", "");
  1250. foreach (KeyValuePair<string, Object> var in vars)
  1251. WriteTypedValue(xmldoc, variables, "Variable", var.Key,
  1252. var.Value);
  1253. rootElement.AppendChild(variables);
  1254. XmlElement queue = xmldoc.CreateElement("", "Queue", "");
  1255. int count = instance.EventQueue.Count;
  1256. while (count > 0)
  1257. {
  1258. EventParams ep = (EventParams)instance.EventQueue.Dequeue();
  1259. instance.EventQueue.Enqueue(ep);
  1260. count--;
  1261. XmlElement item = xmldoc.CreateElement("", "Item", "");
  1262. XmlAttribute itemEvent = xmldoc.CreateAttribute("", "event",
  1263. "");
  1264. itemEvent.Value = ep.EventName;
  1265. item.Attributes.Append(itemEvent);
  1266. XmlElement parms = xmldoc.CreateElement("", "Params", "");
  1267. foreach (Object o in ep.Params)
  1268. WriteTypedValue(xmldoc, parms, "Param", String.Empty, o);
  1269. item.AppendChild(parms);
  1270. XmlElement detect = xmldoc.CreateElement("", "Detected", "");
  1271. foreach (DetectParams det in ep.DetectParams)
  1272. {
  1273. XmlElement objectElem = xmldoc.CreateElement("", "Object",
  1274. "");
  1275. XmlAttribute pos = xmldoc.CreateAttribute("", "pos", "");
  1276. pos.Value = det.OffsetPos.ToString();
  1277. objectElem.Attributes.Append(pos);
  1278. XmlAttribute d_linkNum = xmldoc.CreateAttribute("",
  1279. "linkNum", "");
  1280. d_linkNum.Value = det.LinkNum.ToString();
  1281. objectElem.Attributes.Append(d_linkNum);
  1282. XmlAttribute d_group = xmldoc.CreateAttribute("",
  1283. "group", "");
  1284. d_group.Value = det.Group.ToString();
  1285. objectElem.Attributes.Append(d_group);
  1286. XmlAttribute d_name = xmldoc.CreateAttribute("",
  1287. "name", "");
  1288. d_name.Value = det.Name.ToString();
  1289. objectElem.Attributes.Append(d_name);
  1290. XmlAttribute d_owner = xmldoc.CreateAttribute("",
  1291. "owner", "");
  1292. d_owner.Value = det.Owner.ToString();
  1293. objectElem.Attributes.Append(d_owner);
  1294. XmlAttribute d_position = xmldoc.CreateAttribute("",
  1295. "position", "");
  1296. d_position.Value = det.Position.ToString();
  1297. objectElem.Attributes.Append(d_position);
  1298. XmlAttribute d_rotation = xmldoc.CreateAttribute("",
  1299. "rotation", "");
  1300. d_rotation.Value = det.Rotation.ToString();
  1301. objectElem.Attributes.Append(d_rotation);
  1302. XmlAttribute d_type = xmldoc.CreateAttribute("",
  1303. "type", "");
  1304. d_type.Value = det.Type.ToString();
  1305. objectElem.Attributes.Append(d_type);
  1306. XmlAttribute d_velocity = xmldoc.CreateAttribute("",
  1307. "velocity", "");
  1308. d_velocity.Value = det.Velocity.ToString();
  1309. objectElem.Attributes.Append(d_velocity);
  1310. objectElem.AppendChild(
  1311. xmldoc.CreateTextNode(det.Key.ToString()));
  1312. detect.AppendChild(objectElem);
  1313. }
  1314. item.AppendChild(detect);
  1315. queue.AppendChild(item);
  1316. }
  1317. rootElement.AppendChild(queue);
  1318. XmlNode plugins = xmldoc.CreateElement("", "Plugins", "");
  1319. DumpList(xmldoc, plugins,
  1320. new LSL_Types.list(instance.PluginData));
  1321. rootElement.AppendChild(plugins);
  1322. if (running)
  1323. instance.Start();
  1324. return xmldoc.InnerXml;
  1325. }
  1326. public static void Deserialize(string xml, XScriptInstance instance)
  1327. {
  1328. XmlDocument doc = new XmlDocument();
  1329. Dictionary<string, object> vars = instance.GetVars();
  1330. instance.PluginData = new Object[0];
  1331. doc.LoadXml(xml);
  1332. XmlNodeList rootL = doc.GetElementsByTagName("ScriptState");
  1333. if (rootL.Count != 1)
  1334. {
  1335. return;
  1336. }
  1337. XmlNode rootNode = rootL[0];
  1338. if (rootNode != null)
  1339. {
  1340. object varValue;
  1341. XmlNodeList partL = rootNode.ChildNodes;
  1342. foreach (XmlNode part in partL)
  1343. {
  1344. switch (part.Name)
  1345. {
  1346. case "State":
  1347. instance.State=part.InnerText;
  1348. break;
  1349. case "Running":
  1350. instance.Running=bool.Parse(part.InnerText);
  1351. break;
  1352. case "Variables":
  1353. XmlNodeList varL = part.ChildNodes;
  1354. foreach (XmlNode var in varL)
  1355. {
  1356. string varName;
  1357. varValue=ReadTypedValue(var, out varName);
  1358. if (vars.ContainsKey(varName))
  1359. vars[varName] = varValue;
  1360. }
  1361. instance.SetVars(vars);
  1362. break;
  1363. case "Queue":
  1364. XmlNodeList itemL = part.ChildNodes;
  1365. foreach (XmlNode item in itemL)
  1366. {
  1367. List<Object> parms = new List<Object>();
  1368. List<DetectParams> detected =
  1369. new List<DetectParams>();
  1370. string eventName =
  1371. item.Attributes.GetNamedItem("event").Value;
  1372. XmlNodeList eventL = item.ChildNodes;
  1373. foreach (XmlNode evt in eventL)
  1374. {
  1375. switch (evt.Name)
  1376. {
  1377. case "Params":
  1378. XmlNodeList prms = evt.ChildNodes;
  1379. foreach (XmlNode pm in prms)
  1380. parms.Add(ReadTypedValue(pm));
  1381. break;
  1382. case "Detected":
  1383. XmlNodeList detL = evt.ChildNodes;
  1384. foreach (XmlNode det in detL)
  1385. {
  1386. string vect =
  1387. det.Attributes.GetNamedItem(
  1388. "pos").Value;
  1389. LSL_Types.Vector3 v =
  1390. new LSL_Types.Vector3(vect);
  1391. int d_linkNum=0;
  1392. LLUUID d_group = LLUUID.Zero;
  1393. string d_name = String.Empty;
  1394. LLUUID d_owner = LLUUID.Zero;
  1395. LSL_Types.Vector3 d_position =
  1396. new LSL_Types.Vector3();
  1397. LSL_Types.Quaternion d_rotation =
  1398. new LSL_Types.Quaternion();
  1399. int d_type = 0;
  1400. LSL_Types.Vector3 d_velocity =
  1401. new LSL_Types.Vector3();
  1402. try
  1403. {
  1404. string tmp;
  1405. tmp = det.Attributes.GetNamedItem(
  1406. "linkNum").Value;
  1407. int.TryParse(tmp, out d_linkNum);
  1408. tmp = det.Attributes.GetNamedItem(
  1409. "group").Value;
  1410. LLUUID.TryParse(tmp, out d_group);
  1411. d_name = det.Attributes.GetNamedItem(
  1412. "name").Value;
  1413. tmp = det.Attributes.GetNamedItem(
  1414. "owner").Value;
  1415. LLUUID.TryParse(tmp, out d_owner);
  1416. tmp = det.Attributes.GetNamedItem(
  1417. "position").Value;
  1418. d_position =
  1419. new LSL_Types.Vector3(tmp);
  1420. tmp = det.Attributes.GetNamedItem(
  1421. "rotation").Value;
  1422. d_rotation =
  1423. new LSL_Types.Quaternion(tmp);
  1424. tmp = det.Attributes.GetNamedItem(
  1425. "type").Value;
  1426. int.TryParse(tmp, out d_type);
  1427. tmp = det.Attributes.GetNamedItem(
  1428. "velocity").Value;
  1429. d_velocity =
  1430. new LSL_Types.Vector3(tmp);
  1431. }
  1432. catch (Exception) // Old version XML
  1433. {
  1434. }
  1435. LLUUID uuid = new LLUUID();
  1436. LLUUID.TryParse(det.InnerText,
  1437. out uuid);
  1438. DetectParams d = new DetectParams();
  1439. d.Key = uuid;
  1440. d.OffsetPos = v;
  1441. d.LinkNum = d_linkNum;
  1442. d.Group = d_group;
  1443. d.Name = d_name;
  1444. d.Owner = d_owner;
  1445. d.Position = d_position;
  1446. d.Rotation = d_rotation;
  1447. d.Type = d_type;
  1448. d.Velocity = d_velocity;
  1449. detected.Add(d);
  1450. }
  1451. break;
  1452. }
  1453. }
  1454. EventParams ep = new EventParams(
  1455. eventName, parms.ToArray(),
  1456. detected.ToArray());
  1457. instance.EventQueue.Enqueue(ep);
  1458. }
  1459. break;
  1460. case "Plugins":
  1461. instance.PluginData = ReadList(part).Data;
  1462. break;
  1463. }
  1464. }
  1465. }
  1466. }
  1467. private static void DumpList(XmlDocument doc, XmlNode parent,
  1468. LSL_Types.list l)
  1469. {
  1470. foreach (Object o in l.Data)
  1471. WriteTypedValue(doc, parent, "ListItem", "", o);
  1472. }
  1473. private static LSL_Types.list ReadList(XmlNode parent)
  1474. {
  1475. List<Object> olist = new List<Object>();
  1476. XmlNodeList itemL = parent.ChildNodes;
  1477. foreach (XmlNode item in itemL)
  1478. olist.Add(ReadTypedValue(item));
  1479. return new LSL_Types.list(olist.ToArray());
  1480. }
  1481. private static void WriteTypedValue(XmlDocument doc, XmlNode parent,
  1482. string tag, string name, object value)
  1483. {
  1484. Type t=value.GetType();
  1485. XmlAttribute typ = doc.CreateAttribute("", "type", "");
  1486. XmlNode n = doc.CreateElement("", tag, "");
  1487. if (value is LSL_Types.list)
  1488. {
  1489. typ.Value = "list";
  1490. n.Attributes.Append(typ);
  1491. DumpList(doc, n, (LSL_Types.list) value);
  1492. if (name != String.Empty)
  1493. {
  1494. XmlAttribute nam = doc.CreateAttribute("", "name", "");
  1495. nam.Value = name;
  1496. n.Attributes.Append(nam);
  1497. }
  1498. parent.AppendChild(n);
  1499. return;
  1500. }
  1501. n.AppendChild(doc.CreateTextNode(value.ToString()));
  1502. typ.Value = t.ToString();
  1503. n.Attributes.Append(typ);
  1504. if (name != String.Empty)
  1505. {
  1506. XmlAttribute nam = doc.CreateAttribute("", "name", "");
  1507. nam.Value = name;
  1508. n.Attributes.Append(nam);
  1509. }
  1510. parent.AppendChild(n);
  1511. }
  1512. private static object ReadTypedValue(XmlNode tag, out string name)
  1513. {
  1514. name = tag.Attributes.GetNamedItem("name").Value;
  1515. return ReadTypedValue(tag);
  1516. }
  1517. private static object ReadTypedValue(XmlNode tag)
  1518. {
  1519. Object varValue;
  1520. string assembly;
  1521. string itemType = tag.Attributes.GetNamedItem("type").Value;
  1522. if (itemType == "list")
  1523. return ReadList(tag);
  1524. if (itemType == "libsecondlife.LLUUID")
  1525. {
  1526. LLUUID val = new LLUUID();
  1527. LLUUID.TryParse(tag.InnerText, out val);
  1528. return val;
  1529. }
  1530. Type itemT = Type.GetType(itemType);
  1531. if (itemT == null)
  1532. {
  1533. Object[] args =
  1534. new Object[] { tag.InnerText };
  1535. assembly = itemType+", OpenSim.Region.ScriptEngine.Shared";
  1536. itemT = Type.GetType(assembly);
  1537. if (itemT == null)
  1538. return null;
  1539. varValue = Activator.CreateInstance(itemT, args);
  1540. if (varValue == null)
  1541. return null;
  1542. }
  1543. else
  1544. {
  1545. varValue = Convert.ChangeType(tag.InnerText, itemT);
  1546. }
  1547. return varValue;
  1548. }
  1549. }
  1550. }