DebugHandler.cs 8.5 KB

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