v8js.cc 42 KB

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