XMRInstRun.cs 41 KB

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