v8js_class.cc 31 KB

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