XMRInstCtor.cs 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Threading;
  29. using System.Reflection;
  30. using System.Collections;
  31. using System.Collections.Generic;
  32. using System.Security.Policy;
  33. using System.IO;
  34. using System.Xml;
  35. using System.Text;
  36. using OpenMetaverse;
  37. using OpenSim.Framework;
  38. using OpenSim.Region.ScriptEngine.Interfaces;
  39. using OpenSim.Region.ScriptEngine.Shared;
  40. using OpenSim.Region.ScriptEngine.Shared.Api;
  41. using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
  42. using OpenSim.Region.ScriptEngine.Yengine;
  43. using OpenSim.Region.Framework.Scenes;
  44. using log4net;
  45. using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
  46. using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
  47. using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
  48. using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
  49. using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
  50. using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
  51. using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
  52. namespace OpenSim.Region.ScriptEngine.Yengine
  53. {
  54. public partial class XMRInstance
  55. {
  56. /****************************************************************************\
  57. * The only method of interest to outside this module is the Initializer. *
  58. * *
  59. * The rest of this module contains support routines for the Initializer. *
  60. \****************************************************************************/
  61. /**
  62. * @brief Initializer, loads script in memory and all ready for running.
  63. * @param engine = YEngine instance this is part of
  64. * @param scriptBasePath = directory name where files are
  65. * @param stackSize = number of bytes to allocate for stacks
  66. * @param errors = return compiler errors in this array
  67. * @param forceRecomp = force recompile
  68. * Throws exception if any error, so it was successful if it returns.
  69. */
  70. public void Initialize(Yengine engine, string scriptBasePath,
  71. int stackSize, int heapSize, ArrayList errors)
  72. {
  73. if(stackSize < 16384)
  74. stackSize = 16384;
  75. if(heapSize < 16384)
  76. heapSize = 16384;
  77. // Save all call parameters in instance vars for easy access.
  78. m_Engine = engine;
  79. m_ScriptBasePath = scriptBasePath;
  80. m_StackSize = stackSize;
  81. m_StackLeft = stackSize;
  82. m_HeapSize = heapSize;
  83. m_localsHeapUsed = 0;
  84. m_CompilerErrors = errors;
  85. m_StateFileName = GetStateFileName(scriptBasePath, m_ItemID);
  86. // Not in any XMRInstQueue.
  87. m_NextInst = this;
  88. m_PrevInst = this;
  89. // Set up list of API calls it has available.
  90. // This also gets the API modules ready to accept setup data, such as
  91. // active listeners being restored.
  92. IScriptApi scriptApi;
  93. ApiManager am = new ApiManager();
  94. foreach(string api in am.GetApis())
  95. {
  96. // Instantiate the API for this script instance.
  97. if(api != "LSL")
  98. scriptApi = am.CreateApi(api);
  99. else
  100. scriptApi = m_XMRLSLApi = new XMRLSL_Api();
  101. // Connect it up to the instance.
  102. InitScriptApi(engine, api, scriptApi);
  103. }
  104. m_XMRLSLApi.InitXMRLSLApi(this);
  105. // Get object loaded, compiling script and reading .state file as
  106. // necessary to restore the state.
  107. suspendOnCheckRunHold = true;
  108. InstantiateScript();
  109. m_SourceCode = null;
  110. if(m_ObjCode == null)
  111. throw new ArgumentNullException("m_ObjCode");
  112. if(m_ObjCode.scriptEventHandlerTable == null)
  113. throw new ArgumentNullException("m_ObjCode.scriptEventHandlerTable");
  114. suspendOnCheckRunHold = false;
  115. suspendOnCheckRunTemp = false;
  116. }
  117. private void InitScriptApi(Yengine engine, string api, IScriptApi scriptApi)
  118. {
  119. // Set up m_ApiManager_<APINAME> = instance pointer.
  120. engine.m_XMRInstanceApiCtxFieldInfos[api].SetValue(this, scriptApi);
  121. // Initialize the API instance.
  122. scriptApi.Initialize(m_Engine, m_Part, m_Item);
  123. InitApi(api, scriptApi);
  124. }
  125. /*
  126. * Get script object code loaded in memory and all ready to run,
  127. * ready to resume it from where the .state file says it was last
  128. */
  129. private void InstantiateScript()
  130. {
  131. bool compiledIt = false;
  132. ScriptObjCode objCode;
  133. // If source code string is empty, use the asset ID as the object file name.
  134. // Allow lines of // comments at the beginning (for such as engine selection).
  135. int i, j, len;
  136. if(m_SourceCode == null)
  137. m_SourceCode = String.Empty;
  138. for(len = m_SourceCode.Length; len > 0; --len)
  139. {
  140. if(m_SourceCode[len - 1] > ' ')
  141. break;
  142. }
  143. for(i = 0; i < len; i++)
  144. {
  145. char c = m_SourceCode[i];
  146. if(c <= ' ')
  147. continue;
  148. if(c != '/')
  149. break;
  150. if((i + 1 >= len) || (m_SourceCode[i + 1] != '/'))
  151. break;
  152. i = m_SourceCode.IndexOf('\n', i);
  153. if(i < 0)
  154. i = len - 1;
  155. }
  156. if((i >= len))
  157. {
  158. // Source consists of nothing but // comments and whitespace,
  159. // or we are being forced to use the asset-id as the key, to
  160. // open an already existing object code file.
  161. m_ScriptObjCodeKey = m_Item.AssetID.ToString();
  162. if(i >= len)
  163. m_SourceCode = "";
  164. }
  165. else
  166. {
  167. // Make up dictionary key for the object code.
  168. // Use the same object code for identical source code
  169. // regardless of asset ID, so we don't care if they
  170. // copy scripts or not.
  171. byte[] scbytes = System.Text.Encoding.UTF8.GetBytes(m_SourceCode);
  172. StringBuilder sb = new StringBuilder((256 + 5) / 6);
  173. using (System.Security.Cryptography.SHA256 sha = System.Security.Cryptography.SHA256.Create())
  174. ByteArrayToSixbitStr(sb, sha.ComputeHash(scbytes));
  175. m_ScriptObjCodeKey = sb.ToString();
  176. // But source code can be just a sixbit string itself
  177. // that identifies an already existing object code file.
  178. if(len - i == m_ScriptObjCodeKey.Length)
  179. {
  180. for(j = len; --j >= i;)
  181. {
  182. if(sixbit.IndexOf(m_SourceCode[j]) < 0)
  183. break;
  184. }
  185. if(j < i)
  186. {
  187. m_ScriptObjCodeKey = m_SourceCode.Substring(i, len - i);
  188. m_SourceCode = "";
  189. }
  190. }
  191. }
  192. // There may already be an ScriptObjCode struct in memory that
  193. // we can use. If not, try to compile it.
  194. lock(m_CompileLock)
  195. {
  196. if(!m_CompiledScriptObjCode.TryGetValue(m_ScriptObjCodeKey, out objCode) || m_ForceRecomp)
  197. {
  198. objCode = TryToCompile();
  199. compiledIt = true;
  200. }
  201. // Loaded successfully, increment reference count.
  202. // If we just compiled it though, reset count to 0 first as
  203. // this is the one-and-only existance of this objCode struct,
  204. // and we want any old ones for this source code to be garbage
  205. // collected.
  206. if(compiledIt)
  207. {
  208. m_CompiledScriptObjCode[m_ScriptObjCodeKey] = objCode;
  209. objCode.refCount = 0;
  210. }
  211. objCode.refCount++;
  212. // Now set up to decrement ref count on dispose.
  213. m_ObjCode = objCode;
  214. }
  215. try
  216. {
  217. // Fill in script instance from object code
  218. // Script instance is put in a "never-ever-has-run-before" state.
  219. LoadObjCode();
  220. // Fill in script intial state
  221. // - either as loaded from a .state file
  222. // - or initial default state_entry() event
  223. LoadInitialState();
  224. }
  225. catch
  226. {
  227. // If any error loading, decrement object code reference count.
  228. DecObjCodeRefCount();
  229. throw;
  230. }
  231. }
  232. private const string sixbit = "0123456789_abcdefghijklmnopqrstuvwxyz@ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  233. private static void ByteArrayToSixbitStr(StringBuilder sb, byte[] bytes)
  234. {
  235. int bit = 0;
  236. int val = 0;
  237. foreach(byte b in bytes)
  238. {
  239. val |= (int)((uint)b << bit);
  240. bit += 8;
  241. while(bit >= 6)
  242. {
  243. sb.Append(sixbit[val & 63]);
  244. val >>= 6;
  245. bit -= 6;
  246. }
  247. }
  248. if(bit > 0)
  249. sb.Append(sixbit[val & 63]);
  250. }
  251. // Try to create object code from source code
  252. // If error, just throw exception
  253. private ScriptObjCode TryToCompile()
  254. {
  255. m_CompilerErrors.Clear();
  256. // If object file exists, create ScriptObjCode directly from that.
  257. // Otherwise, compile the source to create object file then create
  258. // ScriptObjCode from that.
  259. string assetID = m_Item.AssetID.ToString();
  260. m_CameFrom = "asset://" + assetID;
  261. ScriptObjCode objCode = Compile();
  262. if(m_CompilerErrors.Count != 0)
  263. throw new Exception("compilation errors");
  264. if(objCode == null)
  265. throw new Exception("compilation failed");
  266. return objCode;
  267. }
  268. /*
  269. * Retrieve source from asset server.
  270. */
  271. private string FetchSource(string cameFrom)
  272. {
  273. m_log.Debug("[YEngine]: fetching source " + cameFrom);
  274. if(!cameFrom.StartsWith("asset://"))
  275. throw new Exception("unable to retrieve source from " + cameFrom);
  276. string assetID = cameFrom.Substring(8);
  277. AssetBase asset = m_Engine.World.AssetService.Get(assetID);
  278. if(asset == null)
  279. throw new Exception("source not found " + cameFrom);
  280. string source = Encoding.UTF8.GetString(asset.Data);
  281. if(EmptySource(source))
  282. throw new Exception("fetched source empty " + cameFrom);
  283. return source;
  284. }
  285. /*
  286. * Fill in script object initial contents.
  287. * Set the initial state to "default".
  288. */
  289. private void LoadObjCode()
  290. {
  291. // Script must leave this much stack remaining on calls to CheckRun().
  292. stackLimit = m_StackSize / 2;
  293. // This is how many total heap bytes script is allowed to use.
  294. heapLimit = m_HeapSize;
  295. // Allocate global variable arrays.
  296. glblVars.AllocVarArrays(m_ObjCode.glblSizes);
  297. // Script can handle these event codes.
  298. for(int i = m_ObjCode.scriptEventHandlerTable.GetLength(0); --i >= 0;)
  299. {
  300. for(int j = m_ObjCode.scriptEventHandlerTable.GetLength(1); --j >= 0;)
  301. {
  302. if(m_ObjCode.scriptEventHandlerTable[i, j] != null)
  303. {
  304. m_HaveEventHandlers[j] = true;
  305. }
  306. }
  307. }
  308. }
  309. /*
  310. * LoadInitialState()
  311. * if no state XML file exists for the asset,
  312. * post initial default state events
  313. * else
  314. * try to restore from .state file
  315. * If any error, throw exception
  316. */
  317. private void LoadInitialState()
  318. {
  319. // If no .state file exists, start from default state
  320. // Otherwise, read initial state from the .state file
  321. if(!File.Exists(m_StateFileName))
  322. {
  323. eventCode = ScriptEventCode.None; // not processing any event
  324. // default state_entry() must initialize global variables
  325. doGblInit = true;
  326. stateCode = 0;
  327. PostEvent(EventParams.StateEntryParams);
  328. }
  329. else
  330. {
  331. try
  332. {
  333. string xml;
  334. using (FileStream fs = File.Open(m_StateFileName,
  335. FileMode.Open,
  336. FileAccess.Read))
  337. {
  338. using(StreamReader ss = new StreamReader(fs))
  339. xml = ss.ReadToEnd();
  340. }
  341. XmlDocument doc = new XmlDocument();
  342. doc.LoadXml(xml);
  343. LoadScriptState(doc);
  344. }
  345. catch
  346. {
  347. File.Delete(m_StateFileName);
  348. eventCode = ScriptEventCode.None; // not processing any event
  349. // default state_entry() must initialize global variables
  350. glblVars.AllocVarArrays(m_ObjCode.glblSizes); // reset globals
  351. doGblInit = true;
  352. stateCode = 0;
  353. PostEvent(EventParams.StateEntryParams);
  354. }
  355. }
  356. // Post event(s) saying what caused the script to start.
  357. if(m_Running)
  358. {
  359. if(m_PostOnRez)
  360. {
  361. PostEvent(new EventParams("on_rez",
  362. new object[] { m_StartParam },
  363. zeroDetectParams));
  364. }
  365. switch(m_StateSource)
  366. {
  367. case StateSource.AttachedRez:
  368. PostEvent(new EventParams("attach",
  369. new object[] { m_Part.ParentGroup.AttachedAvatar.ToString() },
  370. zeroDetectParams));
  371. break;
  372. case StateSource.PrimCrossing:
  373. PostEvent(changedEvent_CR);
  374. break;
  375. case StateSource.Teleporting:
  376. PostEvent(changedEvent_CRT);
  377. break;
  378. case StateSource.RegionStart:
  379. PostEvent(changedEvent_CRS);
  380. break;
  381. }
  382. }
  383. }
  384. private static EventParams changedEvent_CR = new EventParams("changed", new object[] { CHANGED_REGION }, zeroDetectParams);
  385. private static EventParams changedEvent_CT = new EventParams("changed", new object[] { CHANGED_TELEPORT }, zeroDetectParams);
  386. private static EventParams changedEvent_CRT = new EventParams("changed", new object[] { CHANGED_REGION | CHANGED_TELEPORT }, zeroDetectParams);
  387. private static EventParams changedEvent_CRS = new EventParams("changed", new object[] { CHANGED_REGION_START }, zeroDetectParams);
  388. /**
  389. * @brief Save compilation error messages for later retrieval
  390. * via GetScriptErrors().
  391. */
  392. private void ErrorHandler(Token token, string message)
  393. {
  394. if(token != null)
  395. {
  396. string srcloc = token.SrcLoc;
  397. if(srcloc.StartsWith(m_CameFrom))
  398. srcloc = srcloc.Substring(m_CameFrom.Length);
  399. m_CompilerErrors.Add(srcloc + " Error: " + message);
  400. }
  401. else if(message != null)
  402. m_CompilerErrors.Add("(0,0) Error: " + message);
  403. else
  404. m_CompilerErrors.Add("(0,0) Error compiling, see exception in log");
  405. }
  406. /**
  407. * @brief Load script state from the given XML doc into the script memory
  408. * <ScriptState Engine="YEngine" Asset=...>
  409. * <Running>...</Running>
  410. * <DoGblInit>...</DoGblInit>
  411. * <Permissions granted=... mask=... />
  412. * RestoreDetectParams()
  413. * <Plugins>
  414. * ExtractXMLObjectArray("plugin")
  415. * </Plugins>
  416. * <Snapshot>
  417. * MigrateInEventHandler()
  418. * </Snapshot>
  419. * </ScriptState>
  420. */
  421. private void LoadScriptState(XmlDocument doc)
  422. {
  423. // Everything we know is enclosed in <ScriptState>...</ScriptState>
  424. XmlElement scriptStateN = (XmlElement)doc.SelectSingleNode("ScriptState");
  425. if(scriptStateN == null)
  426. throw new Exception("no <ScriptState> tag");
  427. XmlElement XvariablesN = null;
  428. string sen = scriptStateN.GetAttribute("Engine");
  429. if((sen == null) || (sen != m_Engine.ScriptEngineName))
  430. {
  431. XvariablesN = (XmlElement)scriptStateN.SelectSingleNode("Variables");
  432. if(XvariablesN == null)
  433. throw new Exception("<ScriptState> missing Engine=\"YEngine\" attribute");
  434. processXstate(doc);
  435. return;
  436. }
  437. // AssetID is unique for the script source text so make sure the
  438. // state file was written for that source file
  439. string assetID = scriptStateN.GetAttribute("Asset");
  440. if(assetID != m_Item.AssetID.ToString())
  441. throw new Exception("<ScriptState> assetID mismatch");
  442. // Also match the sourceHash in case script was
  443. // loaded via 'xmroption fetchsource' and has changed
  444. string sourceHash = scriptStateN.GetAttribute("SourceHash");
  445. if((sourceHash == null) || (sourceHash != m_ObjCode.sourceHash))
  446. throw new Exception("<ScriptState> SourceHash mismatch");
  447. // Get various attributes
  448. XmlElement runningN = (XmlElement)scriptStateN.SelectSingleNode("Running");
  449. m_Running &= bool.Parse(runningN.InnerText);
  450. XmlElement doGblInitN = (XmlElement)scriptStateN.SelectSingleNode("DoGblInit");
  451. doGblInit = bool.Parse(doGblInitN.InnerText);
  452. if (m_XMRLSLApi != null)
  453. {
  454. XmlElement scpttimeN = (XmlElement)scriptStateN.SelectSingleNode("scrpTime");
  455. if (scpttimeN != null && Double.TryParse(scpttimeN.InnerText, out double t))
  456. {
  457. m_XMRLSLApi.SetLSLTimer(Util.GetTimeStampMS() - t);
  458. }
  459. }
  460. double minEventDelay = 0.0;
  461. XmlElement minEventDelayN = (XmlElement)scriptStateN.SelectSingleNode("mEvtDly");
  462. if (minEventDelayN != null)
  463. minEventDelay = Double.Parse(minEventDelayN.InnerText);
  464. // get values used by stuff like llDetectedGrab, etc.
  465. DetectParams[] detParams = RestoreDetectParams(scriptStateN.SelectSingleNode("DetectArray"));
  466. // Restore queued events
  467. LinkedList<EventParams> eventQueue = RestoreEventQueue(scriptStateN.SelectSingleNode("EventQueue"));
  468. // Restore timers and listeners
  469. XmlElement pluginN = (XmlElement)scriptStateN.SelectSingleNode("Plugins");
  470. Object[] pluginData = ExtractXMLObjectArray(pluginN, "plugin");
  471. // Script's global variables and stack contents
  472. XmlElement snapshotN = (XmlElement)scriptStateN.SelectSingleNode("Snapshot");
  473. Byte[] data = Convert.FromBase64String(snapshotN.InnerText);
  474. using(MemoryStream ms = new MemoryStream())
  475. {
  476. ms.Write(data, 0, data.Length);
  477. ms.Seek(0, SeekOrigin.Begin);
  478. MigrateInEventHandler(ms);
  479. }
  480. XmlElement permissionsN = (XmlElement)scriptStateN.SelectSingleNode("Permissions");
  481. m_Item.PermsGranter = new UUID(permissionsN.GetAttribute("granter"));
  482. m_Item.PermsMask = Convert.ToInt32(permissionsN.GetAttribute("mask"));
  483. m_Part.Inventory.UpdateInventoryItem(m_Item, false, false);
  484. // Restore event queues, preserving any events that queued
  485. // whilst we were restoring the state
  486. lock (m_QueueLock)
  487. {
  488. m_DetectParams = detParams;
  489. foreach(EventParams evt in m_EventQueue)
  490. eventQueue.AddLast(evt);
  491. m_EventQueue = eventQueue;
  492. for(int i = m_EventCounts.Length; --i >= 0;)
  493. m_EventCounts[i] = 0;
  494. foreach(EventParams evt in m_EventQueue)
  495. {
  496. if(m_eventCodeMap.TryGetValue(evt.EventName, out ScriptEventCode eventCode))
  497. m_EventCounts[(int)eventCode]++;
  498. }
  499. }
  500. // Requeue timer and listeners (possibly queuing new events)
  501. AsyncCommandManager.CreateFromData(m_Engine,
  502. m_LocalID, m_ItemID, m_Part.UUID,
  503. pluginData);
  504. MinEventDelay = minEventDelay;
  505. }
  506. private void processXstate(XmlDocument doc)
  507. {
  508. XmlNodeList rootL = doc.GetElementsByTagName("ScriptState");
  509. if (rootL.Count != 1)
  510. throw new Exception("Xstate <ScriptState> missing");
  511. XmlNode rootNode = rootL[0];
  512. if (rootNode == null)
  513. throw new Exception("Xstate root missing");
  514. string stateName = "";
  515. bool running = false;
  516. UUID permsGranter = UUID.Zero;
  517. int permsMask = 0;
  518. double minEventDelay = 0.0;
  519. Object[] pluginData = new Object[0];
  520. LinkedList<EventParams> eventQueue = new LinkedList<EventParams>();
  521. Dictionary<string, int> intNames = new Dictionary<string, int>();
  522. Dictionary<string, int> doubleNames = new Dictionary<string, int>();
  523. Dictionary<string, int> stringNames = new Dictionary<string, int>();
  524. Dictionary<string, int> vectorNames = new Dictionary<string, int>();
  525. Dictionary<string, int> rotationNames = new Dictionary<string, int>();
  526. Dictionary<string, int> listNames = new Dictionary<string, int>();
  527. int[] ints = null;
  528. double[] doubles = null;
  529. string[] strings = null;
  530. LSL_Vector[] vectors = null;
  531. LSL_Rotation[] rotations = null;
  532. LSL_List[] lists = null;
  533. int nn = m_ObjCode.globalVarNames.Count;
  534. if (nn > 0)
  535. {
  536. Dictionary<int, string> tmpVars;
  537. if (m_ObjCode.globalVarNames.TryGetValue("iarIntegers", out tmpVars))
  538. {
  539. getvarNames(tmpVars, intNames);
  540. ints = new int[tmpVars.Count];
  541. }
  542. if (m_ObjCode.globalVarNames.TryGetValue("iarFloats", out tmpVars))
  543. {
  544. getvarNames(tmpVars, doubleNames);
  545. doubles = new double[tmpVars.Count];
  546. }
  547. if (m_ObjCode.globalVarNames.TryGetValue("iarVectors", out tmpVars))
  548. {
  549. getvarNames(tmpVars, vectorNames);
  550. vectors = new LSL_Vector[tmpVars.Count];
  551. }
  552. if (m_ObjCode.globalVarNames.TryGetValue("iarRotations", out tmpVars))
  553. {
  554. getvarNames(tmpVars, rotationNames);
  555. rotations = new LSL_Rotation[tmpVars.Count];
  556. }
  557. if (m_ObjCode.globalVarNames.TryGetValue("iarStrings", out tmpVars))
  558. {
  559. getvarNames(tmpVars, stringNames);
  560. strings = new string[tmpVars.Count];
  561. }
  562. if (m_ObjCode.globalVarNames.TryGetValue("iarLists", out tmpVars))
  563. {
  564. getvarNames(tmpVars, listNames);
  565. lists = new LSL_List[tmpVars.Count];
  566. }
  567. }
  568. int heapsz = 0;
  569. try
  570. {
  571. XmlNodeList partL = rootNode.ChildNodes;
  572. foreach (XmlNode part in partL)
  573. {
  574. switch (part.Name)
  575. {
  576. case "State":
  577. stateName = part.InnerText;
  578. break;
  579. case "Running":
  580. running = bool.Parse(part.InnerText);
  581. break;
  582. case "Variables":
  583. int indx;
  584. XmlNodeList varL = part.ChildNodes;
  585. foreach (XmlNode var in varL)
  586. {
  587. object o = ReadXTypedValue(var, out string varName);
  588. if (o is LSL_Integer lio)
  589. {
  590. if (intNames.TryGetValue(varName, out indx))
  591. ints[indx] = lio;
  592. continue;
  593. }
  594. if (o is LSL_Float lfo)
  595. {
  596. if (doubleNames.TryGetValue(varName, out indx))
  597. doubles[indx] = lfo;
  598. continue;
  599. }
  600. if (o is LSL_String lso)
  601. {
  602. if (stringNames.TryGetValue(varName, out indx))
  603. {
  604. strings[indx] = lso;
  605. heapsz += lso.Length;
  606. }
  607. continue;
  608. }
  609. if (o is LSL_Rotation lro)
  610. {
  611. if (rotationNames.TryGetValue(varName, out indx))
  612. rotations[indx] = lro;
  613. continue;
  614. }
  615. if (o is LSL_Vector lvo)
  616. {
  617. if (vectorNames.TryGetValue(varName, out indx))
  618. vectors[indx] = lvo;
  619. continue;
  620. }
  621. if (o is LSL_Key lko)
  622. {
  623. if (stringNames.TryGetValue(varName, out indx))
  624. {
  625. strings[indx] = lko;
  626. heapsz += lko.Length;
  627. }
  628. continue;
  629. }
  630. if (o is UUID uo)
  631. {
  632. if (stringNames.TryGetValue(varName, out indx))
  633. {
  634. LSL_String id = uo.ToString();
  635. strings[indx] = id;
  636. heapsz += id.Length;
  637. }
  638. continue;
  639. }
  640. if (o is LSL_List llo)
  641. {
  642. if (listNames.TryGetValue(varName, out indx))
  643. {
  644. lists[indx] = (llo);
  645. heapsz += llo.Size;
  646. }
  647. continue;
  648. }
  649. }
  650. break;
  651. case "Queue":
  652. XmlNodeList itemL = part.ChildNodes;
  653. foreach (XmlNode item in itemL)
  654. {
  655. List<Object> parms = new List<Object>();
  656. List<DetectParams> detected = new List<DetectParams>();
  657. string eventName = item.Attributes.GetNamedItem("event").Value;
  658. XmlNodeList eventL = item.ChildNodes;
  659. foreach (XmlNode evt in eventL)
  660. {
  661. switch (evt.Name)
  662. {
  663. case "Params":
  664. XmlNodeList prms = evt.ChildNodes;
  665. foreach (XmlNode pm in prms)
  666. parms.Add(ReadXTypedValue(pm));
  667. break;
  668. case "Detected":
  669. XmlNodeList detL = evt.ChildNodes;
  670. foreach (XmlNode det in detL)
  671. {
  672. string vect = det.Attributes.GetNamedItem("pos").Value;
  673. LSL_Vector v = new LSL_Vector(vect);
  674. int d_linkNum = 0;
  675. UUID d_group = UUID.Zero;
  676. string d_name = String.Empty;
  677. UUID d_owner = UUID.Zero;
  678. LSL_Vector d_position = new LSL_Vector();
  679. LSL_Rotation d_rotation = new LSL_Rotation();
  680. int d_type = 0;
  681. LSL_Vector d_velocity = new LSL_Vector();
  682. try
  683. {
  684. string tmp;
  685. tmp = det.Attributes.GetNamedItem("linkNum").Value;
  686. int.TryParse(tmp, out d_linkNum);
  687. tmp = det.Attributes.GetNamedItem("group").Value;
  688. UUID.TryParse(tmp, out d_group);
  689. d_name = det.Attributes.GetNamedItem("name").Value;
  690. tmp = det.Attributes.GetNamedItem("owner").Value;
  691. UUID.TryParse(tmp, out d_owner);
  692. tmp = det.Attributes.GetNamedItem("position").Value;
  693. d_position = new LSL_Types.Vector3(tmp);
  694. tmp = det.Attributes.GetNamedItem("rotation").Value;
  695. d_rotation = new LSL_Rotation(tmp);
  696. tmp = det.Attributes.GetNamedItem("type").Value;
  697. int.TryParse(tmp, out d_type);
  698. tmp = det.Attributes.GetNamedItem("velocity").Value;
  699. d_velocity = new LSL_Vector(tmp);
  700. }
  701. catch (Exception) // Old version XML
  702. {
  703. }
  704. UUID uuid = new UUID();
  705. UUID.TryParse(det.InnerText, out uuid);
  706. DetectParams d = new DetectParams();
  707. d.Key = uuid;
  708. d.OffsetPos = v;
  709. d.LinkNum = d_linkNum;
  710. d.Group = d_group;
  711. d.Name = d_name;
  712. d.Owner = d_owner;
  713. d.Position = d_position;
  714. d.Rotation = d_rotation;
  715. d.Type = d_type;
  716. d.Velocity = d_velocity;
  717. detected.Add(d);
  718. }
  719. break;
  720. }
  721. }
  722. EventParams ep = new EventParams(
  723. eventName, parms.ToArray(),
  724. detected.ToArray());
  725. eventQueue.AddLast(ep);
  726. }
  727. break;
  728. case "Plugins":
  729. List<Object> olist = new List<Object>();
  730. XmlNodeList itemLP = part.ChildNodes;
  731. foreach (XmlNode item in itemLP)
  732. olist.Add(ReadXTypedValue(item));
  733. pluginData = olist.ToArray();
  734. break;
  735. case "Permissions":
  736. string tmpPerm;
  737. int mask = 0;
  738. tmpPerm = part.Attributes.GetNamedItem("mask").Value;
  739. if (tmpPerm != null)
  740. {
  741. int.TryParse(tmpPerm, out mask);
  742. if (mask != 0)
  743. {
  744. tmpPerm = part.Attributes.GetNamedItem("granter").Value;
  745. if (tmpPerm != null)
  746. {
  747. UUID granter = new UUID();
  748. UUID.TryParse(tmpPerm, out granter);
  749. if (!granter.IsZero())
  750. {
  751. permsMask = mask;
  752. permsGranter = granter;
  753. }
  754. }
  755. }
  756. }
  757. break;
  758. case "MinEventDelay":
  759. double.TryParse(part.InnerText, out minEventDelay);
  760. break;
  761. }
  762. }
  763. }
  764. catch
  765. {
  766. throw new Exception("Xstate fail decode");
  767. }
  768. int k = 0;
  769. stateCode = 0;
  770. foreach (string sn in m_ObjCode.stateNames)
  771. {
  772. if (stateName == sn)
  773. {
  774. stateCode = k;
  775. break;
  776. }
  777. k++;
  778. }
  779. eventCode = ScriptEventCode.None;
  780. m_Running = running;
  781. doGblInit = false;
  782. m_Item.PermsGranter = permsGranter;
  783. m_Item.PermsMask = permsMask;
  784. m_Part.Inventory.UpdateInventoryItem(m_Item, false, false);
  785. lock (m_RunLock)
  786. {
  787. glblVars.iarIntegers = (ints != null) ? ints : XMRInstArrays.noIntegers;
  788. glblVars.iarFloats = (doubles != null) ? doubles : XMRInstArrays.noFloats;
  789. glblVars.iarStrings = (strings != null) ? strings : XMRInstArrays.noStrings;
  790. glblVars.iarVectors = (vectors != null) ? vectors : XMRInstArrays.noVectors;
  791. glblVars.iarRotations = (rotations != null) ? rotations : XMRInstArrays.noRotations;
  792. glblVars.iarLists = (lists != null) ? lists : XMRInstArrays.noLists;
  793. glblVars.iarChars = XMRInstArrays.noChars;
  794. glblVars.iarArrays = XMRInstArrays.noArrays;
  795. glblVars.iarObjects = XMRInstArrays.noObjects;
  796. glblVars.iarSDTClObjs = XMRInstArrays.noSDTClObjs;
  797. glblVars.iarSDTIntfObjs = XMRInstArrays.noSDTIntfObjs;
  798. }
  799. lock (m_QueueLock)
  800. {
  801. m_DetectParams = null;
  802. foreach (EventParams evt in m_EventQueue)
  803. eventQueue.AddLast(evt);
  804. m_EventQueue = eventQueue;
  805. for (int i = m_EventCounts.Length; --i >= 0;)
  806. m_EventCounts[i] = 0;
  807. foreach (EventParams evt in m_EventQueue)
  808. {
  809. if(m_eventCodeMap.TryGetValue(evt.EventName, out ScriptEventCode evtCode))
  810. m_EventCounts[(int)evtCode]++;
  811. }
  812. }
  813. AsyncCommandManager.CreateFromData(m_Engine,
  814. m_LocalID, m_ItemID, m_Part.UUID, pluginData);
  815. MinEventDelay = minEventDelay;
  816. }
  817. private static void getvarNames(Dictionary<int, string> s, Dictionary<string, int> d)
  818. {
  819. foreach(KeyValuePair<int, string> kvp in s)
  820. d[kvp.Value] = kvp.Key;
  821. }
  822. private static LSL_Types.list ReadXList(XmlNode parent)
  823. {
  824. List<Object> olist = new List<Object>();
  825. XmlNodeList itemL = parent.ChildNodes;
  826. foreach (XmlNode item in itemL)
  827. olist.Add(ReadXTypedValue(item));
  828. return new LSL_Types.list(olist.ToArray());
  829. }
  830. private static object ReadXTypedValue(XmlNode tag, out string name)
  831. {
  832. name = tag.Attributes.GetNamedItem("name").Value;
  833. return ReadXTypedValue(tag);
  834. }
  835. private static object ReadXTypedValue(XmlNode tag)
  836. {
  837. Object varValue;
  838. string assembly;
  839. string itemType = tag.Attributes.GetNamedItem("type").Value;
  840. if (itemType == "list")
  841. return ReadXList(tag);
  842. if (itemType == "OpenMetaverse.UUID")
  843. {
  844. UUID.TryParse(tag.InnerText, out UUID val);
  845. return val;
  846. }
  847. Type itemT = Type.GetType(itemType);
  848. if (itemT == null)
  849. {
  850. Object[] args =
  851. new Object[] { tag.InnerText };
  852. assembly = itemType + ", OpenSim.Region.ScriptEngine.Shared";
  853. itemT = Type.GetType(assembly);
  854. if (itemT == null)
  855. return null;
  856. varValue = Activator.CreateInstance(itemT, args);
  857. if (varValue == null)
  858. return null;
  859. }
  860. else
  861. {
  862. varValue = Convert.ChangeType(tag.InnerText, itemT);
  863. }
  864. return varValue;
  865. }
  866. /**
  867. * @brief Read llDetectedGrab, etc, values from XML
  868. * <EventQueue>
  869. * <DetectParams>...</DetectParams>
  870. * .
  871. * .
  872. * .
  873. * </EventQueue>
  874. */
  875. private LinkedList<EventParams> RestoreEventQueue(XmlNode eventsN)
  876. {
  877. LinkedList<EventParams> eventQueue = new LinkedList<EventParams>();
  878. if(eventsN != null)
  879. {
  880. XmlNodeList eventL = eventsN.SelectNodes("Event");
  881. foreach(XmlNode evnt in eventL)
  882. {
  883. string name = ((XmlElement)evnt).GetAttribute("Name");
  884. object[] parms = ExtractXMLObjectArray(evnt, "param");
  885. DetectParams[] detects = RestoreDetectParams(evnt);
  886. if(parms == null)
  887. parms = zeroObjectArray;
  888. if(detects == null)
  889. detects = zeroDetectParams;
  890. EventParams evt = new EventParams(name, parms, detects);
  891. eventQueue.AddLast(evt);
  892. }
  893. }
  894. return eventQueue;
  895. }
  896. /**
  897. * @brief Read llDetectedGrab, etc, values from XML
  898. * <DetectArray>
  899. * <DetectParams>...</DetectParams>
  900. * .
  901. * .
  902. * .
  903. * </DetectArray>
  904. */
  905. private DetectParams[] RestoreDetectParams(XmlNode detectedN)
  906. {
  907. if(detectedN == null)
  908. return null;
  909. List<DetectParams> detected = new List<DetectParams>();
  910. XmlNodeList detectL = detectedN.SelectNodes("DetectParams");
  911. DetectParams detprm = new DetectParams();
  912. foreach(XmlNode detxml in detectL)
  913. {
  914. try
  915. {
  916. detprm.Group = new UUID(detxml.Attributes.GetNamedItem("group").Value);
  917. detprm.Key = new UUID(detxml.Attributes.GetNamedItem("key").Value);
  918. detprm.Owner = new UUID(detxml.Attributes.GetNamedItem("owner").Value);
  919. detprm.LinkNum = Int32.Parse(detxml.Attributes.GetNamedItem("linkNum").Value);
  920. detprm.Type = Int32.Parse(detxml.Attributes.GetNamedItem("type").Value);
  921. detprm.Name = detxml.Attributes.GetNamedItem("name").Value;
  922. detprm.OffsetPos = new LSL_Types.Vector3(detxml.Attributes.GetNamedItem("pos").Value);
  923. detprm.Position = new LSL_Types.Vector3(detxml.Attributes.GetNamedItem("position").Value);
  924. detprm.Velocity = new LSL_Types.Vector3(detxml.Attributes.GetNamedItem("velocity").Value);
  925. detprm.Rotation = new LSL_Types.Quaternion(detxml.Attributes.GetNamedItem("rotation").Value);
  926. detected.Add(detprm);
  927. detprm = new DetectParams();
  928. }
  929. catch(Exception e)
  930. {
  931. m_log.Warn("[YEngine]: RestoreDetectParams bad XML: " + detxml.ToString());
  932. m_log.Warn("[YEngine]: ... " + e.ToString());
  933. }
  934. }
  935. return detected.ToArray();
  936. }
  937. /**
  938. * @brief Extract elements of an array of objects from an XML parent.
  939. * Each element is of form <tag ...>...</tag>
  940. * @param parent = XML parent to extract them from
  941. * @param tag = what the value's tag is
  942. * @returns object array of the values
  943. */
  944. private static object[] ExtractXMLObjectArray(XmlNode parent, string tag)
  945. {
  946. List<Object> olist = new List<Object>();
  947. XmlNodeList itemL = parent.SelectNodes(tag);
  948. foreach(XmlNode item in itemL)
  949. {
  950. olist.Add(ExtractXMLObjectValue(item));
  951. }
  952. return olist.ToArray();
  953. }
  954. private static object ExtractXMLObjectValue(XmlNode item)
  955. {
  956. string itemType = item.Attributes.GetNamedItem("type").Value;
  957. if(itemType == "list")
  958. {
  959. return new LSL_List(ExtractXMLObjectArray(item, "item"));
  960. }
  961. if(itemType == "OpenMetaverse.UUID")
  962. {
  963. UUID val = new UUID();
  964. UUID.TryParse(item.InnerText, out val);
  965. return val;
  966. }
  967. Type itemT = Type.GetType(itemType);
  968. if(itemT == null)
  969. {
  970. Object[] args = new Object[] { item.InnerText };
  971. string assembly = itemType + ", OpenSim.Region.ScriptEngine.Shared";
  972. itemT = Type.GetType(assembly);
  973. if(itemT == null)
  974. {
  975. return null;
  976. }
  977. return Activator.CreateInstance(itemT, args);
  978. }
  979. return Convert.ChangeType(item.InnerText, itemT);
  980. }
  981. /*
  982. * Migrate an event handler in from a stream.
  983. *
  984. * Input:
  985. * stream = as generated by MigrateOutEventHandler()
  986. */
  987. private void MigrateInEventHandler(Stream stream)
  988. {
  989. int mv = stream.ReadByte();
  990. if(mv != migrationVersion)
  991. throw new Exception("incoming migration version " + mv + " but accept only " + migrationVersion);
  992. stream.ReadByte(); // ignored
  993. /*
  994. * Restore script variables and stack and other state from stream.
  995. * And it also marks us busy (by setting this.eventCode) so we can't be
  996. * started again and this event lost. If it restores this.eventCode =
  997. * None, the the script was idle.
  998. */
  999. lock(m_RunLock)
  1000. {
  1001. BinaryReader br = new BinaryReader(stream);
  1002. this.MigrateIn(br);
  1003. //m_RunOnePhase = "MigrateInEventHandler finished";
  1004. //CheckRunLockInvariants(true);
  1005. }
  1006. }
  1007. }
  1008. }