v8js.cc 41 KB

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