v8js_convert.cc 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250
  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. #ifdef HAVE_CONFIG_H
  15. #include "config.h"
  16. #endif
  17. extern "C" {
  18. #include "php.h"
  19. #include "ext/date/php_date.h"
  20. #include "ext/standard/php_string.h"
  21. #include "zend_interfaces.h"
  22. #include "zend_closures.h"
  23. }
  24. #include "php_v8js_macros.h"
  25. #include "v8js_array_access.h"
  26. #include <stdexcept>
  27. #include <limits>
  28. /* Callback for PHP's zend_error_cb; catching any fatal PHP error.
  29. * The callback is installed in the lowest (stack wise) php_v8js_call_php_func
  30. * frame. Just store the error message and jump right back there and fall
  31. * back into V8 context. */
  32. static void php_v8js_error_handler(int error_num, const char *error_filename,
  33. const uint error_lineno, const char *format,
  34. va_list args) /* {{{ */
  35. {
  36. char *buffer;
  37. int buffer_len;
  38. TSRMLS_FETCH();
  39. switch (error_num)
  40. {
  41. case E_ERROR:
  42. case E_CORE_ERROR:
  43. case E_USER_ERROR:
  44. buffer_len = vspprintf(&buffer, PG(log_errors_max_len), format, args);
  45. V8JSG(fatal_error_abort) = true;
  46. V8JSG(error_num) = error_num;
  47. V8JSG(error_message) = buffer;
  48. longjmp(*V8JSG(unwind_env), 1);
  49. break;
  50. default:
  51. V8JSG(old_error_handler)(error_num, error_filename, error_lineno, format, args);
  52. break;
  53. }
  54. }
  55. /* }}} */
  56. static void php_v8js_weak_object_callback(const v8::WeakCallbackData<v8::Object, zval> &data);
  57. /* Callback for PHP methods and functions */
  58. static void php_v8js_call_php_func(zval *value, zend_class_entry *ce, zend_function *method_ptr, v8::Isolate *isolate, const v8::FunctionCallbackInfo<v8::Value>& info TSRMLS_DC) /* {{{ */
  59. {
  60. v8::Handle<v8::Value> return_value;
  61. zend_fcall_info fci;
  62. zend_fcall_info_cache fcc;
  63. zval fname, *retval_ptr = NULL, **argv = NULL;
  64. zend_uint argc = info.Length(), min_num_args = 0, max_num_args = 0;
  65. char *error;
  66. int error_len, i, flags = V8JS_FLAG_NONE;
  67. php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData(0);
  68. /* Set parameter limits */
  69. min_num_args = method_ptr->common.required_num_args;
  70. max_num_args = method_ptr->common.num_args;
  71. /* Function name to call */
  72. INIT_ZVAL(fname);
  73. ZVAL_STRING(&fname, method_ptr->common.function_name, 0);
  74. /* zend_fcall_info */
  75. fci.size = sizeof(fci);
  76. fci.function_table = &ce->function_table;
  77. fci.function_name = &fname;
  78. fci.symbol_table = NULL;
  79. fci.object_ptr = value;
  80. fci.retval_ptr_ptr = &retval_ptr;
  81. fci.param_count = 0;
  82. /* Check for passed vs required number of arguments */
  83. if (argc < min_num_args)
  84. {
  85. error_len = spprintf(&error, 0,
  86. "%s::%s() expects %s %d parameter%s, %d given",
  87. ce->name,
  88. method_ptr->common.function_name,
  89. min_num_args == max_num_args ? "exactly" : argc < min_num_args ? "at least" : "at most",
  90. argc < min_num_args ? min_num_args : max_num_args,
  91. (argc < min_num_args ? min_num_args : max_num_args) == 1 ? "" : "s",
  92. argc);
  93. return_value = V8JS_THROW(isolate, TypeError, error, error_len);
  94. if (ce == zend_ce_closure) {
  95. efree(const_cast<char*>(method_ptr->internal_function.function_name));
  96. efree(method_ptr);
  97. }
  98. efree(error);
  99. info.GetReturnValue().Set(return_value);
  100. return;
  101. }
  102. /* Convert parameters passed from V8 */
  103. if (argc) {
  104. flags = V8JS_GLOBAL_GET_FLAGS(isolate);
  105. fci.params = (zval ***) safe_emalloc(argc, sizeof(zval **), 0);
  106. argv = (zval **) safe_emalloc(argc, sizeof(zval *), 0);
  107. for (i = 0; i < argc; i++) {
  108. v8::Local<v8::Value> php_object;
  109. if (info[i]->IsObject()) {
  110. php_object = v8::Local<v8::Object>::Cast(info[i])->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY));
  111. }
  112. if (!php_object.IsEmpty()) {
  113. /* This is a PHP object, passed to JS and back. */
  114. argv[i] = reinterpret_cast<zval *>(v8::External::Cast(*php_object)->Value());
  115. Z_ADDREF_P(argv[i]);
  116. } else {
  117. MAKE_STD_ZVAL(argv[i]);
  118. if (v8js_to_zval(info[i], argv[i], flags, isolate TSRMLS_CC) == FAILURE) {
  119. fci.param_count++;
  120. error_len = spprintf(&error, 0, "converting parameter #%d passed to %s() failed", i + 1, method_ptr->common.function_name);
  121. return_value = V8JS_THROW(isolate, Error, error, error_len);
  122. efree(error);
  123. goto failure;
  124. }
  125. }
  126. fci.params[fci.param_count++] = &argv[i];
  127. }
  128. } else {
  129. fci.params = NULL;
  130. }
  131. fci.no_separation = 1;
  132. info.GetReturnValue().Set(V8JS_NULL);
  133. {
  134. isolate->Exit();
  135. v8::Unlocker unlocker(isolate);
  136. /* zend_fcall_info_cache */
  137. fcc.initialized = 1;
  138. fcc.function_handler = method_ptr;
  139. fcc.calling_scope = ce;
  140. fcc.called_scope = ce;
  141. fcc.object_ptr = value;
  142. jmp_buf env;
  143. jmp_buf *old_env;
  144. int val = 0;
  145. bool installed_handler = false;
  146. /* If this is the first level call from V8 back to PHP, install a
  147. * handler for fatal errors; we must fall back through V8 to keep
  148. * it from crashing. */
  149. if (V8JSG(unwind_env) == NULL) {
  150. installed_handler = true;
  151. V8JSG(old_error_handler) = zend_error_cb;
  152. zend_error_cb = php_v8js_error_handler;
  153. }
  154. else {
  155. /* inner call, stash unwind env */
  156. old_env = V8JSG(unwind_env);
  157. }
  158. val = setjmp (env);
  159. V8JSG(unwind_env) = &env;
  160. if (!val) {
  161. /* Call the method */
  162. zend_call_function(&fci, &fcc TSRMLS_CC);
  163. }
  164. if (installed_handler) {
  165. /* leaving out-most frame, restore original handler. */
  166. zend_error_cb = V8JSG(old_error_handler);
  167. V8JSG(unwind_env) = NULL;
  168. }
  169. else {
  170. /* leaving inner frame, restore unwind env and jump. */
  171. V8JSG(unwind_env) = old_env;
  172. if (V8JSG(fatal_error_abort)) {
  173. longjmp(*V8JSG(unwind_env), 1);
  174. }
  175. }
  176. if (V8JSG(fatal_error_abort)) {
  177. v8::V8::TerminateExecution(isolate);
  178. return;
  179. }
  180. }
  181. isolate->Enter();
  182. failure:
  183. /* Cleanup */
  184. if (argc) {
  185. for (i = 0; i < fci.param_count; i++) {
  186. zval_ptr_dtor(&argv[i]);
  187. }
  188. efree(argv);
  189. efree(fci.params);
  190. }
  191. if (retval_ptr != NULL) {
  192. return_value = zval_to_v8js(retval_ptr, isolate TSRMLS_CC);
  193. zval_ptr_dtor(&retval_ptr);
  194. } else {
  195. return_value = V8JS_NULL;
  196. }
  197. info.GetReturnValue().Set(return_value);
  198. }
  199. /* }}} */
  200. /* Callback for PHP methods and functions */
  201. static void php_v8js_php_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  202. {
  203. v8::Isolate *isolate = info.GetIsolate();
  204. v8::Local<v8::Object> self = info.Holder();
  205. V8JS_TSRMLS_FETCH();
  206. zval *value = reinterpret_cast<zval *>(v8::External::Cast(*self->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY)))->Value());
  207. zend_function *method_ptr;
  208. zend_class_entry *ce = Z_OBJCE_P(value);
  209. /* Set method_ptr from v8::External or fetch the closure invoker */
  210. if (!info.Data().IsEmpty() && info.Data()->IsExternal()) {
  211. method_ptr = static_cast<zend_function *>(v8::External::Cast(*info.Data())->Value());
  212. } else {
  213. method_ptr = zend_get_closure_invoke_method(value TSRMLS_CC);
  214. }
  215. return php_v8js_call_php_func(value, ce, method_ptr, isolate, info TSRMLS_CC);
  216. }
  217. /* Callback for PHP constructor calls */
  218. static void php_v8js_construct_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  219. {
  220. v8::Isolate *isolate = info.GetIsolate();
  221. info.GetReturnValue().Set(V8JS_UNDEFINED);
  222. // @todo assert constructor call
  223. v8::Handle<v8::Object> newobj = info.This();
  224. v8::Local<v8::External> php_object;
  225. zval *value;
  226. if (!info.IsConstructCall()) {
  227. return;
  228. }
  229. v8::Local<v8::Array> cons_data = v8::Local<v8::Array>::Cast(info.Data());
  230. v8::Local<v8::External> ext_tmpl = v8::Local<v8::External>::Cast(cons_data->Get(0));
  231. v8::Local<v8::External> ext_ce = v8::Local<v8::External>::Cast(cons_data->Get(1));
  232. php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData(0);
  233. if (info[0]->IsExternal()) {
  234. // Object created by v8js in php_v8js_hash_to_jsobj, PHP object passed as v8::External.
  235. php_object = v8::Local<v8::External>::Cast(info[0]);
  236. value = reinterpret_cast<zval *>(php_object->Value());
  237. if(ctx->weak_objects.count(value)) {
  238. // We already exported this object, hence no need to add another
  239. // ref, v8 won't give us a second weak-object callback anyways.
  240. newobj->SetAlignedPointerInInternalField(0, ext_tmpl->Value());
  241. newobj->SetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY), php_object);
  242. return;
  243. }
  244. // Increase the reference count of this value because we're storing it internally for use later
  245. // See https://github.com/preillyme/v8js/issues/6
  246. Z_ADDREF_P(value);
  247. } else {
  248. // Object created from JavaScript context. Need to create PHP object first.
  249. V8JS_TSRMLS_FETCH();
  250. zend_class_entry *ce = static_cast<zend_class_entry *>(ext_ce->Value());
  251. zend_function *ctor_ptr = ce->constructor;
  252. // Check access on __construct function, if any
  253. if (ctor_ptr != NULL && (ctor_ptr->common.fn_flags & ZEND_ACC_PUBLIC) == 0) {
  254. info.GetReturnValue().Set(isolate->ThrowException(V8JS_SYM("Call to protected __construct() not allowed")));
  255. return;
  256. }
  257. MAKE_STD_ZVAL(value);
  258. object_init_ex(value, ce);
  259. // Call __construct function
  260. if (ctor_ptr != NULL) {
  261. php_v8js_call_php_func(value, ce, ctor_ptr, isolate, info TSRMLS_CC);
  262. }
  263. php_object = v8::External::New(isolate, value);
  264. }
  265. newobj->SetAlignedPointerInInternalField(0, ext_tmpl->Value());
  266. newobj->SetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY), php_object);
  267. // Since we got to decrease the reference count again, in case v8 garbage collector
  268. // decides to dispose the JS object, we add a weak persistent handle and register
  269. // a callback function that removes the reference.
  270. ctx->weak_objects[value].Reset(isolate, newobj);
  271. ctx->weak_objects[value].SetWeak(value, php_v8js_weak_object_callback);
  272. // Just tell v8 that we're allocating some external memory
  273. // (for the moment we just always tell 1k instead of trying to find out actual values)
  274. isolate->AdjustAmountOfExternalAllocatedMemory(1024);
  275. }
  276. /* }}} */
  277. static int _php_v8js_is_assoc_array(HashTable *myht TSRMLS_DC) /* {{{ */
  278. {
  279. int i;
  280. char *key;
  281. ulong index, idx = 0;
  282. uint key_len;
  283. HashPosition pos;
  284. zend_hash_internal_pointer_reset_ex(myht, &pos);
  285. for (;; zend_hash_move_forward_ex(myht, &pos)) {
  286. i = zend_hash_get_current_key_ex(myht, &key, &key_len, &index, 0, &pos);
  287. if (i == HASH_KEY_NON_EXISTANT)
  288. break;
  289. if (i == HASH_KEY_IS_STRING || index != idx) {
  290. return 1;
  291. }
  292. idx++;
  293. }
  294. return 0;
  295. }
  296. /* }}} */
  297. static void php_v8js_weak_object_callback(const v8::WeakCallbackData<v8::Object, zval> &data) {
  298. v8::Isolate *isolate = data.GetIsolate();
  299. zval *value = data.GetParameter();
  300. zval_ptr_dtor(&value);
  301. php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData(0);
  302. ctx->weak_objects.at(value).Reset();
  303. ctx->weak_objects.erase(value);
  304. isolate->AdjustAmountOfExternalAllocatedMemory(-1024);
  305. }
  306. static void php_v8js_weak_closure_callback(const v8::WeakCallbackData<v8::Object, v8js_tmpl_t> &data) {
  307. v8::Isolate *isolate = data.GetIsolate();
  308. v8js_tmpl_t *persist_tpl_ = data.GetParameter();
  309. persist_tpl_->Reset();
  310. delete persist_tpl_;
  311. php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData(0);
  312. ctx->weak_closures.at(persist_tpl_).Reset();
  313. ctx->weak_closures.erase(persist_tpl_);
  314. };
  315. /* These are not defined by Zend */
  316. #define ZEND_WAKEUP_FUNC_NAME "__wakeup"
  317. #define ZEND_SLEEP_FUNC_NAME "__sleep"
  318. #define ZEND_SET_STATE_FUNC_NAME "__set_state"
  319. #define IS_MAGIC_FUNC(mname) \
  320. ((key_len == sizeof(mname)) && \
  321. !strncasecmp(key, mname, key_len - 1))
  322. #define PHP_V8JS_CALLBACK(isolate, mptr, tmpl) \
  323. v8::FunctionTemplate::New((isolate), php_v8js_php_callback, v8::External::New((isolate), mptr), v8::Signature::New((isolate), tmpl))->GetFunction()
  324. static void php_v8js_named_property_enumerator(const v8::PropertyCallbackInfo<v8::Array> &info) /* {{{ */
  325. {
  326. // note: 'special' properties like 'constructor' are not enumerated.
  327. v8::Isolate *isolate = info.GetIsolate();
  328. v8::Local<v8::Object> self = info.Holder();
  329. v8::Local<v8::Array> result = v8::Array::New(isolate, 0);
  330. uint32_t result_len = 0;
  331. V8JS_TSRMLS_FETCH();
  332. zend_class_entry *ce;
  333. zend_function *method_ptr;
  334. HashTable *proptable;
  335. HashPosition pos;
  336. char *key = NULL;
  337. uint key_len;
  338. ulong index;
  339. zval *object = reinterpret_cast<zval *>(v8::External::Cast(*self->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY)))->Value());
  340. ce = Z_OBJCE_P(object);
  341. /* enumerate all methods */
  342. zend_hash_internal_pointer_reset_ex(&ce->function_table, &pos);
  343. for (;; zend_hash_move_forward_ex(&ce->function_table, &pos)) {
  344. if (zend_hash_get_current_key_ex(&ce->function_table, &key, &key_len, &index, 0, &pos) != HASH_KEY_IS_STRING ||
  345. zend_hash_get_current_data_ex(&ce->function_table, (void **) &method_ptr, &pos) == FAILURE
  346. ) {
  347. break;
  348. }
  349. if ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) == 0) {
  350. /* Allow only public methods */
  351. continue;
  352. }
  353. if ((method_ptr->common.fn_flags & (ZEND_ACC_CTOR|ZEND_ACC_DTOR|ZEND_ACC_CLONE)) != 0) {
  354. /* no __construct, __destruct(), or __clone() functions */
  355. continue;
  356. }
  357. // hide (do not enumerate) other PHP magic functions
  358. if (IS_MAGIC_FUNC(ZEND_CALLSTATIC_FUNC_NAME) ||
  359. IS_MAGIC_FUNC(ZEND_SLEEP_FUNC_NAME) ||
  360. IS_MAGIC_FUNC(ZEND_WAKEUP_FUNC_NAME) ||
  361. IS_MAGIC_FUNC(ZEND_SET_STATE_FUNC_NAME) ||
  362. IS_MAGIC_FUNC(ZEND_GET_FUNC_NAME) ||
  363. IS_MAGIC_FUNC(ZEND_SET_FUNC_NAME) ||
  364. IS_MAGIC_FUNC(ZEND_UNSET_FUNC_NAME) ||
  365. IS_MAGIC_FUNC(ZEND_CALL_FUNC_NAME) ||
  366. IS_MAGIC_FUNC(ZEND_INVOKE_FUNC_NAME) ||
  367. IS_MAGIC_FUNC(ZEND_ISSET_FUNC_NAME)) {
  368. continue;
  369. }
  370. v8::Local<v8::String> method_name = V8JS_STR(method_ptr->common.function_name);
  371. // rename PHP special method names to JS equivalents.
  372. if (IS_MAGIC_FUNC(ZEND_TOSTRING_FUNC_NAME)) {
  373. method_name = V8JS_SYM("toString");
  374. }
  375. result->Set(result_len++, method_name);
  376. }
  377. /* enumerate all properties */
  378. /* Z_OBJPROP uses the get_properties handler */
  379. proptable = Z_OBJPROP_P(object);
  380. zend_hash_internal_pointer_reset_ex(proptable, &pos);
  381. for (;; zend_hash_move_forward_ex(proptable, &pos)) {
  382. int i = zend_hash_get_current_key_ex(proptable, &key, &key_len, &index, 0, &pos);
  383. if (i == HASH_KEY_NON_EXISTANT)
  384. break;
  385. // for consistency with the 'in' operator, skip properties whose
  386. // value IS_NULL (like isset does)
  387. zval **data;
  388. if (zend_hash_get_current_data_ex(proptable, (void **) &data, &pos) == SUCCESS &&
  389. ZVAL_IS_NULL(*data))
  390. continue;
  391. if (i == HASH_KEY_IS_STRING) {
  392. /* skip protected and private members */
  393. if (key[0] == '\0') {
  394. continue;
  395. }
  396. // prefix enumerated property names with '$' so they can be
  397. // dereferenced unambiguously (ie, don't conflict with method
  398. // names)
  399. char *prefixed = static_cast<char *>(emalloc(key_len + 1));
  400. prefixed[0] = '$';
  401. strncpy(prefixed + 1, key, key_len);
  402. result->Set(result_len++, V8JS_STRL(prefixed, key_len));
  403. efree(prefixed);
  404. } else {
  405. // even numeric indices are enumerated as strings in JavaScript
  406. result->Set(result_len++, V8JS_FLOAT((double) index)->ToString());
  407. }
  408. }
  409. /* done */
  410. info.GetReturnValue().Set(result);
  411. }
  412. /* }}} */
  413. static void php_v8js_invoke_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  414. {
  415. v8::Isolate *isolate = info.GetIsolate();
  416. v8::Local<v8::Object> self = info.Holder();
  417. v8::Local<v8::Function> cb = v8::Local<v8::Function>::Cast(info.Data());
  418. int argc = info.Length(), i;
  419. v8::Local<v8::Value> *argv = static_cast<v8::Local<v8::Value> *>(alloca(sizeof(v8::Local<v8::Value>) * argc));
  420. v8::Local<v8::Value> result;
  421. V8JS_TSRMLS_FETCH();
  422. for (i=0; i<argc; i++) {
  423. new(&argv[i]) v8::Local<v8::Value>;
  424. argv[i] = info[i];
  425. }
  426. if (info.IsConstructCall()) {
  427. php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData(0);
  428. v8::String::Utf8Value str(self->GetConstructorName()->ToString());
  429. const char *constructor_name = ToCString(str);
  430. zend_class_entry **pce;
  431. zend_lookup_class(constructor_name, str.length(), &pce TSRMLS_CC);
  432. v8::Local<v8::FunctionTemplate> new_tpl;
  433. new_tpl = v8::Local<v8::FunctionTemplate>::New
  434. (isolate, ctx->template_cache.at((*pce)->name));
  435. result = new_tpl->GetFunction()->NewInstance(argc, argv);
  436. } else {
  437. result = cb->Call(self, argc, argv);
  438. }
  439. info.GetReturnValue().Set(result);
  440. }
  441. /* }}} */
  442. // this is a magic '__call' implementation for PHP classes which don't actually
  443. // have a '__call' magic function. This way we can always force a method
  444. // call (as opposed to a property get) from JavaScript using __call.
  445. static void php_v8js_fake_call_impl(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  446. {
  447. v8::Isolate *isolate = info.GetIsolate();
  448. v8::Local<v8::Object> self = info.Holder();
  449. v8::Handle<v8::Value> return_value;
  450. char *error;
  451. int error_len;
  452. V8JS_TSRMLS_FETCH();
  453. zend_class_entry *ce;
  454. zval *object = reinterpret_cast<zval *>(v8::External::Cast(*self->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY)))->Value());
  455. ce = Z_OBJCE_P(object);
  456. // first arg is method name, second arg is array of args.
  457. if (info.Length() < 2) {
  458. error_len = spprintf(&error, 0,
  459. "%s::__call expects 2 parameters, %d given",
  460. ce->name, (int) info.Length());
  461. return_value = V8JS_THROW(isolate, TypeError, error, error_len);
  462. efree(error);
  463. info.GetReturnValue().Set(return_value);
  464. return;
  465. }
  466. if (!info[1]->IsArray()) {
  467. error_len = spprintf(&error, 0,
  468. "%s::__call expects 2nd parameter to be an array",
  469. ce->name);
  470. return_value = V8JS_THROW(isolate, TypeError, error, error_len);
  471. efree(error);
  472. info.GetReturnValue().Set(return_value);
  473. return;
  474. }
  475. v8::String::Utf8Value str(info[0]->ToString());
  476. const char *method_name = ToCString(str);
  477. uint method_name_len = strlen(method_name);
  478. v8::Local<v8::Array> args = v8::Local<v8::Array>::Cast(info[1]);
  479. if (args->Length() > 1000000) {
  480. // prevent overflow, since args->Length() is a uint32_t and args
  481. // in the Function->Call method below is a (signed) int.
  482. error_len = spprintf(&error, 0,
  483. "%s::__call expects fewer than a million arguments",
  484. ce->name);
  485. return_value = V8JS_THROW(isolate, TypeError, error, error_len);
  486. efree(error);
  487. info.GetReturnValue().Set(return_value);
  488. return;
  489. }
  490. // okay, look up the method name and manually invoke it.
  491. const zend_object_handlers *h = Z_OBJ_HT_P(object);
  492. zend_function *method_ptr =
  493. h->get_method(&object, (char*)method_name, method_name_len
  494. ZEND_HASH_KEY_NULL TSRMLS_CC);
  495. if (method_ptr == NULL ||
  496. (method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) == 0 ||
  497. (method_ptr->common.fn_flags & (ZEND_ACC_CTOR|ZEND_ACC_DTOR|ZEND_ACC_CLONE)) != 0) {
  498. error_len = spprintf(&error, 0,
  499. "%s::__call to %s method %s", ce->name,
  500. (method_ptr == NULL) ? "undefined" : "non-public", method_name);
  501. return_value = V8JS_THROW(isolate, TypeError, error, error_len);
  502. efree(error);
  503. info.GetReturnValue().Set(return_value);
  504. return;
  505. }
  506. v8::Local<v8::FunctionTemplate> tmpl =
  507. v8::Local<v8::FunctionTemplate>::New
  508. (isolate, *reinterpret_cast<v8js_tmpl_t *>(self->GetAlignedPointerFromInternalField(0)));
  509. // use php_v8js_php_callback to actually execute the method
  510. v8::Local<v8::Function> cb = PHP_V8JS_CALLBACK(isolate, method_ptr, tmpl);
  511. uint32_t i, argc = args->Length();
  512. v8::Local<v8::Value> *argv = static_cast<v8::Local<v8::Value> *>(alloca(sizeof(v8::Local<v8::Value>) * argc));
  513. for (i=0; i<argc; i++) {
  514. new(&argv[i]) v8::Local<v8::Value>;
  515. argv[i] = args->Get(i);
  516. }
  517. return_value = cb->Call(info.This(), (int) argc, argv);
  518. info.GetReturnValue().Set(return_value);
  519. }
  520. /* }}} */
  521. typedef enum {
  522. V8JS_PROP_GETTER,
  523. V8JS_PROP_SETTER,
  524. V8JS_PROP_QUERY,
  525. V8JS_PROP_DELETER
  526. } property_op_t;
  527. /* This method handles named property and method get/set/query/delete. */
  528. template<typename T>
  529. static inline v8::Local<v8::Value> php_v8js_named_property_callback(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<T> &info, property_op_t callback_type, v8::Local<v8::Value> set_value = v8::Local<v8::Value>()) /* {{{ */
  530. {
  531. v8::Isolate *isolate = info.GetIsolate();
  532. v8::String::Utf8Value cstr(property);
  533. const char *name = ToCString(cstr);
  534. uint name_len = strlen(name);
  535. char *lower = estrndup(name, name_len);
  536. const char *method_name;
  537. uint method_name_len;
  538. v8::Local<v8::Object> self = info.Holder();
  539. v8::Local<v8::Value> ret_value;
  540. v8::Local<v8::Function> cb;
  541. V8JS_TSRMLS_FETCH();
  542. zend_class_entry *scope, *ce;
  543. zend_function *method_ptr = NULL;
  544. zval *php_value;
  545. zval *object = reinterpret_cast<zval *>(v8::External::Cast(*self->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY)))->Value());
  546. v8::Local<v8::FunctionTemplate> tmpl =
  547. v8::Local<v8::FunctionTemplate>::New
  548. (isolate, *reinterpret_cast<v8js_tmpl_t *>(self->GetAlignedPointerFromInternalField(0)));
  549. ce = scope = Z_OBJCE_P(object);
  550. /* First, check the (case-insensitive) method table */
  551. php_strtolower(lower, name_len);
  552. method_name = lower;
  553. method_name_len = name_len;
  554. // toString() -> __tostring()
  555. if (name_len == 8 && strcmp(name, "toString") == 0) {
  556. method_name = ZEND_TOSTRING_FUNC_NAME;
  557. method_name_len = sizeof(ZEND_TOSTRING_FUNC_NAME) - 1;
  558. }
  559. bool is_constructor = (name_len == 11 && strcmp(name, "constructor") == 0);
  560. bool is_magic_call = (method_name_len == 6 && strcmp(method_name, "__call") == 0);
  561. if (is_constructor ||
  562. (name[0] != '$' /* leading '$' means property, not method */ &&
  563. zend_hash_find(&ce->function_table, method_name, method_name_len + 1, (void**)&method_ptr) == SUCCESS &&
  564. ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) != 0) && /* Allow only public methods */
  565. ((method_ptr->common.fn_flags & (ZEND_ACC_CTOR|ZEND_ACC_DTOR|ZEND_ACC_CLONE)) == 0) /* no __construct, __destruct(), or __clone() functions */
  566. ) || (method_ptr=NULL, is_magic_call)
  567. ) {
  568. if (callback_type == V8JS_PROP_GETTER) {
  569. if (is_constructor) {
  570. // Don't set a return value here, i.e. indicate that we don't
  571. // have a special value. V8 "knows" the constructor anyways
  572. // (from the template) and will use that.
  573. } else {
  574. if (is_magic_call && method_ptr==NULL) {
  575. // Fake __call implementation
  576. // (only use this if method_ptr==NULL, which means
  577. // there is no actual PHP __call() implementation)
  578. v8::Local<v8::Function> cb =
  579. v8::FunctionTemplate::New(isolate,
  580. php_v8js_fake_call_impl, V8JS_NULL,
  581. v8::Signature::New(isolate, tmpl))->GetFunction();
  582. cb->SetName(property);
  583. ret_value = cb;
  584. } else {
  585. ret_value = PHP_V8JS_CALLBACK(isolate, method_ptr, tmpl);
  586. }
  587. }
  588. } else if (callback_type == V8JS_PROP_QUERY) {
  589. // methods are not enumerable
  590. ret_value = V8JS_UINT(v8::ReadOnly|v8::DontEnum|v8::DontDelete);
  591. } else if (callback_type == V8JS_PROP_SETTER) {
  592. ret_value = set_value; // lie. this field is read-only.
  593. } else if (callback_type == V8JS_PROP_DELETER) {
  594. ret_value = V8JS_BOOL(false);
  595. } else {
  596. /* shouldn't reach here! but bail safely */
  597. ret_value = v8::Handle<v8::Value>();
  598. }
  599. } else {
  600. if (name[0]=='$') {
  601. // this is a property (not a method)
  602. name++; name_len--;
  603. }
  604. if (callback_type == V8JS_PROP_GETTER) {
  605. /* Nope, not a method -- must be a (case-sensitive) property */
  606. zval zname;
  607. INIT_ZVAL(zname);
  608. ZVAL_STRINGL(&zname, name, name_len, 0);
  609. zend_property_info *property_info = zend_get_property_info(ce, &zname, 1 TSRMLS_CC);
  610. if(property_info && property_info->flags & ZEND_ACC_PUBLIC) {
  611. php_value = zend_read_property(NULL, object, V8JS_CONST name, name_len, true TSRMLS_CC);
  612. // special case uninitialized_zval_ptr and return an empty value
  613. // (indicating that we don't intercept this property) if the
  614. // property doesn't exist.
  615. if (php_value == EG(uninitialized_zval_ptr)) {
  616. ret_value = v8::Handle<v8::Value>();
  617. } else {
  618. // wrap it
  619. ret_value = zval_to_v8js(php_value, isolate TSRMLS_CC);
  620. /* We don't own the reference to php_value... unless the
  621. * returned refcount was 0, in which case the below code
  622. * will free it. */
  623. zval_add_ref(&php_value);
  624. zval_ptr_dtor(&php_value);
  625. }
  626. }
  627. else if (zend_hash_find(&ce->function_table, "__get", 6, (void**)&method_ptr) == SUCCESS
  628. /* Allow only public methods */
  629. && ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) != 0)) {
  630. /* Okay, let's call __get. */
  631. zend_fcall_info fci;
  632. zval fmember;
  633. INIT_ZVAL(fmember);
  634. ZVAL_STRING(&fmember, "__get", 0);
  635. fci.size = sizeof(fci);
  636. fci.function_table = &ce->function_table;
  637. fci.function_name = &fmember;
  638. fci.symbol_table = NULL;
  639. fci.retval_ptr_ptr = &php_value;
  640. zval *zname_ptr = &zname;
  641. zval **zname_ptr_ptr = &zname_ptr;
  642. fci.param_count = 1;
  643. fci.params = &zname_ptr_ptr;
  644. fci.object_ptr = object;
  645. fci.no_separation = 0;
  646. zend_call_function(&fci, NULL TSRMLS_CC);
  647. ret_value = zval_to_v8js(php_value, isolate TSRMLS_CC);
  648. zval_ptr_dtor(&php_value);
  649. }
  650. } else if (callback_type == V8JS_PROP_SETTER) {
  651. MAKE_STD_ZVAL(php_value);
  652. if (v8js_to_zval(set_value, php_value, 0, isolate TSRMLS_CC) != SUCCESS) {
  653. ret_value = v8::Handle<v8::Value>();
  654. }
  655. else {
  656. zval zname;
  657. INIT_ZVAL(zname);
  658. ZVAL_STRINGL(&zname, name, name_len, 0);
  659. zend_property_info *property_info = zend_get_property_info(ce, &zname, 1 TSRMLS_CC);
  660. if(property_info && property_info->flags & ZEND_ACC_PUBLIC) {
  661. zend_update_property(scope, object, V8JS_CONST name, name_len, php_value TSRMLS_CC);
  662. ret_value = set_value;
  663. }
  664. else if (zend_hash_find(&ce->function_table, "__set", 6, (void**)&method_ptr) == SUCCESS
  665. /* Allow only public methods */
  666. && ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) != 0)) {
  667. /* Okay, let's call __set. */
  668. zend_fcall_info fci;
  669. zval fmember;
  670. INIT_ZVAL(fmember);
  671. ZVAL_STRING(&fmember, "__set", 0);
  672. zval *php_ret_value;
  673. fci.size = sizeof(fci);
  674. fci.function_table = &ce->function_table;
  675. fci.function_name = &fmember;
  676. fci.symbol_table = NULL;
  677. fci.retval_ptr_ptr = &php_ret_value;
  678. zval *zname_ptr = &zname;
  679. zval **params[2];
  680. fci.param_count = 2;
  681. fci.params = params;
  682. fci.params[0] = &zname_ptr;
  683. fci.params[1] = &php_value;
  684. fci.object_ptr = object;
  685. fci.no_separation = 1;
  686. zend_call_function(&fci, NULL TSRMLS_CC);
  687. ret_value = zval_to_v8js(php_ret_value, isolate TSRMLS_CC);
  688. zval_ptr_dtor(&php_ret_value);
  689. }
  690. }
  691. // if PHP wanted to hold on to this value, update_property would
  692. // have bumped the refcount
  693. zval_ptr_dtor(&php_value);
  694. } else if (callback_type == V8JS_PROP_QUERY ||
  695. callback_type == V8JS_PROP_DELETER) {
  696. const zend_object_handlers *h = Z_OBJ_HT_P(object);
  697. zval *prop;
  698. MAKE_STD_ZVAL(prop);
  699. ZVAL_STRINGL(prop, name, name_len, 1);
  700. if (callback_type == V8JS_PROP_QUERY) {
  701. if (h->has_property(object, prop, 0 ZEND_HASH_KEY_NULL TSRMLS_CC)) {
  702. ret_value = V8JS_UINT(v8::None);
  703. } else {
  704. ret_value = v8::Handle<v8::Value>(); // empty handle
  705. }
  706. } else {
  707. zend_property_info *property_info = zend_get_property_info(ce, prop, 1 TSRMLS_CC);
  708. if(property_info && property_info->flags & ZEND_ACC_PUBLIC) {
  709. h->unset_property(object, prop ZEND_HASH_KEY_NULL TSRMLS_CC);
  710. ret_value = V8JS_BOOL(true);
  711. }
  712. else {
  713. ret_value = v8::Handle<v8::Value>(); // empty handle
  714. }
  715. }
  716. zval_ptr_dtor(&prop);
  717. } else {
  718. /* shouldn't reach here! but bail safely */
  719. ret_value = v8::Handle<v8::Value>();
  720. }
  721. }
  722. efree(lower);
  723. return ret_value;
  724. }
  725. /* }}} */
  726. static void php_v8js_named_property_getter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */
  727. {
  728. info.GetReturnValue().Set(php_v8js_named_property_callback(property, info, V8JS_PROP_GETTER));
  729. }
  730. /* }}} */
  731. static void php_v8js_named_property_setter(v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */
  732. {
  733. info.GetReturnValue().Set(php_v8js_named_property_callback(property, info, V8JS_PROP_SETTER, value));
  734. }
  735. /* }}} */
  736. static void php_v8js_named_property_query(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Integer> &info) /* {{{ */
  737. {
  738. v8::Local<v8::Value> r = php_v8js_named_property_callback(property, info, V8JS_PROP_QUERY);
  739. if (!r.IsEmpty()) {
  740. info.GetReturnValue().Set(r->ToInteger());
  741. }
  742. }
  743. /* }}} */
  744. static void php_v8js_named_property_deleter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Boolean> &info) /* {{{ */
  745. {
  746. v8::Local<v8::Value> r = php_v8js_named_property_callback(property, info, V8JS_PROP_DELETER);
  747. if (!r.IsEmpty()) {
  748. info.GetReturnValue().Set(r->ToBoolean());
  749. }
  750. }
  751. /* }}} */
  752. static v8::Handle<v8::Value> php_v8js_hash_to_jsobj(zval *value, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  753. {
  754. v8::Handle<v8::Object> newobj;
  755. int i;
  756. char *key = NULL;
  757. ulong index;
  758. uint key_len;
  759. HashTable *myht;
  760. HashPosition pos;
  761. zend_class_entry *ce = NULL;
  762. if (Z_TYPE_P(value) == IS_ARRAY) {
  763. myht = HASH_OF(value);
  764. } else {
  765. myht = Z_OBJPROP_P(value);
  766. ce = Z_OBJCE_P(value);
  767. }
  768. /* Prevent recursion */
  769. if (myht && myht->nApplyCount > 1) {
  770. return V8JS_NULL;
  771. }
  772. /* Check for ArrayAccess object */
  773. if (V8JSG(use_array_access) && ce) {
  774. bool has_array_access = false;
  775. bool has_countable = false;
  776. for (int i = 0; i < ce->num_interfaces; i ++) {
  777. if (strcmp (ce->interfaces[i]->name, "ArrayAccess") == 0) {
  778. has_array_access = true;
  779. }
  780. else if (strcmp (ce->interfaces[i]->name, "Countable") == 0) {
  781. has_countable = true;
  782. }
  783. }
  784. if(has_array_access && has_countable) {
  785. return php_v8js_array_access_to_jsobj(value, isolate TSRMLS_CC);
  786. }
  787. }
  788. /* Object methods */
  789. if (ce == php_ce_v8_function) {
  790. php_v8js_object *c = (php_v8js_object *) zend_object_store_get_object(value TSRMLS_CC);
  791. if(isolate != c->ctx->isolate) {
  792. php_error_docref(NULL TSRMLS_CC, E_WARNING, "V8Function object passed to wrong V8Js instance");
  793. return V8JS_NULL;
  794. }
  795. v8::Local<v8::Value> v8obj = v8::Local<v8::Value>::New(isolate, c->v8obj);
  796. return v8obj;
  797. } else if (ce) {
  798. php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData(0);
  799. v8::Local<v8::FunctionTemplate> new_tpl;
  800. v8js_tmpl_t *persist_tpl_;
  801. try {
  802. new_tpl = v8::Local<v8::FunctionTemplate>::New
  803. (isolate, ctx->template_cache.at(ce->name));
  804. }
  805. catch (const std::out_of_range &) {
  806. /* No cached v8::FunctionTemplate available as of yet, create one. */
  807. new_tpl = v8::FunctionTemplate::New(isolate, 0);
  808. new_tpl->SetClassName(V8JS_STRL(ce->name, ce->name_length));
  809. new_tpl->InstanceTemplate()->SetInternalFieldCount(1);
  810. if (ce == zend_ce_closure) {
  811. /* Got a closure, mustn't cache ... */
  812. persist_tpl_ = new v8js_tmpl_t(isolate, new_tpl);
  813. /* We'll free persist_tpl_ via php_v8js_weak_closure_callback, below */
  814. new_tpl->InstanceTemplate()->SetCallAsFunctionHandler(php_v8js_php_callback);
  815. } else {
  816. /* Add new v8::FunctionTemplate to tpl_map, as long as it is not a closure. */
  817. persist_tpl_ = &ctx->template_cache[ce->name];
  818. persist_tpl_->Reset(isolate, new_tpl);
  819. /* We'll free persist_tpl_ when template_cache is destroyed */
  820. // Finish setup of new_tpl
  821. new_tpl->InstanceTemplate()->SetNamedPropertyHandler
  822. (php_v8js_named_property_getter, /* getter */
  823. php_v8js_named_property_setter, /* setter */
  824. php_v8js_named_property_query, /* query */
  825. php_v8js_named_property_deleter, /* deleter */
  826. php_v8js_named_property_enumerator, /* enumerator */
  827. V8JS_NULL /* data */
  828. );
  829. // add __invoke() handler
  830. zend_function *invoke_method_ptr;
  831. if (zend_hash_find(&ce->function_table, ZEND_INVOKE_FUNC_NAME,
  832. sizeof(ZEND_INVOKE_FUNC_NAME),
  833. (void**)&invoke_method_ptr) == SUCCESS &&
  834. invoke_method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) {
  835. new_tpl->InstanceTemplate()->SetCallAsFunctionHandler(php_v8js_invoke_callback, PHP_V8JS_CALLBACK(isolate, invoke_method_ptr, new_tpl));
  836. }
  837. }
  838. v8::Local<v8::Array> call_handler_data = v8::Array::New(isolate, 2);
  839. call_handler_data->Set(0, v8::External::New(isolate, persist_tpl_));
  840. call_handler_data->Set(1, v8::External::New(isolate, ce));
  841. new_tpl->SetCallHandler(php_v8js_construct_callback, call_handler_data);
  842. }
  843. // Create v8 wrapper object
  844. v8::Handle<v8::Value> external = v8::External::New(isolate, value);
  845. newobj = new_tpl->GetFunction()->NewInstance(1, &external);
  846. if (ce == zend_ce_closure) {
  847. // free uncached function template when object is freed
  848. ctx->weak_closures[persist_tpl_].Reset(isolate, newobj);
  849. ctx->weak_closures[persist_tpl_].SetWeak(persist_tpl_, php_v8js_weak_closure_callback);
  850. }
  851. } else {
  852. // @todo re-use template likewise
  853. v8::Local<v8::FunctionTemplate> new_tpl = v8::FunctionTemplate::New(isolate, 0);
  854. new_tpl->SetClassName(V8JS_SYM("Array"));
  855. newobj = new_tpl->InstanceTemplate()->NewInstance();
  856. }
  857. /* Object properties */
  858. i = myht ? zend_hash_num_elements(myht) : 0;
  859. if (i > 0 && !ce)
  860. {
  861. zval **data;
  862. HashTable *tmp_ht;
  863. zend_hash_internal_pointer_reset_ex(myht, &pos);
  864. for (;; zend_hash_move_forward_ex(myht, &pos)) {
  865. i = zend_hash_get_current_key_ex(myht, &key, &key_len, &index, 0, &pos);
  866. if (i == HASH_KEY_NON_EXISTANT)
  867. break;
  868. if (zend_hash_get_current_data_ex(myht, (void **) &data, &pos) == SUCCESS)
  869. {
  870. tmp_ht = HASH_OF(*data);
  871. if (tmp_ht) {
  872. tmp_ht->nApplyCount++;
  873. }
  874. if (i == HASH_KEY_IS_STRING)
  875. {
  876. if (key[0] == '\0' && Z_TYPE_P(value) == IS_OBJECT) {
  877. /* Skip protected and private members. */
  878. if (tmp_ht) {
  879. tmp_ht->nApplyCount--;
  880. }
  881. continue;
  882. }
  883. newobj->Set(V8JS_STRL(key, key_len - 1), zval_to_v8js(*data, isolate TSRMLS_CC));
  884. } else {
  885. newobj->Set(index, zval_to_v8js(*data, isolate TSRMLS_CC));
  886. }
  887. if (tmp_ht) {
  888. tmp_ht->nApplyCount--;
  889. }
  890. }
  891. }
  892. }
  893. return newobj;
  894. }
  895. /* }}} */
  896. static v8::Handle<v8::Value> php_v8js_hash_to_jsarr(zval *value, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  897. {
  898. HashTable *myht = HASH_OF(value);
  899. int i = myht ? zend_hash_num_elements(myht) : 0;
  900. /* Return object if dealing with assoc array */
  901. if (i > 0 && _php_v8js_is_assoc_array(myht TSRMLS_CC)) {
  902. return php_v8js_hash_to_jsobj(value, isolate TSRMLS_CC);
  903. }
  904. v8::Local<v8::Array> newarr;
  905. /* Prevent recursion */
  906. if (myht && myht->nApplyCount > 1) {
  907. return V8JS_NULL;
  908. }
  909. newarr = v8::Array::New(isolate, i);
  910. if (i > 0)
  911. {
  912. zval **data;
  913. ulong index = 0;
  914. HashTable *tmp_ht;
  915. HashPosition pos;
  916. for (zend_hash_internal_pointer_reset_ex(myht, &pos);
  917. SUCCESS == zend_hash_get_current_data_ex(myht, (void **) &data, &pos);
  918. zend_hash_move_forward_ex(myht, &pos)
  919. ) {
  920. tmp_ht = HASH_OF(*data);
  921. if (tmp_ht) {
  922. tmp_ht->nApplyCount++;
  923. }
  924. newarr->Set(index++, zval_to_v8js(*data, isolate TSRMLS_CC));
  925. if (tmp_ht) {
  926. tmp_ht->nApplyCount--;
  927. }
  928. }
  929. }
  930. return newarr;
  931. }
  932. /* }}} */
  933. v8::Handle<v8::Value> zval_to_v8js(zval *value, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  934. {
  935. v8::Handle<v8::Value> jsValue;
  936. long v;
  937. zend_class_entry *ce;
  938. switch (Z_TYPE_P(value))
  939. {
  940. case IS_ARRAY:
  941. jsValue = php_v8js_hash_to_jsarr(value, isolate TSRMLS_CC);
  942. break;
  943. case IS_OBJECT:
  944. if (V8JSG(use_date)) {
  945. ce = php_date_get_date_ce();
  946. if (instanceof_function(Z_OBJCE_P(value), ce TSRMLS_CC)) {
  947. zval *dtval;
  948. zend_call_method_with_0_params(&value, NULL, NULL, "getTimestamp", &dtval);
  949. if (dtval) {
  950. jsValue = V8JS_DATE(((double)Z_LVAL_P(dtval) * 1000.0));
  951. zval_ptr_dtor(&dtval);
  952. }
  953. else
  954. jsValue = V8JS_NULL;
  955. } else
  956. jsValue = php_v8js_hash_to_jsobj(value, isolate TSRMLS_CC);
  957. } else
  958. jsValue = php_v8js_hash_to_jsobj(value, isolate TSRMLS_CC);
  959. break;
  960. case IS_STRING:
  961. jsValue = V8JS_STRL(Z_STRVAL_P(value), Z_STRLEN_P(value));
  962. break;
  963. case IS_LONG:
  964. v = Z_LVAL_P(value);
  965. /* On Windows there are max and min macros, which would clobber the
  966. * method names of std::numeric_limits< > otherwise. */
  967. #undef max
  968. #undef min
  969. if (v < - std::numeric_limits<int32_t>::min() || v > std::numeric_limits<int32_t>::max()) {
  970. jsValue = V8JS_FLOAT((double)v);
  971. } else {
  972. jsValue = V8JS_INT(v);
  973. }
  974. break;
  975. case IS_DOUBLE:
  976. jsValue = V8JS_FLOAT(Z_DVAL_P(value));
  977. break;
  978. case IS_BOOL:
  979. jsValue = V8JS_BOOL(Z_BVAL_P(value));
  980. break;
  981. default:
  982. case IS_NULL:
  983. jsValue = V8JS_NULL;
  984. break;
  985. }
  986. return jsValue;
  987. }
  988. /* }}} */
  989. int v8js_to_zval(v8::Handle<v8::Value> jsValue, zval *return_value, int flags, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  990. {
  991. if (jsValue->IsString())
  992. {
  993. v8::String::Utf8Value str(jsValue);
  994. const char *cstr = ToCString(str);
  995. RETVAL_STRINGL(cstr, jsValue->ToString()->Utf8Length(), 1);
  996. // RETVAL_STRING(cstr, 1);
  997. }
  998. else if (jsValue->IsBoolean())
  999. {
  1000. RETVAL_BOOL(jsValue->Uint32Value());
  1001. }
  1002. else if (jsValue->IsInt32() || jsValue->IsUint32())
  1003. {
  1004. RETVAL_LONG((long) jsValue->IntegerValue());
  1005. }
  1006. else if (jsValue->IsNumber())
  1007. {
  1008. RETVAL_DOUBLE(jsValue->NumberValue());
  1009. }
  1010. else if (jsValue->IsDate()) /* Return as a PHP DateTime object */
  1011. {
  1012. v8::String::Utf8Value str(jsValue);
  1013. const char *cstr = ToCString(str);
  1014. /* cstr has two timezone specifications:
  1015. *
  1016. * example from Linux:
  1017. * Mon Sep 08 1975 09:00:00 GMT+0000 (UTC)
  1018. *
  1019. * example from Windows:
  1020. * Mon Sep 08 1975 11:00:00 GMT+0200 (W. Europe Daylight Time)
  1021. *
  1022. * ... problem is, that PHP can't parse the second timezone
  1023. * specification as returned by v8 running on Windows. And as a
  1024. * matter of that fails due to inconsistent second timezone spec
  1025. */
  1026. char *date_str = estrdup(cstr);
  1027. char *paren_ptr = strchr(date_str, '(');
  1028. if (paren_ptr != NULL) {
  1029. *paren_ptr = 0;
  1030. }
  1031. zend_class_entry *ce = php_date_get_date_ce();
  1032. #if PHP_VERSION_ID < 50304
  1033. zval *param;
  1034. MAKE_STD_ZVAL(param);
  1035. ZVAL_STRING(param, date_str, 0);
  1036. object_init_ex(return_value, ce TSRMLS_CC);
  1037. zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, param);
  1038. zval_ptr_dtor(&param);
  1039. if (EG(exception)) {
  1040. return FAILURE;
  1041. }
  1042. #else
  1043. php_date_instantiate(ce, return_value TSRMLS_CC);
  1044. if (!php_date_initialize((php_date_obj *) zend_object_store_get_object(return_value TSRMLS_CC), date_str, strlen(date_str), NULL, NULL, 0 TSRMLS_CC)) {
  1045. efree(date_str);
  1046. return FAILURE;
  1047. }
  1048. efree(date_str);
  1049. #endif
  1050. }
  1051. else if (jsValue->IsObject())
  1052. {
  1053. v8::Handle<v8::Object> self = v8::Handle<v8::Object>::Cast(jsValue);
  1054. // if this is a wrapped PHP object, then just unwrap it.
  1055. v8::Local<v8::Value> php_object = self->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY));
  1056. if (!php_object.IsEmpty()) {
  1057. zval *object = reinterpret_cast<zval *>(v8::External::Cast(*php_object)->Value());
  1058. RETVAL_ZVAL(object, 1, 0);
  1059. return SUCCESS;
  1060. }
  1061. if ((flags & V8JS_FLAG_FORCE_ARRAY) || jsValue->IsArray()) {
  1062. array_init(return_value);
  1063. return php_v8js_v8_get_properties_hash(jsValue, Z_ARRVAL_P(return_value), flags, isolate TSRMLS_CC);
  1064. } else {
  1065. php_v8js_create_v8(return_value, jsValue, flags, isolate TSRMLS_CC);
  1066. return SUCCESS;
  1067. }
  1068. }
  1069. else /* types External, RegExp, Undefined and Null are considered NULL */
  1070. {
  1071. RETVAL_NULL();
  1072. }
  1073. return SUCCESS;
  1074. }
  1075. /* }}} */
  1076. /*
  1077. * Local variables:
  1078. * tab-width: 4
  1079. * c-basic-offset: 4
  1080. * End:
  1081. * vim600: noet sw=4 ts=4 fdm=marker
  1082. * vim<600: noet sw=4 ts=4
  1083. */