ExecutionConstraintTests.cs 11 KB

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