DebugHandler.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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 = Location.From(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(
  161. BreakLocation breakLocation,
  162. Node? node,
  163. Location? location = null,
  164. JsValue? returnValue = null)
  165. {
  166. CurrentLocation = location ?? node?.Location;
  167. var breakpoint = BreakPoints.FindMatch(this, breakLocation);
  168. bool isStepping = _engine.CallStack.Count <= _steppingDepth;
  169. if (breakpoint != null || isStepping)
  170. {
  171. // Even if we matched a breakpoint, if we're stepping, the reason we're pausing is the step.
  172. // Still, we need to include the breakpoint at this location, in case the debugger UI needs to update
  173. // e.g. a hit count.
  174. Pause(isStepping ? PauseType.Step : PauseType.Break, node!, location, returnValue, breakpoint);
  175. }
  176. _paused = false;
  177. }
  178. private void Pause(
  179. PauseType type,
  180. Node node,
  181. Location? location = null,
  182. JsValue? returnValue = null,
  183. BreakPoint? breakPoint = null)
  184. {
  185. var info = new DebugInformation(
  186. engine: _engine,
  187. currentNode: node,
  188. currentLocation: location ?? node.Location,
  189. returnValue: returnValue,
  190. currentMemoryUsage: _engine.CurrentMemoryUsage,
  191. pauseType: type,
  192. breakPoint: breakPoint
  193. );
  194. StepMode? result = type switch
  195. {
  196. // Conventionally, sender should be DebugHandler - but Engine is more useful
  197. PauseType.Step => Step?.Invoke(_engine, info),
  198. PauseType.Break => Break?.Invoke(_engine, info),
  199. PauseType.DebuggerStatement => Break?.Invoke(_engine, info),
  200. _ => throw new ArgumentException("Invalid pause type", nameof(type))
  201. };
  202. HandleNewStepMode(result);
  203. }
  204. private void HandleNewStepMode(StepMode? newStepMode)
  205. {
  206. if (newStepMode != null)
  207. {
  208. _steppingDepth = newStepMode switch
  209. {
  210. StepMode.Over => _engine.CallStack.Count,// Resume stepping when back at this level of the stack
  211. StepMode.Out => _engine.CallStack.Count - 1,// Resume stepping when we've popped the stack
  212. StepMode.None => int.MinValue,// Never step
  213. _ => int.MaxValue,// Always step
  214. };
  215. }
  216. }
  217. }
  218. }