v8js_class.cc 31 KB

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