1
0

XMRInstRun.cs 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  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.Collections.Generic;
  30. using System.Text;
  31. using OpenMetaverse;
  32. using OpenSim.Framework;
  33. using OpenSim.Region.Framework.Interfaces;
  34. using OpenSim.Region.ScriptEngine.Shared;
  35. using OpenSim.Region.ScriptEngine.Shared.Api;
  36. using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
  37. using OpenSim.Region.Framework.Scenes;
  38. using log4net;
  39. using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
  40. using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
  41. using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
  42. using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
  43. using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
  44. using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
  45. using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
  46. namespace OpenSim.Region.ScriptEngine.Yengine
  47. {
  48. public partial class XMRInstance
  49. {
  50. /************************************************************************************\
  51. * This module contains these externally useful methods: *
  52. * PostEvent() - queues an event to script and wakes script thread to process it *
  53. * RunOne() - runs script for a time slice or until it volunteers to give up cpu *
  54. * CallSEH() - runs in the microthread to call the event handler *
  55. \************************************************************************************/
  56. /**
  57. * @brief This can be called in any thread (including the script thread itself)
  58. * to queue event to script for processing.
  59. */
  60. public void PostEvent(EventParams evt)
  61. {
  62. if(!m_eventCodeMap.TryGetValue(evt.EventName, out ScriptEventCode evc))
  63. return;
  64. // Put event on end of event queue.
  65. bool startIt = false;
  66. bool wakeIt = false;
  67. lock(m_QueueLock)
  68. {
  69. bool construct = (m_IState == XMRInstState.CONSTRUCT);
  70. // Ignore event if we don't even have such an handler in any state.
  71. // We can't be state-specific here because state might be different
  72. // by the time this event is dequeued and delivered to the script.
  73. if(!construct && // make sure m_HaveEventHandlers is filled in
  74. ((uint)evc < (uint)m_HaveEventHandlers.Length) &&
  75. !m_HaveEventHandlers[(int)evc]) // don't bother if we don't have such a handler in any state
  76. return;
  77. // Not running means we ignore any incoming events.
  78. // But queue if still constructing because m_Running is not yet valid.
  79. if(!m_Running && !construct)
  80. {
  81. if(m_IState == XMRInstState.SUSPENDED)
  82. {
  83. if(evc == ScriptEventCode.state_entry && m_EventQueue.Count == 0)
  84. {
  85. LinkedListNode<EventParams> llns = new LinkedListNode<EventParams>(evt);
  86. m_EventQueue.AddFirst(llns);
  87. }
  88. }
  89. return;
  90. }
  91. if(m_minEventDelay != 0)
  92. {
  93. switch (evc)
  94. {
  95. // ignore some events by time set by llMinEventDelay
  96. case ScriptEventCode.collision:
  97. case ScriptEventCode.land_collision:
  98. case ScriptEventCode.listen:
  99. case ScriptEventCode.not_at_target:
  100. case ScriptEventCode.not_at_rot_target:
  101. case ScriptEventCode.no_sensor:
  102. case ScriptEventCode.sensor:
  103. case ScriptEventCode.timer:
  104. case ScriptEventCode.touch:
  105. {
  106. double now = Util.GetTimeStamp();
  107. if (now < m_nextEventTime)
  108. return;
  109. m_nextEventTime = now + m_minEventDelay;
  110. break;
  111. }
  112. case ScriptEventCode.changed:
  113. {
  114. const int canignore = ~(CHANGED_SCALE | CHANGED_POSITION);
  115. int change = (int)evt.Params[0];
  116. if(change == 0) // what?
  117. return;
  118. if((change & canignore) == 0)
  119. {
  120. double now = Util.GetTimeStamp();
  121. if (now < m_nextEventTime)
  122. return;
  123. m_nextEventTime = now + m_minEventDelay;
  124. }
  125. break;
  126. }
  127. default:
  128. break;
  129. }
  130. }
  131. // Only so many of each event type allowed to queue.
  132. if((uint)evc < (uint)m_EventCounts.Length)
  133. {
  134. if(evc == ScriptEventCode.timer)
  135. {
  136. if(m_EventCounts[(int)evc] >= 1)
  137. return;
  138. }
  139. else if(m_EventCounts[(int)evc] >= MAXEVENTQUEUE)
  140. return;
  141. m_EventCounts[(int)evc]++;
  142. }
  143. // Put event on end of instance's event queue.
  144. LinkedListNode<EventParams> lln = new LinkedListNode<EventParams>(evt);
  145. switch(evc)
  146. {
  147. // These need to go first. The only time we manually
  148. // queue them is for the default state_entry() and we
  149. // need to make sure they go before any attach() events
  150. // so the heapLimit value gets properly initialized.
  151. case ScriptEventCode.state_entry:
  152. m_EventQueue.AddFirst(lln);
  153. break;
  154. // The attach event sneaks to the front of the queue.
  155. // This is needed for quantum limiting to work because
  156. // we want the attach(NULL_KEY) event to come in front
  157. // of all others so the m_DetachQuantum won't run out
  158. // before attach(NULL_KEY) is executed.
  159. case ScriptEventCode.attach:
  160. if(evt.Params[0].ToString() == UUID.Zero.ToString())
  161. {
  162. LinkedListNode<EventParams> lln2 = null;
  163. for(lln2 = m_EventQueue.First; lln2 != null; lln2 = lln2.Next)
  164. {
  165. EventParams evt2 = lln2.Value;
  166. m_eventCodeMap.TryGetValue(evt2.EventName, out ScriptEventCode evc2);
  167. if((evc2 != ScriptEventCode.state_entry) && (evc2 != ScriptEventCode.attach))
  168. break;
  169. }
  170. if(lln2 == null)
  171. m_EventQueue.AddLast(lln);
  172. else
  173. m_EventQueue.AddBefore(lln2, lln);
  174. // If we're detaching, limit the qantum. This will also
  175. // cause the script to self-suspend after running this
  176. // event
  177. m_DetachReady.Reset();
  178. m_DetachQuantum = 100;
  179. }
  180. else
  181. m_EventQueue.AddLast(lln);
  182. break;
  183. // All others just go on end in the order queued.
  184. default:
  185. m_EventQueue.AddLast(lln);
  186. break;
  187. }
  188. // If instance is idle (ie, not running or waiting to run),
  189. // flag it to be on m_StartQueue as we are about to do so.
  190. // Flag it now before unlocking so another thread won't try
  191. // to do the same thing right now.
  192. // Dont' flag it if it's still suspended!
  193. if((m_IState == XMRInstState.IDLE) && !m_Suspended)
  194. {
  195. m_IState = XMRInstState.ONSTARTQ;
  196. startIt = true;
  197. }
  198. // If instance is sleeping (ie, possibly in xmrEventDequeue),
  199. // wake it up if event is in the mask.
  200. if((m_SleepUntil > DateTime.UtcNow) && !m_Suspended)
  201. {
  202. int evc1 = (int)evc;
  203. int evc2 = evc1 - 32;
  204. if((((uint)evc1 < (uint)32) && (((m_SleepEventMask1 >> evc1) & 1) != 0)) ||
  205. (((uint)evc2 < (uint)32) && (((m_SleepEventMask2 >> evc2) & 1) != 0)))
  206. wakeIt = true;
  207. }
  208. }
  209. // If transitioned from IDLE->ONSTARTQ, actually go insert it
  210. // on m_StartQueue and give the RunScriptThread() a wake-up.
  211. if(startIt)
  212. m_Engine.QueueToStart(this);
  213. // Likewise, if the event mask triggered a wake, wake it up.
  214. if(wakeIt)
  215. {
  216. m_SleepUntil = DateTime.MinValue;
  217. m_Engine.WakeFromSleep(this);
  218. }
  219. }
  220. public void CancelEvent(string eventName)
  221. {
  222. if (!m_eventCodeMap.TryGetValue(eventName, out ScriptEventCode evc))
  223. return;
  224. lock (m_QueueLock)
  225. {
  226. if(m_EventQueue.Count == 0)
  227. return;
  228. LinkedListNode<EventParams> lln2 = null;
  229. for (lln2 = m_EventQueue.First; lln2 != null; lln2 = lln2.Next)
  230. {
  231. EventParams evt2 = lln2.Value;
  232. if(evt2.EventName.Equals(eventName))
  233. {
  234. m_EventQueue.Remove(lln2);
  235. if (evc >= 0 && m_EventCounts[(int)evc] > 0)
  236. m_EventCounts[(int)evc]--;
  237. }
  238. }
  239. }
  240. }
  241. // This is called in the script thread to step script until it calls
  242. // CheckRun(). It returns what the instance's next state should be,
  243. // ONSLEEPQ, ONYIELDQ, SUSPENDED or FINISHED.
  244. public XMRInstState RunOne()
  245. {
  246. DateTime now = DateTime.UtcNow;
  247. m_SliceStart = Util.GetTimeStampMS();
  248. // If script has called llSleep(), don't do any more until time is up.
  249. m_RunOnePhase = "check m_SleepUntil";
  250. if(m_SleepUntil > now)
  251. {
  252. m_RunOnePhase = "return is sleeping";
  253. return XMRInstState.ONSLEEPQ;
  254. }
  255. // Also, someone may have called Suspend().
  256. m_RunOnePhase = "check m_SuspendCount";
  257. if(m_SuspendCount > 0)
  258. {
  259. m_RunOnePhase = "return is suspended";
  260. return XMRInstState.SUSPENDED;
  261. }
  262. // Make sure we aren't being migrated in or out and prevent that
  263. // whilst we are in here. If migration has it locked, don't call
  264. // back right away, delay a bit so we don't get in infinite loop.
  265. m_RunOnePhase = "lock m_RunLock";
  266. if(!Monitor.TryEnter(m_RunLock))
  267. {
  268. m_SleepUntil = now.AddMilliseconds(15);
  269. m_RunOnePhase = "return was locked";
  270. return XMRInstState.ONSLEEPQ;
  271. }
  272. try
  273. {
  274. m_RunOnePhase = "check entry invariants";
  275. CheckRunLockInvariants(true);
  276. Exception e = null;
  277. // Maybe it has been Disposed()
  278. if(m_Part == null || m_Part.Inventory == null)
  279. {
  280. m_RunOnePhase = "runone saw it disposed";
  281. return XMRInstState.DISPOSED;
  282. }
  283. if(!m_Running)
  284. {
  285. m_RunOnePhase = "return is not running";
  286. return XMRInstState.SUSPENDED;
  287. }
  288. // Do some more of the last event if it didn't finish.
  289. if(this.eventCode != ScriptEventCode.None)
  290. {
  291. lock(m_QueueLock)
  292. {
  293. if(m_DetachQuantum > 0 && --m_DetachQuantum == 0)
  294. {
  295. m_Suspended = true;
  296. m_DetachReady.Set();
  297. m_RunOnePhase = "detach quantum went zero";
  298. CheckRunLockInvariants(true);
  299. return XMRInstState.FINISHED;
  300. }
  301. }
  302. m_RunOnePhase = "resume old event handler";
  303. m_LastRanAt = now;
  304. m_InstEHSlice++;
  305. callMode = CallMode_NORMAL;
  306. e = ResumeEx();
  307. }
  308. // Otherwise, maybe we can dequeue a new event and start
  309. // processing it.
  310. else
  311. {
  312. m_RunOnePhase = "lock event queue";
  313. EventParams evt = null;
  314. ScriptEventCode evc = ScriptEventCode.None;
  315. lock(m_QueueLock)
  316. {
  317. // We can't get here unless the script has been resumed
  318. // after creation, then suspended again, and then had
  319. // an event posted to it. We just pretend there is no
  320. // event int he queue and let the normal mechanics
  321. // carry out the suspension. A Resume will handle the
  322. // restarting gracefully. This is taking the easy way
  323. // out and may be improved in the future.
  324. if(m_Suspended)
  325. {
  326. m_RunOnePhase = "m_Suspended is set";
  327. CheckRunLockInvariants(true);
  328. return XMRInstState.FINISHED;
  329. }
  330. m_RunOnePhase = "dequeue event";
  331. if(m_EventQueue.First != null)
  332. {
  333. evt = m_EventQueue.First.Value;
  334. m_eventCodeMap.TryGetValue(evt.EventName, out evc);
  335. if (m_DetachQuantum > 0)
  336. {
  337. if(evc != ScriptEventCode.attach)
  338. {
  339. // This is the case where the attach event
  340. // has completed and another event is queued
  341. // Stop it from running and suspend
  342. m_Suspended = true;
  343. m_DetachReady.Set();
  344. m_DetachQuantum = 0;
  345. m_RunOnePhase = "nothing to do #3";
  346. CheckRunLockInvariants(true);
  347. return XMRInstState.FINISHED;
  348. }
  349. }
  350. m_EventQueue.RemoveFirst();
  351. if(evc >= 0)
  352. m_EventCounts[(int)evc]--;
  353. }
  354. // If there is no event to dequeue, don't run this script
  355. // until another event gets queued.
  356. if(evt == null)
  357. {
  358. if(m_DetachQuantum > 0)
  359. {
  360. // This will happen if the attach event has run
  361. // and exited with time slice left.
  362. m_Suspended = true;
  363. m_DetachReady.Set();
  364. m_DetachQuantum = 0;
  365. }
  366. m_RunOnePhase = "nothing to do #4";
  367. CheckRunLockInvariants(true);
  368. return XMRInstState.FINISHED;
  369. }
  370. }
  371. // Dequeued an event, so start it going until it either
  372. // finishes or it calls CheckRun().
  373. m_RunOnePhase = "start event handler";
  374. m_DetectParams = evt.DetectParams;
  375. m_LastRanAt = now;
  376. m_InstEHEvent++;
  377. e = StartEventHandler(evc, evt.Params);
  378. }
  379. m_RunOnePhase = "done running";
  380. m_CPUTime += DateTime.UtcNow.Subtract(now).TotalMilliseconds;
  381. // Maybe it puqued.
  382. if(e != null)
  383. {
  384. m_RunOnePhase = "handling exception " + e.Message;
  385. HandleScriptException(e);
  386. m_RunOnePhase = "return had exception " + e.Message;
  387. CheckRunLockInvariants(true);
  388. return XMRInstState.FINISHED;
  389. }
  390. // If event handler completed, get rid of detect params.
  391. if(this.eventCode == ScriptEventCode.None)
  392. m_DetectParams = null;
  393. }
  394. finally
  395. {
  396. m_RunOnePhase += "; checking exit invariants and unlocking";
  397. CheckRunLockInvariants(false);
  398. Monitor.Exit(m_RunLock);
  399. }
  400. // Cycle script through the yield queue and call it back asap.
  401. m_RunOnePhase = "last return";
  402. return XMRInstState.ONYIELDQ;
  403. }
  404. /**
  405. * @brief Immediately after taking m_RunLock or just before releasing it, check invariants.
  406. */
  407. private ScriptEventCode lastEventCode = ScriptEventCode.None;
  408. private bool lastActive = false;
  409. private string lastRunPhase = "";
  410. public void CheckRunLockInvariants(bool throwIt)
  411. {
  412. // If not executing any event handler, there shouldn't be any saved stack frames.
  413. // If executing an event handler, there should be some saved stack frames.
  414. bool active = (stackFrames != null);
  415. ScriptEventCode ec = this.eventCode;
  416. if(((ec == ScriptEventCode.None) && active) ||
  417. ((ec != ScriptEventCode.None) && !active))
  418. {
  419. m_log.Error("CheckRunLockInvariants: script=" + m_DescName);
  420. m_log.Error("CheckRunLockInvariants: eventcode=" + ec.ToString() + ", active=" + active.ToString());
  421. m_log.Error("CheckRunLockInvariants: m_RunOnePhase=" + m_RunOnePhase);
  422. m_log.Error("CheckRunLockInvariants: lastec=" + lastEventCode + ", lastAct=" + lastActive + ", lastPhase=" + lastRunPhase);
  423. if(throwIt)
  424. throw new Exception("CheckRunLockInvariants: eventcode=" + ec.ToString() + ", active=" + active.ToString());
  425. }
  426. lastEventCode = ec;
  427. lastActive = active;
  428. lastRunPhase = m_RunOnePhase;
  429. }
  430. /*
  431. * Start event handler.
  432. *
  433. * Input:
  434. * newEventCode = code of event to be processed
  435. * newEhArgs = arguments for the event handler
  436. *
  437. * Caution:
  438. * It is up to the caller to make sure ehArgs[] is correct for
  439. * the particular event handler being called. The first thing
  440. * a script event handler method does is to unmarshall the args
  441. * from ehArgs[] and will throw an array bounds or cast exception
  442. * if it can't.
  443. */
  444. private Exception StartEventHandler(ScriptEventCode newEventCode, object[] newEhArgs)
  445. {
  446. // We use this.eventCode == ScriptEventCode.None to indicate we are idle.
  447. // So trying to execute ScriptEventCode.None might make a mess.
  448. if(newEventCode == ScriptEventCode.None)
  449. return new Exception("Can't process ScriptEventCode.None");
  450. // Silly to even try if there is no handler defined for this event.
  451. if(((int)newEventCode >= 0) && (m_ObjCode.scriptEventHandlerTable[this.stateCode, (int)newEventCode] == null))
  452. return null;
  453. // The microthread shouldn't be processing any event code.
  454. // These are assert checks so we throw them directly as exceptions.
  455. if(this.eventCode != ScriptEventCode.None)
  456. throw new Exception("still processing event " + this.eventCode.ToString());
  457. // Save eventCode so we know what event handler to run in the microthread.
  458. // And it also marks us busy so we can't be started again and this event lost.
  459. this.eventCode = newEventCode;
  460. this.ehArgs = newEhArgs;
  461. // This calls ScriptUThread.Main() directly, and returns when Main() [indirectly]
  462. // calls Suspend() or when Main() returns, whichever occurs first.
  463. // Setting stackFrames = null means run the event handler from the beginning
  464. // without doing any stack frame restores first.
  465. this.stackFrames = null;
  466. return StartEx();
  467. }
  468. /**
  469. * @brief There was an exception whilst starting/running a script event handler.
  470. * Maybe we handle it directly or just print an error message.
  471. */
  472. private void HandleScriptException(Exception e)
  473. {
  474. // The script threw some kind of exception that was not caught at
  475. // script level, so the script is no longer running an event handler.
  476. ScriptEventCode curevent = eventCode;
  477. eventCode = ScriptEventCode.None;
  478. stackFrames = null;
  479. if(m_Part == null || m_Part.Inventory == null)
  480. {
  481. //we are gone and don't know it still
  482. m_SleepUntil = DateTime.MaxValue;
  483. return;
  484. }
  485. if (e is ScriptDeleteException)
  486. {
  487. // Script did something like llRemoveInventory(llGetScriptName());
  488. // ... to delete itself from the object.
  489. m_SleepUntil = DateTime.MaxValue;
  490. Verbose("[YEngine]: script self-delete {0}", m_ItemID);
  491. m_Part.Inventory.RemoveInventoryItem(m_ItemID);
  492. }
  493. else if(e is ScriptDieException)
  494. {
  495. // Script did an llDie()
  496. m_RunOnePhase = "dying...";
  497. m_SleepUntil = DateTime.MaxValue;
  498. m_Engine.World.DeleteSceneObject(m_Part.ParentGroup, false);
  499. }
  500. else if (e is ScriptResetException)
  501. {
  502. // Script did an llResetScript().
  503. m_RunOnePhase = "resetting...";
  504. ResetLocked("HandleScriptResetException");
  505. }
  506. else if (e is ScriptException)
  507. {
  508. // Some general script error.
  509. SendScriptErrorMessage(e, curevent);
  510. }
  511. else
  512. {
  513. // Some general script error.
  514. SendErrorMessage(e);
  515. }
  516. }
  517. private void SendScriptErrorMessage(Exception e, ScriptEventCode ev)
  518. {
  519. StringBuilder msg = new StringBuilder();
  520. bool toowner = false;
  521. msg.Append("YEngine: ");
  522. if (e.Message != null)
  523. {
  524. string text = e.Message;
  525. if (text.StartsWith("(OWNER)"))
  526. {
  527. text = text.Substring(7);
  528. toowner = true;
  529. }
  530. msg.Append(text);
  531. }
  532. msg.Append(" (script: ");
  533. msg.Append(m_Item.Name);
  534. msg.Append(" event: ");
  535. msg.Append(ev.ToString());
  536. msg.Append(" primID: ");
  537. msg.Append(m_Part.UUID.ToString());
  538. msg.Append(" at: <");
  539. Vector3 pos = m_Part.AbsolutePosition;
  540. msg.Append((int)Math.Floor(pos.X));
  541. msg.Append(',');
  542. msg.Append((int)Math.Floor(pos.Y));
  543. msg.Append(',');
  544. msg.Append((int)Math.Floor(pos.Z));
  545. msg.Append(">) Script must be Reset to re-enable.\n");
  546. string msgst = msg.ToString();
  547. if (msgst.Length > 1000)
  548. msgst = msgst.Substring(0, 1000);
  549. if (toowner)
  550. {
  551. ScenePresence sp = m_Engine.World.GetScenePresence(m_Part.OwnerID);
  552. if (sp != null && !sp.IsNPC)
  553. m_Engine.World.SimChatToAgent(m_Part.OwnerID, Utils.StringToBytes(msgst), 0x7FFFFFFF, m_Part.AbsolutePosition,
  554. m_Part.Name, m_Part.UUID, false);
  555. }
  556. else
  557. m_Engine.World.SimChat(Utils.StringToBytes(msgst),
  558. ChatTypeEnum.DebugChannel, 0x7FFFFFFF,
  559. m_Part.AbsolutePosition,
  560. m_Part.Name, m_Part.UUID, false);
  561. m_log.Debug(string.Format(
  562. "[SCRIPT ERROR]: {0} (at event {1}, part {2} {3} at {4} in {5}",
  563. (e.Message == null)? "" : e.Message,
  564. ev.ToString(),
  565. m_Part.Name,
  566. m_Part.UUID,
  567. m_Part.AbsolutePosition,
  568. m_Part.ParentGroup.Scene.Name));
  569. m_SleepUntil = DateTime.MaxValue;
  570. }
  571. /**
  572. * @brief There was an exception running script event handler.
  573. * Display error message and disable script (in a way
  574. * that the script can be reset to be restarted).
  575. */
  576. private void SendErrorMessage(Exception e)
  577. {
  578. StringBuilder msg = new StringBuilder();
  579. msg.Append("[YEngine]: Exception while running ");
  580. msg.Append(m_ItemID);
  581. msg.Append('\n');
  582. // Add exception message.
  583. string des = e.Message;
  584. des = (des == null) ? "" : (": " + des);
  585. msg.Append(e.GetType().Name + des + "\n");
  586. // Tell script owner what to do.
  587. msg.Append("Prim: <");
  588. msg.Append(m_Part.Name);
  589. msg.Append(">, Script: <");
  590. msg.Append(m_Item.Name);
  591. msg.Append(">, Location: ");
  592. msg.Append(m_Engine.World.RegionInfo.RegionName);
  593. msg.Append(" <");
  594. Vector3 pos = m_Part.AbsolutePosition;
  595. msg.Append((int)Math.Floor(pos.X));
  596. msg.Append(',');
  597. msg.Append((int)Math.Floor(pos.Y));
  598. msg.Append(',');
  599. msg.Append((int)Math.Floor(pos.Z));
  600. msg.Append(">\nScript must be Reset to re-enable.\n");
  601. // Display full exception message in log.
  602. m_log.Info(msg.ToString() + XMRExceptionStackString(e), e);
  603. // Give script owner the stack dump.
  604. msg.Append(XMRExceptionStackString(e));
  605. // Send error message to owner.
  606. // Suppress internal code stack trace lines.
  607. string msgst = msg.ToString();
  608. if(!msgst.EndsWith("\n"))
  609. msgst += '\n';
  610. int j = 0;
  611. StringBuilder imstr = new StringBuilder();
  612. for(int i = 0; (i = msgst.IndexOf('\n', i)) >= 0; j = ++i)
  613. {
  614. string line = msgst.Substring(j, i - j);
  615. if(line.StartsWith("at "))
  616. {
  617. if(line.StartsWith("at (wrapper"))
  618. continue; // at (wrapper ...
  619. int k = line.LastIndexOf(".cs:"); // ... .cs:linenumber
  620. if(Int32.TryParse(line.Substring(k + 4), out k))
  621. continue;
  622. }
  623. this.llOwnerSay(line);
  624. }
  625. // Say script is sleeping for a very long time.
  626. // Reset() is able to cancel this sleeping.
  627. m_SleepUntil = DateTime.MaxValue;
  628. }
  629. /**
  630. * @brief The user clicked the Reset Script button.
  631. * We want to reset the script to a never-has-ever-run-before state.
  632. */
  633. public void Reset()
  634. {
  635. checkstate:
  636. XMRInstState iState = m_IState;
  637. switch(iState)
  638. {
  639. // If it's really being constructed now, that's about as reset as we get.
  640. case XMRInstState.CONSTRUCT:
  641. return;
  642. // If it's idle, that means it is ready to receive a new event.
  643. // So we lock the event queue to prevent another thread from taking
  644. // it out of idle, verify that it is still in idle then transition
  645. // it to resetting so no other thread will touch it.
  646. case XMRInstState.IDLE:
  647. lock(m_QueueLock)
  648. {
  649. if(m_IState == XMRInstState.IDLE)
  650. {
  651. m_IState = XMRInstState.RESETTING;
  652. break;
  653. }
  654. }
  655. goto checkstate;
  656. // If it's on the start queue, that means it is about to dequeue an
  657. // event and start processing it. So we lock the start queue so it
  658. // can't be started and transition it to resetting so no other thread
  659. // will touch it.
  660. case XMRInstState.ONSTARTQ:
  661. lock(m_Engine.m_StartQueue)
  662. {
  663. if(m_IState == XMRInstState.ONSTARTQ)
  664. {
  665. m_Engine.m_StartQueue.Remove(this);
  666. m_IState = XMRInstState.RESETTING;
  667. break;
  668. }
  669. }
  670. goto checkstate;
  671. // If it's running, tell CheckRun() to suspend the thread then go back
  672. // to see what it got transitioned to.
  673. case XMRInstState.RUNNING:
  674. suspendOnCheckRunHold = true;
  675. lock(m_QueueLock)
  676. {
  677. }
  678. goto checkstate;
  679. // If it's sleeping, remove it from sleep queue and transition it to
  680. // resetting so no other thread will touch it.
  681. case XMRInstState.ONSLEEPQ:
  682. lock(m_Engine.m_SleepQueue)
  683. {
  684. if(m_IState == XMRInstState.ONSLEEPQ)
  685. {
  686. m_Engine.m_SleepQueue.Remove(this);
  687. m_IState = XMRInstState.RESETTING;
  688. break;
  689. }
  690. }
  691. goto checkstate;
  692. // It was just removed from the sleep queue and is about to be put
  693. // on the yield queue (ie, is being woken up).
  694. // Let that thread complete transition and try again.
  695. case XMRInstState.REMDFROMSLPQ:
  696. Sleep(10);
  697. goto checkstate;
  698. // If it's yielding, remove it from yield queue and transition it to
  699. // resetting so no other thread will touch it.
  700. case XMRInstState.ONYIELDQ:
  701. lock(m_Engine.m_YieldQueue)
  702. {
  703. if(m_IState == XMRInstState.ONYIELDQ)
  704. {
  705. m_Engine.m_YieldQueue.Remove(this);
  706. m_IState = XMRInstState.RESETTING;
  707. break;
  708. }
  709. }
  710. goto checkstate;
  711. // If it just finished running something, let that thread transition it
  712. // to its next state then check again.
  713. case XMRInstState.FINISHED:
  714. Sleep(10);
  715. goto checkstate;
  716. // If it's disposed, that's about as reset as it gets.
  717. case XMRInstState.DISPOSED:
  718. return;
  719. // Some other thread is already resetting it, let it finish.
  720. case XMRInstState.RESETTING:
  721. return;
  722. case XMRInstState.SUSPENDED:
  723. break;
  724. default:
  725. throw new Exception("bad state");
  726. }
  727. // This thread transitioned the instance to RESETTING so reset it.
  728. lock(m_RunLock)
  729. {
  730. CheckRunLockInvariants(true);
  731. // No other thread should have transitioned it from RESETTING.
  732. if (m_IState != XMRInstState.SUSPENDED)
  733. {
  734. if (m_IState != XMRInstState.RESETTING)
  735. throw new Exception("bad state");
  736. m_IState = XMRInstState.IDLE;
  737. }
  738. // Reset everything and queue up default's start_entry() event.
  739. ClearQueue();
  740. ResetLocked("external Reset");
  741. // Mark it idle now so it can get queued to process new stuff.
  742. CheckRunLockInvariants(true);
  743. }
  744. }
  745. private void ClearQueueExceptLinkMessages()
  746. {
  747. lock(m_QueueLock)
  748. {
  749. EventParams[] linkMessages = new EventParams[m_EventQueue.Count];
  750. int n = 0;
  751. foreach(EventParams evt2 in m_EventQueue)
  752. {
  753. if(evt2.EventName == "link_message")
  754. linkMessages[n++] = evt2;
  755. }
  756. m_EventQueue.Clear();
  757. for(int i = m_EventCounts.Length; --i >= 0;)
  758. m_EventCounts[i] = 0;
  759. for(int i = 0; i < n; i++)
  760. m_EventQueue.AddLast(linkMessages[i]);
  761. m_EventCounts[(int)ScriptEventCode.link_message] = n;
  762. }
  763. }
  764. private void ClearQueue()
  765. {
  766. lock(m_QueueLock)
  767. {
  768. m_EventQueue.Clear(); // no events queued
  769. for(int i = m_EventCounts.Length; --i >= 0;)
  770. m_EventCounts[i] = 0;
  771. }
  772. }
  773. /**
  774. * @brief The script called llResetScript() while it was running and
  775. * has suspended. We want to reset the script to a never-has-
  776. * ever-run-before state.
  777. *
  778. * Caller must have m_RunLock locked so we know script isn't
  779. * running.
  780. */
  781. private void ResetLocked(string from)
  782. {
  783. m_RunOnePhase = "ResetLocked: releasing controls";
  784. ReleaseControlsOrPermissions(true);
  785. m_Part.CollisionSound = UUID.Zero;
  786. if (m_XMRLSLApi != null)
  787. m_XMRLSLApi.llResetTime();
  788. m_RunOnePhase = "ResetLocked: removing script";
  789. IUrlModule urlModule = m_Engine.World.RequestModuleInterface<IUrlModule>();
  790. if(urlModule != null)
  791. urlModule.ScriptRemoved(m_ItemID);
  792. AsyncCommandManager.RemoveScript(m_Engine, m_LocalID, m_ItemID);
  793. m_RunOnePhase = "ResetLocked: clearing current event";
  794. this.eventCode = ScriptEventCode.None; // not processing an event
  795. m_DetectParams = null; // not processing an event
  796. m_SleepUntil = DateTime.MinValue; // not doing llSleep()
  797. m_ResetCount++; // has been reset once more
  798. m_localsHeapUsed = 0;
  799. m_arraysHeapUsed = 0;
  800. glblVars.Clear();
  801. // Tell next call to 'default state_entry()' to reset all global
  802. // vars to their initial values.
  803. doGblInit = true;
  804. // Throw away all its stack frames.
  805. // If the script is resetting itself, there shouldn't be any stack frames.
  806. // If the script is being reset by something else, we throw them away cuz we want to start from the beginning of an event handler.
  807. stackFrames = null;
  808. // Set script to 'default' state and queue call to its
  809. // 'state_entry()' event handler.
  810. m_RunOnePhase = "ResetLocked: posting default:state_entry() event";
  811. stateCode = 0;
  812. m_Part.RemoveScriptTargets(m_ItemID);
  813. m_Part.SetScriptEvents(m_ItemID, GetStateEventFlags(0));
  814. PostEvent(new EventParams("state_entry",
  815. zeroObjectArray,
  816. zeroDetectParams));
  817. // Tell CheckRun() to let script run.
  818. suspendOnCheckRunHold = false;
  819. suspendOnCheckRunTemp = false;
  820. m_RunOnePhase = "ResetLocked: reset complete";
  821. }
  822. private void ReleaseControlsOrPermissions(bool fullPermissions)
  823. {
  824. if(m_Part != null && m_Part.TaskInventory != null)
  825. {
  826. int permsMask;
  827. UUID permsGranter;
  828. m_Part.TaskInventory.LockItemsForWrite(true);
  829. if (!m_Part.TaskInventory.TryGetValue(m_ItemID, out TaskInventoryItem item))
  830. {
  831. m_Part.TaskInventory.LockItemsForWrite(false);
  832. return;
  833. }
  834. permsGranter = item.PermsGranter;
  835. permsMask = item.PermsMask;
  836. if(fullPermissions)
  837. {
  838. item.PermsGranter = UUID.Zero;
  839. item.PermsMask = 0;
  840. }
  841. else
  842. item.PermsMask = permsMask & ~(ScriptBaseClass.PERMISSION_TAKE_CONTROLS | ScriptBaseClass.PERMISSION_CONTROL_CAMERA);
  843. m_Part.TaskInventory.LockItemsForWrite(false);
  844. if ((permsMask & ScriptBaseClass.PERMISSION_TAKE_CONTROLS) != 0)
  845. {
  846. ScenePresence presence = m_Engine.World.GetScenePresence(permsGranter);
  847. if (presence != null)
  848. presence.UnRegisterControlEventsToScript(m_LocalID, m_ItemID);
  849. }
  850. }
  851. }
  852. /**
  853. * @brief The script code should call this routine whenever it is
  854. * convenient to perform a migation or switch microthreads.
  855. */
  856. public override void CheckRunWork()
  857. {
  858. if(!suspendOnCheckRunHold && !suspendOnCheckRunTemp)
  859. {
  860. if(Util.GetTimeStampMS() - m_SliceStart < 60.0)
  861. return;
  862. suspendOnCheckRunTemp = true;
  863. }
  864. m_CheckRunPhase = "entered";
  865. // Stay stuck in this loop as long as something wants us suspended.
  866. while(suspendOnCheckRunHold || suspendOnCheckRunTemp)
  867. {
  868. m_CheckRunPhase = "top of while";
  869. suspendOnCheckRunTemp = false;
  870. switch(this.callMode)
  871. {
  872. // Now we are ready to suspend or resume.
  873. case CallMode_NORMAL:
  874. m_CheckRunPhase = "suspending";
  875. callMode = XMRInstance.CallMode_SAVE;
  876. stackFrames = null;
  877. throw new StackHibernateException(); // does not return
  878. // We get here when the script state has been read in by MigrateInEventHandler().
  879. // Since the stack is completely restored at this point, any subsequent calls
  880. // within the functions should do their normal processing instead of trying to
  881. // restore their state.
  882. // the stack has been restored as a result of calling ResumeEx()
  883. // tell script code to process calls normally
  884. case CallMode_RESTORE:
  885. this.callMode = CallMode_NORMAL;
  886. break;
  887. default:
  888. throw new Exception("callMode=" + callMode);
  889. }
  890. m_CheckRunPhase = "resumed";
  891. }
  892. m_CheckRunPhase = "returning";
  893. // Upon return from CheckRun() it should always be the case that the script is
  894. // going to process calls normally, neither saving nor restoring stack frame state.
  895. if(callMode != CallMode_NORMAL)
  896. throw new Exception("bad callMode " + callMode);
  897. }
  898. /**
  899. * @brief Allow script to dequeue events.
  900. */
  901. public void ResumeIt()
  902. {
  903. lock(m_QueueLock)
  904. {
  905. m_SuspendCount = 0;
  906. m_Suspended = false;
  907. m_DetachQuantum = 0;
  908. m_DetachReady.Set();
  909. if ((m_EventQueue != null) &&
  910. (m_EventQueue.First != null) &&
  911. (m_IState == XMRInstState.IDLE))
  912. {
  913. m_IState = XMRInstState.ONSTARTQ;
  914. m_Engine.QueueToStart(this);
  915. }
  916. m_HasRun = true;
  917. }
  918. }
  919. /**
  920. * @brief Block script from dequeuing events.
  921. */
  922. public void SuspendIt()
  923. {
  924. lock(m_QueueLock)
  925. {
  926. m_SuspendCount = 1;
  927. m_Suspended = true;
  928. }
  929. }
  930. }
  931. /**
  932. * @brief Thrown by CheckRun() to unwind the script stack, capturing frames to
  933. * instance.stackFrames as it unwinds. We don't want scripts to be able
  934. * to intercept this exception as it would block the stack capture
  935. * functionality.
  936. */
  937. public class StackCaptureException: Exception, IXMRUncatchable
  938. {
  939. }
  940. }