v8js.cc 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937
  1. /*
  2. +----------------------------------------------------------------------+
  3. | PHP Version 5 |
  4. +----------------------------------------------------------------------+
  5. | Copyright (c) 1997-2013 The PHP Group |
  6. +----------------------------------------------------------------------+
  7. | http://www.opensource.org/licenses/mit-license.php MIT License |
  8. +----------------------------------------------------------------------+
  9. | Author: Jani Taskinen <[email protected]> |
  10. | Author: Patrick Reilly <[email protected]> |
  11. +----------------------------------------------------------------------+
  12. */
  13. /* $Id$ */
  14. #define V8JS_DEBUG 0
  15. //#define PHP_V8_VERSION "0.1.4"
  16. #ifdef HAVE_CONFIG_H
  17. #include "config.h"
  18. #endif
  19. #include <v8-debug.h>
  20. #include "php_v8js_macros.h"
  21. extern "C" {
  22. #include "php_ini.h"
  23. #include "ext/standard/info.h"
  24. #include "ext/standard/php_string.h"
  25. #include "ext/standard/php_smart_str.h"
  26. #include "zend_exceptions.h"
  27. }
  28. /* Forward declarations */
  29. static void php_v8js_throw_script_exception(v8::TryCatch * TSRMLS_DC);
  30. static void php_v8js_create_script_exception(zval *, v8::TryCatch * TSRMLS_DC);
  31. ZEND_DECLARE_MODULE_GLOBALS(v8js)
  32. /* {{{ INI Settings */
  33. static ZEND_INI_MH(v8js_OnUpdateV8Flags) /* {{{ */
  34. {
  35. if (new_value) {
  36. if (V8JSG(v8_flags)) {
  37. free(V8JSG(v8_flags));
  38. V8JSG(v8_flags) = NULL;
  39. }
  40. if (!new_value[0]) {
  41. return FAILURE;
  42. }
  43. V8JSG(v8_flags) = zend_strndup(new_value, new_value_length);
  44. }
  45. return SUCCESS;
  46. }
  47. static ZEND_INI_MH(v8js_OnUpdateUseDate) /* {{{ */
  48. {
  49. bool value;
  50. if (new_value_length==2 && strcasecmp("on", new_value)==0) {
  51. value = (bool) 1;
  52. } else if (new_value_length==3 && strcasecmp("yes", new_value)==0) {
  53. value = (bool) 1;
  54. } else if (new_value_length==4 && strcasecmp("true", new_value)==0) {
  55. value = (bool) 1;
  56. } else {
  57. value = (bool) atoi(new_value);
  58. }
  59. V8JSG(use_date) = value;
  60. return SUCCESS;
  61. }
  62. /* }}} */
  63. ZEND_INI_BEGIN() /* {{{ */
  64. ZEND_INI_ENTRY("v8js.flags", NULL, ZEND_INI_ALL, v8js_OnUpdateV8Flags)
  65. ZEND_INI_ENTRY("v8js.use_date", "0", ZEND_INI_ALL, v8js_OnUpdateUseDate)
  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. #ifdef ENABLE_DEBUGGER_SUPPORT
  92. static php_v8js_ctx *v8js_debug_context;
  93. static int v8js_debug_auto_break_mode;
  94. #endif
  95. #ifdef COMPILE_DL_V8JS
  96. ZEND_GET_MODULE(v8js)
  97. #endif
  98. /* {{{ Class: V8 */
  99. #define V8JS_V8_INVOKE_FUNC_NAME "V8Js::V8::Invoke"
  100. /* V8 Object handlers */
  101. static int php_v8js_v8_has_property(zval *object, zval *member, int has_set_exists ZEND_HASH_KEY_DC TSRMLS_DC) /* {{{ */
  102. {
  103. /* param has_set_exists:
  104. * 0 (has) whether property exists and is not NULL - isset()
  105. * 1 (set) whether property exists and is true-ish - empty()
  106. * 2 (exists) whether property exists - property_exists()
  107. */
  108. int retval = false;
  109. php_v8js_object *obj = (php_v8js_object *) zend_object_store_get_object(object TSRMLS_CC);
  110. v8::Isolate *isolate = obj->isolate;
  111. v8::Locker locker(isolate);
  112. v8::Isolate::Scope isolate_scope(isolate);
  113. v8::HandleScope local_scope(isolate);
  114. v8::Local<v8::Context> temp_context = v8::Context::New(isolate);
  115. v8::Context::Scope temp_scope(temp_context);
  116. v8::Local<v8::Value> v8obj = v8::Local<v8::Value>::New(isolate, obj->v8obj);
  117. if (Z_TYPE_P(member) == IS_STRING && v8obj->IsObject() && !v8obj->IsFunction())
  118. {
  119. v8::Local<v8::Object> jsObj = v8obj->ToObject();
  120. v8::Local<v8::String> jsKey = V8JS_STRL(Z_STRVAL_P(member), Z_STRLEN_P(member));
  121. v8::Local<v8::Value> jsVal;
  122. /* Skip any prototype properties */
  123. if (jsObj->HasRealNamedProperty(jsKey) || jsObj->HasRealNamedCallbackProperty(jsKey)) {
  124. if (has_set_exists == 2) {
  125. /* property_exists(), that's enough! */
  126. retval = true;
  127. } else {
  128. /* We need to look at the value. */
  129. jsVal = jsObj->Get(jsKey);
  130. if (has_set_exists == 0 ) {
  131. /* isset(): We make 'undefined' equivalent to 'null' */
  132. retval = !( jsVal->IsNull() || jsVal->IsUndefined() );
  133. } else {
  134. /* empty() */
  135. retval = jsVal->BooleanValue();
  136. /* for PHP compatibility, [] should also be empty */
  137. if (jsVal->IsArray() && retval) {
  138. v8::Local<v8::Array> array = v8::Local<v8::Array>::Cast(jsVal);
  139. retval = (array->Length() != 0);
  140. }
  141. /* for PHP compatibility, '0' should also be empty */
  142. if (jsVal->IsString() && retval) {
  143. v8::Local<v8::String> str = jsVal->ToString();
  144. if (str->Length() == 1) {
  145. uint16_t c = 0;
  146. str->Write(&c, 0, 1);
  147. if (c == '0') {
  148. retval = false;
  149. }
  150. }
  151. }
  152. }
  153. }
  154. }
  155. }
  156. return retval;
  157. }
  158. /* }}} */
  159. static zval *php_v8js_v8_read_property(zval *object, zval *member, int type ZEND_HASH_KEY_DC TSRMLS_DC) /* {{{ */
  160. {
  161. zval *retval = NULL;
  162. php_v8js_object *obj = (php_v8js_object *) zend_object_store_get_object(object TSRMLS_CC);
  163. v8::Isolate *isolate = obj->isolate;
  164. v8::Locker locker(isolate);
  165. v8::Isolate::Scope isolate_scope(isolate);
  166. v8::HandleScope local_scope(isolate);
  167. v8::Local<v8::Context> temp_context = v8::Context::New(isolate);
  168. v8::Context::Scope temp_scope(temp_context);
  169. v8::Local<v8::Value> v8obj = v8::Local<v8::Value>::New(isolate, obj->v8obj);
  170. if (Z_TYPE_P(member) == IS_STRING && v8obj->IsObject() && !v8obj->IsFunction())
  171. {
  172. v8::Local<v8::Object> jsObj = v8obj->ToObject();
  173. v8::Local<v8::String> jsKey = V8JS_STRL(Z_STRVAL_P(member), Z_STRLEN_P(member));
  174. v8::Local<v8::Value> jsVal;
  175. /* Skip any prototype properties */
  176. if (jsObj->HasRealNamedProperty(jsKey) || jsObj->HasRealNamedCallbackProperty(jsKey)) {
  177. jsVal = jsObj->Get(jsKey);
  178. if (jsVal->IsObject()) {
  179. ALLOC_INIT_ZVAL(retval);
  180. Z_SET_REFCOUNT_P(retval, 0);
  181. } else {
  182. MAKE_STD_ZVAL(retval);
  183. }
  184. if (v8js_to_zval(jsVal, retval, obj->flags, isolate TSRMLS_CC) == SUCCESS) {
  185. return retval;
  186. }
  187. }
  188. }
  189. ALLOC_INIT_ZVAL(retval);
  190. return retval;
  191. }
  192. /* }}} */
  193. static void php_v8js_v8_write_property(zval *object, zval *member, zval *value ZEND_HASH_KEY_DC TSRMLS_DC) /* {{{ */
  194. {
  195. php_v8js_object *obj = (php_v8js_object *) zend_object_store_get_object(object TSRMLS_CC);
  196. v8::Isolate *isolate = obj->isolate;
  197. v8::Locker locker(isolate);
  198. v8::Isolate::Scope isolate_scope(isolate);
  199. v8::HandleScope local_scope(isolate);
  200. v8::Local<v8::Context> temp_context = v8::Context::New(isolate);
  201. v8::Context::Scope temp_scope(temp_context);
  202. v8::Local<v8::Value> v8obj = v8::Local<v8::Value>::New(isolate, obj->v8obj);
  203. if (v8obj->IsObject() && !v8obj->IsFunction()) {
  204. v8obj->ToObject()->ForceSet(V8JS_SYML(Z_STRVAL_P(member), Z_STRLEN_P(member)), zval_to_v8js(value, isolate TSRMLS_CC));
  205. }
  206. }
  207. /* }}} */
  208. static void php_v8js_v8_unset_property(zval *object, zval *member ZEND_HASH_KEY_DC TSRMLS_DC) /* {{{ */
  209. {
  210. php_v8js_object *obj = (php_v8js_object *) zend_object_store_get_object(object TSRMLS_CC);
  211. v8::Isolate *isolate = obj->isolate;
  212. v8::Locker locker(isolate);
  213. v8::Isolate::Scope isolate_scope(isolate);
  214. v8::HandleScope local_scope(isolate);
  215. v8::Local<v8::Context> temp_context = v8::Context::New(isolate);
  216. v8::Context::Scope temp_scope(temp_context);
  217. v8::Local<v8::Value> v8obj = v8::Local<v8::Value>::New(isolate, obj->v8obj);
  218. if (v8obj->IsObject() && !v8obj->IsFunction()) {
  219. v8obj->ToObject()->ForceDelete(V8JS_SYML(Z_STRVAL_P(member), Z_STRLEN_P(member)));
  220. }
  221. }
  222. /* }}} */
  223. int php_v8js_v8_get_properties_hash(v8::Handle<v8::Value> jsValue, HashTable *retval, int flags, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  224. {
  225. v8::Local<v8::Object> jsObj = jsValue->ToObject();
  226. if (!jsObj.IsEmpty()) {
  227. v8::Local<v8::Array> jsKeys = jsObj->GetPropertyNames();
  228. for (unsigned i = 0; i < jsKeys->Length(); i++)
  229. {
  230. v8::Local<v8::String> jsKey = jsKeys->Get(i)->ToString();
  231. /* Skip any prototype properties */
  232. if (!jsObj->HasOwnProperty(jsKey) && !jsObj->HasRealNamedProperty(jsKey) && !jsObj->HasRealNamedCallbackProperty(jsKey)) {
  233. continue;
  234. }
  235. v8::Local<v8::Value> jsVal = jsObj->Get(jsKey);
  236. v8::String::Utf8Value cstr(jsKey);
  237. const char *key = ToCString(cstr);
  238. zval *value = NULL;
  239. v8::Local<v8::Value> php_object;
  240. if (jsVal->IsObject()) {
  241. php_object = v8::Local<v8::Object>::Cast(jsVal)->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY));
  242. }
  243. if (!php_object.IsEmpty()) {
  244. /* This is a PHP object, passed to JS and back. */
  245. value = reinterpret_cast<zval *>(v8::External::Cast(*php_object)->Value());
  246. Z_ADDREF_P(value);
  247. }
  248. else {
  249. MAKE_STD_ZVAL(value);
  250. if (v8js_to_zval(jsVal, value, flags, isolate TSRMLS_CC) == FAILURE) {
  251. zval_ptr_dtor(&value);
  252. return FAILURE;
  253. }
  254. }
  255. if ((flags & V8JS_FLAG_FORCE_ARRAY) || jsValue->IsArray()) {
  256. zend_symtable_update(retval, key, strlen(key) + 1, (void *)&value, sizeof(zval *), NULL);
  257. } else {
  258. zend_hash_update(retval, key, strlen(key) + 1, (void *) &value, sizeof(zval *), NULL);
  259. }
  260. }
  261. return SUCCESS;
  262. }
  263. return FAILURE;
  264. }
  265. /* }}} */
  266. static HashTable *php_v8js_v8_get_properties(zval *object TSRMLS_DC) /* {{{ */
  267. {
  268. php_v8js_object *obj = (php_v8js_object *) zend_object_store_get_object(object TSRMLS_CC);
  269. HashTable *retval;
  270. if (obj->properties == NULL) {
  271. if (GC_G(gc_active)) {
  272. /* the garbage collector is running, don't create more zvals */
  273. return NULL;
  274. }
  275. if (obj->isolate == NULL) {
  276. /* Half-constructed object. Shouldn't happen, but be safe. */
  277. return NULL;
  278. }
  279. ALLOC_HASHTABLE(obj->properties);
  280. zend_hash_init(obj->properties, 0, NULL, ZVAL_PTR_DTOR, 0);
  281. } else {
  282. zend_hash_clean(obj->properties);
  283. }
  284. v8::Isolate *isolate = obj->isolate;
  285. v8::Locker locker(isolate);
  286. v8::Isolate::Scope isolate_scope(isolate);
  287. v8::HandleScope local_scope(isolate);
  288. v8::Local<v8::Context> temp_context = v8::Context::New(isolate);
  289. v8::Context::Scope temp_scope(temp_context);
  290. v8::Local<v8::Value> v8obj = v8::Local<v8::Value>::New(isolate, obj->v8obj);
  291. if (php_v8js_v8_get_properties_hash(v8obj, obj->properties, obj->flags, isolate TSRMLS_CC) == SUCCESS) {
  292. return obj->properties;
  293. }
  294. return NULL;
  295. }
  296. /* }}} */
  297. static HashTable *php_v8js_v8_get_debug_info(zval *object, int *is_temp TSRMLS_DC) /* {{{ */
  298. {
  299. *is_temp = 0;
  300. return php_v8js_v8_get_properties(object TSRMLS_CC);
  301. }
  302. /* }}} */
  303. static zend_function *php_v8js_v8_get_method(zval **object_ptr, char *method, int method_len ZEND_HASH_KEY_DC TSRMLS_DC) /* {{{ */
  304. {
  305. php_v8js_object *obj = (php_v8js_object *) zend_object_store_get_object(*object_ptr TSRMLS_CC);
  306. zend_function *f;
  307. v8::Isolate *isolate = obj->isolate;
  308. v8::Locker locker(isolate);
  309. v8::Isolate::Scope isolate_scope(isolate);
  310. v8::HandleScope local_scope(isolate);
  311. v8::Local<v8::Context> temp_context = v8::Context::New(isolate);
  312. v8::Context::Scope temp_scope(temp_context);
  313. v8::Local<v8::String> jsKey = V8JS_STRL(method, method_len);
  314. v8::Local<v8::Value> v8obj = v8::Local<v8::Value>::New(isolate, obj->v8obj);
  315. if (!obj->v8obj.IsEmpty() && v8obj->IsObject() && !v8obj->IsFunction()) {
  316. v8::Local<v8::Object> jsObj = v8obj->ToObject();
  317. if (jsObj->Has(jsKey) && jsObj->Get(jsKey)->IsFunction()) {
  318. f = (zend_function *) ecalloc(1, sizeof(*f));
  319. f->type = ZEND_OVERLOADED_FUNCTION_TEMPORARY;
  320. f->common.function_name = estrndup(method, method_len);
  321. return f;
  322. }
  323. }
  324. return NULL;
  325. }
  326. /* }}} */
  327. #if PHP_VERSION_ID >= 50400
  328. static int php_v8js_v8_call_method(const char *method, INTERNAL_FUNCTION_PARAMETERS) /* {{{ */
  329. #else
  330. static int php_v8js_v8_call_method(char *method, INTERNAL_FUNCTION_PARAMETERS) /* {{{ */
  331. #endif
  332. {
  333. zval *object = this_ptr, ***argv = NULL;
  334. int i = 0, argc = ZEND_NUM_ARGS();
  335. php_v8js_object *obj;
  336. obj = (php_v8js_object *) zend_object_store_get_object(object TSRMLS_CC);
  337. if (obj->v8obj.IsEmpty()) {
  338. zval_ptr_dtor(&object);
  339. return FAILURE;
  340. }
  341. if (argc > 0) {
  342. argv = (zval***)safe_emalloc(sizeof(zval**), argc, 0);
  343. zend_get_parameters_array_ex(argc, argv);
  344. }
  345. v8::Isolate *isolate = obj->isolate;
  346. v8::Locker locker(isolate);
  347. v8::Isolate::Scope isolate_scope(isolate);
  348. v8::HandleScope local_scope(isolate);
  349. v8::Local<v8::Context> temp_context = v8::Context::New(isolate);
  350. v8::Context::Scope temp_scope(temp_context);
  351. v8::Local<v8::String> method_name = V8JS_SYML(method, strlen(method));
  352. v8::Local<v8::Object> v8obj = v8::Local<v8::Value>::New(isolate, obj->v8obj)->ToObject();
  353. v8::Local<v8::Function> cb;
  354. if (method_name->Equals(V8JS_SYM(V8JS_V8_INVOKE_FUNC_NAME))) {
  355. cb = v8::Local<v8::Function>::Cast(v8obj);
  356. } else {
  357. cb = v8::Local<v8::Function>::Cast(v8obj->Get(method_name));
  358. }
  359. v8::Local<v8::Value> jsArgv[argc];
  360. v8::Local<v8::Value> js_retval;
  361. for (i = 0; i < argc; i++) {
  362. jsArgv[i] = v8::Local<v8::Value>::New(isolate, zval_to_v8js(*argv[i], isolate TSRMLS_CC));
  363. }
  364. js_retval = cb->Call(V8JS_GLOBAL(isolate), argc, jsArgv);
  365. zval_ptr_dtor(&object);
  366. if (argc > 0) {
  367. efree(argv);
  368. }
  369. if (return_value_used) {
  370. return v8js_to_zval(js_retval, return_value, obj->flags, isolate TSRMLS_CC);
  371. }
  372. return SUCCESS;
  373. }
  374. /* }}} */
  375. static int php_v8js_v8_get_closure(zval *object, zend_class_entry **ce_ptr, zend_function **fptr_ptr, zval **zobj_ptr TSRMLS_DC) /* {{{ */
  376. {
  377. zend_function *invoke;
  378. php_v8js_object *obj = (php_v8js_object *) zend_object_store_get_object(object TSRMLS_CC);
  379. v8::Isolate *isolate = obj->isolate;
  380. v8::Locker locker(isolate);
  381. v8::Isolate::Scope isolate_scope(isolate);
  382. v8::HandleScope local_scope(isolate);
  383. v8::Local<v8::Context> temp_context = v8::Context::New(isolate);
  384. v8::Context::Scope temp_scope(temp_context);
  385. v8::Local<v8::Value> v8obj = v8::Local<v8::Value>::New(isolate, obj->v8obj);
  386. if (!v8obj->IsFunction()) {
  387. return FAILURE;
  388. }
  389. invoke = (zend_function *) ecalloc(1, sizeof(*invoke));
  390. invoke->type = ZEND_OVERLOADED_FUNCTION_TEMPORARY;
  391. invoke->common.function_name = estrndup(V8JS_V8_INVOKE_FUNC_NAME, sizeof(V8JS_V8_INVOKE_FUNC_NAME) - 1);
  392. *fptr_ptr = invoke;
  393. if (zobj_ptr) {
  394. *zobj_ptr = object;
  395. }
  396. *ce_ptr = NULL;
  397. return SUCCESS;
  398. }
  399. /* }}} */
  400. static void php_v8js_v8_free_storage(void *object, zend_object_handle handle TSRMLS_DC) /* {{{ */
  401. {
  402. php_v8js_object *c = (php_v8js_object *) object;
  403. if (c->properties) {
  404. zend_hash_destroy(c->properties);
  405. FREE_HASHTABLE(c->properties);
  406. c->properties = NULL;
  407. }
  408. zend_object_std_dtor(&c->std TSRMLS_CC);
  409. c->v8obj.Reset();
  410. efree(object);
  411. }
  412. /* }}} */
  413. static zend_object_value php_v8js_v8_new(zend_class_entry *ce TSRMLS_DC) /* {{{ */
  414. {
  415. zend_object_value retval;
  416. php_v8js_object *c;
  417. c = (php_v8js_object *) ecalloc(1, sizeof(*c));
  418. zend_object_std_init(&c->std, ce TSRMLS_CC);
  419. new(&c->v8obj) v8::Persistent<v8::Value>();
  420. retval.handle = zend_objects_store_put(c, NULL, (zend_objects_free_object_storage_t) php_v8js_v8_free_storage, NULL TSRMLS_CC);
  421. retval.handlers = &v8_object_handlers;
  422. return retval;
  423. }
  424. /* }}} */
  425. /* NOTE: We could also override v8_object_handlers.get_constructor to throw
  426. * an exception when invoked, but doing so causes the half-constructed object
  427. * to leak -- this seems to be a PHP bug. So we'll define magic __construct
  428. * methods instead. */
  429. /* {{{ proto V8Object::__construct()
  430. */
  431. PHP_METHOD(V8Object,__construct)
  432. {
  433. zend_throw_exception(php_ce_v8js_script_exception,
  434. "Can't directly construct V8 objects!", 0 TSRMLS_CC);
  435. RETURN_FALSE;
  436. }
  437. /* }}} */
  438. /* {{{ proto V8Function::__construct()
  439. */
  440. PHP_METHOD(V8Function,__construct)
  441. {
  442. zend_throw_exception(php_ce_v8js_script_exception,
  443. "Can't directly construct V8 objects!", 0 TSRMLS_CC);
  444. RETURN_FALSE;
  445. }
  446. /* }}} */
  447. void php_v8js_create_v8(zval *res, v8::Handle<v8::Value> value, int flags, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  448. {
  449. php_v8js_object *c;
  450. object_init_ex(res, value->IsFunction() ? php_ce_v8_function : php_ce_v8_object);
  451. c = (php_v8js_object *) zend_object_store_get_object(res TSRMLS_CC);
  452. c->v8obj.Reset(isolate, value);
  453. c->flags = flags;
  454. c->isolate = isolate;
  455. c->properties = NULL;
  456. }
  457. /* }}} */
  458. /* }}} V8 */
  459. /* {{{ Class: V8Js */
  460. static void php_v8js_free_storage(void *object TSRMLS_DC) /* {{{ */
  461. {
  462. php_v8js_ctx *c = (php_v8js_ctx *) object;
  463. zend_object_std_dtor(&c->std TSRMLS_CC);
  464. if (c->pending_exception) {
  465. zval_ptr_dtor(&c->pending_exception);
  466. }
  467. if (c->module_loader) {
  468. zval_ptr_dtor(&c->module_loader);
  469. }
  470. /* Delete PHP global object from JavaScript */
  471. if (!c->context.IsEmpty()) {
  472. v8::Locker locker(c->isolate);
  473. v8::Isolate::Scope isolate_scope(c->isolate);
  474. v8::HandleScope handle_scope(c->isolate);
  475. v8::Local<v8::Context> v8_context = v8::Local<v8::Context>::New(c->isolate, c->context);
  476. v8::Context::Scope context_scope(v8_context);
  477. v8::Local<v8::String> object_name_js = v8::Local<v8::String>::New(c->isolate, c->object_name);
  478. V8JS_GLOBAL(c->isolate)->Delete(object_name_js);
  479. }
  480. c->object_name.Reset();
  481. c->object_name.~Persistent();
  482. c->global_template.Reset();
  483. c->global_template.~Persistent();
  484. /* Clear persistent handles in template cache */
  485. for (std::map<const char *,v8js_tmpl_t>::iterator it = c->template_cache.begin();
  486. it != c->template_cache.end(); ++it) {
  487. it->second.Reset();
  488. }
  489. c->template_cache.~map();
  490. /* Clear contexts */
  491. for (std::vector<php_v8js_accessor_ctx*>::iterator it = c->accessor_list.begin();
  492. it != c->accessor_list.end(); ++it) {
  493. php_v8js_accessor_ctx_dtor(*it TSRMLS_CC);
  494. }
  495. c->accessor_list.~vector();
  496. /* Clear global object, dispose context */
  497. if (!c->context.IsEmpty()) {
  498. c->context.Reset();
  499. }
  500. c->context.~Persistent();
  501. /* Force garbage collection on our isolate, this is needed that V8 triggers
  502. * our MakeWeak callbacks. Without these we won't remove our references
  503. * on the PHP objects leading to memory leaks in PHP context.
  504. */
  505. {
  506. v8::Locker locker(c->isolate);
  507. v8::Isolate::Scope isolate_scope(c->isolate);
  508. while(!v8::V8::IdleNotification()) {};
  509. }
  510. /* Dispose yet undisposed weak refs */
  511. for (std::map<zval *, v8js_persistent_obj_t>::iterator it = c->weak_objects.begin();
  512. it != c->weak_objects.end(); ++it) {
  513. zval *value = it->first;
  514. zval_ptr_dtor(&value);
  515. c->isolate->AdjustAmountOfExternalAllocatedMemory(-1024);
  516. it->second.Reset();
  517. }
  518. c->weak_objects.~map();
  519. for (std::map<v8js_tmpl_t *, v8js_persistent_obj_t>::iterator it = c->weak_closures.begin();
  520. it != c->weak_closures.end(); ++it) {
  521. v8js_tmpl_t *persist_tpl_ = it->first;
  522. persist_tpl_->Reset();
  523. delete persist_tpl_;
  524. it->second.Reset();
  525. }
  526. c->weak_closures.~map();
  527. if(c->tz != NULL) {
  528. free(c->tz);
  529. }
  530. c->modules_stack.~vector();
  531. c->modules_base.~vector();
  532. efree(object);
  533. }
  534. /* }}} */
  535. static zend_object_value php_v8js_new(zend_class_entry *ce TSRMLS_DC) /* {{{ */
  536. {
  537. zend_object_value retval;
  538. php_v8js_ctx *c;
  539. c = (php_v8js_ctx *) ecalloc(1, sizeof(*c));
  540. zend_object_std_init(&c->std, ce TSRMLS_CC);
  541. TSRMLS_SET_CTX(c->zts_ctx);
  542. #if PHP_VERSION_ID >= 50400
  543. object_properties_init(&c->std, ce);
  544. #else
  545. zval *tmp;
  546. zend_hash_copy(c->std.properties, &ce->default_properties,
  547. (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *));
  548. #endif
  549. new(&c->object_name) v8::Persistent<v8::String>();
  550. new(&c->context) v8::Persistent<v8::Context>();
  551. new(&c->global_template) v8::Persistent<v8::FunctionTemplate>();
  552. new(&c->modules_stack) std::vector<char*>();
  553. new(&c->modules_base) std::vector<char*>();
  554. new(&c->template_cache) std::map<const char *,v8js_tmpl_t>();
  555. new(&c->accessor_list) std::vector<php_v8js_accessor_ctx *>();
  556. new(&c->weak_closures) std::map<v8js_tmpl_t *, v8js_persistent_obj_t>();
  557. new(&c->weak_objects) std::map<zval *, v8js_persistent_obj_t>();
  558. retval.handle = zend_objects_store_put(c, NULL, (zend_objects_free_object_storage_t) php_v8js_free_storage, NULL TSRMLS_CC);
  559. retval.handlers = &v8js_object_handlers;
  560. return retval;
  561. }
  562. /* }}} */
  563. static void _php_v8js_free_ext_strarr(const char **arr, int count) /* {{{ */
  564. {
  565. int i;
  566. if (arr) {
  567. for (i = 0; i < count; i++) {
  568. if (arr[i]) {
  569. free((void *) arr[i]);
  570. }
  571. }
  572. free(arr);
  573. }
  574. }
  575. /* }}} */
  576. static void php_v8js_jsext_dtor(php_v8js_jsext *jsext) /* {{{ */
  577. {
  578. if (jsext->deps_ht) {
  579. zend_hash_destroy(jsext->deps_ht);
  580. free(jsext->deps_ht);
  581. }
  582. if (jsext->deps) {
  583. _php_v8js_free_ext_strarr(jsext->deps, jsext->deps_count);
  584. }
  585. free(jsext->name);
  586. free(jsext->source);
  587. }
  588. /* }}} */
  589. static int _php_v8js_create_ext_strarr(const char ***retval, int count, HashTable *ht) /* {{{ */
  590. {
  591. const char **exts = NULL;
  592. HashPosition pos;
  593. zval **tmp;
  594. int i = 0;
  595. exts = (const char **) calloc(1, count * sizeof(char *));
  596. zend_hash_internal_pointer_reset_ex(ht, &pos);
  597. while (zend_hash_get_current_data_ex(ht, (void **) &tmp, &pos) == SUCCESS) {
  598. if (Z_TYPE_PP(tmp) == IS_STRING) {
  599. exts[i++] = zend_strndup(Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp));
  600. } else {
  601. _php_v8js_free_ext_strarr(exts, i);
  602. return FAILURE;
  603. }
  604. zend_hash_move_forward_ex(ht, &pos);
  605. }
  606. *retval = exts;
  607. return SUCCESS;
  608. }
  609. /* }}} */
  610. static void php_v8js_fatal_error_handler(const char *location, const char *message) /* {{{ */
  611. {
  612. if (location) {
  613. zend_error(E_ERROR, "%s %s", location, message);
  614. } else {
  615. zend_error(E_ERROR, "%s", message);
  616. }
  617. }
  618. /* }}} */
  619. #ifdef ENABLE_DEBUGGER_SUPPORT
  620. static void DispatchDebugMessages() { /* {{{ */
  621. if(v8js_debug_context == NULL) {
  622. return;
  623. }
  624. v8::Isolate* isolate = v8js_debug_context->isolate;
  625. v8::Isolate::Scope isolate_scope(isolate);
  626. v8::HandleScope handle_scope(isolate);
  627. v8::Local<v8::Context> context =
  628. v8::Local<v8::Context>::New(isolate, v8js_debug_context->context);
  629. v8::Context::Scope scope(context);
  630. v8::Debug::ProcessDebugMessages();
  631. }
  632. /* }}} */
  633. #endif /* ENABLE_DEBUGGER_SUPPORT */
  634. static void php_v8js_init(TSRMLS_D) /* {{{ */
  635. {
  636. /* Run only once */
  637. if (V8JSG(v8_initialized)) {
  638. return;
  639. }
  640. /* Set V8 command line flags (must be done before V8::Initialize()!) */
  641. if (V8JSG(v8_flags)) {
  642. v8::V8::SetFlagsFromString(V8JSG(v8_flags), strlen(V8JSG(v8_flags)));
  643. }
  644. /* Initialize V8 */
  645. v8::V8::Initialize();
  646. /* Run only once */
  647. V8JSG(v8_initialized) = 1;
  648. }
  649. /* }}} */
  650. /* {{{ proto void V8Js::__construct([string object_name [, array variables [, array extensions [, bool report_uncaught_exceptions]]])
  651. __construct for V8Js */
  652. static PHP_METHOD(V8Js, __construct)
  653. {
  654. char *object_name = NULL, *class_name = NULL;
  655. int object_name_len = 0, free = 0;
  656. zend_uint class_name_len = 0;
  657. zend_bool report_uncaught = 1;
  658. zval *vars_arr = NULL, *exts_arr = NULL;
  659. const char **exts = NULL;
  660. int exts_count = 0;
  661. php_v8js_ctx *c = (php_v8js_ctx *) zend_object_store_get_object(getThis() TSRMLS_CC);
  662. if (!c->context.IsEmpty()) {
  663. /* called __construct() twice, bail out */
  664. return;
  665. }
  666. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|saab", &object_name, &object_name_len, &vars_arr, &exts_arr, &report_uncaught) == FAILURE) {
  667. return;
  668. }
  669. /* Initialize V8 */
  670. php_v8js_init(TSRMLS_C);
  671. /* Throw PHP exception if uncaught exceptions exist */
  672. c->report_uncaught = report_uncaught;
  673. c->pending_exception = NULL;
  674. c->in_execution = 0;
  675. c->isolate = v8::Isolate::New();
  676. #if PHP_V8_API_VERSION <= 3023008
  677. /* Until V8 3.23.8 Isolate could only take one external pointer. */
  678. c->isolate->SetData(c);
  679. #else
  680. c->isolate->SetData(0, c);
  681. #endif
  682. c->time_limit_hit = false;
  683. c->memory_limit_hit = false;
  684. c->module_loader = NULL;
  685. /* Include extensions used by this context */
  686. /* Note: Extensions registered with auto_enable do not need to be added separately like this. */
  687. if (exts_arr)
  688. {
  689. exts_count = zend_hash_num_elements(Z_ARRVAL_P(exts_arr));
  690. if (_php_v8js_create_ext_strarr(&exts, exts_count, Z_ARRVAL_P(exts_arr)) == FAILURE) {
  691. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid extensions array passed");
  692. return;
  693. }
  694. }
  695. /* Declare configuration for extensions */
  696. v8::ExtensionConfiguration extension_conf(exts_count, exts);
  697. // Isolate execution
  698. v8::Isolate *isolate = c->isolate;
  699. v8::Locker locker(isolate);
  700. v8::Isolate::Scope isolate_scope(isolate);
  701. /* Handle scope */
  702. v8::HandleScope handle_scope(isolate);
  703. /* Redirect fatal errors to PHP error handler */
  704. // This needs to be done within the context isolate
  705. v8::V8::SetFatalErrorHandler(php_v8js_fatal_error_handler);
  706. /* Create global template for global object */
  707. // Now we are using multiple isolates this needs to be created for every context
  708. v8::Local<v8::FunctionTemplate> tpl = V8JS_NEW(v8::FunctionTemplate, c->isolate, 0);
  709. tpl->SetClassName(V8JS_SYM("V8Js"));
  710. c->global_template.Reset(isolate, tpl);
  711. /* Register builtin methods */
  712. php_v8js_register_methods(tpl->InstanceTemplate(), c);
  713. /* Create context */
  714. v8::Local<v8::Context> context = v8::Context::New(isolate, &extension_conf, tpl->InstanceTemplate());
  715. context->SetAlignedPointerInEmbedderData(1, c);
  716. c->context.Reset(isolate, context);
  717. if (exts) {
  718. _php_v8js_free_ext_strarr(exts, exts_count);
  719. }
  720. /* If extensions have errors, context will be empty. (NOTE: This is V8 stuff, they expect the passed sources to compile :) */
  721. if (c->context.IsEmpty()) {
  722. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to create V8 context. Check that registered extensions do not have errors.");
  723. ZVAL_NULL(getThis());
  724. return;
  725. }
  726. /* Enter context */
  727. v8::Context::Scope context_scope(context);
  728. /* Create the PHP container object's function template */
  729. v8::Local<v8::FunctionTemplate> php_obj_t = V8JS_NEW(v8::FunctionTemplate, isolate, 0);
  730. /* Set class name for PHP object */
  731. #if PHP_VERSION_ID >= 50400
  732. free = !zend_get_object_classname(getThis(), const_cast<const char**>(&class_name), &class_name_len TSRMLS_CC);
  733. #else
  734. free = !zend_get_object_classname(getThis(), &class_name, &class_name_len TSRMLS_CC);
  735. #endif
  736. php_obj_t->SetClassName(V8JS_SYML(class_name, class_name_len));
  737. if (free) {
  738. efree(class_name);
  739. }
  740. /* Register Get accessor for passed variables */
  741. if (vars_arr && zend_hash_num_elements(Z_ARRVAL_P(vars_arr)) > 0) {
  742. php_v8js_register_accessors(&c->accessor_list, php_obj_t, vars_arr, isolate TSRMLS_CC);
  743. }
  744. /* Set name for the PHP JS object */
  745. v8::Local<v8::String> object_name_js = (object_name_len) ? V8JS_SYML(object_name, object_name_len) : V8JS_SYM("PHP");
  746. c->object_name.Reset(isolate, object_name_js);
  747. /* Add the PHP object into global object */
  748. v8::Local<v8::Object> php_obj = php_obj_t->InstanceTemplate()->NewInstance();
  749. V8JS_GLOBAL(isolate)->Set(object_name_js, php_obj, v8::ReadOnly);
  750. /* Export public property values */
  751. HashTable *properties = zend_std_get_properties(getThis() TSRMLS_CC);
  752. HashPosition pos;
  753. zval **value;
  754. ulong index;
  755. char *member;
  756. uint member_len;
  757. for(zend_hash_internal_pointer_reset_ex(properties, &pos);
  758. zend_hash_get_current_data_ex(properties, (void **) &value, &pos) == SUCCESS;
  759. zend_hash_move_forward_ex(properties, &pos)) {
  760. if(zend_hash_get_current_key_ex(properties, &member, &member_len, &index, 0, &pos) != HASH_KEY_IS_STRING) {
  761. continue;
  762. }
  763. zval zmember;
  764. INIT_ZVAL(zmember);
  765. ZVAL_STRING(&zmember, member, 0);
  766. zend_property_info *property_info = zend_get_property_info(c->std.ce, &zmember, 1 TSRMLS_CC);
  767. if(property_info && property_info->flags & ZEND_ACC_PUBLIC) {
  768. /* Write value to PHP JS object */
  769. php_obj->ForceSet(V8JS_SYML(member, member_len - 1), zval_to_v8js(*value, isolate TSRMLS_CC), v8::ReadOnly);
  770. }
  771. }
  772. }
  773. /* }}} */
  774. #define V8JS_BEGIN_CTX(ctx, object) \
  775. php_v8js_ctx *(ctx); \
  776. \
  777. if (!V8JSG(v8_initialized)) { \
  778. zend_error(E_ERROR, "V8 not initialized"); \
  779. return; \
  780. } \
  781. \
  782. (ctx) = (php_v8js_ctx *) zend_object_store_get_object(object TSRMLS_CC); \
  783. v8::Isolate *isolate = (ctx)->isolate; \
  784. v8::Locker locker(isolate); \
  785. v8::Isolate::Scope isolate_scope(isolate); \
  786. v8::HandleScope handle_scope(isolate); \
  787. v8::Local<v8::Context> v8_context = v8::Local<v8::Context>::New(isolate, (ctx)->context); \
  788. v8::Context::Scope context_scope(v8_context);
  789. static void php_v8js_timer_push(long time_limit, long memory_limit, php_v8js_ctx *c TSRMLS_DC)
  790. {
  791. V8JSG(timer_mutex).lock();
  792. // Create context for this timer
  793. php_v8js_timer_ctx *timer_ctx = (php_v8js_timer_ctx *)emalloc(sizeof(php_v8js_timer_ctx));
  794. // Calculate the time point when the time limit is exceeded
  795. std::chrono::milliseconds duration(time_limit);
  796. std::chrono::time_point<std::chrono::high_resolution_clock> from = std::chrono::high_resolution_clock::now();
  797. // Push the timer context
  798. timer_ctx->time_limit = time_limit;
  799. timer_ctx->memory_limit = memory_limit;
  800. timer_ctx->time_point = from + duration;
  801. timer_ctx->v8js_ctx = c;
  802. timer_ctx->killed = false;
  803. V8JSG(timer_stack).push(timer_ctx);
  804. V8JSG(timer_mutex).unlock();
  805. }
  806. static void php_v8js_timer_pop(TSRMLS_D)
  807. {
  808. V8JSG(timer_mutex).lock();
  809. if (V8JSG(timer_stack).size()) {
  810. php_v8js_timer_ctx *timer_ctx = V8JSG(timer_stack).top();
  811. // Remove the timer context from the stack
  812. V8JSG(timer_stack).pop();
  813. // Free the timer context memory
  814. efree(timer_ctx);
  815. }
  816. V8JSG(timer_mutex).unlock();
  817. }
  818. static void php_v8js_terminate_execution(php_v8js_ctx *c TSRMLS_DC)
  819. {
  820. // Forcefully terminate the current thread of V8 execution in the isolate
  821. v8::V8::TerminateExecution(c->isolate);
  822. // This timer will be removed from stack by the parent thread.
  823. }
  824. static void php_v8js_timer_thread(TSRMLS_D)
  825. {
  826. while (!V8JSG(timer_stop)) {
  827. std::chrono::time_point<std::chrono::high_resolution_clock> now = std::chrono::high_resolution_clock::now();
  828. v8::HeapStatistics hs;
  829. if (V8JSG(timer_stack).size()) {
  830. // Get the current timer context
  831. php_v8js_timer_ctx *timer_ctx = V8JSG(timer_stack).top();
  832. php_v8js_ctx *c = timer_ctx->v8js_ctx;
  833. // Get memory usage statistics for the isolate
  834. c->isolate->GetHeapStatistics(&hs);
  835. if (timer_ctx->time_limit > 0 && now > timer_ctx->time_point &&
  836. !timer_ctx->killed) {
  837. timer_ctx->killed = true;
  838. php_v8js_terminate_execution(c TSRMLS_CC);
  839. V8JSG(timer_mutex).lock();
  840. c->time_limit_hit = true;
  841. V8JSG(timer_mutex).unlock();
  842. }
  843. if (timer_ctx->memory_limit > 0 && hs.used_heap_size() > timer_ctx->memory_limit &&
  844. !timer_ctx->killed) {
  845. timer_ctx->killed = true;
  846. php_v8js_terminate_execution(c TSRMLS_CC);
  847. V8JSG(timer_mutex).lock();
  848. c->memory_limit_hit = true;
  849. V8JSG(timer_mutex).unlock();
  850. }
  851. }
  852. // Sleep for 10ms
  853. std::chrono::milliseconds duration(10);
  854. std::this_thread::sleep_for(duration);
  855. }
  856. }
  857. /* {{{ proto mixed V8Js::executeString(string script [, string identifier [, int flags]])
  858. */
  859. static PHP_METHOD(V8Js, executeString)
  860. {
  861. char *str = NULL, *identifier = NULL, *tz = NULL;
  862. int str_len = 0, identifier_len = 0;
  863. long flags = V8JS_FLAG_NONE, time_limit = 0, memory_limit = 0;
  864. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|slll", &str, &str_len, &identifier, &identifier_len, &flags, &time_limit, &memory_limit) == FAILURE) {
  865. return;
  866. }
  867. V8JS_BEGIN_CTX(c, getThis())
  868. V8JSG(timer_mutex).lock();
  869. c->time_limit_hit = false;
  870. c->memory_limit_hit = false;
  871. V8JSG(timer_mutex).unlock();
  872. /* Catch JS exceptions */
  873. v8::TryCatch try_catch;
  874. /* Set script identifier */
  875. v8::Local<v8::String> sname = identifier_len ? V8JS_SYML(identifier, identifier_len) : V8JS_SYM("V8Js::executeString()");
  876. /* Compiles a string context independently. TODO: Add a php function which calls this and returns the result as resource which can be executed later. */
  877. v8::Local<v8::String> source = V8JS_STRL(str, str_len);
  878. v8::Local<v8::Script> script = v8::Script::Compile(source, sname);
  879. /* Compile errors? */
  880. if (script.IsEmpty()) {
  881. php_v8js_throw_script_exception(&try_catch TSRMLS_CC);
  882. return;
  883. }
  884. /* Set flags for runtime use */
  885. V8JS_GLOBAL_SET_FLAGS(isolate, flags);
  886. /* Check if timezone has been changed and notify V8 */
  887. tz = getenv("TZ");
  888. if (tz != NULL) {
  889. if (c->tz == NULL) {
  890. c->tz = strdup(tz);
  891. }
  892. else if (strcmp(c->tz, tz) != 0) {
  893. #if PHP_V8_API_VERSION <= 3023012
  894. v8::Date::DateTimeConfigurationChangeNotification();
  895. #else
  896. v8::Date::DateTimeConfigurationChangeNotification(c->isolate);
  897. #endif
  898. free(c->tz);
  899. c->tz = strdup(tz);
  900. }
  901. }
  902. if (time_limit > 0 || memory_limit > 0) {
  903. // If timer thread is not running then start it
  904. if (!V8JSG(timer_thread)) {
  905. // If not, start timer thread
  906. V8JSG(timer_thread) = new std::thread(php_v8js_timer_thread TSRMLS_CC);
  907. }
  908. php_v8js_timer_push(time_limit, memory_limit, c TSRMLS_CC);
  909. }
  910. #ifdef ENABLE_DEBUGGER_SUPPORT
  911. if(c == v8js_debug_context && v8js_debug_auto_break_mode != V8JS_DEBUG_AUTO_BREAK_NEVER) {
  912. v8::Debug::DebugBreak(c->isolate);
  913. if(v8js_debug_auto_break_mode == V8JS_DEBUG_AUTO_BREAK_ONCE) {
  914. /* If break-once-mode was enabled, reset flag. */
  915. v8js_debug_auto_break_mode = V8JS_DEBUG_AUTO_BREAK_NEVER;
  916. }
  917. }
  918. #endif /* ENABLE_DEBUGGER_SUPPORT */
  919. /* Execute script */
  920. c->in_execution++;
  921. v8::Local<v8::Value> result = script->Run();
  922. c->in_execution--;
  923. if (time_limit > 0 || memory_limit > 0) {
  924. php_v8js_timer_pop(TSRMLS_C);
  925. }
  926. if(c->fatal_error_abort) {
  927. zend_error(E_ERROR, "V8Js caught fatal error; message lost, sorry :-)");
  928. }
  929. char exception_string[64];
  930. if (c->time_limit_hit) {
  931. // Execution has been terminated due to time limit
  932. sprintf(exception_string, "Script time limit of %lu milliseconds exceeded", time_limit);
  933. zend_throw_exception(php_ce_v8js_time_limit_exception, exception_string, 0 TSRMLS_CC);
  934. return;
  935. }
  936. if (c->memory_limit_hit) {
  937. // Execution has been terminated due to memory limit
  938. sprintf(exception_string, "Script memory limit of %lu bytes exceeded", memory_limit);
  939. zend_throw_exception(php_ce_v8js_memory_limit_exception, exception_string, 0 TSRMLS_CC);
  940. return;
  941. }
  942. if (!try_catch.CanContinue()) {
  943. // At this point we can't re-throw the exception
  944. return;
  945. }
  946. /* There was pending exception left from earlier executions -> throw to PHP */
  947. if (c->pending_exception) {
  948. zend_throw_exception_object(c->pending_exception TSRMLS_CC);
  949. c->pending_exception = NULL;
  950. }
  951. /* Handle runtime JS exceptions */
  952. if (try_catch.HasCaught()) {
  953. /* Pending exceptions are set only in outer caller, inner caller exceptions are always rethrown */
  954. if (c->in_execution < 1) {
  955. /* Report immediately if report_uncaught is true */
  956. if (c->report_uncaught) {
  957. php_v8js_throw_script_exception(&try_catch TSRMLS_CC);
  958. return;
  959. }
  960. /* Exception thrown from JS, preserve it for future execution */
  961. if (result.IsEmpty()) {
  962. MAKE_STD_ZVAL(c->pending_exception);
  963. php_v8js_create_script_exception(c->pending_exception, &try_catch TSRMLS_CC);
  964. return;
  965. }
  966. }
  967. /* Rethrow back to JS */
  968. try_catch.ReThrow();
  969. return;
  970. }
  971. /* Convert V8 value to PHP value */
  972. if (!result.IsEmpty()) {
  973. v8js_to_zval(result, return_value, flags, c->isolate TSRMLS_CC);
  974. }
  975. }
  976. /* }}} */
  977. /* {{{ proto mixed V8Js::checkString(string script)
  978. */
  979. static PHP_METHOD(V8Js, checkString)
  980. {
  981. char *str = NULL;
  982. int str_len = 0;
  983. long flags = V8JS_FLAG_NONE, time_limit = 0, memory_limit = 0;
  984. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &str, &str_len) == FAILURE) {
  985. return;
  986. }
  987. V8JS_BEGIN_CTX(c, getThis())
  988. /* Catch JS exceptions */
  989. v8::TryCatch try_catch;
  990. /* Set script identifier */
  991. v8::Local<v8::String> sname = V8JS_SYM("V8Js::checkString()");
  992. /* Compiles a string context independently. TODO: Add a php function which calls this and returns the result as resource which can be executed later. */
  993. v8::Local<v8::String> source = V8JS_STRL(str, str_len);
  994. v8::Local<v8::Script> script = v8::Script::Compile(source, sname);
  995. /* Compile errors? */
  996. if (script.IsEmpty()) {
  997. php_v8js_throw_script_exception(&try_catch TSRMLS_CC);
  998. return;
  999. }
  1000. RETURN_TRUE;
  1001. }
  1002. /* }}} */
  1003. #ifdef ENABLE_DEBUGGER_SUPPORT
  1004. /* {{{ proto void V8Js::__destruct()
  1005. __destruct for V8Js */
  1006. static PHP_METHOD(V8Js, __destruct)
  1007. {
  1008. V8JS_BEGIN_CTX(c, getThis());
  1009. if(v8js_debug_context == c) {
  1010. v8::Debug::DisableAgent();
  1011. v8js_debug_context = NULL;
  1012. }
  1013. }
  1014. /* }}} */
  1015. /* {{{ proto bool V8Js::startDebugAgent(string agent_name[, int port[, int auto_break]])
  1016. */
  1017. static PHP_METHOD(V8Js, startDebugAgent)
  1018. {
  1019. char *str = NULL;
  1020. int str_len = 0;
  1021. long port = 0, auto_break = 0;
  1022. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sll", &str, &str_len, &port, &auto_break) == FAILURE) {
  1023. return;
  1024. }
  1025. if(!port) {
  1026. port = 9222;
  1027. }
  1028. V8JS_BEGIN_CTX(c, getThis());
  1029. if(v8js_debug_context == c) {
  1030. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Debug agent already started for this V8Js instance");
  1031. RETURN_BOOL(0);
  1032. }
  1033. if(v8js_debug_context != NULL) {
  1034. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Debug agent already started for a different V8Js instance");
  1035. RETURN_BOOL(0);
  1036. }
  1037. v8js_debug_context = c;
  1038. v8js_debug_auto_break_mode = auto_break;
  1039. v8::Debug::SetDebugMessageDispatchHandler(DispatchDebugMessages, true);
  1040. v8::Debug::EnableAgent(str_len ? str : "V8Js", port, auto_break > 0);
  1041. if(auto_break) {
  1042. /* v8::Debug::EnableAgent doesn't really do what we want it to do,
  1043. since it only breaks processing on the default isolate.
  1044. Hence just trigger another DebugBreak, no for our main isolate. */
  1045. v8::Debug::DebugBreak(c->isolate);
  1046. }
  1047. RETURN_BOOL(1);
  1048. }
  1049. /* }}} */
  1050. #endif /* ENABLE_DEBUGGER_SUPPORT */
  1051. /* {{{ proto mixed V8Js::getPendingException()
  1052. */
  1053. static PHP_METHOD(V8Js, getPendingException)
  1054. {
  1055. php_v8js_ctx *c;
  1056. if (zend_parse_parameters_none() == FAILURE) {
  1057. return;
  1058. }
  1059. c = (php_v8js_ctx *) zend_object_store_get_object(getThis() TSRMLS_CC);
  1060. if (c->pending_exception) {
  1061. RETURN_ZVAL(c->pending_exception, 1, 0);
  1062. }
  1063. }
  1064. /* }}} */
  1065. /* {{{ proto void V8Js::setModuleLoader(string module)
  1066. */
  1067. static PHP_METHOD(V8Js, setModuleLoader)
  1068. {
  1069. php_v8js_ctx *c;
  1070. zval *callable;
  1071. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &callable) == FAILURE) {
  1072. return;
  1073. }
  1074. c = (php_v8js_ctx *) zend_object_store_get_object(getThis() TSRMLS_CC);
  1075. c->module_loader = callable;
  1076. Z_ADDREF_P(c->module_loader);
  1077. }
  1078. /* }}} */
  1079. static void php_v8js_persistent_zval_ctor(zval **p) /* {{{ */
  1080. {
  1081. zval *orig_ptr = *p;
  1082. *p = (zval *) malloc(sizeof(zval));
  1083. **p = *orig_ptr;
  1084. switch (Z_TYPE_P(*p)) {
  1085. case IS_STRING:
  1086. Z_STRVAL_P(*p) = (char *) zend_strndup(Z_STRVAL_P(*p), Z_STRLEN_P(*p));
  1087. break;
  1088. default:
  1089. zend_bailout();
  1090. }
  1091. INIT_PZVAL(*p);
  1092. }
  1093. /* }}} */
  1094. static void php_v8js_persistent_zval_dtor(zval **p) /* {{{ */
  1095. {
  1096. switch (Z_TYPE_P(*p)) {
  1097. case IS_STRING:
  1098. free(Z_STRVAL_P(*p));
  1099. break;
  1100. default:
  1101. zend_bailout();
  1102. }
  1103. free(*p);
  1104. }
  1105. /* }}} */
  1106. 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) /* {{{ */
  1107. {
  1108. php_v8js_jsext *jsext = NULL;
  1109. if (!V8JSG(extensions)) {
  1110. V8JSG(extensions) = (HashTable *) malloc(sizeof(HashTable));
  1111. zend_hash_init(V8JSG(extensions), 1, NULL, (dtor_func_t) php_v8js_jsext_dtor, 1);
  1112. } else if (zend_hash_exists(V8JSG(extensions), name, name_len + 1)) {
  1113. return FAILURE;
  1114. }
  1115. jsext = (php_v8js_jsext *) calloc(1, sizeof(php_v8js_jsext));
  1116. if (deps_arr) {
  1117. jsext->deps_count = zend_hash_num_elements(Z_ARRVAL_P(deps_arr));
  1118. if (_php_v8js_create_ext_strarr(&jsext->deps, jsext->deps_count, Z_ARRVAL_P(deps_arr)) == FAILURE) {
  1119. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid dependancy array passed");
  1120. php_v8js_jsext_dtor(jsext);
  1121. free(jsext);
  1122. return FAILURE;
  1123. }
  1124. }
  1125. jsext->auto_enable = auto_enable;
  1126. jsext->name = zend_strndup(name, name_len);
  1127. jsext->source = zend_strndup(source, source_len);
  1128. if (jsext->deps) {
  1129. jsext->deps_ht = (HashTable *) malloc(sizeof(HashTable));
  1130. zend_hash_init(jsext->deps_ht, jsext->deps_count, NULL, (dtor_func_t) php_v8js_persistent_zval_dtor, 1);
  1131. zend_hash_copy(jsext->deps_ht, Z_ARRVAL_P(deps_arr), (copy_ctor_func_t) php_v8js_persistent_zval_ctor, NULL, sizeof(zval *));
  1132. }
  1133. if (zend_hash_add(V8JSG(extensions), name, name_len + 1, jsext, sizeof(php_v8js_jsext), NULL) == FAILURE) {
  1134. php_v8js_jsext_dtor(jsext);
  1135. free(jsext);
  1136. return FAILURE;
  1137. }
  1138. v8::Extension *extension = new v8::Extension(jsext->name, jsext->source, jsext->deps_count, jsext->deps);
  1139. extension->set_auto_enable(auto_enable ? true : false);
  1140. v8::RegisterExtension(extension);
  1141. free(jsext);
  1142. return SUCCESS;
  1143. }
  1144. /* }}} */
  1145. /* {{{ proto bool V8Js::registerExtension(string ext_name, string script [, array deps [, bool auto_enable]])
  1146. */
  1147. static PHP_METHOD(V8Js, registerExtension)
  1148. {
  1149. char *ext_name, *script;
  1150. zval *deps_arr = NULL;
  1151. int ext_name_len, script_len;
  1152. zend_bool auto_enable = 0;
  1153. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|ab", &ext_name, &ext_name_len, &script, &script_len, &deps_arr, &auto_enable) == FAILURE) {
  1154. return;
  1155. }
  1156. if (!ext_name_len) {
  1157. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Extension name cannot be empty");
  1158. } else if (!script_len) {
  1159. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Script cannot be empty");
  1160. } else if (php_v8js_register_extension(ext_name, ext_name_len, script, script_len, deps_arr, auto_enable TSRMLS_CC) == SUCCESS) {
  1161. RETURN_TRUE;
  1162. }
  1163. RETURN_FALSE;
  1164. }
  1165. /* }}} */
  1166. /* ## Static methods ## */
  1167. /* {{{ proto array V8Js::getExtensions()
  1168. */
  1169. static PHP_METHOD(V8Js, getExtensions)
  1170. {
  1171. php_v8js_jsext *jsext;
  1172. zval *ext, *deps_arr;
  1173. HashPosition pos;
  1174. ulong index;
  1175. char *key;
  1176. uint key_len;
  1177. if (zend_parse_parameters_none() == FAILURE) {
  1178. return;
  1179. }
  1180. array_init(return_value);
  1181. if (V8JSG(extensions)) {
  1182. zend_hash_internal_pointer_reset_ex(V8JSG(extensions), &pos);
  1183. while (zend_hash_get_current_data_ex(V8JSG(extensions), (void **) &jsext, &pos) == SUCCESS) {
  1184. if (zend_hash_get_current_key_ex(V8JSG(extensions), &key, &key_len, &index, 0, &pos) == HASH_KEY_IS_STRING) {
  1185. MAKE_STD_ZVAL(ext)
  1186. array_init(ext);
  1187. add_assoc_bool_ex(ext, ZEND_STRS("auto_enable"), jsext->auto_enable);
  1188. if (jsext->deps_ht) {
  1189. MAKE_STD_ZVAL(deps_arr);
  1190. array_init(deps_arr);
  1191. zend_hash_copy(Z_ARRVAL_P(deps_arr), jsext->deps_ht, (copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval *));
  1192. add_assoc_zval_ex(ext, ZEND_STRS("deps"), deps_arr);
  1193. }
  1194. add_assoc_zval_ex(return_value, key, key_len, ext);
  1195. }
  1196. zend_hash_move_forward_ex(V8JSG(extensions), &pos);
  1197. }
  1198. }
  1199. }
  1200. /* }}} */
  1201. /* {{{ arginfo */
  1202. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_construct, 0, 0, 0)
  1203. ZEND_ARG_INFO(0, object_name)
  1204. ZEND_ARG_INFO(0, variables)
  1205. ZEND_ARG_INFO(0, extensions)
  1206. ZEND_ARG_INFO(0, report_uncaught_exceptions)
  1207. ZEND_END_ARG_INFO()
  1208. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_executestring, 0, 0, 1)
  1209. ZEND_ARG_INFO(0, script)
  1210. ZEND_ARG_INFO(0, identifier)
  1211. ZEND_ARG_INFO(0, flags)
  1212. ZEND_ARG_INFO(0, time_limit)
  1213. ZEND_ARG_INFO(0, memory_limit)
  1214. ZEND_END_ARG_INFO()
  1215. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_checkstring, 0, 0, 1)
  1216. ZEND_ARG_INFO(0, script)
  1217. ZEND_END_ARG_INFO()
  1218. #ifdef ENABLE_DEBUGGER_SUPPORT
  1219. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_destruct, 0, 0, 0)
  1220. ZEND_END_ARG_INFO()
  1221. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_startdebugagent, 0, 0, 0)
  1222. ZEND_ARG_INFO(0, agentName)
  1223. ZEND_ARG_INFO(0, port)
  1224. ZEND_ARG_INFO(0, auto_break)
  1225. ZEND_END_ARG_INFO()
  1226. #endif /* ENABLE_DEBUGGER_SUPPORT */
  1227. ZEND_BEGIN_ARG_INFO(arginfo_v8js_getpendingexception, 0)
  1228. ZEND_END_ARG_INFO()
  1229. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_setmoduleloader, 0, 0, 1)
  1230. ZEND_ARG_INFO(0, callable)
  1231. ZEND_END_ARG_INFO()
  1232. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_registerextension, 0, 0, 2)
  1233. ZEND_ARG_INFO(0, extension_name)
  1234. ZEND_ARG_INFO(0, script)
  1235. ZEND_ARG_INFO(0, dependencies)
  1236. ZEND_ARG_INFO(0, auto_enable)
  1237. ZEND_END_ARG_INFO()
  1238. ZEND_BEGIN_ARG_INFO(arginfo_v8js_getextensions, 0)
  1239. ZEND_END_ARG_INFO()
  1240. ZEND_BEGIN_ARG_INFO(arginfo_v8jsscriptexception_no_args, 0)
  1241. ZEND_END_ARG_INFO()
  1242. /* }}} */
  1243. static const zend_function_entry v8_object_methods[] = { /* {{{ */
  1244. PHP_ME(V8Object, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
  1245. {NULL, NULL, NULL}
  1246. };
  1247. /* }}} */
  1248. static const zend_function_entry v8_function_methods[] = { /* {{{ */
  1249. PHP_ME(V8Function, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
  1250. {NULL, NULL, NULL}
  1251. };
  1252. /* }}} */
  1253. static const zend_function_entry v8js_methods[] = { /* {{{ */
  1254. PHP_ME(V8Js, __construct, arginfo_v8js_construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
  1255. PHP_ME(V8Js, executeString, arginfo_v8js_executestring, ZEND_ACC_PUBLIC)
  1256. PHP_ME(V8Js, checkString, arginfo_v8js_checkstring, ZEND_ACC_PUBLIC)
  1257. PHP_ME(V8Js, getPendingException, arginfo_v8js_getpendingexception, ZEND_ACC_PUBLIC)
  1258. PHP_ME(V8Js, setModuleLoader, arginfo_v8js_setmoduleloader, ZEND_ACC_PUBLIC)
  1259. PHP_ME(V8Js, registerExtension, arginfo_v8js_registerextension, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
  1260. PHP_ME(V8Js, getExtensions, arginfo_v8js_getextensions, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
  1261. #ifdef ENABLE_DEBUGGER_SUPPORT
  1262. PHP_ME(V8Js, __destruct, arginfo_v8js_destruct, ZEND_ACC_PUBLIC|ZEND_ACC_DTOR)
  1263. PHP_ME(V8Js, startDebugAgent, arginfo_v8js_startdebugagent, ZEND_ACC_PUBLIC)
  1264. #endif
  1265. {NULL, NULL, NULL}
  1266. };
  1267. /* }}} */
  1268. /* V8Js object handlers */
  1269. static void php_v8js_write_property(zval *object, zval *member, zval *value ZEND_HASH_KEY_DC TSRMLS_DC) /* {{{ */
  1270. {
  1271. V8JS_BEGIN_CTX(c, object)
  1272. /* Check whether member is public, if so, export to V8. */
  1273. zend_property_info *property_info = zend_get_property_info(c->std.ce, member, 1 TSRMLS_CC);
  1274. if(property_info->flags & ZEND_ACC_PUBLIC) {
  1275. /* Global PHP JS object */
  1276. v8::Local<v8::String> object_name_js = v8::Local<v8::String>::New(isolate, c->object_name);
  1277. v8::Local<v8::Object> jsobj = V8JS_GLOBAL(isolate)->Get(object_name_js)->ToObject();
  1278. /* Write value to PHP JS object */
  1279. jsobj->ForceSet(V8JS_SYML(Z_STRVAL_P(member), Z_STRLEN_P(member)), zval_to_v8js(value, isolate TSRMLS_CC), v8::ReadOnly);
  1280. }
  1281. /* Write value to PHP object */
  1282. std_object_handlers.write_property(object, member, value ZEND_HASH_KEY_CC TSRMLS_CC);
  1283. }
  1284. /* }}} */
  1285. static void php_v8js_unset_property(zval *object, zval *member ZEND_HASH_KEY_DC TSRMLS_DC) /* {{{ */
  1286. {
  1287. V8JS_BEGIN_CTX(c, object)
  1288. /* Global PHP JS object */
  1289. v8::Local<v8::String> object_name_js = v8::Local<v8::String>::New(isolate, c->object_name);
  1290. v8::Local<v8::Object> jsobj = V8JS_GLOBAL(isolate)->Get(object_name_js)->ToObject();
  1291. /* Delete value from PHP JS object */
  1292. jsobj->ForceDelete(V8JS_SYML(Z_STRVAL_P(member), Z_STRLEN_P(member)));
  1293. /* Unset from PHP object */
  1294. std_object_handlers.unset_property(object, member ZEND_HASH_KEY_CC TSRMLS_CC);
  1295. }
  1296. /* }}} */
  1297. /* }}} V8Js */
  1298. /* {{{ Class: V8JsScriptException */
  1299. static void php_v8js_create_script_exception(zval *return_value, v8::TryCatch *try_catch TSRMLS_DC) /* {{{ */
  1300. {
  1301. v8::String::Utf8Value exception(try_catch->Exception());
  1302. const char *exception_string = ToCString(exception);
  1303. v8::Handle<v8::Message> tc_message = try_catch->Message();
  1304. const char *filename_string, *sourceline_string;
  1305. char *message_string;
  1306. int linenum, message_len;
  1307. object_init_ex(return_value, php_ce_v8js_script_exception);
  1308. #define PHPV8_EXPROP(type, name, value) \
  1309. zend_update_property##type(php_ce_v8js_script_exception, return_value, #name, sizeof(#name) - 1, value TSRMLS_CC);
  1310. if (tc_message.IsEmpty()) {
  1311. message_len = spprintf(&message_string, 0, "%s", exception_string);
  1312. }
  1313. else
  1314. {
  1315. v8::String::Utf8Value filename(tc_message->GetScriptResourceName());
  1316. filename_string = ToCString(filename);
  1317. PHPV8_EXPROP(_string, JsFileName, filename_string);
  1318. v8::String::Utf8Value sourceline(tc_message->GetSourceLine());
  1319. sourceline_string = ToCString(sourceline);
  1320. PHPV8_EXPROP(_string, JsSourceLine, sourceline_string);
  1321. linenum = tc_message->GetLineNumber();
  1322. PHPV8_EXPROP(_long, JsLineNumber, linenum);
  1323. message_len = spprintf(&message_string, 0, "%s:%d: %s", filename_string, linenum, exception_string);
  1324. v8::String::Utf8Value stacktrace(try_catch->StackTrace());
  1325. if (stacktrace.length() > 0) {
  1326. const char* stacktrace_string = ToCString(stacktrace);
  1327. PHPV8_EXPROP(_string, JsTrace, stacktrace_string);
  1328. }
  1329. }
  1330. PHPV8_EXPROP(_string, message, message_string);
  1331. efree(message_string);
  1332. }
  1333. /* }}} */
  1334. static void php_v8js_throw_script_exception(v8::TryCatch *try_catch TSRMLS_DC) /* {{{ */
  1335. {
  1336. v8::String::Utf8Value exception(try_catch->Exception());
  1337. const char *exception_string = ToCString(exception);
  1338. zval *zexception = NULL;
  1339. if (try_catch->Message().IsEmpty()) {
  1340. zend_throw_exception(php_ce_v8js_script_exception, (char *) exception_string, 0 TSRMLS_CC);
  1341. } else {
  1342. MAKE_STD_ZVAL(zexception);
  1343. php_v8js_create_script_exception(zexception, try_catch TSRMLS_CC);
  1344. zend_throw_exception_object(zexception TSRMLS_CC);
  1345. }
  1346. }
  1347. /* }}} */
  1348. #define V8JS_EXCEPTION_METHOD(property) \
  1349. static PHP_METHOD(V8JsScriptException, get##property) \
  1350. { \
  1351. zval *value; \
  1352. \
  1353. if (zend_parse_parameters_none() == FAILURE) { \
  1354. return; \
  1355. } \
  1356. value = zend_read_property(php_ce_v8js_script_exception, getThis(), #property, sizeof(#property) - 1, 0 TSRMLS_CC); \
  1357. *return_value = *value; \
  1358. zval_copy_ctor(return_value); \
  1359. INIT_PZVAL(return_value); \
  1360. }
  1361. /* {{{ proto string V8JsEScriptxception::getJsFileName()
  1362. */
  1363. V8JS_EXCEPTION_METHOD(JsFileName);
  1364. /* }}} */
  1365. /* {{{ proto string V8JsScriptException::getJsLineNumber()
  1366. */
  1367. V8JS_EXCEPTION_METHOD(JsLineNumber);
  1368. /* }}} */
  1369. /* {{{ proto string V8JsScriptException::getJsSourceLine()
  1370. */
  1371. V8JS_EXCEPTION_METHOD(JsSourceLine);
  1372. /* }}} */
  1373. /* {{{ proto string V8JsScriptException::getJsTrace()
  1374. */
  1375. V8JS_EXCEPTION_METHOD(JsTrace);
  1376. /* }}} */
  1377. static const zend_function_entry v8js_script_exception_methods[] = { /* {{{ */
  1378. PHP_ME(V8JsScriptException, getJsFileName, arginfo_v8jsscriptexception_no_args, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
  1379. PHP_ME(V8JsScriptException, getJsLineNumber, arginfo_v8jsscriptexception_no_args, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
  1380. PHP_ME(V8JsScriptException, getJsSourceLine, arginfo_v8jsscriptexception_no_args, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
  1381. PHP_ME(V8JsScriptException, getJsTrace, arginfo_v8jsscriptexception_no_args, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
  1382. {NULL, NULL, NULL}
  1383. };
  1384. /* }}} */
  1385. /* }}} V8JsScriptException */
  1386. /* {{{ Class: V8JsTimeLimitException */
  1387. static const zend_function_entry v8js_time_limit_exception_methods[] = { /* {{{ */
  1388. {NULL, NULL, NULL}
  1389. };
  1390. /* }}} */
  1391. /* }}} V8JsTimeLimitException */
  1392. /* {{{ Class: V8JsMemoryLimitException */
  1393. static const zend_function_entry v8js_memory_limit_exception_methods[] = { /* {{{ */
  1394. {NULL, NULL, NULL}
  1395. };
  1396. /* }}} */
  1397. /* }}} V8JsMemoryLimitException */
  1398. /* {{{ PHP_MINIT_FUNCTION
  1399. */
  1400. static PHP_MINIT_FUNCTION(v8js)
  1401. {
  1402. zend_class_entry ce;
  1403. /* V8Object Class */
  1404. INIT_CLASS_ENTRY(ce, "V8Object", v8_object_methods);
  1405. php_ce_v8_object = zend_register_internal_class(&ce TSRMLS_CC);
  1406. php_ce_v8_object->ce_flags |= ZEND_ACC_FINAL;
  1407. php_ce_v8_object->create_object = php_v8js_v8_new;
  1408. /* V8Function Class */
  1409. INIT_CLASS_ENTRY(ce, "V8Function", v8_function_methods);
  1410. php_ce_v8_function = zend_register_internal_class(&ce TSRMLS_CC);
  1411. php_ce_v8_function->ce_flags |= ZEND_ACC_FINAL;
  1412. php_ce_v8_function->create_object = php_v8js_v8_new;
  1413. /* V8<Object|Function> handlers */
  1414. memcpy(&v8_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
  1415. v8_object_handlers.clone_obj = NULL;
  1416. v8_object_handlers.cast_object = NULL;
  1417. v8_object_handlers.get_property_ptr_ptr = NULL;
  1418. v8_object_handlers.has_property = php_v8js_v8_has_property;
  1419. v8_object_handlers.read_property = php_v8js_v8_read_property;
  1420. v8_object_handlers.write_property = php_v8js_v8_write_property;
  1421. v8_object_handlers.unset_property = php_v8js_v8_unset_property;
  1422. v8_object_handlers.get_properties = php_v8js_v8_get_properties;
  1423. v8_object_handlers.get_method = php_v8js_v8_get_method;
  1424. v8_object_handlers.call_method = php_v8js_v8_call_method;
  1425. v8_object_handlers.get_debug_info = php_v8js_v8_get_debug_info;
  1426. v8_object_handlers.get_closure = php_v8js_v8_get_closure;
  1427. /* V8Js Class */
  1428. INIT_CLASS_ENTRY(ce, "V8Js", v8js_methods);
  1429. php_ce_v8js = zend_register_internal_class(&ce TSRMLS_CC);
  1430. php_ce_v8js->create_object = php_v8js_new;
  1431. /* V8Js handlers */
  1432. memcpy(&v8js_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
  1433. v8js_object_handlers.clone_obj = NULL;
  1434. v8js_object_handlers.write_property = php_v8js_write_property;
  1435. v8js_object_handlers.unset_property = php_v8js_unset_property;
  1436. /* V8Js Class Constants */
  1437. zend_declare_class_constant_string(php_ce_v8js, ZEND_STRL("V8_VERSION"), PHP_V8_VERSION TSRMLS_CC);
  1438. zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("FLAG_NONE"), V8JS_FLAG_NONE TSRMLS_CC);
  1439. zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("FLAG_FORCE_ARRAY"), V8JS_FLAG_FORCE_ARRAY TSRMLS_CC);
  1440. #ifdef ENABLE_DEBUGGER_SUPPORT
  1441. zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("DEBUG_AUTO_BREAK_NEVER"), V8JS_DEBUG_AUTO_BREAK_NEVER TSRMLS_CC);
  1442. zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("DEBUG_AUTO_BREAK_ONCE"), V8JS_DEBUG_AUTO_BREAK_ONCE TSRMLS_CC);
  1443. zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("DEBUG_AUTO_BREAK_ALWAYS"), V8JS_DEBUG_AUTO_BREAK_ALWAYS TSRMLS_CC);
  1444. #endif
  1445. /* V8JsScriptException Class */
  1446. INIT_CLASS_ENTRY(ce, "V8JsScriptException", v8js_script_exception_methods);
  1447. php_ce_v8js_script_exception = zend_register_internal_class_ex(&ce, zend_exception_get_default(TSRMLS_C), NULL TSRMLS_CC);
  1448. php_ce_v8js_script_exception->ce_flags |= ZEND_ACC_FINAL;
  1449. /* Add custom JS specific properties */
  1450. zend_declare_property_null(php_ce_v8js_script_exception, ZEND_STRL("JsFileName"), ZEND_ACC_PROTECTED TSRMLS_CC);
  1451. zend_declare_property_null(php_ce_v8js_script_exception, ZEND_STRL("JsLineNumber"), ZEND_ACC_PROTECTED TSRMLS_CC);
  1452. zend_declare_property_null(php_ce_v8js_script_exception, ZEND_STRL("JsSourceLine"), ZEND_ACC_PROTECTED TSRMLS_CC);
  1453. zend_declare_property_null(php_ce_v8js_script_exception, ZEND_STRL("JsTrace"), ZEND_ACC_PROTECTED TSRMLS_CC);
  1454. /* V8JsTimeLimitException Class */
  1455. INIT_CLASS_ENTRY(ce, "V8JsTimeLimitException", v8js_time_limit_exception_methods);
  1456. php_ce_v8js_time_limit_exception = zend_register_internal_class_ex(&ce, zend_exception_get_default(TSRMLS_C), NULL TSRMLS_CC);
  1457. php_ce_v8js_time_limit_exception->ce_flags |= ZEND_ACC_FINAL;
  1458. /* V8JsMemoryLimitException Class */
  1459. INIT_CLASS_ENTRY(ce, "V8JsMemoryLimitException", v8js_memory_limit_exception_methods);
  1460. php_ce_v8js_memory_limit_exception = zend_register_internal_class_ex(&ce, zend_exception_get_default(TSRMLS_C), NULL TSRMLS_CC);
  1461. php_ce_v8js_memory_limit_exception->ce_flags |= ZEND_ACC_FINAL;
  1462. REGISTER_INI_ENTRIES();
  1463. return SUCCESS;
  1464. }
  1465. /* }}} */
  1466. /* {{{ PHP_MSHUTDOWN_FUNCTION
  1467. */
  1468. static PHP_MSHUTDOWN_FUNCTION(v8js)
  1469. {
  1470. UNREGISTER_INI_ENTRIES();
  1471. return SUCCESS;
  1472. }
  1473. /* }}} */
  1474. /* {{{ PHP_RSHUTDOWN_FUNCTION
  1475. */
  1476. static PHP_RSHUTDOWN_FUNCTION(v8js)
  1477. {
  1478. // If the timer thread is running then stop it
  1479. if (V8JSG(timer_thread)) {
  1480. V8JSG(timer_stop) = true;
  1481. V8JSG(timer_thread)->join();
  1482. }
  1483. #if V8JS_DEBUG
  1484. v8::HeapStatistics stats;
  1485. v8::V8::GetHeapStatistics(&stats);
  1486. float used = stats.used_heap_size() / 1024.0 / 1024.0;
  1487. float total = stats.total_heap_size() / 1024.0 / 1024.0;
  1488. fprintf(stderr, "### RSHUTDOWN ###\n");
  1489. fprintf(stderr, "############ Heap Used/Total %.2f/%.2f MB ############\n", used, total);
  1490. fflush(stderr);
  1491. #endif
  1492. return SUCCESS;
  1493. }
  1494. /* }}} */
  1495. /* {{{ PHP_MINFO_FUNCTION
  1496. */
  1497. static PHP_MINFO_FUNCTION(v8js)
  1498. {
  1499. php_info_print_table_start();
  1500. php_info_print_table_header(2, "V8 Javascript Engine", "enabled");
  1501. php_info_print_table_header(2, "V8 Engine Compiled Version", PHP_V8_VERSION);
  1502. php_info_print_table_header(2, "V8 Engine Linked Version", v8::V8::GetVersion());
  1503. php_info_print_table_header(2, "Version", V8JS_VERSION);
  1504. php_info_print_table_end();
  1505. DISPLAY_INI_ENTRIES();
  1506. }
  1507. /* }}} */
  1508. /* {{{ PHP_GINIT_FUNCTION
  1509. */
  1510. static PHP_GINIT_FUNCTION(v8js)
  1511. {
  1512. /*
  1513. If ZTS is disabled, the v8js_globals instance is declared right
  1514. in the BSS and hence automatically initialized by C++ compiler.
  1515. Most of the variables are just zeroed.
  1516. If ZTS is enabled however, v8js_globals just points to a freshly
  1517. allocated, uninitialized piece of memory, hence we need to
  1518. initialize all fields on our own. Likewise on shutdown we have to
  1519. run the destructors manually.
  1520. */
  1521. #ifdef ZTS
  1522. v8js_globals->extensions = NULL;
  1523. v8js_globals->v8_initialized = 0;
  1524. v8js_globals->v8_flags = NULL;
  1525. v8js_globals->timer_thread = NULL;
  1526. v8js_globals->timer_stop = false;
  1527. new(&v8js_globals->timer_mutex) std::mutex;
  1528. new(&v8js_globals->timer_stack) std::stack<php_v8js_timer_ctx *>;
  1529. new(&v8js_globals->modules_loaded) std::map<char *, v8::Handle<v8::Object>>;
  1530. #endif
  1531. }
  1532. /* }}} */
  1533. /* {{{ PHP_GSHUTDOWN_FUNCTION
  1534. */
  1535. static PHP_GSHUTDOWN_FUNCTION(v8js)
  1536. {
  1537. if (v8js_globals->extensions) {
  1538. zend_hash_destroy(v8js_globals->extensions);
  1539. free(v8js_globals->extensions);
  1540. v8js_globals->extensions = NULL;
  1541. }
  1542. if (v8js_globals->v8_flags) {
  1543. free(v8js_globals->v8_flags);
  1544. v8js_globals->v8_flags = NULL;
  1545. }
  1546. #ifdef ZTS
  1547. v8js_globals->timer_stack.~stack();
  1548. v8js_globals->timer_mutex.~mutex();
  1549. v8js_globals->modules_loaded.~map();
  1550. #endif
  1551. }
  1552. /* }}} */
  1553. /* {{{ v8js_functions[] */
  1554. static const zend_function_entry v8js_functions[] = {
  1555. {NULL, NULL, NULL}
  1556. };
  1557. /* }}} */
  1558. /* {{{ v8js_module_entry
  1559. */
  1560. zend_module_entry v8js_module_entry = {
  1561. STANDARD_MODULE_HEADER_EX,
  1562. NULL,
  1563. NULL,
  1564. "v8js",
  1565. v8js_functions,
  1566. PHP_MINIT(v8js),
  1567. PHP_MSHUTDOWN(v8js),
  1568. NULL,
  1569. PHP_RSHUTDOWN(v8js),
  1570. PHP_MINFO(v8js),
  1571. V8JS_VERSION,
  1572. PHP_MODULE_GLOBALS(v8js),
  1573. PHP_GINIT(v8js),
  1574. PHP_GSHUTDOWN(v8js),
  1575. NULL,
  1576. STANDARD_MODULE_PROPERTIES_EX
  1577. };
  1578. /* }}} */
  1579. /*
  1580. * Local variables:
  1581. * tab-width: 4
  1582. * c-basic-offset: 4
  1583. * End:
  1584. * vim600: noet sw=4 ts=4 fdm=marker
  1585. * vim<600: noet sw=4 ts=4
  1586. */