Permalink
Browse files

Merge pull request #400 from sk89q/bugfix/timed-calc

Attach a configurable timeout to expression evaluation
  • Loading branch information...
me4502 committed Oct 12, 2018
2 parents 844971b + e16dacc commit 9f43963379d2e3d41e15e453d28b96c4ec7249e1
@@ -137,10 +137,13 @@ history:
size: 15
expiration: 10
calculation:
timeout: 100
wand-item: minecraft:wooden_axe
shell-save-type:
no-double-slash: false
no-op-permissions: false
debug: false
show-help-on-first-use: true
server-side-cui: true
server-side-cui: true
@@ -127,6 +127,7 @@
public String navigationWand = ItemTypes.COMPASS.getId();
public int navigationWandMaxDistance = 50;
public int scriptTimeout = 3000;
public int calculationTimeout = 100;
public Set<String> allowedDataCycleBlocks = new HashSet<>();
public String saveDir = "schematics";
public String scriptsDir = "craftscripts";
@@ -19,6 +19,8 @@
package com.sk89q.worldedit.internal.expression;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.internal.expression.lexer.Lexer;
import com.sk89q.worldedit.internal.expression.lexer.tokens.Token;
import com.sk89q.worldedit.internal.expression.parser.Parser;
@@ -34,6 +36,13 @@
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Compiles and evaluates expressions.
@@ -69,6 +78,11 @@
public class Expression {
private static final ThreadLocal<Stack<Expression>> instance = new ThreadLocal<>();
private static final ExecutorService evalThread = Executors.newCachedThreadPool(
new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat("worldedit-expression-eval-%d")
.build());
private final Map<String, RValue> variables = new HashMap<>();
private final String[] variableNames;
@@ -113,13 +127,34 @@ public double evaluate(double... values) throws EvaluationException {
((Variable) invokable).value = values[i];
}
pushInstance();
Future<Double> result = evalThread.submit(new Callable<Double>() {
@Override
public Double call() throws Exception {
pushInstance();
try {
return root.getValue();
} finally {
popInstance();
}
}
});
try {
return root.getValue();
} catch (ReturnException e) {
return e.getValue();
} finally {
popInstance();
return result.get(WorldEdit.getInstance().getConfiguration().calculationTimeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof ReturnException) {
return ((ReturnException) cause).getValue();
}
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
}
throw new RuntimeException(cause);
} catch (TimeoutException e) {
result.cancel(true);
throw new EvaluationException(-1, "Calculations exceeded time limit.");
}
}
@@ -146,20 +181,20 @@ public static Expression getInstance() {
}
private void pushInstance() {
Stack<Expression> foo = instance.get();
if (foo == null) {
instance.set(foo = new Stack<>());
Stack<Expression> threadLocalExprStack = instance.get();
if (threadLocalExprStack == null) {
instance.set(threadLocalExprStack = new Stack<>());
}
foo.push(this);
threadLocalExprStack.push(this);
}
private void popInstance() {
Stack<Expression> foo = instance.get();
Stack<Expression> threadLocalExprStack = instance.get();
foo.pop();
threadLocalExprStack.pop();
if (foo.isEmpty()) {
if (threadLocalExprStack.isEmpty()) {
instance.set(null);
}
}
@@ -50,6 +50,9 @@ public double getValue() throws EvaluationException {
if (iterations > 256) {
throw new EvaluationException(getPosition(), "Loop exceeded 256 iterations.");
}
if (Thread.interrupted()) {
throw new EvaluationException(getPosition(), "Calculations exceeded time limit.");
}
++iterations;
try {
@@ -53,6 +53,9 @@ public double getValue() throws EvaluationException {
if (iterations > 256) {
throw new EvaluationException(getPosition(), "Loop exceeded 256 iterations.");
}
if (Thread.interrupted()) {
throw new EvaluationException(getPosition(), "Calculations exceeded time limit.");
}
++iterations;
try {
@@ -49,6 +49,9 @@ public double getValue() throws EvaluationException {
if (iterations > 256) {
throw new EvaluationException(getPosition(), "Loop exceeded 256 iterations.");
}
if (Thread.interrupted()) {
throw new EvaluationException(getPosition(), "Calculations exceeded time limit.");
}
++iterations;
try {
@@ -66,6 +69,9 @@ public double getValue() throws EvaluationException {
if (iterations > 256) {
throw new EvaluationException(getPosition(), "Loop exceeded 256 iterations.");
}
if (Thread.interrupted()) {
throw new EvaluationException(getPosition(), "Calculations exceeded time limit.");
}
++iterations;
try {
@@ -109,6 +109,7 @@ public void load() {
navigationWandMaxDistance = getInt("nav-wand-distance", navigationWandMaxDistance);
navigationUseGlass = getBool("nav-use-glass", navigationUseGlass);
scriptTimeout = getInt("scripting-timeout", scriptTimeout);
calculationTimeout = getInt("calculation-timeout", calculationTimeout);
saveDir = getString("schematic-save-dir", saveDir);
scriptsDir = getString("craftscript-dir", scriptsDir);
butcherDefaultRadius = getInt("butcher-default-radius", butcherDefaultRadius);
@@ -105,6 +105,8 @@ public void load() {
scriptTimeout = config.getInt("scripting.timeout", scriptTimeout);
scriptsDir = config.getString("scripting.dir", scriptsDir);
calculationTimeout = config.getInt("calculation.timeout", calculationTimeout);
saveDir = config.getString("saving.dir", saveDir);
allowSymlinks = config.getBoolean("files.allow-symbolic-links", false);
@@ -22,15 +22,33 @@
import static java.lang.Math.atan2;
import static java.lang.Math.sin;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.internal.expression.lexer.LexerException;
import com.sk89q.worldedit.internal.expression.parser.ParserException;
import com.sk89q.worldedit.internal.expression.runtime.EvaluationException;
import com.sk89q.worldedit.internal.expression.runtime.ExpressionEnvironment;
import org.junit.Test;
public class ExpressionTest {
@Before
public void setup() {
Platform mockPlat = Mockito.mock(Platform.class);
Mockito.when(mockPlat.getConfiguration()).thenReturn(new LocalConfiguration() {
@Override
public void load() {
}
});
WorldEdit.getInstance().getPlatformManager().register(mockPlat);
}
@Test
public void testEvaluate() throws ExpressionException {
// check
@@ -162,6 +180,16 @@ public void testQuery() throws Exception {
assertEquals(1, simpleEval("!queryRel(3,4,5,100,200)"), 0);
}
@Test
public void testTimeout() throws Exception {
try {
simpleEval("for(i=0;i<256;i++){for(j=0;j<256;j++){for(k=0;k<256;k++){for(l=0;l<256;l++){ln(pi)}}}}");
fail("Loop was not stopped.");
} catch (EvaluationException e) {
assertTrue(e.getMessage().contains("Calculations exceeded time limit"));
}
}
private double simpleEval(String expressionString) throws ExpressionException {
final Expression expression = compile(expressionString);

0 comments on commit 9f43963

Please sign in to comment.