XMREngine.cs 82 KB

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