v8js.cc 42 KB

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