v8js_class.cc 31 KB

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