v8js.cc 59 KB

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