v8js_convert.cc 31 KB

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