v8js_class.cc 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  1. /*
  2. +----------------------------------------------------------------------+
  3. | PHP Version 5 |
  4. +----------------------------------------------------------------------+
  5. | Copyright (c) 1997-2013 The PHP Group |
  6. +----------------------------------------------------------------------+
  7. | http://www.opensource.org/licenses/mit-license.php MIT License |
  8. +----------------------------------------------------------------------+
  9. | Author: Jani Taskinen <[email protected]> |
  10. | Author: Patrick Reilly <[email protected]> |
  11. +----------------------------------------------------------------------+
  12. */
  13. #ifdef HAVE_CONFIG_H
  14. #include "config.h"
  15. #endif
  16. extern "C" {
  17. #include "php.h"
  18. #include "ext/date/php_date.h"
  19. #include "ext/standard/php_string.h"
  20. #include "zend_interfaces.h"
  21. #include "zend_closures.h"
  22. #include "ext/spl/spl_exceptions.h"
  23. #include "zend_exceptions.h"
  24. }
  25. #include "php_v8js_macros.h"
  26. #include "v8js_v8.h"
  27. #include "v8js_debug.h"
  28. #include "v8js_exceptions.h"
  29. #include "v8js_v8object_class.h"
  30. #include "v8js_timer.h"
  31. #include <functional>
  32. #include <algorithm>
  33. #define PHP_V8JS_SCRIPT_RES_NAME "V8Js script"
  34. /* {{{ Class Entries */
  35. static zend_class_entry *php_ce_v8js;
  36. /* }}} */
  37. /* {{{ Object Handlers */
  38. static zend_object_handlers v8js_object_handlers;
  39. /* }}} */
  40. typedef struct _v8js_script {
  41. char *name;
  42. v8js_ctx *ctx;
  43. v8::Persistent<v8::Script, v8::CopyablePersistentTraits<v8::Script>> *script;
  44. } v8js_script;
  45. static void v8js_script_free(v8js_script *res);
  46. int le_v8js_script;
  47. /* {{{ Extension container */
  48. struct v8js_jsext {
  49. zend_bool auto_enable;
  50. HashTable *deps_ht;
  51. const char **deps;
  52. int deps_count;
  53. zend_string *name;
  54. zend_string *source;
  55. v8::Extension *extension;
  56. };
  57. /* }}} */
  58. #if PHP_V8_API_VERSION >= 4004010
  59. class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
  60. public:
  61. virtual void* Allocate(size_t length) {
  62. void* data = AllocateUninitialized(length);
  63. return data == NULL ? data : memset(data, 0, length);
  64. }
  65. virtual void* AllocateUninitialized(size_t length) { return malloc(length); }
  66. virtual void Free(void* data, size_t) { free(data); }
  67. };
  68. #endif
  69. static void v8js_free_storage(zend_object *object TSRMLS_DC) /* {{{ */
  70. {
  71. v8js_ctx *c = v8js_ctx_fetch_object(object);
  72. zend_object_std_dtor(&c->std TSRMLS_CC);
  73. zval_dtor(&c->pending_exception);
  74. zval_dtor(&c->module_loader);
  75. /* Delete PHP global object from JavaScript */
  76. if (!c->context.IsEmpty()) {
  77. v8::Locker locker(c->isolate);
  78. v8::Isolate::Scope isolate_scope(c->isolate);
  79. v8::HandleScope handle_scope(c->isolate);
  80. v8::Local<v8::Context> v8_context = v8::Local<v8::Context>::New(c->isolate, c->context);
  81. v8::Context::Scope context_scope(v8_context);
  82. v8::Local<v8::String> object_name_js = v8::Local<v8::String>::New(c->isolate, c->object_name);
  83. V8JS_GLOBAL(c->isolate)->Delete(object_name_js);
  84. }
  85. c->object_name.Reset();
  86. c->object_name.~Persistent();
  87. c->global_template.Reset();
  88. c->global_template.~Persistent();
  89. /* Clear persistent handles in template cache */
  90. for (std::map<const zend_string *,v8js_tmpl_t>::iterator it = c->template_cache.begin();
  91. it != c->template_cache.end(); ++it) {
  92. it->second.Reset();
  93. }
  94. c->template_cache.~map();
  95. /* Clear contexts */
  96. for (std::vector<v8js_accessor_ctx*>::iterator it = c->accessor_list.begin();
  97. it != c->accessor_list.end(); ++it) {
  98. v8js_accessor_ctx_dtor(*it TSRMLS_CC);
  99. }
  100. c->accessor_list.~vector();
  101. /* Clear global object, dispose context */
  102. if (!c->context.IsEmpty()) {
  103. c->context.Reset();
  104. }
  105. c->context.~Persistent();
  106. /* Dispose yet undisposed weak refs */
  107. for (std::map<zend_object *, v8js_persistent_obj_t>::iterator it = c->weak_objects.begin();
  108. it != c->weak_objects.end(); ++it) {
  109. zend_object *object = it->first;
  110. zval value;
  111. ZVAL_OBJ(&value, object);
  112. zval_dtor(&value);
  113. c->isolate->AdjustAmountOfExternalAllocatedMemory(-1024);
  114. it->second.Reset();
  115. }
  116. c->weak_objects.~map();
  117. for (std::map<v8js_tmpl_t *, v8js_persistent_obj_t>::iterator it = c->weak_closures.begin();
  118. it != c->weak_closures.end(); ++it) {
  119. v8js_tmpl_t *persist_tpl_ = it->first;
  120. persist_tpl_->Reset();
  121. delete persist_tpl_;
  122. it->second.Reset();
  123. }
  124. c->weak_closures.~map();
  125. for (std::list<v8js_v8object *>::iterator it = c->v8js_v8objects.begin();
  126. it != c->v8js_v8objects.end(); it ++) {
  127. (*it)->v8obj.Reset();
  128. (*it)->ctx = NULL;
  129. }
  130. c->v8js_v8objects.~list();
  131. for (std::vector<v8js_script *>::iterator it = c->script_objects.begin();
  132. it != c->script_objects.end(); it ++) {
  133. (*it)->ctx = NULL;
  134. (*it)->script->Reset();
  135. }
  136. c->script_objects.~vector();
  137. /* Clear persistent handles in module cache */
  138. for (std::map<char *, v8js_persistent_obj_t>::iterator it = c->modules_loaded.begin();
  139. it != c->modules_loaded.end(); ++it) {
  140. efree(it->first);
  141. it->second.Reset();
  142. }
  143. c->modules_loaded.~map();
  144. if(c->isolate) {
  145. /* c->isolate is initialized by V8Js::__construct, but __wakeup calls
  146. * are not fully constructed and hence this would cause a NPE. */
  147. c->isolate->Dispose();
  148. }
  149. if(c->tz != NULL) {
  150. free(c->tz);
  151. }
  152. c->modules_stack.~vector();
  153. c->modules_base.~vector();
  154. }
  155. /* }}} */
  156. static zend_object* v8js_new(zend_class_entry *ce TSRMLS_DC) /* {{{ */
  157. {
  158. v8js_ctx *c;
  159. c = (v8js_ctx *) ecalloc(1, sizeof(*c) + zend_object_properties_size(ce));
  160. zend_object_std_init(&c->std, ce TSRMLS_CC);
  161. c->std.handlers = &v8js_object_handlers;
  162. TSRMLS_SET_CTX(c->zts_ctx);
  163. new(&c->object_name) v8::Persistent<v8::String>();
  164. new(&c->context) v8::Persistent<v8::Context>();
  165. new(&c->global_template) v8::Persistent<v8::FunctionTemplate>();
  166. new(&c->modules_stack) std::vector<char*>();
  167. new(&c->modules_base) std::vector<char*>();
  168. new(&c->modules_loaded) std::map<char *, v8js_persistent_obj_t, cmp_str>;
  169. new(&c->template_cache) std::map<const zend_string *,v8js_tmpl_t>();
  170. new(&c->accessor_list) std::vector<v8js_accessor_ctx *>();
  171. new(&c->weak_closures) std::map<v8js_tmpl_t *, v8js_persistent_obj_t>();
  172. new(&c->weak_objects) std::map<zend_object *, v8js_persistent_obj_t>();
  173. new(&c->v8js_v8objects) std::list<v8js_v8object *>();
  174. new(&c->script_objects) std::vector<v8js_script *>();
  175. // @fixme following is const, run on startup
  176. v8js_object_handlers.offset = XtOffsetOf(struct v8js_ctx, std);
  177. v8js_object_handlers.free_obj = v8js_free_storage;
  178. return &c->std;
  179. }
  180. /* }}} */
  181. static void v8js_free_ext_strarr(const char **arr, int count) /* {{{ */
  182. {
  183. int i;
  184. if (arr) {
  185. for (i = 0; i < count; i++) {
  186. if (arr[i]) {
  187. free((void *) arr[i]);
  188. }
  189. }
  190. free(arr);
  191. }
  192. }
  193. /* }}} */
  194. static void v8js_jsext_free_storage(v8js_jsext *jsext) /* {{{ */
  195. {
  196. if (jsext->deps_ht) {
  197. zend_hash_destroy(jsext->deps_ht);
  198. free(jsext->deps_ht);
  199. }
  200. if (jsext->deps) {
  201. v8js_free_ext_strarr(jsext->deps, jsext->deps_count);
  202. }
  203. delete jsext->extension;
  204. zend_string_release(jsext->name);
  205. zend_string_release(jsext->source);
  206. free(jsext);
  207. }
  208. /* }}} */
  209. static void v8js_jsext_dtor(zval *zv) /* {{{ */
  210. {
  211. v8js_jsext_free_storage(reinterpret_cast<v8js_jsext *>(Z_PTR_P(zv)));
  212. }
  213. /* }}} */
  214. static int v8js_create_ext_strarr(const char ***retval, int count, HashTable *ht) /* {{{ */
  215. {
  216. const char **exts = NULL;
  217. HashPosition pos;
  218. zval *tmp;
  219. int i = 0;
  220. exts = (const char **) calloc(1, count * sizeof(char *));
  221. zend_hash_internal_pointer_reset_ex(ht, &pos);
  222. while ((tmp = zend_hash_get_current_data_ex(ht, &pos))) {
  223. if (Z_TYPE_P(tmp) == IS_STRING) {
  224. exts[i++] = zend_strndup(Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));
  225. } else {
  226. v8js_free_ext_strarr(exts, i);
  227. return FAILURE;
  228. }
  229. zend_hash_move_forward_ex(ht, &pos);
  230. }
  231. *retval = exts;
  232. return SUCCESS;
  233. }
  234. /* }}} */
  235. static void v8js_fatal_error_handler(const char *location, const char *message) /* {{{ */
  236. {
  237. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  238. if (isolate) {
  239. isolate->Exit();
  240. }
  241. if (location) {
  242. zend_error(E_ERROR, "%s %s", location, message);
  243. } else {
  244. zend_error(E_ERROR, "%s", message);
  245. }
  246. }
  247. /* }}} */
  248. /* {{{ proto void V8Js::__construct([string object_name [, array variables [, array extensions [, bool report_uncaught_exceptions]]])
  249. __construct for V8Js */
  250. static PHP_METHOD(V8Js, __construct)
  251. {
  252. char *object_name = NULL, *class_name = NULL;
  253. int object_name_len = 0, free = 0;
  254. unsigned int class_name_len = 0;
  255. zend_bool report_uncaught = 1;
  256. zval *vars_arr = NULL, *exts_arr = NULL;
  257. const char **exts = NULL;
  258. int exts_count = 0;
  259. v8js_ctx *c = Z_V8JS_CTX_OBJ_P(getThis())
  260. if (!c->context.IsEmpty()) {
  261. /* called __construct() twice, bail out */
  262. return;
  263. }
  264. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|saab", &object_name, &object_name_len, &vars_arr, &exts_arr, &report_uncaught) == FAILURE) {
  265. return;
  266. }
  267. /* Initialize V8 */
  268. v8js_v8_init(TSRMLS_C);
  269. /* Throw PHP exception if uncaught exceptions exist */
  270. c->report_uncaught = report_uncaught;
  271. ZVAL_NULL(&c->pending_exception);
  272. c->in_execution = 0;
  273. #if PHP_V8_API_VERSION >= 4004044
  274. static ArrayBufferAllocator array_buffer_allocator;
  275. static v8::Isolate::CreateParams create_params;
  276. create_params.array_buffer_allocator = &array_buffer_allocator;
  277. c->isolate = v8::Isolate::New(create_params);
  278. #else
  279. c->isolate = v8::Isolate::New();
  280. #endif
  281. c->isolate->SetData(0, c);
  282. c->time_limit = 0;
  283. c->time_limit_hit = false;
  284. c->memory_limit = 0;
  285. c->memory_limit_hit = false;
  286. ZVAL_NULL(&c->module_loader);
  287. /* Include extensions used by this context */
  288. /* Note: Extensions registered with auto_enable do not need to be added separately like this. */
  289. if (exts_arr)
  290. {
  291. exts_count = zend_hash_num_elements(Z_ARRVAL_P(exts_arr));
  292. if (v8js_create_ext_strarr(&exts, exts_count, Z_ARRVAL_P(exts_arr)) == FAILURE) {
  293. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid extensions array passed");
  294. return;
  295. }
  296. }
  297. /* Declare configuration for extensions */
  298. v8::ExtensionConfiguration extension_conf(exts_count, exts);
  299. // Isolate execution
  300. v8::Isolate *isolate = c->isolate;
  301. v8::Locker locker(isolate);
  302. v8::Isolate::Scope isolate_scope(isolate);
  303. /* Handle scope */
  304. v8::HandleScope handle_scope(isolate);
  305. /* Redirect fatal errors to PHP error handler */
  306. // This needs to be done within the context isolate
  307. v8::V8::SetFatalErrorHandler(v8js_fatal_error_handler);
  308. /* Create global template for global object */
  309. // Now we are using multiple isolates this needs to be created for every context
  310. v8::Local<v8::FunctionTemplate> tpl = v8::FunctionTemplate::New(c->isolate, 0);
  311. tpl->SetClassName(V8JS_SYM("V8Js"));
  312. c->global_template.Reset(isolate, tpl);
  313. /* Register builtin methods */
  314. v8js_register_methods(tpl->InstanceTemplate(), c);
  315. /* Create context */
  316. v8::Local<v8::Context> context = v8::Context::New(isolate, &extension_conf, tpl->InstanceTemplate());
  317. if (exts) {
  318. v8js_free_ext_strarr(exts, exts_count);
  319. }
  320. /* If extensions have errors, context will be empty. (NOTE: This is V8 stuff, they expect the passed sources to compile :) */
  321. if (context.IsEmpty()) {
  322. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to create V8 context. Check that registered extensions do not have errors.");
  323. ZVAL_NULL(getThis());
  324. return;
  325. }
  326. context->SetAlignedPointerInEmbedderData(1, c);
  327. c->context.Reset(isolate, context);
  328. /* Enter context */
  329. v8::Context::Scope context_scope(context);
  330. /* Create the PHP container object's function template */
  331. v8::Local<v8::FunctionTemplate> php_obj_t = v8::FunctionTemplate::New(isolate, 0);
  332. /* Set class name for PHP object */
  333. zend_class_entry *ce = Z_OBJCE_P(getThis());
  334. php_obj_t->SetClassName(V8JS_SYML(ZSTR_VAL(ce->name), ZSTR_LEN(ce->name)));
  335. if (free) {
  336. efree(class_name);
  337. }
  338. /* Register Get accessor for passed variables */
  339. if (vars_arr && zend_hash_num_elements(Z_ARRVAL_P(vars_arr)) > 0) {
  340. v8js_register_accessors(&c->accessor_list, php_obj_t, vars_arr, isolate TSRMLS_CC);
  341. }
  342. /* Set name for the PHP JS object */
  343. v8::Local<v8::String> object_name_js = (object_name_len) ? V8JS_SYML(object_name, object_name_len) : V8JS_SYM("PHP");
  344. c->object_name.Reset(isolate, object_name_js);
  345. /* Add the PHP object into global object */
  346. v8::Local<v8::Object> php_obj = php_obj_t->InstanceTemplate()->NewInstance();
  347. V8JS_GLOBAL(isolate)->ForceSet(object_name_js, php_obj, v8::ReadOnly);
  348. /* Export public property values */
  349. HashTable *properties = zend_std_get_properties(getThis() TSRMLS_CC);
  350. HashPosition pos;
  351. zval *value;
  352. ulong index;
  353. zend_string *member;
  354. uint member_len;
  355. for(zend_hash_internal_pointer_reset_ex(properties, &pos);
  356. value = zend_hash_get_current_data_ex(properties, &pos);
  357. zend_hash_move_forward_ex(properties, &pos)) {
  358. if(zend_hash_get_current_key_ex(properties, &member, &index, &pos) != HASH_KEY_IS_STRING) {
  359. continue;
  360. }
  361. zend_property_info *property_info = zend_get_property_info(c->std.ce, member, 1 TSRMLS_CC);
  362. if(property_info &&
  363. property_info != ZEND_WRONG_PROPERTY_INFO &&
  364. property_info->flags & ZEND_ACC_PUBLIC) {
  365. /* Write value to PHP JS object */
  366. php_obj->ForceSet(V8JS_SYML(ZSTR_VAL(member), ZSTR_LEN(member) - 1), zval_to_v8js(value, isolate TSRMLS_CC), v8::ReadOnly);
  367. }
  368. }
  369. }
  370. /* }}} */
  371. /* {{{ proto V8JS::__sleep()
  372. */
  373. PHP_METHOD(V8Js, __sleep)
  374. {
  375. zend_throw_exception(php_ce_v8js_exception,
  376. "You cannot serialize or unserialize V8Js instances", 0 TSRMLS_CC);
  377. RETURN_FALSE;
  378. }
  379. /* }}} */
  380. /* {{{ proto V8JS::__wakeup()
  381. */
  382. PHP_METHOD(V8Js, __wakeup)
  383. {
  384. zend_throw_exception(php_ce_v8js_exception,
  385. "You cannot serialize or unserialize V8Js instances", 0 TSRMLS_CC);
  386. RETURN_FALSE;
  387. }
  388. /* }}} */
  389. static void v8js_compile_script(zval *this_ptr, zend_string *str, zend_string *identifier, v8js_script **ret TSRMLS_DC)
  390. {
  391. v8js_script *res = NULL;
  392. V8JS_BEGIN_CTX(c, this_ptr)
  393. /* Catch JS exceptions */
  394. v8::TryCatch try_catch;
  395. /* Set script identifier */
  396. v8::Local<v8::String> sname = identifier ? V8JS_ZSTR(identifier) : V8JS_SYM("V8Js::compileString()");
  397. /* Compiles a string context independently. TODO: Add a php function which calls this and returns the result as resource which can be executed later. */
  398. v8::Local<v8::String> source = V8JS_ZSTR(str);
  399. v8::Local<v8::Script> script = v8::Script::Compile(source, sname);
  400. /* Compile errors? */
  401. if (script.IsEmpty()) {
  402. v8js_throw_script_exception(&try_catch TSRMLS_CC);
  403. return;
  404. }
  405. res = (v8js_script *)emalloc(sizeof(v8js_script));
  406. res->script = new v8::Persistent<v8::Script, v8::CopyablePersistentTraits<v8::Script>>(c->isolate, script);
  407. v8::String::Utf8Value _sname(sname);
  408. res->name = estrndup(ToCString(_sname), _sname.length());
  409. res->ctx = c;
  410. *ret = res;
  411. return;
  412. }
  413. static void v8js_execute_script(zval *this_ptr, v8js_script *res, long flags, long time_limit, long memory_limit, zval **return_value TSRMLS_DC)
  414. {
  415. v8js_ctx *c = Z_V8JS_CTX_OBJ_P(this_ptr);
  416. if (res->ctx != c) {
  417. zend_error(E_WARNING, "Script resource from wrong V8Js object passed");
  418. ZVAL_BOOL(*return_value, 0);
  419. return;
  420. }
  421. if (!c->in_execution && time_limit == 0) {
  422. time_limit = c->time_limit;
  423. }
  424. if (!c->in_execution && memory_limit == 0) {
  425. memory_limit = c->memory_limit;
  426. }
  427. std::function< v8::Local<v8::Value>(v8::Isolate *) > v8_call = [res](v8::Isolate *isolate) {
  428. v8::Local<v8::Script> script = v8::Local<v8::Script>::New(isolate, *res->script);
  429. return script->Run();
  430. };
  431. v8js_v8_call(c, return_value, flags, time_limit, memory_limit, v8_call TSRMLS_CC);
  432. }
  433. /* {{{ proto mixed V8Js::executeString(string script [, string identifier [, int flags]])
  434. */
  435. static PHP_METHOD(V8Js, executeString)
  436. {
  437. zend_string *str = NULL, *identifier = NULL;
  438. int str_len = 0, identifier_len = 0;
  439. long flags = V8JS_FLAG_NONE, time_limit = 0, memory_limit = 0;
  440. v8js_script *res = NULL;
  441. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "S|Slll", &str, &identifier, &flags, &time_limit, &memory_limit) == FAILURE) {
  442. return;
  443. }
  444. v8js_compile_script(getThis(), str, identifier, &res TSRMLS_CC);
  445. if (!res) {
  446. RETURN_FALSE;
  447. }
  448. v8js_execute_script(getThis(), res, flags, time_limit, memory_limit, &return_value TSRMLS_CC);
  449. v8js_script_free(res);
  450. efree(res);
  451. }
  452. /* }}} */
  453. /* {{{ proto mixed V8Js::compileString(string script [, string identifier])
  454. */
  455. static PHP_METHOD(V8Js, compileString)
  456. {
  457. zend_string *str = NULL, *identifier = NULL;
  458. int str_len = 0, identifier_len = 0;
  459. v8js_script *res = NULL;
  460. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "S|S", &str, &identifier) == FAILURE) {
  461. return;
  462. }
  463. v8js_compile_script(getThis(), str, identifier, &res TSRMLS_CC);
  464. if (res) {
  465. RETVAL_RES(zend_register_resource(res, le_v8js_script));
  466. v8js_ctx *ctx;
  467. ctx = Z_V8JS_CTX_OBJ_P(getThis());
  468. ctx->script_objects.push_back(res);
  469. }
  470. return;
  471. }
  472. /* }}} */
  473. /* {{{ proto mixed V8Js::executeScript(resource script [, int flags]])
  474. */
  475. static PHP_METHOD(V8Js, executeScript)
  476. {
  477. long flags = V8JS_FLAG_NONE, time_limit = 0, memory_limit = 0;
  478. zval *zscript;
  479. v8js_script *res;
  480. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|lll", &zscript, &flags, &time_limit, &memory_limit) == FAILURE) {
  481. return;
  482. }
  483. if((res = (v8js_script *)zend_fetch_resource(Z_RES_P(zscript), PHP_V8JS_SCRIPT_RES_NAME, le_v8js_script)) == NULL) {
  484. RETURN_FALSE;
  485. }
  486. v8js_execute_script(getThis(), res, flags, time_limit, memory_limit, &return_value TSRMLS_CC);
  487. }
  488. /* }}} */
  489. /* {{{ proto mixed V8Js::checkString(string script)
  490. */
  491. static PHP_METHOD(V8Js, checkString)
  492. {
  493. zend_string *str = NULL;
  494. int str_len = 0;
  495. zend_string *identifier = zend_string_init("V8Js::checkString()", 19, 0);
  496. v8js_script *res = NULL;
  497. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "S", &str) == FAILURE) {
  498. return;
  499. }
  500. v8js_compile_script(getThis(), str, identifier, &res TSRMLS_CC);
  501. zend_string_release(identifier);
  502. if (!res) {
  503. RETURN_FALSE;
  504. }
  505. v8js_script_free(res);
  506. efree(res);
  507. RETURN_TRUE;
  508. }
  509. /* }}} */
  510. /* {{{ proto mixed V8Js::getPendingException()
  511. */
  512. static PHP_METHOD(V8Js, getPendingException)
  513. {
  514. v8js_ctx *c;
  515. if (zend_parse_parameters_none() == FAILURE) {
  516. return;
  517. }
  518. c = Z_V8JS_CTX_OBJ_P(getThis());
  519. if (Z_TYPE(c->pending_exception) == IS_OBJECT) {
  520. RETURN_ZVAL(&c->pending_exception, 1, 0);
  521. }
  522. }
  523. /* }}} */
  524. /* {{{ proto void V8Js::clearPendingException()
  525. */
  526. static PHP_METHOD(V8Js, clearPendingException)
  527. {
  528. v8js_ctx *c;
  529. if (zend_parse_parameters_none() == FAILURE) {
  530. return;
  531. }
  532. c = Z_V8JS_CTX_OBJ_P(getThis());
  533. if (Z_TYPE(c->pending_exception) == IS_OBJECT) {
  534. zval_dtor(&c->pending_exception);
  535. ZVAL_NULL(&c->pending_exception);
  536. }
  537. }
  538. /* }}} */
  539. /* {{{ proto void V8Js::setModuleLoader(string module)
  540. */
  541. static PHP_METHOD(V8Js, setModuleLoader)
  542. {
  543. v8js_ctx *c;
  544. zval *callable;
  545. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &callable) == FAILURE) {
  546. return;
  547. }
  548. c = Z_V8JS_CTX_OBJ_P(getThis());
  549. ZVAL_COPY(&c->module_loader, callable);
  550. }
  551. /* }}} */
  552. /* {{{ proto void V8Js::setTimeLimit(int time_limit)
  553. */
  554. static PHP_METHOD(V8Js, setTimeLimit)
  555. {
  556. v8js_ctx *c;
  557. long time_limit = 0;
  558. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &time_limit) == FAILURE) {
  559. return;
  560. }
  561. c = Z_V8JS_CTX_OBJ_P(getThis());
  562. c->time_limit = time_limit;
  563. V8JSG(timer_mutex).lock();
  564. for (std::deque< v8js_timer_ctx* >::iterator it = V8JSG(timer_stack).begin();
  565. it != V8JSG(timer_stack).end(); it ++) {
  566. if((*it)->ctx == c && !(*it)->killed) {
  567. (*it)->time_limit = time_limit;
  568. // Calculate the time point when the time limit is exceeded
  569. std::chrono::milliseconds duration(time_limit);
  570. std::chrono::time_point<std::chrono::high_resolution_clock> from = std::chrono::high_resolution_clock::now();
  571. (*it)->time_point = from + duration;
  572. }
  573. }
  574. V8JSG(timer_mutex).unlock();
  575. if (c->in_execution && time_limit && !V8JSG(timer_thread)) {
  576. /* If timer thread is not started already and we now impose a time limit
  577. * finally install the timer. */
  578. V8JSG(timer_thread) = new std::thread(v8js_timer_thread TSRMLS_CC);
  579. }
  580. }
  581. /* }}} */
  582. /* {{{ proto void V8Js::setMemoryLimit(int memory_limit)
  583. */
  584. static PHP_METHOD(V8Js, setMemoryLimit)
  585. {
  586. v8js_ctx *c;
  587. long memory_limit = 0;
  588. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &memory_limit) == FAILURE) {
  589. return;
  590. }
  591. c = Z_V8JS_CTX_OBJ_P(getThis());
  592. c->memory_limit = memory_limit;
  593. V8JSG(timer_mutex).lock();
  594. for (std::deque< v8js_timer_ctx* >::iterator it = V8JSG(timer_stack).begin();
  595. it != V8JSG(timer_stack).end(); it ++) {
  596. if((*it)->ctx == c && !(*it)->killed) {
  597. (*it)->memory_limit = memory_limit;
  598. }
  599. }
  600. V8JSG(timer_mutex).unlock();
  601. if (c->in_execution && memory_limit && !V8JSG(timer_thread)) {
  602. /* If timer thread is not started already and we now impose a memory limit
  603. * finally install the timer. */
  604. V8JSG(timer_thread) = new std::thread(v8js_timer_thread TSRMLS_CC);
  605. }
  606. }
  607. /* }}} */
  608. static void v8js_persistent_zval_ctor(zval *p) /* {{{ */
  609. {
  610. assert(Z_TYPE_P(p) == IS_STRING);
  611. Z_STR_P(p) = zend_string_dup(Z_STR_P(p), 1);
  612. }
  613. /* }}} */
  614. static void v8js_persistent_zval_dtor(zval *p) /* {{{ */
  615. {
  616. assert(Z_TYPE_P(p) == IS_STRING);
  617. free(Z_STR_P(p));
  618. }
  619. /* }}} */
  620. static void v8js_script_free(v8js_script *res)
  621. {
  622. efree(res->name);
  623. delete res->script; // does Reset()
  624. }
  625. static void v8js_script_dtor(zend_resource *rsrc) /* {{{ */
  626. {
  627. v8js_script *res = (v8js_script *)rsrc->ptr;
  628. if (res) {
  629. if(res->ctx) {
  630. std::vector<v8js_script *>::iterator it = std::find(res->ctx->script_objects.begin(), res->ctx->script_objects.end(), res);
  631. res->ctx->script_objects.erase(it);
  632. }
  633. v8js_script_free(res);
  634. efree(res);
  635. }
  636. }
  637. /* }}} */
  638. static int v8js_register_extension(zend_string *name, zend_string *source, zval *deps_arr, zend_bool auto_enable TSRMLS_DC) /* {{{ */
  639. {
  640. v8js_jsext *jsext = NULL;
  641. if (!V8JSG(extensions)) {
  642. V8JSG(extensions) = (HashTable *) malloc(sizeof(HashTable));
  643. zend_hash_init(V8JSG(extensions), 1, NULL, v8js_jsext_dtor, 1);
  644. } else if (zend_hash_exists(V8JSG(extensions), name)) {
  645. return FAILURE;
  646. }
  647. jsext = (v8js_jsext *) calloc(1, sizeof(v8js_jsext));
  648. if (deps_arr) {
  649. jsext->deps_count = zend_hash_num_elements(Z_ARRVAL_P(deps_arr));
  650. if (v8js_create_ext_strarr(&jsext->deps, jsext->deps_count, Z_ARRVAL_P(deps_arr)) == FAILURE) {
  651. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid dependency array passed");
  652. v8js_jsext_free_storage(jsext);
  653. return FAILURE;
  654. }
  655. }
  656. jsext->auto_enable = auto_enable;
  657. jsext->name = zend_string_dup(name, 1);
  658. jsext->source = zend_string_dup(source, 1);
  659. if (jsext->deps) {
  660. jsext->deps_ht = (HashTable *) malloc(sizeof(HashTable));
  661. zend_hash_init(jsext->deps_ht, jsext->deps_count, NULL, v8js_persistent_zval_dtor, 1);
  662. zend_hash_copy(jsext->deps_ht, Z_ARRVAL_P(deps_arr), v8js_persistent_zval_ctor);
  663. }
  664. jsext->extension = new v8::Extension(ZSTR_VAL(jsext->name), ZSTR_VAL(jsext->source), jsext->deps_count, jsext->deps);
  665. if (!zend_hash_add_ptr(V8JSG(extensions), jsext->name, jsext)) {
  666. v8js_jsext_free_storage(jsext);
  667. return FAILURE;
  668. }
  669. jsext->extension->set_auto_enable(auto_enable ? true : false);
  670. v8::RegisterExtension(jsext->extension);
  671. return SUCCESS;
  672. }
  673. /* }}} */
  674. /* {{{ proto bool V8Js::registerExtension(string ext_name, string script [, array deps [, bool auto_enable]])
  675. */
  676. static PHP_METHOD(V8Js, registerExtension)
  677. {
  678. zend_string *ext_name, *script;
  679. zval *deps_arr = NULL;
  680. zend_bool auto_enable = 0;
  681. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "SS|ab", &ext_name, &script, &deps_arr, &auto_enable) == FAILURE) {
  682. return;
  683. }
  684. if (!ZSTR_LEN(ext_name)) {
  685. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Extension name cannot be empty");
  686. } else if (!ZSTR_LEN(script)) {
  687. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Script cannot be empty");
  688. } else if (v8js_register_extension(ext_name, script, deps_arr, auto_enable TSRMLS_CC) == SUCCESS) {
  689. RETURN_TRUE;
  690. }
  691. RETURN_FALSE;
  692. }
  693. /* }}} */
  694. /* ## Static methods ## */
  695. /* {{{ proto array V8Js::getExtensions()
  696. */
  697. static PHP_METHOD(V8Js, getExtensions)
  698. {
  699. v8js_jsext *jsext;
  700. ulong index;
  701. zend_string *key;
  702. zval *val, ext;
  703. if (zend_parse_parameters_none() == FAILURE) {
  704. return;
  705. }
  706. array_init(return_value);
  707. if (V8JSG(extensions)) {
  708. ZEND_HASH_FOREACH_KEY_VAL(V8JSG(extensions), index, key, val) {
  709. if (key) {
  710. jsext = (v8js_jsext *) Z_PTR_P(val);
  711. array_init(&ext);
  712. add_assoc_bool_ex(&ext, ZEND_STRL("auto_enable"), jsext->auto_enable);
  713. if (jsext->deps_ht) {
  714. zval deps_arr;
  715. array_init(&deps_arr);
  716. zend_hash_copy(Z_ARRVAL_P(&deps_arr), jsext->deps_ht, (copy_ctor_func_t) zval_add_ref);
  717. add_assoc_zval_ex(&ext, ZEND_STRL("deps"), &deps_arr);
  718. }
  719. add_assoc_zval_ex(return_value, ZSTR_VAL(key), ZSTR_LEN(key), &ext);
  720. }
  721. } ZEND_HASH_FOREACH_END();
  722. }
  723. }
  724. /* }}} */
  725. /* {{{ arginfo */
  726. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_construct, 0, 0, 0)
  727. ZEND_ARG_INFO(0, object_name)
  728. ZEND_ARG_INFO(0, variables)
  729. ZEND_ARG_INFO(0, extensions)
  730. ZEND_ARG_INFO(0, report_uncaught_exceptions)
  731. ZEND_END_ARG_INFO()
  732. ZEND_BEGIN_ARG_INFO(arginfo_v8js_sleep, 0)
  733. ZEND_END_ARG_INFO()
  734. ZEND_BEGIN_ARG_INFO(arginfo_v8js_wakeup, 0)
  735. ZEND_END_ARG_INFO()
  736. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_executestring, 0, 0, 1)
  737. ZEND_ARG_INFO(0, script)
  738. ZEND_ARG_INFO(0, identifier)
  739. ZEND_ARG_INFO(0, flags)
  740. ZEND_ARG_INFO(0, time_limit)
  741. ZEND_ARG_INFO(0, memory_limit)
  742. ZEND_END_ARG_INFO()
  743. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_compilestring, 0, 0, 1)
  744. ZEND_ARG_INFO(0, script)
  745. ZEND_ARG_INFO(0, identifier)
  746. ZEND_END_ARG_INFO()
  747. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_executescript, 0, 0, 1)
  748. ZEND_ARG_INFO(0, script)
  749. ZEND_ARG_INFO(0, flags)
  750. ZEND_ARG_INFO(0, time_limit)
  751. ZEND_ARG_INFO(0, memory_limit)
  752. ZEND_END_ARG_INFO()
  753. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_checkstring, 0, 0, 1)
  754. ZEND_ARG_INFO(0, script)
  755. ZEND_END_ARG_INFO()
  756. #ifdef ENABLE_DEBUGGER_SUPPORT
  757. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_destruct, 0, 0, 0)
  758. ZEND_END_ARG_INFO()
  759. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_startdebugagent, 0, 0, 0)
  760. ZEND_ARG_INFO(0, agentName)
  761. ZEND_ARG_INFO(0, port)
  762. ZEND_ARG_INFO(0, auto_break)
  763. ZEND_END_ARG_INFO()
  764. #endif /* ENABLE_DEBUGGER_SUPPORT */
  765. ZEND_BEGIN_ARG_INFO(arginfo_v8js_getpendingexception, 0)
  766. ZEND_END_ARG_INFO()
  767. ZEND_BEGIN_ARG_INFO(arginfo_v8js_clearpendingexception, 0)
  768. ZEND_END_ARG_INFO()
  769. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_setmoduleloader, 0, 0, 1)
  770. ZEND_ARG_INFO(0, callable)
  771. ZEND_END_ARG_INFO()
  772. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_registerextension, 0, 0, 2)
  773. ZEND_ARG_INFO(0, extension_name)
  774. ZEND_ARG_INFO(0, script)
  775. ZEND_ARG_INFO(0, dependencies)
  776. ZEND_ARG_INFO(0, auto_enable)
  777. ZEND_END_ARG_INFO()
  778. ZEND_BEGIN_ARG_INFO(arginfo_v8js_getextensions, 0)
  779. ZEND_END_ARG_INFO()
  780. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_settimelimit, 0, 0, 1)
  781. ZEND_ARG_INFO(0, time_limit)
  782. ZEND_END_ARG_INFO()
  783. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_setmemorylimit, 0, 0, 1)
  784. ZEND_ARG_INFO(0, memory_limit)
  785. ZEND_END_ARG_INFO()
  786. static const zend_function_entry v8js_methods[] = { /* {{{ */
  787. PHP_ME(V8Js, __construct, arginfo_v8js_construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
  788. PHP_ME(V8Js, __sleep, arginfo_v8js_sleep, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
  789. PHP_ME(V8Js, __wakeup, arginfo_v8js_sleep, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
  790. PHP_ME(V8Js, executeString, arginfo_v8js_executestring, ZEND_ACC_PUBLIC)
  791. PHP_ME(V8Js, compileString, arginfo_v8js_compilestring, ZEND_ACC_PUBLIC)
  792. PHP_ME(V8Js, executeScript, arginfo_v8js_executescript, ZEND_ACC_PUBLIC)
  793. PHP_ME(V8Js, checkString, arginfo_v8js_checkstring, ZEND_ACC_PUBLIC|ZEND_ACC_DEPRECATED)
  794. PHP_ME(V8Js, getPendingException, arginfo_v8js_getpendingexception, ZEND_ACC_PUBLIC)
  795. PHP_ME(V8Js, clearPendingException, arginfo_v8js_clearpendingexception, ZEND_ACC_PUBLIC)
  796. PHP_ME(V8Js, setModuleLoader, arginfo_v8js_setmoduleloader, ZEND_ACC_PUBLIC)
  797. PHP_ME(V8Js, registerExtension, arginfo_v8js_registerextension, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
  798. PHP_ME(V8Js, getExtensions, arginfo_v8js_getextensions, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
  799. PHP_ME(V8Js, setTimeLimit, arginfo_v8js_settimelimit, ZEND_ACC_PUBLIC)
  800. PHP_ME(V8Js, setMemoryLimit, arginfo_v8js_setmemorylimit, ZEND_ACC_PUBLIC)
  801. #ifdef ENABLE_DEBUGGER_SUPPORT
  802. PHP_ME(V8Js, __destruct, arginfo_v8js_destruct, ZEND_ACC_PUBLIC|ZEND_ACC_DTOR)
  803. PHP_ME(V8Js, startDebugAgent, arginfo_v8js_startdebugagent, ZEND_ACC_PUBLIC)
  804. #endif
  805. {NULL, NULL, NULL}
  806. };
  807. /* }}} */
  808. /* V8Js object handlers */
  809. static void v8js_write_property(zval *object, zval *member, zval *value, void **cache_slot TSRMLS_DC) /* {{{ */
  810. {
  811. V8JS_BEGIN_CTX(c, object)
  812. /* Check whether member is public, if so, export to V8. */
  813. zend_property_info *property_info = zend_get_property_info(c->std.ce, Z_STR_P(member), 1 TSRMLS_CC);
  814. if(!property_info ||
  815. (property_info != ZEND_WRONG_PROPERTY_INFO &&
  816. property_info->flags & ZEND_ACC_PUBLIC)) {
  817. /* Global PHP JS object */
  818. v8::Local<v8::String> object_name_js = v8::Local<v8::String>::New(isolate, c->object_name);
  819. v8::Local<v8::Object> jsobj = V8JS_GLOBAL(isolate)->Get(object_name_js)->ToObject();
  820. /* Write value to PHP JS object */
  821. jsobj->ForceSet(V8JS_SYML(Z_STRVAL_P(member), Z_STRLEN_P(member)), zval_to_v8js(value, isolate TSRMLS_CC), v8::ReadOnly);
  822. }
  823. /* Write value to PHP object */
  824. std_object_handlers.write_property(object, member, value, cache_slot TSRMLS_CC);
  825. }
  826. /* }}} */
  827. static void v8js_unset_property(zval *object, zval *member, void **cache_slot TSRMLS_DC) /* {{{ */
  828. {
  829. V8JS_BEGIN_CTX(c, object)
  830. /* Global PHP JS object */
  831. v8::Local<v8::String> object_name_js = v8::Local<v8::String>::New(isolate, c->object_name);
  832. v8::Local<v8::Object> jsobj = V8JS_GLOBAL(isolate)->Get(object_name_js)->ToObject();
  833. /* Delete value from PHP JS object */
  834. jsobj->Delete(V8JS_SYML(Z_STRVAL_P(member), Z_STRLEN_P(member)));
  835. /* Unset from PHP object */
  836. std_object_handlers.unset_property(object, member, cache_slot TSRMLS_CC);
  837. }
  838. /* }}} */
  839. PHP_MINIT_FUNCTION(v8js_class) /* {{{ */
  840. {
  841. zend_class_entry ce;
  842. /* V8Js Class */
  843. INIT_CLASS_ENTRY(ce, "V8Js", v8js_methods);
  844. php_ce_v8js = zend_register_internal_class(&ce TSRMLS_CC);
  845. php_ce_v8js->create_object = v8js_new;
  846. /* V8Js handlers */
  847. memcpy(&v8js_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
  848. v8js_object_handlers.clone_obj = NULL;
  849. v8js_object_handlers.write_property = v8js_write_property;
  850. v8js_object_handlers.unset_property = v8js_unset_property;
  851. /* V8Js Class Constants */
  852. zend_declare_class_constant_string(php_ce_v8js, ZEND_STRL("V8_VERSION"), PHP_V8_VERSION TSRMLS_CC);
  853. zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("FLAG_NONE"), V8JS_FLAG_NONE TSRMLS_CC);
  854. zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("FLAG_FORCE_ARRAY"), V8JS_FLAG_FORCE_ARRAY TSRMLS_CC);
  855. #ifdef ENABLE_DEBUGGER_SUPPORT
  856. zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("DEBUG_AUTO_BREAK_NEVER"), V8JS_DEBUG_AUTO_BREAK_NEVER TSRMLS_CC);
  857. zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("DEBUG_AUTO_BREAK_ONCE"), V8JS_DEBUG_AUTO_BREAK_ONCE TSRMLS_CC);
  858. zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("DEBUG_AUTO_BREAK_ALWAYS"), V8JS_DEBUG_AUTO_BREAK_ALWAYS TSRMLS_CC);
  859. #endif
  860. le_v8js_script = zend_register_list_destructors_ex(v8js_script_dtor, NULL, PHP_V8JS_SCRIPT_RES_NAME, module_number);
  861. #if PHP_V8_API_VERSION >= 4004010 && PHP_V8_API_VERSION < 4004044
  862. static ArrayBufferAllocator array_buffer_allocator;
  863. v8::V8::SetArrayBufferAllocator(&array_buffer_allocator);
  864. #endif
  865. return SUCCESS;
  866. } /* }}} */
  867. /*
  868. * Local variables:
  869. * tab-width: 4
  870. * c-basic-offset: 4
  871. * End:
  872. * vim600: noet sw=4 ts=4 fdm=marker
  873. * vim<600: noet sw=4 ts=4
  874. */