Skip to content

Commit d84af69

Browse files
authored
Array.sort should obey execution constraints (#1026)
1 parent 8c4a51e commit d84af69

File tree

2 files changed

+26
-5
lines changed

2 files changed

+26
-5
lines changed

Jint.Tests/Runtime/ArrayTests.cs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,22 @@ function compare(a, b) {
115115
_engine.Execute(code);
116116
}
117117

118+
#if !NETCOREAPP
119+
// this test case only triggers on older full framework where the is no checks for infinite comparisons
120+
[Fact]
121+
public void ArraySortShouldObeyExecutionConstraints()
122+
{
123+
const string script = @"
124+
let cases = [5,5];
125+
let latestCase = cases.sort((c1, c2) => c1 > c2 ? -1: 1);";
126+
127+
var engine = new Engine(options => options
128+
.TimeoutInterval(TimeSpan.FromSeconds(1))
129+
);
130+
Assert.Throws<TimeoutException>(() => engine.Evaluate(script));
131+
}
132+
#endif
133+
118134
[Fact]
119135
public void ExtendingArrayAndInstanceOf()
120136
{

Jint/Native/Array/ArrayPrototype.cs

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -959,7 +959,7 @@ private JsValue Sort(JsValue thisObj, JsValue[] arguments)
959959
// don't eat inner exceptions
960960
try
961961
{
962-
var array = obj.OrderBy(x => x, ArrayComparer.WithFunction(compareFn)).ToArray();
962+
var array = obj.OrderBy(x => x, ArrayComparer.WithFunction(_engine, compareFn)).ToArray();
963963

964964
for (uint i = 0; i < (uint) array.Length; ++i)
965965
{
@@ -1399,22 +1399,25 @@ private sealed class ArrayComparer : IComparer<JsValue>
13991399
/// <summary>
14001400
/// Default instance without any compare function.
14011401
/// </summary>
1402-
public static ArrayComparer Default = new ArrayComparer(null);
1403-
public static ArrayComparer WithFunction(ICallable compare)
1402+
public static readonly ArrayComparer Default = new(null, null);
1403+
1404+
public static ArrayComparer WithFunction(Engine engine, ICallable compare)
14041405
{
14051406
if (compare == null)
14061407
{
14071408
return Default;
14081409
}
14091410

1410-
return new ArrayComparer(compare);
1411+
return new ArrayComparer(engine, compare);
14111412
}
14121413

1414+
private readonly Engine _engine;
14131415
private readonly ICallable _compare;
14141416
private readonly JsValue[] _comparableArray = new JsValue[2];
14151417

1416-
private ArrayComparer(ICallable compare)
1418+
private ArrayComparer(Engine engine, ICallable compare)
14171419
{
1420+
_engine = engine;
14181421
_compare = compare;
14191422
}
14201423

@@ -1459,6 +1462,8 @@ public int Compare(JsValue x, JsValue y)
14591462

14601463
if (_compare != null)
14611464
{
1465+
_engine.RunBeforeExecuteStatementChecks(null);
1466+
14621467
_comparableArray[0] = x;
14631468
_comparableArray[1] = y;
14641469

0 commit comments

Comments
 (0)