1
0

XEngine.cs 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.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 : INonSharedRegionModule, 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 = null;
  60. private IConfigSource m_ConfigSource = null;
  61. private ICompiler m_Compiler;
  62. private int m_MinThreads;
  63. private int m_MaxThreads ;
  64. private int m_IdleTimeout;
  65. private int m_StackSize;
  66. private int m_SleepTime;
  67. private int m_SaveTime;
  68. private ThreadPriority m_Prio;
  69. private bool m_Enabled = false;
  70. private bool m_InitialStartup = true;
  71. private int m_ScriptFailCount; // Number of script fails since compile queue was last empty
  72. private string m_ScriptErrorMessage;
  73. // disable warning: need to keep a reference to XEngine.EventManager
  74. // alive to avoid it being garbage collected
  75. #pragma warning disable 414
  76. private EventManager m_EventManager;
  77. #pragma warning restore 414
  78. private IXmlRpcRouter m_XmlRpcRouter;
  79. private int m_EventLimit;
  80. private bool m_KillTimedOutScripts;
  81. private static List<XEngine> m_ScriptEngines =
  82. new List<XEngine>();
  83. // Maps the local id to the script inventory items in it
  84. private Dictionary<uint, List<UUID> > m_PrimObjects =
  85. new Dictionary<uint, List<UUID> >();
  86. // Maps the UUID above to the script instance
  87. private Dictionary<UUID, IScriptInstance> m_Scripts =
  88. new Dictionary<UUID, IScriptInstance>();
  89. // Maps the asset ID to the assembly
  90. private Dictionary<UUID, string> m_Assemblies =
  91. new Dictionary<UUID, string>();
  92. private Dictionary<string, int> m_AddingAssemblies =
  93. new Dictionary<string, int>();
  94. // This will list AppDomains by script asset
  95. private Dictionary<UUID, AppDomain> m_AppDomains =
  96. new Dictionary<UUID, AppDomain>();
  97. // List the scripts running in each appdomain
  98. private Dictionary<UUID, List<UUID> > m_DomainScripts =
  99. new Dictionary<UUID, List<UUID> >();
  100. private Queue m_CompileQueue = new Queue(100);
  101. IWorkItemResult m_CurrentCompile = null;
  102. public string ScriptEngineName
  103. {
  104. get { return "XEngine"; }
  105. }
  106. public Scene World
  107. {
  108. get { return m_Scene; }
  109. }
  110. public static List<XEngine> ScriptEngines
  111. {
  112. get { return m_ScriptEngines; }
  113. }
  114. public IScriptModule ScriptModule
  115. {
  116. get { return this; }
  117. }
  118. // private struct RezScriptParms
  119. // {
  120. // uint LocalID;
  121. // UUID ItemID;
  122. // string Script;
  123. // }
  124. public IConfig Config
  125. {
  126. get { return m_ScriptConfig; }
  127. }
  128. public IConfigSource ConfigSource
  129. {
  130. get { return m_ConfigSource; }
  131. }
  132. public event ScriptRemoved OnScriptRemoved;
  133. public event ObjectRemoved OnObjectRemoved;
  134. //
  135. // IRegionModule functions
  136. //
  137. public void Initialise(IConfigSource configSource)
  138. {
  139. if (configSource.Configs["XEngine"] == null)
  140. return;
  141. m_ScriptConfig = configSource.Configs["XEngine"];
  142. m_ConfigSource = configSource;
  143. }
  144. public void AddRegion(Scene scene)
  145. {
  146. if (m_ScriptConfig == null)
  147. return;
  148. m_ScriptFailCount = 0;
  149. m_ScriptErrorMessage = String.Empty;
  150. if (m_ScriptConfig == null)
  151. {
  152. // m_log.ErrorFormat("[XEngine] No script configuration found. Scripts disabled");
  153. return;
  154. }
  155. m_Enabled = m_ScriptConfig.GetBoolean("Enabled", true);
  156. if (!m_Enabled)
  157. return;
  158. AppDomain.CurrentDomain.AssemblyResolve +=
  159. OnAssemblyResolve;
  160. m_log.InfoFormat("[XEngine] Initializing scripts in region {0}",
  161. scene.RegionInfo.RegionName);
  162. m_Scene = scene;
  163. m_MinThreads = m_ScriptConfig.GetInt("MinThreads", 2);
  164. m_MaxThreads = m_ScriptConfig.GetInt("MaxThreads", 100);
  165. m_IdleTimeout = m_ScriptConfig.GetInt("IdleTimeout", 60);
  166. string priority = m_ScriptConfig.GetString("Priority", "BelowNormal");
  167. m_MaxScriptQueue = m_ScriptConfig.GetInt("MaxScriptEventQueue",300);
  168. m_StackSize = m_ScriptConfig.GetInt("ThreadStackSize", 262144);
  169. m_SleepTime = m_ScriptConfig.GetInt("MaintenanceInterval", 10) * 1000;
  170. m_EventLimit = m_ScriptConfig.GetInt("EventLimit", 30);
  171. m_KillTimedOutScripts = m_ScriptConfig.GetBoolean("KillTimedOutScripts", false);
  172. m_SaveTime = m_ScriptConfig.GetInt("SaveInterval", 120) * 1000;
  173. m_Prio = ThreadPriority.BelowNormal;
  174. switch (priority)
  175. {
  176. case "Lowest":
  177. m_Prio = ThreadPriority.Lowest;
  178. break;
  179. case "BelowNormal":
  180. m_Prio = ThreadPriority.BelowNormal;
  181. break;
  182. case "Normal":
  183. m_Prio = ThreadPriority.Normal;
  184. break;
  185. case "AboveNormal":
  186. m_Prio = ThreadPriority.AboveNormal;
  187. break;
  188. case "Highest":
  189. m_Prio = ThreadPriority.Highest;
  190. break;
  191. default:
  192. m_log.ErrorFormat("[XEngine] Invalid thread priority: '{0}'. Assuming BelowNormal", priority);
  193. break;
  194. }
  195. lock (m_ScriptEngines)
  196. {
  197. m_ScriptEngines.Add(this);
  198. }
  199. // Needs to be here so we can queue the scripts that need starting
  200. //
  201. m_Scene.EventManager.OnRezScript += OnRezScript;
  202. // Complete basic setup of the thread pool
  203. //
  204. SetupEngine(m_MinThreads, m_MaxThreads, m_IdleTimeout, m_Prio,
  205. m_MaxScriptQueue, m_StackSize);
  206. m_Scene.StackModuleInterface<IScriptModule>(this);
  207. m_XmlRpcRouter = m_Scene.RequestModuleInterface<IXmlRpcRouter>();
  208. if (m_XmlRpcRouter != null)
  209. {
  210. OnScriptRemoved += m_XmlRpcRouter.ScriptRemoved;
  211. OnObjectRemoved += m_XmlRpcRouter.ObjectRemoved;
  212. }
  213. }
  214. public void RemoveRegion(Scene scene)
  215. {
  216. lock (m_Scripts)
  217. {
  218. foreach (IScriptInstance instance in m_Scripts.Values)
  219. {
  220. // Force a final state save
  221. //
  222. if (m_Assemblies.ContainsKey(instance.AssetID))
  223. {
  224. string assembly = m_Assemblies[instance.AssetID];
  225. instance.SaveState(assembly);
  226. }
  227. // Clear the event queue and abort the instance thread
  228. //
  229. instance.ClearQueue();
  230. instance.Stop(0);
  231. // Release events, timer, etc
  232. //
  233. instance.DestroyScriptInstance();
  234. // Unload scripts and app domains
  235. // Must be done explicitly because they have infinite
  236. // lifetime
  237. //
  238. m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
  239. if (m_DomainScripts[instance.AppDomain].Count == 0)
  240. {
  241. m_DomainScripts.Remove(instance.AppDomain);
  242. UnloadAppDomain(instance.AppDomain);
  243. }
  244. }
  245. m_Scripts.Clear();
  246. m_PrimObjects.Clear();
  247. m_Assemblies.Clear();
  248. m_DomainScripts.Clear();
  249. }
  250. lock (m_ScriptEngines)
  251. {
  252. m_ScriptEngines.Remove(this);
  253. }
  254. }
  255. public void RegionLoaded(Scene scene)
  256. {
  257. if (!m_Enabled)
  258. return;
  259. m_EventManager = new EventManager(this);
  260. m_Compiler = new Compiler(this);
  261. m_Scene.EventManager.OnRemoveScript += OnRemoveScript;
  262. m_Scene.EventManager.OnScriptReset += OnScriptReset;
  263. m_Scene.EventManager.OnStartScript += OnStartScript;
  264. m_Scene.EventManager.OnStopScript += OnStopScript;
  265. m_Scene.EventManager.OnGetScriptRunning += OnGetScriptRunning;
  266. m_Scene.EventManager.OnShutdown += OnShutdown;
  267. if (m_SleepTime > 0)
  268. {
  269. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance),
  270. new Object[]{ m_SleepTime });
  271. }
  272. if (m_SaveTime > 0)
  273. {
  274. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup),
  275. new Object[] { m_SaveTime });
  276. }
  277. m_ThreadPool.Start();
  278. }
  279. public void Close()
  280. {
  281. lock (m_ScriptEngines)
  282. {
  283. if (m_ScriptEngines.Contains(this))
  284. m_ScriptEngines.Remove(this);
  285. }
  286. }
  287. public object DoBackup(object o)
  288. {
  289. Object[] p = (Object[])o;
  290. int saveTime = (int)p[0];
  291. if (saveTime > 0)
  292. System.Threading.Thread.Sleep(saveTime);
  293. // m_log.Debug("[XEngine] Backing up script states");
  294. List<IScriptInstance> instances = new List<IScriptInstance>();
  295. lock (m_Scripts)
  296. {
  297. foreach (IScriptInstance instance in m_Scripts.Values)
  298. instances.Add(instance);
  299. }
  300. foreach (IScriptInstance i in instances)
  301. {
  302. string assembly = String.Empty;
  303. lock (m_Scripts)
  304. {
  305. if (!m_Assemblies.ContainsKey(i.AssetID))
  306. continue;
  307. assembly = m_Assemblies[i.AssetID];
  308. }
  309. i.SaveState(assembly);
  310. }
  311. instances.Clear();
  312. if (saveTime > 0)
  313. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup),
  314. new Object[] { saveTime });
  315. return 0;
  316. }
  317. public object DoMaintenance(object p)
  318. {
  319. object[] parms = (object[])p;
  320. int sleepTime = (int)parms[0];
  321. foreach (IScriptInstance inst in m_Scripts.Values)
  322. {
  323. if (inst.EventTime() > m_EventLimit)
  324. {
  325. inst.Stop(100);
  326. if (!m_KillTimedOutScripts)
  327. inst.Start();
  328. }
  329. }
  330. System.Threading.Thread.Sleep(sleepTime);
  331. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance),
  332. new Object[]{ sleepTime });
  333. return 0;
  334. }
  335. public Type ReplaceableInterface
  336. {
  337. get { return null; }
  338. }
  339. public string Name
  340. {
  341. get { return "XEngine"; }
  342. }
  343. public void OnRezScript(uint localID, UUID itemID, string script, int startParam, bool postOnRez, string engine, int stateSource)
  344. {
  345. if (script.StartsWith("//MRM:"))
  346. return;
  347. List<IScriptModule> engines = new List<IScriptModule>(m_Scene.RequestModuleInterfaces<IScriptModule>());
  348. List<string> names = new List<string>();
  349. foreach (IScriptModule m in engines)
  350. names.Add(m.ScriptEngineName);
  351. int lineEnd = script.IndexOf('\n');
  352. if (lineEnd > 1)
  353. {
  354. string firstline = script.Substring(0, lineEnd).Trim();
  355. int colon = firstline.IndexOf(':');
  356. if (firstline.Length > 2 && firstline.Substring(0, 2) == "//" && colon != -1)
  357. {
  358. string engineName = firstline.Substring(2, colon-2);
  359. if (names.Contains(engineName))
  360. {
  361. engine = engineName;
  362. script = "//" + script.Substring(script.IndexOf(':')+1);
  363. }
  364. else
  365. {
  366. if (engine == ScriptEngineName)
  367. {
  368. SceneObjectPart part =
  369. m_Scene.GetSceneObjectPart(
  370. localID);
  371. TaskInventoryItem item =
  372. part.Inventory.GetInventoryItem(itemID);
  373. ScenePresence presence =
  374. m_Scene.GetScenePresence(
  375. item.OwnerID);
  376. if (presence != null)
  377. {
  378. presence.ControllingClient.SendAgentAlertMessage(
  379. "Selected engine unavailable. "+
  380. "Running script on "+
  381. ScriptEngineName,
  382. false);
  383. }
  384. }
  385. }
  386. }
  387. }
  388. if (engine != ScriptEngineName)
  389. return;
  390. Object[] parms = new Object[]{localID, itemID, script, startParam, postOnRez, (StateSource)stateSource};
  391. if (stateSource == (int)StateSource.ScriptedRez)
  392. {
  393. DoOnRezScript(parms);
  394. }
  395. else
  396. {
  397. lock (m_CompileQueue)
  398. {
  399. m_CompileQueue.Enqueue(parms);
  400. if (m_CurrentCompile == null)
  401. {
  402. m_CurrentCompile = m_ThreadPool.QueueWorkItem(
  403. new WorkItemCallback(this.DoOnRezScriptQueue),
  404. new Object[0]);
  405. }
  406. }
  407. }
  408. }
  409. public Object DoOnRezScriptQueue(Object dummy)
  410. {
  411. if (m_InitialStartup)
  412. {
  413. m_InitialStartup = false;
  414. System.Threading.Thread.Sleep(15000);
  415. lock (m_CompileQueue)
  416. {
  417. if (m_CompileQueue.Count==0)
  418. // No scripts on region, so won't get triggered later
  419. // by the queue becoming empty so we trigger it here
  420. m_Scene.EventManager.TriggerEmptyScriptCompileQueue(0, String.Empty);
  421. }
  422. }
  423. Object o;
  424. lock (m_CompileQueue)
  425. {
  426. o = m_CompileQueue.Dequeue();
  427. if (o == null)
  428. {
  429. m_CurrentCompile = null;
  430. return null;
  431. }
  432. }
  433. DoOnRezScript(o);
  434. lock (m_CompileQueue)
  435. {
  436. if (m_CompileQueue.Count > 0)
  437. {
  438. m_CurrentCompile = m_ThreadPool.QueueWorkItem(
  439. new WorkItemCallback(this.DoOnRezScriptQueue),
  440. new Object[0]);
  441. }
  442. else
  443. {
  444. m_CurrentCompile = null;
  445. m_Scene.EventManager.TriggerEmptyScriptCompileQueue(m_ScriptFailCount,
  446. m_ScriptErrorMessage);
  447. m_ScriptFailCount = 0;
  448. }
  449. }
  450. return null;
  451. }
  452. private bool DoOnRezScript(object parm)
  453. {
  454. Object[] p = (Object[])parm;
  455. uint localID = (uint)p[0];
  456. UUID itemID = (UUID)p[1];
  457. string script =(string)p[2];
  458. int startParam = (int)p[3];
  459. bool postOnRez = (bool)p[4];
  460. StateSource stateSource = (StateSource)p[5];
  461. // Get the asset ID of the script, so we can check if we
  462. // already have it.
  463. // We must look for the part outside the m_Scripts lock because GetSceneObjectPart later triggers the
  464. // m_parts lock on SOG. At the same time, a scene object that is being deleted will take the m_parts lock
  465. // and then later on try to take the m_scripts lock in this class when it calls OnRemoveScript()
  466. SceneObjectPart part = m_Scene.GetSceneObjectPart(localID);
  467. if (part == null)
  468. {
  469. m_log.Error("[Script] SceneObjectPart unavailable. Script NOT started.");
  470. m_ScriptErrorMessage += "SceneObjectPart unavailable. Script NOT started.\n";
  471. m_ScriptFailCount++;
  472. return false;
  473. }
  474. TaskInventoryItem item = part.Inventory.GetInventoryItem(itemID);
  475. if (item == null)
  476. {
  477. m_ScriptErrorMessage += "Can't find script inventory item.\n";
  478. m_ScriptFailCount++;
  479. return false;
  480. }
  481. UUID assetID = item.AssetID;
  482. //m_log.DebugFormat("[XEngine] Compiling script {0} ({1} on object {2})",
  483. // item.Name, itemID.ToString(), part.ParentGroup.RootPart.Name);
  484. ScenePresence presence = m_Scene.GetScenePresence(item.OwnerID);
  485. string assembly = "";
  486. CultureInfo USCulture = new CultureInfo("en-US");
  487. Thread.CurrentThread.CurrentCulture = USCulture;
  488. Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap;
  489. try
  490. {
  491. lock (m_AddingAssemblies)
  492. {
  493. assembly = m_Compiler.PerformScriptCompile(script,
  494. assetID.ToString(), item.OwnerID);
  495. if (!m_AddingAssemblies.ContainsKey(assembly)) {
  496. m_AddingAssemblies[assembly] = 1;
  497. } else {
  498. m_AddingAssemblies[assembly]++;
  499. }
  500. linemap = m_Compiler.LineMap();
  501. }
  502. string[] warnings = m_Compiler.GetWarnings();
  503. if (warnings != null && warnings.Length != 0)
  504. {
  505. if (presence != null && (!postOnRez))
  506. presence.ControllingClient.SendAgentAlertMessage("Script saved with warnings, check debug window!", false);
  507. foreach (string warning in warnings)
  508. {
  509. try
  510. {
  511. // DISPLAY WARNING INWORLD
  512. string text = "Warning:\n" + warning;
  513. if (text.Length > 1000)
  514. text = text.Substring(0, 1000);
  515. World.SimChat(Utils.StringToBytes(text),
  516. ChatTypeEnum.DebugChannel, 2147483647,
  517. part.AbsolutePosition,
  518. part.Name, part.UUID, false);
  519. }
  520. catch (Exception e2) // LEGIT: User Scripting
  521. {
  522. m_log.Error("[XEngine]: " +
  523. "Error displaying warning in-world: " +
  524. e2.ToString());
  525. m_log.Error("[XEngine]: " +
  526. "Warning:\r\n" +
  527. warning);
  528. }
  529. }
  530. }
  531. }
  532. catch (Exception e)
  533. {
  534. if (presence != null && (!postOnRez))
  535. presence.ControllingClient.SendAgentAlertMessage("Script saved with errors, check debug window!", false);
  536. try
  537. {
  538. // DISPLAY ERROR INWORLD
  539. m_ScriptErrorMessage += "Failed to compile script in object: '" + part.ParentGroup.RootPart.Name + "' Script name: '" + item.Name + "' Error message: " + e.Message.ToString();
  540. m_ScriptFailCount++;
  541. string text = "Error compiling script:\n" + e.Message.ToString();
  542. if (text.Length > 1000)
  543. text = text.Substring(0, 1000);
  544. World.SimChat(Utils.StringToBytes(text),
  545. ChatTypeEnum.DebugChannel, 2147483647,
  546. part.AbsolutePosition,
  547. part.Name, part.UUID, false);
  548. }
  549. catch (Exception e2) // LEGIT: User Scripting
  550. {
  551. m_log.Error("[XEngine]: "+
  552. "Error displaying error in-world: " +
  553. e2.ToString());
  554. m_log.Error("[XEngine]: " +
  555. "Errormessage: Error compiling script:\r\n" +
  556. e.Message.ToString());
  557. }
  558. return false;
  559. }
  560. lock (m_Scripts)
  561. {
  562. ScriptInstance instance = null;
  563. // Create the object record
  564. if ((!m_Scripts.ContainsKey(itemID)) ||
  565. (m_Scripts[itemID].AssetID != assetID))
  566. {
  567. UUID appDomain = assetID;
  568. if (part.ParentGroup.IsAttachment)
  569. appDomain = part.ParentGroup.RootPart.UUID;
  570. if (!m_AppDomains.ContainsKey(appDomain))
  571. {
  572. try
  573. {
  574. AppDomainSetup appSetup = new AppDomainSetup();
  575. // appSetup.ApplicationBase = Path.Combine(
  576. // "ScriptEngines",
  577. // m_Scene.RegionInfo.RegionID.ToString());
  578. Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
  579. Evidence evidence = new Evidence(baseEvidence);
  580. AppDomain sandbox =
  581. AppDomain.CreateDomain(
  582. m_Scene.RegionInfo.RegionID.ToString(),
  583. evidence, appSetup);
  584. /*
  585. PolicyLevel sandboxPolicy = PolicyLevel.CreateAppDomainLevel();
  586. AllMembershipCondition sandboxMembershipCondition = new AllMembershipCondition();
  587. PermissionSet sandboxPermissionSet = sandboxPolicy.GetNamedPermissionSet("Internet");
  588. PolicyStatement sandboxPolicyStatement = new PolicyStatement(sandboxPermissionSet);
  589. CodeGroup sandboxCodeGroup = new UnionCodeGroup(sandboxMembershipCondition, sandboxPolicyStatement);
  590. sandboxPolicy.RootCodeGroup = sandboxCodeGroup;
  591. sandbox.SetAppDomainPolicy(sandboxPolicy);
  592. */
  593. m_AppDomains[appDomain] = sandbox;
  594. m_AppDomains[appDomain].AssemblyResolve +=
  595. new ResolveEventHandler(
  596. AssemblyResolver.OnAssemblyResolve);
  597. m_DomainScripts[appDomain] = new List<UUID>();
  598. }
  599. catch (Exception e)
  600. {
  601. m_log.ErrorFormat("[XEngine] Exception creating app domain:\n {0}", e.ToString());
  602. m_ScriptErrorMessage += "Exception creating app domain:\n";
  603. m_ScriptFailCount++;
  604. lock (m_AddingAssemblies)
  605. {
  606. m_AddingAssemblies[assembly]--;
  607. }
  608. return false;
  609. }
  610. }
  611. m_DomainScripts[appDomain].Add(itemID);
  612. instance = new ScriptInstance(this, part,
  613. itemID, assetID, assembly,
  614. m_AppDomains[appDomain],
  615. part.ParentGroup.RootPart.Name,
  616. item.Name, startParam, postOnRez,
  617. stateSource, m_MaxScriptQueue);
  618. m_log.DebugFormat("[XEngine] Loaded script {0}.{1}, script UUID {2}, prim UUID {3} @ {4}",
  619. part.ParentGroup.RootPart.Name, item.Name, assetID, part.UUID, part.ParentGroup.RootPart.AbsolutePosition.ToString());
  620. instance.AppDomain = appDomain;
  621. instance.LineMap = linemap;
  622. m_Scripts[itemID] = instance;
  623. }
  624. lock (m_PrimObjects)
  625. {
  626. if (!m_PrimObjects.ContainsKey(localID))
  627. m_PrimObjects[localID] = new List<UUID>();
  628. if (!m_PrimObjects[localID].Contains(itemID))
  629. m_PrimObjects[localID].Add(itemID);
  630. }
  631. if (!m_Assemblies.ContainsKey(assetID))
  632. m_Assemblies[assetID] = assembly;
  633. lock (m_AddingAssemblies)
  634. {
  635. m_AddingAssemblies[assembly]--;
  636. }
  637. if (instance!=null)
  638. instance.Init();
  639. }
  640. return true;
  641. }
  642. public void OnRemoveScript(uint localID, UUID itemID)
  643. {
  644. lock (m_Scripts)
  645. {
  646. // Do we even have it?
  647. if (!m_Scripts.ContainsKey(itemID))
  648. return;
  649. IScriptInstance instance=m_Scripts[itemID];
  650. m_Scripts.Remove(itemID);
  651. instance.ClearQueue();
  652. instance.Stop(0);
  653. SceneObjectPart part =
  654. m_Scene.GetSceneObjectPart(localID);
  655. if (part != null)
  656. part.RemoveScriptEvents(itemID);
  657. // bool objectRemoved = false;
  658. lock (m_PrimObjects)
  659. {
  660. // Remove the script from it's prim
  661. if (m_PrimObjects.ContainsKey(localID))
  662. {
  663. // Remove inventory item record
  664. if (m_PrimObjects[localID].Contains(itemID))
  665. m_PrimObjects[localID].Remove(itemID);
  666. // If there are no more scripts, remove prim
  667. if (m_PrimObjects[localID].Count == 0)
  668. {
  669. m_PrimObjects.Remove(localID);
  670. // objectRemoved = true;
  671. }
  672. }
  673. }
  674. instance.RemoveState();
  675. instance.DestroyScriptInstance();
  676. m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
  677. if (m_DomainScripts[instance.AppDomain].Count == 0)
  678. {
  679. m_DomainScripts.Remove(instance.AppDomain);
  680. UnloadAppDomain(instance.AppDomain);
  681. }
  682. instance = null;
  683. ObjectRemoved handlerObjectRemoved = OnObjectRemoved;
  684. if (handlerObjectRemoved != null)
  685. handlerObjectRemoved(part.UUID);
  686. CleanAssemblies();
  687. }
  688. ScriptRemoved handlerScriptRemoved = OnScriptRemoved;
  689. if (handlerScriptRemoved != null)
  690. handlerScriptRemoved(itemID);
  691. }
  692. public void OnScriptReset(uint localID, UUID itemID)
  693. {
  694. ResetScript(itemID);
  695. }
  696. public void OnStartScript(uint localID, UUID itemID)
  697. {
  698. StartScript(itemID);
  699. }
  700. public void OnStopScript(uint localID, UUID itemID)
  701. {
  702. StopScript(itemID);
  703. }
  704. private void CleanAssemblies()
  705. {
  706. List<UUID> assetIDList = new List<UUID>(m_Assemblies.Keys);
  707. foreach (IScriptInstance i in m_Scripts.Values)
  708. {
  709. if (assetIDList.Contains(i.AssetID))
  710. assetIDList.Remove(i.AssetID);
  711. }
  712. lock (m_AddingAssemblies)
  713. {
  714. foreach (UUID assetID in assetIDList)
  715. {
  716. // Do not remove assembly files if another instance of the script
  717. // is currently initialising
  718. if (!m_AddingAssemblies.ContainsKey(m_Assemblies[assetID])
  719. || m_AddingAssemblies[m_Assemblies[assetID]] == 0)
  720. {
  721. // m_log.DebugFormat("[XEngine] Removing unreferenced assembly {0}", m_Assemblies[assetID]);
  722. try
  723. {
  724. if (File.Exists(m_Assemblies[assetID]))
  725. File.Delete(m_Assemblies[assetID]);
  726. if (File.Exists(m_Assemblies[assetID]+".text"))
  727. File.Delete(m_Assemblies[assetID]+".text");
  728. if (File.Exists(m_Assemblies[assetID]+".mdb"))
  729. File.Delete(m_Assemblies[assetID]+".mdb");
  730. if (File.Exists(m_Assemblies[assetID]+".map"))
  731. File.Delete(m_Assemblies[assetID]+".map");
  732. }
  733. catch (Exception)
  734. {
  735. }
  736. m_Assemblies.Remove(assetID);
  737. }
  738. }
  739. }
  740. }
  741. private void UnloadAppDomain(UUID id)
  742. {
  743. if (m_AppDomains.ContainsKey(id))
  744. {
  745. AppDomain domain = m_AppDomains[id];
  746. m_AppDomains.Remove(id);
  747. AppDomain.Unload(domain);
  748. domain = null;
  749. // m_log.DebugFormat("[XEngine] Unloaded app domain {0}", id.ToString());
  750. }
  751. }
  752. //
  753. // Start processing
  754. //
  755. private void SetupEngine(int minThreads, int maxThreads,
  756. int idleTimeout, ThreadPriority threadPriority,
  757. int maxScriptQueue, int stackSize)
  758. {
  759. m_MaxScriptQueue = maxScriptQueue;
  760. STPStartInfo startInfo = new STPStartInfo();
  761. startInfo.IdleTimeout = idleTimeout*1000; // convert to seconds as stated in .ini
  762. startInfo.MaxWorkerThreads = maxThreads;
  763. startInfo.MinWorkerThreads = minThreads;
  764. startInfo.ThreadPriority = threadPriority;
  765. startInfo.StackSize = stackSize;
  766. startInfo.StartSuspended = true;
  767. m_ThreadPool = new SmartThreadPool(startInfo);
  768. }
  769. //
  770. // Used by script instances to queue event handler jobs
  771. //
  772. public IScriptWorkItem QueueEventHandler(object parms)
  773. {
  774. return new XWorkItem(m_ThreadPool.QueueWorkItem(
  775. new WorkItemCallback(this.ProcessEventHandler),
  776. parms));
  777. }
  778. /// <summary>
  779. /// Process a previously posted script event.
  780. /// </summary>
  781. /// <param name="parms"></param>
  782. /// <returns></returns>
  783. private object ProcessEventHandler(object parms)
  784. {
  785. CultureInfo USCulture = new CultureInfo("en-US");
  786. Thread.CurrentThread.CurrentCulture = USCulture;
  787. IScriptInstance instance = (ScriptInstance) parms;
  788. //m_log.DebugFormat("[XENGINE]: Processing event for {0}", instance);
  789. return instance.EventProcessor();
  790. }
  791. /// <summary>
  792. /// Post event to an entire prim
  793. /// </summary>
  794. /// <param name="localID"></param>
  795. /// <param name="p"></param>
  796. /// <returns></returns>
  797. public bool PostObjectEvent(uint localID, EventParams p)
  798. {
  799. bool result = false;
  800. lock (m_PrimObjects)
  801. {
  802. if (!m_PrimObjects.ContainsKey(localID))
  803. return false;
  804. foreach (UUID itemID in m_PrimObjects[localID])
  805. {
  806. if (m_Scripts.ContainsKey(itemID))
  807. {
  808. IScriptInstance instance = m_Scripts[itemID];
  809. if (instance != null)
  810. {
  811. instance.PostEvent(p);
  812. result = true;
  813. }
  814. }
  815. }
  816. }
  817. return result;
  818. }
  819. /// <summary>
  820. /// Post an event to a single script
  821. /// </summary>
  822. /// <param name="itemID"></param>
  823. /// <param name="p"></param>
  824. /// <returns></returns>
  825. public bool PostScriptEvent(UUID itemID, EventParams p)
  826. {
  827. if (m_Scripts.ContainsKey(itemID))
  828. {
  829. IScriptInstance instance = m_Scripts[itemID];
  830. if (instance != null)
  831. instance.PostEvent(p);
  832. return true;
  833. }
  834. return false;
  835. }
  836. public bool PostScriptEvent(UUID itemID, string name, Object[] p)
  837. {
  838. Object[] lsl_p = new Object[p.Length];
  839. for (int i = 0; i < p.Length ; i++)
  840. {
  841. if (p[i] is int)
  842. lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]);
  843. else if (p[i] is string)
  844. lsl_p[i] = new LSL_Types.LSLString((string)p[i]);
  845. else if (p[i] is Vector3)
  846. lsl_p[i] = new LSL_Types.Vector3(((Vector3)p[i]).X, ((Vector3)p[i]).Y, ((Vector3)p[i]).Z);
  847. else if (p[i] is Quaternion)
  848. lsl_p[i] = new LSL_Types.Quaternion(((Quaternion)p[i]).X, ((Quaternion)p[i]).Y, ((Quaternion)p[i]).Z, ((Quaternion)p[i]).W);
  849. else if (p[i] is float)
  850. lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]);
  851. else
  852. lsl_p[i] = p[i];
  853. }
  854. return PostScriptEvent(itemID, new EventParams(name, lsl_p, new DetectParams[0]));
  855. }
  856. public bool PostObjectEvent(UUID itemID, string name, Object[] p)
  857. {
  858. SceneObjectPart part = m_Scene.GetSceneObjectPart(itemID);
  859. if (part == null)
  860. return false;
  861. Object[] lsl_p = new Object[p.Length];
  862. for (int i = 0; i < p.Length ; i++)
  863. {
  864. if (p[i] is int)
  865. lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]);
  866. else if (p[i] is string)
  867. lsl_p[i] = new LSL_Types.LSLString((string)p[i]);
  868. else if (p[i] is Vector3)
  869. lsl_p[i] = new LSL_Types.Vector3(((Vector3)p[i]).X, ((Vector3)p[i]).Y, ((Vector3)p[i]).Z);
  870. else if (p[i] is Quaternion)
  871. lsl_p[i] = new LSL_Types.Quaternion(((Quaternion)p[i]).X, ((Quaternion)p[i]).Y, ((Quaternion)p[i]).Z, ((Quaternion)p[i]).W);
  872. else if (p[i] is float)
  873. lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]);
  874. else
  875. lsl_p[i] = p[i];
  876. }
  877. return PostObjectEvent(part.LocalId, new EventParams(name, lsl_p, new DetectParams[0]));
  878. }
  879. public Assembly OnAssemblyResolve(object sender,
  880. ResolveEventArgs args)
  881. {
  882. if (!(sender is System.AppDomain))
  883. return null;
  884. string[] pathList = new string[] {"bin", "ScriptEngines",
  885. Path.Combine("ScriptEngines",
  886. m_Scene.RegionInfo.RegionID.ToString())};
  887. string assemblyName = args.Name;
  888. if (assemblyName.IndexOf(",") != -1)
  889. assemblyName = args.Name.Substring(0, args.Name.IndexOf(","));
  890. foreach (string s in pathList)
  891. {
  892. string path = Path.Combine(Directory.GetCurrentDirectory(),
  893. Path.Combine(s, assemblyName))+".dll";
  894. if (File.Exists(path))
  895. return Assembly.LoadFrom(path);
  896. }
  897. return null;
  898. }
  899. private IScriptInstance GetInstance(UUID itemID)
  900. {
  901. IScriptInstance instance;
  902. lock (m_Scripts)
  903. {
  904. if (!m_Scripts.ContainsKey(itemID))
  905. return null;
  906. instance = m_Scripts[itemID];
  907. }
  908. return instance;
  909. }
  910. public void SetScriptState(UUID itemID, bool running)
  911. {
  912. IScriptInstance instance = GetInstance(itemID);
  913. if (instance != null)
  914. {
  915. if (running)
  916. instance.Start();
  917. else
  918. instance.Stop(100);
  919. }
  920. }
  921. public bool GetScriptState(UUID itemID)
  922. {
  923. IScriptInstance instance = GetInstance(itemID);
  924. if (instance != null)
  925. return instance.Running;
  926. return false;
  927. }
  928. public void ApiResetScript(UUID itemID)
  929. {
  930. IScriptInstance instance = GetInstance(itemID);
  931. if (instance != null)
  932. instance.ApiResetScript();
  933. }
  934. public void ResetScript(UUID itemID)
  935. {
  936. IScriptInstance instance = GetInstance(itemID);
  937. if (instance != null)
  938. instance.ResetScript();
  939. }
  940. public void StartScript(UUID itemID)
  941. {
  942. IScriptInstance instance = GetInstance(itemID);
  943. if (instance != null)
  944. instance.Start();
  945. }
  946. public void StopScript(UUID itemID)
  947. {
  948. IScriptInstance instance = GetInstance(itemID);
  949. if (instance != null)
  950. instance.Stop(0);
  951. }
  952. public DetectParams GetDetectParams(UUID itemID, int idx)
  953. {
  954. IScriptInstance instance = GetInstance(itemID);
  955. if (instance != null)
  956. return instance.GetDetectParams(idx);
  957. return null;
  958. }
  959. public void SetMinEventDelay(UUID itemID, double delay)
  960. {
  961. IScriptInstance instance = GetInstance(itemID);
  962. if (instance != null)
  963. instance.MinEventDelay = delay;
  964. }
  965. public UUID GetDetectID(UUID itemID, int idx)
  966. {
  967. IScriptInstance instance = GetInstance(itemID);
  968. if (instance != null)
  969. return instance.GetDetectID(idx);
  970. return UUID.Zero;
  971. }
  972. public void SetState(UUID itemID, string newState)
  973. {
  974. IScriptInstance instance = GetInstance(itemID);
  975. if (instance == null)
  976. return;
  977. instance.SetState(newState);
  978. }
  979. public string GetState(UUID itemID)
  980. {
  981. IScriptInstance instance = GetInstance(itemID);
  982. if (instance == null)
  983. return "default";
  984. return instance.State;
  985. }
  986. public int GetStartParameter(UUID itemID)
  987. {
  988. IScriptInstance instance = GetInstance(itemID);
  989. if (instance == null)
  990. return 0;
  991. return instance.StartParam;
  992. }
  993. public void OnShutdown()
  994. {
  995. List<IScriptInstance> instances = new List<IScriptInstance>();
  996. lock (m_Scripts)
  997. {
  998. foreach (IScriptInstance instance in m_Scripts.Values)
  999. instances.Add(instance);
  1000. }
  1001. foreach (IScriptInstance i in instances)
  1002. {
  1003. // Stop the script, even forcibly if needed. Then flag
  1004. // it as shutting down and restore the previous run state
  1005. // for serialization, so the scripts don't come back
  1006. // dead after region restart
  1007. //
  1008. bool prevRunning = i.Running;
  1009. i.Stop(50);
  1010. i.ShuttingDown = true;
  1011. i.Running = prevRunning;
  1012. }
  1013. DoBackup(new Object[] {0});
  1014. }
  1015. public IScriptApi GetApi(UUID itemID, string name)
  1016. {
  1017. IScriptInstance instance = GetInstance(itemID);
  1018. if (instance == null)
  1019. return null;
  1020. return instance.GetApi(name);
  1021. }
  1022. public void OnGetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID)
  1023. {
  1024. IScriptInstance instance = GetInstance(itemID);
  1025. if (instance == null)
  1026. return;
  1027. IEventQueue eq = World.RequestModuleInterface<IEventQueue>();
  1028. if (eq == null)
  1029. {
  1030. controllingClient.SendScriptRunningReply(objectID, itemID,
  1031. GetScriptState(itemID));
  1032. }
  1033. else
  1034. {
  1035. eq.Enqueue(EventQueueHelper.ScriptRunningReplyEvent(objectID, itemID, GetScriptState(itemID), true),
  1036. controllingClient.AgentId);
  1037. }
  1038. }
  1039. public string GetAssemblyName(UUID itemID)
  1040. {
  1041. IScriptInstance instance = GetInstance(itemID);
  1042. if (instance == null)
  1043. return "";
  1044. return instance.GetAssemblyName();
  1045. }
  1046. public string GetXMLState(UUID itemID)
  1047. {
  1048. IScriptInstance instance = GetInstance(itemID);
  1049. if (instance == null)
  1050. return "";
  1051. return instance.GetXMLState();
  1052. }
  1053. public bool CanBeDeleted(UUID itemID)
  1054. {
  1055. IScriptInstance instance = GetInstance(itemID);
  1056. if (instance == null)
  1057. return true;
  1058. return instance.CanBeDeleted();
  1059. }
  1060. }
  1061. }