浏览代码

Allow to impose memory & time limits

Stefan Siegl 10 年之前
父节点
当前提交
c17208c9c0
共有 3 个文件被更改,包括 97 次插入0 次删除
  1. 45 0
      tests/set_memory_limit_003.phpt
  2. 40 0
      tests/set_time_limit_003.phpt
  3. 12 0
      v8js.cc

+ 45 - 0
tests/set_memory_limit_003.phpt

@@ -0,0 +1,45 @@
+--TEST--
+Test V8::setMemoryLimit() : Memory limit can be imposed later
+--SKIPIF--
+<?php require_once(dirname(__FILE__) . '/skipif.inc'); ?>
+--FILE--
+<?php
+
+$JS = <<< EOT
+var jsfunc = function() {
+    PHP.imposeMemoryLimit();
+    var text = "abcdefghijklmnopqrstuvwyxz0123456789";
+    var memory = "";
+    for (var i = 0; i < 100; ++i) {
+	for (var j = 0; j < 10000; ++j) {
+            memory += text;
+	}
+	sleep(0);
+    }
+};
+jsfunc;
+EOT;
+
+$v8 = new V8Js();
+
+$v8->imposeMemoryLimit = function() use ($v8) {
+    $v8->setMemoryLimit(10000000);
+};
+
+$func = $v8->executeString($JS);
+var_dump($func);
+
+try {
+    $func();
+} catch (V8JsMemoryLimitException $e) {
+    print get_class($e); print PHP_EOL;
+    print $e->getMessage(); print PHP_EOL;
+}
+?>
+===EOF===
+--EXPECTF--
+object(V8Function)#%d (0) {
+}
+V8JsMemoryLimitException
+Script memory limit of 10000000 bytes exceeded
+===EOF===

+ 40 - 0
tests/set_time_limit_003.phpt

@@ -0,0 +1,40 @@
+--TEST--
+Test V8::setTimeLimit() : Time limit can be imposed later on
+--SKIPIF--
+<?php require_once(dirname(__FILE__) . '/skipif.inc'); ?>
+--FILE--
+<?php
+
+$JS = <<< EOT
+var jsfunc = function() {
+    PHP.imposeTimeLimit();
+    var text = "abcdefghijklmnopqrstuvwyxz0123456789";
+    for (var i = 0; i < 10000000; ++i) {
+	var encoded = encodeURI(text);
+    }
+};
+jsfunc;
+EOT;
+
+$v8 = new V8Js();
+$v8->imposeTimeLimit = function() use ($v8) {
+    $v8->setTimeLimit(100);
+};
+
+$func = $v8->executeString($JS);
+var_dump($func);
+
+try {
+    $func();
+} catch (V8JsTimeLimitException $e) {
+    print get_class($e); print PHP_EOL;
+    print $e->getMessage(); print PHP_EOL;
+}
+?>
+===EOF===
+--EXPECTF--
+object(V8Function)#%d (0) {
+}
+V8JsTimeLimitException
+Script time limit of 100 milliseconds exceeded
+===EOF===

+ 12 - 0
v8js.cc

@@ -1559,6 +1559,12 @@ static PHP_METHOD(V8Js, setTimeLimit)
 		}
 	}
 	V8JSG(timer_mutex).unlock();
+
+	if (c->in_execution && time_limit && !V8JSG(timer_thread)) {
+		/* If timer thread is not started already and we now impose a time limit
+		 * finally install the timer. */
+		V8JSG(timer_thread) = new std::thread(php_v8js_timer_thread TSRMLS_CC);
+	}
 }
 /* }}} */
 
@@ -1584,6 +1590,12 @@ static PHP_METHOD(V8Js, setMemoryLimit)
 		}
 	}
 	V8JSG(timer_mutex).unlock();
+
+	if (c->in_execution && memory_limit && !V8JSG(timer_thread)) {
+		/* If timer thread is not started already and we now impose a memory limit
+		 * finally install the timer. */
+		V8JSG(timer_thread) = new std::thread(php_v8js_timer_thread TSRMLS_CC);
+	}
 }
 /* }}} */