v8js_convert.cc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  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 "zend_interfaces.h"
  21. #include "zend_closures.h"
  22. }
  23. #include "php_v8js_macros.h"
  24. #include <v8.h>
  25. #include <stdexcept>
  26. #define PHPJS_OBJECT_KEY "phpjs::object"
  27. #if PHP_V8_API_VERSION < 3022000
  28. /* CopyablePersistentTraits is only part of V8 from 3.22.0 on,
  29. to be compatible with lower versions add our own (compatible) version. */
  30. namespace v8 {
  31. template<class T>
  32. struct CopyablePersistentTraits {
  33. typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
  34. static const bool kResetInDestructor = true;
  35. template<class S, class M>
  36. #if PHP_V8_API_VERSION >= 3021015
  37. static V8_INLINE void Copy(const Persistent<S, M>& source,
  38. CopyablePersistent* dest)
  39. #else
  40. V8_INLINE(static void Copy(const Persistent<S, M>& source,
  41. CopyablePersistent* dest))
  42. #endif
  43. {
  44. // do nothing, just allow copy
  45. }
  46. };
  47. }
  48. #endif
  49. typedef std::pair<struct php_v8js_ctx *, const char *> TemplateCacheKey;
  50. typedef v8::Persistent<v8::FunctionTemplate, v8::CopyablePersistentTraits<v8::FunctionTemplate> > TemplateCacheEntry;
  51. typedef std::map<TemplateCacheKey, TemplateCacheEntry> TemplateCache;
  52. /* Callback for PHP methods and functions */
  53. 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) /* {{{ */
  54. {
  55. v8::Handle<v8::Value> return_value;
  56. zend_fcall_info fci;
  57. zend_fcall_info_cache fcc;
  58. zval fname, *retval_ptr = NULL, **argv = NULL;
  59. zend_uint argc = info.Length(), min_num_args = 0, max_num_args = 0;
  60. char *error;
  61. int error_len, i, flags = V8JS_FLAG_NONE;
  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. ZVAL_STRING(&fname, method_ptr->common.function_name, 0);
  67. /* zend_fcall_info */
  68. fci.size = sizeof(fci);
  69. fci.function_table = &ce->function_table;
  70. fci.function_name = &fname;
  71. fci.symbol_table = NULL;
  72. fci.object_ptr = value;
  73. fci.retval_ptr_ptr = &retval_ptr;
  74. fci.param_count = 0;
  75. /* Check for passed vs required number of arguments */
  76. if (argc < min_num_args)
  77. {
  78. error_len = spprintf(&error, 0,
  79. "%s::%s() expects %s %d parameter%s, %d given",
  80. ce->name,
  81. method_ptr->common.function_name,
  82. min_num_args == max_num_args ? "exactly" : argc < min_num_args ? "at least" : "at most",
  83. argc < min_num_args ? min_num_args : max_num_args,
  84. (argc < min_num_args ? min_num_args : max_num_args) == 1 ? "" : "s",
  85. argc);
  86. return_value = V8JS_THROW(TypeError, error, error_len);
  87. if (ce == zend_ce_closure) {
  88. efree(const_cast<char*>(method_ptr->internal_function.function_name));
  89. efree(method_ptr);
  90. }
  91. efree(error);
  92. info.GetReturnValue().Set(return_value);
  93. return;
  94. }
  95. /* Convert parameters passed from V8 */
  96. if (argc) {
  97. flags = V8JS_GLOBAL_GET_FLAGS();
  98. fci.params = (zval ***) safe_emalloc(argc, sizeof(zval **), 0);
  99. argv = (zval **) safe_emalloc(argc, sizeof(zval *), 0);
  100. for (i = 0; i < argc; i++) {
  101. if(info[i]->IsObject()
  102. && !info[i]->IsFunction()
  103. && info[i]->ToObject()->InternalFieldCount() == 2) {
  104. /* This is a PHP object, passed to JS and back. */
  105. argv[i] = reinterpret_cast<zval *>(info[i]->ToObject()->GetAlignedPointerFromInternalField(0));
  106. Z_ADDREF_P(argv[i]);
  107. } else {
  108. MAKE_STD_ZVAL(argv[i]);
  109. if (v8js_to_zval(info[i], argv[i], flags, isolate TSRMLS_CC) == FAILURE) {
  110. fci.param_count++;
  111. error_len = spprintf(&error, 0, "converting parameter #%d passed to %s() failed", i + 1, method_ptr->common.function_name);
  112. return_value = V8JS_THROW(Error, error, error_len);
  113. efree(error);
  114. goto failure;
  115. }
  116. }
  117. fci.params[fci.param_count++] = &argv[i];
  118. }
  119. } else {
  120. fci.params = NULL;
  121. }
  122. fci.no_separation = 1;
  123. {
  124. isolate->Exit();
  125. v8::Unlocker unlocker(isolate);
  126. /* zend_fcall_info_cache */
  127. fcc.initialized = 1;
  128. fcc.function_handler = method_ptr;
  129. fcc.calling_scope = ce;
  130. fcc.called_scope = ce;
  131. fcc.object_ptr = value;
  132. /* Call the method */
  133. zend_call_function(&fci, &fcc TSRMLS_CC);
  134. }
  135. isolate->Enter();
  136. failure:
  137. /* Cleanup */
  138. if (argc) {
  139. for (i = 0; i < fci.param_count; i++) {
  140. zval_ptr_dtor(&argv[i]);
  141. }
  142. efree(argv);
  143. efree(fci.params);
  144. }
  145. if (retval_ptr != NULL) {
  146. return_value = zval_to_v8js(retval_ptr, isolate TSRMLS_CC);
  147. zval_ptr_dtor(&retval_ptr);
  148. } else {
  149. return_value = V8JS_NULL;
  150. }
  151. info.GetReturnValue().Set(return_value);
  152. }
  153. /* }}} */
  154. /* Callback for PHP methods and functions */
  155. static void php_v8js_php_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  156. {
  157. zval *value = reinterpret_cast<zval *>(info.Holder()->GetAlignedPointerFromInternalField(0));
  158. v8::Isolate *isolate = reinterpret_cast<v8::Isolate *>(info.Holder()->GetAlignedPointerFromInternalField(1));
  159. zend_function *method_ptr;
  160. TSRMLS_FETCH();
  161. zend_class_entry *ce = Z_OBJCE_P(value);
  162. /* Set method_ptr from v8::External or fetch the closure invoker */
  163. if (!info.Data().IsEmpty() && info.Data()->IsExternal()) {
  164. method_ptr = static_cast<zend_function *>(v8::External::Cast(*info.Data())->Value());
  165. } else {
  166. method_ptr = zend_get_closure_invoke_method(value TSRMLS_CC);
  167. }
  168. return php_v8js_call_php_func(value, ce, method_ptr, isolate, info TSRMLS_CC);
  169. }
  170. /* Callback for PHP constructor calls */
  171. static void php_v8js_construct_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  172. {
  173. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  174. info.GetReturnValue().Set(V8JS_UNDEFINED);
  175. // @todo assert constructor call
  176. v8::Handle<v8::Object> newobj = info.This();
  177. zval *value;
  178. TSRMLS_FETCH();
  179. if (!info.IsConstructCall()) {
  180. return;
  181. }
  182. if (info[0]->IsExternal()) {
  183. // Object created by v8js in php_v8js_hash_to_jsobj, PHP object passed as v8::External.
  184. value = static_cast<zval *>(v8::External::Cast(*info[0])->Value());
  185. } else {
  186. // Object created from JavaScript context. Need to create PHP object first.
  187. zend_class_entry *ce = static_cast<zend_class_entry *>(v8::External::Cast(*info.Data())->Value());
  188. zend_function *ctor_ptr = ce->constructor;
  189. // Check access on __construct function, if any
  190. if (ctor_ptr != NULL && (ctor_ptr->common.fn_flags & ZEND_ACC_PUBLIC) == 0) {
  191. info.GetReturnValue().Set(v8::ThrowException(v8::String::New("Call to protected __construct() not allowed")));
  192. return;
  193. }
  194. MAKE_STD_ZVAL(value);
  195. object_init_ex(value, ce);
  196. // Call __construct function
  197. if (ctor_ptr != NULL) {
  198. php_v8js_call_php_func(value, ce, ctor_ptr, isolate, info TSRMLS_CC);
  199. }
  200. }
  201. newobj->SetAlignedPointerInInternalField(0, value);
  202. newobj->SetAlignedPointerInInternalField(1, (void *) isolate);
  203. newobj->SetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY), v8::True(isolate));
  204. }
  205. /* }}} */
  206. static int _php_v8js_is_assoc_array(HashTable *myht TSRMLS_DC) /* {{{ */
  207. {
  208. int i;
  209. char *key;
  210. ulong index, idx = 0;
  211. uint key_len;
  212. HashPosition pos;
  213. zend_hash_internal_pointer_reset_ex(myht, &pos);
  214. for (;; zend_hash_move_forward_ex(myht, &pos)) {
  215. i = zend_hash_get_current_key_ex(myht, &key, &key_len, &index, 0, &pos);
  216. if (i == HASH_KEY_NON_EXISTANT)
  217. break;
  218. if (i == HASH_KEY_IS_STRING || index != idx) {
  219. return 1;
  220. }
  221. idx++;
  222. }
  223. return 0;
  224. }
  225. /* }}} */
  226. static void php_v8js_property_caller(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  227. {
  228. v8::Local<v8::Object> self = info.Holder();
  229. v8::Local<v8::String> cname = info.Callee()->GetName()->ToString();
  230. v8::Local<v8::Value> value;
  231. v8::Local<v8::String> cb_func = v8::Local<v8::String>::Cast(info.Data());
  232. value = self->GetHiddenValue(cb_func);
  233. if (!value.IsEmpty() && value->IsFunction())
  234. {
  235. int argc = info.Length(), i = 0;
  236. v8::Local<v8::Value> *argv = new v8::Local<v8::Value>[argc];
  237. v8::Local<v8::Function> cb = v8::Local<v8::Function>::Cast(value);
  238. if (cb_func->Equals(V8JS_SYM(ZEND_INVOKE_FUNC_NAME))) {
  239. for (; i < argc; ++i) {
  240. argv[i] = info[i];
  241. }
  242. value = cb->Call(self, argc, argv);
  243. }
  244. else /* __call() */
  245. {
  246. v8::Local<v8::Array> argsarr = v8::Array::New(argc);
  247. for (; i < argc; ++i) {
  248. argsarr->Set(i, info[i]);
  249. }
  250. v8::Local<v8::Value> argsv[2] = { cname, argsarr };
  251. value = cb->Call(self, 2, argsv);
  252. }
  253. }
  254. if (info.IsConstructCall()) {
  255. if (!value.IsEmpty() && !value->IsNull()) {
  256. info.GetReturnValue().Set(value);
  257. return;
  258. }
  259. info.GetReturnValue().Set(self);
  260. return;
  261. }
  262. info.GetReturnValue().Set(value);
  263. }
  264. /* }}} */
  265. static void php_v8js_property_getter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */
  266. {
  267. v8::Local<v8::Object> self = info.Holder();
  268. v8::Local<v8::Value> value;
  269. v8::Local<v8::Function> cb;
  270. /* Check first if JS object has the named property */
  271. value = self->GetRealNamedProperty(property);
  272. if (!value.IsEmpty()) {
  273. info.GetReturnValue().Set(value);
  274. return;
  275. }
  276. /* If __get() is set for PHP object, call it */
  277. value = self->GetHiddenValue(V8JS_SYM(ZEND_GET_FUNC_NAME));
  278. if (!value.IsEmpty() && value->IsFunction()) {
  279. cb = v8::Local<v8::Function>::Cast(value);
  280. v8::Local<v8::Value> argv[1] = {property};
  281. value = cb->Call(self, 1, argv);
  282. }
  283. /* If __get() does not exist or returns NULL, create new function with callback for __call() */
  284. if ((value.IsEmpty() || value->IsNull()) && info.Data()->IsTrue()) {
  285. v8::Local<v8::FunctionTemplate> cb_t = v8::FunctionTemplate::New(php_v8js_property_caller, V8JS_SYM(ZEND_CALL_FUNC_NAME));
  286. cb = cb_t->GetFunction();
  287. cb->SetName(property);
  288. info.GetReturnValue().Set(cb);
  289. return;
  290. }
  291. info.GetReturnValue().Set(value);
  292. }
  293. /* }}} */
  294. static void php_v8js_property_query(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Integer> &info) /* {{{ */
  295. {
  296. v8::Local<v8::Object> self = info.Holder();
  297. v8::Local<v8::Value> value;
  298. /* Return early if property is set in JS object */
  299. if (self->HasRealNamedProperty(property)) {
  300. info.GetReturnValue().Set(V8JS_INT(v8::ReadOnly));
  301. return;
  302. }
  303. value = self->GetHiddenValue(V8JS_SYM(ZEND_ISSET_FUNC_NAME));
  304. if (!value.IsEmpty() && value->IsFunction()) {
  305. v8::Local<v8::Function> cb = v8::Local<v8::Function>::Cast(value);
  306. v8::Local<v8::Value> argv[1] = {property};
  307. value = cb->Call(self, 1, argv);
  308. }
  309. info.GetReturnValue().Set((!value.IsEmpty() && value->IsTrue()) ? V8JS_INT(v8::ReadOnly) : v8::Local<v8::Integer>());
  310. }
  311. /* }}} */
  312. /* These are not defined by Zend */
  313. #define ZEND_WAKEUP_FUNC_NAME "__wakeup"
  314. #define ZEND_SLEEP_FUNC_NAME "__sleep"
  315. #define ZEND_SET_STATE_FUNC_NAME "__set_state"
  316. #define IS_MAGIC_FUNC(mname) \
  317. ((key_len == sizeof(mname)) && \
  318. !strncasecmp(key, mname, key_len - 1))
  319. #define PHP_V8JS_CALLBACK(mptr, tmpl) \
  320. v8::FunctionTemplate::New(php_v8js_php_callback, v8::External::New(mptr), v8::Signature::New(tmpl))->GetFunction()
  321. static void php_v8js_weak_object_callback(v8::Isolate *isolate, v8::Persistent<v8::Object> *object, zval *value)
  322. {
  323. TSRMLS_FETCH();
  324. if (READY_TO_DESTROY(value)) {
  325. zval_dtor(value);
  326. FREE_ZVAL(value);
  327. } else {
  328. Z_DELREF_P(value);
  329. }
  330. v8::V8::AdjustAmountOfExternalAllocatedMemory(-1024);
  331. object->Dispose();
  332. }
  333. static v8::Handle<v8::Value> php_v8js_hash_to_jsobj(zval *value, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  334. {
  335. v8::Handle<v8::Object> newobj;
  336. int i;
  337. char *key = NULL;
  338. ulong index;
  339. uint key_len;
  340. HashTable *myht;
  341. HashPosition pos;
  342. zend_class_entry *ce = NULL;
  343. zend_function *method_ptr, *call_ptr = NULL, *get_ptr = NULL, *invoke_ptr = NULL, *isset_ptr = NULL;
  344. if (Z_TYPE_P(value) == IS_ARRAY) {
  345. myht = HASH_OF(value);
  346. } else {
  347. myht = Z_OBJPROP_P(value);
  348. ce = Z_OBJCE_P(value);
  349. }
  350. /* Prevent recursion */
  351. if (myht && myht->nApplyCount > 1) {
  352. return V8JS_NULL;
  353. }
  354. /* Object methods */
  355. if (ce == php_ce_v8_function) {
  356. php_v8js_object *c = (php_v8js_object *) zend_object_store_get_object(value TSRMLS_CC);
  357. v8::Local<v8::Value> v8obj = v8::Local<v8::Value>::New(isolate, c->v8obj);
  358. return v8obj;
  359. } else if (ce) {
  360. php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData();
  361. v8::Local<v8::FunctionTemplate> new_tpl;
  362. bool cached_tpl = true;
  363. static TemplateCache tpl_map;
  364. try {
  365. new_tpl = v8::Local<v8::FunctionTemplate>::New
  366. (isolate, tpl_map.at(std::make_pair(ctx, ce->name)));
  367. }
  368. catch (const std::out_of_range &) {
  369. cached_tpl = false;
  370. /* No cached v8::FunctionTemplate available as of yet, create one. */
  371. new_tpl = v8::FunctionTemplate::New();
  372. new_tpl->SetClassName(V8JS_STRL(ce->name, ce->name_length));
  373. new_tpl->InstanceTemplate()->SetInternalFieldCount(2);
  374. v8::Handle<v8::Value> wrapped_ce = v8::External::New(ce);
  375. new_tpl->SetCallHandler(php_v8js_construct_callback, wrapped_ce);
  376. if (ce == zend_ce_closure) {
  377. /* Got a closure, mustn't cache ... */
  378. new_tpl->InstanceTemplate()->SetCallAsFunctionHandler(php_v8js_php_callback);
  379. } else {
  380. /* Add new v8::FunctionTemplate to tpl_map, as long as it is not a closure. */
  381. TemplateCacheEntry tce(isolate, new_tpl);
  382. tpl_map[std::make_pair(ctx, ce->name)] = tce;
  383. }
  384. }
  385. if (ce != zend_ce_closure) {
  386. /* Attach object methods to the instance template. */
  387. zend_hash_internal_pointer_reset_ex(&ce->function_table, &pos);
  388. for (;; zend_hash_move_forward_ex(&ce->function_table, &pos)) {
  389. if (zend_hash_get_current_key_ex(&ce->function_table, &key, &key_len, &index, 0, &pos) != HASH_KEY_IS_STRING ||
  390. zend_hash_get_current_data_ex(&ce->function_table, (void **) &method_ptr, &pos) == FAILURE
  391. ) {
  392. break;
  393. }
  394. if ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) && /* Allow only public methods */
  395. (method_ptr->common.fn_flags & ZEND_ACC_CTOR) == 0 && /* ..and no __construct() */
  396. (method_ptr->common.fn_flags & ZEND_ACC_DTOR) == 0 && /* ..or __destruct() */
  397. (method_ptr->common.fn_flags & ZEND_ACC_CLONE) == 0 /* ..or __clone() functions */
  398. ) {
  399. /* Override native toString() with __tostring() if it is set in passed object */
  400. if (!cached_tpl && IS_MAGIC_FUNC(ZEND_TOSTRING_FUNC_NAME)) {
  401. new_tpl->InstanceTemplate()->Set(V8JS_SYM("toString"), PHP_V8JS_CALLBACK(method_ptr, new_tpl));
  402. /* TODO: __set(), __unset() disabled as JS is not allowed to modify the passed PHP object yet.
  403. * __sleep(), __wakeup(), __set_state() are always ignored */
  404. } else if (
  405. IS_MAGIC_FUNC(ZEND_CALLSTATIC_FUNC_NAME)|| /* TODO */
  406. IS_MAGIC_FUNC(ZEND_SLEEP_FUNC_NAME) ||
  407. IS_MAGIC_FUNC(ZEND_WAKEUP_FUNC_NAME) ||
  408. IS_MAGIC_FUNC(ZEND_SET_STATE_FUNC_NAME) ||
  409. IS_MAGIC_FUNC(ZEND_SET_FUNC_NAME) ||
  410. IS_MAGIC_FUNC(ZEND_UNSET_FUNC_NAME)
  411. ) {
  412. /* Register all magic function as hidden with lowercase name */
  413. } else if (IS_MAGIC_FUNC(ZEND_GET_FUNC_NAME)) {
  414. get_ptr = method_ptr;
  415. } else if (IS_MAGIC_FUNC(ZEND_CALL_FUNC_NAME)) {
  416. call_ptr = method_ptr;
  417. } else if (IS_MAGIC_FUNC(ZEND_INVOKE_FUNC_NAME)) {
  418. invoke_ptr = method_ptr;
  419. } else if (IS_MAGIC_FUNC(ZEND_ISSET_FUNC_NAME)) {
  420. isset_ptr = method_ptr;
  421. } else if (!cached_tpl) {
  422. new_tpl->InstanceTemplate()->Set(V8JS_STR(method_ptr->common.function_name), PHP_V8JS_CALLBACK(method_ptr, new_tpl), v8::ReadOnly);
  423. }
  424. }
  425. }
  426. if (!cached_tpl) {
  427. /* Only register getter, etc. when they're set in PHP side */
  428. if (call_ptr || get_ptr || isset_ptr)
  429. {
  430. /* Set __get() handler which acts also as __call() proxy */
  431. new_tpl->InstanceTemplate()->SetNamedPropertyHandler(
  432. php_v8js_property_getter, /* getter */
  433. 0, /* setter */
  434. isset_ptr ? php_v8js_property_query : 0, /* query */
  435. 0, /* deleter */
  436. 0, /* enumerator */
  437. V8JS_BOOL(call_ptr ? true : false)
  438. );
  439. }
  440. /* __invoke() handler */
  441. if (invoke_ptr) {
  442. new_tpl->InstanceTemplate()->SetCallAsFunctionHandler(php_v8js_property_caller, V8JS_SYM(ZEND_INVOKE_FUNC_NAME));
  443. }
  444. }
  445. }
  446. // Increase the reference count of this value because we're storing it internally for use later
  447. // See https://github.com/preillyme/v8js/issues/6
  448. Z_ADDREF_P(value);
  449. // Since we got to decrease the reference count again, in case v8 garbage collector
  450. // decides to dispose the JS object, we add a weak persistent handle and register
  451. // a callback function that removes the reference.
  452. v8::Handle<v8::Value> external = v8::External::New(value);
  453. v8::Persistent<v8::Object> persist_newobj(isolate, new_tpl->GetFunction()->NewInstance(1, &external));
  454. persist_newobj.MakeWeak(value, php_v8js_weak_object_callback);
  455. // Just tell v8 that we're allocating some external memory
  456. // (for the moment we just always tell 1k instead of trying to find out actual values)
  457. v8::V8::AdjustAmountOfExternalAllocatedMemory(1024);
  458. newobj = v8::Local<v8::Object>::New(isolate, persist_newobj);
  459. if (ce != zend_ce_closure) {
  460. // These unfortunately cannot be attached to the template, hence we have to put them
  461. // on each and every object instance manually.
  462. if (call_ptr) {
  463. newobj->SetHiddenValue(V8JS_SYM(ZEND_CALL_FUNC_NAME), PHP_V8JS_CALLBACK(call_ptr, new_tpl));
  464. }
  465. if (get_ptr) {
  466. newobj->SetHiddenValue(V8JS_SYM(ZEND_GET_FUNC_NAME), PHP_V8JS_CALLBACK(get_ptr, new_tpl));
  467. }
  468. if (invoke_ptr) {
  469. newobj->SetHiddenValue(V8JS_SYM(ZEND_INVOKE_FUNC_NAME), PHP_V8JS_CALLBACK(invoke_ptr, new_tpl));
  470. }
  471. if (isset_ptr) {
  472. newobj->SetHiddenValue(V8JS_SYM(ZEND_ISSET_FUNC_NAME), PHP_V8JS_CALLBACK(isset_ptr, new_tpl));
  473. }
  474. }
  475. } else {
  476. v8::Local<v8::FunctionTemplate> new_tpl = v8::FunctionTemplate::New(); // @todo re-use template likewise
  477. new_tpl->SetClassName(V8JS_SYM("Array"));
  478. newobj = new_tpl->InstanceTemplate()->NewInstance();
  479. }
  480. /* Object properties */
  481. i = myht ? zend_hash_num_elements(myht) : 0;
  482. if (i > 0)
  483. {
  484. zval **data;
  485. HashTable *tmp_ht;
  486. zend_hash_internal_pointer_reset_ex(myht, &pos);
  487. for (;; zend_hash_move_forward_ex(myht, &pos)) {
  488. i = zend_hash_get_current_key_ex(myht, &key, &key_len, &index, 0, &pos);
  489. if (i == HASH_KEY_NON_EXISTANT)
  490. break;
  491. if (zend_hash_get_current_data_ex(myht, (void **) &data, &pos) == SUCCESS)
  492. {
  493. tmp_ht = HASH_OF(*data);
  494. if (tmp_ht) {
  495. tmp_ht->nApplyCount++;
  496. }
  497. if (i == HASH_KEY_IS_STRING)
  498. {
  499. if (key[0] == '\0' && Z_TYPE_P(value) == IS_OBJECT) {
  500. /* Skip protected and private members. */
  501. if (tmp_ht) {
  502. tmp_ht->nApplyCount--;
  503. }
  504. continue;
  505. }
  506. newobj->Set(V8JS_STRL(key, key_len - 1), zval_to_v8js(*data, isolate TSRMLS_CC), v8::ReadOnly);
  507. } else {
  508. newobj->Set(index, zval_to_v8js(*data, isolate TSRMLS_CC));
  509. }
  510. if (tmp_ht) {
  511. tmp_ht->nApplyCount--;
  512. }
  513. }
  514. }
  515. }
  516. return newobj;
  517. }
  518. /* }}} */
  519. static v8::Handle<v8::Value> php_v8js_hash_to_jsarr(zval *value, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  520. {
  521. HashTable *myht = HASH_OF(value);
  522. int i = myht ? zend_hash_num_elements(myht) : 0;
  523. /* Return object if dealing with assoc array */
  524. if (i > 0 && _php_v8js_is_assoc_array(myht TSRMLS_CC)) {
  525. return php_v8js_hash_to_jsobj(value, isolate TSRMLS_CC);
  526. }
  527. v8::Local<v8::Array> newarr;
  528. /* Prevent recursion */
  529. if (myht && myht->nApplyCount > 1) {
  530. return V8JS_NULL;
  531. }
  532. newarr = v8::Array::New(i);
  533. if (i > 0)
  534. {
  535. zval **data;
  536. ulong index = 0;
  537. HashTable *tmp_ht;
  538. HashPosition pos;
  539. for (zend_hash_internal_pointer_reset_ex(myht, &pos);
  540. SUCCESS == zend_hash_get_current_data_ex(myht, (void **) &data, &pos);
  541. zend_hash_move_forward_ex(myht, &pos)
  542. ) {
  543. tmp_ht = HASH_OF(*data);
  544. if (tmp_ht) {
  545. tmp_ht->nApplyCount++;
  546. }
  547. newarr->Set(index++, zval_to_v8js(*data, isolate TSRMLS_CC));
  548. if (tmp_ht) {
  549. tmp_ht->nApplyCount--;
  550. }
  551. }
  552. }
  553. return newarr;
  554. }
  555. /* }}} */
  556. v8::Handle<v8::Value> zval_to_v8js(zval *value, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  557. {
  558. v8::Handle<v8::Value> jsValue;
  559. switch (Z_TYPE_P(value))
  560. {
  561. case IS_ARRAY:
  562. jsValue = php_v8js_hash_to_jsarr(value, isolate TSRMLS_CC);
  563. break;
  564. case IS_OBJECT:
  565. jsValue = php_v8js_hash_to_jsobj(value, isolate TSRMLS_CC);
  566. break;
  567. case IS_STRING:
  568. jsValue = V8JS_STRL(Z_STRVAL_P(value), Z_STRLEN_P(value));
  569. break;
  570. case IS_LONG:
  571. jsValue = V8JS_INT(Z_LVAL_P(value));
  572. break;
  573. case IS_DOUBLE:
  574. jsValue = V8JS_FLOAT(Z_DVAL_P(value));
  575. break;
  576. case IS_BOOL:
  577. jsValue = V8JS_BOOL(Z_BVAL_P(value));
  578. break;
  579. default:
  580. case IS_NULL:
  581. jsValue = V8JS_NULL;
  582. break;
  583. }
  584. return jsValue;
  585. }
  586. /* }}} */
  587. int v8js_to_zval(v8::Handle<v8::Value> jsValue, zval *return_value, int flags, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  588. {
  589. if (jsValue->IsString())
  590. {
  591. v8::String::Utf8Value str(jsValue);
  592. const char *cstr = ToCString(str);
  593. RETVAL_STRING(cstr, 1);
  594. }
  595. else if (jsValue->IsBoolean())
  596. {
  597. RETVAL_BOOL(jsValue->Uint32Value());
  598. }
  599. else if (jsValue->IsInt32() || jsValue->IsUint32())
  600. {
  601. RETVAL_LONG((long) jsValue->IntegerValue());
  602. }
  603. else if (jsValue->IsNumber())
  604. {
  605. RETVAL_DOUBLE(jsValue->NumberValue());
  606. }
  607. else if (jsValue->IsDate()) /* Return as a PHP DateTime object */
  608. {
  609. v8::String::Utf8Value str(jsValue);
  610. const char *cstr = ToCString(str);
  611. zend_class_entry *ce = php_date_get_date_ce();
  612. #if PHP_VERSION_ID < 50304
  613. zval *param;
  614. MAKE_STD_ZVAL(param);
  615. ZVAL_STRING(param, cstr, 1);
  616. object_init_ex(return_value, ce TSRMLS_CC);
  617. zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, param);
  618. zval_ptr_dtor(&param);
  619. if (EG(exception)) {
  620. return FAILURE;
  621. }
  622. #else
  623. php_date_instantiate(ce, return_value TSRMLS_CC);
  624. 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)) {
  625. return FAILURE;
  626. }
  627. #endif
  628. }
  629. else if (jsValue->IsObject())
  630. {
  631. v8::Handle<v8::Object> self = v8::Handle<v8::Object>::Cast(jsValue);
  632. // if this is a wrapped PHP object, then just unwrap it.
  633. if (!self->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY)).IsEmpty()) {
  634. zval *object = reinterpret_cast<zval *>(self->GetAlignedPointerFromInternalField(0));
  635. RETVAL_ZVAL(object, 1, 0);
  636. return SUCCESS;
  637. }
  638. if ((flags & V8JS_FLAG_FORCE_ARRAY) || jsValue->IsArray()) {
  639. array_init(return_value);
  640. return php_v8js_v8_get_properties_hash(jsValue, Z_ARRVAL_P(return_value), flags, isolate TSRMLS_CC);
  641. } else {
  642. php_v8js_create_v8(return_value, jsValue, flags, isolate TSRMLS_CC);
  643. return SUCCESS;
  644. }
  645. }
  646. else /* types External, RegExp, Undefined and Null are considered NULL */
  647. {
  648. RETVAL_NULL();
  649. }
  650. return SUCCESS;
  651. }
  652. /* }}} */
  653. /*
  654. * Local variables:
  655. * tab-width: 4
  656. * c-basic-offset: 4
  657. * End:
  658. * vim600: noet sw=4 ts=4 fdm=marker
  659. * vim<600: noet sw=4 ts=4
  660. */