XEngine.cs 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  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;
  33. using System.Security.Policy;
  34. using System.Reflection;
  35. using System.Globalization;
  36. using System.Xml;
  37. using OpenMetaverse;
  38. using OpenMetaverse.StructuredData;
  39. using log4net;
  40. using Nini.Config;
  41. using Amib.Threading;
  42. using OpenSim.Framework;
  43. using OpenSim.Region.CoreModules.Framework.EventQueue;
  44. using OpenSim.Region.Framework.Scenes;
  45. using OpenSim.Region.Framework.Interfaces;
  46. using OpenSim.Region.ScriptEngine.Shared;
  47. using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
  48. using OpenSim.Region.ScriptEngine.Shared.CodeTools;
  49. using OpenSim.Region.ScriptEngine.Shared.Instance;
  50. using OpenSim.Region.ScriptEngine.Interfaces;
  51. namespace OpenSim.Region.ScriptEngine.XEngine
  52. {
  53. public class XEngine : IRegionModule, IScriptModule, IScriptEngine
  54. {
  55. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  56. private SmartThreadPool m_ThreadPool;
  57. private int m_MaxScriptQueue;
  58. private Scene m_Scene;
  59. private IConfig m_ScriptConfig;
  60. private ICompiler m_Compiler;
  61. private int m_MinThreads;
  62. private int m_MaxThreads ;
  63. private int m_IdleTimeout;
  64. private int m_StackSize;
  65. private int m_SleepTime;
  66. private int m_SaveTime;
  67. private ThreadPriority m_Prio;
  68. private bool m_Enabled = false;
  69. private bool m_InitialStartup = true;
  70. private int m_ScriptFailCount; // Number of script fails since compile queue was last empty
  71. private string m_ScriptErrorMessage;
  72. // disable warning: need to keep a reference to XEngine.EventManager
  73. // alive to avoid it being garbage collected
  74. #pragma warning disable 414
  75. private EventManager m_EventManager;
  76. #pragma warning restore 414
  77. private int m_EventLimit;
  78. private bool m_KillTimedOutScripts;
  79. private static List<XEngine> m_ScriptEngines =
  80. new List<XEngine>();
  81. // Maps the local id to the script inventory items in it
  82. private Dictionary<uint, List<UUID> > m_PrimObjects =
  83. new Dictionary<uint, List<UUID> >();
  84. // Maps the UUID above to the script instance
  85. private Dictionary<UUID, IScriptInstance> m_Scripts =
  86. new Dictionary<UUID, IScriptInstance>();
  87. // Maps the asset ID to the assembly
  88. private Dictionary<UUID, string> m_Assemblies =
  89. new Dictionary<UUID, string>();
  90. private Dictionary<string, int> m_AddingAssemblies =
  91. new Dictionary<string, int>();
  92. // This will list AppDomains by script asset
  93. private Dictionary<UUID, AppDomain> m_AppDomains =
  94. new Dictionary<UUID, AppDomain>();
  95. // List the scripts running in each appdomain
  96. private Dictionary<UUID, List<UUID> > m_DomainScripts =
  97. new Dictionary<UUID, List<UUID> >();
  98. private Queue m_CompileQueue = new Queue(100);
  99. IWorkItemResult m_CurrentCompile = null;
  100. public string ScriptEngineName
  101. {
  102. get { return "XEngine"; }
  103. }
  104. public Scene World
  105. {
  106. get { return m_Scene; }
  107. }
  108. public static List<XEngine> ScriptEngines
  109. {
  110. get { return m_ScriptEngines; }
  111. }
  112. // private struct RezScriptParms
  113. // {
  114. // uint LocalID;
  115. // UUID ItemID;
  116. // string Script;
  117. // }
  118. public IConfig Config
  119. {
  120. get { return m_ScriptConfig; }
  121. }
  122. //
  123. // IRegionModule functions
  124. //
  125. public void Initialise(Scene scene, IConfigSource configSource)
  126. {
  127. m_ScriptConfig = configSource.Configs["XEngine"];
  128. m_ScriptFailCount = 0;
  129. m_ScriptErrorMessage = String.Empty;
  130. if (m_ScriptConfig == null)
  131. {
  132. // m_log.ErrorFormat("[XEngine] No script configuration found. Scripts disabled");
  133. return;
  134. }
  135. m_Enabled = m_ScriptConfig.GetBoolean("Enabled", true);
  136. if (!m_Enabled)
  137. return;
  138. AppDomain.CurrentDomain.AssemblyResolve +=
  139. OnAssemblyResolve;
  140. m_log.InfoFormat("[XEngine] Initializing scripts in region {0}",
  141. scene.RegionInfo.RegionName);
  142. m_Scene = scene;
  143. m_MinThreads = m_ScriptConfig.GetInt("MinThreads", 2);
  144. m_MaxThreads = m_ScriptConfig.GetInt("MaxThreads", 100);
  145. m_IdleTimeout = m_ScriptConfig.GetInt("IdleTimeout", 60);
  146. string priority = m_ScriptConfig.GetString("Priority", "BelowNormal");
  147. m_MaxScriptQueue = m_ScriptConfig.GetInt("MaxScriptEventQueue",300);
  148. m_StackSize = m_ScriptConfig.GetInt("ThreadStackSize", 262144);
  149. m_SleepTime = m_ScriptConfig.GetInt("MaintenanceInterval", 10) * 1000;
  150. m_EventLimit = m_ScriptConfig.GetInt("EventLimit", 30);
  151. m_KillTimedOutScripts = m_ScriptConfig.GetBoolean("KillTimedOutScripts", false);
  152. m_SaveTime = m_ScriptConfig.GetInt("SaveInterval", 120) * 1000;
  153. m_Prio = ThreadPriority.BelowNormal;
  154. switch (priority)
  155. {
  156. case "Lowest":
  157. m_Prio = ThreadPriority.Lowest;
  158. break;
  159. case "BelowNormal":
  160. m_Prio = ThreadPriority.BelowNormal;
  161. break;
  162. case "Normal":
  163. m_Prio = ThreadPriority.Normal;
  164. break;
  165. case "AboveNormal":
  166. m_Prio = ThreadPriority.AboveNormal;
  167. break;
  168. case "Highest":
  169. m_Prio = ThreadPriority.Highest;
  170. break;
  171. default:
  172. m_log.ErrorFormat("[XEngine] Invalid thread priority: '{0}'. Assuming BelowNormal", priority);
  173. break;
  174. }
  175. lock (m_ScriptEngines)
  176. {
  177. m_ScriptEngines.Add(this);
  178. }
  179. // Needs to be here so we can queue the scripts that need starting
  180. //
  181. m_Scene.EventManager.OnRezScript += OnRezScript;
  182. // Complete basic setup of the thread pool
  183. //
  184. SetupEngine(m_MinThreads, m_MaxThreads, m_IdleTimeout, m_Prio,
  185. m_MaxScriptQueue, m_StackSize);
  186. m_Scene.StackModuleInterface<IScriptModule>(this);
  187. }
  188. public void PostInitialise()
  189. {
  190. if (!m_Enabled)
  191. return;
  192. m_EventManager = new EventManager(this);
  193. m_Compiler = new Compiler(this);
  194. m_Scene.EventManager.OnRemoveScript += OnRemoveScript;
  195. m_Scene.EventManager.OnScriptReset += OnScriptReset;
  196. m_Scene.EventManager.OnStartScript += OnStartScript;
  197. m_Scene.EventManager.OnStopScript += OnStopScript;
  198. m_Scene.EventManager.OnGetScriptRunning += OnGetScriptRunning;
  199. m_Scene.EventManager.OnShutdown += OnShutdown;
  200. if (m_SleepTime > 0)
  201. {
  202. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance),
  203. new Object[]{ m_SleepTime });
  204. }
  205. if (m_SaveTime > 0)
  206. {
  207. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup),
  208. new Object[] { m_SaveTime });
  209. }
  210. m_ThreadPool.Start();
  211. }
  212. public void Close()
  213. {
  214. lock (m_ScriptEngines)
  215. {
  216. if (m_ScriptEngines.Contains(this))
  217. m_ScriptEngines.Remove(this);
  218. }
  219. }
  220. public object DoBackup(object o)
  221. {
  222. Object[] p = (Object[])o;
  223. int saveTime = (int)p[0];
  224. if (saveTime > 0)
  225. System.Threading.Thread.Sleep(saveTime);
  226. // m_log.Debug("[XEngine] Backing up script states");
  227. List<IScriptInstance> instances = new List<IScriptInstance>();
  228. lock (m_Scripts)
  229. {
  230. foreach (IScriptInstance instance in m_Scripts.Values)
  231. instances.Add(instance);
  232. }
  233. foreach (IScriptInstance i in instances)
  234. {
  235. string assembly = String.Empty;
  236. lock (m_Scripts)
  237. {
  238. if (!m_Assemblies.ContainsKey(i.AssetID))
  239. continue;
  240. assembly = m_Assemblies[i.AssetID];
  241. }
  242. i.SaveState(assembly);
  243. }
  244. instances.Clear();
  245. if (saveTime > 0)
  246. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup),
  247. new Object[] { saveTime });
  248. return 0;
  249. }
  250. public object DoMaintenance(object p)
  251. {
  252. object[] parms = (object[])p;
  253. int sleepTime = (int)parms[0];
  254. foreach (IScriptInstance inst in m_Scripts.Values)
  255. {
  256. if (inst.EventTime() > m_EventLimit)
  257. {
  258. inst.Stop(100);
  259. if (!m_KillTimedOutScripts)
  260. inst.Start();
  261. }
  262. }
  263. System.Threading.Thread.Sleep(sleepTime);
  264. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance),
  265. new Object[]{ sleepTime });
  266. return 0;
  267. }
  268. public string Name
  269. {
  270. get { return "XEngine"; }
  271. }
  272. public bool IsSharedModule
  273. {
  274. get { return false; }
  275. }
  276. public void OnRezScript(uint localID, UUID itemID, string script, int startParam, bool postOnRez, string engine, int stateSource)
  277. {
  278. List<IScriptModule> engines = new List<IScriptModule>(m_Scene.RequestModuleInterfaces<IScriptModule>());
  279. List<string> names = new List<string>();
  280. foreach (IScriptModule m in engines)
  281. names.Add(m.ScriptEngineName);
  282. int lineEnd = script.IndexOf('\n');
  283. if (lineEnd > 1)
  284. {
  285. string firstline = script.Substring(0, lineEnd).Trim();
  286. int colon = firstline.IndexOf(':');
  287. if (firstline.Length > 2 && firstline.Substring(0, 2) == "//" && colon != -1)
  288. {
  289. string engineName = firstline.Substring(2, colon-2);
  290. if (names.Contains(engineName))
  291. {
  292. engine = engineName;
  293. script = "//" + script.Substring(script.IndexOf(':')+1);
  294. }
  295. else
  296. {
  297. if (engine == ScriptEngineName)
  298. {
  299. SceneObjectPart part =
  300. m_Scene.GetSceneObjectPart(
  301. localID);
  302. TaskInventoryItem item =
  303. part.Inventory.GetInventoryItem(itemID);
  304. ScenePresence presence =
  305. m_Scene.GetScenePresence(
  306. item.OwnerID);
  307. if (presence != null)
  308. {
  309. presence.ControllingClient.SendAgentAlertMessage(
  310. "Selected engine unavailable. "+
  311. "Running script on "+
  312. ScriptEngineName,
  313. false);
  314. }
  315. }
  316. }
  317. }
  318. }
  319. if (engine != ScriptEngineName)
  320. return;
  321. Object[] parms = new Object[]{localID, itemID, script, startParam, postOnRez, (StateSource)stateSource};
  322. if (stateSource == (int)StateSource.ScriptedRez)
  323. {
  324. DoOnRezScript(parms);
  325. }
  326. else
  327. {
  328. lock (m_CompileQueue)
  329. {
  330. m_CompileQueue.Enqueue(parms);
  331. if (m_CurrentCompile == null)
  332. {
  333. m_CurrentCompile = m_ThreadPool.QueueWorkItem(
  334. new WorkItemCallback(this.DoOnRezScriptQueue),
  335. new Object[0]);
  336. }
  337. }
  338. }
  339. }
  340. public Object DoOnRezScriptQueue(Object dummy)
  341. {
  342. if (m_InitialStartup)
  343. {
  344. m_InitialStartup = false;
  345. System.Threading.Thread.Sleep(15000);
  346. lock (m_CompileQueue)
  347. {
  348. if (m_CompileQueue.Count==0)
  349. // No scripts on region, so won't get triggered later
  350. // by the queue becoming empty so we trigger it here
  351. m_Scene.EventManager.TriggerEmptyScriptCompileQueue(0, String.Empty);
  352. }
  353. }
  354. Object o;
  355. lock (m_CompileQueue)
  356. {
  357. o = m_CompileQueue.Dequeue();
  358. if (o == null)
  359. {
  360. m_CurrentCompile = null;
  361. return null;
  362. }
  363. }
  364. DoOnRezScript(o);
  365. lock (m_CompileQueue)
  366. {
  367. if (m_CompileQueue.Count > 0)
  368. {
  369. m_CurrentCompile = m_ThreadPool.QueueWorkItem(
  370. new WorkItemCallback(this.DoOnRezScriptQueue),
  371. new Object[0]);
  372. }
  373. else
  374. {
  375. m_CurrentCompile = null;
  376. m_Scene.EventManager.TriggerEmptyScriptCompileQueue(m_ScriptFailCount,
  377. m_ScriptErrorMessage);
  378. m_ScriptFailCount = 0;
  379. }
  380. }
  381. return null;
  382. }
  383. private bool DoOnRezScript(object parm)
  384. {
  385. Object[] p = (Object[])parm;
  386. uint localID = (uint)p[0];
  387. UUID itemID = (UUID)p[1];
  388. string script =(string)p[2];
  389. int startParam = (int)p[3];
  390. bool postOnRez = (bool)p[4];
  391. StateSource stateSource = (StateSource)p[5];
  392. // Get the asset ID of the script, so we can check if we
  393. // already have it.
  394. // We must look for the part outside the m_Scripts lock because GetSceneObjectPart later triggers the
  395. // m_parts lock on SOG. At the same time, a scene object that is being deleted will take the m_parts lock
  396. // and then later on try to take the m_scripts lock in this class when it calls OnRemoveScript()
  397. SceneObjectPart part = m_Scene.GetSceneObjectPart(localID);
  398. if (part == null)
  399. {
  400. m_log.Error("[Script] SceneObjectPart unavailable. Script NOT started.");
  401. m_ScriptErrorMessage += "SceneObjectPart unavailable. Script NOT started.\n";
  402. m_ScriptFailCount++;
  403. return false;
  404. }
  405. TaskInventoryItem item = part.Inventory.GetInventoryItem(itemID);
  406. if (item == null)
  407. {
  408. m_ScriptErrorMessage += "Can't find script inventory item.\n";
  409. m_ScriptFailCount++;
  410. return false;
  411. }
  412. UUID assetID = item.AssetID;
  413. // m_log.DebugFormat("[XEngine] Compiling script {0} ({1})",
  414. // item.Name, itemID.ToString());
  415. ScenePresence presence = m_Scene.GetScenePresence(item.OwnerID);
  416. string assembly = "";
  417. CultureInfo USCulture = new CultureInfo("en-US");
  418. Thread.CurrentThread.CurrentCulture = USCulture;
  419. try
  420. {
  421. lock (m_AddingAssemblies)
  422. {
  423. assembly = m_Compiler.PerformScriptCompile(script,
  424. assetID.ToString());
  425. if (!m_AddingAssemblies.ContainsKey(assembly)) {
  426. m_AddingAssemblies[assembly] = 1;
  427. } else {
  428. m_AddingAssemblies[assembly]++;
  429. }
  430. }
  431. string[] warnings = m_Compiler.GetWarnings();
  432. if (warnings != null && warnings.Length != 0)
  433. {
  434. if (presence != null && (!postOnRez))
  435. presence.ControllingClient.SendAgentAlertMessage("Script saved with warnings, check debug window!", false);
  436. foreach (string warning in warnings)
  437. {
  438. try
  439. {
  440. // DISPLAY WARNING INWORLD
  441. string text = "Warning:\n" + warning;
  442. if (text.Length > 1000)
  443. text = text.Substring(0, 1000);
  444. World.SimChat(Utils.StringToBytes(text),
  445. ChatTypeEnum.DebugChannel, 2147483647,
  446. part.AbsolutePosition,
  447. part.Name, part.UUID, false);
  448. }
  449. catch (Exception e2) // LEGIT: User Scripting
  450. {
  451. m_log.Error("[XEngine]: " +
  452. "Error displaying warning in-world: " +
  453. e2.ToString());
  454. m_log.Error("[XEngine]: " +
  455. "Warning:\r\n" +
  456. warning);
  457. }
  458. }
  459. }
  460. }
  461. catch (Exception e)
  462. {
  463. if (presence != null && (!postOnRez))
  464. presence.ControllingClient.SendAgentAlertMessage("Script saved with errors, check debug window!", false);
  465. try
  466. {
  467. // DISPLAY ERROR INWORLD
  468. m_ScriptErrorMessage += "Failed to compile: " + e.Message.ToString();
  469. m_ScriptFailCount++;
  470. string text = "Error compiling script:\n" + e.Message.ToString();
  471. if (text.Length > 1000)
  472. text = text.Substring(0, 1000);
  473. World.SimChat(Utils.StringToBytes(text),
  474. ChatTypeEnum.DebugChannel, 2147483647,
  475. part.AbsolutePosition,
  476. part.Name, part.UUID, false);
  477. }
  478. catch (Exception e2) // LEGIT: User Scripting
  479. {
  480. m_log.Error("[XEngine]: "+
  481. "Error displaying error in-world: " +
  482. e2.ToString());
  483. m_log.Error("[XEngine]: " +
  484. "Errormessage: Error compiling script:\r\n" +
  485. e.Message.ToString());
  486. }
  487. return false;
  488. }
  489. lock (m_Scripts)
  490. {
  491. ScriptInstance instance = null;
  492. // Create the object record
  493. if ((!m_Scripts.ContainsKey(itemID)) ||
  494. (m_Scripts[itemID].AssetID != assetID))
  495. {
  496. UUID appDomain = assetID;
  497. if (part.ParentGroup.IsAttachment)
  498. appDomain = part.ParentGroup.RootPart.UUID;
  499. if (!m_AppDomains.ContainsKey(appDomain))
  500. {
  501. try
  502. {
  503. AppDomainSetup appSetup = new AppDomainSetup();
  504. // appSetup.ApplicationBase = Path.Combine(
  505. // "ScriptEngines",
  506. // m_Scene.RegionInfo.RegionID.ToString());
  507. Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
  508. Evidence evidence = new Evidence(baseEvidence);
  509. AppDomain sandbox =
  510. AppDomain.CreateDomain(
  511. m_Scene.RegionInfo.RegionID.ToString(),
  512. evidence, appSetup);
  513. /*
  514. PolicyLevel sandboxPolicy = PolicyLevel.CreateAppDomainLevel();
  515. AllMembershipCondition sandboxMembershipCondition = new AllMembershipCondition();
  516. PermissionSet sandboxPermissionSet = sandboxPolicy.GetNamedPermissionSet("Internet");
  517. PolicyStatement sandboxPolicyStatement = new PolicyStatement(sandboxPermissionSet);
  518. CodeGroup sandboxCodeGroup = new UnionCodeGroup(sandboxMembershipCondition, sandboxPolicyStatement);
  519. sandboxPolicy.RootCodeGroup = sandboxCodeGroup;
  520. sandbox.SetAppDomainPolicy(sandboxPolicy);
  521. */
  522. m_AppDomains[appDomain] = sandbox;
  523. m_AppDomains[appDomain].AssemblyResolve +=
  524. new ResolveEventHandler(
  525. AssemblyResolver.OnAssemblyResolve);
  526. m_DomainScripts[appDomain] = new List<UUID>();
  527. }
  528. catch (Exception e)
  529. {
  530. m_log.ErrorFormat("[XEngine] Exception creating app domain:\n {0}", e.ToString());
  531. m_ScriptErrorMessage += "Exception creating app domain:\n";
  532. m_ScriptFailCount++;
  533. lock (m_AddingAssemblies)
  534. {
  535. m_AddingAssemblies[assembly]--;
  536. }
  537. return false;
  538. }
  539. }
  540. m_DomainScripts[appDomain].Add(itemID);
  541. instance = new ScriptInstance(this, part,
  542. itemID, assetID, assembly,
  543. m_AppDomains[appDomain],
  544. part.ParentGroup.RootPart.Name,
  545. item.Name, startParam, postOnRez,
  546. stateSource, m_MaxScriptQueue);
  547. m_log.DebugFormat("[XEngine] Loaded script {0}.{1}",
  548. part.ParentGroup.RootPart.Name, item.Name);
  549. instance.AppDomain = appDomain;
  550. instance.LineMap = m_Compiler.LineMap();
  551. m_Scripts[itemID] = instance;
  552. }
  553. lock (m_PrimObjects)
  554. {
  555. if (!m_PrimObjects.ContainsKey(localID))
  556. m_PrimObjects[localID] = new List<UUID>();
  557. if (!m_PrimObjects[localID].Contains(itemID))
  558. m_PrimObjects[localID].Add(itemID);
  559. }
  560. if (!m_Assemblies.ContainsKey(assetID))
  561. m_Assemblies[assetID] = assembly;
  562. lock (m_AddingAssemblies)
  563. {
  564. m_AddingAssemblies[assembly]--;
  565. }
  566. if (instance!=null)
  567. instance.Init();
  568. }
  569. return true;
  570. }
  571. public void OnRemoveScript(uint localID, UUID itemID)
  572. {
  573. lock (m_Scripts)
  574. {
  575. // Do we even have it?
  576. if (!m_Scripts.ContainsKey(itemID))
  577. return;
  578. IScriptInstance instance=m_Scripts[itemID];
  579. m_Scripts.Remove(itemID);
  580. instance.ClearQueue();
  581. instance.Stop(0);
  582. SceneObjectPart part =
  583. m_Scene.GetSceneObjectPart(localID);
  584. if (part != null)
  585. part.RemoveScriptEvents(itemID);
  586. lock (m_PrimObjects)
  587. {
  588. // Remove the script from it's prim
  589. if (m_PrimObjects.ContainsKey(localID))
  590. {
  591. // Remove inventory item record
  592. if (m_PrimObjects[localID].Contains(itemID))
  593. m_PrimObjects[localID].Remove(itemID);
  594. // If there are no more scripts, remove prim
  595. if (m_PrimObjects[localID].Count == 0)
  596. {
  597. m_PrimObjects.Remove(localID);
  598. }
  599. }
  600. }
  601. m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
  602. if (m_DomainScripts[instance.AppDomain].Count == 0)
  603. {
  604. m_DomainScripts.Remove(instance.AppDomain);
  605. UnloadAppDomain(instance.AppDomain);
  606. }
  607. instance.RemoveState();
  608. instance.DestroyScriptInstance();
  609. instance = null;
  610. CleanAssemblies();
  611. }
  612. }
  613. public void OnScriptReset(uint localID, UUID itemID)
  614. {
  615. ResetScript(itemID);
  616. }
  617. public void OnStartScript(uint localID, UUID itemID)
  618. {
  619. StartScript(itemID);
  620. }
  621. public void OnStopScript(uint localID, UUID itemID)
  622. {
  623. StopScript(itemID);
  624. }
  625. private void CleanAssemblies()
  626. {
  627. List<UUID> assetIDList = new List<UUID>(m_Assemblies.Keys);
  628. foreach (IScriptInstance i in m_Scripts.Values)
  629. {
  630. if (assetIDList.Contains(i.AssetID))
  631. assetIDList.Remove(i.AssetID);
  632. }
  633. lock (m_AddingAssemblies)
  634. {
  635. foreach (UUID assetID in assetIDList)
  636. {
  637. // Do not remove assembly files if another instance of the script
  638. // is currently initialising
  639. if (!m_AddingAssemblies.ContainsKey(m_Assemblies[assetID])
  640. || m_AddingAssemblies[m_Assemblies[assetID]] == 0)
  641. {
  642. // m_log.DebugFormat("[XEngine] Removing unreferenced assembly {0}", m_Assemblies[assetID]);
  643. try
  644. {
  645. if (File.Exists(m_Assemblies[assetID]))
  646. File.Delete(m_Assemblies[assetID]);
  647. if (File.Exists(m_Assemblies[assetID]+".text"))
  648. File.Delete(m_Assemblies[assetID]+".text");
  649. if (File.Exists(m_Assemblies[assetID]+".mdb"))
  650. File.Delete(m_Assemblies[assetID]+".mdb");
  651. }
  652. catch (Exception)
  653. {
  654. }
  655. m_Assemblies.Remove(assetID);
  656. }
  657. }
  658. }
  659. }
  660. private void UnloadAppDomain(UUID id)
  661. {
  662. if (m_AppDomains.ContainsKey(id))
  663. {
  664. AppDomain domain = m_AppDomains[id];
  665. m_AppDomains.Remove(id);
  666. AppDomain.Unload(domain);
  667. domain = null;
  668. // m_log.DebugFormat("[XEngine] Unloaded app domain {0}", id.ToString());
  669. }
  670. }
  671. //
  672. // Start processing
  673. //
  674. private void SetupEngine(int minThreads, int maxThreads,
  675. int idleTimeout, ThreadPriority threadPriority,
  676. int maxScriptQueue, int stackSize)
  677. {
  678. m_MaxScriptQueue = maxScriptQueue;
  679. STPStartInfo startInfo = new STPStartInfo();
  680. startInfo.IdleTimeout = idleTimeout;
  681. startInfo.MaxWorkerThreads = maxThreads;
  682. startInfo.MinWorkerThreads = minThreads;
  683. startInfo.ThreadPriority = threadPriority;
  684. startInfo.StackSize = stackSize;
  685. startInfo.StartSuspended = true;
  686. m_ThreadPool = new SmartThreadPool(startInfo);
  687. }
  688. //
  689. // Used by script instances to queue event handler jobs
  690. //
  691. public IScriptWorkItem QueueEventHandler(object parms)
  692. {
  693. return new XWorkItem(m_ThreadPool.QueueWorkItem(
  694. new WorkItemCallback(this.ProcessEventHandler),
  695. parms));
  696. }
  697. /// <summary>
  698. /// Process a previously posted script event.
  699. /// </summary>
  700. /// <param name="parms"></param>
  701. /// <returns></returns>
  702. private object ProcessEventHandler(object parms)
  703. {
  704. CultureInfo USCulture = new CultureInfo("en-US");
  705. Thread.CurrentThread.CurrentCulture = USCulture;
  706. IScriptInstance instance = (ScriptInstance) parms;
  707. //m_log.DebugFormat("[XENGINE]: Processing event for {0}", instance);
  708. return instance.EventProcessor();
  709. }
  710. /// <summary>
  711. /// Post event to an entire prim
  712. /// </summary>
  713. /// <param name="localID"></param>
  714. /// <param name="p"></param>
  715. /// <returns></returns>
  716. public bool PostObjectEvent(uint localID, EventParams p)
  717. {
  718. bool result = false;
  719. lock (m_PrimObjects)
  720. {
  721. if (!m_PrimObjects.ContainsKey(localID))
  722. return false;
  723. foreach (UUID itemID in m_PrimObjects[localID])
  724. {
  725. if (m_Scripts.ContainsKey(itemID))
  726. {
  727. IScriptInstance instance = m_Scripts[itemID];
  728. if (instance != null)
  729. {
  730. instance.PostEvent(p);
  731. result = true;
  732. }
  733. }
  734. }
  735. }
  736. return result;
  737. }
  738. /// <summary>
  739. /// Post an event to a single script
  740. /// </summary>
  741. /// <param name="itemID"></param>
  742. /// <param name="p"></param>
  743. /// <returns></returns>
  744. public bool PostScriptEvent(UUID itemID, EventParams p)
  745. {
  746. if (m_Scripts.ContainsKey(itemID))
  747. {
  748. IScriptInstance instance = m_Scripts[itemID];
  749. if (instance != null)
  750. instance.PostEvent(p);
  751. return true;
  752. }
  753. return false;
  754. }
  755. public Assembly OnAssemblyResolve(object sender,
  756. ResolveEventArgs args)
  757. {
  758. if (!(sender is System.AppDomain))
  759. return null;
  760. string[] pathList = new string[] {"bin", "ScriptEngines",
  761. Path.Combine("ScriptEngines",
  762. m_Scene.RegionInfo.RegionID.ToString())};
  763. string assemblyName = args.Name;
  764. if (assemblyName.IndexOf(",") != -1)
  765. assemblyName = args.Name.Substring(0, args.Name.IndexOf(","));
  766. foreach (string s in pathList)
  767. {
  768. string path = Path.Combine(Directory.GetCurrentDirectory(),
  769. Path.Combine(s, assemblyName))+".dll";
  770. if (File.Exists(path))
  771. return Assembly.LoadFrom(path);
  772. }
  773. return null;
  774. }
  775. private IScriptInstance GetInstance(UUID itemID)
  776. {
  777. IScriptInstance instance;
  778. lock (m_Scripts)
  779. {
  780. if (!m_Scripts.ContainsKey(itemID))
  781. return null;
  782. instance = m_Scripts[itemID];
  783. }
  784. return instance;
  785. }
  786. public void SetScriptState(UUID itemID, bool running)
  787. {
  788. IScriptInstance instance = GetInstance(itemID);
  789. if (instance != null)
  790. {
  791. if (running)
  792. instance.Start();
  793. else
  794. instance.Stop(100);
  795. }
  796. }
  797. public bool GetScriptState(UUID itemID)
  798. {
  799. IScriptInstance instance = GetInstance(itemID);
  800. if (instance != null)
  801. return instance.Running;
  802. return false;
  803. }
  804. public void ApiResetScript(UUID itemID)
  805. {
  806. IScriptInstance instance = GetInstance(itemID);
  807. if (instance != null)
  808. instance.ApiResetScript();
  809. }
  810. public void ResetScript(UUID itemID)
  811. {
  812. IScriptInstance instance = GetInstance(itemID);
  813. if (instance != null)
  814. instance.ResetScript();
  815. }
  816. public void StartScript(UUID itemID)
  817. {
  818. IScriptInstance instance = GetInstance(itemID);
  819. if (instance != null)
  820. instance.Start();
  821. }
  822. public void StopScript(UUID itemID)
  823. {
  824. IScriptInstance instance = GetInstance(itemID);
  825. if (instance != null)
  826. instance.Stop(0);
  827. }
  828. public DetectParams GetDetectParams(UUID itemID, int idx)
  829. {
  830. IScriptInstance instance = GetInstance(itemID);
  831. if (instance != null)
  832. return instance.GetDetectParams(idx);
  833. return null;
  834. }
  835. public void SetMinEventDelay(UUID itemID, double delay)
  836. {
  837. IScriptInstance instance = GetInstance(itemID);
  838. if (instance != null)
  839. instance.MinEventDelay = delay;
  840. }
  841. public UUID GetDetectID(UUID itemID, int idx)
  842. {
  843. IScriptInstance instance = GetInstance(itemID);
  844. if (instance != null)
  845. return instance.GetDetectID(idx);
  846. return UUID.Zero;
  847. }
  848. public void SetState(UUID itemID, string newState)
  849. {
  850. IScriptInstance instance = GetInstance(itemID);
  851. if (instance == null)
  852. return;
  853. instance.SetState(newState);
  854. }
  855. public string GetState(UUID itemID)
  856. {
  857. IScriptInstance instance = GetInstance(itemID);
  858. if (instance == null)
  859. return "default";
  860. return instance.State;
  861. }
  862. public int GetStartParameter(UUID itemID)
  863. {
  864. IScriptInstance instance = GetInstance(itemID);
  865. if (instance == null)
  866. return 0;
  867. return instance.StartParam;
  868. }
  869. public void OnShutdown()
  870. {
  871. List<IScriptInstance> instances = new List<IScriptInstance>();
  872. lock (m_Scripts)
  873. {
  874. foreach (IScriptInstance instance in m_Scripts.Values)
  875. instances.Add(instance);
  876. }
  877. foreach (IScriptInstance i in instances)
  878. {
  879. // Stop the script, even forcibly if needed. Then flag
  880. // it as shutting down and restore the previous run state
  881. // for serialization, so the scripts don't come back
  882. // dead after region restart
  883. //
  884. bool prevRunning = i.Running;
  885. i.Stop(50);
  886. i.ShuttingDown = true;
  887. i.Running = prevRunning;
  888. }
  889. DoBackup(new Object[] {0});
  890. }
  891. public IScriptApi GetApi(UUID itemID, string name)
  892. {
  893. IScriptInstance instance = GetInstance(itemID);
  894. if (instance == null)
  895. return null;
  896. return instance.GetApi(name);
  897. }
  898. public void OnGetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID)
  899. {
  900. IScriptInstance instance = GetInstance(itemID);
  901. if (instance == null)
  902. return;
  903. IEventQueue eq = World.RequestModuleInterface<IEventQueue>();
  904. if (eq == null)
  905. {
  906. controllingClient.SendScriptRunningReply(objectID, itemID,
  907. GetScriptState(itemID));
  908. }
  909. else
  910. {
  911. eq.Enqueue(EventQueueHelper.ScriptRunningReplyEvent(objectID, itemID, GetScriptState(itemID), true),
  912. controllingClient.AgentId);
  913. }
  914. }
  915. public string GetAssemblyName(UUID itemID)
  916. {
  917. IScriptInstance instance = GetInstance(itemID);
  918. if (instance == null)
  919. return "";
  920. return instance.GetAssemblyName();
  921. }
  922. public string GetXMLState(UUID itemID)
  923. {
  924. IScriptInstance instance = GetInstance(itemID);
  925. if (instance == null)
  926. return "";
  927. return instance.GetXMLState();
  928. }
  929. }
  930. }