v8js_convert.cc 37 KB

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