浏览代码

Merge pull request #132 from stesie/code-cleanup

Code cleanup
Patrick Reilly 10 年之前
父节点
当前提交
bb95374985
共有 22 个文件被更改,包括 2822 次插入2417 次删除
  1. 14 3
      config.m4
  2. 1 1
      config.w32
  3. 9 117
      php_v8js_macros.h
  4. 8 2181
      v8js.cc
  5. 21 21
      v8js_array_access.cc
  6. 6 6
      v8js_array_access.h
  7. 1151 0
      v8js_class.cc
  8. 80 0
      v8js_class.h
  9. 4 4
      v8js_commonjs.cc
  10. 11 11
      v8js_convert.cc
  11. 244 0
      v8js_exceptions.cc
  12. 36 0
      v8js_exceptions.h
  13. 8 10
      v8js_methods.cc
  14. 56 55
      v8js_object_export.cc
  15. 2 2
      v8js_object_export.h
  16. 143 0
      v8js_timer.cc
  17. 39 0
      v8js_timer.h
  18. 270 0
      v8js_v8.cc
  19. 81 0
      v8js_v8.h
  20. 588 0
      v8js_v8object_class.cc
  21. 44 0
      v8js_v8object_class.h
  22. 6 6
      v8js_variables.cc

+ 14 - 3
config.m4

@@ -1,5 +1,3 @@
-dnl $Id$
-
 PHP_ARG_WITH(v8js, for V8 Javascript Engine,
 [  --with-v8js           Include V8 JavaScript Engine])
 
@@ -123,7 +121,20 @@ AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include <v8-debug.h>]],
     CPPFLAGS=$old_CPPFLAGS
   ]);
   
-  PHP_NEW_EXTENSION(v8js, v8js.cc v8js_array_access.cc v8js_convert.cc v8js_methods.cc v8js_object_export.cc v8js_variables.cc v8js_commonjs.cc, $ext_shared, , "-std="$ac_cv_v8_cstd)
+  PHP_NEW_EXTENSION(v8js, [	\
+    v8js_array_access.cc	\
+    v8js.cc					\
+    v8js_class.cc			\
+    v8js_commonjs.cc		\
+    v8js_convert.cc			\
+    v8js_exceptions.cc		\
+    v8js_methods.cc			\
+    v8js_object_export.cc	\
+	v8js_timer.cc			\
+	v8js_v8.cc				\
+    v8js_v8object_class.cc	\
+    v8js_variables.cc		\
+  ], $ext_shared, , "-std="$ac_cv_v8_cstd)
 
   PHP_ADD_MAKEFILE_FRAGMENT
 fi

+ 1 - 1
config.w32

@@ -13,7 +13,7 @@ if (PHP_V8JS != "no") {
 		AC_DEFINE("PHP_V8_API_VERSION", "3017015", "", false);
 		AC_DEFINE("PHP_V8_VERSION", "3.17.15", "", true);
 
-		EXTENSION("v8js", "v8js.cc v8js_array_access.cc v8js_commonjs.cc v8js_convert.cc v8js_methods.cc v8js_object_export.cc v8js_variables.cc", "yes");
+		EXTENSION("v8js", "v8js_array_access.cc v8js.cc v8js_class.cc v8js_commonjs.cc v8js_convert.cc v8js_exceptions.cc v8js_methods.cc v8js_object_export.cc v8js_timer.cc v8js_v8.cc v8js_v8object_class.cc v8js_variables.cc", "yes");
 
 	} else {
 		WARNING("v8js not enabled, headers or libs not found");

+ 9 - 117
php_v8js_macros.h

@@ -11,8 +11,6 @@
   +----------------------------------------------------------------------+
 */
 
-/* $Id$ */
-
 #ifndef PHP_V8JS_MACROS_H
 #define PHP_V8JS_MACROS_H
 
@@ -42,6 +40,10 @@ extern "C" {
 #include <vector>
 #include <mutex>
 
+#include "v8js_class.h"
+#include "v8js_v8.h"
+#include "v8js_timer.h"
+
 #ifndef PATH_MAX
 /* Some platforms (Windows among others) don't have a PATH_MAX, for the moment
  * just assume an arbitrary upper bound of 4096 chars.
@@ -53,27 +55,6 @@ extern "C" {
 /* V8Js Version */
 #define V8JS_VERSION "0.1.5"
 
-/* Helper macros */
-#define V8JS_SYM(v)			v8::String::NewFromUtf8(isolate, v, v8::String::kInternalizedString, sizeof(v) - 1)
-#define V8JS_SYML(v, l)		v8::String::NewFromUtf8(isolate, v, v8::String::kInternalizedString, l)
-#define V8JS_STR(v)			v8::String::NewFromUtf8(isolate, v)
-#define V8JS_STRL(v, l)		v8::String::NewFromUtf8(isolate, v, v8::String::kNormalString, l)
-#define V8JS_INT(v)			v8::Integer::New(isolate, v)
-#define V8JS_UINT(v)		v8::Integer::NewFromUnsigned(isolate, v)
-#define V8JS_FLOAT(v)		v8::Number::New(isolate, v)
-#define V8JS_BOOL(v)		((v)?v8::True(isolate):v8::False(isolate))
-#define V8JS_DATE(v)		v8::Date::New(isolate, v)
-#define V8JS_NULL			v8::Null(isolate)
-#define V8JS_UNDEFINED		v8::Undefined(isolate)
-#define V8JS_MN(name)		v8js_method_##name
-#define V8JS_METHOD(name)	void V8JS_MN(name)(const v8::FunctionCallbackInfo<v8::Value>& info)
-#define V8JS_THROW(isolate, type, message, message_len)	(isolate)->ThrowException(v8::Exception::type(V8JS_STRL(message, message_len)))
-#define V8JS_GLOBAL(isolate)			((isolate)->GetCurrentContext()->Global())
-
-/* Abbreviate long type names */
-typedef v8::Persistent<v8::FunctionTemplate, v8::CopyablePersistentTraits<v8::FunctionTemplate> > v8js_tmpl_t;
-typedef v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object> > v8js_persistent_obj_t;
-
 /* Hidden field name used to link JS wrappers with underlying PHP object */
 #define PHPJS_OBJECT_KEY "phpjs::object"
 
@@ -111,104 +92,23 @@ typedef v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object> > v8
 #define V8JS_DEBUG_AUTO_BREAK_ONCE		1
 #define V8JS_DEBUG_AUTO_BREAK_ALWAYS	2
 
-/* Extracts a C string from a V8 Utf8Value. */
-static inline const char * ToCString(const v8::String::Utf8Value &value) /* {{{ */
-{
-	return *value ? *value : "<string conversion failed>";
-}
-/* }}} */
-
-/* Extern Class entries */
-extern zend_class_entry *php_ce_v8_object;
-extern zend_class_entry *php_ce_v8_function;
-
-/* Create PHP V8 object */
-void php_v8js_create_v8(zval *, v8::Handle<v8::Value>, int, v8::Isolate * TSRMLS_DC);
-
-/* Fetch V8 object properties */
-int php_v8js_v8_get_properties_hash(v8::Handle<v8::Value>, HashTable *, int, v8::Isolate * TSRMLS_DC);
-
 /* Convert zval into V8 value */
 v8::Handle<v8::Value> zval_to_v8js(zval *, v8::Isolate * TSRMLS_DC);
 
 /* Convert V8 value into zval */
 int v8js_to_zval(v8::Handle<v8::Value>, zval *, int, v8::Isolate * TSRMLS_DC);
 
-struct php_v8js_accessor_ctx
+struct v8js_accessor_ctx
 {
     char *variable_name_string;
     uint variable_name_string_len;
     v8::Isolate *isolate;
 };
 
-void php_v8js_accessor_ctx_dtor(php_v8js_accessor_ctx * TSRMLS_DC);
+void v8js_accessor_ctx_dtor(v8js_accessor_ctx * TSRMLS_DC);
 
 /* Register accessors into passed object */
-void php_v8js_register_accessors(std::vector<php_v8js_accessor_ctx*> *accessor_list, v8::Local<v8::FunctionTemplate>, zval *, v8::Isolate * TSRMLS_DC);
-
-struct php_v8js_object;
-
-/* {{{ Context container */
-struct php_v8js_ctx {
-  zend_object std;
-  v8::Persistent<v8::String> object_name;
-  v8::Persistent<v8::Context> context;
-  zend_bool report_uncaught;
-  zval *pending_exception;
-  int in_execution;
-  v8::Isolate *isolate;
-
-  long time_limit;
-  bool time_limit_hit;
-  long memory_limit;
-  bool memory_limit_hit;
-
-  v8::Persistent<v8::FunctionTemplate> global_template;
-
-  zval *module_loader;
-  std::vector<char *> modules_stack;
-  std::vector<char *> modules_base;
-  std::map<char *, v8js_persistent_obj_t> modules_loaded;
-  std::map<const char *,v8js_tmpl_t> template_cache;
-
-  std::map<zval *, v8js_persistent_obj_t> weak_objects;
-  std::map<v8js_tmpl_t *, v8js_persistent_obj_t> weak_closures;
-
-  std::list<php_v8js_object *> php_v8js_objects;
-
-  std::vector<php_v8js_accessor_ctx *> accessor_list;
-  char *tz;
-#ifdef ZTS
-  void ***zts_ctx;
-#endif
-};
-/* }}} */
-
-#ifdef ZTS
-# define V8JS_TSRMLS_FETCH() TSRMLS_FETCH_FROM_CTX(((php_v8js_ctx *) isolate->GetData(0))->zts_ctx);
-#else
-# define V8JS_TSRMLS_FETCH()
-#endif
-
-// Timer context
-struct php_v8js_timer_ctx
-{
-  long time_limit;
-  long memory_limit;
-  std::chrono::time_point<std::chrono::high_resolution_clock> time_point;
-  php_v8js_ctx *v8js_ctx;
-  bool killed;
-};
-
-/* {{{ Object container */
-struct php_v8js_object {
-	zend_object std;
-	v8::Persistent<v8::Value> v8obj;
-	int flags;
-	struct php_v8js_ctx *ctx;
-	HashTable *properties;
-};
-/* }}} */
+void v8js_register_accessors(std::vector<v8js_accessor_ctx*> *accessor_list, v8::Local<v8::FunctionTemplate>, zval *, v8::Isolate * TSRMLS_DC);
 
 /* Resource declaration */
 
@@ -223,7 +123,7 @@ ZEND_BEGIN_MODULE_GLOBALS(v8js)
   bool use_array_access; /* Convert ArrayAccess, Countable objects to array-like objects */
 
   // Timer thread globals
-  std::deque<php_v8js_timer_ctx *> timer_stack;
+  std::deque<v8js_timer_ctx *> timer_stack;
   std::thread *timer_thread;
   std::mutex timer_mutex;
   bool timer_stop;
@@ -242,15 +142,7 @@ ZEND_EXTERN_MODULE_GLOBALS(v8js)
 #endif
 
 /* Register builtin methods into passed object */
-void php_v8js_register_methods(v8::Handle<v8::ObjectTemplate>, php_v8js_ctx *c);
-
-typedef struct _php_v8js_script {
-	char *name;
-	v8::Isolate *isolate;	
-	v8::Persistent<v8::Script, v8::CopyablePersistentTraits<v8::Script>> *script;
-} php_v8js_script;
-
-static void php_v8js_script_free(php_v8js_script *res, bool dispose_persistent);
+void v8js_register_methods(v8::Handle<v8::ObjectTemplate>, v8js_ctx *c);
 
 #endif	/* PHP_V8JS_MACROS_H */
 

文件差异内容过多而无法显示
+ 8 - 2181
v8js.cc


+ 21 - 21
v8js_array_access.cc

@@ -27,7 +27,7 @@ extern "C" {
 #include "v8js_object_export.h"
 
 
-static zval *php_v8js_array_access_dispatch(zval *object, const char *method_name, int param_count,
+static zval *v8js_array_access_dispatch(zval *object, const char *method_name, int param_count,
 											uint32_t index, zval *zvalue_ptr TSRMLS_DC) /* {{{ */
 {
 	zend_class_entry *ce = Z_OBJCE_P(object);
@@ -66,7 +66,7 @@ static zval *php_v8js_array_access_dispatch(zval *object, const char *method_nam
 
 
 
-void php_v8js_array_access_getter(uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& info) /* {{{ */
+void v8js_array_access_getter(uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& info) /* {{{ */
 {
 	v8::Isolate *isolate = info.GetIsolate();
 	v8::Local<v8::Object> self = info.Holder();
@@ -76,7 +76,7 @@ void php_v8js_array_access_getter(uint32_t index, const v8::PropertyCallbackInfo
 	v8::Local<v8::Value> php_object = self->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY));
 	zval *object = reinterpret_cast<zval *>(v8::External::Cast(*php_object)->Value());
 
-	zval *php_value = php_v8js_array_access_dispatch(object, "offsetGet", 1, index, NULL TSRMLS_CC);
+	zval *php_value = v8js_array_access_dispatch(object, "offsetGet", 1, index, NULL TSRMLS_CC);
 	v8::Local<v8::Value> ret_value = zval_to_v8js(php_value, isolate TSRMLS_CC);
 	zval_ptr_dtor(&php_value);
 
@@ -84,7 +84,7 @@ void php_v8js_array_access_getter(uint32_t index, const v8::PropertyCallbackInfo
 }
 /* }}} */
 
-void php_v8js_array_access_setter(uint32_t index, v8::Local<v8::Value> value,
+void v8js_array_access_setter(uint32_t index, v8::Local<v8::Value> value,
 								  const v8::PropertyCallbackInfo<v8::Value>& info) /* {{{ */
 {
 	v8::Isolate *isolate = info.GetIsolate();
@@ -102,7 +102,7 @@ void php_v8js_array_access_setter(uint32_t index, v8::Local<v8::Value> value,
 		return;
 	}
 
-	zval *php_value = php_v8js_array_access_dispatch(object, "offsetSet", 2, index, zvalue_ptr TSRMLS_CC);
+	zval *php_value = v8js_array_access_dispatch(object, "offsetSet", 2, index, zvalue_ptr TSRMLS_CC);
 	zval_ptr_dtor(&php_value);
 
 	/* simply pass back the value to tell we intercepted the call
@@ -116,9 +116,9 @@ void php_v8js_array_access_setter(uint32_t index, v8::Local<v8::Value> value,
 /* }}} */
 
 
-static int php_v8js_array_access_get_count_result(zval *object TSRMLS_DC) /* {{{ */
+static int v8js_array_access_get_count_result(zval *object TSRMLS_DC) /* {{{ */
 {
-	zval *php_value = php_v8js_array_access_dispatch(object, "count", 0, 0, NULL TSRMLS_CC);
+	zval *php_value = v8js_array_access_dispatch(object, "count", 0, 0, NULL TSRMLS_CC);
 
 	if(Z_TYPE_P(php_value) != IS_LONG) {
 		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Non-numeric return value from count() method");
@@ -132,9 +132,9 @@ static int php_v8js_array_access_get_count_result(zval *object TSRMLS_DC) /* {{{
 }
 /* }}} */
 
-static bool php_v8js_array_access_isset_p(zval *object, int index TSRMLS_DC) /* {{{ */
+static bool v8js_array_access_isset_p(zval *object, int index TSRMLS_DC) /* {{{ */
 {
-	zval *php_value = php_v8js_array_access_dispatch(object, "offsetExists", 1, index, NULL TSRMLS_CC);
+	zval *php_value = v8js_array_access_dispatch(object, "offsetExists", 1, index, NULL TSRMLS_CC);
 
 	if(Z_TYPE_P(php_value) != IS_BOOL) {
 		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Non-boolean return value from offsetExists() method");
@@ -149,7 +149,7 @@ static bool php_v8js_array_access_isset_p(zval *object, int index TSRMLS_DC) /*
 /* }}} */
 
 
-static void php_v8js_array_access_length(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& info) /* {{{ */
+static void v8js_array_access_length(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& info) /* {{{ */
 {
 	v8::Isolate *isolate = info.GetIsolate();
 	v8::Local<v8::Object> self = info.Holder();
@@ -159,12 +159,12 @@ static void php_v8js_array_access_length(v8::Local<v8::String> property, const v
 	v8::Local<v8::Value> php_object = self->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY));
 	zval *object = reinterpret_cast<zval *>(v8::External::Cast(*php_object)->Value());
 
-	int length = php_v8js_array_access_get_count_result(object TSRMLS_CC);
+	int length = v8js_array_access_get_count_result(object TSRMLS_CC);
 	info.GetReturnValue().Set(V8JS_INT(length));
 }
 /* }}} */
 
-void php_v8js_array_access_deleter(uint32_t index, const v8::PropertyCallbackInfo<v8::Boolean>& info) /* {{{ */
+void v8js_array_access_deleter(uint32_t index, const v8::PropertyCallbackInfo<v8::Boolean>& info) /* {{{ */
 {
 	v8::Isolate *isolate = info.GetIsolate();
 	v8::Local<v8::Object> self = info.Holder();
@@ -174,14 +174,14 @@ void php_v8js_array_access_deleter(uint32_t index, const v8::PropertyCallbackInf
 	v8::Local<v8::Value> php_object = self->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY));
 	zval *object = reinterpret_cast<zval *>(v8::External::Cast(*php_object)->Value());
 
-	zval *php_value = php_v8js_array_access_dispatch(object, "offsetUnset", 1, index, NULL TSRMLS_CC);
+	zval *php_value = v8js_array_access_dispatch(object, "offsetUnset", 1, index, NULL TSRMLS_CC);
 	zval_ptr_dtor(&php_value);
 
 	info.GetReturnValue().Set(V8JS_BOOL(true));
 }
 /* }}} */
 
-void php_v8js_array_access_query(uint32_t index, const v8::PropertyCallbackInfo<v8::Integer>& info) /* {{{ */
+void v8js_array_access_query(uint32_t index, const v8::PropertyCallbackInfo<v8::Integer>& info) /* {{{ */
 {
 	v8::Isolate *isolate = info.GetIsolate();
 	v8::Local<v8::Object> self = info.Holder();
@@ -193,14 +193,14 @@ void php_v8js_array_access_query(uint32_t index, const v8::PropertyCallbackInfo<
 
 	/* If index is set, then return an integer encoding a v8::PropertyAttribute;
 	 * otherwise we're expected to return an empty handle. */
-	if(php_v8js_array_access_isset_p(object, index TSRMLS_CC)) {
+	if(v8js_array_access_isset_p(object, index TSRMLS_CC)) {
 		info.GetReturnValue().Set(V8JS_UINT(v8::PropertyAttribute::None));
 	}
 }
 /* }}} */
 
 
-void php_v8js_array_access_enumerator(const v8::PropertyCallbackInfo<v8::Array>& info) /* {{{ */
+void v8js_array_access_enumerator(const v8::PropertyCallbackInfo<v8::Array>& info) /* {{{ */
 {
 	v8::Isolate *isolate = info.GetIsolate();
 	v8::Local<v8::Object> self = info.Holder();
@@ -210,13 +210,13 @@ void php_v8js_array_access_enumerator(const v8::PropertyCallbackInfo<v8::Array>&
 	v8::Local<v8::Value> php_object = self->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY));
 	zval *object = reinterpret_cast<zval *>(v8::External::Cast(*php_object)->Value());
 
-	int length = php_v8js_array_access_get_count_result(object TSRMLS_CC);
+	int length = v8js_array_access_get_count_result(object TSRMLS_CC);
 	v8::Local<v8::Array> result = v8::Array::New(isolate, length);
 
 	int i = 0;
 
 	for(int j = 0; j < length; j ++) {
-		if(php_v8js_array_access_isset_p(object, j TSRMLS_CC)) {
+		if(v8js_array_access_isset_p(object, j TSRMLS_CC)) {
 			result->Set(i ++, V8JS_INT(j));
 		}
 	}
@@ -228,17 +228,17 @@ void php_v8js_array_access_enumerator(const v8::PropertyCallbackInfo<v8::Array>&
 
 
 
-void php_v8js_array_access_named_getter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */
+void v8js_array_access_named_getter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */
 {
 	v8::String::Utf8Value cstr(property);
 	const char *name = ToCString(cstr);
 
 	if(strcmp(name, "length") == 0) {
-		php_v8js_array_access_length(property, info);
+		v8js_array_access_length(property, info);
 		return;
 	}
 
-	v8::Local<v8::Value> ret_value = php_v8js_named_property_callback(property, info, V8JS_PROP_GETTER);
+	v8::Local<v8::Value> ret_value = v8js_named_property_callback(property, info, V8JS_PROP_GETTER);
 
 	if(ret_value.IsEmpty()) {
 		v8::Isolate *isolate = info.GetIsolate();

+ 6 - 6
v8js_array_access.h

@@ -14,18 +14,18 @@
 #define V8JS_ARRAY_ACCESS_H
 
 /* Indexed Property Handlers */
-void php_v8js_array_access_getter(uint32_t index,
+void v8js_array_access_getter(uint32_t index,
 				  const v8::PropertyCallbackInfo<v8::Value>& info);
-void php_v8js_array_access_setter(uint32_t index, v8::Local<v8::Value> value,
+void v8js_array_access_setter(uint32_t index, v8::Local<v8::Value> value,
 				  const v8::PropertyCallbackInfo<v8::Value>& info);
-void php_v8js_array_access_enumerator(const v8::PropertyCallbackInfo<v8::Array>& info);
-void php_v8js_array_access_deleter(uint32_t index,
+void v8js_array_access_enumerator(const v8::PropertyCallbackInfo<v8::Array>& info);
+void v8js_array_access_deleter(uint32_t index,
 				   const v8::PropertyCallbackInfo<v8::Boolean>& info);
-void php_v8js_array_access_query(uint32_t index,
+void v8js_array_access_query(uint32_t index,
 				 const v8::PropertyCallbackInfo<v8::Integer>& info);
 
 /* Named Property Handlers */
-void php_v8js_array_access_named_getter(v8::Local<v8::String> property,
+void v8js_array_access_named_getter(v8::Local<v8::String> property,
 					const v8::PropertyCallbackInfo<v8::Value> &info);
 
 #endif /* V8JS_ARRAY_ACCESS_H */

+ 1151 - 0
v8js_class.cc

@@ -0,0 +1,1151 @@
+/*
+  +----------------------------------------------------------------------+
+  | PHP Version 5                                                        |
+  +----------------------------------------------------------------------+
+  | Copyright (c) 1997-2013 The PHP Group                                |
+  +----------------------------------------------------------------------+
+  | http://www.opensource.org/licenses/mit-license.php  MIT License      |
+  +----------------------------------------------------------------------+
+  | Author: Jani Taskinen <[email protected]>                         |
+  | Author: Patrick Reilly <[email protected]>                             |
+  +----------------------------------------------------------------------+
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+extern "C" {
+#include "php.h"
+#include "ext/date/php_date.h"
+#include "ext/standard/php_string.h"
+#include "zend_interfaces.h"
+#include "zend_closures.h"
+#include "ext/spl/spl_exceptions.h"
+#include "zend_exceptions.h"
+}
+
+#include "php_v8js_macros.h"
+#include "v8js_v8.h"
+#include "v8js_exceptions.h"
+#include "v8js_v8object_class.h"
+#include "v8js_timer.h"
+
+#include <functional>
+
+#define PHP_V8JS_SCRIPT_RES_NAME "V8Js script"
+
+/* {{{ Class Entries */
+static zend_class_entry *php_ce_v8js;
+/* }}} */
+
+/* {{{ Object Handlers */
+static zend_object_handlers v8js_object_handlers;
+/* }}} */
+
+typedef struct _v8js_script {
+	char *name;
+	v8::Isolate *isolate;	
+	v8::Persistent<v8::Script, v8::CopyablePersistentTraits<v8::Script>> *script;
+} v8js_script;
+
+static void v8js_script_free(v8js_script *res, bool dispose_persistent);
+
+int le_v8js_script;
+
+/* {{{ Extension container */
+struct v8js_jsext {
+	zend_bool auto_enable;
+	HashTable *deps_ht;
+	const char **deps;
+	int deps_count;
+	char *name;
+	char *source;
+};
+/* }}} */
+
+#ifdef ENABLE_DEBUGGER_SUPPORT
+static v8js_ctx *v8js_debug_context;
+static int v8js_debug_auto_break_mode;
+#endif
+
+static void v8js_free_storage(void *object TSRMLS_DC) /* {{{ */
+{
+	v8js_ctx *c = (v8js_ctx *) object;
+
+	zend_object_std_dtor(&c->std TSRMLS_CC);
+
+	if (c->pending_exception) {
+		zval_ptr_dtor(&c->pending_exception);
+	}
+
+	if (c->module_loader) {
+		zval_ptr_dtor(&c->module_loader);
+	}
+
+	/* Delete PHP global object from JavaScript */
+	if (!c->context.IsEmpty()) {
+		v8::Locker locker(c->isolate);
+		v8::Isolate::Scope isolate_scope(c->isolate);
+		v8::HandleScope handle_scope(c->isolate);
+		v8::Local<v8::Context> v8_context = v8::Local<v8::Context>::New(c->isolate, c->context);
+		v8::Context::Scope context_scope(v8_context);
+		v8::Local<v8::String> object_name_js = v8::Local<v8::String>::New(c->isolate, c->object_name);
+		V8JS_GLOBAL(c->isolate)->Delete(object_name_js);
+	}
+
+	c->object_name.Reset();
+	c->object_name.~Persistent();
+	c->global_template.Reset();
+	c->global_template.~Persistent();
+
+	/* Clear persistent handles in template cache */
+	for (std::map<const char *,v8js_tmpl_t>::iterator it = c->template_cache.begin();
+		 it != c->template_cache.end(); ++it) {
+		it->second.Reset();
+	}
+	c->template_cache.~map();
+
+	/* Clear contexts */
+	for (std::vector<v8js_accessor_ctx*>::iterator it = c->accessor_list.begin();
+		 it != c->accessor_list.end(); ++it) {
+		v8js_accessor_ctx_dtor(*it TSRMLS_CC);
+	}
+	c->accessor_list.~vector();
+
+	/* Clear global object, dispose context */
+	if (!c->context.IsEmpty()) {
+		c->context.Reset();
+	}
+	c->context.~Persistent();
+
+	/* Dispose yet undisposed weak refs */
+	for (std::map<zval *, v8js_persistent_obj_t>::iterator it = c->weak_objects.begin();
+		 it != c->weak_objects.end(); ++it) {
+		zval *value = it->first;
+		zval_ptr_dtor(&value);
+		c->isolate->AdjustAmountOfExternalAllocatedMemory(-1024);
+		it->second.Reset();
+	}
+	c->weak_objects.~map();
+
+	for (std::map<v8js_tmpl_t *, v8js_persistent_obj_t>::iterator it = c->weak_closures.begin();
+		 it != c->weak_closures.end(); ++it) {
+		v8js_tmpl_t *persist_tpl_ = it->first;
+		persist_tpl_->Reset();
+		delete persist_tpl_;
+		it->second.Reset();
+	}
+	c->weak_closures.~map();
+
+	for (std::list<v8js_v8object *>::iterator it = c->v8js_v8objects.begin();
+		 it != c->v8js_v8objects.end(); it ++) {
+		(*it)->v8obj.Reset();
+		(*it)->ctx = NULL;
+	}
+	c->v8js_v8objects.~list();
+
+	/* Clear persistent handles in module cache */
+	for (std::map<char *, v8js_persistent_obj_t>::iterator it = c->modules_loaded.begin();
+		 it != c->modules_loaded.end(); ++it) {
+		it->second.Reset();
+	}
+	c->modules_loaded.~map();
+
+	if(c->isolate) {
+		/* c->isolate is initialized by V8Js::__construct, but __wakeup calls
+		 * are not fully constructed and hence this would cause a NPE. */
+		c->isolate->Dispose();
+	}
+
+	if(c->tz != NULL) {
+		free(c->tz);
+	}
+
+	c->modules_stack.~vector();
+	c->modules_base.~vector();
+
+	efree(object);
+}
+/* }}} */
+
+static zend_object_value v8js_new(zend_class_entry *ce TSRMLS_DC) /* {{{ */
+{
+	zend_object_value retval;
+	v8js_ctx *c;
+
+	c = (v8js_ctx *) ecalloc(1, sizeof(*c));
+	zend_object_std_init(&c->std, ce TSRMLS_CC);
+	TSRMLS_SET_CTX(c->zts_ctx);
+
+#if PHP_VERSION_ID >= 50400
+	object_properties_init(&c->std, ce);
+#else
+	zval *tmp;
+	zend_hash_copy(c->std.properties, &ce->default_properties,
+				   (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *));
+#endif
+
+	new(&c->object_name) v8::Persistent<v8::String>();
+	new(&c->context) v8::Persistent<v8::Context>();
+	new(&c->global_template) v8::Persistent<v8::FunctionTemplate>();
+
+	new(&c->modules_stack) std::vector<char*>();
+	new(&c->modules_base) std::vector<char*>();
+	new(&c->modules_loaded) std::map<char *, v8js_persistent_obj_t>;
+
+	new(&c->template_cache) std::map<const char *,v8js_tmpl_t>();
+	new(&c->accessor_list) std::vector<v8js_accessor_ctx *>();
+
+	new(&c->weak_closures) std::map<v8js_tmpl_t *, v8js_persistent_obj_t>();
+	new(&c->weak_objects) std::map<zval *, v8js_persistent_obj_t>();
+
+	new(&c->v8js_v8objects) std::list<v8js_v8object *>();
+
+	retval.handle = zend_objects_store_put(c, NULL, (zend_objects_free_object_storage_t) v8js_free_storage, NULL TSRMLS_CC);
+	retval.handlers = &v8js_object_handlers;
+
+	return retval;
+}
+/* }}} */
+
+static void v8js_free_ext_strarr(const char **arr, int count) /* {{{ */
+{
+	int i;
+
+	if (arr) {
+		for (i = 0; i < count; i++) {
+			if (arr[i]) {
+				free((void *) arr[i]);
+			}
+		}
+		free(arr);
+	}
+}
+/* }}} */
+
+static void v8js_jsext_dtor(v8js_jsext *jsext) /* {{{ */
+{
+	if (jsext->deps_ht) {
+		zend_hash_destroy(jsext->deps_ht);
+		free(jsext->deps_ht);
+	}
+	if (jsext->deps) {
+		v8js_free_ext_strarr(jsext->deps, jsext->deps_count);
+	}
+	free(jsext->name);
+	free(jsext->source);
+}
+/* }}} */
+
+static int v8js_create_ext_strarr(const char ***retval, int count, HashTable *ht) /* {{{ */
+{
+	const char **exts = NULL;
+	HashPosition pos;
+	zval **tmp;
+	int i = 0;
+
+	exts = (const char **) calloc(1, count * sizeof(char *));
+	zend_hash_internal_pointer_reset_ex(ht, &pos);
+	while (zend_hash_get_current_data_ex(ht, (void **) &tmp, &pos) == SUCCESS) {
+		if (Z_TYPE_PP(tmp) == IS_STRING) {
+			exts[i++] = zend_strndup(Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp));
+		} else {
+			v8js_free_ext_strarr(exts, i);
+			return FAILURE;
+		}
+		zend_hash_move_forward_ex(ht, &pos);
+	}
+	*retval = exts;
+
+	return SUCCESS;
+}
+/* }}} */
+
+static void v8js_fatal_error_handler(const char *location, const char *message) /* {{{ */
+{
+	v8::Isolate *isolate = v8::Isolate::GetCurrent();
+	if (isolate) {
+		isolate->Exit();
+	}
+	if (location) {
+		zend_error(E_ERROR, "%s %s", location, message);
+	} else {
+		zend_error(E_ERROR, "%s", message);
+	}
+}
+/* }}} */
+
+#ifdef ENABLE_DEBUGGER_SUPPORT
+static void DispatchDebugMessages() { /* {{{ */
+	if(v8js_debug_context == NULL) {
+		return;
+	}
+
+	v8::Isolate* isolate = v8js_debug_context->isolate;
+	v8::Isolate::Scope isolate_scope(isolate);
+
+	v8::HandleScope handle_scope(isolate);
+	v8::Local<v8::Context> context =
+		v8::Local<v8::Context>::New(isolate, v8js_debug_context->context);
+	v8::Context::Scope scope(context);
+
+	v8::Debug::ProcessDebugMessages();
+}
+/* }}} */
+#endif  /* ENABLE_DEBUGGER_SUPPORT */
+
+/* {{{ proto void V8Js::__construct([string object_name [, array variables [, array extensions [, bool report_uncaught_exceptions]]])
+   __construct for V8Js */
+static PHP_METHOD(V8Js, __construct)
+{
+	char *object_name = NULL, *class_name = NULL;
+	int object_name_len = 0, free = 0;
+	zend_uint class_name_len = 0;
+	zend_bool report_uncaught = 1;
+	zval *vars_arr = NULL, *exts_arr = NULL;
+	const char **exts = NULL;
+	int exts_count = 0;
+
+	v8js_ctx *c = (v8js_ctx *) zend_object_store_get_object(getThis() TSRMLS_CC);
+
+	if (!c->context.IsEmpty()) {
+		/* called __construct() twice, bail out */
+		return;
+	}
+
+	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|saab", &object_name, &object_name_len, &vars_arr, &exts_arr, &report_uncaught) == FAILURE) {
+		return;
+	}
+
+	/* Initialize V8 */
+	v8js_v8_init(TSRMLS_C);
+
+	/* Throw PHP exception if uncaught exceptions exist */
+	c->report_uncaught = report_uncaught;
+	c->pending_exception = NULL;
+	c->in_execution = 0;
+	c->isolate = v8::Isolate::New();
+	c->isolate->SetData(0, c);
+
+	c->time_limit = 0;
+	c->time_limit_hit = false;
+	c->memory_limit = 0;
+	c->memory_limit_hit = false;
+
+	c->module_loader = NULL;
+
+	/* Include extensions used by this context */
+	/* Note: Extensions registered with auto_enable do not need to be added separately like this. */
+	if (exts_arr)
+	{
+		exts_count = zend_hash_num_elements(Z_ARRVAL_P(exts_arr));
+		if (v8js_create_ext_strarr(&exts, exts_count, Z_ARRVAL_P(exts_arr)) == FAILURE) {
+			php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid extensions array passed");
+			return;
+		}
+	}
+
+	/* Declare configuration for extensions */
+	v8::ExtensionConfiguration extension_conf(exts_count, exts);
+
+	// Isolate execution
+	v8::Isolate *isolate = c->isolate;
+	v8::Locker locker(isolate);
+	v8::Isolate::Scope isolate_scope(isolate);
+
+	/* Handle scope */
+	v8::HandleScope handle_scope(isolate);
+
+	/* Redirect fatal errors to PHP error handler */
+	// This needs to be done within the context isolate
+	v8::V8::SetFatalErrorHandler(v8js_fatal_error_handler);
+
+	/* Create global template for global object */
+	// Now we are using multiple isolates this needs to be created for every context
+
+	v8::Local<v8::FunctionTemplate> tpl = v8::FunctionTemplate::New(c->isolate, 0);
+
+	tpl->SetClassName(V8JS_SYM("V8Js"));
+	c->global_template.Reset(isolate, tpl);
+
+	/* Register builtin methods */
+	v8js_register_methods(tpl->InstanceTemplate(), c);
+
+	/* Create context */
+	v8::Local<v8::Context> context = v8::Context::New(isolate, &extension_conf, tpl->InstanceTemplate());
+	context->SetAlignedPointerInEmbedderData(1, c);
+	c->context.Reset(isolate, context);
+
+	if (exts) {
+		v8js_free_ext_strarr(exts, exts_count);
+	}
+
+	/* If extensions have errors, context will be empty. (NOTE: This is V8 stuff, they expect the passed sources to compile :) */
+	if (c->context.IsEmpty()) {
+		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to create V8 context. Check that registered extensions do not have errors.");
+		ZVAL_NULL(getThis());
+		return;
+	}
+
+	/* Enter context */
+	v8::Context::Scope context_scope(context);
+
+	/* Create the PHP container object's function template */
+	v8::Local<v8::FunctionTemplate> php_obj_t = v8::FunctionTemplate::New(isolate, 0);
+
+	/* Set class name for PHP object */
+#if PHP_VERSION_ID >= 50400
+	free = !zend_get_object_classname(getThis(), const_cast<const char**>(&class_name), &class_name_len TSRMLS_CC);
+#else
+	free = !zend_get_object_classname(getThis(), &class_name, &class_name_len TSRMLS_CC);
+#endif
+	php_obj_t->SetClassName(V8JS_SYML(class_name, class_name_len));
+
+	if (free) {
+		efree(class_name);
+	}
+
+	/* Register Get accessor for passed variables */
+	if (vars_arr && zend_hash_num_elements(Z_ARRVAL_P(vars_arr)) > 0) {
+		v8js_register_accessors(&c->accessor_list, php_obj_t, vars_arr, isolate TSRMLS_CC);
+	}
+
+	/* Set name for the PHP JS object */
+	v8::Local<v8::String> object_name_js = (object_name_len) ? V8JS_SYML(object_name, object_name_len) : V8JS_SYM("PHP");
+	c->object_name.Reset(isolate, object_name_js);
+
+	/* Add the PHP object into global object */
+	v8::Local<v8::Object> php_obj = php_obj_t->InstanceTemplate()->NewInstance();
+	V8JS_GLOBAL(isolate)->ForceSet(object_name_js, php_obj, v8::ReadOnly);
+
+	/* Export public property values */
+	HashTable *properties = zend_std_get_properties(getThis() TSRMLS_CC);
+	HashPosition pos;
+	zval **value;
+	ulong index;
+	char *member;
+	uint member_len;
+
+	for(zend_hash_internal_pointer_reset_ex(properties, &pos);
+		zend_hash_get_current_data_ex(properties, (void **) &value, &pos) == SUCCESS;
+		zend_hash_move_forward_ex(properties, &pos)) {
+		if(zend_hash_get_current_key_ex(properties, &member, &member_len, &index, 0, &pos) != HASH_KEY_IS_STRING) {
+			continue;
+		}
+
+		zval zmember;
+		INIT_ZVAL(zmember);
+		ZVAL_STRING(&zmember, member, 0);
+
+		zend_property_info *property_info = zend_get_property_info(c->std.ce, &zmember, 1 TSRMLS_CC);
+		if(property_info && property_info->flags & ZEND_ACC_PUBLIC) {
+			/* Write value to PHP JS object */
+			php_obj->ForceSet(V8JS_SYML(member, member_len - 1), zval_to_v8js(*value, isolate TSRMLS_CC), v8::ReadOnly);
+		}
+	}
+
+
+}
+/* }}} */
+
+/* {{{ proto V8JS::__sleep()
+ */
+PHP_METHOD(V8Js, __sleep)
+{
+	zend_throw_exception(php_ce_v8js_exception,
+		"You cannot serialize or unserialize V8Js instances", 0 TSRMLS_CC);
+	RETURN_FALSE;
+}
+/* }}} */
+
+/* {{{ proto V8JS::__wakeup()
+ */
+PHP_METHOD(V8Js, __wakeup)
+{
+	zend_throw_exception(php_ce_v8js_exception,
+		"You cannot serialize or unserialize V8Js instances", 0 TSRMLS_CC);
+	RETURN_FALSE;
+}
+/* }}} */
+
+static void v8js_compile_script(zval *this_ptr, const char *str, int str_len, const char *identifier, int identifier_len, v8js_script **ret TSRMLS_DC)
+{
+	v8js_script *res = NULL;
+
+	V8JS_BEGIN_CTX(c, this_ptr)
+
+	/* Catch JS exceptions */
+	v8::TryCatch try_catch;
+
+	/* Set script identifier */
+	v8::Local<v8::String> sname = identifier_len ? V8JS_SYML(identifier, identifier_len) : V8JS_SYM("V8Js::compileString()");
+
+	/* Compiles a string context independently. TODO: Add a php function which calls this and returns the result as resource which can be executed later. */
+	v8::Local<v8::String> source = V8JS_STRL(str, str_len);
+	v8::Local<v8::Script> script = v8::Script::Compile(source, sname);
+
+	/* Compile errors? */
+	if (script.IsEmpty()) {
+		v8js_throw_script_exception(&try_catch TSRMLS_CC);
+		return;
+	}
+	res = (v8js_script *)emalloc(sizeof(v8js_script));
+	res->script = new v8::Persistent<v8::Script, v8::CopyablePersistentTraits<v8::Script>>(c->isolate, script);
+
+	v8::String::Utf8Value _sname(sname);
+	res->name = estrndup(ToCString(_sname), _sname.length());
+	res->isolate = c->isolate;
+	*ret = res;
+	return;
+}
+
+static void v8js_execute_script(zval *this_ptr, v8js_script *res, long flags, long time_limit, long memory_limit, zval **return_value TSRMLS_DC)
+{
+	v8js_ctx *c = (v8js_ctx *) zend_object_store_get_object(getThis() TSRMLS_CC);
+
+	if (res->isolate != c->isolate) {
+		zend_error(E_WARNING, "Script resource from wrong V8Js object passed");
+		ZVAL_BOOL(*return_value, 0);
+		return;
+	}
+
+	if (!c->in_execution && time_limit == 0) {
+		time_limit = c->time_limit;
+	}
+
+	if (!c->in_execution && memory_limit == 0) {
+		memory_limit = c->memory_limit;
+	}
+
+	std::function< v8::Local<v8::Value>(v8::Isolate *) > v8_call = [res](v8::Isolate *isolate) {
+		v8::Local<v8::Script> script = v8::Local<v8::Script>::New(isolate, *res->script);
+		return script->Run();
+	};
+
+	v8js_v8_call(c, return_value, flags, time_limit, memory_limit, v8_call TSRMLS_CC);
+}
+
+/* {{{ proto mixed V8Js::executeString(string script [, string identifier [, int flags]])
+ */
+static PHP_METHOD(V8Js, executeString)
+{
+	char *str = NULL, *identifier = NULL, *tz = NULL;
+	int str_len = 0, identifier_len = 0;
+	long flags = V8JS_FLAG_NONE, time_limit = 0, memory_limit = 0;
+	v8js_script *res = NULL;
+
+	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|slll", &str, &str_len, &identifier, &identifier_len, &flags, &time_limit, &memory_limit) == FAILURE) {
+		return;
+	}
+
+	v8js_compile_script(getThis(), str, str_len, identifier, identifier_len, &res TSRMLS_CC);
+	if (!res) {
+		RETURN_FALSE;
+	}
+	v8js_execute_script(getThis(), res, flags, time_limit, memory_limit, &return_value TSRMLS_CC);
+	v8js_script_free(res, true);
+	efree(res);
+}
+/* }}} */
+
+
+/* {{{ proto mixed V8Js::compileString(string script [, string identifier])
+ */
+static PHP_METHOD(V8Js, compileString)
+{
+	char *str = NULL, *identifier = NULL;
+	int str_len = 0, identifier_len = 0;
+	v8js_script *res = NULL;
+
+	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &str, &str_len, &identifier, &identifier_len) == FAILURE) {
+		return;
+	}
+
+	v8js_compile_script(getThis(), str, str_len, identifier, identifier_len, &res TSRMLS_CC);
+	if (res) {
+		ZEND_REGISTER_RESOURCE(return_value, res, le_v8js_script);
+	}
+	return;
+}
+
+/* }}} */
+
+/* {{{ proto mixed V8Js::executeScript(resource script [, int flags]])
+ */
+static PHP_METHOD(V8Js, executeScript)
+{
+	long flags = V8JS_FLAG_NONE, time_limit = 0, memory_limit = 0;
+	zval *zscript;
+	v8js_script *res;
+
+	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|lll", &zscript, &flags, &time_limit, &memory_limit) == FAILURE) {
+		return;
+	}
+
+	ZEND_FETCH_RESOURCE(res, v8js_script*, &zscript, -1, PHP_V8JS_SCRIPT_RES_NAME, le_v8js_script);
+	ZEND_VERIFY_RESOURCE(res);
+
+	v8js_execute_script(getThis(), res, flags, time_limit, memory_limit, &return_value TSRMLS_CC);
+}
+/* }}} */
+
+/* {{{ proto mixed V8Js::checkString(string script)
+ */
+static PHP_METHOD(V8Js, checkString)
+{
+	char *str = NULL;
+	int str_len = 0;
+	const char *identifier = "V8Js::checkString()";
+	int identifier_len = 19;
+
+	v8js_script *res = NULL;
+
+	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &str, &str_len) == FAILURE) {
+		return;
+	}
+
+	v8js_compile_script(getThis(), str, str_len, identifier, identifier_len, &res TSRMLS_CC);
+	if (!res) {
+		RETURN_FALSE;
+	}
+
+	v8js_script_free(res, true);
+	efree(res);
+	RETURN_TRUE;
+}
+/* }}} */
+
+
+#ifdef ENABLE_DEBUGGER_SUPPORT
+/* {{{ proto void V8Js::__destruct()
+   __destruct for V8Js */
+static PHP_METHOD(V8Js, __destruct)
+{
+	v8js_ctx *c = (v8js_ctx *) zend_object_store_get_object(getThis() TSRMLS_CC);
+
+	if(!c->isolate) {
+		/* c->isolate is initialized by __construct, which wasn't called if this
+		 * instance was deserialized (which we already caught in __wakeup). */
+		return;
+	}
+
+	V8JS_CTX_PROLOGUE(c);
+	if(v8js_debug_context == c) {
+		v8::Debug::DisableAgent();
+		v8js_debug_context = NULL;
+	}
+}
+/* }}} */
+
+/* {{{ proto bool V8Js::startDebugAgent(string agent_name[, int port[, int auto_break]])
+ */
+static PHP_METHOD(V8Js, startDebugAgent)
+{
+	char *str = NULL;
+	int str_len = 0;
+	long port = 0, auto_break = 0;
+
+	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sll", &str, &str_len, &port, &auto_break) == FAILURE) {
+		return;
+	}
+
+	if(!port) {
+		port = 9222;
+	}
+
+	V8JS_BEGIN_CTX(c, getThis());
+
+	if(v8js_debug_context == c) {
+		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Debug agent already started for this V8Js instance");
+		RETURN_BOOL(0);
+	}
+
+	if(v8js_debug_context != NULL) {
+		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Debug agent already started for a different V8Js instance");
+		RETURN_BOOL(0);
+	}
+
+	v8js_debug_context = c;
+	v8js_debug_auto_break_mode = auto_break;
+
+	v8::Debug::SetDebugMessageDispatchHandler(DispatchDebugMessages, true);
+	v8::Debug::EnableAgent(str_len ? str : "V8Js", port, auto_break > 0);
+
+	if(auto_break) {
+		/* v8::Debug::EnableAgent doesn't really do what we want it to do,
+		   since it only breaks processing on the default isolate.
+		   Hence just trigger another DebugBreak, no for our main isolate. */
+		v8::Debug::DebugBreak(c->isolate);
+	}
+
+	RETURN_BOOL(1);
+}
+/* }}} */
+#endif  /* ENABLE_DEBUGGER_SUPPORT */
+
+/* {{{ proto mixed V8Js::getPendingException()
+ */
+static PHP_METHOD(V8Js, getPendingException)
+{
+	v8js_ctx *c;
+
+	if (zend_parse_parameters_none() == FAILURE) {
+		return;
+	}
+
+	c = (v8js_ctx *) zend_object_store_get_object(getThis() TSRMLS_CC);
+
+	if (c->pending_exception) {
+		RETURN_ZVAL(c->pending_exception, 1, 0);
+	}
+}
+/* }}} */
+
+/* {{{ proto void V8Js::clearPendingException()
+ */
+static PHP_METHOD(V8Js, clearPendingException)
+{
+	v8js_ctx *c;
+
+	if (zend_parse_parameters_none() == FAILURE) {
+		return;
+	}
+
+	c = (v8js_ctx *) zend_object_store_get_object(getThis() TSRMLS_CC);
+
+	if (c->pending_exception) {
+		zval_ptr_dtor(&c->pending_exception);
+		c->pending_exception = NULL;
+	}
+}
+/* }}} */
+
+/* {{{ proto void V8Js::setModuleLoader(string module)
+ */
+static PHP_METHOD(V8Js, setModuleLoader)
+{
+	v8js_ctx *c;
+	zval *callable;
+
+	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &callable) == FAILURE) {
+		return;
+	}
+
+	c = (v8js_ctx *) zend_object_store_get_object(getThis() TSRMLS_CC);
+
+	c->module_loader = callable;
+	Z_ADDREF_P(c->module_loader);
+}
+/* }}} */
+
+/* {{{ proto void V8Js::setTimeLimit(int time_limit)
+ */
+static PHP_METHOD(V8Js, setTimeLimit)
+{
+	v8js_ctx *c;
+	long time_limit = 0;
+
+	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &time_limit) == FAILURE) {
+		return;
+	}
+
+	c = (v8js_ctx *) zend_object_store_get_object(getThis() TSRMLS_CC);
+	c->time_limit = time_limit;
+
+	V8JSG(timer_mutex).lock();
+	for (std::deque< v8js_timer_ctx* >::iterator it = V8JSG(timer_stack).begin();
+		 it != V8JSG(timer_stack).end(); it ++) {
+		if((*it)->ctx == c && !(*it)->killed) {
+			(*it)->time_limit = time_limit;
+
+			// Calculate the time point when the time limit is exceeded
+			std::chrono::milliseconds duration(time_limit);
+			std::chrono::time_point<std::chrono::high_resolution_clock> from = std::chrono::high_resolution_clock::now();
+			(*it)->time_point = from + duration;
+		}
+	}
+	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(v8js_timer_thread TSRMLS_CC);
+	}
+}
+/* }}} */
+
+/* {{{ proto void V8Js::setMemoryLimit(int memory_limit)
+ */
+static PHP_METHOD(V8Js, setMemoryLimit)
+{
+	v8js_ctx *c;
+	long memory_limit = 0;
+
+	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &memory_limit) == FAILURE) {
+		return;
+	}
+
+	c = (v8js_ctx *) zend_object_store_get_object(getThis() TSRMLS_CC);
+	c->memory_limit = memory_limit;
+
+	V8JSG(timer_mutex).lock();
+	for (std::deque< v8js_timer_ctx* >::iterator it = V8JSG(timer_stack).begin();
+		 it != V8JSG(timer_stack).end(); it ++) {
+		if((*it)->ctx == c && !(*it)->killed) {
+			(*it)->memory_limit = memory_limit;
+		}
+	}
+	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(v8js_timer_thread TSRMLS_CC);
+	}
+}
+/* }}} */
+
+static void v8js_persistent_zval_ctor(zval **p) /* {{{ */
+{
+	zval *orig_ptr = *p;
+	*p = (zval *) malloc(sizeof(zval));
+	**p = *orig_ptr;
+	switch (Z_TYPE_P(*p)) {
+		case IS_STRING:
+			Z_STRVAL_P(*p) = (char *) zend_strndup(Z_STRVAL_P(*p), Z_STRLEN_P(*p));
+			break;
+		default:
+			zend_bailout();
+	}
+	INIT_PZVAL(*p);
+}
+/* }}} */
+
+static void v8js_persistent_zval_dtor(zval **p) /* {{{ */
+{
+	switch (Z_TYPE_P(*p)) {
+		case IS_STRING:
+			free(Z_STRVAL_P(*p));
+			break;
+		default:
+			zend_bailout();
+	}
+	free(*p);
+}
+/* }}} */
+
+static void v8js_script_free(v8js_script *res, bool dispose_persistent)
+{
+	if (res->name) {
+		efree(res->name);
+		res->name = NULL;
+	}
+	if (dispose_persistent) {
+		res->script->~Persistent(); // does Reset()
+		res->script = NULL;
+	}
+}
+
+static void v8js_script_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) /* {{{ */
+{
+	v8js_script *res = (v8js_script *)rsrc->ptr;
+	if (res) {
+		v8js_script_free(res, false);
+		efree(res);
+	}
+}
+/* }}} */
+
+static int v8js_register_extension(char *name, uint name_len, char *source, uint source_len, zval *deps_arr, zend_bool auto_enable TSRMLS_DC) /* {{{ */
+{
+	v8js_jsext *jsext = NULL;
+
+	if (!V8JSG(extensions)) {
+		V8JSG(extensions) = (HashTable *) malloc(sizeof(HashTable));
+		zend_hash_init(V8JSG(extensions), 1, NULL, (dtor_func_t) v8js_jsext_dtor, 1);
+	} else if (zend_hash_exists(V8JSG(extensions), name, name_len + 1)) {
+		return FAILURE;
+	}
+
+	jsext = (v8js_jsext *) calloc(1, sizeof(v8js_jsext));
+
+	if (deps_arr) {
+		jsext->deps_count = zend_hash_num_elements(Z_ARRVAL_P(deps_arr));
+
+		if (v8js_create_ext_strarr(&jsext->deps, jsext->deps_count, Z_ARRVAL_P(deps_arr)) == FAILURE) {
+			php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid dependency array passed");
+			v8js_jsext_dtor(jsext);
+			free(jsext);
+			return FAILURE;
+		}
+	}
+
+	jsext->auto_enable = auto_enable;
+	jsext->name = zend_strndup(name, name_len);
+	jsext->source = zend_strndup(source, source_len);
+
+	if (jsext->deps) {
+		jsext->deps_ht = (HashTable *) malloc(sizeof(HashTable));
+		zend_hash_init(jsext->deps_ht, jsext->deps_count, NULL, (dtor_func_t) v8js_persistent_zval_dtor, 1);
+		zend_hash_copy(jsext->deps_ht, Z_ARRVAL_P(deps_arr), (copy_ctor_func_t) v8js_persistent_zval_ctor, NULL, sizeof(zval *));
+	}
+
+	if (zend_hash_add(V8JSG(extensions), name, name_len + 1, jsext, sizeof(v8js_jsext), NULL) == FAILURE) {
+		v8js_jsext_dtor(jsext);
+		free(jsext);
+		return FAILURE;
+	}
+
+	v8::Extension *extension = new v8::Extension(jsext->name, jsext->source, jsext->deps_count, jsext->deps);
+	extension->set_auto_enable(auto_enable ? true : false);
+	v8::RegisterExtension(extension);
+
+	free(jsext);
+
+	return SUCCESS;
+}
+/* }}} */
+
+/* {{{ proto bool V8Js::registerExtension(string ext_name, string script [, array deps [, bool auto_enable]])
+ */
+static PHP_METHOD(V8Js, registerExtension)
+{
+	char *ext_name, *script;
+	zval *deps_arr = NULL;
+	int ext_name_len, script_len;
+	zend_bool auto_enable = 0;
+
+	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|ab", &ext_name, &ext_name_len, &script, &script_len, &deps_arr, &auto_enable) == FAILURE) {
+		return;
+	}
+
+	if (!ext_name_len) {
+		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Extension name cannot be empty");
+	} else if (!script_len) {
+		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Script cannot be empty");
+	} else if (v8js_register_extension(ext_name, ext_name_len, script, script_len, deps_arr, auto_enable TSRMLS_CC) == SUCCESS) {
+		RETURN_TRUE;
+	}
+	RETURN_FALSE;
+}
+/* }}} */
+
+/* ## Static methods ## */
+
+/* {{{ proto array V8Js::getExtensions()
+ */
+static PHP_METHOD(V8Js, getExtensions)
+{
+	v8js_jsext *jsext;
+	zval *ext, *deps_arr;
+	HashPosition pos;
+	ulong index;
+	char *key;
+	uint key_len;
+
+	if (zend_parse_parameters_none() == FAILURE) {
+		return;
+	}
+
+	array_init(return_value);
+	if (V8JSG(extensions)) {
+		zend_hash_internal_pointer_reset_ex(V8JSG(extensions), &pos);
+		while (zend_hash_get_current_data_ex(V8JSG(extensions), (void **) &jsext, &pos) == SUCCESS) {
+			if (zend_hash_get_current_key_ex(V8JSG(extensions), &key, &key_len, &index, 0, &pos) == HASH_KEY_IS_STRING) {
+				MAKE_STD_ZVAL(ext)
+				array_init(ext);
+				add_assoc_bool_ex(ext, ZEND_STRS("auto_enable"), jsext->auto_enable);
+				if (jsext->deps_ht) {
+					MAKE_STD_ZVAL(deps_arr);
+					array_init(deps_arr);
+					zend_hash_copy(Z_ARRVAL_P(deps_arr), jsext->deps_ht, (copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval *));
+					add_assoc_zval_ex(ext, ZEND_STRS("deps"), deps_arr);
+				}
+				add_assoc_zval_ex(return_value, key, key_len, ext);
+			}
+			zend_hash_move_forward_ex(V8JSG(extensions), &pos);
+		}
+	}
+}
+/* }}} */
+
+/* {{{ arginfo */
+ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_construct, 0, 0, 0)
+	ZEND_ARG_INFO(0, object_name)
+	ZEND_ARG_INFO(0, variables)
+	ZEND_ARG_INFO(0, extensions)
+	ZEND_ARG_INFO(0, report_uncaught_exceptions)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO(arginfo_v8js_sleep, 0)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO(arginfo_v8js_wakeup, 0)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_executestring, 0, 0, 1)
+	ZEND_ARG_INFO(0, script)
+	ZEND_ARG_INFO(0, identifier)
+	ZEND_ARG_INFO(0, flags)
+	ZEND_ARG_INFO(0, time_limit)
+	ZEND_ARG_INFO(0, memory_limit)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_compilestring, 0, 0, 1)
+	ZEND_ARG_INFO(0, script)
+	ZEND_ARG_INFO(0, identifier)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_executescript, 0, 0, 1)
+	ZEND_ARG_INFO(0, script)
+	ZEND_ARG_INFO(0, flags)
+	ZEND_ARG_INFO(0, time_limit)
+	ZEND_ARG_INFO(0, memory_limit)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_checkstring, 0, 0, 1)
+	ZEND_ARG_INFO(0, script)
+ZEND_END_ARG_INFO()
+
+#ifdef ENABLE_DEBUGGER_SUPPORT
+ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_destruct, 0, 0, 0)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_startdebugagent, 0, 0, 0)
+	ZEND_ARG_INFO(0, agentName)
+	ZEND_ARG_INFO(0, port)
+	ZEND_ARG_INFO(0, auto_break)
+ZEND_END_ARG_INFO()
+#endif  /* ENABLE_DEBUGGER_SUPPORT */
+
+ZEND_BEGIN_ARG_INFO(arginfo_v8js_getpendingexception, 0)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO(arginfo_v8js_clearpendingexception, 0)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_setmoduleloader, 0, 0, 1)
+	ZEND_ARG_INFO(0, callable)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_registerextension, 0, 0, 2)
+	ZEND_ARG_INFO(0, extension_name)
+	ZEND_ARG_INFO(0, script)
+	ZEND_ARG_INFO(0, dependencies)
+	ZEND_ARG_INFO(0, auto_enable)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO(arginfo_v8js_getextensions, 0)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_settimelimit, 0, 0, 1)
+	ZEND_ARG_INFO(0, time_limit)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_setmemorylimit, 0, 0, 1)
+	ZEND_ARG_INFO(0, memory_limit)
+ZEND_END_ARG_INFO()
+
+
+static const zend_function_entry v8js_methods[] = { /* {{{ */
+	PHP_ME(V8Js,	__construct,			arginfo_v8js_construct,				ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+	PHP_ME(V8Js,	__sleep,				arginfo_v8js_sleep,					ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
+	PHP_ME(V8Js,	__wakeup,				arginfo_v8js_sleep,					ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
+	PHP_ME(V8Js,	executeString,			arginfo_v8js_executestring,			ZEND_ACC_PUBLIC)
+	PHP_ME(V8Js,	compileString,			arginfo_v8js_compilestring,			ZEND_ACC_PUBLIC)
+	PHP_ME(V8Js,    executeScript,			arginfo_v8js_executescript,			ZEND_ACC_PUBLIC)
+	PHP_ME(V8Js,    checkString,			arginfo_v8js_checkstring,			ZEND_ACC_PUBLIC|ZEND_ACC_DEPRECATED)
+	PHP_ME(V8Js,	getPendingException,	arginfo_v8js_getpendingexception,	ZEND_ACC_PUBLIC)
+	PHP_ME(V8Js,	clearPendingException,	arginfo_v8js_clearpendingexception,	ZEND_ACC_PUBLIC)
+	PHP_ME(V8Js,	setModuleLoader,		arginfo_v8js_setmoduleloader,		ZEND_ACC_PUBLIC)
+	PHP_ME(V8Js,	registerExtension,		arginfo_v8js_registerextension,		ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
+	PHP_ME(V8Js,	getExtensions,			arginfo_v8js_getextensions,			ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
+	PHP_ME(V8Js,	setTimeLimit,			arginfo_v8js_settimelimit,			ZEND_ACC_PUBLIC)
+	PHP_ME(V8Js,	setMemoryLimit,			arginfo_v8js_setmemorylimit,		ZEND_ACC_PUBLIC)
+#ifdef ENABLE_DEBUGGER_SUPPORT
+	PHP_ME(V8Js,	__destruct,				arginfo_v8js_destruct,				ZEND_ACC_PUBLIC|ZEND_ACC_DTOR)
+	PHP_ME(V8Js,	startDebugAgent,		arginfo_v8js_startdebugagent,		ZEND_ACC_PUBLIC)
+#endif
+	{NULL, NULL, NULL}
+};
+/* }}} */
+
+
+
+/* V8Js object handlers */
+
+static void v8js_write_property(zval *object, zval *member, zval *value ZEND_HASH_KEY_DC TSRMLS_DC) /* {{{ */
+{
+	V8JS_BEGIN_CTX(c, object)
+
+	/* Check whether member is public, if so, export to V8. */
+	zend_property_info *property_info = zend_get_property_info(c->std.ce, member, 1 TSRMLS_CC);
+	if(property_info->flags & ZEND_ACC_PUBLIC) {
+		/* Global PHP JS object */
+		v8::Local<v8::String> object_name_js = v8::Local<v8::String>::New(isolate, c->object_name);
+		v8::Local<v8::Object> jsobj = V8JS_GLOBAL(isolate)->Get(object_name_js)->ToObject();
+
+		/* Write value to PHP JS object */
+		jsobj->ForceSet(V8JS_SYML(Z_STRVAL_P(member), Z_STRLEN_P(member)), zval_to_v8js(value, isolate TSRMLS_CC), v8::ReadOnly);
+	}
+
+	/* Write value to PHP object */
+	std_object_handlers.write_property(object, member, value ZEND_HASH_KEY_CC TSRMLS_CC);
+}
+/* }}} */
+
+static void v8js_unset_property(zval *object, zval *member ZEND_HASH_KEY_DC TSRMLS_DC) /* {{{ */
+{
+	V8JS_BEGIN_CTX(c, object)
+
+	/* Global PHP JS object */
+	v8::Local<v8::String> object_name_js = v8::Local<v8::String>::New(isolate, c->object_name);
+	v8::Local<v8::Object> jsobj = V8JS_GLOBAL(isolate)->Get(object_name_js)->ToObject();
+	
+	/* Delete value from PHP JS object */
+	jsobj->ForceDelete(V8JS_SYML(Z_STRVAL_P(member), Z_STRLEN_P(member)));
+
+	/* Unset from PHP object */
+	std_object_handlers.unset_property(object, member ZEND_HASH_KEY_CC TSRMLS_CC);
+}
+/* }}} */
+
+PHP_MINIT_FUNCTION(v8js_class) /* {{{ */
+{
+	zend_class_entry ce;
+
+	/* V8Js Class */
+	INIT_CLASS_ENTRY(ce, "V8Js", v8js_methods);
+	php_ce_v8js = zend_register_internal_class(&ce TSRMLS_CC);
+	php_ce_v8js->create_object = v8js_new;
+
+	/* V8Js handlers */
+	memcpy(&v8js_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
+	v8js_object_handlers.clone_obj = NULL;
+	v8js_object_handlers.write_property = v8js_write_property;
+	v8js_object_handlers.unset_property = v8js_unset_property;
+
+	/* V8Js Class Constants */
+	zend_declare_class_constant_string(php_ce_v8js, ZEND_STRL("V8_VERSION"),		PHP_V8_VERSION			TSRMLS_CC);
+
+	zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("FLAG_NONE"),			V8JS_FLAG_NONE			TSRMLS_CC);
+	zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("FLAG_FORCE_ARRAY"),	V8JS_FLAG_FORCE_ARRAY	TSRMLS_CC);
+
+#ifdef ENABLE_DEBUGGER_SUPPORT
+	zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("DEBUG_AUTO_BREAK_NEVER"),	V8JS_DEBUG_AUTO_BREAK_NEVER			TSRMLS_CC);
+	zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("DEBUG_AUTO_BREAK_ONCE"),	V8JS_DEBUG_AUTO_BREAK_ONCE			TSRMLS_CC);
+	zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("DEBUG_AUTO_BREAK_ALWAYS"),	V8JS_DEBUG_AUTO_BREAK_ALWAYS		TSRMLS_CC);
+#endif
+
+	le_v8js_script = zend_register_list_destructors_ex(v8js_script_dtor, NULL, PHP_V8JS_SCRIPT_RES_NAME, module_number);
+} /* }}} */
+
+/*
+ * Local variables:
+ * tab-width: 4
+ * c-basic-offset: 4
+ * End:
+ * vim600: noet sw=4 ts=4 fdm=marker
+ * vim<600: noet sw=4 ts=4
+ */

+ 80 - 0
v8js_class.h

@@ -0,0 +1,80 @@
+/*
+  +----------------------------------------------------------------------+
+  | PHP Version 5                                                        |
+  +----------------------------------------------------------------------+
+  | Copyright (c) 1997-2013 The PHP Group                                |
+  +----------------------------------------------------------------------+
+  | http://www.opensource.org/licenses/mit-license.php  MIT License      |
+  +----------------------------------------------------------------------+
+  | Author: Jani Taskinen <[email protected]>                         |
+  | Author: Patrick Reilly <[email protected]>                             |
+  +----------------------------------------------------------------------+
+*/
+
+#ifndef V8JS_CLASS_H
+#define V8JS_CLASS_H
+
+
+/* Abbreviate long type names */
+typedef v8::Persistent<v8::FunctionTemplate, v8::CopyablePersistentTraits<v8::FunctionTemplate> > v8js_tmpl_t;
+typedef v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object> > v8js_persistent_obj_t;
+
+/* Forward declarations */
+struct v8js_v8object;
+struct v8js_accessor_ctx;
+
+/* {{{ Context container */
+struct v8js_ctx {
+  zend_object std;
+  v8::Persistent<v8::String> object_name;
+  v8::Persistent<v8::Context> context;
+  zend_bool report_uncaught;
+  zval *pending_exception;
+  int in_execution;
+  v8::Isolate *isolate;
+
+  long time_limit;
+  bool time_limit_hit;
+  long memory_limit;
+  bool memory_limit_hit;
+
+  v8::Persistent<v8::FunctionTemplate> global_template;
+
+  zval *module_loader;
+  std::vector<char *> modules_stack;
+  std::vector<char *> modules_base;
+  std::map<char *, v8js_persistent_obj_t> modules_loaded;
+  std::map<const char *,v8js_tmpl_t> template_cache;
+
+  std::map<zval *, v8js_persistent_obj_t> weak_objects;
+  std::map<v8js_tmpl_t *, v8js_persistent_obj_t> weak_closures;
+
+  std::list<v8js_v8object *> v8js_v8objects;
+
+  std::vector<v8js_accessor_ctx *> accessor_list;
+  char *tz;
+#ifdef ZTS
+  void ***zts_ctx;
+#endif
+};
+/* }}} */
+
+#ifdef ZTS
+# define V8JS_TSRMLS_FETCH() TSRMLS_FETCH_FROM_CTX(((v8js_ctx *) isolate->GetData(0))->zts_ctx);
+#else
+# define V8JS_TSRMLS_FETCH()
+#endif
+
+
+PHP_MINIT_FUNCTION(v8js_class);
+
+#endif /* V8JS_CLASS_H */
+
+/*
+ * Local variables:
+ * tab-width: 4
+ * c-basic-offset: 4
+ * End:
+ * vim600: noet sw=4 ts=4 fdm=marker
+ * vim<600: noet sw=4 ts=4
+ */

+ 4 - 4
v8js_commonjs.cc

@@ -22,7 +22,7 @@ extern "C" {
 
 #include "php_v8js_macros.h"
 
-void php_v8js_commonjs_split_terms(char *identifier, std::vector<char *> &terms)
+void v8js_commonjs_split_terms(char *identifier, std::vector<char *> &terms)
 {
     char *term = (char *)malloc(PATH_MAX), *ptr = term;
 
@@ -58,14 +58,14 @@ void php_v8js_commonjs_split_terms(char *identifier, std::vector<char *> &terms)
     }
 }
 
-void php_v8js_commonjs_normalise_identifier(char *base, char *identifier, char *normalised_path, char *module_name)
+void v8js_commonjs_normalise_identifier(char *base, char *identifier, char *normalised_path, char *module_name)
 {
     std::vector<char *> id_terms, terms;
-    php_v8js_commonjs_split_terms(identifier, id_terms);
+    v8js_commonjs_split_terms(identifier, id_terms);
 
     // If we have a relative module identifier then include the base terms
     if (!strcmp(id_terms.front(), ".") || !strcmp(id_terms.front(), "..")) {
-        php_v8js_commonjs_split_terms(base, terms);
+        v8js_commonjs_split_terms(base, terms);
     }
 
     terms.insert(terms.end(), id_terms.begin(), id_terms.end());

+ 11 - 11
v8js_convert.cc

@@ -11,8 +11,6 @@
   +----------------------------------------------------------------------+
 */
 
-/* $Id$ */
-
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif
@@ -27,11 +25,13 @@ extern "C" {
 
 #include "php_v8js_macros.h"
 #include "v8js_object_export.h"
+#include "v8js_v8object_class.h"
+#include "v8js_v8.h"
 
 #include <stdexcept>
 #include <limits>
 
-static int _php_v8js_is_assoc_array(HashTable *myht TSRMLS_DC) /* {{{ */
+static int v8js_is_assoc_array(HashTable *myht TSRMLS_DC) /* {{{ */
 {
 	int i;
 	char *key;
@@ -54,14 +54,14 @@ static int _php_v8js_is_assoc_array(HashTable *myht TSRMLS_DC) /* {{{ */
 /* }}} */
 
 
-static v8::Handle<v8::Value> php_v8js_hash_to_jsarr(zval *value, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
+static v8::Handle<v8::Value> v8js_hash_to_jsarr(zval *value, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
 {
 	HashTable *myht = HASH_OF(value);
 	int i = myht ? zend_hash_num_elements(myht) : 0;
 
 	/* Return object if dealing with assoc array */
-	if (i > 0 && _php_v8js_is_assoc_array(myht TSRMLS_CC)) {
-		return php_v8js_hash_to_jsobj(value, isolate TSRMLS_CC);
+	if (i > 0 && v8js_is_assoc_array(myht TSRMLS_CC)) {
+		return v8js_hash_to_jsobj(value, isolate TSRMLS_CC);
 	}
 
 	v8::Local<v8::Array> newarr;
@@ -110,7 +110,7 @@ v8::Handle<v8::Value> zval_to_v8js(zval *value, v8::Isolate *isolate TSRMLS_DC)
 	switch (Z_TYPE_P(value))
 	{
 		case IS_ARRAY:
-			jsValue = php_v8js_hash_to_jsarr(value, isolate TSRMLS_CC);
+			jsValue = v8js_hash_to_jsarr(value, isolate TSRMLS_CC);
 			break;
 
 		case IS_OBJECT:
@@ -126,9 +126,9 @@ v8::Handle<v8::Value> zval_to_v8js(zval *value, v8::Isolate *isolate TSRMLS_DC)
 					 else
 						 jsValue = V8JS_NULL;
 				 } else
-					 jsValue = php_v8js_hash_to_jsobj(value, isolate TSRMLS_CC);
+					 jsValue = v8js_hash_to_jsobj(value, isolate TSRMLS_CC);
 			 } else
-				 jsValue = php_v8js_hash_to_jsobj(value, isolate TSRMLS_CC);
+				 jsValue = v8js_hash_to_jsobj(value, isolate TSRMLS_CC);
 			break;
 
 		case IS_STRING:
@@ -246,9 +246,9 @@ int v8js_to_zval(v8::Handle<v8::Value> jsValue, zval *return_value, int flags, v
 		}
 		if ((flags & V8JS_FLAG_FORCE_ARRAY) || jsValue->IsArray()) {
 			array_init(return_value);
-			return php_v8js_v8_get_properties_hash(jsValue, Z_ARRVAL_P(return_value), flags, isolate TSRMLS_CC);
+			return v8js_get_properties_hash(jsValue, Z_ARRVAL_P(return_value), flags, isolate TSRMLS_CC);
 		} else {
-			php_v8js_create_v8(return_value, jsValue, flags, isolate TSRMLS_CC);
+			v8js_v8object_create(return_value, jsValue, flags, isolate TSRMLS_CC);
 			return SUCCESS;
 		}
 	}

+ 244 - 0
v8js_exceptions.cc

@@ -0,0 +1,244 @@
+/*
+  +----------------------------------------------------------------------+
+  | PHP Version 5                                                        |
+  +----------------------------------------------------------------------+
+  | Copyright (c) 1997-2013 The PHP Group                                |
+  +----------------------------------------------------------------------+
+  | http://www.opensource.org/licenses/mit-license.php  MIT License      |
+  +----------------------------------------------------------------------+
+  | Author: Jani Taskinen <[email protected]>                         |
+  | Author: Patrick Reilly <[email protected]>                             |
+  +----------------------------------------------------------------------+
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+extern "C" {
+#include "php.h"
+#include "ext/date/php_date.h"
+#include "ext/standard/php_string.h"
+#include "zend_interfaces.h"
+#include "zend_closures.h"
+#include "ext/spl/spl_exceptions.h"
+#include "zend_exceptions.h"
+}
+
+#include "php_v8js_macros.h"
+
+
+/* {{{ Class Entries */
+zend_class_entry *php_ce_v8js_exception;
+zend_class_entry *php_ce_v8js_script_exception;
+zend_class_entry *php_ce_v8js_time_limit_exception;
+zend_class_entry *php_ce_v8js_memory_limit_exception;
+/* }}} */
+
+
+/* {{{ Class: V8JsScriptException */
+
+void v8js_create_script_exception(zval *return_value, v8::TryCatch *try_catch TSRMLS_DC) /* {{{ */
+{
+	v8::String::Utf8Value exception(try_catch->Exception());
+	const char *exception_string = ToCString(exception);
+	v8::Handle<v8::Message> tc_message = try_catch->Message();
+	const char *filename_string, *sourceline_string;
+	char *message_string;
+	int linenum, start_col, end_col, message_len;
+
+	object_init_ex(return_value, php_ce_v8js_script_exception);
+
+#define PHPV8_EXPROP(type, name, value) \
+	zend_update_property##type(php_ce_v8js_script_exception, return_value, #name, sizeof(#name) - 1, value TSRMLS_CC);
+
+	if (tc_message.IsEmpty()) {
+		message_len = spprintf(&message_string, 0, "%s", exception_string);
+	}
+	else
+	{
+		v8::String::Utf8Value filename(tc_message->GetScriptResourceName());
+		filename_string = ToCString(filename);
+		PHPV8_EXPROP(_string, JsFileName, filename_string);
+
+		v8::String::Utf8Value sourceline(tc_message->GetSourceLine());
+		sourceline_string = ToCString(sourceline);
+		PHPV8_EXPROP(_string, JsSourceLine, sourceline_string);
+
+		linenum = tc_message->GetLineNumber();
+		PHPV8_EXPROP(_long, JsLineNumber, linenum);
+
+		start_col = tc_message->GetStartColumn();
+		PHPV8_EXPROP(_long, JsStartColumn, start_col);
+
+		end_col = tc_message->GetEndColumn();
+		PHPV8_EXPROP(_long, JsEndColumn, end_col);
+
+		message_len = spprintf(&message_string, 0, "%s:%d: %s", filename_string, linenum, exception_string);
+
+		v8::String::Utf8Value stacktrace(try_catch->StackTrace());
+		if (stacktrace.length() > 0) {
+			const char* stacktrace_string = ToCString(stacktrace);
+			PHPV8_EXPROP(_string, JsTrace, stacktrace_string);
+		}
+	}
+
+	PHPV8_EXPROP(_string, message, message_string);
+
+	efree(message_string);
+}
+/* }}} */
+
+void v8js_throw_script_exception(v8::TryCatch *try_catch TSRMLS_DC) /* {{{ */
+{
+	v8::String::Utf8Value exception(try_catch->Exception());
+	const char *exception_string = ToCString(exception);
+	zval *zexception = NULL;
+
+	if (try_catch->Message().IsEmpty()) {
+		zend_throw_exception(php_ce_v8js_script_exception, (char *) exception_string, 0 TSRMLS_CC);
+	} else {
+		MAKE_STD_ZVAL(zexception);
+		v8js_create_script_exception(zexception, try_catch TSRMLS_CC);
+		zend_throw_exception_object(zexception TSRMLS_CC);
+	}
+}
+/* }}} */
+
+#define V8JS_EXCEPTION_METHOD(property) \
+	static PHP_METHOD(V8JsScriptException, get##property) \
+	{ \
+		zval *value; \
+		\
+		if (zend_parse_parameters_none() == FAILURE) { \
+			return; \
+		} \
+		value = zend_read_property(php_ce_v8js_script_exception, getThis(), #property, sizeof(#property) - 1, 0 TSRMLS_CC); \
+		*return_value = *value; \
+		zval_copy_ctor(return_value); \
+		INIT_PZVAL(return_value); \
+	}
+
+/* {{{ proto string V8JsEScriptxception::getJsFileName()
+ */
+V8JS_EXCEPTION_METHOD(JsFileName);
+/* }}} */
+
+/* {{{ proto string V8JsScriptException::getJsLineNumber()
+ */
+V8JS_EXCEPTION_METHOD(JsLineNumber);
+/* }}} */
+
+/* {{{ proto string V8JsScriptException::getJsStartColumn()
+ */
+V8JS_EXCEPTION_METHOD(JsStartColumn);
+/* }}} */
+
+/* {{{ proto string V8JsScriptException::getJsEndColumn()
+ */
+V8JS_EXCEPTION_METHOD(JsEndColumn);
+/* }}} */
+
+/* {{{ proto string V8JsScriptException::getJsSourceLine()
+ */
+V8JS_EXCEPTION_METHOD(JsSourceLine);
+/* }}} */
+
+/* {{{ proto string V8JsScriptException::getJsTrace()
+ */
+V8JS_EXCEPTION_METHOD(JsTrace);	
+/* }}} */
+
+
+ZEND_BEGIN_ARG_INFO(arginfo_v8jsscriptexception_no_args, 0)
+ZEND_END_ARG_INFO()
+
+static const zend_function_entry v8js_script_exception_methods[] = { /* {{{ */
+	PHP_ME(V8JsScriptException,	getJsFileName,		arginfo_v8jsscriptexception_no_args,	ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
+	PHP_ME(V8JsScriptException,	getJsLineNumber,	arginfo_v8jsscriptexception_no_args,	ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
+	PHP_ME(V8JsScriptException,	getJsStartColumn,	arginfo_v8jsscriptexception_no_args,	ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
+	PHP_ME(V8JsScriptException,	getJsEndColumn,		arginfo_v8jsscriptexception_no_args,	ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
+	PHP_ME(V8JsScriptException,	getJsSourceLine,	arginfo_v8jsscriptexception_no_args,	ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
+	PHP_ME(V8JsScriptException,	getJsTrace,			arginfo_v8jsscriptexception_no_args,	ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
+	{NULL, NULL, NULL}
+};
+/* }}} */
+
+/* }}} V8JsScriptException */
+
+
+
+/* {{{ Class: V8JsException */
+
+static const zend_function_entry v8js_exception_methods[] = { /* {{{ */
+	{NULL, NULL, NULL}
+};
+/* }}} */
+
+/* }}} V8JsException */
+
+
+
+/* {{{ Class: V8JsTimeLimitException */
+
+static const zend_function_entry v8js_time_limit_exception_methods[] = { /* {{{ */
+	{NULL, NULL, NULL}
+};
+/* }}} */
+
+/* }}} V8JsTimeLimitException */
+
+
+
+/* {{{ Class: V8JsMemoryLimitException */
+
+static const zend_function_entry v8js_memory_limit_exception_methods[] = { /* {{{ */
+	{NULL, NULL, NULL}
+};
+/* }}} */
+
+/* }}} V8JsMemoryLimitException */
+
+
+
+PHP_MINIT_FUNCTION(v8js_exceptions) /* {{{ */
+{
+	zend_class_entry ce;
+
+	/* V8JsException Class */
+	INIT_CLASS_ENTRY(ce, "V8JsException", v8js_exception_methods);
+	php_ce_v8js_exception = zend_register_internal_class_ex(&ce, spl_ce_RuntimeException, NULL TSRMLS_CC);
+
+	/* V8JsScriptException Class */
+	INIT_CLASS_ENTRY(ce, "V8JsScriptException", v8js_script_exception_methods);
+	php_ce_v8js_script_exception = zend_register_internal_class_ex(&ce, php_ce_v8js_exception, NULL TSRMLS_CC);
+	php_ce_v8js_script_exception->ce_flags |= ZEND_ACC_FINAL;
+
+	/* Add custom JS specific properties */
+	zend_declare_property_null(php_ce_v8js_script_exception, ZEND_STRL("JsFileName"),		ZEND_ACC_PROTECTED TSRMLS_CC);
+	zend_declare_property_null(php_ce_v8js_script_exception, ZEND_STRL("JsLineNumber"),		ZEND_ACC_PROTECTED TSRMLS_CC);
+	zend_declare_property_null(php_ce_v8js_script_exception, ZEND_STRL("JsStartColumn"),	ZEND_ACC_PROTECTED TSRMLS_CC);
+	zend_declare_property_null(php_ce_v8js_script_exception, ZEND_STRL("JsEndColumn"),		ZEND_ACC_PROTECTED TSRMLS_CC);
+	zend_declare_property_null(php_ce_v8js_script_exception, ZEND_STRL("JsSourceLine"),		ZEND_ACC_PROTECTED TSRMLS_CC);
+	zend_declare_property_null(php_ce_v8js_script_exception, ZEND_STRL("JsTrace"),			ZEND_ACC_PROTECTED TSRMLS_CC);
+
+	/* V8JsTimeLimitException Class */
+	INIT_CLASS_ENTRY(ce, "V8JsTimeLimitException", v8js_time_limit_exception_methods);
+	php_ce_v8js_time_limit_exception = zend_register_internal_class_ex(&ce, php_ce_v8js_exception, NULL TSRMLS_CC);
+	php_ce_v8js_time_limit_exception->ce_flags |= ZEND_ACC_FINAL;
+
+	/* V8JsMemoryLimitException Class */
+	INIT_CLASS_ENTRY(ce, "V8JsMemoryLimitException", v8js_memory_limit_exception_methods);
+	php_ce_v8js_memory_limit_exception = zend_register_internal_class_ex(&ce, php_ce_v8js_exception, NULL TSRMLS_CC);
+	php_ce_v8js_memory_limit_exception->ce_flags |= ZEND_ACC_FINAL;
+
+} /* }}} */
+
+/*
+ * Local variables:
+ * tab-width: 4
+ * c-basic-offset: 4
+ * End:
+ * vim600: noet sw=4 ts=4 fdm=marker
+ * vim<600: noet sw=4 ts=4
+ */

+ 36 - 0
v8js_exceptions.h

@@ -0,0 +1,36 @@
+/*
+  +----------------------------------------------------------------------+
+  | PHP Version 5                                                        |
+  +----------------------------------------------------------------------+
+  | Copyright (c) 1997-2013 The PHP Group                                |
+  +----------------------------------------------------------------------+
+  | http://www.opensource.org/licenses/mit-license.php  MIT License      |
+  +----------------------------------------------------------------------+
+  | Author: Jani Taskinen <[email protected]>                         |
+  | Author: Patrick Reilly <[email protected]>                             |
+  +----------------------------------------------------------------------+
+*/
+
+#ifndef V8JS_EXCEPTIONS_H
+#define V8JS_EXCEPTIONS_H
+
+extern zend_class_entry *php_ce_v8js_exception;
+extern zend_class_entry *php_ce_v8js_script_exception;
+extern zend_class_entry *php_ce_v8js_time_limit_exception;
+extern zend_class_entry *php_ce_v8js_memory_limit_exception;
+
+void v8js_create_script_exception(zval *return_value, v8::TryCatch *try_catch TSRMLS_DC);
+void v8js_throw_script_exception(v8::TryCatch *try_catch TSRMLS_DC);
+
+PHP_MINIT_FUNCTION(v8js_exceptions);
+
+#endif /* V8JS_EXCEPTIONS_H */
+
+/*
+ * Local variables:
+ * tab-width: 4
+ * c-basic-offset: 4
+ * End:
+ * vim600: noet sw=4 ts=4 fdm=marker
+ * vim<600: noet sw=4 ts=4
+ */

+ 8 - 10
v8js_methods.cc

@@ -11,8 +11,6 @@
   +----------------------------------------------------------------------+
 */
 
-/* $Id$ */
-
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif
@@ -24,7 +22,7 @@ extern "C" {
 }
 
 /* Forward declarations */
-void php_v8js_commonjs_normalise_identifier(char *base, char *identifier, char *normalised_path, char *module_name);
+void v8js_commonjs_normalise_identifier(char *base, char *identifier, char *normalised_path, char *module_name);
 
 /* global.exit - terminate execution */
 V8JS_METHOD(exit) /* {{{ */
@@ -56,7 +54,7 @@ V8JS_METHOD(print) /* {{{ */
 }
 /* }}} */
 
-static void _php_v8js_dumper(v8::Isolate *isolate, v8::Local<v8::Value> var, int level TSRMLS_DC) /* {{{ */
+static void v8js_dumper(v8::Isolate *isolate, v8::Local<v8::Value> var, int level TSRMLS_DC) /* {{{ */
 {
 	if (level > 1) {
 		php_printf("%*c", (level - 1) * 2, ' ');
@@ -126,7 +124,7 @@ static void _php_v8js_dumper(v8::Isolate *isolate, v8::Local<v8::Value> var, int
 
 		for (unsigned i = 0; i < length; i++) {
 			php_printf("%*c[%d] =>\n", level * 2, ' ', i);
-			_php_v8js_dumper(isolate, array->Get(i), level + 1 TSRMLS_CC);
+			v8js_dumper(isolate, array->Get(i), level + 1 TSRMLS_CC);
 		}
 
 		if (level > 1) {
@@ -163,7 +161,7 @@ static void _php_v8js_dumper(v8::Isolate *isolate, v8::Local<v8::Value> var, int
 				v8::Local<v8::String> key = keys->Get(i)->ToString();
 				v8::String::Utf8Value kname(key);
 				php_printf("%*c[\"%s\"] =>\n", level * 2, ' ', ToCString(kname));
-				_php_v8js_dumper(isolate, object->Get(key), level + 1 TSRMLS_CC);
+				v8js_dumper(isolate, object->Get(key), level + 1 TSRMLS_CC);
 			}
 		}
 
@@ -187,7 +185,7 @@ V8JS_METHOD(var_dump) /* {{{ */
 	V8JS_TSRMLS_FETCH();
 
 	for (int i = 0; i < info.Length(); i++) {
-		_php_v8js_dumper(isolate, info[i], 1 TSRMLS_CC);
+		v8js_dumper(isolate, info[i], 1 TSRMLS_CC);
 	}
 
 	info.GetReturnValue().Set(V8JS_NULL);
@@ -201,7 +199,7 @@ V8JS_METHOD(require)
 
 	// Get the extension context
 	v8::Handle<v8::External> data = v8::Handle<v8::External>::Cast(info.Data());
-	php_v8js_ctx *c = static_cast<php_v8js_ctx*>(data->Value());
+	v8js_ctx *c = static_cast<v8js_ctx*>(data->Value());
 
 	// Check that we have a module loader
 	if (c->module_loader == NULL) {
@@ -216,7 +214,7 @@ V8JS_METHOD(require)
 	char *normalised_path = (char *)emalloc(PATH_MAX);
 	char *module_name = (char *)emalloc(PATH_MAX);
 
-	php_v8js_commonjs_normalise_identifier(c->modules_base.back(), module_id, normalised_path, module_name);
+	v8js_commonjs_normalise_identifier(c->modules_base.back(), module_id, normalised_path, module_name);
 	efree(module_id);
 
 	char *normalised_module_id = (char *)emalloc(strlen(normalised_path)+1+strlen(module_name)+1);
@@ -391,7 +389,7 @@ V8JS_METHOD(require)
 	efree(normalised_module_id);
 }
 
-void php_v8js_register_methods(v8::Handle<v8::ObjectTemplate> global, php_v8js_ctx *c) /* {{{ */
+void v8js_register_methods(v8::Handle<v8::ObjectTemplate> global, v8js_ctx *c) /* {{{ */
 {
 	v8::Isolate *isolate = c->isolate;
 	global->Set(V8JS_SYM("exit"), v8::FunctionTemplate::New(isolate, V8JS_MN(exit)), v8::ReadOnly);

+ 56 - 55
v8js_object_export.cc

@@ -26,11 +26,12 @@ extern "C" {
 #include "php_v8js_macros.h"
 #include "v8js_array_access.h"
 #include "v8js_object_export.h"
+#include "v8js_v8object_class.h"
 
-static void php_v8js_weak_object_callback(const v8::WeakCallbackData<v8::Object, zval> &data);
+static void v8js_weak_object_callback(const v8::WeakCallbackData<v8::Object, zval> &data);
 
 /* Callback for PHP methods and functions */
-static void php_v8js_call_php_func(zval *value, zend_class_entry *ce, zend_function *method_ptr, v8::Isolate *isolate, const v8::FunctionCallbackInfo<v8::Value>& info TSRMLS_DC) /* {{{ */
+static void v8js_call_php_func(zval *value, zend_class_entry *ce, zend_function *method_ptr, v8::Isolate *isolate, const v8::FunctionCallbackInfo<v8::Value>& info TSRMLS_DC) /* {{{ */
 {
 	v8::Handle<v8::Value> return_value;
 	zend_fcall_info fci;
@@ -40,7 +41,7 @@ static void php_v8js_call_php_func(zval *value, zend_class_entry *ce, zend_funct
 	char *error;
 	int error_len, i, flags = V8JS_FLAG_NONE;
 
-	php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData(0);
+	v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
 
 	/* Set parameter limits */
 	min_num_args = method_ptr->common.required_num_args;
@@ -160,7 +161,7 @@ failure:
 /* }}} */
 
 /* Callback for PHP methods and functions */
-static void php_v8js_php_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
+static void v8js_php_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
 {
 	v8::Isolate *isolate = info.GetIsolate();
 	v8::Local<v8::Object> self = info.Holder();
@@ -177,11 +178,11 @@ static void php_v8js_php_callback(const v8::FunctionCallbackInfo<v8::Value>& inf
 		method_ptr = zend_get_closure_invoke_method(value TSRMLS_CC);
 	}
 
-	return php_v8js_call_php_func(value, ce, method_ptr, isolate, info TSRMLS_CC);
+	return v8js_call_php_func(value, ce, method_ptr, isolate, info TSRMLS_CC);
 }
 
 /* Callback for PHP constructor calls */
-static void php_v8js_construct_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
+static void v8js_construct_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
 {
 	v8::Isolate *isolate = info.GetIsolate();
 	info.GetReturnValue().Set(V8JS_UNDEFINED);
@@ -199,10 +200,10 @@ static void php_v8js_construct_callback(const v8::FunctionCallbackInfo<v8::Value
 	v8::Local<v8::External> ext_tmpl = v8::Local<v8::External>::Cast(cons_data->Get(0));
 	v8::Local<v8::External> ext_ce =  v8::Local<v8::External>::Cast(cons_data->Get(1));
 
-	php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData(0);
+	v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
 
 	if (info[0]->IsExternal()) {
-		// Object created by v8js in php_v8js_hash_to_jsobj, PHP object passed as v8::External.
+		// Object created by v8js in v8js_hash_to_jsobj, PHP object passed as v8::External.
 		php_object = v8::Local<v8::External>::Cast(info[0]);
 		value = reinterpret_cast<zval *>(php_object->Value());
 
@@ -234,7 +235,7 @@ static void php_v8js_construct_callback(const v8::FunctionCallbackInfo<v8::Value
 
 		// Call __construct function
 		if (ctor_ptr != NULL) {
-			php_v8js_call_php_func(value, ce, ctor_ptr, isolate, info TSRMLS_CC);
+			v8js_call_php_func(value, ce, ctor_ptr, isolate, info TSRMLS_CC);
 		}
 		php_object = v8::External::New(isolate, value);
 	}
@@ -246,7 +247,7 @@ static void php_v8js_construct_callback(const v8::FunctionCallbackInfo<v8::Value
 	// decides to dispose the JS object, we add a weak persistent handle and register
 	// a callback function that removes the reference.
 	ctx->weak_objects[value].Reset(isolate, newobj);
-	ctx->weak_objects[value].SetWeak(value, php_v8js_weak_object_callback);
+	ctx->weak_objects[value].SetWeak(value, v8js_weak_object_callback);
 
 	// Just tell v8 that we're allocating some external memory
 	// (for the moment we just always tell 1k instead of trying to find out actual values)
@@ -255,13 +256,13 @@ static void php_v8js_construct_callback(const v8::FunctionCallbackInfo<v8::Value
 /* }}} */
 
 
-static void php_v8js_weak_object_callback(const v8::WeakCallbackData<v8::Object, zval> &data) {
+static void v8js_weak_object_callback(const v8::WeakCallbackData<v8::Object, zval> &data) {
 	v8::Isolate *isolate = data.GetIsolate();
 
 	zval *value = data.GetParameter();
 	zval_ptr_dtor(&value);
 
-	php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData(0);
+	v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
 
 	ctx->weak_objects.at(value).Reset();
 	ctx->weak_objects.erase(value);
@@ -269,14 +270,14 @@ static void php_v8js_weak_object_callback(const v8::WeakCallbackData<v8::Object,
 	isolate->AdjustAmountOfExternalAllocatedMemory(-1024);
 }
 
-static void php_v8js_weak_closure_callback(const v8::WeakCallbackData<v8::Object, v8js_tmpl_t> &data) {
+static void v8js_weak_closure_callback(const v8::WeakCallbackData<v8::Object, v8js_tmpl_t> &data) {
 	v8::Isolate *isolate = data.GetIsolate();
 
 	v8js_tmpl_t *persist_tpl_ = data.GetParameter();
 	persist_tpl_->Reset();
 	delete persist_tpl_;
 
-	php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData(0);
+	v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
 
 	ctx->weak_closures.at(persist_tpl_).Reset();
 	ctx->weak_closures.erase(persist_tpl_);
@@ -292,10 +293,10 @@ static void php_v8js_weak_closure_callback(const v8::WeakCallbackData<v8::Object
 	!strncasecmp(key, mname, key_len - 1))
 
 #define PHP_V8JS_CALLBACK(isolate, mptr, tmpl)										\
-	v8::FunctionTemplate::New((isolate), php_v8js_php_callback, v8::External::New((isolate), mptr), v8::Signature::New((isolate), tmpl))->GetFunction()
+	v8::FunctionTemplate::New((isolate), v8js_php_callback, v8::External::New((isolate), mptr), v8::Signature::New((isolate), tmpl))->GetFunction()
 
 
-static void php_v8js_named_property_enumerator(const v8::PropertyCallbackInfo<v8::Array> &info) /* {{{ */
+static void v8js_named_property_enumerator(const v8::PropertyCallbackInfo<v8::Array> &info) /* {{{ */
 {
 	// note: 'special' properties like 'constructor' are not enumerated.
 	v8::Isolate *isolate = info.GetIsolate();
@@ -392,7 +393,7 @@ static void php_v8js_named_property_enumerator(const v8::PropertyCallbackInfo<v8
 }
 /* }}} */
 
-static void php_v8js_invoke_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
+static void v8js_invoke_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
 {
 	v8::Isolate *isolate = info.GetIsolate();
 	v8::Local<v8::Object> self = info.Holder();
@@ -409,7 +410,7 @@ static void php_v8js_invoke_callback(const v8::FunctionCallbackInfo<v8::Value>&
 	}
 
 	if (info.IsConstructCall()) {
-		php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData(0);
+		v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
 
 		v8::String::Utf8Value str(self->GetConstructorName()->ToString());
 		const char *constructor_name = ToCString(str);
@@ -431,7 +432,7 @@ static void php_v8js_invoke_callback(const v8::FunctionCallbackInfo<v8::Value>&
 // this is a magic '__call' implementation for PHP classes which don't actually
 // have a '__call' magic function.  This way we can always force a method
 // call (as opposed to a property get) from JavaScript using __call.
-static void php_v8js_fake_call_impl(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
+static void v8js_fake_call_impl(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
 {
 	v8::Isolate *isolate = info.GetIsolate();
 	v8::Local<v8::Object> self = info.Holder();
@@ -499,7 +500,7 @@ static void php_v8js_fake_call_impl(const v8::FunctionCallbackInfo<v8::Value>& i
 	v8::Local<v8::FunctionTemplate> tmpl =
 		v8::Local<v8::FunctionTemplate>::New
 			(isolate, *reinterpret_cast<v8js_tmpl_t *>(self->GetAlignedPointerFromInternalField(0)));
-	// use php_v8js_php_callback to actually execute the method
+	// use v8js_php_callback to actually execute the method
 	v8::Local<v8::Function> cb = PHP_V8JS_CALLBACK(isolate, method_ptr, tmpl);
 	uint32_t i, argc = args->Length();
 	v8::Local<v8::Value> *argv = static_cast<v8::Local<v8::Value> *>(alloca(sizeof(v8::Local<v8::Value>) * argc));
@@ -514,7 +515,7 @@ static void php_v8js_fake_call_impl(const v8::FunctionCallbackInfo<v8::Value>& i
 
 /* This method handles named property and method get/set/query/delete. */
 template<typename T>
-inline v8::Local<v8::Value> php_v8js_named_property_callback(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<T> &info, property_op_t callback_type, v8::Local<v8::Value> set_value) /* {{{ */
+inline v8::Local<v8::Value> v8js_named_property_callback(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<T> &info, property_op_t callback_type, v8::Local<v8::Value> set_value) /* {{{ */
 {
 	v8::Isolate *isolate = info.GetIsolate();
 	v8::String::Utf8Value cstr(property);
@@ -569,7 +570,7 @@ inline v8::Local<v8::Value> php_v8js_named_property_callback(v8::Local<v8::Strin
 					//  there is no actual PHP __call() implementation)
 					v8::Local<v8::Function> cb =
 						v8::FunctionTemplate::New(isolate,
-							php_v8js_fake_call_impl, V8JS_NULL,
+							v8js_fake_call_impl, V8JS_NULL,
 							v8::Signature::New(isolate, tmpl))->GetFunction();
 					cb->SetName(property);
 					ret_value = cb;
@@ -734,30 +735,30 @@ inline v8::Local<v8::Value> php_v8js_named_property_callback(v8::Local<v8::Strin
 }
 /* }}} */
 
-static void php_v8js_named_property_getter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */
+static void v8js_named_property_getter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */
 {
-	info.GetReturnValue().Set(php_v8js_named_property_callback(property, info, V8JS_PROP_GETTER));
+	info.GetReturnValue().Set(v8js_named_property_callback(property, info, V8JS_PROP_GETTER));
 }
 /* }}} */
 
-static void php_v8js_named_property_setter(v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */
+static void v8js_named_property_setter(v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */
 {
-	info.GetReturnValue().Set(php_v8js_named_property_callback(property, info, V8JS_PROP_SETTER, value));
+	info.GetReturnValue().Set(v8js_named_property_callback(property, info, V8JS_PROP_SETTER, value));
 }
 /* }}} */
 
-static void php_v8js_named_property_query(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Integer> &info) /* {{{ */
+static void v8js_named_property_query(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Integer> &info) /* {{{ */
 {
-	v8::Local<v8::Value> r = php_v8js_named_property_callback(property, info, V8JS_PROP_QUERY);
+	v8::Local<v8::Value> r = v8js_named_property_callback(property, info, V8JS_PROP_QUERY);
 	if (!r.IsEmpty()) {
 		info.GetReturnValue().Set(r->ToInteger());
 	}
 }
 /* }}} */
 
-static void php_v8js_named_property_deleter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Boolean> &info) /* {{{ */
+static void v8js_named_property_deleter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Boolean> &info) /* {{{ */
 {
-	v8::Local<v8::Value> r = php_v8js_named_property_callback(property, info, V8JS_PROP_DELETER);
+	v8::Local<v8::Value> r = v8js_named_property_callback(property, info, V8JS_PROP_DELETER);
 	if (!r.IsEmpty()) {
 		info.GetReturnValue().Set(r->ToBoolean());
 	}
@@ -766,9 +767,9 @@ static void php_v8js_named_property_deleter(v8::Local<v8::String> property, cons
 
 
 
-static v8::Handle<v8::Object> php_v8js_wrap_object(v8::Isolate *isolate, zend_class_entry *ce, zval *value TSRMLS_DC) /* {{{ */
+static v8::Handle<v8::Object> v8js_wrap_object(v8::Isolate *isolate, zend_class_entry *ce, zval *value TSRMLS_DC) /* {{{ */
 {
-	php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData(0);
+	v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
 	v8::Local<v8::FunctionTemplate> new_tpl;
 	v8js_tmpl_t *persist_tpl_;
 
@@ -786,8 +787,8 @@ static v8::Handle<v8::Object> php_v8js_wrap_object(v8::Isolate *isolate, zend_cl
 		if (ce == zend_ce_closure) {
 			/* Got a closure, mustn't cache ... */
 			persist_tpl_ = new v8js_tmpl_t(isolate, new_tpl);
-			/* We'll free persist_tpl_ via php_v8js_weak_closure_callback, below */
-			new_tpl->InstanceTemplate()->SetCallAsFunctionHandler(php_v8js_php_callback);
+			/* We'll free persist_tpl_ via v8js_weak_closure_callback, below */
+			new_tpl->InstanceTemplate()->SetCallAsFunctionHandler(v8js_php_callback);
 		} else {
 			/* Add new v8::FunctionTemplate to tpl_map, as long as it is not a closure. */
 			persist_tpl_ = &ctx->template_cache[ce->name];
@@ -795,8 +796,8 @@ static v8::Handle<v8::Object> php_v8js_wrap_object(v8::Isolate *isolate, zend_cl
 			/* We'll free persist_tpl_ when template_cache is destroyed */
 
 			v8::Local<v8::ObjectTemplate> inst_tpl = new_tpl->InstanceTemplate();
-			v8::NamedPropertyGetterCallback getter = php_v8js_named_property_getter;
-			v8::NamedPropertyEnumeratorCallback enumerator = php_v8js_named_property_enumerator;
+			v8::NamedPropertyGetterCallback getter = v8js_named_property_getter;
+			v8::NamedPropertyEnumeratorCallback enumerator = v8js_named_property_enumerator;
 
 			/* Check for ArrayAccess object */
 			if (V8JSG(use_array_access) && ce) {
@@ -813,16 +814,16 @@ static v8::Handle<v8::Object> php_v8js_wrap_object(v8::Isolate *isolate, zend_cl
 				}
 
 				if(has_array_access && has_countable) {
-					inst_tpl->SetIndexedPropertyHandler(php_v8js_array_access_getter,
-														php_v8js_array_access_setter,
-														php_v8js_array_access_query,
-														php_v8js_array_access_deleter,
-														php_v8js_array_access_enumerator);
+					inst_tpl->SetIndexedPropertyHandler(v8js_array_access_getter,
+														v8js_array_access_setter,
+														v8js_array_access_query,
+														v8js_array_access_deleter,
+														v8js_array_access_enumerator);
 
 					/* Switch to special ArrayAccess getter, which falls back to
-					 * php_v8js_named_property_getter, but possibly bridges the
+					 * v8js_named_property_getter, but possibly bridges the
 					 * call to Array.prototype functions. */
-					getter = php_v8js_array_access_named_getter;
+					getter = v8js_array_access_named_getter;
 
 					/* Overwrite enumerator, since for(... in ...) loop should
 					 * not see the methods but iterate over the elements. */
@@ -834,9 +835,9 @@ static v8::Handle<v8::Object> php_v8js_wrap_object(v8::Isolate *isolate, zend_cl
 			// Finish setup of new_tpl
 			inst_tpl->SetNamedPropertyHandler
 				(getter, /* getter */
-				 php_v8js_named_property_setter, /* setter */
-				 php_v8js_named_property_query, /* query */
-				 php_v8js_named_property_deleter, /* deleter */
+				 v8js_named_property_setter, /* setter */
+				 v8js_named_property_query, /* query */
+				 v8js_named_property_deleter, /* deleter */
 				 enumerator, /* enumerator */
 				 V8JS_NULL /* data */
 				 );
@@ -846,13 +847,13 @@ static v8::Handle<v8::Object> php_v8js_wrap_object(v8::Isolate *isolate, zend_cl
 							   sizeof(ZEND_INVOKE_FUNC_NAME),
 							   (void**)&invoke_method_ptr) == SUCCESS &&
 				invoke_method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) {
-				new_tpl->InstanceTemplate()->SetCallAsFunctionHandler(php_v8js_invoke_callback, PHP_V8JS_CALLBACK(isolate, invoke_method_ptr, new_tpl));
+				new_tpl->InstanceTemplate()->SetCallAsFunctionHandler(v8js_invoke_callback, PHP_V8JS_CALLBACK(isolate, invoke_method_ptr, new_tpl));
 			}
 		}
 		v8::Local<v8::Array> call_handler_data = v8::Array::New(isolate, 2);
 		call_handler_data->Set(0, v8::External::New(isolate, persist_tpl_));
 		call_handler_data->Set(1, v8::External::New(isolate, ce));
-		new_tpl->SetCallHandler(php_v8js_construct_callback, call_handler_data);
+		new_tpl->SetCallHandler(v8js_construct_callback, call_handler_data);
 	}
 
 	// Create v8 wrapper object
@@ -862,7 +863,7 @@ static v8::Handle<v8::Object> php_v8js_wrap_object(v8::Isolate *isolate, zend_cl
 	if (ce == zend_ce_closure) {
 		// free uncached function template when object is freed
 		ctx->weak_closures[persist_tpl_].Reset(isolate, newobj);
-		ctx->weak_closures[persist_tpl_].SetWeak(persist_tpl_, php_v8js_weak_closure_callback);
+		ctx->weak_closures[persist_tpl_].SetWeak(persist_tpl_, v8js_weak_closure_callback);
 	}
 
 	return newobj;
@@ -870,7 +871,7 @@ static v8::Handle<v8::Object> php_v8js_wrap_object(v8::Isolate *isolate, zend_cl
 /* }}} */
 
 
-static v8::Handle<v8::Object> php_v8js_wrap_array_to_object(v8::Isolate *isolate, zval *value TSRMLS_DC) /* {{{ */
+static v8::Handle<v8::Object> v8js_wrap_array_to_object(v8::Isolate *isolate, zval *value TSRMLS_DC) /* {{{ */
 {
 	int i;
 	HashPosition pos;
@@ -935,7 +936,7 @@ static v8::Handle<v8::Object> php_v8js_wrap_array_to_object(v8::Isolate *isolate
 /* }}} */
 
 
-v8::Handle<v8::Value> php_v8js_hash_to_jsobj(zval *value, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
+v8::Handle<v8::Value> v8js_hash_to_jsobj(zval *value, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
 {
 	HashTable *myht;
 	zend_class_entry *ce = NULL;
@@ -953,8 +954,8 @@ v8::Handle<v8::Value> php_v8js_hash_to_jsobj(zval *value, v8::Isolate *isolate T
 	}
 
 	/* Special case, passing back object originating from JS to JS */
-	if (ce == php_ce_v8_function) {
-		php_v8js_object *c = (php_v8js_object *) zend_object_store_get_object(value TSRMLS_CC);
+	if (ce == php_ce_v8function) {
+		v8js_v8object *c = (v8js_v8object *) zend_object_store_get_object(value TSRMLS_CC);
 
 		if(isolate != c->ctx->isolate) {
 			php_error_docref(NULL TSRMLS_CC, E_WARNING, "V8Function object passed to wrong V8Js instance");
@@ -966,12 +967,12 @@ v8::Handle<v8::Value> php_v8js_hash_to_jsobj(zval *value, v8::Isolate *isolate T
 
 	/* If it's a PHP object, wrap it */
 	if (ce) {
-		return php_v8js_wrap_object(isolate, ce, value TSRMLS_CC);
+		return v8js_wrap_object(isolate, ce, value TSRMLS_CC);
 	}
 
 	/* Associative PHP arrays cannot be wrapped to JS arrays, convert them to
 	 * JS objects and attach all their array keys as properties. */
-	return php_v8js_wrap_array_to_object(isolate, value TSRMLS_CC);
+	return v8js_wrap_array_to_object(isolate, value TSRMLS_CC);
 }
 /* }}} */
 

+ 2 - 2
v8js_object_export.h

@@ -14,7 +14,7 @@
 #ifndef V8JS_OBJECT_EXPORT_H
 #define V8JS_OBJECT_EXPORT_H
 
-v8::Handle<v8::Value> php_v8js_hash_to_jsobj(zval *value, v8::Isolate *isolate TSRMLS_DC);
+v8::Handle<v8::Value> v8js_hash_to_jsobj(zval *value, v8::Isolate *isolate TSRMLS_DC);
 
 
 typedef enum {
@@ -25,7 +25,7 @@ typedef enum {
 } property_op_t;
 
 template<typename T>
-v8::Local<v8::Value> php_v8js_named_property_callback(v8::Local<v8::String> property,
+v8::Local<v8::Value> v8js_named_property_callback(v8::Local<v8::String> property,
 						      const v8::PropertyCallbackInfo<T> &info,
 						      property_op_t callback_type,
 						      v8::Local<v8::Value> set_value = v8::Local<v8::Value>());

+ 143 - 0
v8js_timer.cc

@@ -0,0 +1,143 @@
+/*
+  +----------------------------------------------------------------------+
+  | PHP Version 5                                                        |
+  +----------------------------------------------------------------------+
+  | Copyright (c) 1997-2013 The PHP Group                                |
+  +----------------------------------------------------------------------+
+  | http://www.opensource.org/licenses/mit-license.php  MIT License      |
+  +----------------------------------------------------------------------+
+  | Author: Jani Taskinen <[email protected]>                         |
+  | Author: Patrick Reilly <[email protected]>                             |
+  +----------------------------------------------------------------------+
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+extern "C" {
+#include "php.h"
+#include "ext/date/php_date.h"
+#include "ext/standard/php_string.h"
+#include "zend_interfaces.h"
+#include "zend_closures.h"
+#include "ext/spl/spl_exceptions.h"
+#include "zend_exceptions.h"
+}
+
+#include "php_v8js_macros.h"
+#include "v8js_v8.h"
+#include "v8js_exceptions.h"
+
+static void v8js_timer_interrupt_handler(v8::Isolate *isolate, void *data) { /* {{{ */
+#ifdef ZTS
+	TSRMLS_D = (void ***) data;
+#endif
+
+	if (!V8JSG(timer_stack).size()) {
+		return;
+	}
+
+	v8::Locker locker(isolate);
+	v8::HeapStatistics hs;
+	isolate->GetHeapStatistics(&hs);
+
+	V8JSG(timer_mutex).lock();
+
+	for (std::deque< v8js_timer_ctx* >::iterator it = V8JSG(timer_stack).begin();
+		 it != V8JSG(timer_stack).end(); it ++) {
+		v8js_timer_ctx *timer_ctx = *it;
+		v8js_ctx *c = timer_ctx->ctx;
+
+		if(c->isolate != isolate || timer_ctx->killed) {
+			continue;
+		}
+
+		if (timer_ctx->memory_limit > 0 && hs.used_heap_size() > timer_ctx->memory_limit) {
+			timer_ctx->killed = true;
+			v8js_terminate_execution(c TSRMLS_CC);
+			c->memory_limit_hit = true;
+		}
+	}
+
+	V8JSG(timer_mutex).unlock();
+}
+/* }}} */
+
+void v8js_timer_thread(TSRMLS_D) /* {{{ */
+{
+	while (!V8JSG(timer_stop)) {
+
+		V8JSG(timer_mutex).lock();
+		if (V8JSG(timer_stack).size()) {
+			v8js_timer_ctx *timer_ctx = V8JSG(timer_stack).front();
+			v8js_ctx *c = timer_ctx->ctx;
+			std::chrono::time_point<std::chrono::high_resolution_clock> now = std::chrono::high_resolution_clock::now();
+
+			if(timer_ctx->killed) {
+				/* execution already terminated, nothing to check anymore,
+				 * but wait for caller to pop this timer context. */
+			}
+			else if(timer_ctx->time_limit > 0 && now > timer_ctx->time_point) {
+				timer_ctx->killed = true;
+				v8js_terminate_execution(c TSRMLS_CC);
+				c->time_limit_hit = true;
+			}
+			else if (timer_ctx->memory_limit > 0) {
+				/* If a memory_limit is set, we need to interrupt execution
+				 * and check heap size within the callback.  We must *not*
+				 * directly call GetHeapStatistics here, since we don't have
+				 * a v8::Locker on the isolate, but are expected to hold one,
+				 * and cannot aquire it as v8 is executing the script ... */
+				void *data = NULL;
+#ifdef ZTS
+				data = (void *) TSRMLS_C;
+#endif
+				c->isolate->RequestInterrupt(v8js_timer_interrupt_handler, data);
+			}
+		}
+		V8JSG(timer_mutex).unlock();
+
+		// Sleep for 10ms
+#ifdef _WIN32
+		concurrency::wait(10);
+#else
+		std::chrono::milliseconds duration(10);
+		std::this_thread::sleep_for(duration);
+#endif
+	}
+}
+/* }}} */
+
+
+void v8js_timer_push(long time_limit, long memory_limit, v8js_ctx *c TSRMLS_DC) /* {{{ */
+{
+	V8JSG(timer_mutex).lock();
+
+	// Create context for this timer
+	v8js_timer_ctx *timer_ctx = (v8js_timer_ctx *)emalloc(sizeof(v8js_timer_ctx));
+
+	// Calculate the time point when the time limit is exceeded
+	std::chrono::milliseconds duration(time_limit);
+	std::chrono::time_point<std::chrono::high_resolution_clock> from = std::chrono::high_resolution_clock::now();
+
+	// Push the timer context
+	timer_ctx->time_limit = time_limit;
+	timer_ctx->memory_limit = memory_limit;
+	timer_ctx->time_point = from + duration;
+	timer_ctx->ctx = c;
+	timer_ctx->killed = false;
+	V8JSG(timer_stack).push_front(timer_ctx);
+
+	V8JSG(timer_mutex).unlock();
+}
+/* }}} */
+
+/*
+ * Local variables:
+ * tab-width: 4
+ * c-basic-offset: 4
+ * End:
+ * vim600: noet sw=4 ts=4 fdm=marker
+ * vim<600: noet sw=4 ts=4
+ */

+ 39 - 0
v8js_timer.h

@@ -0,0 +1,39 @@
+/*
+  +----------------------------------------------------------------------+
+  | PHP Version 5                                                        |
+  +----------------------------------------------------------------------+
+  | Copyright (c) 1997-2013 The PHP Group                                |
+  +----------------------------------------------------------------------+
+  | http://www.opensource.org/licenses/mit-license.php  MIT License      |
+  +----------------------------------------------------------------------+
+  | Author: Jani Taskinen <[email protected]>                         |
+  | Author: Patrick Reilly <[email protected]>                             |
+  +----------------------------------------------------------------------+
+*/
+
+#ifndef V8JS_TIMER_H
+#define V8JS_TIMER_H
+
+// Timer context
+struct v8js_timer_ctx
+{
+  long time_limit;
+  long memory_limit;
+  std::chrono::time_point<std::chrono::high_resolution_clock> time_point;
+  v8js_ctx *ctx;
+  bool killed;
+};
+
+void v8js_timer_thread(TSRMLS_D);
+void v8js_timer_push(long time_limit, long memory_limit, v8js_ctx *c TSRMLS_DC);
+
+#endif /* V8JS_TIMER_H */
+
+/*
+ * Local variables:
+ * tab-width: 4
+ * c-basic-offset: 4
+ * End:
+ * vim600: noet sw=4 ts=4 fdm=marker
+ * vim<600: noet sw=4 ts=4
+ */

+ 270 - 0
v8js_v8.cc

@@ -0,0 +1,270 @@
+/*
+  +----------------------------------------------------------------------+
+  | PHP Version 5                                                        |
+  +----------------------------------------------------------------------+
+  | Copyright (c) 1997-2013 The PHP Group                                |
+  +----------------------------------------------------------------------+
+  | http://www.opensource.org/licenses/mit-license.php  MIT License      |
+  +----------------------------------------------------------------------+
+  | Author: Jani Taskinen <[email protected]>                         |
+  | Author: Patrick Reilly <[email protected]>                             |
+  +----------------------------------------------------------------------+
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#if !defined(_WIN32) && PHP_V8_API_VERSION >= 3029036
+#include <libplatform/libplatform.h>
+#endif
+
+extern "C" {
+#include "php.h"
+#include "ext/date/php_date.h"
+#include "ext/standard/php_string.h"
+#include "zend_interfaces.h"
+#include "zend_closures.h"
+#include "zend_exceptions.h"
+}
+
+#include "php_v8js_macros.h"
+#include "v8js_v8.h"
+#include "v8js_timer.h"
+#include "v8js_exceptions.h"
+
+void v8js_v8_init(TSRMLS_D) /* {{{ */
+{
+	/* Run only once */
+	if (V8JSG(v8_initialized)) {
+		return;
+	}
+
+#if !defined(_WIN32) && PHP_V8_API_VERSION >= 3029036
+	v8::Platform* platform = v8::platform::CreateDefaultPlatform();
+	v8::V8::InitializePlatform(platform);
+#endif
+
+	/* Set V8 command line flags (must be done before V8::Initialize()!) */
+	if (V8JSG(v8_flags)) {
+		v8::V8::SetFlagsFromString(V8JSG(v8_flags), strlen(V8JSG(v8_flags)));
+	}
+
+	/* Initialize V8 */
+	v8::V8::Initialize();
+
+	/* Run only once */
+	V8JSG(v8_initialized) = 1;
+}
+/* }}} */
+
+
+void v8js_v8_call(v8js_ctx *c, zval **return_value,
+				  long flags, long time_limit, long memory_limit,
+				  std::function< v8::Local<v8::Value>(v8::Isolate *) >& v8_call TSRMLS_DC) /* {{{ */
+{
+	char *tz = NULL;
+
+	V8JS_CTX_PROLOGUE(c);
+
+	V8JSG(timer_mutex).lock();
+	c->time_limit_hit = false;
+	c->memory_limit_hit = false;
+	V8JSG(timer_mutex).unlock();
+
+	/* Catch JS exceptions */
+	v8::TryCatch try_catch;
+
+	/* Set flags for runtime use */
+	V8JS_GLOBAL_SET_FLAGS(isolate, flags);
+
+	/* Check if timezone has been changed and notify V8 */
+	tz = getenv("TZ");
+
+	if (tz != NULL) {
+		if (c->tz == NULL) {
+			c->tz = strdup(tz);
+		}
+		else if (strcmp(c->tz, tz) != 0) {
+			v8::Date::DateTimeConfigurationChangeNotification(c->isolate);
+
+			free(c->tz);
+			c->tz = strdup(tz);
+		}
+	}
+
+	if (time_limit > 0 || memory_limit > 0) {
+		// If timer thread is not running then start it
+		if (!V8JSG(timer_thread)) {
+			// If not, start timer thread
+			V8JSG(timer_thread) = new std::thread(v8js_timer_thread TSRMLS_CC);
+		}
+	}
+
+	/* Always pass the timer to the stack so there can be follow-up changes to
+	 * the time & memory limit. */
+	v8js_timer_push(time_limit, memory_limit, c TSRMLS_CC);
+
+#ifdef ENABLE_DEBUGGER_SUPPORT
+	if(c == v8js_debug_context && v8js_debug_auto_break_mode != V8JS_DEBUG_AUTO_BREAK_NEVER) {
+		v8::Debug::DebugBreak(c->isolate);
+
+		if(v8js_debug_auto_break_mode == V8JS_DEBUG_AUTO_BREAK_ONCE) {
+			/* If break-once-mode was enabled, reset flag. */
+			v8js_debug_auto_break_mode = V8JS_DEBUG_AUTO_BREAK_NEVER;
+		}
+	}
+#endif  /* ENABLE_DEBUGGER_SUPPORT */
+
+	/* Execute script */
+	c->in_execution++;
+	v8::Local<v8::Value> result = v8_call(c->isolate);
+	c->in_execution--;
+
+	/* Pop our context from the stack and read (possibly updated) limits
+	 * into local variables. */
+	V8JSG(timer_mutex).lock();
+	v8js_timer_ctx *timer_ctx = V8JSG(timer_stack).front();
+	V8JSG(timer_stack).pop_front();
+	V8JSG(timer_mutex).unlock();
+
+	time_limit = timer_ctx->time_limit;
+	memory_limit = timer_ctx->memory_limit;
+
+	efree(timer_ctx);
+
+	/* Check for fatal error marker possibly set by v8js_error_handler; just
+	 * rethrow the error since we're now out of V8. */
+	if(V8JSG(fatal_error_abort)) {
+		zend_bailout();
+	}
+
+	char exception_string[64];
+
+	if (c->time_limit_hit) {
+		// Execution has been terminated due to time limit
+		sprintf(exception_string, "Script time limit of %lu milliseconds exceeded", time_limit);
+		zend_throw_exception(php_ce_v8js_time_limit_exception, exception_string, 0 TSRMLS_CC);
+		return;
+	}
+
+	if (c->memory_limit_hit) {
+		// Execution has been terminated due to memory limit
+		sprintf(exception_string, "Script memory limit of %lu bytes exceeded", memory_limit);
+		zend_throw_exception(php_ce_v8js_memory_limit_exception, exception_string, 0 TSRMLS_CC);
+		return;
+	}
+
+	if (!try_catch.CanContinue()) {
+		// At this point we can't re-throw the exception
+		return;
+	}
+
+	/* There was pending exception left from earlier executions -> throw to PHP */
+	if (c->pending_exception) {
+		zend_throw_exception_object(c->pending_exception TSRMLS_CC);
+		c->pending_exception = NULL;
+	}
+
+	/* Handle runtime JS exceptions */
+	if (try_catch.HasCaught()) {
+
+		/* Pending exceptions are set only in outer caller, inner caller exceptions are always rethrown */
+		if (c->in_execution < 1) {
+
+			/* Report immediately if report_uncaught is true */
+			if (c->report_uncaught) {
+				v8js_throw_script_exception(&try_catch TSRMLS_CC);
+				return;
+			}
+
+			/* Exception thrown from JS, preserve it for future execution */
+			if (result.IsEmpty()) {
+				MAKE_STD_ZVAL(c->pending_exception);
+				v8js_create_script_exception(c->pending_exception, &try_catch TSRMLS_CC);
+				return;
+			}
+		}
+
+		/* Rethrow back to JS */
+		try_catch.ReThrow();
+		return;
+	}
+
+	/* Convert V8 value to PHP value */
+	if (!result.IsEmpty()) {
+		v8js_to_zval(result, *return_value, flags, c->isolate TSRMLS_CC);
+	}
+}
+/* }}} */
+
+void v8js_terminate_execution(v8js_ctx *c TSRMLS_DC) /* {{{ */
+{
+	// Forcefully terminate the current thread of V8 execution in the isolate
+	v8::V8::TerminateExecution(c->isolate);
+}
+/* }}} */
+
+
+int v8js_get_properties_hash(v8::Handle<v8::Value> jsValue, HashTable *retval, int flags, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
+{
+	v8::Local<v8::Object> jsObj = jsValue->ToObject();
+
+	if (!jsObj.IsEmpty()) {
+		v8::Local<v8::Array> jsKeys = jsObj->GetPropertyNames();
+
+		for (unsigned i = 0; i < jsKeys->Length(); i++)
+		{
+			v8::Local<v8::String> jsKey = jsKeys->Get(i)->ToString();
+
+			/* Skip any prototype properties */
+			if (!jsObj->HasOwnProperty(jsKey) && !jsObj->HasRealNamedProperty(jsKey) && !jsObj->HasRealNamedCallbackProperty(jsKey)) {
+				continue;
+			}
+
+			v8::Local<v8::Value> jsVal = jsObj->Get(jsKey);
+			v8::String::Utf8Value cstr(jsKey);
+			const char *key = ToCString(cstr);
+			zval *value = NULL;
+
+			v8::Local<v8::Value> php_object;
+			if (jsVal->IsObject()) {
+				php_object = v8::Local<v8::Object>::Cast(jsVal)->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY));
+			}
+			if (!php_object.IsEmpty()) {
+				/* This is a PHP object, passed to JS and back. */
+				value = reinterpret_cast<zval *>(v8::External::Cast(*php_object)->Value());
+				Z_ADDREF_P(value);
+			}
+			else {
+				MAKE_STD_ZVAL(value);
+
+				if (v8js_to_zval(jsVal, value, flags, isolate TSRMLS_CC) == FAILURE) {
+					zval_ptr_dtor(&value);
+					return FAILURE;
+				}
+			}
+
+			if ((flags & V8JS_FLAG_FORCE_ARRAY) || jsValue->IsArray()) {
+				zend_symtable_update(retval, key, strlen(key) + 1, (void *)&value, sizeof(zval *), NULL);
+			} else {
+				zend_hash_update(retval, key, strlen(key) + 1, (void *) &value, sizeof(zval *), NULL);
+			}
+		}
+		return SUCCESS;
+	}
+	return FAILURE;
+}
+/* }}} */
+
+
+
+
+/*
+ * Local variables:
+ * tab-width: 4
+ * c-basic-offset: 4
+ * End:
+ * vim600: noet sw=4 ts=4 fdm=marker
+ * vim<600: noet sw=4 ts=4
+ */

+ 81 - 0
v8js_v8.h

@@ -0,0 +1,81 @@
+/*
+  +----------------------------------------------------------------------+
+  | PHP Version 5                                                        |
+  +----------------------------------------------------------------------+
+  | Copyright (c) 1997-2013 The PHP Group                                |
+  +----------------------------------------------------------------------+
+  | http://www.opensource.org/licenses/mit-license.php  MIT License      |
+  +----------------------------------------------------------------------+
+  | Author: Jani Taskinen <[email protected]>                         |
+  | Author: Patrick Reilly <[email protected]>                             |
+  +----------------------------------------------------------------------+
+*/
+
+#ifndef V8JS_V8_H
+#define V8JS_V8_H
+
+/* Helper macros */
+#define V8JS_SYM(v)			v8::String::NewFromUtf8(isolate, v, v8::String::kInternalizedString, sizeof(v) - 1)
+#define V8JS_SYML(v, l)		v8::String::NewFromUtf8(isolate, v, v8::String::kInternalizedString, l)
+#define V8JS_STR(v)			v8::String::NewFromUtf8(isolate, v)
+#define V8JS_STRL(v, l)		v8::String::NewFromUtf8(isolate, v, v8::String::kNormalString, l)
+#define V8JS_INT(v)			v8::Integer::New(isolate, v)
+#define V8JS_UINT(v)		v8::Integer::NewFromUnsigned(isolate, v)
+#define V8JS_FLOAT(v)		v8::Number::New(isolate, v)
+#define V8JS_BOOL(v)		((v)?v8::True(isolate):v8::False(isolate))
+#define V8JS_DATE(v)		v8::Date::New(isolate, v)
+#define V8JS_NULL			v8::Null(isolate)
+#define V8JS_UNDEFINED		v8::Undefined(isolate)
+#define V8JS_MN(name)		v8js_method_##name
+#define V8JS_METHOD(name)	void V8JS_MN(name)(const v8::FunctionCallbackInfo<v8::Value>& info)
+#define V8JS_THROW(isolate, type, message, message_len)	(isolate)->ThrowException(v8::Exception::type(V8JS_STRL(message, message_len)))
+#define V8JS_GLOBAL(isolate)			((isolate)->GetCurrentContext()->Global())
+
+
+/* Extracts a C string from a V8 Utf8Value. */
+static inline const char * ToCString(const v8::String::Utf8Value &value) /* {{{ */
+{
+	return *value ? *value : "<string conversion failed>";
+}
+/* }}} */
+
+
+
+void v8js_v8_init(TSRMLS_D);
+void v8js_v8_call(v8js_ctx *c, zval **return_value,
+				  long flags, long time_limit, long memory_limit,
+				  std::function< v8::Local<v8::Value>(v8::Isolate *) >& v8_call TSRMLS_DC);
+void v8js_terminate_execution(v8js_ctx *c TSRMLS_DC);
+
+/* Fetch V8 object properties */
+int v8js_get_properties_hash(v8::Handle<v8::Value> jsValue, HashTable *retval, int flags, v8::Isolate *isolate TSRMLS_DC);
+
+#define V8JS_CTX_PROLOGUE(ctx) \
+	if (!V8JSG(v8_initialized)) { \
+		zend_error(E_ERROR, "V8 not initialized"); \
+		return; \
+	} \
+	\
+	v8::Isolate *isolate = (ctx)->isolate; \
+	v8::Locker locker(isolate); \
+	v8::Isolate::Scope isolate_scope(isolate); \
+	v8::HandleScope handle_scope(isolate); \
+	v8::Local<v8::Context> v8_context = v8::Local<v8::Context>::New(isolate, (ctx)->context); \
+	v8::Context::Scope context_scope(v8_context);
+
+#define V8JS_BEGIN_CTX(ctx, object) \
+	v8js_ctx *(ctx); \
+	(ctx) = (v8js_ctx *) zend_object_store_get_object(object TSRMLS_CC); \
+	V8JS_CTX_PROLOGUE(ctx);
+
+
+#endif /* V8JS_V8_H */
+
+/*
+ * Local variables:
+ * tab-width: 4
+ * c-basic-offset: 4
+ * End:
+ * vim600: noet sw=4 ts=4 fdm=marker
+ * vim<600: noet sw=4 ts=4
+ */

+ 588 - 0
v8js_v8object_class.cc

@@ -0,0 +1,588 @@
+/*
+  +----------------------------------------------------------------------+
+  | PHP Version 5                                                        |
+  +----------------------------------------------------------------------+
+  | Copyright (c) 1997-2013 The PHP Group                                |
+  +----------------------------------------------------------------------+
+  | http://www.opensource.org/licenses/mit-license.php  MIT License      |
+  +----------------------------------------------------------------------+
+  | Author: Jani Taskinen <[email protected]>                         |
+  | Author: Patrick Reilly <[email protected]>                             |
+  +----------------------------------------------------------------------+
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+extern "C" {
+#include "php.h"
+#include "ext/date/php_date.h"
+#include "ext/standard/php_string.h"
+#include "zend_interfaces.h"
+#include "zend_closures.h"
+#include "ext/spl/spl_exceptions.h"
+#include "zend_exceptions.h"
+}
+
+#include "php_v8js_macros.h"
+#include "v8js_exceptions.h"
+#include "v8js_v8.h"
+#include "v8js_v8object_class.h"
+
+/* {{{ Class Entries */
+zend_class_entry *php_ce_v8object;
+zend_class_entry *php_ce_v8function;
+/* }}} */
+
+/* {{{ Object Handlers */
+static zend_object_handlers v8js_v8object_handlers;
+/* }}} */
+
+#define V8JS_V8_INVOKE_FUNC_NAME "V8Js::V8::Invoke"
+
+
+/* V8 Object handlers */
+
+static int v8js_v8object_has_property(zval *object, zval *member, int has_set_exists ZEND_HASH_KEY_DC TSRMLS_DC) /* {{{ */
+{
+	/* param has_set_exists:
+	 * 0 (has) whether property exists and is not NULL  - isset()
+	 * 1 (set) whether property exists and is true-ish  - empty()
+	 * 2 (exists) whether property exists               - property_exists()
+	 */
+	int retval = false;
+	v8js_v8object *obj = (v8js_v8object *) zend_object_store_get_object(object TSRMLS_CC);
+
+	if (!obj->ctx) {
+		zend_throw_exception(php_ce_v8js_exception,
+			"Can't access V8Object after V8Js instance is destroyed!", 0 TSRMLS_CC);
+		return retval;
+	}
+
+	v8::Isolate *isolate = obj->ctx->isolate;
+	v8::Locker locker(isolate);
+	v8::Isolate::Scope isolate_scope(isolate);
+	v8::HandleScope local_scope(isolate);
+	v8::Local<v8::Context> temp_context = v8::Context::New(isolate);
+	v8::Context::Scope temp_scope(temp_context);
+
+	v8::Local<v8::Value> v8obj = v8::Local<v8::Value>::New(isolate, obj->v8obj);
+
+	if (Z_TYPE_P(member) == IS_STRING && v8obj->IsObject() && !v8obj->IsFunction())
+	{
+
+		v8::Local<v8::Object> jsObj = v8obj->ToObject();
+		v8::Local<v8::String> jsKey = V8JS_STRL(Z_STRVAL_P(member), Z_STRLEN_P(member));
+		v8::Local<v8::Value> jsVal;
+
+		/* Skip any prototype properties */
+		if (jsObj->HasRealNamedProperty(jsKey) || jsObj->HasRealNamedCallbackProperty(jsKey)) {
+			if (has_set_exists == 2) {
+				/* property_exists(), that's enough! */
+				retval = true;
+			} else {
+				/* We need to look at the value. */
+				jsVal = jsObj->Get(jsKey);
+				if (has_set_exists == 0 ) {
+					/* isset(): We make 'undefined' equivalent to 'null' */
+					retval = !( jsVal->IsNull() || jsVal->IsUndefined() );
+				} else {
+					/* empty() */
+					retval = jsVal->BooleanValue();
+					/* for PHP compatibility, [] should also be empty */
+					if (jsVal->IsArray() && retval) {
+						v8::Local<v8::Array> array = v8::Local<v8::Array>::Cast(jsVal);
+						retval = (array->Length() != 0);
+					}
+					/* for PHP compatibility, '0' should also be empty */
+					if (jsVal->IsString() && retval) {
+						v8::Local<v8::String> str = jsVal->ToString();
+						if (str->Length() == 1) {
+							uint16_t c = 0;
+							str->Write(&c, 0, 1);
+							if (c == '0') {
+								retval = false;
+							}
+						}
+					}
+				}
+			}
+		}
+	}
+	return retval;
+}
+/* }}} */
+
+static zval *v8js_v8object_read_property(zval *object, zval *member, int type ZEND_HASH_KEY_DC TSRMLS_DC) /* {{{ */
+{
+	zval *retval = NULL;
+	v8js_v8object *obj = (v8js_v8object *) zend_object_store_get_object(object TSRMLS_CC);
+
+	if (!obj->ctx) {
+		zend_throw_exception(php_ce_v8js_exception,
+			"Can't access V8Object after V8Js instance is destroyed!", 0 TSRMLS_CC);
+		ALLOC_INIT_ZVAL(retval);
+		return retval;
+	}
+
+	v8::Isolate *isolate = obj->ctx->isolate;
+	v8::Locker locker(isolate);
+	v8::Isolate::Scope isolate_scope(isolate);
+	v8::HandleScope local_scope(isolate);
+	v8::Local<v8::Context> temp_context = v8::Context::New(isolate);
+	v8::Context::Scope temp_scope(temp_context);
+
+	v8::Local<v8::Value> v8obj = v8::Local<v8::Value>::New(isolate, obj->v8obj);
+
+	if (Z_TYPE_P(member) == IS_STRING && v8obj->IsObject() && !v8obj->IsFunction())
+	{
+
+		v8::Local<v8::Object> jsObj = v8obj->ToObject();
+		v8::Local<v8::String> jsKey = V8JS_STRL(Z_STRVAL_P(member), Z_STRLEN_P(member));
+		v8::Local<v8::Value> jsVal;
+
+		/* Skip any prototype properties */
+		if (jsObj->HasRealNamedProperty(jsKey) || jsObj->HasRealNamedCallbackProperty(jsKey)) {
+			jsVal = jsObj->Get(jsKey);
+			
+			if (jsVal->IsObject()) {
+				ALLOC_INIT_ZVAL(retval);
+				Z_SET_REFCOUNT_P(retval, 0);
+			} else {
+				MAKE_STD_ZVAL(retval);
+			}
+
+			if (v8js_to_zval(jsVal, retval, obj->flags, isolate TSRMLS_CC) == SUCCESS) {
+				return retval;
+			}
+		}
+	}
+
+	ALLOC_INIT_ZVAL(retval);
+
+	return retval;
+}
+/* }}} */
+
+static void v8js_v8object_write_property(zval *object, zval *member, zval *value ZEND_HASH_KEY_DC TSRMLS_DC) /* {{{ */
+{
+	v8js_v8object *obj = (v8js_v8object *) zend_object_store_get_object(object TSRMLS_CC);
+
+	if (!obj->ctx) {
+		zend_throw_exception(php_ce_v8js_exception,
+			"Can't access V8Object after V8Js instance is destroyed!", 0 TSRMLS_CC);
+		return;
+	}
+
+	v8::Isolate *isolate = obj->ctx->isolate;
+	v8::Locker locker(isolate);
+	v8::Isolate::Scope isolate_scope(isolate);
+	v8::HandleScope local_scope(isolate);
+	v8::Local<v8::Context> temp_context = v8::Context::New(isolate);
+	v8::Context::Scope temp_scope(temp_context);
+
+	v8::Local<v8::Value> v8obj = v8::Local<v8::Value>::New(isolate, obj->v8obj);
+
+	if (v8obj->IsObject() && !v8obj->IsFunction()) {
+		v8obj->ToObject()->ForceSet(V8JS_SYML(Z_STRVAL_P(member), Z_STRLEN_P(member)), zval_to_v8js(value, isolate TSRMLS_CC));
+	}
+}
+/* }}} */
+
+static void v8js_v8object_unset_property(zval *object, zval *member ZEND_HASH_KEY_DC TSRMLS_DC) /* {{{ */
+{
+	v8js_v8object *obj = (v8js_v8object *) zend_object_store_get_object(object TSRMLS_CC);
+
+	if (!obj->ctx) {
+		zend_throw_exception(php_ce_v8js_exception,
+			"Can't access V8Object after V8Js instance is destroyed!", 0 TSRMLS_CC);
+		return;
+	}
+
+	v8::Isolate *isolate = obj->ctx->isolate;
+	v8::Locker locker(isolate);
+	v8::Isolate::Scope isolate_scope(isolate);
+	v8::HandleScope local_scope(isolate);
+	v8::Local<v8::Context> temp_context = v8::Context::New(isolate);
+	v8::Context::Scope temp_scope(temp_context);
+
+	v8::Local<v8::Value> v8obj = v8::Local<v8::Value>::New(isolate, obj->v8obj);
+
+	if (v8obj->IsObject() && !v8obj->IsFunction()) {
+		v8obj->ToObject()->ForceDelete(V8JS_SYML(Z_STRVAL_P(member), Z_STRLEN_P(member)));
+	}
+}
+/* }}} */
+
+static HashTable *v8js_v8object_get_properties(zval *object TSRMLS_DC) /* {{{ */
+{
+	v8js_v8object *obj = (v8js_v8object *) zend_object_store_get_object(object TSRMLS_CC);
+	HashTable *retval;
+
+	if (obj->properties == NULL) {
+		if (GC_G(gc_active)) {
+			/* the garbage collector is running, don't create more zvals */
+			return NULL;
+		}
+
+		ALLOC_HASHTABLE(obj->properties);
+		zend_hash_init(obj->properties, 0, NULL, ZVAL_PTR_DTOR, 0);
+
+		if (!obj->ctx) {
+			/* Half-constructed object, probably due to unserialize call.
+			 * Just pass back properties hash so unserialize can write to
+			 * it (instead of crashing the engine). */
+			return obj->properties;
+		}
+	} else {
+		zend_hash_clean(obj->properties);
+	}
+
+	if (!obj->ctx) {
+		zend_throw_exception(php_ce_v8js_exception,
+			"Can't access V8Object after V8Js instance is destroyed!", 0 TSRMLS_CC);
+		return NULL;
+	}
+
+	v8::Isolate *isolate = obj->ctx->isolate;
+	v8::Locker locker(isolate);
+	v8::Isolate::Scope isolate_scope(isolate);
+	v8::HandleScope local_scope(isolate);
+	v8::Local<v8::Context> temp_context = v8::Context::New(isolate);
+	v8::Context::Scope temp_scope(temp_context);
+	v8::Local<v8::Value> v8obj = v8::Local<v8::Value>::New(isolate, obj->v8obj);
+
+	if (v8js_get_properties_hash(v8obj, obj->properties, obj->flags, isolate TSRMLS_CC) == SUCCESS) {
+		return obj->properties;
+	}
+
+	return NULL;
+}
+/* }}} */
+
+static HashTable *v8js_v8object_get_debug_info(zval *object, int *is_temp TSRMLS_DC) /* {{{ */
+{
+	*is_temp = 0;
+	return v8js_v8object_get_properties(object TSRMLS_CC);
+}
+/* }}} */
+
+static zend_function *v8js_v8object_get_method(zval **object_ptr, char *method, int method_len ZEND_HASH_KEY_DC TSRMLS_DC) /* {{{ */
+{
+	v8js_v8object *obj = (v8js_v8object *) zend_object_store_get_object(*object_ptr TSRMLS_CC);
+	zend_function *f;
+
+	if (!obj->ctx) {
+		zend_throw_exception(php_ce_v8js_exception,
+			"Can't access V8Object after V8Js instance is destroyed!", 0 TSRMLS_CC);
+		return NULL;
+	}
+
+	v8::Isolate *isolate = obj->ctx->isolate;
+	v8::Locker locker(isolate);
+	v8::Isolate::Scope isolate_scope(isolate);
+	v8::HandleScope local_scope(isolate);
+	v8::Local<v8::Context> temp_context = v8::Context::New(isolate);
+	v8::Context::Scope temp_scope(temp_context);
+	v8::Local<v8::String> jsKey = V8JS_STRL(method, method_len);
+	v8::Local<v8::Value> v8obj = v8::Local<v8::Value>::New(isolate, obj->v8obj);
+
+	if (!obj->v8obj.IsEmpty() && v8obj->IsObject() && !v8obj->IsFunction()) {
+		v8::Local<v8::Object> jsObj = v8obj->ToObject();
+		
+		if (jsObj->Has(jsKey) && jsObj->Get(jsKey)->IsFunction()) {
+			f = (zend_function *) ecalloc(1, sizeof(*f));
+			f->type = ZEND_OVERLOADED_FUNCTION_TEMPORARY;
+			f->common.function_name = estrndup(method, method_len);
+			return f;
+		}
+	}
+
+	return NULL;
+}
+/* }}} */
+
+#if PHP_VERSION_ID >= 50400
+static int v8js_v8object_call_method(const char *method, INTERNAL_FUNCTION_PARAMETERS) /* {{{ */
+#else
+static int v8js_v8object_call_method(char *method, INTERNAL_FUNCTION_PARAMETERS) /* {{{ */
+#endif
+{
+	zval *object = this_ptr, ***argv = NULL;
+	int argc = ZEND_NUM_ARGS();
+	v8js_v8object *obj;
+
+	obj = (v8js_v8object *) zend_object_store_get_object(object TSRMLS_CC);
+
+	if (!obj->ctx) {
+		zend_throw_exception(php_ce_v8js_exception,
+			"Can't access V8Object after V8Js instance is destroyed!", 0 TSRMLS_CC);
+		return FAILURE;
+	}
+
+	if (obj->v8obj.IsEmpty()) {
+		zval_ptr_dtor(&object);
+		return FAILURE;
+	}
+
+	if (argc > 0) {
+		argv = (zval***)safe_emalloc(sizeof(zval**), argc, 0);
+		zend_get_parameters_array_ex(argc, argv);
+	}
+
+	std::function< v8::Local<v8::Value>(v8::Isolate *) > v8_call = [obj, method, argc, argv TSRMLS_CC](v8::Isolate *isolate) {
+		int i = 0;
+
+		v8::Local<v8::String> method_name = V8JS_SYML(method, strlen(method));
+		v8::Local<v8::Object> v8obj = v8::Local<v8::Value>::New(isolate, obj->v8obj)->ToObject();
+		v8::Local<v8::Function> cb;
+
+		if (method_name->Equals(V8JS_SYM(V8JS_V8_INVOKE_FUNC_NAME))) {
+			cb = v8::Local<v8::Function>::Cast(v8obj);
+		} else {
+			cb = v8::Local<v8::Function>::Cast(v8obj->Get(method_name));
+		}
+
+		v8::Local<v8::Value> *jsArgv = static_cast<v8::Local<v8::Value> *>(alloca(sizeof(v8::Local<v8::Value>) * argc));
+		v8::Local<v8::Value> js_retval;
+
+		for (i = 0; i < argc; i++) {
+			new(&jsArgv[i]) v8::Local<v8::Value>;
+			jsArgv[i] = v8::Local<v8::Value>::New(isolate, zval_to_v8js(*argv[i], isolate TSRMLS_CC));
+		}
+
+		return cb->Call(V8JS_GLOBAL(isolate), argc, jsArgv);
+	};
+
+	v8js_v8_call(obj->ctx, &return_value, obj->flags, obj->ctx->time_limit, obj->ctx->memory_limit, v8_call TSRMLS_CC);
+	zval_ptr_dtor(&object);
+
+	if (argc > 0) {
+		efree(argv);
+	}
+
+	return SUCCESS;
+}
+/* }}} */
+
+static int v8js_v8object_get_closure(zval *object, zend_class_entry **ce_ptr, zend_function **fptr_ptr, zval **zobj_ptr TSRMLS_DC) /* {{{ */
+{
+	zend_function *invoke;
+
+	v8js_v8object *obj = (v8js_v8object *) zend_object_store_get_object(object TSRMLS_CC);
+
+	if (!obj->ctx) {
+		zend_throw_exception(php_ce_v8js_exception,
+			"Can't access V8Object after V8Js instance is destroyed!", 0 TSRMLS_CC);
+		return FAILURE;
+	}
+
+	v8::Isolate *isolate = obj->ctx->isolate;
+	v8::Locker locker(isolate);
+	v8::Isolate::Scope isolate_scope(isolate);
+	v8::HandleScope local_scope(isolate);
+	v8::Local<v8::Context> temp_context = v8::Context::New(isolate);
+	v8::Context::Scope temp_scope(temp_context);
+	v8::Local<v8::Value> v8obj = v8::Local<v8::Value>::New(isolate, obj->v8obj);
+
+	if (!v8obj->IsFunction()) {
+		return FAILURE;
+	}
+
+	invoke = (zend_function *) ecalloc(1, sizeof(*invoke));
+	invoke->type = ZEND_OVERLOADED_FUNCTION_TEMPORARY;
+	invoke->common.function_name = estrndup(V8JS_V8_INVOKE_FUNC_NAME, sizeof(V8JS_V8_INVOKE_FUNC_NAME) - 1);
+
+	*fptr_ptr = invoke;
+
+	if (zobj_ptr) {
+		*zobj_ptr = object;
+	}
+
+	*ce_ptr = NULL;
+
+	return SUCCESS;
+}
+/* }}} */
+
+static void v8js_v8object_free_storage(void *object, zend_object_handle handle TSRMLS_DC) /* {{{ */
+{
+	v8js_v8object *c = (v8js_v8object *) object;
+
+	if (c->properties) {
+		zend_hash_destroy(c->properties);
+		FREE_HASHTABLE(c->properties);
+		c->properties = NULL;
+	}
+
+	zend_object_std_dtor(&c->std TSRMLS_CC);
+
+	if(c->ctx) {
+		c->v8obj.Reset();
+		c->ctx->v8js_v8objects.remove(c);
+	}
+
+	efree(object);
+}
+/* }}} */
+
+static zend_object_value v8js_v8object_new(zend_class_entry *ce TSRMLS_DC) /* {{{ */
+{
+	zend_object_value retval;
+	v8js_v8object *c;
+	
+	c = (v8js_v8object *) ecalloc(1, sizeof(*c));
+
+	zend_object_std_init(&c->std, ce TSRMLS_CC);
+	new(&c->v8obj) v8::Persistent<v8::Value>();
+
+	retval.handle = zend_objects_store_put(c, NULL, (zend_objects_free_object_storage_t) v8js_v8object_free_storage, NULL TSRMLS_CC);
+	retval.handlers = &v8js_v8object_handlers;
+
+	return retval;
+}
+/* }}} */
+
+/* NOTE: We could also override v8js_v8object_handlers.get_constructor to throw
+ * an exception when invoked, but doing so causes the half-constructed object
+ * to leak -- this seems to be a PHP bug.  So we'll define magic __construct
+ * methods instead. */
+
+/* {{{ proto V8Object::__construct()
+ */
+PHP_METHOD(V8Object,__construct)
+{
+	zend_throw_exception(php_ce_v8js_exception,
+		"Can't directly construct V8 objects!", 0 TSRMLS_CC);
+	RETURN_FALSE;
+}
+/* }}} */
+
+/* {{{ proto V8Object::__sleep()
+ */
+PHP_METHOD(V8Object, __sleep)
+{
+	zend_throw_exception(php_ce_v8js_exception,
+		"You cannot serialize or unserialize V8Object instances", 0 TSRMLS_CC);
+	RETURN_FALSE;
+}
+/* }}} */
+
+/* {{{ proto V8Object::__wakeup()
+ */
+PHP_METHOD(V8Object, __wakeup)
+{
+	zend_throw_exception(php_ce_v8js_exception,
+		"You cannot serialize or unserialize V8Object instances", 0 TSRMLS_CC);
+	RETURN_FALSE;
+}
+/* }}} */
+
+/* {{{ proto V8Function::__construct()
+ */
+PHP_METHOD(V8Function,__construct)
+{
+	zend_throw_exception(php_ce_v8js_exception,
+		"Can't directly construct V8 objects!", 0 TSRMLS_CC);
+	RETURN_FALSE;
+}
+/* }}} */
+
+/* {{{ proto V8Function::__sleep()
+ */
+PHP_METHOD(V8Function, __sleep)
+{
+	zend_throw_exception(php_ce_v8js_exception,
+		"You cannot serialize or unserialize V8Function instances", 0 TSRMLS_CC);
+	RETURN_FALSE;
+}
+/* }}} */
+
+/* {{{ proto V8Function::__wakeup()
+ */
+PHP_METHOD(V8Function, __wakeup)
+{
+	zend_throw_exception(php_ce_v8js_exception,
+		"You cannot serialize or unserialize V8Function instances", 0 TSRMLS_CC);
+	RETURN_FALSE;
+}
+/* }}} */
+
+void v8js_v8object_create(zval *res, v8::Handle<v8::Value> value, int flags, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
+{
+	v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
+	v8js_v8object *c;
+
+	object_init_ex(res, value->IsFunction() ? php_ce_v8function : php_ce_v8object);
+
+	c = (v8js_v8object *) zend_object_store_get_object(res TSRMLS_CC);
+
+	c->v8obj.Reset(isolate, value);
+	c->flags = flags;
+	c->ctx = ctx;
+	c->properties = NULL;
+
+	ctx->v8js_v8objects.push_front(c);
+}
+/* }}} */
+
+
+static const zend_function_entry v8js_v8object_methods[] = { /* {{{ */
+	PHP_ME(V8Object,	__construct,			NULL,				ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+	PHP_ME(V8Object,	__sleep,				NULL,				ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
+	PHP_ME(V8Object,	__wakeup,				NULL,				ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
+	{NULL, NULL, NULL}
+};
+/* }}} */
+
+static const zend_function_entry v8js_v8function_methods[] = { /* {{{ */
+	PHP_ME(V8Function,	__construct,			NULL,				ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+	PHP_ME(V8Function,	__sleep,				NULL,				ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
+	PHP_ME(V8Function,	__wakeup,				NULL,				ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
+	{NULL, NULL, NULL}
+};
+/* }}} */
+
+
+PHP_MINIT_FUNCTION(v8js_v8object_class) /* {{{ */
+{
+	zend_class_entry ce;
+
+	/* V8Object Class */
+	INIT_CLASS_ENTRY(ce, "V8Object", v8js_v8object_methods);
+	php_ce_v8object = zend_register_internal_class(&ce TSRMLS_CC);
+	php_ce_v8object->ce_flags |= ZEND_ACC_FINAL;
+	php_ce_v8object->create_object = v8js_v8object_new;
+
+	/* V8Function Class */
+	INIT_CLASS_ENTRY(ce, "V8Function", v8js_v8function_methods);
+	php_ce_v8function = zend_register_internal_class(&ce TSRMLS_CC);
+	php_ce_v8function->ce_flags |= ZEND_ACC_FINAL;
+	php_ce_v8function->create_object = v8js_v8object_new;
+
+	/* V8<Object|Function> handlers */
+	memcpy(&v8js_v8object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
+	v8js_v8object_handlers.clone_obj = NULL;
+	v8js_v8object_handlers.cast_object = NULL;
+	v8js_v8object_handlers.get_property_ptr_ptr = NULL;
+	v8js_v8object_handlers.has_property = v8js_v8object_has_property;
+	v8js_v8object_handlers.read_property = v8js_v8object_read_property;
+	v8js_v8object_handlers.write_property = v8js_v8object_write_property;
+	v8js_v8object_handlers.unset_property = v8js_v8object_unset_property;
+	v8js_v8object_handlers.get_properties = v8js_v8object_get_properties;
+	v8js_v8object_handlers.get_method = v8js_v8object_get_method;
+	v8js_v8object_handlers.call_method = v8js_v8object_call_method;
+	v8js_v8object_handlers.get_debug_info = v8js_v8object_get_debug_info;
+	v8js_v8object_handlers.get_closure = v8js_v8object_get_closure;
+} /* }}} */
+
+
+/*
+ * Local variables:
+ * tab-width: 4
+ * c-basic-offset: 4
+ * End:
+ * vim600: noet sw=4 ts=4 fdm=marker
+ * vim<600: noet sw=4 ts=4
+ */

+ 44 - 0
v8js_v8object_class.h

@@ -0,0 +1,44 @@
+/*
+  +----------------------------------------------------------------------+
+  | PHP Version 5                                                        |
+  +----------------------------------------------------------------------+
+  | Copyright (c) 1997-2013 The PHP Group                                |
+  +----------------------------------------------------------------------+
+  | http://www.opensource.org/licenses/mit-license.php  MIT License      |
+  +----------------------------------------------------------------------+
+  | Author: Jani Taskinen <[email protected]>                         |
+  | Author: Patrick Reilly <[email protected]>                             |
+  +----------------------------------------------------------------------+
+*/
+
+#ifndef V8JS_V8OBJECT_CLASS_H
+#define V8JS_V8OBJECT_CLASS_H
+
+/* {{{ Object container */
+struct v8js_v8object {
+	zend_object std;
+	v8::Persistent<v8::Value> v8obj;
+	int flags;
+	struct v8js_ctx *ctx;
+	HashTable *properties;
+};
+/* }}} */
+
+extern zend_class_entry *php_ce_v8object;
+extern zend_class_entry *php_ce_v8function;
+
+/* Create PHP V8 object */
+void v8js_v8object_create(zval *, v8::Handle<v8::Value>, int, v8::Isolate * TSRMLS_DC);
+
+PHP_MINIT_FUNCTION(v8js_v8object_class);
+
+#endif /* V8JS_V8OBJECT_CLASS_H */
+
+/*
+ * Local variables:
+ * tab-width: 4
+ * c-basic-offset: 4
+ * End:
+ * vim600: noet sw=4 ts=4 fdm=marker
+ * vim<600: noet sw=4 ts=4
+ */

+ 6 - 6
v8js_variables.cc

@@ -25,10 +25,10 @@ extern "C" {
 #include <v8.h>
 #include <string>
 
-static void php_v8js_fetch_php_variable(v8::Local<v8::String> name, const v8::PropertyCallbackInfo<v8::Value>& info) /* {{{ */
+static void v8js_fetch_php_variable(v8::Local<v8::String> name, const v8::PropertyCallbackInfo<v8::Value>& info) /* {{{ */
 {
     v8::Handle<v8::External> data = v8::Handle<v8::External>::Cast(info.Data());
-    php_v8js_accessor_ctx *ctx = static_cast<php_v8js_accessor_ctx *>(data->Value());
+    v8js_accessor_ctx *ctx = static_cast<v8js_accessor_ctx *>(data->Value());
 	v8::Isolate *isolate = ctx->isolate;
 	zval **variable;
 
@@ -43,14 +43,14 @@ static void php_v8js_fetch_php_variable(v8::Local<v8::String> name, const v8::Pr
 }
 /* }}} */
 
-void php_v8js_accessor_ctx_dtor(php_v8js_accessor_ctx *ctx TSRMLS_DC) /* {{{ */
+void v8js_accessor_ctx_dtor(v8js_accessor_ctx *ctx TSRMLS_DC) /* {{{ */
 {
 	efree(ctx->variable_name_string);
 	efree(ctx);
 }
 /* }}} */
 
-void php_v8js_register_accessors(std::vector<php_v8js_accessor_ctx*> *accessor_list, v8::Local<v8::FunctionTemplate> php_obj_t, zval *array, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
+void v8js_register_accessors(std::vector<v8js_accessor_ctx*> *accessor_list, v8::Local<v8::FunctionTemplate> php_obj_t, zval *array, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
 {
 	char *property_name;
 	uint property_name_len;
@@ -80,13 +80,13 @@ void php_v8js_register_accessors(std::vector<php_v8js_accessor_ctx*> *accessor_l
 		}
 
         // Create context to store accessor data
-        php_v8js_accessor_ctx *ctx = (php_v8js_accessor_ctx *)emalloc(sizeof(php_v8js_accessor_ctx));
+        v8js_accessor_ctx *ctx = (v8js_accessor_ctx *)emalloc(sizeof(v8js_accessor_ctx));
         ctx->variable_name_string = estrdup(Z_STRVAL_PP(item));
         ctx->variable_name_string_len = Z_STRLEN_PP(item);
         ctx->isolate = isolate;
 
 		/* Set the variable fetch callback for given symbol on named property */
-		php_obj->SetAccessor(V8JS_STRL(property_name, property_name_len - 1), php_v8js_fetch_php_variable, NULL, v8::External::New(isolate, ctx), v8::PROHIBITS_OVERWRITING, v8::ReadOnly, v8::AccessorSignature::New(isolate, php_obj_t));
+		php_obj->SetAccessor(V8JS_STRL(property_name, property_name_len - 1), v8js_fetch_php_variable, NULL, v8::External::New(isolate, ctx), v8::PROHIBITS_OVERWRITING, v8::ReadOnly, v8::AccessorSignature::New(isolate, php_obj_t));
 
 		/* record the context so we can free it later */
 		accessor_list->push_back(ctx);

部分文件因为文件数量过多而无法显示