DebugHandler.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. using System;
  2. using Esprima;
  3. using Esprima.Ast;
  4. using Jint.Native;
  5. using Jint.Runtime.Interpreter;
  6. namespace Jint.Runtime.Debugger
  7. {
  8. public enum PauseType
  9. {
  10. Step,
  11. Break,
  12. DebuggerStatement
  13. }
  14. public class DebugHandler
  15. {
  16. public delegate StepMode DebugEventHandler(object sender, DebugInformation e);
  17. private readonly Engine _engine;
  18. private bool _paused;
  19. private int _steppingDepth;
  20. /// <summary>
  21. /// The Step event is triggered before the engine executes a step-eligible AST node.
  22. /// </summary>
  23. /// <remarks>
  24. /// If the current step mode is <see cref="StepMode.None"/>, this event is never triggered. The script may
  25. /// still be paused by a debugger statement or breakpoint, but these will trigger the
  26. /// <see cref="Break"/> event.
  27. /// </remarks>
  28. public event DebugEventHandler Step;
  29. /// <summary>
  30. /// The Break event is triggered when a breakpoint or debugger statement is hit.
  31. /// </summary>
  32. /// <remarks>
  33. /// This is event is not triggered if the current script location was reached by stepping. In that case, only
  34. /// the <see cref="Step"/> event is triggered.
  35. /// </remarks>
  36. public event DebugEventHandler Break;
  37. internal DebugHandler(Engine engine, StepMode initialStepMode)
  38. {
  39. _engine = engine;
  40. HandleNewStepMode(initialStepMode);
  41. }
  42. /// <summary>
  43. /// The location of the current (step-eligible) AST node being executed.
  44. /// </summary>
  45. /// <remarks>
  46. /// The location is available as long as DebugMode is enabled - i.e. even when not stepping
  47. /// or hitting a breakpoint.
  48. /// </remarks>
  49. public Location? CurrentLocation { get; private set; }
  50. /// <summary>
  51. /// Collection of active breakpoints for the engine.
  52. /// </summary>
  53. public BreakPointCollection BreakPoints { get; } = new BreakPointCollection();
  54. /// <summary>
  55. /// Evaluates a script (expression) within the current execution context.
  56. /// </summary>
  57. /// <remarks>
  58. /// Internally, this is used for evaluating breakpoint conditions, but may also be used for e.g. watch lists
  59. /// in a debugger.
  60. /// </remarks>
  61. public JsValue Evaluate(Script script)
  62. {
  63. var context = _engine._activeEvaluationContext;
  64. if (context == null)
  65. {
  66. throw new DebugEvaluationException("Jint has no active evaluation context");
  67. }
  68. int callStackSize = _engine.CallStack.Count;
  69. var list = new JintStatementList(null, script.Body);
  70. Completion result;
  71. try
  72. {
  73. result = list.Execute(context);
  74. }
  75. catch (Exception ex)
  76. {
  77. // An error in the evaluation may return a Throw Completion, or it may throw an exception:
  78. throw new DebugEvaluationException("An error occurred during debugger evaluation", ex);
  79. }
  80. finally
  81. {
  82. // Restore call stack
  83. while (_engine.CallStack.Count > callStackSize)
  84. {
  85. _engine.CallStack.Pop();
  86. }
  87. }
  88. if (result.Type == CompletionType.Throw)
  89. {
  90. // TODO: Should we return an error here? (avoid exception overhead, since e.g. breakpoint
  91. // evaluation may be high volume.
  92. var error = result.GetValueOrDefault();
  93. var ex = new JavaScriptException(error).SetCallstack(_engine, result.Location);
  94. throw new DebugEvaluationException("An error occurred during debugger evaluation", ex);
  95. }
  96. return result.GetValueOrDefault();
  97. }
  98. /// <inheritdoc cref="Evaluate(Script)" />
  99. public JsValue Evaluate(string source, ParserOptions options = null)
  100. {
  101. options ??= new ParserOptions("evaluation") { AdaptRegexp = true, Tolerant = true };
  102. var parser = new JavaScriptParser(source, options);
  103. try
  104. {
  105. var script = parser.ParseScript();
  106. return Evaluate(script);
  107. }
  108. catch (ParserException ex)
  109. {
  110. throw new DebugEvaluationException("An error occurred during debugger expression parsing", ex);
  111. }
  112. }
  113. internal void OnStep(Node node)
  114. {
  115. // Don't reenter if we're already paused (e.g. when evaluating a getter in a Break/Step handler)
  116. if (_paused)
  117. {
  118. return;
  119. }
  120. _paused = true;
  121. CheckBreakPointAndPause(
  122. new BreakLocation(node.Location.Source, node.Location.Start),
  123. node: node,
  124. location: null,
  125. returnValue: null);
  126. }
  127. internal void OnReturnPoint(Node functionBody, JsValue returnValue)
  128. {
  129. // Don't reenter if we're already paused (e.g. when evaluating a getter in a Break/Step handler)
  130. if (_paused)
  131. {
  132. return;
  133. }
  134. _paused = true;
  135. var bodyLocation = functionBody.Location;
  136. var functionBodyEnd = bodyLocation.End;
  137. var location = new Location(functionBodyEnd, functionBodyEnd, bodyLocation.Source);
  138. CheckBreakPointAndPause(
  139. new BreakLocation(bodyLocation.Source, bodyLocation.End),
  140. node: null,
  141. location: location,
  142. returnValue: returnValue);
  143. }
  144. internal void OnDebuggerStatement(Statement statement)
  145. {
  146. // Don't reenter if we're already paused
  147. if (_paused)
  148. {
  149. return;
  150. }
  151. _paused = true;
  152. bool isStepping = _engine.CallStack.Count <= _steppingDepth;
  153. // Even though we're at a debugger statement, if we're stepping, ignore the statement. OnStep already
  154. // takes care of pausing.
  155. if (!isStepping)
  156. {
  157. Pause(PauseType.DebuggerStatement, statement);
  158. }
  159. _paused = false;
  160. }
  161. private void CheckBreakPointAndPause(BreakLocation breakLocation, Node node = null, Location? location = null,
  162. JsValue returnValue = null)
  163. {
  164. CurrentLocation = location ?? node?.Location;
  165. BreakPoint breakpoint = BreakPoints.FindMatch(this, breakLocation);
  166. bool isStepping = _engine.CallStack.Count <= _steppingDepth;
  167. if (breakpoint != null || isStepping)
  168. {
  169. // Even if we matched a breakpoint, if we're stepping, the reason we're pausing is the step.
  170. // Still, we need to include the breakpoint at this location, in case the debugger UI needs to update
  171. // e.g. a hit count.
  172. Pause(isStepping ? PauseType.Step : PauseType.Break, node, location, returnValue, breakpoint);
  173. }
  174. _paused = false;
  175. }
  176. private void Pause(PauseType type, Node node = null, Location? location = null, JsValue returnValue = null,
  177. BreakPoint breakPoint = null)
  178. {
  179. var info = new DebugInformation(
  180. engine: _engine,
  181. currentNode: node,
  182. currentLocation: location ?? node.Location,
  183. returnValue: returnValue,
  184. currentMemoryUsage: _engine.CurrentMemoryUsage,
  185. pauseType: type,
  186. breakPoint: breakPoint
  187. );
  188. StepMode? result = type switch
  189. {
  190. // Conventionally, sender should be DebugHandler - but Engine is more useful
  191. PauseType.Step => Step?.Invoke(_engine, info),
  192. PauseType.Break => Break?.Invoke(_engine, info),
  193. PauseType.DebuggerStatement => Break?.Invoke(_engine, info),
  194. _ => throw new ArgumentException("Invalid pause type", nameof(type))
  195. };
  196. HandleNewStepMode(result);
  197. }
  198. private void HandleNewStepMode(StepMode? newStepMode)
  199. {
  200. if (newStepMode != null)
  201. {
  202. _steppingDepth = newStepMode switch
  203. {
  204. StepMode.Over => _engine.CallStack.Count,// Resume stepping when back at this level of the stack
  205. StepMode.Out => _engine.CallStack.Count - 1,// Resume stepping when we've popped the stack
  206. StepMode.None => int.MinValue,// Never step
  207. _ => int.MaxValue,// Always step
  208. };
  209. }
  210. }
  211. }
  212. }