v8js_convert.cc 31 KB

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