JintCallStack.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. var hasShortDescription = !string.IsNullOrWhiteSpace(shortDescription);
  113. sb.Append(" at ");
  114. if (hasShortDescription)
  115. {
  116. sb.Append(shortDescription);
  117. sb.Append(" (");
  118. }
  119. sb.Append(loc.SourceFile);
  120. sb.Append(':');
  121. sb.Append(loc.End.Line);
  122. sb.Append(':');
  123. sb.Append(loc.Start.Column + 1); // report column number instead of index
  124. if (hasShortDescription)
  125. {
  126. sb.Append(')');
  127. }
  128. sb.Append(System.Environment.NewLine);
  129. }
  130. var customCallStackBuilder = engine.Options.Interop.BuildCallStackHandler;
  131. var builder = new ValueStringBuilder();
  132. // stack is one frame behind function-wise when we start to process it from expression level
  133. var index = _stack._size - 1 - excludeTop;
  134. var element = index >= 0 ? _stack[index] : (CallStackElement?) null;
  135. var shortDescription = element?.ToString() ?? "";
  136. AppendLocation(ref builder, shortDescription, location, element, customCallStackBuilder);
  137. location = element?.Location ?? default;
  138. index--;
  139. while (index >= -1)
  140. {
  141. element = index >= 0 ? _stack[index] : null;
  142. shortDescription = element?.ToString() ?? "";
  143. AppendLocation(ref builder, shortDescription, location, element, customCallStackBuilder);
  144. location = element?.Location ?? default;
  145. index--;
  146. }
  147. var result = builder.AsSpan().TrimEnd().ToString();
  148. builder.Dispose();
  149. return result;
  150. }
  151. private static bool TryInvokeCustomCallStackHandler(
  152. Options.BuildCallStackDelegate handler,
  153. CallStackElement? element,
  154. string shortDescription,
  155. SourceLocation loc,
  156. ref ValueStringBuilder sb)
  157. {
  158. string[]? arguments = null;
  159. if (element?.Arguments is not null)
  160. {
  161. var args = element.Value.Arguments.Value;
  162. arguments = args.Count > 0 ? new string[args.Count] : [];
  163. for (var i = 0; i < arguments.Length; i++)
  164. {
  165. arguments[i] = GetPropertyKey(args[i]);
  166. }
  167. }
  168. var str = handler(shortDescription, loc, arguments);
  169. if (!string.IsNullOrEmpty(str))
  170. {
  171. sb.Append(str);
  172. return true;
  173. }
  174. return false;
  175. }
  176. /// <summary>
  177. /// A version of <see cref="AstExtensions.GetKey"/> that cannot get into loop as we are already building a stack.
  178. /// </summary>
  179. private static string GetPropertyKey(Node expression)
  180. {
  181. if (expression is Literal literal)
  182. {
  183. return AstExtensions.LiteralKeyToString(literal);
  184. }
  185. if (expression is Identifier identifier)
  186. {
  187. return identifier.Name ?? "";
  188. }
  189. if (expression is MemberExpression { Computed: false } staticMemberExpression)
  190. {
  191. return $"{GetPropertyKey(staticMemberExpression.Object)}.{GetPropertyKey(staticMemberExpression.Property)}";
  192. }
  193. return "?";
  194. }
  195. }