v8js_convert.cc 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  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. 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[key_len + 1];
  400. prefixed[0] = '$';
  401. strncpy(prefixed + 1, key, key_len);
  402. result->Set(result_len++, V8JS_STRL(prefixed, key_len));
  403. } else {
  404. // even numeric indices are enumerated as strings in JavaScript
  405. result->Set(result_len++, V8JS_FLOAT((double) index)->ToString());
  406. }
  407. }
  408. /* done */
  409. info.GetReturnValue().Set(result);
  410. }
  411. /* }}} */
  412. static void php_v8js_invoke_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  413. {
  414. v8::Isolate *isolate = info.GetIsolate();
  415. v8::Local<v8::Object> self = info.Holder();
  416. v8::Local<v8::Function> cb = v8::Local<v8::Function>::Cast(info.Data());
  417. int argc = info.Length(), i;
  418. v8::Local<v8::Value> argv[argc];
  419. v8::Local<v8::Value> result;
  420. V8JS_TSRMLS_FETCH();
  421. for (i=0; i<argc; i++) {
  422. argv[i] = info[i];
  423. }
  424. if (info.IsConstructCall()) {
  425. php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData(0);
  426. v8::String::Utf8Value str(self->GetConstructorName()->ToString());
  427. const char *constructor_name = ToCString(str);
  428. zend_class_entry **pce;
  429. zend_lookup_class(constructor_name, str.length(), &pce TSRMLS_CC);
  430. v8::Local<v8::FunctionTemplate> new_tpl;
  431. new_tpl = v8::Local<v8::FunctionTemplate>::New
  432. (isolate, ctx->template_cache.at((*pce)->name));
  433. result = new_tpl->GetFunction()->NewInstance(argc, argv);
  434. } else {
  435. result = cb->Call(self, argc, argv);
  436. }
  437. info.GetReturnValue().Set(result);
  438. }
  439. /* }}} */
  440. // this is a magic '__call' implementation for PHP classes which don't actually
  441. // have a '__call' magic function. This way we can always force a method
  442. // call (as opposed to a property get) from JavaScript using __call.
  443. static void php_v8js_fake_call_impl(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  444. {
  445. v8::Isolate *isolate = info.GetIsolate();
  446. v8::Local<v8::Object> self = info.Holder();
  447. v8::Handle<v8::Value> return_value;
  448. char *error;
  449. int error_len;
  450. V8JS_TSRMLS_FETCH();
  451. zend_class_entry *ce;
  452. zval *object = reinterpret_cast<zval *>(v8::External::Cast(*self->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY)))->Value());
  453. ce = Z_OBJCE_P(object);
  454. // first arg is method name, second arg is array of args.
  455. if (info.Length() < 2) {
  456. error_len = spprintf(&error, 0,
  457. "%s::__call expects 2 parameters, %d given",
  458. ce->name, (int) info.Length());
  459. return_value = V8JS_THROW(isolate, TypeError, error, error_len);
  460. efree(error);
  461. info.GetReturnValue().Set(return_value);
  462. return;
  463. }
  464. if (!info[1]->IsArray()) {
  465. error_len = spprintf(&error, 0,
  466. "%s::__call expects 2nd parameter to be an array",
  467. ce->name);
  468. return_value = V8JS_THROW(isolate, TypeError, error, error_len);
  469. efree(error);
  470. info.GetReturnValue().Set(return_value);
  471. return;
  472. }
  473. v8::String::Utf8Value str(info[0]->ToString());
  474. const char *method_name = ToCString(str);
  475. uint method_name_len = strlen(method_name);
  476. v8::Local<v8::Array> args = v8::Local<v8::Array>::Cast(info[1]);
  477. if (args->Length() > 1000000) {
  478. // prevent overflow, since args->Length() is a uint32_t and args
  479. // in the Function->Call method below is a (signed) int.
  480. error_len = spprintf(&error, 0,
  481. "%s::__call expects fewer than a million arguments",
  482. ce->name);
  483. return_value = V8JS_THROW(isolate, TypeError, error, error_len);
  484. efree(error);
  485. info.GetReturnValue().Set(return_value);
  486. return;
  487. }
  488. // okay, look up the method name and manually invoke it.
  489. const zend_object_handlers *h = Z_OBJ_HT_P(object);
  490. zend_function *method_ptr =
  491. h->get_method(&object, (char*)method_name, method_name_len
  492. ZEND_HASH_KEY_NULL TSRMLS_CC);
  493. if (method_ptr == NULL ||
  494. (method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) == 0 ||
  495. (method_ptr->common.fn_flags & (ZEND_ACC_CTOR|ZEND_ACC_DTOR|ZEND_ACC_CLONE)) != 0) {
  496. error_len = spprintf(&error, 0,
  497. "%s::__call to %s method %s", ce->name,
  498. (method_ptr == NULL) ? "undefined" : "non-public", method_name);
  499. return_value = V8JS_THROW(isolate, TypeError, error, error_len);
  500. efree(error);
  501. info.GetReturnValue().Set(return_value);
  502. return;
  503. }
  504. v8::Local<v8::FunctionTemplate> tmpl =
  505. v8::Local<v8::FunctionTemplate>::New
  506. (isolate, *reinterpret_cast<v8js_tmpl_t *>(self->GetAlignedPointerFromInternalField(0)));
  507. // use php_v8js_php_callback to actually execute the method
  508. v8::Local<v8::Function> cb = PHP_V8JS_CALLBACK(isolate, method_ptr, tmpl);
  509. uint32_t i, argc = args->Length();
  510. v8::Local<v8::Value> argv[argc];
  511. for (i=0; i<argc; i++) {
  512. argv[i] = args->Get(i);
  513. }
  514. return_value = cb->Call(info.This(), (int) argc, argv);
  515. info.GetReturnValue().Set(return_value);
  516. }
  517. /* }}} */
  518. typedef enum {
  519. V8JS_PROP_GETTER,
  520. V8JS_PROP_SETTER,
  521. V8JS_PROP_QUERY,
  522. V8JS_PROP_DELETER
  523. } property_op_t;
  524. /* This method handles named property and method get/set/query/delete. */
  525. template<typename T>
  526. 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>()) /* {{{ */
  527. {
  528. v8::Isolate *isolate = info.GetIsolate();
  529. v8::String::Utf8Value cstr(property);
  530. const char *name = ToCString(cstr);
  531. uint name_len = strlen(name);
  532. char *lower = estrndup(name, name_len);
  533. const char *method_name;
  534. uint method_name_len;
  535. v8::Local<v8::Object> self = info.Holder();
  536. v8::Local<v8::Value> ret_value;
  537. v8::Local<v8::Function> cb;
  538. V8JS_TSRMLS_FETCH();
  539. zend_class_entry *scope, *ce;
  540. zend_function *method_ptr = NULL;
  541. zval *php_value;
  542. zval *object = reinterpret_cast<zval *>(v8::External::Cast(*self->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY)))->Value());
  543. v8::Local<v8::FunctionTemplate> tmpl =
  544. v8::Local<v8::FunctionTemplate>::New
  545. (isolate, *reinterpret_cast<v8js_tmpl_t *>(self->GetAlignedPointerFromInternalField(0)));
  546. ce = scope = Z_OBJCE_P(object);
  547. /* First, check the (case-insensitive) method table */
  548. php_strtolower(lower, name_len);
  549. method_name = lower;
  550. method_name_len = name_len;
  551. // toString() -> __tostring()
  552. if (name_len == 8 && strcmp(name, "toString") == 0) {
  553. method_name = ZEND_TOSTRING_FUNC_NAME;
  554. method_name_len = sizeof(ZEND_TOSTRING_FUNC_NAME) - 1;
  555. }
  556. bool is_constructor = (name_len == 11 && strcmp(name, "constructor") == 0);
  557. bool is_magic_call = (method_name_len == 6 && strcmp(method_name, "__call") == 0);
  558. if (is_constructor ||
  559. (name[0] != '$' /* leading '$' means property, not method */ &&
  560. zend_hash_find(&ce->function_table, method_name, method_name_len + 1, (void**)&method_ptr) == SUCCESS &&
  561. ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) != 0) && /* Allow only public methods */
  562. ((method_ptr->common.fn_flags & (ZEND_ACC_CTOR|ZEND_ACC_DTOR|ZEND_ACC_CLONE)) == 0) /* no __construct, __destruct(), or __clone() functions */
  563. ) || (method_ptr=NULL, is_magic_call)
  564. ) {
  565. if (callback_type == V8JS_PROP_GETTER) {
  566. if (is_constructor) {
  567. // Don't set a return value here, i.e. indicate that we don't
  568. // have a special value. V8 "knows" the constructor anyways
  569. // (from the template) and will use that.
  570. } else {
  571. if (is_magic_call && method_ptr==NULL) {
  572. // Fake __call implementation
  573. // (only use this if method_ptr==NULL, which means
  574. // there is no actual PHP __call() implementation)
  575. v8::Local<v8::Function> cb =
  576. v8::FunctionTemplate::New(isolate,
  577. php_v8js_fake_call_impl, V8JS_NULL,
  578. v8::Signature::New(isolate, tmpl))->GetFunction();
  579. cb->SetName(property);
  580. ret_value = cb;
  581. } else {
  582. ret_value = PHP_V8JS_CALLBACK(isolate, method_ptr, tmpl);
  583. }
  584. }
  585. } else if (callback_type == V8JS_PROP_QUERY) {
  586. // methods are not enumerable
  587. ret_value = V8JS_UINT(v8::ReadOnly|v8::DontEnum|v8::DontDelete);
  588. } else if (callback_type == V8JS_PROP_SETTER) {
  589. ret_value = set_value; // lie. this field is read-only.
  590. } else if (callback_type == V8JS_PROP_DELETER) {
  591. ret_value = V8JS_BOOL(false);
  592. } else {
  593. /* shouldn't reach here! but bail safely */
  594. ret_value = v8::Handle<v8::Value>();
  595. }
  596. } else {
  597. if (name[0]=='$') {
  598. // this is a property (not a method)
  599. name++; name_len--;
  600. }
  601. if (callback_type == V8JS_PROP_GETTER) {
  602. /* Nope, not a method -- must be a (case-sensitive) property */
  603. zval zname;
  604. INIT_ZVAL(zname);
  605. ZVAL_STRINGL(&zname, name, name_len, 0);
  606. zend_property_info *property_info = zend_get_property_info(ce, &zname, 1 TSRMLS_CC);
  607. if(property_info && property_info->flags & ZEND_ACC_PUBLIC) {
  608. php_value = zend_read_property(NULL, object, V8JS_CONST name, name_len, true TSRMLS_CC);
  609. // special case uninitialized_zval_ptr and return an empty value
  610. // (indicating that we don't intercept this property) if the
  611. // property doesn't exist.
  612. if (php_value == EG(uninitialized_zval_ptr)) {
  613. ret_value = v8::Handle<v8::Value>();
  614. } else {
  615. // wrap it
  616. ret_value = zval_to_v8js(php_value, isolate TSRMLS_CC);
  617. /* We don't own the reference to php_value... unless the
  618. * returned refcount was 0, in which case the below code
  619. * will free it. */
  620. zval_add_ref(&php_value);
  621. zval_ptr_dtor(&php_value);
  622. }
  623. }
  624. else if (zend_hash_find(&ce->function_table, "__get", 6, (void**)&method_ptr) == SUCCESS
  625. /* Allow only public methods */
  626. && ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) != 0)) {
  627. /* Okay, let's call __get. */
  628. zend_fcall_info fci;
  629. zval fmember;
  630. INIT_ZVAL(fmember);
  631. ZVAL_STRING(&fmember, "__get", 0);
  632. fci.size = sizeof(fci);
  633. fci.function_table = &ce->function_table;
  634. fci.function_name = &fmember;
  635. fci.symbol_table = NULL;
  636. fci.retval_ptr_ptr = &php_value;
  637. zval *zname_ptr = &zname;
  638. zval **zname_ptr_ptr = &zname_ptr;
  639. fci.param_count = 1;
  640. fci.params = &zname_ptr_ptr;
  641. fci.object_ptr = object;
  642. fci.no_separation = 0;
  643. zend_call_function(&fci, NULL TSRMLS_CC);
  644. ret_value = zval_to_v8js(php_value, isolate TSRMLS_CC);
  645. zval_ptr_dtor(&php_value);
  646. }
  647. } else if (callback_type == V8JS_PROP_SETTER) {
  648. MAKE_STD_ZVAL(php_value);
  649. if (v8js_to_zval(set_value, php_value, 0, isolate TSRMLS_CC) != SUCCESS) {
  650. ret_value = v8::Handle<v8::Value>();
  651. }
  652. else {
  653. zval zname;
  654. INIT_ZVAL(zname);
  655. ZVAL_STRINGL(&zname, name, name_len, 0);
  656. zend_property_info *property_info = zend_get_property_info(ce, &zname, 1 TSRMLS_CC);
  657. if(property_info && property_info->flags & ZEND_ACC_PUBLIC) {
  658. zend_update_property(scope, object, V8JS_CONST name, name_len, php_value TSRMLS_CC);
  659. ret_value = set_value;
  660. }
  661. else if (zend_hash_find(&ce->function_table, "__set", 6, (void**)&method_ptr) == SUCCESS
  662. /* Allow only public methods */
  663. && ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) != 0)) {
  664. /* Okay, let's call __set. */
  665. zend_fcall_info fci;
  666. zval fmember;
  667. INIT_ZVAL(fmember);
  668. ZVAL_STRING(&fmember, "__set", 0);
  669. zval *php_ret_value;
  670. fci.size = sizeof(fci);
  671. fci.function_table = &ce->function_table;
  672. fci.function_name = &fmember;
  673. fci.symbol_table = NULL;
  674. fci.retval_ptr_ptr = &php_ret_value;
  675. zval *zname_ptr = &zname;
  676. zval **params[2];
  677. fci.param_count = 2;
  678. fci.params = params;
  679. fci.params[0] = &zname_ptr;
  680. fci.params[1] = &php_value;
  681. fci.object_ptr = object;
  682. fci.no_separation = 1;
  683. zend_call_function(&fci, NULL TSRMLS_CC);
  684. ret_value = zval_to_v8js(php_ret_value, isolate TSRMLS_CC);
  685. zval_ptr_dtor(&php_ret_value);
  686. }
  687. }
  688. // if PHP wanted to hold on to this value, update_property would
  689. // have bumped the refcount
  690. zval_ptr_dtor(&php_value);
  691. } else if (callback_type == V8JS_PROP_QUERY ||
  692. callback_type == V8JS_PROP_DELETER) {
  693. const zend_object_handlers *h = Z_OBJ_HT_P(object);
  694. zval *prop;
  695. MAKE_STD_ZVAL(prop);
  696. ZVAL_STRINGL(prop, name, name_len, 1);
  697. if (callback_type == V8JS_PROP_QUERY) {
  698. if (h->has_property(object, prop, 0 ZEND_HASH_KEY_NULL TSRMLS_CC)) {
  699. ret_value = V8JS_UINT(v8::None);
  700. } else {
  701. ret_value = v8::Handle<v8::Value>(); // empty handle
  702. }
  703. } else {
  704. zend_property_info *property_info = zend_get_property_info(ce, prop, 1 TSRMLS_CC);
  705. if(property_info && property_info->flags & ZEND_ACC_PUBLIC) {
  706. h->unset_property(object, prop ZEND_HASH_KEY_NULL TSRMLS_CC);
  707. ret_value = V8JS_BOOL(true);
  708. }
  709. else {
  710. ret_value = v8::Handle<v8::Value>(); // empty handle
  711. }
  712. }
  713. zval_ptr_dtor(&prop);
  714. } else {
  715. /* shouldn't reach here! but bail safely */
  716. ret_value = v8::Handle<v8::Value>();
  717. }
  718. }
  719. efree(lower);
  720. return ret_value;
  721. }
  722. /* }}} */
  723. static void php_v8js_named_property_getter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */
  724. {
  725. info.GetReturnValue().Set(php_v8js_named_property_callback(property, info, V8JS_PROP_GETTER));
  726. }
  727. /* }}} */
  728. static void php_v8js_named_property_setter(v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */
  729. {
  730. info.GetReturnValue().Set(php_v8js_named_property_callback(property, info, V8JS_PROP_SETTER, value));
  731. }
  732. /* }}} */
  733. static void php_v8js_named_property_query(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Integer> &info) /* {{{ */
  734. {
  735. v8::Local<v8::Value> r = php_v8js_named_property_callback(property, info, V8JS_PROP_QUERY);
  736. if (!r.IsEmpty()) {
  737. info.GetReturnValue().Set(r->ToInteger());
  738. }
  739. }
  740. /* }}} */
  741. static void php_v8js_named_property_deleter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Boolean> &info) /* {{{ */
  742. {
  743. v8::Local<v8::Value> r = php_v8js_named_property_callback(property, info, V8JS_PROP_DELETER);
  744. if (!r.IsEmpty()) {
  745. info.GetReturnValue().Set(r->ToBoolean());
  746. }
  747. }
  748. /* }}} */
  749. static v8::Handle<v8::Value> php_v8js_hash_to_jsobj(zval *value, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  750. {
  751. v8::Handle<v8::Object> newobj;
  752. int i;
  753. char *key = NULL;
  754. ulong index;
  755. uint key_len;
  756. HashTable *myht;
  757. HashPosition pos;
  758. zend_class_entry *ce = NULL;
  759. if (Z_TYPE_P(value) == IS_ARRAY) {
  760. myht = HASH_OF(value);
  761. } else {
  762. myht = Z_OBJPROP_P(value);
  763. ce = Z_OBJCE_P(value);
  764. }
  765. /* Prevent recursion */
  766. if (myht && myht->nApplyCount > 1) {
  767. return V8JS_NULL;
  768. }
  769. /* Object methods */
  770. if (ce == php_ce_v8_function) {
  771. php_v8js_object *c = (php_v8js_object *) zend_object_store_get_object(value TSRMLS_CC);
  772. if(isolate != c->ctx->isolate) {
  773. php_error_docref(NULL TSRMLS_CC, E_WARNING, "V8Function object passed to wrong V8Js instance");
  774. return V8JS_NULL;
  775. }
  776. v8::Local<v8::Value> v8obj = v8::Local<v8::Value>::New(isolate, c->v8obj);
  777. return v8obj;
  778. } else if (ce) {
  779. php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData(0);
  780. v8::Local<v8::FunctionTemplate> new_tpl;
  781. v8js_tmpl_t *persist_tpl_;
  782. try {
  783. new_tpl = v8::Local<v8::FunctionTemplate>::New
  784. (isolate, ctx->template_cache.at(ce->name));
  785. }
  786. catch (const std::out_of_range &) {
  787. /* No cached v8::FunctionTemplate available as of yet, create one. */
  788. new_tpl = v8::FunctionTemplate::New(isolate, 0);
  789. new_tpl->SetClassName(V8JS_STRL(ce->name, ce->name_length));
  790. new_tpl->InstanceTemplate()->SetInternalFieldCount(1);
  791. if (ce == zend_ce_closure) {
  792. /* Got a closure, mustn't cache ... */
  793. persist_tpl_ = new v8js_tmpl_t(isolate, new_tpl);
  794. /* We'll free persist_tpl_ via php_v8js_weak_closure_callback, below */
  795. new_tpl->InstanceTemplate()->SetCallAsFunctionHandler(php_v8js_php_callback);
  796. } else {
  797. /* Add new v8::FunctionTemplate to tpl_map, as long as it is not a closure. */
  798. persist_tpl_ = &ctx->template_cache[ce->name];
  799. persist_tpl_->Reset(isolate, new_tpl);
  800. /* We'll free persist_tpl_ when template_cache is destroyed */
  801. // Finish setup of new_tpl
  802. new_tpl->InstanceTemplate()->SetNamedPropertyHandler
  803. (php_v8js_named_property_getter, /* getter */
  804. php_v8js_named_property_setter, /* setter */
  805. php_v8js_named_property_query, /* query */
  806. php_v8js_named_property_deleter, /* deleter */
  807. php_v8js_named_property_enumerator, /* enumerator */
  808. V8JS_NULL /* data */
  809. );
  810. // add __invoke() handler
  811. zend_function *invoke_method_ptr;
  812. if (zend_hash_find(&ce->function_table, ZEND_INVOKE_FUNC_NAME,
  813. sizeof(ZEND_INVOKE_FUNC_NAME),
  814. (void**)&invoke_method_ptr) == SUCCESS &&
  815. invoke_method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) {
  816. new_tpl->InstanceTemplate()->SetCallAsFunctionHandler(php_v8js_invoke_callback, PHP_V8JS_CALLBACK(isolate, invoke_method_ptr, new_tpl));
  817. }
  818. }
  819. v8::Local<v8::Array> call_handler_data = v8::Array::New(isolate, 2);
  820. call_handler_data->Set(0, v8::External::New(isolate, persist_tpl_));
  821. call_handler_data->Set(1, v8::External::New(isolate, ce));
  822. new_tpl->SetCallHandler(php_v8js_construct_callback, call_handler_data);
  823. }
  824. // Create v8 wrapper object
  825. v8::Handle<v8::Value> external = v8::External::New(isolate, value);
  826. newobj = new_tpl->GetFunction()->NewInstance(1, &external);
  827. if (ce == zend_ce_closure) {
  828. // free uncached function template when object is freed
  829. ctx->weak_closures[persist_tpl_].Reset(isolate, newobj);
  830. ctx->weak_closures[persist_tpl_].SetWeak(persist_tpl_, php_v8js_weak_closure_callback);
  831. }
  832. } else {
  833. // @todo re-use template likewise
  834. v8::Local<v8::FunctionTemplate> new_tpl = v8::FunctionTemplate::New(isolate, 0);
  835. new_tpl->SetClassName(V8JS_SYM("Array"));
  836. newobj = new_tpl->InstanceTemplate()->NewInstance();
  837. }
  838. /* Object properties */
  839. i = myht ? zend_hash_num_elements(myht) : 0;
  840. if (i > 0 && !ce)
  841. {
  842. zval **data;
  843. HashTable *tmp_ht;
  844. zend_hash_internal_pointer_reset_ex(myht, &pos);
  845. for (;; zend_hash_move_forward_ex(myht, &pos)) {
  846. i = zend_hash_get_current_key_ex(myht, &key, &key_len, &index, 0, &pos);
  847. if (i == HASH_KEY_NON_EXISTANT)
  848. break;
  849. if (zend_hash_get_current_data_ex(myht, (void **) &data, &pos) == SUCCESS)
  850. {
  851. tmp_ht = HASH_OF(*data);
  852. if (tmp_ht) {
  853. tmp_ht->nApplyCount++;
  854. }
  855. if (i == HASH_KEY_IS_STRING)
  856. {
  857. if (key[0] == '\0' && Z_TYPE_P(value) == IS_OBJECT) {
  858. /* Skip protected and private members. */
  859. if (tmp_ht) {
  860. tmp_ht->nApplyCount--;
  861. }
  862. continue;
  863. }
  864. newobj->Set(V8JS_STRL(key, key_len - 1), zval_to_v8js(*data, isolate TSRMLS_CC));
  865. } else {
  866. newobj->Set(index, zval_to_v8js(*data, isolate TSRMLS_CC));
  867. }
  868. if (tmp_ht) {
  869. tmp_ht->nApplyCount--;
  870. }
  871. }
  872. }
  873. }
  874. return newobj;
  875. }
  876. /* }}} */
  877. static v8::Handle<v8::Value> php_v8js_hash_to_jsarr(zval *value, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  878. {
  879. HashTable *myht = HASH_OF(value);
  880. int i = myht ? zend_hash_num_elements(myht) : 0;
  881. /* Return object if dealing with assoc array */
  882. if (i > 0 && _php_v8js_is_assoc_array(myht TSRMLS_CC)) {
  883. return php_v8js_hash_to_jsobj(value, isolate TSRMLS_CC);
  884. }
  885. v8::Local<v8::Array> newarr;
  886. /* Prevent recursion */
  887. if (myht && myht->nApplyCount > 1) {
  888. return V8JS_NULL;
  889. }
  890. newarr = v8::Array::New(isolate, i);
  891. if (i > 0)
  892. {
  893. zval **data;
  894. ulong index = 0;
  895. HashTable *tmp_ht;
  896. HashPosition pos;
  897. for (zend_hash_internal_pointer_reset_ex(myht, &pos);
  898. SUCCESS == zend_hash_get_current_data_ex(myht, (void **) &data, &pos);
  899. zend_hash_move_forward_ex(myht, &pos)
  900. ) {
  901. tmp_ht = HASH_OF(*data);
  902. if (tmp_ht) {
  903. tmp_ht->nApplyCount++;
  904. }
  905. newarr->Set(index++, zval_to_v8js(*data, isolate TSRMLS_CC));
  906. if (tmp_ht) {
  907. tmp_ht->nApplyCount--;
  908. }
  909. }
  910. }
  911. return newarr;
  912. }
  913. /* }}} */
  914. v8::Handle<v8::Value> zval_to_v8js(zval *value, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  915. {
  916. v8::Handle<v8::Value> jsValue;
  917. long v;
  918. zend_class_entry *ce;
  919. switch (Z_TYPE_P(value))
  920. {
  921. case IS_ARRAY:
  922. jsValue = php_v8js_hash_to_jsarr(value, isolate TSRMLS_CC);
  923. break;
  924. case IS_OBJECT:
  925. if (V8JSG(use_date)) {
  926. ce = php_date_get_date_ce();
  927. if (instanceof_function(Z_OBJCE_P(value), ce TSRMLS_CC)) {
  928. zval *dtval;
  929. zend_call_method_with_0_params(&value, NULL, NULL, "getTimestamp", &dtval);
  930. if (dtval) {
  931. jsValue = V8JS_DATE(((double)Z_LVAL_P(dtval) * 1000.0));
  932. zval_ptr_dtor(&dtval);
  933. }
  934. else
  935. jsValue = V8JS_NULL;
  936. } else
  937. jsValue = php_v8js_hash_to_jsobj(value, isolate TSRMLS_CC);
  938. } else
  939. jsValue = php_v8js_hash_to_jsobj(value, isolate TSRMLS_CC);
  940. break;
  941. case IS_STRING:
  942. jsValue = V8JS_STRL(Z_STRVAL_P(value), Z_STRLEN_P(value));
  943. break;
  944. case IS_LONG:
  945. v = Z_LVAL_P(value);
  946. if (v < - std::numeric_limits<int32_t>::min() || v > std::numeric_limits<int32_t>::max()) {
  947. jsValue = V8JS_FLOAT((double)v);
  948. } else {
  949. jsValue = V8JS_INT(v);
  950. }
  951. break;
  952. case IS_DOUBLE:
  953. jsValue = V8JS_FLOAT(Z_DVAL_P(value));
  954. break;
  955. case IS_BOOL:
  956. jsValue = V8JS_BOOL(Z_BVAL_P(value));
  957. break;
  958. default:
  959. case IS_NULL:
  960. jsValue = V8JS_NULL;
  961. break;
  962. }
  963. return jsValue;
  964. }
  965. /* }}} */
  966. int v8js_to_zval(v8::Handle<v8::Value> jsValue, zval *return_value, int flags, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  967. {
  968. if (jsValue->IsString())
  969. {
  970. v8::String::Utf8Value str(jsValue);
  971. const char *cstr = ToCString(str);
  972. RETVAL_STRINGL(cstr, jsValue->ToString()->Utf8Length(), 1);
  973. // RETVAL_STRING(cstr, 1);
  974. }
  975. else if (jsValue->IsBoolean())
  976. {
  977. RETVAL_BOOL(jsValue->Uint32Value());
  978. }
  979. else if (jsValue->IsInt32() || jsValue->IsUint32())
  980. {
  981. RETVAL_LONG((long) jsValue->IntegerValue());
  982. }
  983. else if (jsValue->IsNumber())
  984. {
  985. RETVAL_DOUBLE(jsValue->NumberValue());
  986. }
  987. else if (jsValue->IsDate()) /* Return as a PHP DateTime object */
  988. {
  989. v8::String::Utf8Value str(jsValue);
  990. const char *cstr = ToCString(str);
  991. zend_class_entry *ce = php_date_get_date_ce();
  992. #if PHP_VERSION_ID < 50304
  993. zval *param;
  994. MAKE_STD_ZVAL(param);
  995. ZVAL_STRING(param, cstr, 1);
  996. object_init_ex(return_value, ce TSRMLS_CC);
  997. zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, param);
  998. zval_ptr_dtor(&param);
  999. if (EG(exception)) {
  1000. return FAILURE;
  1001. }
  1002. #else
  1003. php_date_instantiate(ce, return_value TSRMLS_CC);
  1004. 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)) {
  1005. return FAILURE;
  1006. }
  1007. #endif
  1008. }
  1009. else if (jsValue->IsObject())
  1010. {
  1011. v8::Handle<v8::Object> self = v8::Handle<v8::Object>::Cast(jsValue);
  1012. // if this is a wrapped PHP object, then just unwrap it.
  1013. v8::Local<v8::Value> php_object = self->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY));
  1014. if (!php_object.IsEmpty()) {
  1015. zval *object = reinterpret_cast<zval *>(v8::External::Cast(*php_object)->Value());
  1016. RETVAL_ZVAL(object, 1, 0);
  1017. return SUCCESS;
  1018. }
  1019. if ((flags & V8JS_FLAG_FORCE_ARRAY) || jsValue->IsArray()) {
  1020. array_init(return_value);
  1021. return php_v8js_v8_get_properties_hash(jsValue, Z_ARRVAL_P(return_value), flags, isolate TSRMLS_CC);
  1022. } else {
  1023. php_v8js_create_v8(return_value, jsValue, flags, isolate TSRMLS_CC);
  1024. return SUCCESS;
  1025. }
  1026. }
  1027. else /* types External, RegExp, Undefined and Null are considered NULL */
  1028. {
  1029. RETVAL_NULL();
  1030. }
  1031. return SUCCESS;
  1032. }
  1033. /* }}} */
  1034. /*
  1035. * Local variables:
  1036. * tab-width: 4
  1037. * c-basic-offset: 4
  1038. * End:
  1039. * vim600: noet sw=4 ts=4 fdm=marker
  1040. * vim<600: noet sw=4 ts=4
  1041. */