v8js.cc 45 KB

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