DebugHandler.cs 8.7 KB

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