v8js.cc 40 KB

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