v8js_class.cc 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  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. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  256. if (isolate) {
  257. isolate->Exit();
  258. }
  259. if (location) {
  260. zend_error(E_ERROR, "%s %s", location, message);
  261. } else {
  262. zend_error(E_ERROR, "%s", message);
  263. }
  264. }
  265. /* }}} */
  266. /* {{{ proto void V8Js::__construct([string object_name [, array variables [, array extensions [, bool report_uncaught_exceptions]]])
  267. __construct for V8Js */
  268. static PHP_METHOD(V8Js, __construct)
  269. {
  270. zend_string *object_name = NULL;
  271. zend_bool report_uncaught = 1;
  272. zval *vars_arr = NULL, *exts_arr = NULL;
  273. const char **exts = NULL;
  274. int exts_count = 0;
  275. v8js_ctx *c = Z_V8JS_CTX_OBJ_P(getThis())
  276. if (!c->context.IsEmpty()) {
  277. /* called __construct() twice, bail out */
  278. return;
  279. }
  280. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|Saab", &object_name, &vars_arr, &exts_arr, &report_uncaught) == FAILURE) {
  281. return;
  282. }
  283. /* Initialize V8 */
  284. v8js_v8_init(TSRMLS_C);
  285. /* Throw PHP exception if uncaught exceptions exist */
  286. c->report_uncaught = report_uncaught;
  287. ZVAL_NULL(&c->pending_exception);
  288. c->in_execution = 0;
  289. #if PHP_V8_API_VERSION >= 4004044
  290. static ArrayBufferAllocator array_buffer_allocator;
  291. static v8::Isolate::CreateParams create_params;
  292. create_params.array_buffer_allocator = &array_buffer_allocator;
  293. c->isolate = v8::Isolate::New(create_params);
  294. #else
  295. c->isolate = v8::Isolate::New();
  296. #endif
  297. c->isolate->SetData(0, c);
  298. c->time_limit = 0;
  299. c->time_limit_hit = false;
  300. c->memory_limit = 0;
  301. c->memory_limit_hit = false;
  302. ZVAL_NULL(&c->module_loader);
  303. /* Include extensions used by this context */
  304. /* Note: Extensions registered with auto_enable do not need to be added separately like this. */
  305. if (exts_arr)
  306. {
  307. exts_count = zend_hash_num_elements(Z_ARRVAL_P(exts_arr));
  308. if (v8js_create_ext_strarr(&exts, exts_count, Z_ARRVAL_P(exts_arr)) == FAILURE) {
  309. zend_throw_exception(php_ce_v8js_exception,
  310. "Invalid extensions array passed", 0);
  311. return;
  312. }
  313. }
  314. /* Declare configuration for extensions */
  315. v8::ExtensionConfiguration extension_conf(exts_count, exts);
  316. // Isolate execution
  317. v8::Isolate *isolate = c->isolate;
  318. v8::Locker locker(isolate);
  319. v8::Isolate::Scope isolate_scope(isolate);
  320. /* Handle scope */
  321. v8::HandleScope handle_scope(isolate);
  322. /* Redirect fatal errors to PHP error handler */
  323. // This needs to be done within the context isolate
  324. v8::V8::SetFatalErrorHandler(v8js_fatal_error_handler);
  325. /* Create global template for global object */
  326. // Now we are using multiple isolates this needs to be created for every context
  327. v8::Local<v8::FunctionTemplate> tpl = v8::FunctionTemplate::New(c->isolate, 0);
  328. tpl->SetClassName(V8JS_SYM("V8Js"));
  329. c->global_template.Reset(isolate, tpl);
  330. /* Register builtin methods */
  331. v8js_register_methods(tpl->InstanceTemplate(), c);
  332. /* Create context */
  333. v8::Local<v8::Context> context = v8::Context::New(isolate, &extension_conf, tpl->InstanceTemplate());
  334. if (exts) {
  335. v8js_free_ext_strarr(exts, exts_count);
  336. }
  337. /* If extensions have errors, context will be empty. (NOTE: This is V8 stuff, they expect the passed sources to compile :) */
  338. if (context.IsEmpty()) {
  339. zend_throw_exception(php_ce_v8js_exception,
  340. "Failed to create V8 context. "
  341. "Check that registered extensions do not have errors.", 0);
  342. return;
  343. }
  344. context->SetAlignedPointerInEmbedderData(1, c);
  345. c->context.Reset(isolate, context);
  346. /* Enter context */
  347. v8::Context::Scope context_scope(context);
  348. /* Create the PHP container object's function template */
  349. v8::Local<v8::FunctionTemplate> php_obj_t = v8::FunctionTemplate::New(isolate, 0);
  350. /* Set class name for PHP object */
  351. zend_class_entry *ce = Z_OBJCE_P(getThis());
  352. php_obj_t->SetClassName(V8JS_SYML(ZSTR_VAL(ce->name), ZSTR_LEN(ce->name)));
  353. /* Register Get accessor for passed variables */
  354. if (vars_arr && zend_hash_num_elements(Z_ARRVAL_P(vars_arr)) > 0) {
  355. v8js_register_accessors(&c->accessor_list, php_obj_t, vars_arr, isolate TSRMLS_CC);
  356. }
  357. /* Set name for the PHP JS object */
  358. v8::Local<v8::String> object_name_js = (object_name && ZSTR_LEN(object_name))
  359. ? V8JS_ZSYM(object_name)
  360. : V8JS_SYM("PHP");
  361. c->object_name.Reset(isolate, object_name_js);
  362. /* Add the PHP object into global object */
  363. v8::Local<v8::Object> php_obj = php_obj_t->InstanceTemplate()->NewInstance();
  364. V8JS_GLOBAL(isolate)->ForceSet(object_name_js, php_obj, v8::ReadOnly);
  365. /* Export public property values */
  366. HashTable *properties = zend_std_get_properties(getThis() TSRMLS_CC);
  367. zval *value;
  368. zend_string *member;
  369. ZEND_HASH_FOREACH_STR_KEY(properties, member) {
  370. zend_property_info *property_info = zend_get_property_info(c->std.ce, member, 1 TSRMLS_CC);
  371. if(property_info &&
  372. property_info != ZEND_WRONG_PROPERTY_INFO &&
  373. property_info->flags & ZEND_ACC_PUBLIC) {
  374. /* Write value to PHP JS object */
  375. value = OBJ_PROP(Z_OBJ_P(getThis()), property_info->offset);
  376. php_obj->ForceSet(V8JS_ZSYM(member), zval_to_v8js(value, isolate TSRMLS_CC), v8::ReadOnly);
  377. }
  378. } ZEND_HASH_FOREACH_END();
  379. }
  380. /* }}} */
  381. /* {{{ proto V8JS::__sleep()
  382. */
  383. PHP_METHOD(V8Js, __sleep)
  384. {
  385. zend_throw_exception(php_ce_v8js_exception,
  386. "You cannot serialize or unserialize V8Js instances", 0 TSRMLS_CC);
  387. RETURN_FALSE;
  388. }
  389. /* }}} */
  390. /* {{{ proto V8JS::__wakeup()
  391. */
  392. PHP_METHOD(V8Js, __wakeup)
  393. {
  394. zend_throw_exception(php_ce_v8js_exception,
  395. "You cannot serialize or unserialize V8Js instances", 0 TSRMLS_CC);
  396. RETURN_FALSE;
  397. }
  398. /* }}} */
  399. static void v8js_compile_script(zval *this_ptr, zend_string *str, zend_string *identifier, v8js_script **ret TSRMLS_DC)
  400. {
  401. v8js_script *res = NULL;
  402. V8JS_BEGIN_CTX(c, this_ptr)
  403. /* Catch JS exceptions */
  404. v8::TryCatch try_catch;
  405. /* Set script identifier */
  406. v8::Local<v8::String> sname = identifier ? V8JS_ZSTR(identifier) : V8JS_SYM("V8Js::compileString()");
  407. /* Compiles a string context independently. TODO: Add a php function which calls this and returns the result as resource which can be executed later. */
  408. v8::Local<v8::String> source = V8JS_ZSTR(str);
  409. v8::Local<v8::Script> script = v8::Script::Compile(source, sname);
  410. /* Compile errors? */
  411. if (script.IsEmpty()) {
  412. v8js_throw_script_exception(c->isolate, &try_catch TSRMLS_CC);
  413. return;
  414. }
  415. res = (v8js_script *)emalloc(sizeof(v8js_script));
  416. res->script = new v8::Persistent<v8::Script, v8::CopyablePersistentTraits<v8::Script>>(c->isolate, script);
  417. v8::String::Utf8Value _sname(sname);
  418. res->name = estrndup(ToCString(_sname), _sname.length());
  419. res->ctx = c;
  420. *ret = res;
  421. return;
  422. }
  423. static void v8js_execute_script(zval *this_ptr, v8js_script *res, long flags, long time_limit, long memory_limit, zval **return_value TSRMLS_DC)
  424. {
  425. v8js_ctx *c = Z_V8JS_CTX_OBJ_P(this_ptr);
  426. if (res->ctx != c) {
  427. zend_error(E_WARNING, "Script resource from wrong V8Js object passed");
  428. ZVAL_BOOL(*return_value, 0);
  429. return;
  430. }
  431. if (!c->in_execution && time_limit == 0) {
  432. time_limit = c->time_limit;
  433. }
  434. if (!c->in_execution && memory_limit == 0) {
  435. memory_limit = c->memory_limit;
  436. }
  437. std::function< v8::Local<v8::Value>(v8::Isolate *) > v8_call = [res](v8::Isolate *isolate) {
  438. v8::Local<v8::Script> script = v8::Local<v8::Script>::New(isolate, *res->script);
  439. return script->Run();
  440. };
  441. v8js_v8_call(c, return_value, flags, time_limit, memory_limit, v8_call TSRMLS_CC);
  442. }
  443. /* {{{ proto mixed V8Js::executeString(string script [, string identifier [, int flags]])
  444. */
  445. static PHP_METHOD(V8Js, executeString)
  446. {
  447. zend_string *str = NULL, *identifier = NULL;
  448. int str_len = 0, identifier_len = 0;
  449. long flags = V8JS_FLAG_NONE, time_limit = 0, memory_limit = 0;
  450. v8js_script *res = NULL;
  451. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "S|Slll", &str, &identifier, &flags, &time_limit, &memory_limit) == FAILURE) {
  452. return;
  453. }
  454. v8js_compile_script(getThis(), str, identifier, &res TSRMLS_CC);
  455. if (!res) {
  456. RETURN_FALSE;
  457. }
  458. v8js_execute_script(getThis(), res, flags, time_limit, memory_limit, &return_value TSRMLS_CC);
  459. v8js_script_free(res);
  460. efree(res);
  461. }
  462. /* }}} */
  463. /* {{{ proto mixed V8Js::compileString(string script [, string identifier])
  464. */
  465. static PHP_METHOD(V8Js, compileString)
  466. {
  467. zend_string *str = NULL, *identifier = NULL;
  468. int str_len = 0, identifier_len = 0;
  469. v8js_script *res = NULL;
  470. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "S|S", &str, &identifier) == FAILURE) {
  471. return;
  472. }
  473. v8js_compile_script(getThis(), str, identifier, &res TSRMLS_CC);
  474. if (res) {
  475. RETVAL_RES(zend_register_resource(res, le_v8js_script));
  476. v8js_ctx *ctx;
  477. ctx = Z_V8JS_CTX_OBJ_P(getThis());
  478. ctx->script_objects.push_back(res);
  479. }
  480. return;
  481. }
  482. /* }}} */
  483. /* {{{ proto mixed V8Js::executeScript(resource script [, int flags]])
  484. */
  485. static PHP_METHOD(V8Js, executeScript)
  486. {
  487. long flags = V8JS_FLAG_NONE, time_limit = 0, memory_limit = 0;
  488. zval *zscript;
  489. v8js_script *res;
  490. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|lll", &zscript, &flags, &time_limit, &memory_limit) == FAILURE) {
  491. return;
  492. }
  493. if((res = (v8js_script *)zend_fetch_resource(Z_RES_P(zscript), PHP_V8JS_SCRIPT_RES_NAME, le_v8js_script)) == NULL) {
  494. RETURN_FALSE;
  495. }
  496. v8js_execute_script(getThis(), res, flags, time_limit, memory_limit, &return_value TSRMLS_CC);
  497. }
  498. /* }}} */
  499. /* {{{ proto mixed V8Js::checkString(string script)
  500. */
  501. static PHP_METHOD(V8Js, checkString)
  502. {
  503. zend_string *str = NULL;
  504. int str_len = 0;
  505. zend_string *identifier = zend_string_init("V8Js::checkString()", 19, 0);
  506. v8js_script *res = NULL;
  507. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "S", &str) == FAILURE) {
  508. return;
  509. }
  510. v8js_compile_script(getThis(), str, identifier, &res TSRMLS_CC);
  511. zend_string_release(identifier);
  512. if (!res) {
  513. RETURN_FALSE;
  514. }
  515. v8js_script_free(res);
  516. efree(res);
  517. RETURN_TRUE;
  518. }
  519. /* }}} */
  520. /* {{{ proto mixed V8Js::getPendingException()
  521. */
  522. static PHP_METHOD(V8Js, getPendingException)
  523. {
  524. v8js_ctx *c;
  525. if (zend_parse_parameters_none() == FAILURE) {
  526. return;
  527. }
  528. c = Z_V8JS_CTX_OBJ_P(getThis());
  529. if (Z_TYPE(c->pending_exception) == IS_OBJECT) {
  530. RETURN_ZVAL(&c->pending_exception, 1, 0);
  531. }
  532. }
  533. /* }}} */
  534. /* {{{ proto void V8Js::clearPendingException()
  535. */
  536. static PHP_METHOD(V8Js, clearPendingException)
  537. {
  538. v8js_ctx *c;
  539. if (zend_parse_parameters_none() == FAILURE) {
  540. return;
  541. }
  542. c = Z_V8JS_CTX_OBJ_P(getThis());
  543. if (Z_TYPE(c->pending_exception) == IS_OBJECT) {
  544. zval_dtor(&c->pending_exception);
  545. ZVAL_NULL(&c->pending_exception);
  546. }
  547. }
  548. /* }}} */
  549. /* {{{ proto void V8Js::setModuleLoader(string module)
  550. */
  551. static PHP_METHOD(V8Js, setModuleLoader)
  552. {
  553. v8js_ctx *c;
  554. zval *callable;
  555. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &callable) == FAILURE) {
  556. return;
  557. }
  558. c = Z_V8JS_CTX_OBJ_P(getThis());
  559. ZVAL_COPY(&c->module_loader, callable);
  560. }
  561. /* }}} */
  562. /* {{{ proto void V8Js::setTimeLimit(int time_limit)
  563. */
  564. static PHP_METHOD(V8Js, setTimeLimit)
  565. {
  566. v8js_ctx *c;
  567. long time_limit = 0;
  568. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &time_limit) == FAILURE) {
  569. return;
  570. }
  571. c = Z_V8JS_CTX_OBJ_P(getThis());
  572. c->time_limit = time_limit;
  573. V8JSG(timer_mutex).lock();
  574. for (std::deque< v8js_timer_ctx* >::iterator it = V8JSG(timer_stack).begin();
  575. it != V8JSG(timer_stack).end(); it ++) {
  576. if((*it)->ctx == c && !(*it)->killed) {
  577. (*it)->time_limit = time_limit;
  578. // Calculate the time point when the time limit is exceeded
  579. std::chrono::milliseconds duration(time_limit);
  580. std::chrono::time_point<std::chrono::high_resolution_clock> from = std::chrono::high_resolution_clock::now();
  581. (*it)->time_point = from + duration;
  582. }
  583. }
  584. V8JSG(timer_mutex).unlock();
  585. if (c->in_execution && time_limit && !V8JSG(timer_thread)) {
  586. /* If timer thread is not started already and we now impose a time limit
  587. * finally install the timer. */
  588. V8JSG(timer_thread) = new std::thread(v8js_timer_thread, ZEND_MODULE_GLOBALS_BULK(v8js));
  589. }
  590. }
  591. /* }}} */
  592. /* {{{ proto void V8Js::setMemoryLimit(int memory_limit)
  593. */
  594. static PHP_METHOD(V8Js, setMemoryLimit)
  595. {
  596. v8js_ctx *c;
  597. long memory_limit = 0;
  598. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &memory_limit) == FAILURE) {
  599. return;
  600. }
  601. c = Z_V8JS_CTX_OBJ_P(getThis());
  602. c->memory_limit = memory_limit;
  603. V8JSG(timer_mutex).lock();
  604. for (std::deque< v8js_timer_ctx* >::iterator it = V8JSG(timer_stack).begin();
  605. it != V8JSG(timer_stack).end(); it ++) {
  606. if((*it)->ctx == c && !(*it)->killed) {
  607. (*it)->memory_limit = memory_limit;
  608. }
  609. }
  610. V8JSG(timer_mutex).unlock();
  611. if (c->in_execution && memory_limit && !V8JSG(timer_thread)) {
  612. /* If timer thread is not started already and we now impose a memory limit
  613. * finally install the timer. */
  614. V8JSG(timer_thread) = new std::thread(v8js_timer_thread, ZEND_MODULE_GLOBALS_BULK(v8js));
  615. }
  616. }
  617. /* }}} */
  618. static void v8js_persistent_zval_ctor(zval *p) /* {{{ */
  619. {
  620. assert(Z_TYPE_P(p) == IS_STRING);
  621. Z_STR_P(p) = zend_string_dup(Z_STR_P(p), 1);
  622. }
  623. /* }}} */
  624. static void v8js_persistent_zval_dtor(zval *p) /* {{{ */
  625. {
  626. assert(Z_TYPE_P(p) == IS_STRING);
  627. free(Z_STR_P(p));
  628. }
  629. /* }}} */
  630. static void v8js_script_free(v8js_script *res)
  631. {
  632. efree(res->name);
  633. delete res->script; // does Reset()
  634. }
  635. static void v8js_script_dtor(zend_resource *rsrc) /* {{{ */
  636. {
  637. v8js_script *res = (v8js_script *)rsrc->ptr;
  638. if (res) {
  639. if(res->ctx) {
  640. std::vector<v8js_script *>::iterator it = std::find(res->ctx->script_objects.begin(), res->ctx->script_objects.end(), res);
  641. res->ctx->script_objects.erase(it);
  642. }
  643. v8js_script_free(res);
  644. efree(res);
  645. }
  646. }
  647. /* }}} */
  648. static int v8js_register_extension(zend_string *name, zend_string *source, zval *deps_arr, zend_bool auto_enable TSRMLS_DC) /* {{{ */
  649. {
  650. v8js_jsext *jsext = NULL;
  651. #ifdef ZTS
  652. v8js_process_globals.lock.lock();
  653. #endif
  654. if (!v8js_process_globals.extensions) {
  655. v8js_process_globals.extensions = (HashTable *) malloc(sizeof(HashTable));
  656. zend_hash_init(v8js_process_globals.extensions, 1, NULL, v8js_jsext_dtor, 1);
  657. } else if (zend_hash_exists(v8js_process_globals.extensions, name)) {
  658. #ifdef ZTS
  659. v8js_process_globals.lock.unlock();
  660. #endif
  661. return FAILURE;
  662. }
  663. jsext = (v8js_jsext *) calloc(1, sizeof(v8js_jsext));
  664. if (deps_arr) {
  665. jsext->deps_count = zend_hash_num_elements(Z_ARRVAL_P(deps_arr));
  666. if (v8js_create_ext_strarr(&jsext->deps, jsext->deps_count, Z_ARRVAL_P(deps_arr)) == FAILURE) {
  667. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid dependency array passed");
  668. v8js_jsext_free_storage(jsext);
  669. #ifdef ZTS
  670. v8js_process_globals.lock.unlock();
  671. #endif
  672. return FAILURE;
  673. }
  674. }
  675. jsext->auto_enable = auto_enable;
  676. jsext->name = zend_string_dup(name, 1);
  677. jsext->source = zend_string_dup(source, 1);
  678. if (jsext->deps) {
  679. jsext->deps_ht = (HashTable *) malloc(sizeof(HashTable));
  680. zend_hash_init(jsext->deps_ht, jsext->deps_count, NULL, v8js_persistent_zval_dtor, 1);
  681. zend_hash_copy(jsext->deps_ht, Z_ARRVAL_P(deps_arr), v8js_persistent_zval_ctor);
  682. }
  683. jsext->extension = new v8::Extension(ZSTR_VAL(jsext->name), ZSTR_VAL(jsext->source), jsext->deps_count, jsext->deps);
  684. if (!zend_hash_add_ptr(v8js_process_globals.extensions, jsext->name, jsext)) {
  685. v8js_jsext_free_storage(jsext);
  686. #ifdef ZTS
  687. v8js_process_globals.lock.unlock();
  688. #endif
  689. return FAILURE;
  690. }
  691. #ifdef ZTS
  692. v8js_process_globals.lock.unlock();
  693. #endif
  694. jsext->extension->set_auto_enable(auto_enable ? true : false);
  695. v8::RegisterExtension(jsext->extension);
  696. return SUCCESS;
  697. }
  698. /* }}} */
  699. /* {{{ proto bool V8Js::registerExtension(string ext_name, string script [, array deps [, bool auto_enable]])
  700. */
  701. static PHP_METHOD(V8Js, registerExtension)
  702. {
  703. zend_string *ext_name, *script;
  704. zval *deps_arr = NULL;
  705. zend_bool auto_enable = 0;
  706. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "SS|ab", &ext_name, &script, &deps_arr, &auto_enable) == FAILURE) {
  707. return;
  708. }
  709. if (!ZSTR_LEN(ext_name)) {
  710. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Extension name cannot be empty");
  711. } else if (!ZSTR_LEN(script)) {
  712. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Script cannot be empty");
  713. } else if (v8js_register_extension(ext_name, script, deps_arr, auto_enable TSRMLS_CC) == SUCCESS) {
  714. RETURN_TRUE;
  715. }
  716. RETURN_FALSE;
  717. }
  718. /* }}} */
  719. /* ## Static methods ## */
  720. /* {{{ proto array V8Js::getExtensions()
  721. */
  722. static PHP_METHOD(V8Js, getExtensions)
  723. {
  724. v8js_jsext *jsext;
  725. ulong index;
  726. zend_string *key;
  727. zval *val, ext;
  728. if (zend_parse_parameters_none() == FAILURE) {
  729. return;
  730. }
  731. array_init(return_value);
  732. #ifdef ZTS
  733. v8js_process_globals.lock.lock();
  734. #endif
  735. if (v8js_process_globals.extensions) {
  736. ZEND_HASH_FOREACH_KEY_VAL(v8js_process_globals.extensions, index, key, val) {
  737. if (key) {
  738. jsext = (v8js_jsext *) Z_PTR_P(val);
  739. array_init(&ext);
  740. add_assoc_bool_ex(&ext, ZEND_STRL("auto_enable"), jsext->auto_enable);
  741. if (jsext->deps_ht) {
  742. zval deps_arr;
  743. array_init(&deps_arr);
  744. zend_hash_copy(Z_ARRVAL_P(&deps_arr), jsext->deps_ht, (copy_ctor_func_t) zval_add_ref);
  745. add_assoc_zval_ex(&ext, ZEND_STRL("deps"), &deps_arr);
  746. }
  747. add_assoc_zval_ex(return_value, ZSTR_VAL(key), ZSTR_LEN(key), &ext);
  748. }
  749. } ZEND_HASH_FOREACH_END();
  750. }
  751. #ifdef ZTS
  752. v8js_process_globals.lock.unlock();
  753. #endif
  754. }
  755. /* }}} */
  756. /* {{{ arginfo */
  757. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_construct, 0, 0, 0)
  758. ZEND_ARG_INFO(0, object_name)
  759. ZEND_ARG_INFO(0, variables)
  760. ZEND_ARG_INFO(0, extensions)
  761. ZEND_ARG_INFO(0, report_uncaught_exceptions)
  762. ZEND_END_ARG_INFO()
  763. ZEND_BEGIN_ARG_INFO(arginfo_v8js_sleep, 0)
  764. ZEND_END_ARG_INFO()
  765. ZEND_BEGIN_ARG_INFO(arginfo_v8js_wakeup, 0)
  766. ZEND_END_ARG_INFO()
  767. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_executestring, 0, 0, 1)
  768. ZEND_ARG_INFO(0, script)
  769. ZEND_ARG_INFO(0, identifier)
  770. ZEND_ARG_INFO(0, flags)
  771. ZEND_ARG_INFO(0, time_limit)
  772. ZEND_ARG_INFO(0, memory_limit)
  773. ZEND_END_ARG_INFO()
  774. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_compilestring, 0, 0, 1)
  775. ZEND_ARG_INFO(0, script)
  776. ZEND_ARG_INFO(0, identifier)
  777. ZEND_END_ARG_INFO()
  778. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_executescript, 0, 0, 1)
  779. ZEND_ARG_INFO(0, script)
  780. ZEND_ARG_INFO(0, flags)
  781. ZEND_ARG_INFO(0, time_limit)
  782. ZEND_ARG_INFO(0, memory_limit)
  783. ZEND_END_ARG_INFO()
  784. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_checkstring, 0, 0, 1)
  785. ZEND_ARG_INFO(0, script)
  786. ZEND_END_ARG_INFO()
  787. ZEND_BEGIN_ARG_INFO(arginfo_v8js_getpendingexception, 0)
  788. ZEND_END_ARG_INFO()
  789. ZEND_BEGIN_ARG_INFO(arginfo_v8js_clearpendingexception, 0)
  790. ZEND_END_ARG_INFO()
  791. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_setmoduleloader, 0, 0, 1)
  792. ZEND_ARG_INFO(0, callable)
  793. ZEND_END_ARG_INFO()
  794. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_registerextension, 0, 0, 2)
  795. ZEND_ARG_INFO(0, extension_name)
  796. ZEND_ARG_INFO(0, script)
  797. ZEND_ARG_INFO(0, dependencies)
  798. ZEND_ARG_INFO(0, auto_enable)
  799. ZEND_END_ARG_INFO()
  800. ZEND_BEGIN_ARG_INFO(arginfo_v8js_getextensions, 0)
  801. ZEND_END_ARG_INFO()
  802. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_settimelimit, 0, 0, 1)
  803. ZEND_ARG_INFO(0, time_limit)
  804. ZEND_END_ARG_INFO()
  805. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_setmemorylimit, 0, 0, 1)
  806. ZEND_ARG_INFO(0, memory_limit)
  807. ZEND_END_ARG_INFO()
  808. static const zend_function_entry v8js_methods[] = { /* {{{ */
  809. PHP_ME(V8Js, __construct, arginfo_v8js_construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
  810. PHP_ME(V8Js, __sleep, arginfo_v8js_sleep, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
  811. PHP_ME(V8Js, __wakeup, arginfo_v8js_sleep, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
  812. PHP_ME(V8Js, executeString, arginfo_v8js_executestring, ZEND_ACC_PUBLIC)
  813. PHP_ME(V8Js, compileString, arginfo_v8js_compilestring, ZEND_ACC_PUBLIC)
  814. PHP_ME(V8Js, executeScript, arginfo_v8js_executescript, ZEND_ACC_PUBLIC)
  815. PHP_ME(V8Js, checkString, arginfo_v8js_checkstring, ZEND_ACC_PUBLIC|ZEND_ACC_DEPRECATED)
  816. PHP_ME(V8Js, getPendingException, arginfo_v8js_getpendingexception, ZEND_ACC_PUBLIC)
  817. PHP_ME(V8Js, clearPendingException, arginfo_v8js_clearpendingexception, ZEND_ACC_PUBLIC)
  818. PHP_ME(V8Js, setModuleLoader, arginfo_v8js_setmoduleloader, ZEND_ACC_PUBLIC)
  819. PHP_ME(V8Js, registerExtension, arginfo_v8js_registerextension, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
  820. PHP_ME(V8Js, getExtensions, arginfo_v8js_getextensions, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
  821. PHP_ME(V8Js, setTimeLimit, arginfo_v8js_settimelimit, ZEND_ACC_PUBLIC)
  822. PHP_ME(V8Js, setMemoryLimit, arginfo_v8js_setmemorylimit, ZEND_ACC_PUBLIC)
  823. {NULL, NULL, NULL}
  824. };
  825. /* }}} */
  826. /* V8Js object handlers */
  827. static void v8js_write_property(zval *object, zval *member, zval *value, void **cache_slot TSRMLS_DC) /* {{{ */
  828. {
  829. V8JS_BEGIN_CTX(c, object)
  830. /* Check whether member is public, if so, export to V8. */
  831. zend_property_info *property_info = zend_get_property_info(c->std.ce, Z_STR_P(member), 1 TSRMLS_CC);
  832. if(!property_info ||
  833. (property_info != ZEND_WRONG_PROPERTY_INFO &&
  834. property_info->flags & ZEND_ACC_PUBLIC)) {
  835. /* Global PHP JS object */
  836. v8::Local<v8::String> object_name_js = v8::Local<v8::String>::New(isolate, c->object_name);
  837. v8::Local<v8::Object> jsobj = V8JS_GLOBAL(isolate)->Get(object_name_js)->ToObject();
  838. /* Write value to PHP JS object */
  839. jsobj->ForceSet(V8JS_SYML(Z_STRVAL_P(member), Z_STRLEN_P(member)), zval_to_v8js(value, isolate TSRMLS_CC), v8::ReadOnly);
  840. }
  841. /* Write value to PHP object */
  842. std_object_handlers.write_property(object, member, value, NULL);
  843. }
  844. /* }}} */
  845. static void v8js_unset_property(zval *object, zval *member, void **cache_slot TSRMLS_DC) /* {{{ */
  846. {
  847. V8JS_BEGIN_CTX(c, object)
  848. /* Global PHP JS object */
  849. v8::Local<v8::String> object_name_js = v8::Local<v8::String>::New(isolate, c->object_name);
  850. v8::Local<v8::Object> jsobj = V8JS_GLOBAL(isolate)->Get(object_name_js)->ToObject();
  851. /* Delete value from PHP JS object */
  852. jsobj->Delete(V8JS_SYML(Z_STRVAL_P(member), Z_STRLEN_P(member)));
  853. /* Unset from PHP object */
  854. std_object_handlers.unset_property(object, member, NULL);
  855. }
  856. /* }}} */
  857. PHP_MINIT_FUNCTION(v8js_class) /* {{{ */
  858. {
  859. zend_class_entry ce;
  860. /* V8Js Class */
  861. INIT_CLASS_ENTRY(ce, "V8Js", v8js_methods);
  862. php_ce_v8js = zend_register_internal_class(&ce TSRMLS_CC);
  863. php_ce_v8js->create_object = v8js_new;
  864. /* V8Js handlers */
  865. memcpy(&v8js_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
  866. v8js_object_handlers.clone_obj = NULL;
  867. v8js_object_handlers.write_property = v8js_write_property;
  868. v8js_object_handlers.unset_property = v8js_unset_property;
  869. /* V8Js Class Constants */
  870. zend_declare_class_constant_string(php_ce_v8js, ZEND_STRL("V8_VERSION"), PHP_V8_VERSION TSRMLS_CC);
  871. zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("FLAG_NONE"), V8JS_FLAG_NONE TSRMLS_CC);
  872. zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("FLAG_FORCE_ARRAY"), V8JS_FLAG_FORCE_ARRAY TSRMLS_CC);
  873. zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("FLAG_PROPAGATE_PHP_EXCEPTIONS"), V8JS_FLAG_PROPAGATE_PHP_EXCEPTIONS TSRMLS_CC);
  874. le_v8js_script = zend_register_list_destructors_ex(v8js_script_dtor, NULL, PHP_V8JS_SCRIPT_RES_NAME, module_number);
  875. #if PHP_V8_API_VERSION >= 4004010 && PHP_V8_API_VERSION < 4004044
  876. static ArrayBufferAllocator array_buffer_allocator;
  877. v8::V8::SetArrayBufferAllocator(&array_buffer_allocator);
  878. #endif
  879. return SUCCESS;
  880. } /* }}} */
  881. /*
  882. * Local variables:
  883. * tab-width: 4
  884. * c-basic-offset: 4
  885. * End:
  886. * vim600: noet sw=4 ts=4 fdm=marker
  887. * vim<600: noet sw=4 ts=4
  888. */