v8js.cc 43 KB

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