v8js.cc 41 KB

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