v8js.cc 42 KB

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