ExecutionConstraintTests.cs 11 KB

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