XMREngine.cs 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089
  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. // based on XMREngine from Mike Rieker (DreamNation), Melanie Thielker and meta7
  28. // but with several changes to be more cross platform.
  29. using log4net;
  30. using Mono.Addins;
  31. using Nini.Config;
  32. using OpenSim.Framework;
  33. using OpenSim.Framework.Console;
  34. using OpenSim.Framework.Monitoring;
  35. using OpenSim.Region.ClientStack.Linden;
  36. using OpenSim.Region.Framework.Interfaces;
  37. using OpenSim.Region.Framework.Scenes;
  38. using OpenSim.Region.ScriptEngine.Interfaces;
  39. using OpenSim.Region.ScriptEngine.Shared;
  40. using OpenSim.Region.ScriptEngine.Shared.Api;
  41. using OpenMetaverse;
  42. using System;
  43. using System.Collections;
  44. using System.Collections.Generic;
  45. using System.IO;
  46. using System.Reflection;
  47. using System.Reflection.Emit;
  48. using System.Text;
  49. using System.Threading;
  50. using System.Timers;
  51. using System.Xml;
  52. using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
  53. using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
  54. using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
  55. using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
  56. using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
  57. using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
  58. using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
  59. [assembly: Addin("YEngine", OpenSim.VersionInfo.VersionNumber)]
  60. [assembly: AddinDependency("OpenSim.Region.Framework", OpenSim.VersionInfo.VersionNumber)]
  61. namespace OpenSim.Region.ScriptEngine.Yengine
  62. {
  63. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "YEngine")]
  64. public partial class Yengine: INonSharedRegionModule, IScriptEngine,
  65. IScriptModule
  66. {
  67. public static readonly DetectParams[] zeroDetectParams = new DetectParams[0];
  68. private static ArrayList noScriptErrors = new ArrayList();
  69. public static readonly ILog m_log =
  70. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  71. private static readonly string[] scriptReferencedAssemblies = new string[0];
  72. private bool m_LateInit;
  73. private bool m_TraceCalls;
  74. public bool m_Verbose;
  75. public bool m_ScriptDebug;
  76. public bool m_ScriptDebugSaveSource;
  77. public bool m_ScriptDebugSaveIL;
  78. public Scene m_Scene;
  79. private IConfigSource m_ConfigSource;
  80. private IConfig m_Config;
  81. private string m_ScriptBasePath;
  82. private bool m_Enabled = false;
  83. public bool m_StartProcessing = false;
  84. private Dictionary<UUID, ArrayList> m_ScriptErrors = new Dictionary<UUID, ArrayList>();
  85. private Dictionary<UUID, List<UUID>> m_ObjectItemList = new Dictionary<UUID, List<UUID>>();
  86. private Dictionary<UUID, XMRInstance[]> m_ObjectInstArray = new Dictionary<UUID, XMRInstance[]>();
  87. public Dictionary<string, FieldInfo> m_XMRInstanceApiCtxFieldInfos = new Dictionary<string, FieldInfo>();
  88. public int m_StackSize;
  89. private int m_HeapSize;
  90. private Thread m_SleepThread = null;
  91. private bool m_Exiting = false;
  92. private int m_MaintenanceInterval = 10;
  93. private System.Timers.Timer m_MaintenanceTimer;
  94. public int numThreadScriptWorkers;
  95. private object m_FrameUpdateLock = new object();
  96. private event ThreadStart m_FrameUpdateList = null;
  97. // Various instance lists:
  98. // m_InstancesDict = all known instances
  99. // find an instance given its itemID
  100. // m_StartQueue = instances that have just had event queued to them
  101. // m_YieldQueue = instances that are ready to run right now
  102. // m_SleepQueue = instances that have m_SleepUntil valid
  103. // sorted by ascending m_SleepUntil
  104. private Dictionary<UUID, XMRInstance> m_InstancesDict =
  105. new Dictionary<UUID, XMRInstance>();
  106. public Queue<ThreadStart> m_ThunkQueue = new Queue<ThreadStart>();
  107. public XMRInstQueue m_StartQueue = new XMRInstQueue();
  108. public XMRInstQueue m_YieldQueue = new XMRInstQueue();
  109. public XMRInstQueue m_SleepQueue = new XMRInstQueue();
  110. private string m_LockedDict = "nobody";
  111. private ThreadPriority m_workersPrio;
  112. public Yengine()
  113. {
  114. }
  115. public string Name
  116. {
  117. get
  118. {
  119. return "YEngine";
  120. }
  121. }
  122. public Type ReplaceableInterface
  123. {
  124. get
  125. {
  126. return null;
  127. }
  128. }
  129. public string ScriptEnginePath
  130. {
  131. get
  132. {
  133. return m_ScriptBasePath;
  134. }
  135. }
  136. public string ScriptClassName
  137. {
  138. get
  139. {
  140. return "YEngineScript";
  141. }
  142. }
  143. public string ScriptBaseClassName
  144. {
  145. get
  146. {
  147. return typeof(XMRInstance).FullName;
  148. }
  149. }
  150. public ParameterInfo[] ScriptBaseClassParameters
  151. {
  152. get
  153. {
  154. return typeof(XMRInstance).GetConstructor(new Type[] { typeof(WaitHandle) }).GetParameters();
  155. }
  156. }
  157. public string[] ScriptReferencedAssemblies
  158. {
  159. get
  160. {
  161. return scriptReferencedAssemblies;
  162. }
  163. }
  164. public void Initialise(IConfigSource config)
  165. {
  166. TraceCalls("[YEngine]: Initialize entry");
  167. m_ConfigSource = config;
  168. ////foreach (IConfig icfg in config.Configs) {
  169. //// m_log.Debug("[YEngine]: Initialise: configs[" + icfg.Name + "]");
  170. //// foreach (string key in icfg.GetKeys ()) {
  171. //// m_log.Debug("[YEngine]: Initialise: " + key + "=" + icfg.GetExpanded (key));
  172. //// }
  173. ////}
  174. m_Enabled = false;
  175. m_Config = config.Configs["YEngine"];
  176. if(m_Config == null)
  177. {
  178. m_log.Info("[YEngine]: no config, assuming disabled");
  179. return;
  180. }
  181. m_Enabled = m_Config.GetBoolean("Enabled", false);
  182. m_log.InfoFormat("[YEngine]: config enabled={0}", m_Enabled);
  183. if(!m_Enabled)
  184. return;
  185. numThreadScriptWorkers = m_Config.GetInt("NumThreadScriptWorkers", 2);
  186. string priority = m_Config.GetString("Priority", "Normal");
  187. m_TraceCalls = m_Config.GetBoolean("TraceCalls", false);
  188. m_Verbose = m_Config.GetBoolean("Verbose", false);
  189. m_ScriptDebug = m_Config.GetBoolean("ScriptDebug", false);
  190. m_ScriptDebugSaveSource = m_Config.GetBoolean("ScriptDebugSaveSource", false);
  191. m_ScriptDebugSaveIL = m_Config.GetBoolean("ScriptDebugSaveIL", false);
  192. m_StackSize = m_Config.GetInt("ScriptStackSize", 2048) << 10;
  193. m_HeapSize = m_Config.GetInt("ScriptHeapSize", 1024) << 10;
  194. // Verify that our ScriptEventCode's match OpenSim's scriptEvent's.
  195. bool err = false;
  196. for(int i = 0; i < (int)ScriptEventCode.Size; i++)
  197. {
  198. string mycode = "undefined";
  199. string oscode = "undefined";
  200. try
  201. {
  202. mycode = ((ScriptEventCode)i).ToString();
  203. Convert.ToInt64(mycode);
  204. mycode = "undefined";
  205. }
  206. catch { }
  207. try
  208. {
  209. oscode = ((OpenSim.Region.Framework.Scenes.scriptEvents)(1ul << i)).ToString();
  210. Convert.ToInt64(oscode);
  211. oscode = "undefined";
  212. }
  213. catch { }
  214. if(mycode != oscode)
  215. {
  216. m_log.ErrorFormat("[YEngine]: {0} mycode={1}, oscode={2}", i, mycode, oscode);
  217. err = true;
  218. }
  219. }
  220. if(err)
  221. {
  222. m_Enabled = false;
  223. return;
  224. }
  225. m_workersPrio = ThreadPriority.Normal;
  226. switch (priority)
  227. {
  228. case "Lowest":
  229. m_workersPrio = ThreadPriority.Lowest;
  230. break;
  231. case "BelowNormal":
  232. m_workersPrio = ThreadPriority.BelowNormal;
  233. break;
  234. case "Normal":
  235. m_workersPrio = ThreadPriority.Normal;
  236. break;
  237. case "AboveNormal":
  238. m_workersPrio = ThreadPriority.AboveNormal;
  239. break;
  240. case "Highest":
  241. m_workersPrio = ThreadPriority.Highest;
  242. break;
  243. default:
  244. m_log.ErrorFormat("[YEngine] Invalid thread priority: '{0}'. Assuming Normal", priority);
  245. break;
  246. }
  247. m_MaintenanceInterval = m_Config.GetInt("MaintenanceInterval", 10);
  248. if(m_MaintenanceInterval > 0)
  249. {
  250. m_MaintenanceTimer = new System.Timers.Timer(m_MaintenanceInterval * 60000);
  251. m_MaintenanceTimer.Elapsed += DoMaintenance;
  252. m_MaintenanceTimer.Start();
  253. }
  254. MainConsole.Instance.Commands.AddCommand("yeng", false,
  255. "yeng", "yeng [...|help|...] ...",
  256. "Run YEngine script engine commands",
  257. HandleConsoleCmds);
  258. TraceCalls("[YEngine]: Initialize successful");
  259. }
  260. public void AddRegion(Scene scene)
  261. {
  262. if(!m_Enabled)
  263. return;
  264. TraceCalls("[YEngine]: YEngine.AddRegion({0})", scene.RegionInfo.RegionName);
  265. m_Scene = scene;
  266. m_Scene.RegisterModuleInterface<IScriptModule>(this);
  267. m_ScriptBasePath = m_Config.GetString("ScriptEnginesPath");
  268. //look for old
  269. if (string.IsNullOrWhiteSpace(m_ScriptBasePath))
  270. m_ScriptBasePath = m_Config.GetString("ScriptBasePath");
  271. if (string.IsNullOrWhiteSpace(m_ScriptBasePath))
  272. m_ScriptBasePath = "ScriptEngines";
  273. m_ScriptBasePath = Path.Combine(m_ScriptBasePath, "Yengine");
  274. m_ScriptBasePath = Path.Combine(m_ScriptBasePath, scene.RegionInfo.RegionID.ToString());
  275. Directory.CreateDirectory(m_ScriptBasePath);
  276. string sceneName = m_Scene.Name;
  277. m_log.InfoFormat("[YEngine]: Enabled for region {0}", sceneName);
  278. m_log.InfoFormat("[YEngine]: {0}.{1}MB stacksize, {2}.{3}MB heapsize",
  279. (m_StackSize >> 20).ToString(),
  280. (((m_StackSize % 0x100000) * 1000)
  281. >> 20).ToString("D3"),
  282. (m_HeapSize >> 20).ToString(),
  283. (((m_HeapSize % 0x100000) * 1000)
  284. >> 20).ToString("D3"));
  285. m_SleepThread = StartMyThread(RunSleepThread, "Yengine sleep" + " (" + sceneName + ")", ThreadPriority.Normal, -1);
  286. for (int i = 0; i < numThreadScriptWorkers; i++)
  287. StartThreadWorker(i, m_workersPrio, sceneName);
  288. m_Scene.EventManager.OnRezScript += OnRezScript;
  289. m_Scene.StackModuleInterface<IScriptModule>(this);
  290. }
  291. private void OneTimeLateInitialization()
  292. {
  293. // Build list of defined APIs and their 'this' types and define a field in XMRInstanceSuperType.
  294. ApiManager am = new ApiManager();
  295. Dictionary<string, Type> apiCtxTypes = new Dictionary<string, Type>();
  296. foreach(string api in am.GetApis())
  297. {
  298. m_log.Debug("[YEngine]: adding api " + api);
  299. IScriptApi scriptApi = am.CreateApi(api);
  300. Type apiCtxType = scriptApi.GetType();
  301. if(api == "LSL")
  302. apiCtxType = typeof(XMRLSL_Api);
  303. apiCtxTypes[api] = apiCtxType;
  304. }
  305. if(ScriptCodeGen.xmrInstSuperType == null) // Only create type once!
  306. {
  307. // Start creating type XMRInstanceSuperType that contains a field
  308. // m_ApiManager_<APINAME> that points to the per-instance context
  309. // struct for that API, ie, the 'this' value passed to all methods
  310. // in that API. It is in essence:
  311. // public class XMRInstanceSuperType : XMRInstance {
  312. // public XMRLSL_Api m_ApiManager_LSL; // 'this' value for all ll...() functions
  313. // public MOD_Api m_ApiManager_MOD; // 'this' value for all mod...() functions
  314. // public OSSL_Api m_ApiManager_OSSL; // 'this' value for all os...() functions
  315. // ....
  316. // }
  317. AssemblyName assemblyName = new AssemblyName();
  318. assemblyName.Name = "XMRInstanceSuperAssembly";
  319. AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
  320. ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("XMRInstanceSuperModule");
  321. TypeBuilder typeBuilder = moduleBuilder.DefineType("XMRInstanceSuperType", TypeAttributes.Public | TypeAttributes.Class);
  322. typeBuilder.SetParent(typeof(XMRInstance));
  323. foreach(string apiname in apiCtxTypes.Keys)
  324. {
  325. string fieldName = "m_ApiManager_" + apiname;
  326. typeBuilder.DefineField(fieldName, apiCtxTypes[apiname], FieldAttributes.Public);
  327. }
  328. // Finalize definition of XMRInstanceSuperType.
  329. // Give the compiler a short name to reference it by,
  330. // otherwise it will try to use the AssemblyQualifiedName
  331. // and fail miserably.
  332. ScriptCodeGen.xmrInstSuperType = typeBuilder.CreateType();
  333. ScriptObjWriter.DefineInternalType("xmrsuper", ScriptCodeGen.xmrInstSuperType);
  334. }
  335. // Tell the compiler about all the constants and methods for each API.
  336. // We also tell the compiler how to get the per-instance context for each API
  337. // by reading the corresponding m_ApiManager_<APINAME> field of XMRInstanceSuperType.
  338. foreach(KeyValuePair<string, Type> kvp in apiCtxTypes)
  339. {
  340. // get API name and the corresponding per-instance context type
  341. string api = kvp.Key;
  342. Type apiCtxType = kvp.Value;
  343. // give script compiler an abbreviated name for the API context type
  344. ScriptObjWriter.DefineInternalType("apimanager_" + api, apiCtxType);
  345. // this field tells the compiled code where the per-instance API context object is
  346. // eg, for the OSSL API, it is in ((XMRInstanceSuperType)inst).m_ApiManager_OSSL
  347. string fieldName = "m_ApiManager_" + api;
  348. FieldInfo fieldInfo = ScriptCodeGen.xmrInstSuperType.GetField(fieldName);
  349. m_XMRInstanceApiCtxFieldInfos[api] = fieldInfo;
  350. // now tell the compiler about the constants and methods for the API
  351. ScriptConst.AddInterfaceConstants(null, apiCtxType.GetFields());
  352. TokenDeclInline.AddInterfaceMethods(null, apiCtxType.GetMethods(), fieldInfo);
  353. }
  354. // Add sim-specific APIs to the compiler.
  355. IScriptModuleComms comms = m_Scene.RequestModuleInterface<IScriptModuleComms>();
  356. if(comms != null)
  357. {
  358. // Add methods to list of built-in functions.
  359. Delegate[] methods = comms.GetScriptInvocationList();
  360. foreach(Delegate m in methods)
  361. {
  362. MethodInfo mi = m.Method;
  363. try
  364. {
  365. CommsCallCodeGen cccg = new CommsCallCodeGen(mi, comms, m_XMRInstanceApiCtxFieldInfos["MOD"]);
  366. Verbose("[YEngine]: added comms function " + cccg.fullName);
  367. }
  368. catch(Exception e)
  369. {
  370. m_log.Error("[YEngine]: failed to add comms function " + mi.Name);
  371. m_log.Error("[YEngine]: - " + e.ToString());
  372. }
  373. }
  374. // Add constants to list of built-in constants.
  375. Dictionary<string, object> consts = comms.GetConstants();
  376. foreach(KeyValuePair<string, object> kvp in consts)
  377. {
  378. try
  379. {
  380. ScriptConst sc = ScriptConst.AddConstant(kvp.Key, kvp.Value);
  381. Verbose("[YEngine]: added comms constant " + sc.name);
  382. }
  383. catch(Exception e)
  384. {
  385. m_log.Error("[YEngine]: failed to add comms constant " + kvp.Key);
  386. m_log.Error("[YEngine]: - " + e.Message);
  387. }
  388. }
  389. }
  390. else
  391. {
  392. Verbose("[YEngine]: comms not enabled");
  393. }
  394. }
  395. /**
  396. * @brief Generate code for the calls to the comms functions.
  397. * It is a tRUlY EvIL interface.
  398. * To call the function we must call an XMRInstanceSuperType.m_ApiManager_MOD.modInvoker?()
  399. * method passing it the name of the function as a string and the script
  400. * argument list wrapped up in an object[] array. The modInvoker?() methods
  401. * do some sick type conversions (with corresponding mallocs) so we can't
  402. * call the methods directly.
  403. */
  404. private class CommsCallCodeGen: TokenDeclInline
  405. {
  406. private static Type[] modInvokerArgTypes = new Type[] { typeof(string), typeof(object[]) };
  407. public static FieldInfo xmrInstModApiCtxField;
  408. private MethodInfo modInvokerMeth;
  409. private string methName;
  410. /**
  411. * @brief Constructor
  412. * @param mi = method to make available to scripts
  413. * mi.Name = name that is used by scripts
  414. * mi.GetParameters() = parameter list as defined by module
  415. * includes the 'UUID host','UUID script' parameters that script does not see
  416. * allowed types for script-visible parameters are as follows:
  417. * Single -> float
  418. * Int32 -> integer
  419. * OpenMetaverse.UUID -> key
  420. * Object[] -> list
  421. * OpenMetaverse.Quaternion -> rotation
  422. * String -> string
  423. * OpenMetaverse.Vector3 -> vector
  424. * mi.ReturnType = return type as defined by module
  425. * types are same as allowed for parameters
  426. * @param comms = comms module the method came from
  427. * @param apictxfi = what field in XMRInstanceSuperType the 'this' value is for this method
  428. */
  429. public CommsCallCodeGen(MethodInfo mi, IScriptModuleComms comms, FieldInfo apictxfi)
  430. : base(null, false, NameArgSig(mi), RetType(mi))
  431. {
  432. methName = mi.Name;
  433. string modInvokerName = comms.LookupModInvocation(methName);
  434. if(modInvokerName == null)
  435. throw new Exception("cannot find comms method " + methName);
  436. modInvokerMeth = typeof(MOD_Api).GetMethod(modInvokerName, modInvokerArgTypes);
  437. xmrInstModApiCtxField = apictxfi;
  438. }
  439. // script-visible name(argtype,...) signature string
  440. private static string NameArgSig(MethodInfo mi)
  441. {
  442. StringBuilder sb = new StringBuilder();
  443. sb.Append(mi.Name);
  444. sb.Append('(');
  445. ParameterInfo[] mps = mi.GetParameters();
  446. for(int i = 2; i < mps.Length; i++)
  447. {
  448. ParameterInfo pi = mps[i];
  449. if(i > 2)
  450. sb.Append(',');
  451. sb.Append(ParamType(pi.ParameterType));
  452. }
  453. sb.Append(')');
  454. return sb.ToString();
  455. }
  456. // script-visible return type
  457. // note that although we support void, the comms stuff does not
  458. private static TokenType RetType(MethodInfo mi)
  459. {
  460. Type rt = mi.ReturnType;
  461. if(rt == typeof(float))
  462. return new TokenTypeFloat(null);
  463. if(rt == typeof(int))
  464. return new TokenTypeInt(null);
  465. if(rt == typeof(object[]))
  466. return new TokenTypeList(null);
  467. if(rt == typeof(OpenMetaverse.UUID))
  468. return new TokenTypeKey(null);
  469. if(rt == typeof(OpenMetaverse.Quaternion))
  470. return new TokenTypeRot(null);
  471. if(rt == typeof(string))
  472. return new TokenTypeStr(null);
  473. if(rt == typeof(OpenMetaverse.Vector3))
  474. return new TokenTypeVec(null);
  475. if(rt == null || rt == typeof(void))
  476. return new TokenTypeVoid(null);
  477. throw new Exception("unsupported return type " + rt.Name);
  478. }
  479. // script-visible parameter type
  480. private static string ParamType(Type t)
  481. {
  482. if(t == typeof(float))
  483. return "float";
  484. if(t == typeof(int))
  485. return "integer";
  486. if(t == typeof(OpenMetaverse.UUID))
  487. return "key";
  488. if(t == typeof(object[]))
  489. return "list";
  490. if(t == typeof(OpenMetaverse.Quaternion))
  491. return "rotation";
  492. if(t == typeof(string))
  493. return "string";
  494. if(t == typeof(OpenMetaverse.Vector3))
  495. return "vector";
  496. throw new Exception("unsupported parameter type " + t.Name);
  497. }
  498. /**
  499. * @brief Called by the compiler to generate a call to the comms function.
  500. * @param scg = which script is being compiled
  501. * @param errorAt = where in the source code the call is being made (for error messages)
  502. * @param result = a temp location to put the return value in if any
  503. * @param args = array of script-visible arguments being passed to the function
  504. */
  505. public override void CodeGen(ScriptCodeGen scg, Token errorAt, CompValuTemp result, CompValu[] args)
  506. {
  507. // Set up 'this' pointer for modInvoker?() = value from ApiManager.CreateApi("MOD").
  508. scg.PushXMRInst();
  509. scg.ilGen.Emit(errorAt, OpCodes.Castclass, xmrInstModApiCtxField.DeclaringType);
  510. scg.ilGen.Emit(errorAt, OpCodes.Ldfld, xmrInstModApiCtxField);
  511. // Set up 'fname' argument to modInvoker?() = name of the function to be called.
  512. scg.ilGen.Emit(errorAt, OpCodes.Ldstr, methName);
  513. // Set up 'parms' argument to modInvoker?() = object[] of the script-visible parameters,
  514. // in their LSL-wrapped form. Of course, the modInvoker?() method will malloc yet another
  515. // object[] and type-convert these parameters one-by-one with another round of unwrapping
  516. // and wrapping.
  517. // Types allowed in this object[]:
  518. // LSL_Float, LSL_Integer, LSL_Key, LSL_List, LSL_Rotation, LSL_String, LSL_Vector
  519. int nargs = args.Length;
  520. scg.ilGen.Emit(errorAt, OpCodes.Ldc_I4, nargs);
  521. scg.ilGen.Emit(errorAt, OpCodes.Newarr, typeof(object));
  522. for(int i = 0; i < nargs; i++)
  523. {
  524. scg.ilGen.Emit(errorAt, OpCodes.Dup);
  525. scg.ilGen.Emit(errorAt, OpCodes.Ldc_I4, i);
  526. // get location and type of argument
  527. CompValu arg = args[i];
  528. TokenType argtype = arg.type;
  529. // if already in a form acceptable to modInvoker?(),
  530. // just push it to the stack and convert to object
  531. // by boxing it if necessary
  532. // but if something like a double, int, string, etc
  533. // push to stack converting to the LSL-wrapped type
  534. // then convert to object by boxing if necessary
  535. Type boxit = null;
  536. if(argtype is TokenTypeLSLFloat)
  537. {
  538. args[i].PushVal(scg, errorAt);
  539. boxit = typeof(LSL_Float);
  540. }
  541. else if(argtype is TokenTypeLSLInt)
  542. {
  543. args[i].PushVal(scg, errorAt);
  544. boxit = typeof(LSL_Integer);
  545. }
  546. else if(argtype is TokenTypeLSLKey)
  547. {
  548. args[i].PushVal(scg, errorAt);
  549. boxit = typeof(LSL_Key);
  550. }
  551. else if(argtype is TokenTypeList)
  552. {
  553. args[i].PushVal(scg, errorAt);
  554. boxit = typeof(LSL_List);
  555. }
  556. else if(argtype is TokenTypeRot)
  557. {
  558. args[i].PushVal(scg, errorAt);
  559. boxit = typeof(LSL_Rotation);
  560. }
  561. else if(argtype is TokenTypeLSLString)
  562. {
  563. args[i].PushVal(scg, errorAt);
  564. boxit = typeof(LSL_String);
  565. }
  566. else if(argtype is TokenTypeVec)
  567. {
  568. args[i].PushVal(scg, errorAt);
  569. boxit = typeof(LSL_Vector);
  570. }
  571. else if(argtype is TokenTypeFloat)
  572. {
  573. args[i].PushVal(scg, errorAt, new TokenTypeLSLFloat(argtype));
  574. boxit = typeof(LSL_Float);
  575. }
  576. else if(argtype is TokenTypeInt)
  577. {
  578. args[i].PushVal(scg, errorAt, new TokenTypeLSLInt(argtype));
  579. boxit = typeof(LSL_Integer);
  580. }
  581. else if(argtype is TokenTypeKey)
  582. {
  583. args[i].PushVal(scg, errorAt, new TokenTypeLSLKey(argtype));
  584. boxit = typeof(LSL_Key);
  585. }
  586. else if(argtype is TokenTypeStr)
  587. {
  588. args[i].PushVal(scg, errorAt, new TokenTypeLSLString(argtype));
  589. boxit = typeof(LSL_String);
  590. }
  591. else
  592. throw new Exception("unsupported arg type " + argtype.GetType().Name);
  593. if(boxit.IsValueType)
  594. scg.ilGen.Emit(errorAt, OpCodes.Box, boxit);
  595. // pop the object into the object[]
  596. scg.ilGen.Emit(errorAt, OpCodes.Stelem, typeof(object));
  597. }
  598. // Call the modInvoker?() method.
  599. // It leaves an LSL-wrapped type on the stack.
  600. if(modInvokerMeth.IsVirtual)
  601. scg.ilGen.Emit(errorAt, OpCodes.Callvirt, modInvokerMeth);
  602. else
  603. scg.ilGen.Emit(errorAt, OpCodes.Call, modInvokerMeth);
  604. // The 3rd arg to Pop() is the type on the stack,
  605. // ie, what modInvoker?() actually returns.
  606. // The Pop() method will wrap/unwrap as needed.
  607. Type retSysType = modInvokerMeth.ReturnType;
  608. if(retSysType == null)
  609. retSysType = typeof(void);
  610. TokenType retTokType = TokenType.FromSysType(errorAt, retSysType);
  611. result.Pop(scg, errorAt, retTokType);
  612. }
  613. }
  614. /**
  615. * @brief Called late in shutdown procedure,
  616. * after the 'Shutting down..." message.
  617. */
  618. public void RemoveRegion(Scene scene)
  619. {
  620. if(!m_Enabled)
  621. return;
  622. TraceCalls("[YEngine]: YEngine.RemoveRegion({0})", scene.RegionInfo.RegionName);
  623. if(m_MaintenanceTimer != null)
  624. {
  625. m_MaintenanceTimer.Stop();
  626. m_MaintenanceTimer.Dispose();
  627. }
  628. // Write script states out to .state files so it will be
  629. // available when the region is restarted.
  630. DoMaintenance(null, null);
  631. // Stop executing script threads and wait for final
  632. // one to finish (ie, script gets to CheckRun() call).
  633. m_Exiting = true;
  634. if(m_SleepThread != null)
  635. {
  636. lock(m_SleepQueue)
  637. Monitor.PulseAll(m_SleepQueue);
  638. if(!m_SleepThread.Join(250))
  639. m_SleepThread.Abort();
  640. m_SleepThread = null;
  641. }
  642. StopThreadWorkers();
  643. m_Scene.EventManager.OnFrame -= OnFrame;
  644. m_Scene.EventManager.OnRezScript -= OnRezScript;
  645. m_Scene.EventManager.OnRemoveScript -= OnRemoveScript;
  646. m_Scene.EventManager.OnScriptReset -= OnScriptReset;
  647. m_Scene.EventManager.OnStartScript -= OnStartScript;
  648. m_Scene.EventManager.OnStopScript -= OnStopScript;
  649. m_Scene.EventManager.OnGetScriptRunning -= OnGetScriptRunning;
  650. m_Scene.EventManager.OnShutdown -= OnShutdown;
  651. m_Enabled = false;
  652. m_Scene = null;
  653. }
  654. public void RegionLoaded(Scene scene)
  655. {
  656. if(!m_Enabled)
  657. return;
  658. TraceCalls("[YEngine]: YEngine.RegionLoaded({0})", scene.RegionInfo.RegionName);
  659. m_Scene.EventManager.OnFrame += OnFrame;
  660. m_Scene.EventManager.OnRemoveScript += OnRemoveScript;
  661. m_Scene.EventManager.OnScriptReset += OnScriptReset;
  662. m_Scene.EventManager.OnStartScript += OnStartScript;
  663. m_Scene.EventManager.OnStopScript += OnStopScript;
  664. m_Scene.EventManager.OnGetScriptRunning += OnGetScriptRunning;
  665. m_Scene.EventManager.OnShutdown += OnShutdown;
  666. InitEvents();
  667. }
  668. public void StartProcessing()
  669. {
  670. m_log.Debug("[YEngine]: StartProcessing entry");
  671. m_StartProcessing = true;
  672. ResumeThreads();
  673. m_log.Debug("[YEngine]: StartProcessing return");
  674. m_Scene.EventManager.TriggerEmptyScriptCompileQueue(0, "");
  675. }
  676. public void Close()
  677. {
  678. TraceCalls("[YEngine]: YEngine.Close()");
  679. }
  680. private void HandleConsoleCmds(string module, string[] args)
  681. {
  682. if(args.Length < 2)
  683. {
  684. m_log.Info("[YEngine]: missing command, try 'yeng help'");
  685. return;
  686. }
  687. Scene consoleScene = SceneManager.Instance.CurrentOrFirstScene;
  688. bool SelectedRegion = (consoleScene != null && consoleScene.RegionInfo.RegionID == m_Scene.RegionInfo.RegionID);
  689. string cmd = args[1].ToLower();
  690. int firstPerRegionarg = args.Length >= 3 && args[2].Equals("allregions",StringComparison.InvariantCultureIgnoreCase) ? 3 : 2;
  691. if (!SelectedRegion)
  692. {
  693. if(firstPerRegionarg < 3)
  694. return;
  695. switch (cmd)
  696. {
  697. case "reset":
  698. case "resume":
  699. case "suspend":
  700. break;
  701. default:
  702. return;
  703. }
  704. }
  705. m_log.InfoFormat("[YEngine] ****Region: {0}", m_Scene.RegionInfo.RegionName);
  706. switch(cmd)
  707. {
  708. case "cvv":
  709. m_log.InfoFormat("[YEngine]: compiled version value = {0}",
  710. ScriptCodeGen.COMPILED_VERSION_VALUE);
  711. break;
  712. case "help":
  713. case "?":
  714. m_log.Info("[YEngine]: yeng reset [allregions] | [-help ...]");
  715. m_log.Info("[YEngine]: yeng resume [allregions] - resume script processing");
  716. m_log.Info("[YEngine]: yeng suspend [allregions] - suspend script processing");
  717. m_log.Info("[YEngine]: yeng ls [-help ...]");
  718. m_log.Info("[YEngine]: yeng cvv - show compiler version value");
  719. //m_log.Info("[YEngine]: yeng mvv [<newvalue>] - show migration version value");
  720. m_log.Info("[YEngine]: yeng mvv - show migration version value");
  721. m_log.Info("[YEngine]: yeng tracecalls [yes | no]");
  722. m_log.Info("[YEngine]: yeng verbose [yes | no]");
  723. //m_log.Info("[YEngine]: yeng pev [-help ...] - post event");
  724. break;
  725. case "ls":
  726. XmrTestLs(args, firstPerRegionarg);
  727. break;
  728. case "mvv":
  729. m_log.InfoFormat("[YEngine]: migration version value = {0}", XMRInstance.migrationVersion);
  730. break;
  731. //case "pev":
  732. // XmrTestPev(args, 2);
  733. // break;
  734. case "reset":
  735. XmrTestReset(args, firstPerRegionarg);
  736. break;
  737. case "resume":
  738. m_log.Info("[YEngine]: resuming scripts");
  739. ResumeThreads();
  740. break;
  741. case "suspend":
  742. m_log.Info("[YEngine]: suspending scripts");
  743. SuspendThreads();
  744. break;
  745. case "tracecalls":
  746. if(args.Length > firstPerRegionarg)
  747. m_TraceCalls = args[firstPerRegionarg].StartsWith("y", StringComparison.InvariantCultureIgnoreCase);
  748. m_log.Info("[YEngine]: tracecalls " + (m_TraceCalls ? "yes" : "no"));
  749. break;
  750. case "verbose":
  751. if(args.Length > firstPerRegionarg)
  752. m_Verbose = args[firstPerRegionarg].StartsWith("y", StringComparison.InvariantCultureIgnoreCase);
  753. m_log.Info("[YEngine]: verbose " + (m_Verbose ? "yes" : "no"));
  754. break;
  755. default:
  756. m_log.ErrorFormat("[YEngine]: unknown command \"{0}\", try 'yeng help'", cmd);
  757. break;
  758. }
  759. }
  760. // Not required when not using IScriptInstance
  761. //
  762. public IScriptWorkItem QueueEventHandler(object parms)
  763. {
  764. return null;
  765. }
  766. public Scene World
  767. {
  768. get
  769. {
  770. return m_Scene;
  771. }
  772. }
  773. public IScriptModule ScriptModule
  774. {
  775. get
  776. {
  777. return this;
  778. }
  779. }
  780. public void SaveAllState()
  781. {
  782. m_log.Error("[YEngine]: YEngine.SaveAllState() called!!");
  783. }
  784. #pragma warning disable 0067
  785. public event ScriptRemoved OnScriptRemoved;
  786. public event ObjectRemoved OnObjectRemoved;
  787. #pragma warning restore 0067
  788. // Events targeted at a specific script
  789. // ... like listen() for an llListen() call
  790. //
  791. public bool PostScriptEvent(UUID itemID, EventParams parms)
  792. {
  793. XMRInstance instance = GetInstance(itemID);
  794. if (instance == null)
  795. return false;
  796. TraceCalls("[YEngine]: YEngine.PostScriptEvent({0},{1})", itemID.ToString(), parms.EventName);
  797. instance.PostEvent(parms);
  798. return true;
  799. }
  800. public void CancelScriptEvent(UUID itemID, string eventName)
  801. {
  802. XMRInstance instance = GetInstance(itemID);
  803. if (instance == null)
  804. return;
  805. TraceCalls("[YEngine]: YEngine.CancelScriptEvent({0},{1})", itemID.ToString(), eventName);
  806. instance.CancelEvent(eventName);
  807. }
  808. // Events targeted at all scripts in the given prim.
  809. // localID = which prim
  810. // parms = event to post
  811. //
  812. public bool PostObjectEvent(uint localID, EventParams parms)
  813. {
  814. if(m_Exiting)
  815. return false;
  816. SceneObjectPart part = m_Scene.GetSceneObjectPart(localID);
  817. if(part == null)
  818. return false;
  819. TraceCalls("[YEngine]: YEngine.PostObjectEvent({0},{1})", localID.ToString(), parms.EventName);
  820. // In SecondLife, attach events go to all scripts of all prims
  821. // in a linked object. So here we duplicate that functionality,
  822. // as all we ever get is a single attach event for the whole
  823. // object.
  824. if(parms.EventName == "attach")
  825. {
  826. bool posted = false;
  827. foreach(SceneObjectPart primpart in part.ParentGroup.Parts)
  828. posted |= PostPrimEvent(primpart, parms);
  829. return posted;
  830. }
  831. // Other events go to just the scripts in that prim.
  832. return PostPrimEvent(part, parms);
  833. }
  834. private bool PostPrimEvent(SceneObjectPart part, EventParams parms)
  835. {
  836. UUID partUUID = part.UUID;
  837. // Get list of script instances running in the object.
  838. XMRInstance[] objInstArray;
  839. lock(m_InstancesDict)
  840. {
  841. if(!m_ObjectInstArray.TryGetValue(partUUID, out objInstArray))
  842. return false;
  843. if (objInstArray == null)
  844. {
  845. objInstArray = RebuildObjectInstArray(partUUID);
  846. m_ObjectInstArray[partUUID] = objInstArray;
  847. }
  848. }
  849. // Post event to all script instances in the object.
  850. if(objInstArray.Length <= 0)
  851. return false;
  852. foreach (XMRInstance inst in objInstArray)
  853. inst.PostEvent(parms);
  854. return true;
  855. }
  856. public DetectParams GetDetectParams(UUID itemID, int number)
  857. {
  858. XMRInstance instance = GetInstance(itemID);
  859. if(instance == null)
  860. return null;
  861. return instance.GetDetectParams(number);
  862. }
  863. public void SetMinEventDelay(UUID itemID, double delay)
  864. {
  865. XMRInstance instance = GetInstance(itemID);
  866. if (instance != null)
  867. instance.MinEventDelay = delay;
  868. }
  869. public int GetStartParameter(UUID itemID)
  870. {
  871. XMRInstance instance = GetInstance(itemID);
  872. if (instance == null)
  873. return 0;
  874. return instance.StartParam;
  875. }
  876. // This is the "set running" method
  877. //
  878. public void SetScriptState(UUID itemID, bool state, bool self)
  879. {
  880. SetScriptState(itemID, state);
  881. }
  882. public void SetScriptState(UUID itemID, bool state)
  883. {
  884. XMRInstance instance = GetInstance(itemID);
  885. if(instance != null)
  886. {
  887. instance.Running = state;
  888. if(instance.m_Item != null)
  889. instance.m_Item.ScriptRunning = instance.Running;
  890. }
  891. }
  892. //
  893. public bool GetScriptState(UUID itemID)
  894. {
  895. XMRInstance instance = GetInstance(itemID);
  896. if(instance == null)
  897. return false;
  898. return instance.Running;
  899. }
  900. public void SetState(UUID itemID, string newState)
  901. {
  902. TraceCalls("[YEngine]: YEngine.SetState({0},{1})", itemID.ToString(), newState);
  903. }
  904. public void ApiResetScript(UUID itemID)
  905. {
  906. XMRInstance instance = GetInstance(itemID);
  907. if(instance != null)
  908. instance.ApiReset();
  909. }
  910. public void ResetScript(UUID itemID)
  911. {
  912. XMRInstance instance = GetInstance(itemID);
  913. if(instance != null)
  914. {
  915. IUrlModule urlModule = m_Scene.RequestModuleInterface<IUrlModule>();
  916. if(urlModule != null)
  917. urlModule.ScriptRemoved(itemID);
  918. instance.Reset();
  919. }
  920. }
  921. public IConfig Config
  922. {
  923. get
  924. {
  925. return m_Config;
  926. }
  927. }
  928. public IConfigSource ConfigSource
  929. {
  930. get
  931. {
  932. return m_ConfigSource;
  933. }
  934. }
  935. public string ScriptEngineName
  936. {
  937. get
  938. {
  939. return "YEngine";
  940. }
  941. }
  942. public IScriptApi GetApi(UUID itemID, string name)
  943. {
  944. FieldInfo fi;
  945. if(!m_XMRInstanceApiCtxFieldInfos.TryGetValue(name, out fi))
  946. return null;
  947. XMRInstance inst = GetInstance(itemID);
  948. if(inst == null)
  949. return null;
  950. return (IScriptApi)fi.GetValue(inst);
  951. }
  952. /**
  953. * @brief Get script's current state as an XML string
  954. * - called by "Take", "Take Copy" and when object deleted (ie, moved to Trash)
  955. * This includes the .state file
  956. */
  957. public string GetXMLState(UUID itemID)
  958. {
  959. XMRInstance instance = GetInstance(itemID);
  960. if(instance == null)
  961. return String.Empty;
  962. TraceCalls("[YEngine]: YEngine.GetXMLState({0})", itemID.ToString());
  963. if(!instance.m_HasRun)
  964. return String.Empty;
  965. XmlDocument doc = new XmlDocument();
  966. /*
  967. * Set up <State Engine="YEngine" UUID="itemID" Asset="assetID"> tag.
  968. */
  969. XmlElement stateN = doc.CreateElement("", "State", "");
  970. doc.AppendChild(stateN);
  971. XmlAttribute engineA = doc.CreateAttribute("", "Engine", "");
  972. engineA.Value = ScriptEngineName;
  973. stateN.Attributes.Append(engineA);
  974. XmlAttribute uuidA = doc.CreateAttribute("", "UUID", "");
  975. uuidA.Value = itemID.ToString();
  976. stateN.Attributes.Append(uuidA);
  977. XmlAttribute assetA = doc.CreateAttribute("", "Asset", "");
  978. string assetID = instance.AssetID.ToString();
  979. assetA.Value = assetID;
  980. stateN.Attributes.Append(assetA);
  981. // Get <ScriptState>...</ScriptState> item that hold's script's state.
  982. // This suspends the script if necessary then takes a snapshot.
  983. XmlElement scriptStateN = instance.GetExecutionState(doc);
  984. stateN.AppendChild(scriptStateN);
  985. return doc.OuterXml;
  986. }
  987. // Set script's current state from an XML string
  988. // - called just before a script is instantiated
  989. // So we write the .state file so the .state file will be seen when
  990. // the script is instantiated.
  991. public bool SetXMLState(UUID itemID, string xml)
  992. {
  993. XmlDocument doc = new XmlDocument();
  994. try
  995. {
  996. doc.LoadXml(xml);
  997. }
  998. catch
  999. {
  1000. return false;
  1001. }
  1002. TraceCalls("[YEngine]: YEngine.SetXMLState({0})", itemID.ToString());
  1003. // Make sure <State Engine="YEngine"> so we know it is in our
  1004. // format.
  1005. XmlElement stateN = (XmlElement)doc.SelectSingleNode("State");
  1006. if(stateN == null)
  1007. return false;
  1008. bool isX = false;
  1009. string sen = stateN.GetAttribute("Engine");
  1010. if (sen == null)
  1011. return false;
  1012. if (sen != ScriptEngineName)
  1013. {
  1014. if(sen != "XEngine")
  1015. return false;
  1016. isX = true;
  1017. }
  1018. // <ScriptState>...</ScriptState> contains contents of .state file.
  1019. XmlElement scriptStateN = (XmlElement)stateN.SelectSingleNode("ScriptState");
  1020. if(scriptStateN == null)
  1021. return false;
  1022. if(!isX)
  1023. {
  1024. sen = stateN.GetAttribute("Engine");
  1025. if ((sen == null) || (sen != ScriptEngineName))
  1026. return false;
  1027. }
  1028. XmlAttribute assetA = doc.CreateAttribute("", "Asset", "");
  1029. assetA.Value = stateN.GetAttribute("Asset");
  1030. scriptStateN.Attributes.Append(assetA);
  1031. // Write out the .state file with the <ScriptState ...>...</ScriptState> XML text
  1032. string statePath = XMRInstance.GetStateFileName(m_ScriptBasePath, itemID);
  1033. using (FileStream ss = File.Create(statePath))
  1034. {
  1035. using (StreamWriter sw = new StreamWriter(ss))
  1036. sw.Write(scriptStateN.OuterXml);
  1037. }
  1038. return true;
  1039. }
  1040. public bool PostScriptEvent(UUID itemID, string name, Object[] p)
  1041. {
  1042. if(!m_Enabled)
  1043. return false;
  1044. TraceCalls("[YEngine]: YEngine.PostScriptEvent({0},{1})", itemID.ToString(), name);
  1045. return PostScriptEvent(itemID, new EventParams(name, p, zeroDetectParams));
  1046. }
  1047. public bool PostObjectEvent(UUID itemID, string name, Object[] p)
  1048. {
  1049. if(!m_Enabled)
  1050. return false;
  1051. TraceCalls("[YEngine]: YEngine.PostObjectEvent({0},{1})", itemID.ToString(), name);
  1052. SceneObjectPart part = m_Scene.GetSceneObjectPart(itemID);
  1053. if(part == null)
  1054. return false;
  1055. return PostObjectEvent(part.LocalId, new EventParams(name, p, zeroDetectParams));
  1056. }
  1057. // about the 3523rd entrypoint for a script to put itself to sleep
  1058. public void SleepScript(UUID itemID, int delay)
  1059. {
  1060. XMRInstance instance = GetInstance(itemID);
  1061. if(instance != null)
  1062. instance.Sleep(delay);
  1063. }
  1064. // Get a script instance loaded, compiling it if necessary
  1065. //
  1066. // localID = the object as a whole, may contain many scripts
  1067. // itemID = this instance of the script in this object
  1068. // script = script source code
  1069. // startParam = value passed to 'on_rez' event handler
  1070. // postOnRez = true to post an 'on_rez' event to script on load
  1071. // defEngine = default script engine
  1072. // stateSource = post this event to script on load
  1073. public void OnRezScript(uint localID, UUID itemID, string script,
  1074. int startParam, bool postOnRez, string defEngine, int stateSource)
  1075. {
  1076. if (script.StartsWith("//MRM:"))
  1077. return;
  1078. if(!m_LateInit)
  1079. {
  1080. m_LateInit = true;
  1081. OneTimeLateInitialization();
  1082. }
  1083. TraceCalls("[YEngine]: OnRezScript(...,{0},...)", itemID.ToString());
  1084. // Assume script uses the default engine
  1085. string engineName = defEngine;
  1086. // Very first line might contain // scriptengine : language
  1087. string langsrt = "";
  1088. if (script.StartsWith("//"))
  1089. {
  1090. int lineEnd = script.IndexOf('\n');
  1091. if(lineEnd > 5)
  1092. {
  1093. string firstline = script.Substring(2, lineEnd - 2).Trim();
  1094. int colon = firstline.IndexOf(':');
  1095. if(colon >= 3)
  1096. {
  1097. engineName = firstline.Substring(0, colon).TrimEnd();
  1098. if(string.IsNullOrEmpty(engineName))
  1099. engineName = defEngine;
  1100. }
  1101. if (colon > 0 && colon < firstline.Length - 2)
  1102. {
  1103. langsrt = firstline.Substring(colon + 1).Trim();
  1104. langsrt = langsrt.ToLower();
  1105. }
  1106. }
  1107. }
  1108. // Make sure the default or requested engine is us.
  1109. if(engineName != ScriptEngineName)
  1110. {
  1111. // Not us, if requested engine exists, silently ignore script and let
  1112. // requested engine handle it.
  1113. IScriptModule[] engines = m_Scene.RequestModuleInterfaces<IScriptModule>();
  1114. foreach(IScriptModule eng in engines)
  1115. {
  1116. if(eng.ScriptEngineName == engineName)
  1117. return;
  1118. }
  1119. // Requested engine not defined, warn on console.
  1120. // Then we try to handle it if we're the default engine, else we ignore it.
  1121. //m_log.Warn("[YEngine]: " + itemID.ToString() + " requests undefined/disabled engine " + engineName);
  1122. //m_log.Info("[YEngine]: - " + part.GetWorldPosition());
  1123. //m_log.Info("[YEngine]: first line: " + firstline);
  1124. if(defEngine != ScriptEngineName)
  1125. {
  1126. //m_log.Info("[YEngine]: leaving it to the default script engine (" + defEngine + ") to process it");
  1127. return;
  1128. }
  1129. // m_log.Info("[YEngine]: will attempt to processing it anyway as default script engine");
  1130. langsrt = "";
  1131. }
  1132. if(!string.IsNullOrEmpty(langsrt) && langsrt !="lsl")
  1133. return;
  1134. SceneObjectPart part = m_Scene.GetSceneObjectPart(localID);
  1135. TaskInventoryItem item = part.Inventory.GetInventoryItem(itemID);
  1136. // Put on object/instance lists.
  1137. XMRInstance instance = (XMRInstance)Activator.CreateInstance(ScriptCodeGen.xmrInstSuperType);
  1138. instance.m_LocalID = localID;
  1139. instance.m_ItemID = itemID;
  1140. instance.m_SourceCode = script;
  1141. instance.m_StartParam = startParam;
  1142. instance.m_PostOnRez = postOnRez;
  1143. instance.m_StateSource = (StateSource)stateSource;
  1144. instance.m_Part = part;
  1145. instance.m_PartUUID = part.UUID;
  1146. instance.m_Item = item;
  1147. instance.m_DescName = part.Name + ":" + item.Name;
  1148. instance.m_IState = XMRInstState.CONSTRUCT;
  1149. instance.m_Running = item.ScriptRunning;
  1150. lock (m_InstancesDict)
  1151. {
  1152. m_LockedDict = "RegisterInstance";
  1153. // Insert on internal list of all scripts being handled by this engine instance.
  1154. m_InstancesDict[instance.m_ItemID] = instance;
  1155. // Insert on internal list of all scripts being handled by this engine instance
  1156. // that are part of the object.
  1157. List<UUID> itemIDList;
  1158. if(!m_ObjectItemList.TryGetValue(instance.m_PartUUID, out itemIDList))
  1159. {
  1160. itemIDList = new List<UUID>();
  1161. m_ObjectItemList[instance.m_PartUUID] = itemIDList;
  1162. }
  1163. if(!itemIDList.Contains(instance.m_ItemID))
  1164. {
  1165. itemIDList.Add(instance.m_ItemID);
  1166. m_ObjectInstArray[instance.m_PartUUID] = null;
  1167. }
  1168. m_LockedDict = "~RegisterInstance";
  1169. }
  1170. // Compile and load it.
  1171. lock(m_ScriptErrors)
  1172. m_ScriptErrors.Remove(instance.m_ItemID);
  1173. LoadThreadWork(instance);
  1174. }
  1175. /**
  1176. * @brief This routine instantiates one script.
  1177. */
  1178. private void LoadThreadWork(XMRInstance instance)
  1179. {
  1180. // Compile and load the script in memory.
  1181. ArrayList errors = new ArrayList();
  1182. Exception initerr = null;
  1183. try
  1184. {
  1185. instance.Initialize(this, m_ScriptBasePath, m_StackSize, m_HeapSize, errors);
  1186. }
  1187. catch(Exception e1)
  1188. {
  1189. initerr = e1;
  1190. }
  1191. if(initerr != null && !instance.m_ForceRecomp && initerr is CVVMismatchException)
  1192. {
  1193. UUID itemID = instance.m_ItemID;
  1194. Verbose("[YEngine]: {0}/{2} first load failed ({1}), retrying after recompile",
  1195. itemID.ToString(), initerr.Message, instance.m_Item.AssetID.ToString());
  1196. Verbose("[YEngine]:\n{0}", initerr.ToString());
  1197. initerr = null;
  1198. errors = new ArrayList();
  1199. instance.m_ForceRecomp = true;
  1200. try
  1201. {
  1202. instance.Initialize(this, m_ScriptBasePath, m_StackSize, m_HeapSize, errors);
  1203. }
  1204. catch(Exception e2)
  1205. {
  1206. initerr = e2;
  1207. }
  1208. }
  1209. if(initerr != null)
  1210. {
  1211. UUID itemID = instance.m_ItemID;
  1212. Verbose("[YEngine]: Error starting script {0}/{2}: {1}",
  1213. itemID.ToString(), initerr.Message, instance.m_Item.AssetID.ToString());
  1214. if(initerr.Message != "compilation errors")
  1215. {
  1216. Verbose("[YEngine]: - " + instance.m_Part.GetWorldPosition() + " " + instance.m_DescName);
  1217. Verbose("[YEngine]: exception:\n{0}", initerr.ToString());
  1218. }
  1219. OnRemoveScript(0, itemID);
  1220. // Post errors where GetScriptErrors() can see them.
  1221. if(errors.Count == 0)
  1222. errors.Add(initerr.Message);
  1223. else
  1224. {
  1225. foreach(Object err in errors)
  1226. {
  1227. if(m_ScriptDebug)
  1228. m_log.DebugFormat("[YEngine]: {0}", err.ToString());
  1229. }
  1230. }
  1231. lock(m_ScriptErrors)
  1232. m_ScriptErrors[instance.m_ItemID] = errors;
  1233. return;
  1234. }
  1235. // Tell GetScriptErrors() that we have finished compiling/loading
  1236. // successfully (by posting a 0 element array).
  1237. lock(m_ScriptErrors)
  1238. {
  1239. if(instance.m_IState != XMRInstState.CONSTRUCT)
  1240. throw new Exception("bad state");
  1241. m_ScriptErrors[instance.m_ItemID] = noScriptErrors;
  1242. }
  1243. // Transition from CONSTRUCT->ONSTARTQ and give to RunScriptThread().
  1244. // Put it on the start queue so it will run any queued event handlers,
  1245. // such as state_entry() or on_rez(). If there aren't any queued, it
  1246. // will just go to idle state when RunOne() tries to dequeue an event.
  1247. // Declare which events the script's current state can handle.
  1248. ulong eventMask = instance.GetStateEventFlags(instance.stateCode);
  1249. instance.m_Part.SetScriptEvents(instance.m_ItemID, eventMask);
  1250. lock (instance.m_QueueLock)
  1251. {
  1252. if(instance.m_IState != XMRInstState.CONSTRUCT)
  1253. throw new Exception("bad state");
  1254. if (instance.m_Running)
  1255. {
  1256. instance.m_Item.ScriptRunning = true;
  1257. instance.m_IState = XMRInstState.ONSTARTQ;
  1258. QueueToStart(instance);
  1259. }
  1260. else
  1261. {
  1262. instance.m_Item.ScriptRunning = false;
  1263. instance.m_IState = XMRInstState.SUSPENDED;
  1264. }
  1265. }
  1266. }
  1267. public void OnRemoveScript(uint localID, UUID itemID)
  1268. {
  1269. TraceCalls("[YEngine]: OnRemoveScript(...,{0})", itemID.ToString());
  1270. // Remove from our list of known scripts.
  1271. // After this, no more events can queue because we won't be
  1272. // able to translate the itemID to an XMRInstance pointer.
  1273. XMRInstance instance = null;
  1274. lock(m_InstancesDict)
  1275. {
  1276. m_LockedDict = "OnRemoveScript:" + itemID.ToString();
  1277. // Tell the instance to free off everything it can.
  1278. if(!m_InstancesDict.TryGetValue(itemID, out instance))
  1279. {
  1280. m_LockedDict = "~OnRemoveScript";
  1281. return;
  1282. }
  1283. // Tell it to stop executing anything.
  1284. instance.suspendOnCheckRunHold = true;
  1285. // Remove it from our list of known script instances
  1286. // mostly so no more events can queue to it.
  1287. m_InstancesDict.Remove(itemID);
  1288. List<UUID> itemIDList;
  1289. if(m_ObjectItemList.TryGetValue(instance.m_PartUUID, out itemIDList))
  1290. {
  1291. itemIDList.Remove(itemID);
  1292. if(itemIDList.Count == 0)
  1293. {
  1294. m_ObjectItemList.Remove(instance.m_PartUUID);
  1295. m_ObjectInstArray.Remove(instance.m_PartUUID);
  1296. }
  1297. else
  1298. m_ObjectInstArray[instance.m_PartUUID] = null;
  1299. }
  1300. // Delete the .state file as any needed contents were fetched with GetXMLState()
  1301. // and stored on the database server.
  1302. string stateFileName = XMRInstance.GetStateFileName(m_ScriptBasePath, itemID);
  1303. File.Delete(stateFileName);
  1304. OnScriptRemoved?.Invoke(itemID);
  1305. m_LockedDict = "~~OnRemoveScript";
  1306. }
  1307. // Free off its stack and fun things like that.
  1308. // If it is running, abort it.
  1309. instance.Dispose();
  1310. }
  1311. public void OnScriptReset(uint localID, UUID itemID)
  1312. {
  1313. TraceCalls("[YEngine]: YEngine.OnScriptReset({0},{1})", localID.ToString(), itemID.ToString());
  1314. ResetScript(itemID);
  1315. }
  1316. public void OnStartScript(uint localID, UUID itemID)
  1317. {
  1318. XMRInstance instance = GetInstance(itemID);
  1319. if(instance != null)
  1320. {
  1321. instance.Running = true;
  1322. if (instance.m_Item != null)
  1323. instance.m_Item.ScriptRunning = true;
  1324. }
  1325. }
  1326. public void OnStopScript(uint localID, UUID itemID)
  1327. {
  1328. XMRInstance instance = GetInstance(itemID);
  1329. if(instance != null)
  1330. {
  1331. instance.Running = false;
  1332. if (instance.m_Item != null)
  1333. instance.m_Item.ScriptRunning = false;
  1334. }
  1335. }
  1336. public void OnGetScriptRunning(IClientAPI controllingClient,
  1337. UUID objectID, UUID itemID)
  1338. {
  1339. XMRInstance instance = GetInstance(itemID);
  1340. if(instance != null)
  1341. {
  1342. TraceCalls("[YEngine]: YEngine.OnGetScriptRunning({0},{1})", objectID.ToString(), itemID.ToString());
  1343. bool curRunnning = instance.Running;
  1344. instance.m_Item.ScriptRunning = curRunnning;
  1345. IEventQueue eq = World.RequestModuleInterface<IEventQueue>();
  1346. if(eq == null)
  1347. {
  1348. controllingClient.SendScriptRunningReply(objectID, itemID, curRunnning);
  1349. }
  1350. else
  1351. {
  1352. eq.ScriptRunningEvent(objectID, itemID, curRunnning, controllingClient.AgentId);
  1353. }
  1354. }
  1355. }
  1356. public bool HasScript(UUID itemID, out bool running)
  1357. {
  1358. XMRInstance instance = GetInstance(itemID);
  1359. if(instance == null)
  1360. {
  1361. running = true;
  1362. return false;
  1363. }
  1364. running = instance.Running;
  1365. return true;
  1366. }
  1367. /**
  1368. * @brief Called once per frame update to see if scripts have
  1369. * any such work to do.
  1370. */
  1371. private void OnFrame()
  1372. {
  1373. if(m_FrameUpdateList != null)
  1374. {
  1375. ThreadStart frameupdates;
  1376. lock(m_FrameUpdateLock)
  1377. {
  1378. frameupdates = m_FrameUpdateList;
  1379. m_FrameUpdateList = null;
  1380. }
  1381. frameupdates();
  1382. }
  1383. }
  1384. /**
  1385. * @brief Add a one-shot delegate to list of things to do
  1386. * synchronized with frame updates.
  1387. */
  1388. public void AddOnFrameUpdate(ThreadStart thunk)
  1389. {
  1390. lock(m_FrameUpdateLock)
  1391. m_FrameUpdateList += thunk;
  1392. }
  1393. /**
  1394. * @brief Gets called early as part of shutdown,
  1395. * right after "Persisting changed objects" message.
  1396. */
  1397. public void OnShutdown()
  1398. {
  1399. TraceCalls("[YEngine]: YEngine.OnShutdown()");
  1400. }
  1401. /**
  1402. * @brief Queue an instance to the StartQueue so it will run.
  1403. * This queue is used for instances that have just had
  1404. * an event queued to them when they were previously
  1405. * idle. It must only be called by the thread that
  1406. * transitioned the thread to XMRInstState.ONSTARTQ so
  1407. * we don't get two threads trying to queue the same
  1408. * instance to the m_StartQueue at the same time.
  1409. */
  1410. public void QueueToStart(XMRInstance inst)
  1411. {
  1412. if (inst.m_IState != XMRInstState.ONSTARTQ)
  1413. throw new Exception("bad state");
  1414. lock (m_StartQueue)
  1415. m_StartQueue.InsertTail(inst);
  1416. WakeUpOne();
  1417. }
  1418. public void QueueToYield(XMRInstance inst)
  1419. {
  1420. if (inst.m_IState != XMRInstState.ONYIELDQ)
  1421. throw new Exception("bad state");
  1422. lock (m_YieldQueue)
  1423. m_YieldQueue.InsertTail(inst);
  1424. WakeUpOne();
  1425. }
  1426. public void RemoveFromSleep(XMRInstance inst)
  1427. {
  1428. lock (m_SleepQueue)
  1429. {
  1430. if (inst.m_IState != XMRInstState.ONSLEEPQ)
  1431. return;
  1432. m_SleepQueue.Remove(inst);
  1433. inst.m_IState = XMRInstState.REMDFROMSLPQ;
  1434. }
  1435. }
  1436. /**
  1437. * @brief A script may be sleeping, in which case we wake it.
  1438. */
  1439. public void WakeFromSleep(XMRInstance inst)
  1440. {
  1441. // Remove from sleep queue unless someone else already woke it.
  1442. lock(m_SleepQueue)
  1443. {
  1444. if(inst.m_IState != XMRInstState.ONSLEEPQ)
  1445. return;
  1446. m_SleepQueue.Remove(inst);
  1447. inst.m_IState = XMRInstState.REMDFROMSLPQ;
  1448. }
  1449. // Put on end of list of scripts that are ready to run.
  1450. lock(m_YieldQueue)
  1451. {
  1452. inst.m_IState = XMRInstState.ONYIELDQ;
  1453. m_YieldQueue.InsertTail(inst);
  1454. }
  1455. // Make sure the OS thread is running so it will see the script.
  1456. WakeUpOne();
  1457. }
  1458. /**
  1459. * @brief An instance has just finished running for now,
  1460. * figure out what to do with it next.
  1461. * @param inst = instance in question, not on any queue at the moment
  1462. * @param newIState = its new state
  1463. * @returns with instance inserted onto proper queue (if any)
  1464. */
  1465. public void HandleNewIState(XMRInstance inst, XMRInstState newIState)
  1466. {
  1467. // RunOne() should have left the instance in RUNNING state.
  1468. if(inst.m_IState != XMRInstState.RUNNING)
  1469. throw new Exception("bad state");
  1470. // Now see what RunOne() wants us to do with the instance next.
  1471. switch(newIState)
  1472. {
  1473. // Instance has set m_SleepUntil to when it wants to sleep until.
  1474. // So insert instance in sleep queue by ascending wake time.
  1475. // Then wake the timer thread if this is the new first entry
  1476. // so it will reset its timer.
  1477. case XMRInstState.ONSLEEPQ:
  1478. lock(m_SleepQueue)
  1479. {
  1480. XMRInstance after;
  1481. inst.m_IState = XMRInstState.ONSLEEPQ;
  1482. for(after = m_SleepQueue.PeekHead(); after != null; after = after.m_NextInst)
  1483. {
  1484. if(after.m_SleepUntil > inst.m_SleepUntil)
  1485. break;
  1486. }
  1487. m_SleepQueue.InsertBefore(inst, after);
  1488. if(m_SleepQueue.PeekHead() == inst)
  1489. Monitor.Pulse(m_SleepQueue);
  1490. }
  1491. break;
  1492. // Instance just took a long time to run and got wacked by the
  1493. // slicer. So put on end of yield queue to let someone else
  1494. // run. If there is no one else, it will run again right away.
  1495. case XMRInstState.ONYIELDQ:
  1496. lock(m_YieldQueue)
  1497. {
  1498. inst.m_IState = XMRInstState.ONYIELDQ;
  1499. m_YieldQueue.InsertTail(inst);
  1500. }
  1501. break;
  1502. // Instance finished executing an event handler. So if there is
  1503. // another event queued for it, put it on the start queue so it
  1504. // will process the new event. Otherwise, mark it idle and the
  1505. // next event to queue to it will start it up.
  1506. case XMRInstState.FINISHED:
  1507. Monitor.Enter(inst.m_QueueLock);
  1508. if(!inst.m_Suspended && (inst.m_EventQueue.Count > 0))
  1509. {
  1510. inst.m_IState = XMRInstState.ONSTARTQ;
  1511. Monitor.Exit(inst.m_QueueLock);
  1512. lock(m_StartQueue)
  1513. m_StartQueue.InsertTail(inst);
  1514. }
  1515. else
  1516. {
  1517. inst.m_IState = XMRInstState.IDLE;
  1518. Monitor.Exit(inst.m_QueueLock);
  1519. }
  1520. m_Scene.AddScriptEvents(1);
  1521. break;
  1522. // Its m_SuspendCount > 0.
  1523. // Don't put it on any queue and it won't run.
  1524. // Since it's not IDLE, even queuing an event won't start it.
  1525. case XMRInstState.SUSPENDED:
  1526. inst.m_IState = XMRInstState.SUSPENDED;
  1527. break;
  1528. // It has been disposed of.
  1529. // Just set the new state and all refs should theoretically drop off
  1530. // as the instance is no longer in any list.
  1531. case XMRInstState.DISPOSED:
  1532. inst.m_IState = XMRInstState.DISPOSED;
  1533. break;
  1534. // RunOne returned something bad.
  1535. default:
  1536. throw new Exception("bad new state");
  1537. }
  1538. }
  1539. /**
  1540. * @brief Thread that moves instances from the Sleep queue to the Yield queue.
  1541. */
  1542. private void RunSleepThread()
  1543. {
  1544. double deltaTS;
  1545. int deltaMS;
  1546. XMRInstance inst;
  1547. while(true)
  1548. {
  1549. lock(m_SleepQueue)
  1550. {
  1551. // Wait here until there is a script on the timer queue that has expired.
  1552. while(true)
  1553. {
  1554. UpdateMyThread();
  1555. if(m_Exiting)
  1556. {
  1557. MyThreadExiting();
  1558. return;
  1559. }
  1560. inst = m_SleepQueue.PeekHead();
  1561. if(inst == null)
  1562. {
  1563. Monitor.Wait(m_SleepQueue, Watchdog.DEFAULT_WATCHDOG_TIMEOUT_MS / 2);
  1564. continue;
  1565. }
  1566. if(inst.m_IState != XMRInstState.ONSLEEPQ)
  1567. throw new Exception("bad state");
  1568. deltaTS = (inst.m_SleepUntil - DateTime.UtcNow).TotalMilliseconds;
  1569. if(deltaTS <= 0.0)
  1570. break;
  1571. deltaMS = Int32.MaxValue;
  1572. if(deltaTS < Int32.MaxValue)
  1573. deltaMS = (int)deltaTS;
  1574. if(deltaMS > Watchdog.DEFAULT_WATCHDOG_TIMEOUT_MS / 2)
  1575. deltaMS = Watchdog.DEFAULT_WATCHDOG_TIMEOUT_MS / 2;
  1576. Monitor.Wait(m_SleepQueue, deltaMS);
  1577. }
  1578. // Remove the expired entry from the timer queue.
  1579. m_SleepQueue.RemoveHead();
  1580. inst.m_IState = XMRInstState.REMDFROMSLPQ;
  1581. }
  1582. // Post the script to the yield queue so it will run and wake a script thread to run it.
  1583. lock(m_YieldQueue)
  1584. {
  1585. inst.m_IState = XMRInstState.ONYIELDQ;
  1586. m_YieldQueue.InsertTail(inst);
  1587. }
  1588. WakeUpOne();
  1589. }
  1590. }
  1591. public void Suspend(UUID itemID, int ms)
  1592. {
  1593. XMRInstance instance = GetInstance(itemID);
  1594. if(instance != null)
  1595. instance.Sleep(ms);
  1596. }
  1597. public void Die(UUID itemID)
  1598. {
  1599. XMRInstance instance = GetInstance(itemID);
  1600. if(instance != null)
  1601. {
  1602. TraceCalls("[YEngine]: YEngine.Die({0})", itemID.ToString());
  1603. instance.Die();
  1604. }
  1605. }
  1606. /**
  1607. * @brief Get specific script instance for which OnRezScript()
  1608. * has been called for an YEngine script, and that
  1609. * OnRemoveScript() has not been called since.
  1610. * @param itemID = as passed to OnRezScript() identifying a specific script instance
  1611. * @returns null: not one of our scripts (maybe XEngine etc)
  1612. * else: points to the script instance
  1613. */
  1614. public XMRInstance GetInstance(UUID itemID)
  1615. {
  1616. XMRInstance instance;
  1617. lock(m_InstancesDict)
  1618. {
  1619. if(!m_InstancesDict.TryGetValue(itemID, out instance))
  1620. instance = null;
  1621. }
  1622. return instance;
  1623. }
  1624. // Called occasionally to write script state to .state file so the
  1625. // script will restart from its last known state if the region crashes
  1626. // and gets restarted.
  1627. private void DoMaintenance(object source, ElapsedEventArgs e)
  1628. {
  1629. XMRInstance[] instanceArray;
  1630. lock(m_InstancesDict)
  1631. instanceArray = System.Linq.Enumerable.ToArray(m_InstancesDict.Values);
  1632. foreach(XMRInstance ins in instanceArray)
  1633. {
  1634. // Don't save attachments
  1635. if(ins.m_Part.ParentGroup.IsAttachment)
  1636. continue;
  1637. ins.GetExecutionState(new XmlDocument());
  1638. }
  1639. }
  1640. /**
  1641. * @brief Retrieve errors generated by a previous call to OnRezScript().
  1642. * We are guaranteed this routine will not be called before the
  1643. * corresponding OnRezScript() has returned. It blocks until the
  1644. * compile has completed.
  1645. */
  1646. public ArrayList GetScriptErrors(UUID itemID)
  1647. {
  1648. ArrayList errors;
  1649. lock(m_ScriptErrors)
  1650. {
  1651. while(!m_ScriptErrors.TryGetValue(itemID, out errors))
  1652. {
  1653. Monitor.Wait(m_ScriptErrors);
  1654. }
  1655. m_ScriptErrors.Remove(itemID);
  1656. }
  1657. return errors;
  1658. }
  1659. /**
  1660. * @brief Return a list of all script execution times.
  1661. */
  1662. public Dictionary<uint, float> GetObjectScriptsExecutionTimes()
  1663. {
  1664. Dictionary<uint, float> topScripts = new Dictionary<uint, float>();
  1665. lock(m_InstancesDict)
  1666. {
  1667. foreach(XMRInstance instance in m_InstancesDict.Values)
  1668. {
  1669. uint rootLocalID = instance.m_Part.ParentGroup.LocalId;
  1670. float oldTotal;
  1671. if(!topScripts.TryGetValue(rootLocalID, out oldTotal))
  1672. oldTotal = 0;
  1673. topScripts[rootLocalID] = (float)instance.m_CPUTime + oldTotal;
  1674. }
  1675. }
  1676. return topScripts;
  1677. }
  1678. /**
  1679. * @brief Return a list of object script used bytes and time
  1680. */
  1681. public ICollection<ScriptTopStatsData> GetTopObjectStats(float mintime, int minmemory, out float totaltime, out float totalmemory)
  1682. {
  1683. Dictionary<uint, ScriptTopStatsData> topScripts = new Dictionary<uint, ScriptTopStatsData>();
  1684. totalmemory = 0;
  1685. totaltime = 0;
  1686. lock (m_InstancesDict)
  1687. {
  1688. foreach (XMRInstance instance in m_InstancesDict.Values)
  1689. {
  1690. uint rootLocalID = instance.m_Part.ParentGroup.LocalId;
  1691. float time = (float)instance.m_CPUTime;
  1692. totaltime += time;
  1693. int mem = instance.xmrHeapUsed();
  1694. totalmemory += mem;
  1695. if (time > mintime || mem > minmemory)
  1696. {
  1697. ScriptTopStatsData sd;
  1698. if (topScripts.TryGetValue(rootLocalID, out sd))
  1699. {
  1700. sd.time += time;
  1701. sd.memory += mem;
  1702. }
  1703. else
  1704. {
  1705. sd = new ScriptTopStatsData();
  1706. sd.localID = rootLocalID;
  1707. sd.time = time;
  1708. sd.memory = mem;
  1709. topScripts[rootLocalID] = sd;
  1710. }
  1711. }
  1712. }
  1713. }
  1714. return topScripts.Values;
  1715. }
  1716. /**
  1717. * @brief A float the value is a representative execution time in
  1718. * milliseconds of all scripts in the link set.
  1719. * @param itemIDs = list of scripts in the link set
  1720. * @returns milliseconds for all those scripts
  1721. */
  1722. public float GetScriptExecutionTime(List<UUID> itemIDs)
  1723. {
  1724. if((itemIDs == null) || (itemIDs.Count == 0))
  1725. return 0;
  1726. float time = 0;
  1727. foreach(UUID itemID in itemIDs)
  1728. {
  1729. XMRInstance instance = GetInstance(itemID);
  1730. if((instance != null) && instance.Running)
  1731. time += (float)instance.m_CPUTime;
  1732. }
  1733. return time;
  1734. }
  1735. public int GetScriptsMemory(List<UUID> itemIDs)
  1736. {
  1737. if ((itemIDs == null) || (itemIDs.Count == 0))
  1738. return 0;
  1739. int memory = 0;
  1740. foreach (UUID itemID in itemIDs)
  1741. {
  1742. XMRInstance instance = GetInstance(itemID);
  1743. if ((instance != null) && instance.Running)
  1744. memory += instance.xmrHeapUsed();
  1745. }
  1746. return memory;
  1747. }
  1748. /**
  1749. * @brief Block script from dequeuing events.
  1750. */
  1751. public bool SuspendScript(UUID itemID)
  1752. {
  1753. XMRInstance instance = GetInstance(itemID);
  1754. if(instance != null)
  1755. {
  1756. TraceCalls("[YEngine]: YEngine.SuspendScript({0})", itemID.ToString());
  1757. instance.SuspendIt();
  1758. return true;
  1759. }
  1760. return false;
  1761. }
  1762. /**
  1763. * @brief Allow script to dequeue events.
  1764. */
  1765. public bool ResumeScript(UUID itemID)
  1766. {
  1767. XMRInstance instance = GetInstance(itemID);
  1768. if(instance != null)
  1769. {
  1770. TraceCalls("[YEngine]: YEngine.ResumeScript({0})", itemID.ToString());
  1771. instance.ResumeIt();
  1772. return true;
  1773. }
  1774. else
  1775. {
  1776. // probably an XEngine script
  1777. }
  1778. return false;
  1779. }
  1780. /**
  1781. * @brief Rebuild m_ObjectInstArray[partUUID] from m_ObjectItemList[partUUID]
  1782. * @param partUUID = which object in scene to rebuild for
  1783. */
  1784. private XMRInstance[] RebuildObjectInstArray(UUID partUUID)
  1785. {
  1786. List<UUID> itemIDList = m_ObjectItemList[partUUID];
  1787. XMRInstance[] a = new XMRInstance[itemIDList.Count];
  1788. if(itemIDList.Count > 0)
  1789. {
  1790. int n = 0;
  1791. foreach (UUID itemID in itemIDList)
  1792. {
  1793. if (m_InstancesDict.TryGetValue(itemID, out a[n]))
  1794. n++;
  1795. }
  1796. if(n < itemIDList.Count)
  1797. Array.Resize(ref a, n);
  1798. }
  1799. m_ObjectInstArray[partUUID] = a;
  1800. return a;
  1801. }
  1802. public void TraceCalls(string format, params object[] args)
  1803. {
  1804. if(m_TraceCalls)
  1805. m_log.DebugFormat(format, args);
  1806. }
  1807. public void Verbose(string format, params object[] args)
  1808. {
  1809. if(m_Verbose)
  1810. m_log.DebugFormat(format, args);
  1811. }
  1812. /**
  1813. * @brief Manage our threads.
  1814. */
  1815. public static Thread StartMyThread(ThreadStart start, string name, ThreadPriority priority, int stackSize)
  1816. {
  1817. m_log.Debug("[YEngine]: starting thread " + name);
  1818. Thread thread = WorkManager.StartThread(start, name, priority, stackSize);
  1819. return thread;
  1820. }
  1821. public static void UpdateMyThread()
  1822. {
  1823. Watchdog.UpdateThread();
  1824. }
  1825. public static void MyThreadExiting()
  1826. {
  1827. Watchdog.RemoveThread(true);
  1828. }
  1829. }
  1830. }