JintCallStack.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. using System.Diagnostics.CodeAnalysis;
  2. using System.Linq;
  3. using System.Text;
  4. using Jint.Collections;
  5. using Jint.Native.Function;
  6. using Jint.Runtime.Environments;
  7. using Jint.Runtime.Interpreter.Expressions;
  8. using Environment = Jint.Runtime.Environments.Environment;
  9. namespace Jint.Runtime.CallStack;
  10. // smaller version with only required info
  11. internal readonly record struct CallStackExecutionContext
  12. {
  13. public CallStackExecutionContext(in ExecutionContext context)
  14. {
  15. LexicalEnvironment = context.LexicalEnvironment;
  16. }
  17. internal readonly Environment LexicalEnvironment;
  18. internal Environment GetThisEnvironment()
  19. {
  20. var lex = LexicalEnvironment;
  21. while (true)
  22. {
  23. if (lex is not null)
  24. {
  25. if (lex.HasThisBinding())
  26. {
  27. return lex;
  28. }
  29. lex = lex._outerEnv;
  30. }
  31. }
  32. }
  33. }
  34. internal sealed class JintCallStack
  35. {
  36. private readonly RefStack<CallStackElement> _stack = new();
  37. private readonly Dictionary<CallStackElement, int>? _statistics;
  38. // Internal for use by DebugHandler
  39. internal RefStack<CallStackElement> Stack => _stack;
  40. public JintCallStack(bool trackRecursionDepth)
  41. {
  42. if (trackRecursionDepth)
  43. {
  44. _statistics = new Dictionary<CallStackElement, int>(CallStackElementComparer.Instance);
  45. }
  46. }
  47. public int Push(Function function, JintExpression? expression, in ExecutionContext executionContext)
  48. {
  49. var item = new CallStackElement(function, expression, new CallStackExecutionContext(executionContext));
  50. _stack.Push(item);
  51. if (_statistics is not null)
  52. {
  53. #pragma warning disable CA1854
  54. #pragma warning disable CA1864
  55. if (_statistics.ContainsKey(item))
  56. #pragma warning restore CA1854
  57. #pragma warning restore CA1864
  58. {
  59. return ++_statistics[item];
  60. }
  61. else
  62. {
  63. _statistics.Add(item, 0);
  64. return 0;
  65. }
  66. }
  67. return -1;
  68. }
  69. public CallStackElement Pop()
  70. {
  71. ref readonly var item = ref _stack.Pop();
  72. if (_statistics is not null)
  73. {
  74. if (_statistics[item] == 0)
  75. {
  76. _statistics.Remove(item);
  77. }
  78. else
  79. {
  80. _statistics[item]--;
  81. }
  82. }
  83. return item;
  84. }
  85. public bool TryPeek([NotNullWhen(true)] out CallStackElement item)
  86. {
  87. return _stack.TryPeek(out item);
  88. }
  89. public int Count => _stack._size;
  90. public void Clear()
  91. {
  92. _stack.Clear();
  93. _statistics?.Clear();
  94. }
  95. public override string ToString()
  96. {
  97. return string.Join("->", _stack.Select(static cse => cse.ToString()).Reverse());
  98. }
  99. internal string BuildCallStackString(Engine engine, SourceLocation location, int excludeTop = 0)
  100. {
  101. static void AppendLocation(
  102. ref ValueStringBuilder sb,
  103. string shortDescription,
  104. in SourceLocation loc,
  105. in CallStackElement? element,
  106. Options.BuildCallStackDelegate? callStackBuilder)
  107. {
  108. if (callStackBuilder != null && TryInvokeCustomCallStackHandler(callStackBuilder, element, shortDescription, loc, ref sb))
  109. {
  110. return;
  111. }
  112. sb.Append(" at");
  113. if (!string.IsNullOrWhiteSpace(shortDescription))
  114. {
  115. sb.Append(' ');
  116. sb.Append(shortDescription);
  117. }
  118. if (element?.Arguments is not null)
  119. {
  120. // it's a function
  121. sb.Append(" (");
  122. var arguments = element.Value.Arguments.Value;
  123. for (var i = 0; i < arguments.Count; i++)
  124. {
  125. if (i != 0)
  126. {
  127. sb.Append(", ");
  128. }
  129. sb.Append(GetPropertyKey(arguments[i]));
  130. }
  131. sb.Append(')');
  132. }
  133. sb.Append(' ');
  134. sb.Append(loc.SourceFile);
  135. sb.Append(':');
  136. sb.Append(loc.End.Line);
  137. sb.Append(':');
  138. sb.Append(loc.Start.Column + 1); // report column number instead of index
  139. sb.Append(System.Environment.NewLine);
  140. }
  141. var customCallStackBuilder = engine.Options.Interop.BuildCallStackHandler;
  142. var builder = new ValueStringBuilder();
  143. // stack is one frame behind function-wise when we start to process it from expression level
  144. var index = _stack._size - 1 - excludeTop;
  145. var element = index >= 0 ? _stack[index] : (CallStackElement?) null;
  146. var shortDescription = element?.ToString() ?? "";
  147. AppendLocation(ref builder, shortDescription, location, element, customCallStackBuilder);
  148. location = element?.Location ?? default;
  149. index--;
  150. while (index >= -1)
  151. {
  152. element = index >= 0 ? _stack[index] : null;
  153. shortDescription = element?.ToString() ?? "";
  154. AppendLocation(ref builder, shortDescription, location, element, customCallStackBuilder);
  155. location = element?.Location ?? default;
  156. index--;
  157. }
  158. var result = builder.AsSpan().TrimEnd().ToString();
  159. builder.Dispose();
  160. return result;
  161. }
  162. private static bool TryInvokeCustomCallStackHandler(
  163. Options.BuildCallStackDelegate handler,
  164. CallStackElement? element,
  165. string shortDescription,
  166. SourceLocation loc,
  167. ref ValueStringBuilder sb)
  168. {
  169. string[]? arguments = null;
  170. if (element?.Arguments is not null)
  171. {
  172. var args = element.Value.Arguments.Value;
  173. arguments = args.Count > 0 ? new string[args.Count] : [];
  174. for (var i = 0; i < arguments.Length; i++)
  175. {
  176. arguments[i] = GetPropertyKey(args[i]);
  177. }
  178. }
  179. var str = handler(shortDescription, loc, arguments);
  180. if (!string.IsNullOrEmpty(str))
  181. {
  182. sb.Append(str);
  183. return true;
  184. }
  185. return false;
  186. }
  187. /// <summary>
  188. /// A version of <see cref="AstExtensions.GetKey"/> that cannot get into loop as we are already building a stack.
  189. /// </summary>
  190. private static string GetPropertyKey(Node expression)
  191. {
  192. if (expression is Literal literal)
  193. {
  194. return AstExtensions.LiteralKeyToString(literal);
  195. }
  196. if (expression is Identifier identifier)
  197. {
  198. return identifier.Name ?? "";
  199. }
  200. if (expression is MemberExpression { Computed: false } staticMemberExpression)
  201. {
  202. return $"{GetPropertyKey(staticMemberExpression.Object)}.{GetPropertyKey(staticMemberExpression.Property)}";
  203. }
  204. return "?";
  205. }
  206. }