Skip to content

Commit

Permalink
Merge pull request #90 from yantrajs/feature/stack-overflow
Browse files Browse the repository at this point in the history
Added support for stack overflow
  • Loading branch information
ackava committed Oct 21, 2023
2 parents 4723e6f + 6a7942e commit 9ef2e77
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
17 changes: 17 additions & 0 deletions YantraJS.Core.Tests/Generator/Files/es5/Function/stack-overflow.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
let i = 0;
function recursive() {
i++;
recursive();
}

try {
recursive();
} catch (error) {
if (error instanceof RangeError) {
if (/maximum\scall\sstack/i.test(error.message)) {
console.log(`Failed after ${i} recursive calls`);
return;
}
}
throw new Error("Stack overflow expected");
}
3 changes: 3 additions & 0 deletions YantraJS.Core/Core/JSContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
using YantraJS.Core.Core.DataView;
using YantraJS.Debugger;
using YantraJS.Core.Clr;
using YantraJS.Core.Core;

namespace YantraJS.Core
{
Expand All @@ -47,6 +48,7 @@ internal CallStackItem(string fileName, in StringSpan function, int line, int co
int nameLength, int line, int column)
{
context = context ?? JSContext.Current;
context.EnsureSufficientExecutionStack();
this.context = context;
this.FileName = scriptInfo.FileName;
this.Function = (nameLength>0)
Expand All @@ -62,6 +64,7 @@ internal CallStackItem(string fileName, in StringSpan function, int line, int co
public CallStackItem(JSContext context, string fileName, in StringSpan function, int line, int column)
{
context = context ?? JSContext.Current;
context.EnsureSufficientExecutionStack();
this.context = context;
this.FileName = fileName;
this.Function = function;
Expand Down
36 changes: 36 additions & 0 deletions YantraJS.Core/Core/JSContextExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;

namespace YantraJS.Core.Core
{
public static class JSContextExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void EnsureSufficientExecutionStack(this JSContext context)
{
#if NETSTANDARD2_1_OR_GREATER
if(RuntimeHelpers.TryEnsureSufficientExecutionStack())
{
return;
}
#else
try
{
RuntimeHelpers.EnsureSufficientExecutionStack();
}
catch (Exception ex)
{
if (ex is not InsufficientExecutionStackException)
{
throw ex;
}
}
#endif
throw context.NewRangeError("Maximum call stack size exceeded");
}


}
}

0 comments on commit 9ef2e77

Please sign in to comment.