XMRInstCtor.cs 47 KB

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