v8js_convert.cc 31 KB

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