v8js.cc 41 KB

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