ExecutionConstraintTests.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. using Jint.Native.Function;
  2. using Jint.Runtime;
  3. namespace Jint.Tests.Runtime;
  4. public class ExecutionConstraintTests
  5. {
  6. [Fact]
  7. public void ShouldThrowStatementCountOverflow()
  8. {
  9. Assert.Throws<StatementsCountOverflowException>(
  10. () => new Engine(cfg => cfg.MaxStatements(100)).Evaluate("while(true);")
  11. );
  12. }
  13. [Fact]
  14. public void ShouldThrowMemoryLimitExceeded()
  15. {
  16. Assert.Throws<MemoryLimitExceededException>(
  17. () => new Engine(cfg => cfg.LimitMemory(2048)).Evaluate("a=[]; while(true){ a.push(0); }")
  18. );
  19. }
  20. [Fact]
  21. public void ShouldThrowTimeout()
  22. {
  23. Assert.Throws<TimeoutException>(
  24. () => new Engine(cfg => cfg.TimeoutInterval(new TimeSpan(0, 0, 0, 0, 500))).Evaluate("while(true);")
  25. );
  26. }
  27. [Fact]
  28. public void ShouldThrowExecutionCanceled()
  29. {
  30. Assert.Throws<ExecutionCanceledException>(
  31. () =>
  32. {
  33. using (var tcs = new CancellationTokenSource())
  34. using (var waitHandle = new ManualResetEvent(false))
  35. {
  36. var engine = new Engine(cfg => cfg.CancellationToken(tcs.Token));
  37. ThreadPool.QueueUserWorkItem(state =>
  38. {
  39. waitHandle.WaitOne();
  40. tcs.Cancel();
  41. });
  42. engine.SetValue("waitHandle", waitHandle);
  43. engine.Evaluate(@"
  44. function sleep(millisecondsTimeout) {
  45. var totalMilliseconds = new Date().getTime() + millisecondsTimeout;
  46. while (new Date() < totalMilliseconds) { }
  47. }
  48. sleep(100);
  49. waitHandle.Set();
  50. sleep(1000);
  51. sleep(1000);
  52. sleep(1000);
  53. sleep(1000);
  54. sleep(1000);
  55. ");
  56. }
  57. }
  58. );
  59. }
  60. [Fact]
  61. public void CanDiscardRecursion()
  62. {
  63. var script = @"var factorial = function(n) {
  64. if (n>1) {
  65. return n * factorial(n - 1);
  66. }
  67. };
  68. var result = factorial(500);
  69. ";
  70. Assert.Throws<RecursionDepthOverflowException>(
  71. () => new Engine(cfg => cfg.LimitRecursion()).Execute(script)
  72. );
  73. }
  74. [Fact]
  75. public void ShouldDiscardHiddenRecursion()
  76. {
  77. var script = @"var renamedFunc;
  78. var exec = function(callback) {
  79. renamedFunc = callback;
  80. callback();
  81. };
  82. var result = exec(function() {
  83. renamedFunc();
  84. });
  85. ";
  86. Assert.Throws<RecursionDepthOverflowException>(
  87. () => new Engine(cfg => cfg.LimitRecursion()).Execute(script)
  88. );
  89. }
  90. [Fact]
  91. public void ShouldRecognizeAndDiscardChainedRecursion()
  92. {
  93. var script = @" var funcRoot, funcA, funcB, funcC, funcD;
  94. var funcRoot = function() {
  95. funcA();
  96. };
  97. var funcA = function() {
  98. funcB();
  99. };
  100. var funcB = function() {
  101. funcC();
  102. };
  103. var funcC = function() {
  104. funcD();
  105. };
  106. var funcD = function() {
  107. funcRoot();
  108. };
  109. funcRoot();
  110. ";
  111. Assert.Throws<RecursionDepthOverflowException>(
  112. () => new Engine(cfg => cfg.LimitRecursion()).Execute(script)
  113. );
  114. }
  115. [Fact]
  116. public void ShouldProvideCallChainWhenDiscardRecursion()
  117. {
  118. var script = @" var funcRoot, funcA, funcB, funcC, funcD;
  119. var funcRoot = function() {
  120. funcA();
  121. };
  122. var funcA = function() {
  123. funcB();
  124. };
  125. var funcB = function() {
  126. funcC();
  127. };
  128. var funcC = function() {
  129. funcD();
  130. };
  131. var funcD = function() {
  132. funcRoot();
  133. };
  134. funcRoot();
  135. ";
  136. RecursionDepthOverflowException exception = null;
  137. try
  138. {
  139. new Engine(cfg => cfg.LimitRecursion()).Execute(script);
  140. }
  141. catch (RecursionDepthOverflowException ex)
  142. {
  143. exception = ex;
  144. }
  145. Assert.NotNull(exception);
  146. Assert.Equal("funcRoot->funcA->funcB->funcC->funcD", exception.CallChain);
  147. Assert.Equal("funcRoot", exception.CallExpressionReference);
  148. }
  149. [Fact]
  150. public void ShouldAllowShallowRecursion()
  151. {
  152. var script = @"var factorial = function(n) {
  153. if (n>1) {
  154. return n * factorial(n - 1);
  155. }
  156. };
  157. var result = factorial(8);
  158. ";
  159. new Engine(cfg => cfg.LimitRecursion(20)).Execute(script);
  160. }
  161. [Fact]
  162. public void ShouldDiscardDeepRecursion()
  163. {
  164. var script = @"var factorial = function(n) {
  165. if (n>1) {
  166. return n * factorial(n - 1);
  167. }
  168. };
  169. var result = factorial(38);
  170. ";
  171. Assert.Throws<RecursionDepthOverflowException>(
  172. () => new Engine(cfg => cfg.LimitRecursion(20)).Execute(script)
  173. );
  174. }
  175. [Fact]
  176. public void ShouldAllowRecursionLimitWithoutReferencedName()
  177. {
  178. const string input = @"(function () {
  179. var factorial = function(n) {
  180. if (n>1) {
  181. return n * factorial(n - 1);
  182. }
  183. };
  184. var result = factorial(38);
  185. })();
  186. ";
  187. var engine = new Engine(o => o.LimitRecursion(20));
  188. Assert.Throws<RecursionDepthOverflowException>(() => engine.Execute(input));
  189. }
  190. [Fact]
  191. public void ShouldLimitRecursionWithAllFunctionInstances()
  192. {
  193. var engine = new Engine(cfg =>
  194. {
  195. // Limit recursion to 5 invocations
  196. cfg.LimitRecursion(5);
  197. cfg.Strict();
  198. });
  199. var ex = Assert.Throws<RecursionDepthOverflowException>(() => engine.Evaluate(@"
  200. var myarr = new Array(5000);
  201. for (var i = 0; i < myarr.length; i++) {
  202. myarr[i] = function(i) {
  203. myarr[i + 1](i + 1);
  204. }
  205. }
  206. myarr[0](0);
  207. "));
  208. }
  209. [Fact]
  210. public void ShouldLimitRecursionWithGetters()
  211. {
  212. const string code = @"var obj = { get test() { return this.test + '2'; } }; obj.test;";
  213. var engine = new Engine(cfg => cfg.LimitRecursion(10));
  214. Assert.Throws<RecursionDepthOverflowException>(() => engine.Evaluate(code));
  215. }
  216. [Fact]
  217. public void ShouldLimitArraySizeForConcat()
  218. {
  219. var engine = new Engine(o => o.MaxStatements(1_000).MaxArraySize(1_000_000));
  220. Assert.Throws<MemoryLimitExceededException>(() => engine.Evaluate("for (let a = [1, 2, 3];; a = a.concat(a)) ;"));
  221. }
  222. [Fact]
  223. public void ShouldLimitArraySizeForFill()
  224. {
  225. var engine = new Engine(o => o.MaxStatements(1_000).MaxArraySize(1_000_000));
  226. Assert.Throws<MemoryLimitExceededException>(() => engine.Evaluate("var arr = Array(1000000000).fill(new Array(1000000000));"));
  227. }
  228. [Fact]
  229. public void ShouldLimitArraySizeForJoin()
  230. {
  231. var engine = new Engine(o => o.MaxStatements(1_000).MaxArraySize(1_000_000));
  232. Assert.Throws<MemoryLimitExceededException>(() => engine.Evaluate("new Array(2147483647).join('*')"));
  233. }
  234. [Fact]
  235. public void ShouldConsiderConstraintsWhenCallingInvoke()
  236. {
  237. var engine = new Engine(options =>
  238. {
  239. options.TimeoutInterval(TimeSpan.FromMilliseconds(100));
  240. });
  241. var myApi = new MyApi();
  242. engine.SetValue("myApi", myApi);
  243. engine.Execute("myApi.addEventListener('DataReceived', (data) => { myApi.log(data) })");
  244. var dataReceivedCallbacks = myApi.Callbacks.Where(kvp => kvp.Key == "DataReceived");
  245. foreach (var callback in dataReceivedCallbacks)
  246. {
  247. engine.Invoke(callback.Value, "Data Received #1");
  248. Thread.Sleep(101);
  249. engine.Invoke(callback.Value, "Data Received #2");
  250. }
  251. }
  252. [Fact]
  253. public void ResetConstraints()
  254. {
  255. void ExecuteAction(Engine engine) => engine.Execute("recursion()");
  256. void InvokeAction(Engine engine) => engine.Invoke("recursion");
  257. List<int> expected = [6, 6, 6, 6, 6];
  258. Assert.Equal(expected, RunLoop(CreateEngine(), ExecuteAction));
  259. Assert.Equal(expected, RunLoop(CreateEngine(), InvokeAction));
  260. var e1 = CreateEngine();
  261. Assert.Equal(expected, RunLoop(e1, ExecuteAction));
  262. Assert.Equal(expected, RunLoop(e1, InvokeAction));
  263. var e2 = CreateEngine();
  264. Assert.Equal(expected, RunLoop(e2, InvokeAction));
  265. Assert.Equal(expected, RunLoop(e2, ExecuteAction));
  266. var e3 = CreateEngine();
  267. Assert.Equal(expected, RunLoop(e3, InvokeAction));
  268. Assert.Equal(expected, RunLoop(e3, ExecuteAction));
  269. Assert.Equal(expected, RunLoop(e3, InvokeAction));
  270. var e4 = CreateEngine();
  271. Assert.Equal(expected, RunLoop(e4, InvokeAction));
  272. Assert.Equal(expected, RunLoop(e4, InvokeAction));
  273. }
  274. private static Engine CreateEngine()
  275. {
  276. Engine engine = new(options => options.LimitRecursion(5));
  277. return engine.Execute("""
  278. var num = 0;
  279. function recursion() {
  280. num++;
  281. recursion(num);
  282. }
  283. """);
  284. }
  285. private static List<int> RunLoop(Engine engine, Action<Engine> engineAction)
  286. {
  287. List<int> results = new();
  288. for (var i = 0; i < 5; i++)
  289. {
  290. try
  291. {
  292. engine.SetValue("num", 0);
  293. engineAction.Invoke(engine);
  294. }
  295. catch (RecursionDepthOverflowException)
  296. {
  297. results.Add((int) engine.GetValue("num").AsNumber());
  298. }
  299. }
  300. return results;
  301. }
  302. private class MyApi
  303. {
  304. public readonly Dictionary<string, ScriptFunction> Callbacks = new Dictionary<string, ScriptFunction>();
  305. public void AddEventListener(string eventName, ScriptFunction callback)
  306. {
  307. Callbacks.Add(eventName, callback);
  308. }
  309. public void Log(string logMessage)
  310. {
  311. Console.WriteLine(logMessage);
  312. }
  313. }
  314. }