v8js_class.cc 31 KB

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