v8js.cc 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402
  1. /*
  2. +----------------------------------------------------------------------+
  3. | PHP Version 5 |
  4. +----------------------------------------------------------------------+
  5. | Copyright (c) 1997-2012 The PHP Group |
  6. +----------------------------------------------------------------------+
  7. | This source file is subject to version 3.01 of the PHP license, |
  8. | that is bundled with this package in the file LICENSE, and is |
  9. | available through the world-wide-web at the following url: |
  10. | http://www.php.net/license/3_01.txt |
  11. | If you did not receive a copy of the PHP license and are unable to |
  12. | obtain it through the world-wide-web, please send a note to |
  13. | [email protected] so we can mail you a copy immediately. |
  14. +----------------------------------------------------------------------+
  15. | Author: Jani Taskinen <[email protected]> |
  16. | Author: Patrick Reilly <[email protected]> |
  17. +----------------------------------------------------------------------+
  18. */
  19. /* $Id$ */
  20. #define V8JS_DEBUG 0
  21. #ifdef HAVE_CONFIG_H
  22. #include "config.h"
  23. #endif
  24. extern "C" {
  25. #include "php.h"
  26. #include "php_ini.h"
  27. #include "ext/standard/info.h"
  28. #include "ext/standard/php_string.h"
  29. #include "ext/standard/php_smart_str.h"
  30. #include "zend_exceptions.h"
  31. #include "php_v8js.h"
  32. }
  33. #include <v8.h>
  34. #include "php_v8js_macros.h"
  35. #include <chrono>
  36. #include <stack>
  37. #include <thread>
  38. /* Forward declarations */
  39. static void php_v8js_throw_exception(v8::TryCatch * TSRMLS_DC);
  40. static void php_v8js_create_exception(zval *, v8::TryCatch * TSRMLS_DC);
  41. /* {{{ Context container */
  42. struct php_v8js_ctx {
  43. zend_object std;
  44. v8::Persistent<v8::String> object_name;
  45. v8::Persistent<v8::Context> context;
  46. zend_bool report_uncaught;
  47. zval *pending_exception;
  48. int in_execution;
  49. v8::Isolate *isolate;
  50. bool execution_terminated;
  51. };
  52. /* }}} */
  53. // Timer context
  54. struct php_v8js_timer_ctx
  55. {
  56. std::chrono::time_point<std::chrono::high_resolution_clock> time_point;
  57. php_v8js_ctx *v8js_ctx;
  58. };
  59. /* Module globals */
  60. ZEND_BEGIN_MODULE_GLOBALS(v8js)
  61. int v8_initialized;
  62. HashTable *extensions;
  63. v8::Persistent<v8::FunctionTemplate> global_template;
  64. int disposed_contexts; /* Disposed contexts since last time V8 did GC */
  65. /* Ini globals */
  66. char *v8_flags; /* V8 command line flags */
  67. int max_disposed_contexts; /* Max disposed context allowed before forcing V8 GC */
  68. // Timer thread globals
  69. std::stack<php_v8js_timer_ctx *> timer_stack;
  70. std::thread *timer_thread;
  71. bool timer_stop;
  72. ZEND_END_MODULE_GLOBALS(v8js)
  73. #ifdef ZTS
  74. # define V8JSG(v) TSRMG(v8js_globals_id, zend_v8js_globals *, v)
  75. #else
  76. # define V8JSG(v) (v8js_globals.v)
  77. #endif
  78. ZEND_DECLARE_MODULE_GLOBALS(v8js)
  79. /* {{{ INI Settings */
  80. static ZEND_INI_MH(v8js_OnUpdateMaxDisposedContexts) /* {{{ */
  81. {
  82. int max_disposed = zend_atoi(new_value, new_value_length);
  83. if (max_disposed <= 0) {
  84. return FAILURE;
  85. }
  86. V8JSG(max_disposed_contexts) = max_disposed;
  87. return SUCCESS;
  88. }
  89. /* }}} */
  90. static ZEND_INI_MH(v8js_OnUpdateV8Flags) /* {{{ */
  91. {
  92. if (new_value) {
  93. if (V8JSG(v8_flags)) {
  94. free(V8JSG(v8_flags));
  95. V8JSG(v8_flags) = NULL;
  96. }
  97. if (!new_value[0]) {
  98. return FAILURE;
  99. }
  100. V8JSG(v8_flags) = zend_strndup(new_value, new_value_length);
  101. }
  102. return SUCCESS;
  103. }
  104. /* }}} */
  105. ZEND_INI_BEGIN() /* {{{ */
  106. ZEND_INI_ENTRY("v8js.max_disposed_contexts", "25", ZEND_INI_ALL, v8js_OnUpdateMaxDisposedContexts)
  107. ZEND_INI_ENTRY("v8js.flags", NULL, ZEND_INI_ALL, v8js_OnUpdateV8Flags)
  108. ZEND_INI_END()
  109. /* }}} */
  110. /* }}} INI */
  111. /* {{{ Class Entries */
  112. zend_class_entry *php_ce_v8_object;
  113. zend_class_entry *php_ce_v8_function;
  114. static zend_class_entry *php_ce_v8js;
  115. static zend_class_entry *php_ce_v8js_exception;
  116. /* }}} */
  117. /* {{{ Object Handlers */
  118. static zend_object_handlers v8js_object_handlers;
  119. static zend_object_handlers v8_object_handlers;
  120. /* }}} */
  121. /* {{{ Extension container */
  122. struct php_v8js_jsext {
  123. zend_bool auto_enable;
  124. HashTable *deps_ht;
  125. const char **deps;
  126. int deps_count;
  127. char *name;
  128. char *source;
  129. };
  130. /* }}} */
  131. /* {{{ Object container */
  132. struct php_v8js_object {
  133. zend_object std;
  134. v8::Persistent<v8::Value> v8obj;
  135. int flags;
  136. };
  137. /* }}} */
  138. #ifdef COMPILE_DL_V8JS
  139. ZEND_GET_MODULE(v8js)
  140. #endif
  141. /* {{{ Class: V8 */
  142. #define V8JS_V8_INVOKE_FUNC_NAME "V8Js::V8::Invoke"
  143. /* V8 Object handlers */
  144. static zval *php_v8js_v8_read_property(zval *object, zval *member, int type ZEND_HASH_KEY_DC TSRMLS_DC) /* {{{ */
  145. {
  146. zval *retval = NULL;
  147. php_v8js_object *obj = (php_v8js_object *) zend_object_store_get_object(object TSRMLS_CC);
  148. if (Z_TYPE_P(member) == IS_STRING && obj->v8obj->IsObject() && !obj->v8obj->IsFunction())
  149. {
  150. v8::Local<v8::Object> jsObj = obj->v8obj->ToObject();
  151. v8::Local<v8::String> jsKey = V8JS_STRL(Z_STRVAL_P(member), Z_STRLEN_P(member));
  152. v8::Local<v8::Value> jsVal;
  153. /* Skip any prototype properties */
  154. if (jsObj->HasRealNamedProperty(jsKey) || jsObj->HasRealNamedCallbackProperty(jsKey)) {
  155. jsVal = jsObj->Get(jsKey);
  156. if (jsVal->IsObject()) {
  157. ALLOC_INIT_ZVAL(retval);
  158. Z_SET_REFCOUNT_P(retval, 0);
  159. } else {
  160. MAKE_STD_ZVAL(retval);
  161. }
  162. if (v8js_to_zval(jsVal, retval, obj->flags TSRMLS_CC) == SUCCESS) {
  163. return retval;
  164. }
  165. }
  166. }
  167. ALLOC_INIT_ZVAL(retval);
  168. return retval;
  169. }
  170. /* }}} */
  171. static void php_v8js_v8_write_property(zval *object, zval *member, zval *value ZEND_HASH_KEY_DC TSRMLS_DC) /* {{{ */
  172. {
  173. php_v8js_object *obj = (php_v8js_object *) zend_object_store_get_object(object TSRMLS_CC);
  174. if (obj->v8obj->IsObject() && !obj->v8obj->IsFunction()) {
  175. obj->v8obj->ToObject()->ForceSet(V8JS_SYML(Z_STRVAL_P(member), Z_STRLEN_P(member)), zval_to_v8js(value TSRMLS_CC));
  176. }
  177. }
  178. /* }}} */
  179. static void php_v8js_v8_unset_property(zval *object, zval *member ZEND_HASH_KEY_DC TSRMLS_DC) /* {{{ */
  180. {
  181. php_v8js_object *obj = (php_v8js_object *) zend_object_store_get_object(object TSRMLS_CC);
  182. if (obj->v8obj->IsObject() && !obj->v8obj->IsFunction()) {
  183. obj->v8obj->ToObject()->ForceDelete(V8JS_SYML(Z_STRVAL_P(member), Z_STRLEN_P(member)));
  184. }
  185. }
  186. /* }}} */
  187. int php_v8js_v8_get_properties_hash(v8::Handle<v8::Value> jsValue, HashTable *retval, int flags TSRMLS_DC) /* {{{ */
  188. {
  189. v8::Local<v8::Object> jsObj = jsValue->ToObject();
  190. if (!jsObj.IsEmpty()) {
  191. v8::Local<v8::Array> jsKeys = jsObj->GetPropertyNames();
  192. for (unsigned i = 0; i < jsKeys->Length(); i++)
  193. {
  194. v8::Local<v8::String> jsKey = jsKeys->Get(i)->ToString();
  195. /* Skip any prototype properties */
  196. if (!jsObj->HasRealNamedProperty(jsKey) && !jsObj->HasRealNamedCallbackProperty(jsKey) && !jsObj->HasRealIndexedProperty(i)) {
  197. continue;
  198. }
  199. v8::Local<v8::Value> jsVal = jsObj->Get(jsKey);
  200. v8::String::Utf8Value cstr(jsKey);
  201. const char *key = ToCString(cstr);
  202. zval *value = NULL;
  203. MAKE_STD_ZVAL(value);
  204. if (v8js_to_zval(jsVal, value, flags TSRMLS_CC) == FAILURE) {
  205. zval_ptr_dtor(&value);
  206. return FAILURE;
  207. }
  208. if ((flags & V8JS_FLAG_FORCE_ARRAY) || jsValue->IsArray()) {
  209. zend_symtable_update(retval, key, strlen(key) + 1, (void *)&value, sizeof(zval *), NULL);
  210. } else {
  211. zend_hash_update(retval, key, strlen(key) + 1, (void *) &value, sizeof(zval *), NULL);
  212. }
  213. }
  214. return SUCCESS;
  215. }
  216. return FAILURE;
  217. }
  218. /* }}} */
  219. static HashTable *php_v8js_v8_get_properties(zval *object TSRMLS_DC) /* {{{ */
  220. {
  221. php_v8js_object *obj = (php_v8js_object *) zend_object_store_get_object(object TSRMLS_CC);
  222. HashTable *retval;
  223. ALLOC_HASHTABLE(retval);
  224. zend_hash_init(retval, 0, NULL, ZVAL_PTR_DTOR, 0);
  225. v8::HandleScope local_scope;
  226. v8::Handle<v8::Context> temp_context = v8::Context::New();
  227. v8::Context::Scope temp_scope(temp_context);
  228. if (php_v8js_v8_get_properties_hash(obj->v8obj, retval, obj->flags TSRMLS_CC) == SUCCESS) {
  229. return retval;
  230. }
  231. return NULL;
  232. }
  233. /* }}} */
  234. static HashTable *php_v8js_v8_get_debug_info(zval *object, int *is_temp TSRMLS_DC) /* {{{ */
  235. {
  236. *is_temp = 1;
  237. return php_v8js_v8_get_properties(object TSRMLS_CC);
  238. }
  239. /* }}} */
  240. static zend_function *php_v8js_v8_get_method(zval **object_ptr, char *method, int method_len ZEND_HASH_KEY_DC TSRMLS_DC) /* {{{ */
  241. {
  242. zend_function *f;
  243. v8::Local<v8::String> jsKey = V8JS_STRL(method, method_len);
  244. php_v8js_object *obj = (php_v8js_object *) zend_object_store_get_object(*object_ptr TSRMLS_CC);
  245. if (!obj->v8obj.IsEmpty() && obj->v8obj->IsObject() && !obj->v8obj->IsFunction()) {
  246. v8::Local<v8::Object> jsObj = obj->v8obj->ToObject();
  247. if (jsObj->Has(jsKey) && jsObj->Get(jsKey)->IsFunction()) {
  248. f = (zend_function *) ecalloc(1, sizeof(*f));
  249. f->type = ZEND_OVERLOADED_FUNCTION_TEMPORARY;
  250. f->common.function_name = estrndup(method, method_len);
  251. return f;
  252. }
  253. }
  254. return NULL;
  255. }
  256. /* }}} */
  257. #if PHP_VERSION_ID >= 50400
  258. static int php_v8js_v8_call_method(const char *method, INTERNAL_FUNCTION_PARAMETERS) /* {{{ */
  259. #else
  260. static int php_v8js_v8_call_method(char *method, INTERNAL_FUNCTION_PARAMETERS) /* {{{ */
  261. #endif
  262. {
  263. zval *object = this_ptr, ***argv = NULL;
  264. int i = 0, argc = ZEND_NUM_ARGS();
  265. php_v8js_object *obj;
  266. obj = (php_v8js_object *) zend_object_store_get_object(object TSRMLS_CC);
  267. if (obj->v8obj.IsEmpty()) {
  268. zval_ptr_dtor(&object);
  269. return FAILURE;
  270. }
  271. if (argc > 0) {
  272. argv = (zval***)safe_emalloc(sizeof(zval**), argc, 0);
  273. zend_get_parameters_array_ex(argc, argv);
  274. }
  275. v8::Local<v8::String> method_name = V8JS_SYML(method, strlen(method));
  276. v8::Local<v8::Object> v8obj = obj->v8obj->ToObject();
  277. v8::Local<v8::Function> cb;
  278. if (method_name->Equals(V8JS_SYM(V8JS_V8_INVOKE_FUNC_NAME))) {
  279. cb = v8::Local<v8::Function>::Cast(v8obj);
  280. } else {
  281. cb = v8::Local<v8::Function>::Cast(v8obj->Get(method_name));
  282. }
  283. v8::Local<v8::Value> *jsArgv = new v8::Local<v8::Value>[argc];
  284. v8::Local<v8::Value> js_retval;
  285. for (i = 0; i < argc; i++) {
  286. jsArgv[i] = v8::Local<v8::Value>::New(zval_to_v8js(*argv[i] TSRMLS_CC));
  287. }
  288. js_retval = cb->Call(V8JS_GLOBAL, argc, jsArgv);
  289. zval_ptr_dtor(&object);
  290. if (argc > 0) {
  291. efree(argv);
  292. }
  293. if (return_value_used) {
  294. return v8js_to_zval(js_retval, return_value, obj->flags TSRMLS_CC);
  295. }
  296. return SUCCESS;
  297. }
  298. /* }}} */
  299. static int php_v8js_v8_get_closure(zval *object, zend_class_entry **ce_ptr, zend_function **fptr_ptr, zval **zobj_ptr TSRMLS_DC) /* {{{ */
  300. {
  301. zend_function *invoke;
  302. php_v8js_object *obj = (php_v8js_object *) zend_object_store_get_object(object TSRMLS_CC);
  303. if (!obj->v8obj->IsFunction()) {
  304. return FAILURE;
  305. }
  306. invoke = (zend_function *) ecalloc(1, sizeof(*invoke));
  307. invoke->type = ZEND_OVERLOADED_FUNCTION_TEMPORARY;
  308. invoke->common.function_name = estrndup(V8JS_V8_INVOKE_FUNC_NAME, sizeof(V8JS_V8_INVOKE_FUNC_NAME) - 1);
  309. *fptr_ptr = invoke;
  310. if (zobj_ptr) {
  311. *zobj_ptr = object;
  312. }
  313. *ce_ptr = NULL;
  314. return SUCCESS;
  315. }
  316. /* }}} */
  317. static void php_v8js_v8_free_storage(void *object, zend_object_handle handle TSRMLS_DC) /* {{{ */
  318. {
  319. php_v8js_object *c = (php_v8js_object *) object;
  320. zend_object_std_dtor(&c->std TSRMLS_CC);
  321. if (!c->v8obj.IsEmpty()) {
  322. c->v8obj.Dispose();
  323. }
  324. efree(object);
  325. }
  326. /* }}} */
  327. static zend_object_value php_v8js_v8_new(zend_class_entry *ce TSRMLS_DC) /* {{{ */
  328. {
  329. zend_object_value retval;
  330. php_v8js_object *c;
  331. c = (php_v8js_object *) ecalloc(1, sizeof(*c));
  332. zend_object_std_init(&c->std, ce TSRMLS_CC);
  333. retval.handle = zend_objects_store_put(c, NULL, (zend_objects_free_object_storage_t) php_v8js_v8_free_storage, NULL TSRMLS_CC);
  334. retval.handlers = &v8_object_handlers;
  335. return retval;
  336. }
  337. /* }}} */
  338. void php_v8js_create_v8(zval *res, v8::Handle<v8::Value> value, int flags TSRMLS_DC) /* {{{ */
  339. {
  340. php_v8js_object *c;
  341. object_init_ex(res, value->IsFunction() ? php_ce_v8_function : php_ce_v8_object);
  342. c = (php_v8js_object *) zend_object_store_get_object(res TSRMLS_CC);
  343. c->v8obj = v8::Persistent<v8::Value>::New(value);
  344. c->flags = flags;
  345. }
  346. /* }}} */
  347. /* }}} V8 */
  348. /* {{{ Class: V8Js */
  349. static void php_v8js_free_storage(void *object TSRMLS_DC) /* {{{ */
  350. {
  351. php_v8js_ctx *c = (php_v8js_ctx *) object;
  352. zend_object_std_dtor(&c->std TSRMLS_CC);
  353. if (c->pending_exception) {
  354. zval_ptr_dtor(&c->pending_exception);
  355. }
  356. c->object_name.Dispose();
  357. /* Clear global object, dispose context */
  358. if (!c->context.IsEmpty()) {
  359. c->context.Dispose();
  360. c->context.Clear();
  361. V8JSG(disposed_contexts) = v8::V8::ContextDisposedNotification();
  362. #if V8JS_DEBUG
  363. fprintf(stderr, "Context dispose notification sent (%d)\n", V8JSG(disposed_contexts));
  364. fflush(stderr);
  365. #endif
  366. }
  367. efree(object);
  368. }
  369. /* }}} */
  370. static zend_object_value php_v8js_new(zend_class_entry *ce TSRMLS_DC) /* {{{ */
  371. {
  372. zend_object_value retval;
  373. php_v8js_ctx *c;
  374. c = (php_v8js_ctx *) ecalloc(1, sizeof(*c));
  375. zend_object_std_init(&c->std, ce TSRMLS_CC);
  376. retval.handle = zend_objects_store_put(c, NULL, (zend_objects_free_object_storage_t) php_v8js_free_storage, NULL TSRMLS_CC);
  377. retval.handlers = &v8js_object_handlers;
  378. return retval;
  379. }
  380. /* }}} */
  381. static void _php_v8js_free_ext_strarr(const char **arr, int count) /* {{{ */
  382. {
  383. int i;
  384. if (arr) {
  385. for (i = 0; i < count; i++) {
  386. if (arr[i]) {
  387. free((void *) arr[i]);
  388. }
  389. }
  390. free(arr);
  391. }
  392. }
  393. /* }}} */
  394. static void php_v8js_jsext_dtor(php_v8js_jsext *jsext) /* {{{ */
  395. {
  396. if (jsext->deps_ht) {
  397. zend_hash_destroy(jsext->deps_ht);
  398. free(jsext->deps_ht);
  399. }
  400. if (jsext->deps) {
  401. _php_v8js_free_ext_strarr(jsext->deps, jsext->deps_count);
  402. }
  403. free(jsext->name);
  404. free(jsext->source);
  405. }
  406. /* }}} */
  407. static int _php_v8js_create_ext_strarr(const char ***retval, int count, HashTable *ht) /* {{{ */
  408. {
  409. const char **exts = NULL;
  410. HashPosition pos;
  411. zval **tmp;
  412. int i = 0;
  413. exts = (const char **) calloc(1, count * sizeof(char *));
  414. zend_hash_internal_pointer_reset_ex(ht, &pos);
  415. while (zend_hash_get_current_data_ex(ht, (void **) &tmp, &pos) == SUCCESS) {
  416. if (Z_TYPE_PP(tmp) == IS_STRING) {
  417. exts[i++] = zend_strndup(Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp));
  418. } else {
  419. _php_v8js_free_ext_strarr(exts, i);
  420. return FAILURE;
  421. }
  422. zend_hash_move_forward_ex(ht, &pos);
  423. }
  424. *retval = exts;
  425. return SUCCESS;
  426. }
  427. /* }}} */
  428. static void php_v8js_fatal_error_handler(const char *location, const char *message) /* {{{ */
  429. {
  430. if (location) {
  431. zend_error(E_ERROR, "%s %s", location, message);
  432. } else {
  433. zend_error(E_ERROR, "%s", message);
  434. }
  435. }
  436. /* }}} */
  437. static void php_v8js_init(TSRMLS_D) /* {{{ */
  438. {
  439. /* Run only once */
  440. if (V8JSG(v8_initialized)) {
  441. return;
  442. }
  443. /* Set V8 command line flags (must be done before V8::Initialize()!) */
  444. if (V8JSG(v8_flags)) {
  445. v8::V8::SetFlagsFromString(V8JSG(v8_flags), strlen(V8JSG(v8_flags)));
  446. }
  447. /* Initialize V8 */
  448. v8::V8::Initialize();
  449. /* Redirect fatal errors to PHP error handler */
  450. v8::V8::SetFatalErrorHandler(php_v8js_fatal_error_handler);
  451. /* Run only once */
  452. V8JSG(v8_initialized) = 1;
  453. }
  454. /* }}} */
  455. /* {{{ proto void V8Js::__construct([string object_name [, array variables [, array extensions [, bool report_uncaught_exceptions]]])
  456. __construct for V8Js */
  457. static PHP_METHOD(V8Js, __construct)
  458. {
  459. char *object_name = NULL, *class_name = NULL;
  460. int object_name_len = 0, free = 0;
  461. zend_uint class_name_len = 0;
  462. zend_bool report_uncaught = 1;
  463. zval *vars_arr = NULL, *exts_arr = NULL;
  464. const char **exts = NULL;
  465. int exts_count = 0;
  466. php_v8js_ctx *c = (php_v8js_ctx *) zend_object_store_get_object(getThis() TSRMLS_CC);
  467. if (!c->context.IsEmpty()) {
  468. /* called __construct() twice, bail out */
  469. return;
  470. }
  471. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|saab", &object_name, &object_name_len, &vars_arr, &exts_arr, &report_uncaught) == FAILURE) {
  472. return;
  473. }
  474. /* Throw PHP exception if uncaught exceptions exist */
  475. c->report_uncaught = report_uncaught;
  476. c->pending_exception = NULL;
  477. c->in_execution = 0;
  478. c->isolate = v8::Isolate::New();
  479. c->execution_terminated = false;
  480. /* Initialize V8 */
  481. php_v8js_init(TSRMLS_C);
  482. /* Include extensions used by this context */
  483. /* Note: Extensions registered with auto_enable do not need to be added separately like this. */
  484. if (exts_arr)
  485. {
  486. exts_count = zend_hash_num_elements(Z_ARRVAL_P(exts_arr));
  487. if (_php_v8js_create_ext_strarr(&exts, exts_count, Z_ARRVAL_P(exts_arr)) == FAILURE) {
  488. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid extensions array passed");
  489. return;
  490. }
  491. }
  492. /* Declare configuration for extensions */
  493. v8::ExtensionConfiguration extension_conf(exts_count, exts);
  494. // Isolate execution
  495. v8::Locker locker(c->isolate);
  496. v8::Isolate::Scope isolate_scope(c->isolate);
  497. /* Handle scope */
  498. v8::HandleScope handle_scope;
  499. /* Create global template for global object */
  500. if (V8JSG(global_template).IsEmpty()) {
  501. V8JSG(global_template) = v8::Persistent<v8::FunctionTemplate>::New(v8::FunctionTemplate::New());
  502. V8JSG(global_template)->SetClassName(V8JS_SYM("V8Js"));
  503. /* Register builtin methods */
  504. php_v8js_register_methods(V8JSG(global_template)->InstanceTemplate());
  505. }
  506. /* Create context */
  507. c->context = v8::Context::New(&extension_conf, V8JSG(global_template)->InstanceTemplate());
  508. if (exts) {
  509. _php_v8js_free_ext_strarr(exts, exts_count);
  510. }
  511. /* If extensions have errors, context will be empty. (NOTE: This is V8 stuff, they expect the passed sources to compile :) */
  512. if (c->context.IsEmpty()) {
  513. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to create V8 context. Check that registered extensions do not have errors.");
  514. ZVAL_NULL(getThis());
  515. return;
  516. }
  517. /* Enter context */
  518. v8::Context::Scope context_scope(c->context);
  519. /* Create the PHP container object's function template */
  520. v8::Local<v8::FunctionTemplate> php_obj_t = v8::FunctionTemplate::New();
  521. /* Set class name for PHP object */
  522. #if PHP_VERSION_ID >= 50400
  523. free = !zend_get_object_classname(getThis(), const_cast<const char**>(&class_name), &class_name_len TSRMLS_CC);
  524. #else
  525. free = !zend_get_object_classname(getThis(), &class_name, &class_name_len TSRMLS_CC);
  526. #endif
  527. php_obj_t->SetClassName(V8JS_SYML(class_name, class_name_len));
  528. if (free) {
  529. efree(class_name);
  530. }
  531. /* Register Get accessor for passed variables */
  532. if (vars_arr && zend_hash_num_elements(Z_ARRVAL_P(vars_arr)) > 0) {
  533. php_v8js_register_accessors(php_obj_t->InstanceTemplate(), vars_arr TSRMLS_CC);
  534. }
  535. /* Set name for the PHP JS object */
  536. c->object_name = v8::Persistent<v8::String>::New((object_name_len) ? V8JS_SYML(object_name, object_name_len) : V8JS_SYM("PHP"));
  537. /* Add the PHP object into global object */
  538. V8JS_GLOBAL->Set(c->object_name, php_obj_t->InstanceTemplate()->NewInstance(), v8::ReadOnly);
  539. }
  540. /* }}} */
  541. #define V8JS_BEGIN_CTX(ctx, object) \
  542. php_v8js_ctx *(ctx); \
  543. \
  544. if (!V8JSG(v8_initialized)) { \
  545. zend_error(E_ERROR, "V8 not initialized"); \
  546. return; \
  547. } \
  548. \
  549. (ctx) = (php_v8js_ctx *) zend_object_store_get_object(object TSRMLS_CC); \
  550. v8::Locker locker((ctx)->isolate); \
  551. v8::Isolate::Scope isolate_scope((ctx)->isolate); \
  552. v8::Context::Scope context_scope((ctx)->context);
  553. static void timer_push(long timeout, php_v8js_ctx *c)
  554. {
  555. // Create context for this timer
  556. php_v8js_timer_ctx *timer_ctx = (php_v8js_timer_ctx *)malloc(sizeof(php_v8js_timer_ctx));
  557. // Calculate the time point when the timeout is exceeded
  558. std::chrono::milliseconds duration(timeout);
  559. std::chrono::time_point<std::chrono::high_resolution_clock> from = std::chrono::high_resolution_clock::now();
  560. // Push the timer context
  561. timer_ctx->time_point = from + duration;
  562. timer_ctx->v8js_ctx = c;
  563. V8JSG(timer_stack).push(timer_ctx);
  564. }
  565. static void timer_pop()
  566. {
  567. if (V8JSG(timer_stack).size()) {
  568. // Free the timer context memory
  569. php_v8js_timer_ctx *timer_ctx = V8JSG(timer_stack).top();
  570. free(timer_ctx);
  571. // Remove the timer context from the stack
  572. V8JSG(timer_stack).pop();
  573. }
  574. }
  575. static void php_v8js_timer_thread()
  576. {
  577. while (!V8JSG(timer_stop)) {
  578. std::chrono::time_point<std::chrono::high_resolution_clock> now = std::chrono::high_resolution_clock::now();
  579. if (V8JSG(timer_stack).size()) {
  580. // Get the current timer context
  581. php_v8js_timer_ctx *timer_ctx = V8JSG(timer_stack).top();
  582. php_v8js_ctx *c = timer_ctx->v8js_ctx;
  583. if (now > timer_ctx->time_point) {
  584. // Forcefully terminate the current thread of V8 execution in the isolate
  585. v8::V8::TerminateExecution(c->isolate);
  586. // Remove this timer from the stack
  587. timer_pop();
  588. c->execution_terminated = true;
  589. }
  590. }
  591. // Sleep for 10ms
  592. std::chrono::milliseconds duration(10);
  593. std::this_thread::sleep_for(duration);
  594. }
  595. }
  596. /* {{{ proto mixed V8Js::executeString(string script [, string identifier [, int flags]])
  597. */
  598. static PHP_METHOD(V8Js, executeString)
  599. {
  600. char *str = NULL, *identifier = NULL;
  601. int str_len = 0, identifier_len = 0;
  602. long flags = V8JS_FLAG_NONE, timeout = 0;
  603. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|sll", &str, &str_len, &identifier, &identifier_len, &flags, &timeout) == FAILURE) {
  604. return;
  605. }
  606. V8JS_BEGIN_CTX(c, getThis())
  607. /* Catch JS exceptions */
  608. v8::TryCatch try_catch;
  609. v8::HandleScope handle_scope;
  610. /* Set script identifier */
  611. v8::Local<v8::String> sname = identifier_len ? V8JS_SYML(identifier, identifier_len) : V8JS_SYM("V8Js::executeString()");
  612. /* Compiles a string context independently. TODO: Add a php function which calls this and returns the result as resource which can be executed later. */
  613. v8::Local<v8::String> source = v8::String::New(str, str_len);
  614. v8::Local<v8::Script> script = v8::Script::New(source, sname);
  615. /* Compile errors? */
  616. if (script.IsEmpty()) {
  617. php_v8js_throw_exception(&try_catch TSRMLS_CC);
  618. return;
  619. }
  620. /* Set flags for runtime use */
  621. V8JS_GLOBAL_SET_FLAGS(flags);
  622. if (timeout > 0) {
  623. // If timer thread is not running then start it
  624. if (!V8JSG(timer_thread)) {
  625. // If not, start timer thread
  626. V8JSG(timer_thread) = new std::thread(php_v8js_timer_thread);
  627. }
  628. timer_push(timeout, c);
  629. }
  630. /* Execute script */
  631. c->in_execution++;
  632. v8::Local<v8::Value> result = script->Run();
  633. c->in_execution--;
  634. if (timeout > 0) {
  635. timer_pop();
  636. }
  637. if (c->execution_terminated) {
  638. // Execution has been terminated due to timeout
  639. zend_throw_exception(php_ce_v8js_exception, "Script timeout", 0 TSRMLS_CC);
  640. }
  641. if (!try_catch.CanContinue()) {
  642. // At this point we can't re-throw the exception
  643. return;
  644. }
  645. /* There was pending exception left from earlier executions -> throw to PHP */
  646. if (c->pending_exception) {
  647. zend_throw_exception_object(c->pending_exception TSRMLS_CC);
  648. c->pending_exception = NULL;
  649. }
  650. /* Handle runtime JS exceptions */
  651. if (try_catch.HasCaught()) {
  652. /* Pending exceptions are set only in outer caller, inner caller exceptions are always rethrown */
  653. if (c->in_execution < 1) {
  654. /* Report immediately if report_uncaught is true */
  655. if (c->report_uncaught) {
  656. php_v8js_throw_exception(&try_catch TSRMLS_CC);
  657. return;
  658. }
  659. /* Exception thrown from JS, preserve it for future execution */
  660. if (result.IsEmpty()) {
  661. MAKE_STD_ZVAL(c->pending_exception);
  662. php_v8js_create_exception(c->pending_exception, &try_catch TSRMLS_CC);
  663. }
  664. }
  665. /* Rethrow back to JS */
  666. try_catch.ReThrow();
  667. return;
  668. }
  669. /* Convert V8 value to PHP value */
  670. if (!result.IsEmpty()) {
  671. v8js_to_zval(result, return_value, flags TSRMLS_CC);
  672. }
  673. }
  674. /* }}} */
  675. /* {{{ proto mixed V8Js::getPendingException()
  676. */
  677. static PHP_METHOD(V8Js, getPendingException)
  678. {
  679. php_v8js_ctx *c;
  680. if (zend_parse_parameters_none() == FAILURE) {
  681. return;
  682. }
  683. c = (php_v8js_ctx *) zend_object_store_get_object(getThis() TSRMLS_CC);
  684. if (c->pending_exception) {
  685. RETURN_ZVAL(c->pending_exception, 1, 0);
  686. }
  687. }
  688. /* }}} */
  689. static void php_v8js_persistent_zval_ctor(zval **p) /* {{{ */
  690. {
  691. zval *orig_ptr = *p;
  692. *p = (zval *) malloc(sizeof(zval));
  693. **p = *orig_ptr;
  694. switch (Z_TYPE_P(*p)) {
  695. case IS_STRING:
  696. Z_STRVAL_P(*p) = (char *) zend_strndup(Z_STRVAL_P(*p), Z_STRLEN_P(*p));
  697. break;
  698. default:
  699. zend_bailout();
  700. }
  701. INIT_PZVAL(*p);
  702. }
  703. /* }}} */
  704. static void php_v8js_persistent_zval_dtor(zval **p) /* {{{ */
  705. {
  706. switch (Z_TYPE_P(*p)) {
  707. case IS_STRING:
  708. free(Z_STRVAL_P(*p));
  709. break;
  710. default:
  711. zend_bailout();
  712. }
  713. free(*p);
  714. }
  715. /* }}} */
  716. static int php_v8js_register_extension(char *name, uint name_len, char *source, uint source_len, zval *deps_arr, zend_bool auto_enable TSRMLS_DC) /* {{{ */
  717. {
  718. php_v8js_jsext *jsext = NULL;
  719. if (!V8JSG(extensions)) {
  720. V8JSG(extensions) = (HashTable *) malloc(sizeof(HashTable));
  721. zend_hash_init(V8JSG(extensions), 1, NULL, (dtor_func_t) php_v8js_jsext_dtor, 1);
  722. } else if (zend_hash_exists(V8JSG(extensions), name, name_len + 1)) {
  723. return FAILURE;
  724. }
  725. jsext = (php_v8js_jsext *) calloc(1, sizeof(php_v8js_jsext));
  726. if (deps_arr) {
  727. jsext->deps_count = zend_hash_num_elements(Z_ARRVAL_P(deps_arr));
  728. if (_php_v8js_create_ext_strarr(&jsext->deps, jsext->deps_count, Z_ARRVAL_P(deps_arr)) == FAILURE) {
  729. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid dependancy array passed");
  730. php_v8js_jsext_dtor(jsext);
  731. free(jsext);
  732. return FAILURE;
  733. }
  734. }
  735. jsext->auto_enable = auto_enable;
  736. jsext->name = zend_strndup(name, name_len);
  737. jsext->source = zend_strndup(source, source_len);
  738. if (jsext->deps) {
  739. jsext->deps_ht = (HashTable *) malloc(sizeof(HashTable));
  740. zend_hash_init(jsext->deps_ht, jsext->deps_count, NULL, (dtor_func_t) php_v8js_persistent_zval_dtor, 1);
  741. zend_hash_copy(jsext->deps_ht, Z_ARRVAL_P(deps_arr), (copy_ctor_func_t) php_v8js_persistent_zval_ctor, NULL, sizeof(zval *));
  742. }
  743. if (zend_hash_add(V8JSG(extensions), name, name_len + 1, jsext, sizeof(php_v8js_jsext), NULL) == FAILURE) {
  744. php_v8js_jsext_dtor(jsext);
  745. free(jsext);
  746. return FAILURE;
  747. }
  748. v8::Extension *extension = new v8::Extension(jsext->name, jsext->source, jsext->deps_count, jsext->deps);
  749. extension->set_auto_enable(auto_enable ? true : false);
  750. v8::RegisterExtension(extension);
  751. free(jsext);
  752. return SUCCESS;
  753. }
  754. /* }}} */
  755. /* {{{ proto bool V8Js::registerExtension(string ext_name, string script [, array deps [, bool auto_enable]])
  756. */
  757. static PHP_METHOD(V8Js, registerExtension)
  758. {
  759. char *ext_name, *script;
  760. zval *deps_arr = NULL;
  761. int ext_name_len, script_len;
  762. zend_bool auto_enable = 0;
  763. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|ab", &ext_name, &ext_name_len, &script, &script_len, &deps_arr, &auto_enable) == FAILURE) {
  764. return;
  765. }
  766. if (!ext_name_len) {
  767. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Extension name cannot be empty");
  768. } else if (!script_len) {
  769. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Script cannot be empty");
  770. } else if (php_v8js_register_extension(ext_name, ext_name_len, script, script_len, deps_arr, auto_enable TSRMLS_CC) == SUCCESS) {
  771. RETURN_TRUE;
  772. }
  773. RETURN_FALSE;
  774. }
  775. /* }}} */
  776. /* ## Static methods ## */
  777. /* {{{ proto array V8Js::getExtensions()
  778. */
  779. static PHP_METHOD(V8Js, getExtensions)
  780. {
  781. php_v8js_jsext *jsext;
  782. zval *ext, *deps_arr;
  783. HashPosition pos;
  784. ulong index;
  785. char *key;
  786. uint key_len;
  787. if (zend_parse_parameters_none() == FAILURE) {
  788. return;
  789. }
  790. array_init(return_value);
  791. if (V8JSG(extensions)) {
  792. zend_hash_internal_pointer_reset_ex(V8JSG(extensions), &pos);
  793. while (zend_hash_get_current_data_ex(V8JSG(extensions), (void **) &jsext, &pos) == SUCCESS) {
  794. if (zend_hash_get_current_key_ex(V8JSG(extensions), &key, &key_len, &index, 0, &pos) == HASH_KEY_IS_STRING) {
  795. MAKE_STD_ZVAL(ext)
  796. array_init(ext);
  797. add_assoc_bool_ex(ext, ZEND_STRS("auto_enable"), jsext->auto_enable);
  798. if (jsext->deps_ht) {
  799. MAKE_STD_ZVAL(deps_arr);
  800. array_init(deps_arr);
  801. zend_hash_copy(Z_ARRVAL_P(deps_arr), jsext->deps_ht, (copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval *));
  802. add_assoc_zval_ex(ext, ZEND_STRS("deps"), deps_arr);
  803. }
  804. add_assoc_zval_ex(return_value, key, key_len, ext);
  805. }
  806. zend_hash_move_forward_ex(V8JSG(extensions), &pos);
  807. }
  808. }
  809. }
  810. /* }}} */
  811. /* {{{ arginfo */
  812. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_construct, 0, 0, 0)
  813. ZEND_ARG_INFO(0, object_name)
  814. ZEND_ARG_INFO(0, variables)
  815. ZEND_ARG_INFO(0, extensions)
  816. ZEND_ARG_INFO(0, report_uncaught_exceptions)
  817. ZEND_END_ARG_INFO()
  818. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_executestring, 0, 0, 1)
  819. ZEND_ARG_INFO(0, script)
  820. ZEND_ARG_INFO(0, identifier)
  821. ZEND_ARG_INFO(0, flags)
  822. ZEND_ARG_INFO(0, timeout)
  823. ZEND_END_ARG_INFO()
  824. ZEND_BEGIN_ARG_INFO(arginfo_v8js_getpendingexception, 0)
  825. ZEND_END_ARG_INFO()
  826. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_registerextension, 0, 0, 2)
  827. ZEND_ARG_INFO(0, extension_name)
  828. ZEND_ARG_INFO(0, script)
  829. ZEND_ARG_INFO(0, dependencies)
  830. ZEND_ARG_INFO(0, auto_enable)
  831. ZEND_END_ARG_INFO()
  832. ZEND_BEGIN_ARG_INFO(arginfo_v8js_getextensions, 0)
  833. ZEND_END_ARG_INFO()
  834. ZEND_BEGIN_ARG_INFO(arginfo_v8jsexception_no_args, 0)
  835. ZEND_END_ARG_INFO()
  836. /* }}} */
  837. static const zend_function_entry v8js_methods[] = { /* {{{ */
  838. PHP_ME(V8Js, __construct, arginfo_v8js_construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
  839. PHP_ME(V8Js, executeString, arginfo_v8js_executestring, ZEND_ACC_PUBLIC)
  840. PHP_ME(V8Js, getPendingException, arginfo_v8js_getpendingexception, ZEND_ACC_PUBLIC)
  841. PHP_ME(V8Js, registerExtension, arginfo_v8js_registerextension, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
  842. PHP_ME(V8Js, getExtensions, arginfo_v8js_getextensions, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
  843. {NULL, NULL, NULL}
  844. };
  845. /* }}} */
  846. /* V8Js object handlers */
  847. static void php_v8js_write_property(zval *object, zval *member, zval *value ZEND_HASH_KEY_DC TSRMLS_DC) /* {{{ */
  848. {
  849. V8JS_BEGIN_CTX(c, object)
  850. v8::HandleScope handle_scope;
  851. /* Global PHP JS object */
  852. v8::Local<v8::Object> jsobj = V8JS_GLOBAL->Get(c->object_name)->ToObject();
  853. /* Write value to PHP JS object */
  854. jsobj->ForceSet(V8JS_SYML(Z_STRVAL_P(member), Z_STRLEN_P(member)), zval_to_v8js(value TSRMLS_CC), v8::ReadOnly);
  855. /* Write value to PHP object */
  856. std_object_handlers.write_property(object, member, value ZEND_HASH_KEY_CC TSRMLS_CC);
  857. }
  858. /* }}} */
  859. static void php_v8js_unset_property(zval *object, zval *member ZEND_HASH_KEY_DC TSRMLS_DC) /* {{{ */
  860. {
  861. V8JS_BEGIN_CTX(c, object)
  862. v8::HandleScope handle_scope;
  863. /* Global PHP JS object */
  864. v8::Local<v8::Object> jsobj = V8JS_GLOBAL->Get(c->object_name)->ToObject();
  865. /* Delete value from PHP JS object */
  866. jsobj->ForceDelete(V8JS_SYML(Z_STRVAL_P(member), Z_STRLEN_P(member)));
  867. /* Unset from PHP object */
  868. std_object_handlers.unset_property(object, member ZEND_HASH_KEY_CC TSRMLS_CC);
  869. }
  870. /* }}} */
  871. /* }}} V8Js */
  872. /* {{{ Class: V8JsException */
  873. static void php_v8js_create_exception(zval *return_value, v8::TryCatch *try_catch TSRMLS_DC) /* {{{ */
  874. {
  875. v8::String::Utf8Value exception(try_catch->Exception());
  876. const char *exception_string = ToCString(exception);
  877. v8::Handle<v8::Message> tc_message = try_catch->Message();
  878. const char *filename_string, *sourceline_string;
  879. char *message_string;
  880. int linenum, message_len;
  881. object_init_ex(return_value, php_ce_v8js_exception);
  882. #define PHPV8_EXPROP(type, name, value) \
  883. zend_update_property##type(php_ce_v8js_exception, return_value, #name, sizeof(#name) - 1, value TSRMLS_CC);
  884. if (tc_message.IsEmpty()) {
  885. message_len = spprintf(&message_string, 0, "%s", exception_string);
  886. }
  887. else
  888. {
  889. v8::String::Utf8Value filename(tc_message->GetScriptResourceName());
  890. filename_string = ToCString(filename);
  891. PHPV8_EXPROP(_string, JsFileName, filename_string);
  892. v8::String::Utf8Value sourceline(tc_message->GetSourceLine());
  893. sourceline_string = ToCString(sourceline);
  894. PHPV8_EXPROP(_string, JsSourceLine, sourceline_string);
  895. linenum = tc_message->GetLineNumber();
  896. PHPV8_EXPROP(_long, JsLineNumber, linenum);
  897. message_len = spprintf(&message_string, 0, "%s:%d: %s", filename_string, linenum, exception_string);
  898. v8::String::Utf8Value stacktrace(try_catch->StackTrace());
  899. if (stacktrace.length() > 0) {
  900. const char* stacktrace_string = ToCString(stacktrace);
  901. PHPV8_EXPROP(_string, JsTrace, stacktrace_string);
  902. }
  903. }
  904. PHPV8_EXPROP(_string, message, message_string);
  905. efree(message_string);
  906. }
  907. /* }}} */
  908. static void php_v8js_throw_exception(v8::TryCatch *try_catch TSRMLS_DC) /* {{{ */
  909. {
  910. v8::String::Utf8Value exception(try_catch->Exception());
  911. const char *exception_string = ToCString(exception);
  912. zval *zexception = NULL;
  913. if (try_catch->Message().IsEmpty()) {
  914. zend_throw_exception(php_ce_v8js_exception, (char *) exception_string, 0 TSRMLS_CC);
  915. } else {
  916. MAKE_STD_ZVAL(zexception);
  917. php_v8js_create_exception(zexception, try_catch TSRMLS_CC);
  918. zend_throw_exception_object(zexception TSRMLS_CC);
  919. }
  920. }
  921. /* }}} */
  922. #define V8JS_EXCEPTION_METHOD(property) \
  923. static PHP_METHOD(V8JsException, get##property) \
  924. { \
  925. zval *value; \
  926. \
  927. if (zend_parse_parameters_none() == FAILURE) { \
  928. return; \
  929. } \
  930. value = zend_read_property(php_ce_v8js_exception, getThis(), #property, sizeof(#property) - 1, 0 TSRMLS_CC); \
  931. *return_value = *value; \
  932. zval_copy_ctor(return_value); \
  933. INIT_PZVAL(return_value); \
  934. }
  935. /* {{{ proto string V8JsException::getJsFileName()
  936. */
  937. V8JS_EXCEPTION_METHOD(JsFileName);
  938. /* }}} */
  939. /* {{{ proto string V8JsException::getJsLineNumber()
  940. */
  941. V8JS_EXCEPTION_METHOD(JsLineNumber);
  942. /* }}} */
  943. /* {{{ proto string V8JsException::getJsSourceLine()
  944. */
  945. V8JS_EXCEPTION_METHOD(JsSourceLine);
  946. /* }}} */
  947. /* {{{ proto string V8JsException::getJsTrace()
  948. */
  949. V8JS_EXCEPTION_METHOD(JsTrace);
  950. /* }}} */
  951. static const zend_function_entry v8js_exception_methods[] = { /* {{{ */
  952. PHP_ME(V8JsException, getJsFileName, arginfo_v8jsexception_no_args, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
  953. PHP_ME(V8JsException, getJsLineNumber, arginfo_v8jsexception_no_args, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
  954. PHP_ME(V8JsException, getJsSourceLine, arginfo_v8jsexception_no_args, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
  955. PHP_ME(V8JsException, getJsTrace, arginfo_v8jsexception_no_args, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
  956. {NULL, NULL, NULL}
  957. };
  958. /* }}} */
  959. /* }}} V8JsException */
  960. /* {{{ PHP_MINIT_FUNCTION
  961. */
  962. static PHP_MINIT_FUNCTION(v8js)
  963. {
  964. zend_class_entry ce;
  965. /* V8Object Class */
  966. INIT_CLASS_ENTRY(ce, "V8Object", NULL);
  967. php_ce_v8_object = zend_register_internal_class(&ce TSRMLS_CC);
  968. php_ce_v8_object->ce_flags |= ZEND_ACC_FINAL;
  969. php_ce_v8_object->create_object = php_v8js_v8_new;
  970. /* V8Function Class */
  971. INIT_CLASS_ENTRY(ce, "V8Function", NULL);
  972. php_ce_v8_function = zend_register_internal_class(&ce TSRMLS_CC);
  973. php_ce_v8_function->ce_flags |= ZEND_ACC_FINAL;
  974. php_ce_v8_function->create_object = php_v8js_v8_new;
  975. /* V8<Object|Function> handlers */
  976. memcpy(&v8_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
  977. v8_object_handlers.clone_obj = NULL;
  978. v8_object_handlers.cast_object = NULL;
  979. v8_object_handlers.get_constructor = NULL;
  980. v8_object_handlers.get_property_ptr_ptr = NULL;
  981. // v8_object_handlers.has_property = php_v8js_v8_has_property; // Not implemented yet
  982. v8_object_handlers.read_property = php_v8js_v8_read_property;
  983. v8_object_handlers.write_property = php_v8js_v8_write_property;
  984. v8_object_handlers.unset_property = php_v8js_v8_unset_property;
  985. v8_object_handlers.get_properties = php_v8js_v8_get_properties;
  986. v8_object_handlers.get_method = php_v8js_v8_get_method;
  987. v8_object_handlers.call_method = php_v8js_v8_call_method;
  988. v8_object_handlers.get_debug_info = php_v8js_v8_get_debug_info;
  989. v8_object_handlers.get_closure = php_v8js_v8_get_closure;
  990. /* V8Js Class */
  991. INIT_CLASS_ENTRY(ce, "V8Js", v8js_methods);
  992. php_ce_v8js = zend_register_internal_class(&ce TSRMLS_CC);
  993. php_ce_v8js->create_object = php_v8js_new;
  994. /* V8Js handlers */
  995. memcpy(&v8js_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
  996. v8js_object_handlers.clone_obj = NULL;
  997. v8js_object_handlers.write_property = php_v8js_write_property;
  998. v8js_object_handlers.unset_property = php_v8js_unset_property;
  999. /* V8Js Class Constants */
  1000. zend_declare_class_constant_string(php_ce_v8js, ZEND_STRL("V8_VERSION"), PHP_V8_VERSION TSRMLS_CC);
  1001. zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("FLAG_NONE"), V8JS_FLAG_NONE TSRMLS_CC);
  1002. zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("FLAG_FORCE_ARRAY"), V8JS_FLAG_FORCE_ARRAY TSRMLS_CC);
  1003. /* V8JsException Class */
  1004. INIT_CLASS_ENTRY(ce, "V8JsException", v8js_exception_methods);
  1005. php_ce_v8js_exception = zend_register_internal_class_ex(&ce, zend_exception_get_default(TSRMLS_C), NULL TSRMLS_CC);
  1006. php_ce_v8js_exception->ce_flags |= ZEND_ACC_FINAL;
  1007. /* Add custom JS specific properties */
  1008. zend_declare_property_null(php_ce_v8js_exception, ZEND_STRL("JsFileName"), ZEND_ACC_PROTECTED TSRMLS_CC);
  1009. zend_declare_property_null(php_ce_v8js_exception, ZEND_STRL("JsLineNumber"), ZEND_ACC_PROTECTED TSRMLS_CC);
  1010. zend_declare_property_null(php_ce_v8js_exception, ZEND_STRL("JsSourceLine"), ZEND_ACC_PROTECTED TSRMLS_CC);
  1011. zend_declare_property_null(php_ce_v8js_exception, ZEND_STRL("JsTrace"), ZEND_ACC_PROTECTED TSRMLS_CC);
  1012. REGISTER_INI_ENTRIES();
  1013. return SUCCESS;
  1014. }
  1015. /* }}} */
  1016. static void php_v8js_force_v8_gc(void) /* {{{ */
  1017. {
  1018. #if V8JS_DEBUG
  1019. TSRMLS_FETCH();
  1020. fprintf(stderr, "############ Running V8 Idle notification: disposed/max_disposed %d/%d ############\n", V8JSG(disposed_contexts), V8JSG(max_disposed_contexts));
  1021. fflush(stderr);
  1022. #endif
  1023. while (!v8::V8::IdleNotification()) {
  1024. #if V8JS_DEBUG
  1025. fprintf(stderr, ".");
  1026. fflush(stderr);
  1027. #endif
  1028. }
  1029. #if V8JS_DEBUG
  1030. fprintf(stderr, "\n");
  1031. fflush(stderr);
  1032. #endif
  1033. }
  1034. /* }}} */
  1035. /* {{{ PHP_MSHUTDOWN_FUNCTION
  1036. */
  1037. static PHP_MSHUTDOWN_FUNCTION(v8js)
  1038. {
  1039. UNREGISTER_INI_ENTRIES();
  1040. v8::V8::Dispose();
  1041. if (V8JSG(extensions)) {
  1042. zend_hash_destroy(V8JSG(extensions));
  1043. free(V8JSG(extensions));
  1044. V8JSG(extensions) = NULL;
  1045. }
  1046. if (V8JSG(v8_flags)) {
  1047. free(V8JSG(v8_flags));
  1048. V8JSG(v8_flags) = NULL;
  1049. }
  1050. return SUCCESS;
  1051. }
  1052. /* }}} */
  1053. /* {{{ PHP_RSHUTDOWN_FUNCTION
  1054. */
  1055. static PHP_RSHUTDOWN_FUNCTION(v8js)
  1056. {
  1057. // If the timer thread is running then stop it
  1058. if (V8JSG(timer_thread)) {
  1059. V8JSG(timer_stop) = true;
  1060. V8JSG(timer_thread)->join();
  1061. }
  1062. #if V8JS_DEBUG
  1063. v8::HeapStatistics stats;
  1064. v8::V8::GetHeapStatistics(&stats);
  1065. float used = stats.used_heap_size() / 1024.0 / 1024.0;
  1066. float total = stats.total_heap_size() / 1024.0 / 1024.0;
  1067. fprintf(stderr, "### RSHUTDOWN ###\n");
  1068. fprintf(stderr, "############ Heap Used/Total %.2f/%.2f MB ############\n", used, total);
  1069. fflush(stderr);
  1070. #endif
  1071. /* Force V8 to do as much GC as possible */
  1072. if (V8JSG(max_disposed_contexts) && (V8JSG(disposed_contexts) > V8JSG(max_disposed_contexts))) {
  1073. php_v8js_force_v8_gc();
  1074. }
  1075. return SUCCESS;
  1076. }
  1077. /* }}} */
  1078. /* {{{ PHP_MINFO_FUNCTION
  1079. */
  1080. static PHP_MINFO_FUNCTION(v8js)
  1081. {
  1082. php_info_print_table_start();
  1083. php_info_print_table_header(2, "V8 Javascript Engine", "enabled");
  1084. php_info_print_table_header(2, "V8 Engine Compiled Version", PHP_V8_VERSION);
  1085. php_info_print_table_header(2, "V8 Engine Linked Version", v8::V8::GetVersion());
  1086. php_info_print_table_header(2, "Version", V8JS_VERSION);
  1087. php_info_print_table_end();
  1088. DISPLAY_INI_ENTRIES();
  1089. }
  1090. /* }}} */
  1091. /* {{{ PHP_GINIT_FUNCTION
  1092. */
  1093. static PHP_GINIT_FUNCTION(v8js)
  1094. {
  1095. v8js_globals->extensions = NULL;
  1096. v8js_globals->disposed_contexts = 0;
  1097. v8js_globals->v8_initialized = 0;
  1098. v8js_globals->v8_flags = NULL;
  1099. v8js_globals->timer_thread = NULL;
  1100. v8js_globals->timer_stop = false;
  1101. }
  1102. /* }}} */
  1103. /* {{{ v8js_functions[] */
  1104. static const zend_function_entry v8js_functions[] = {
  1105. {NULL, NULL, NULL}
  1106. };
  1107. /* }}} */
  1108. /* {{{ v8js_module_entry
  1109. */
  1110. zend_module_entry v8js_module_entry = {
  1111. STANDARD_MODULE_HEADER_EX,
  1112. NULL,
  1113. NULL,
  1114. "v8js",
  1115. v8js_functions,
  1116. PHP_MINIT(v8js),
  1117. PHP_MSHUTDOWN(v8js),
  1118. NULL,
  1119. PHP_RSHUTDOWN(v8js),
  1120. PHP_MINFO(v8js),
  1121. V8JS_VERSION,
  1122. PHP_MODULE_GLOBALS(v8js),
  1123. PHP_GINIT(v8js),
  1124. NULL,
  1125. NULL,
  1126. STANDARD_MODULE_PROPERTIES_EX
  1127. };
  1128. /* }}} */
  1129. /*
  1130. * Local variables:
  1131. * tab-width: 4
  1132. * c-basic-offset: 4
  1133. * End:
  1134. * vim600: noet sw=4 ts=4 fdm=marker
  1135. * vim<600: noet sw=4 ts=4
  1136. */