v8js_object_export.cc 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  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. #ifdef HAVE_CONFIG_H
  14. #include "config.h"
  15. #endif
  16. extern "C" {
  17. #include "php.h"
  18. #include "ext/date/php_date.h"
  19. #include "ext/standard/php_string.h"
  20. #include "zend_interfaces.h"
  21. #include "zend_closures.h"
  22. }
  23. #include "php_v8js_macros.h"
  24. #include "v8js_array_access.h"
  25. #include "v8js_object_export.h"
  26. #include "v8js_v8object_class.h"
  27. static void v8js_weak_object_callback(const v8::WeakCallbackData<v8::Object, zend_object> &data);
  28. /* Callback for PHP methods and functions */
  29. static void v8js_call_php_func(zend_object *object, zend_function *method_ptr, v8::Isolate *isolate, const v8::FunctionCallbackInfo<v8::Value>& info TSRMLS_DC) /* {{{ */
  30. {
  31. v8::Handle<v8::Value> return_value;
  32. zend_fcall_info fci;
  33. zend_fcall_info_cache fcc;
  34. zval fname, retval, **argv = NULL;
  35. unsigned int argc = info.Length(), min_num_args = 0, max_num_args = 0;
  36. char *error;
  37. int error_len, i, flags = V8JS_FLAG_NONE;
  38. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  39. /* Set parameter limits */
  40. min_num_args = method_ptr->common.required_num_args;
  41. max_num_args = method_ptr->common.num_args;
  42. /* Function name to call */
  43. ZVAL_STR_COPY(&fname, method_ptr->common.function_name);
  44. /* zend_fcall_info */
  45. fci.size = sizeof(fci);
  46. fci.function_table = &object->ce->function_table;
  47. fci.function_name = fname;
  48. fci.symbol_table = NULL;
  49. fci.object = object;
  50. fci.retval = &retval;
  51. fci.param_count = 0;
  52. /* Check for passed vs required number of arguments */
  53. if (argc < min_num_args)
  54. {
  55. error_len = spprintf(&error, 0,
  56. "%s::%s() expects %s %d parameter%s, %d given",
  57. object->ce->name,
  58. method_ptr->common.function_name,
  59. min_num_args == max_num_args ? "exactly" : argc < min_num_args ? "at least" : "at most",
  60. argc < min_num_args ? min_num_args : max_num_args,
  61. (argc < min_num_args ? min_num_args : max_num_args) == 1 ? "" : "s",
  62. argc);
  63. return_value = V8JS_THROW(isolate, TypeError, error, error_len);
  64. if (object->ce == zend_ce_closure) {
  65. zend_string_release(method_ptr->internal_function.function_name);
  66. efree(method_ptr);
  67. }
  68. efree(error);
  69. info.GetReturnValue().Set(return_value);
  70. zval_dtor(&fname);
  71. return;
  72. }
  73. /* Convert parameters passed from V8 */
  74. if (argc) {
  75. flags = V8JS_GLOBAL_GET_FLAGS(isolate);
  76. fci.params = (zval *) safe_emalloc(argc, sizeof(zval), 0);
  77. for (i = 0; i < argc; i++) {
  78. v8::Local<v8::Value> php_object;
  79. if (info[i]->IsObject()) {
  80. php_object = v8::Local<v8::Object>::Cast(info[i])->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY));
  81. }
  82. if (!php_object.IsEmpty()) {
  83. /* This is a PHP object, passed to JS and back. */
  84. zend_object *object = reinterpret_cast<zend_object *>(v8::External::Cast(*php_object)->Value());
  85. ZVAL_OBJ(&fci.params[i], object);
  86. Z_ADDREF_P(&fci.params[i]);
  87. } else {
  88. if (v8js_to_zval(info[i], &fci.params[i], flags, isolate TSRMLS_CC) == FAILURE) {
  89. error_len = spprintf(&error, 0, "converting parameter #%d passed to %s() failed", i + 1, method_ptr->common.function_name);
  90. return_value = V8JS_THROW(isolate, Error, error, error_len);
  91. efree(error);
  92. goto failure;
  93. }
  94. }
  95. fci.param_count++;
  96. }
  97. } else {
  98. fci.params = NULL;
  99. }
  100. fci.no_separation = 1;
  101. info.GetReturnValue().Set(V8JS_NULL);
  102. zend_try {
  103. {
  104. isolate->Exit();
  105. v8::Unlocker unlocker(isolate);
  106. /* zend_fcall_info_cache */
  107. fcc.initialized = 1;
  108. fcc.function_handler = method_ptr;
  109. fcc.calling_scope = object->ce;
  110. fcc.called_scope = object->ce;
  111. fcc.object = object;
  112. zend_call_function(&fci, &fcc TSRMLS_CC);
  113. }
  114. isolate->Enter();
  115. }
  116. zend_catch {
  117. v8::V8::TerminateExecution(isolate);
  118. V8JSG(fatal_error_abort) = 1;
  119. }
  120. zend_end_try();
  121. failure:
  122. /* Cleanup */
  123. if (argc) {
  124. for (i = 0; i < fci.param_count; i++) {
  125. zval_dtor(&fci.params[i]);
  126. }
  127. efree(fci.params);
  128. }
  129. return_value = zval_to_v8js(&retval, isolate TSRMLS_CC);
  130. zval_dtor(&retval);
  131. zval_dtor(&fname);
  132. info.GetReturnValue().Set(return_value);
  133. }
  134. /* }}} */
  135. /* Callback for PHP methods and functions */
  136. static void v8js_php_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  137. {
  138. v8::Isolate *isolate = info.GetIsolate();
  139. v8::Local<v8::Object> self = info.Holder();
  140. V8JS_TSRMLS_FETCH();
  141. zend_object *object = reinterpret_cast<zend_object *>(v8::External::Cast(*self->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY)))->Value());
  142. zend_function *method_ptr;
  143. /* Set method_ptr from v8::External or fetch the closure invoker */
  144. if (!info.Data().IsEmpty() && info.Data()->IsExternal()) {
  145. method_ptr = static_cast<zend_function *>(v8::External::Cast(*info.Data())->Value());
  146. } else {
  147. method_ptr = zend_get_closure_invoke_method(object TSRMLS_CC);
  148. }
  149. return v8js_call_php_func(object, method_ptr, isolate, info TSRMLS_CC);
  150. }
  151. /* Callback for PHP constructor calls */
  152. static void v8js_construct_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  153. {
  154. v8::Isolate *isolate = info.GetIsolate();
  155. info.GetReturnValue().Set(V8JS_UNDEFINED);
  156. // @todo assert constructor call
  157. v8::Handle<v8::Object> newobj = info.This();
  158. v8::Local<v8::External> php_object;
  159. zval value;
  160. if (!info.IsConstructCall()) {
  161. return;
  162. }
  163. v8::Local<v8::Array> cons_data = v8::Local<v8::Array>::Cast(info.Data());
  164. v8::Local<v8::External> ext_tmpl = v8::Local<v8::External>::Cast(cons_data->Get(0));
  165. v8::Local<v8::External> ext_ce = v8::Local<v8::External>::Cast(cons_data->Get(1));
  166. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  167. if (info[0]->IsExternal()) {
  168. // Object created by v8js in v8js_hash_to_jsobj, PHP object passed as v8::External.
  169. php_object = v8::Local<v8::External>::Cast(info[0]);
  170. zend_object *object = reinterpret_cast<zend_object *>(php_object->Value());
  171. ZVAL_OBJ(&value, object);
  172. if(ctx->weak_objects.count(object)) {
  173. // We already exported this object, hence no need to add another
  174. // ref, v8 won't give us a second weak-object callback anyways.
  175. newobj->SetAlignedPointerInInternalField(0, ext_tmpl->Value());
  176. newobj->SetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY), php_object);
  177. return;
  178. }
  179. // Increase the reference count of this value because we're storing it internally for use later
  180. // See https://github.com/preillyme/v8js/issues/6
  181. Z_ADDREF_P(&value);
  182. } else {
  183. // Object created from JavaScript context. Need to create PHP object first.
  184. V8JS_TSRMLS_FETCH();
  185. zend_class_entry *ce = static_cast<zend_class_entry *>(ext_ce->Value());
  186. zend_function *ctor_ptr = ce->constructor;
  187. // Check access on __construct function, if any
  188. if (ctor_ptr != NULL && (ctor_ptr->common.fn_flags & ZEND_ACC_PUBLIC) == 0) {
  189. info.GetReturnValue().Set(isolate->ThrowException(V8JS_SYM("Call to protected __construct() not allowed")));
  190. return;
  191. }
  192. object_init_ex(&value, ce);
  193. // Call __construct function
  194. if (ctor_ptr != NULL) {
  195. v8js_call_php_func(Z_OBJ(value), ctor_ptr, isolate, info TSRMLS_CC);
  196. }
  197. php_object = v8::External::New(isolate, Z_OBJ(value));
  198. }
  199. newobj->SetAlignedPointerInInternalField(0, ext_tmpl->Value());
  200. newobj->SetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY), php_object);
  201. // Since we got to decrease the reference count again, in case v8 garbage collector
  202. // decides to dispose the JS object, we add a weak persistent handle and register
  203. // a callback function that removes the reference.
  204. ctx->weak_objects[Z_OBJ(value)].Reset(isolate, newobj);
  205. ctx->weak_objects[Z_OBJ(value)].SetWeak(Z_OBJ(value), v8js_weak_object_callback);
  206. // Just tell v8 that we're allocating some external memory
  207. // (for the moment we just always tell 1k instead of trying to find out actual values)
  208. isolate->AdjustAmountOfExternalAllocatedMemory(1024);
  209. }
  210. /* }}} */
  211. static void v8js_weak_object_callback(const v8::WeakCallbackData<v8::Object, zend_object> &data) {
  212. v8::Isolate *isolate = data.GetIsolate();
  213. zend_object *object = data.GetParameter();
  214. zval value;
  215. ZVAL_OBJ(&value, object);
  216. zval_dtor(&value);
  217. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  218. ctx->weak_objects.at(object).Reset();
  219. ctx->weak_objects.erase(object);
  220. isolate->AdjustAmountOfExternalAllocatedMemory(-1024);
  221. }
  222. static void v8js_weak_closure_callback(const v8::WeakCallbackData<v8::Object, v8js_tmpl_t> &data) {
  223. v8::Isolate *isolate = data.GetIsolate();
  224. v8js_tmpl_t *persist_tpl_ = data.GetParameter();
  225. persist_tpl_->Reset();
  226. delete persist_tpl_;
  227. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  228. ctx->weak_closures.at(persist_tpl_).Reset();
  229. ctx->weak_closures.erase(persist_tpl_);
  230. };
  231. /* These are not defined by Zend */
  232. #define ZEND_WAKEUP_FUNC_NAME "__wakeup"
  233. #define ZEND_SLEEP_FUNC_NAME "__sleep"
  234. #define ZEND_SET_STATE_FUNC_NAME "__set_state"
  235. #define IS_MAGIC_FUNC(mname) \
  236. ((ZSTR_LEN(key) == sizeof(mname) - 1) && \
  237. !strncasecmp(ZSTR_VAL(key), mname, ZSTR_LEN(key)))
  238. #define PHP_V8JS_CALLBACK(isolate, mptr, tmpl) \
  239. v8::FunctionTemplate::New((isolate), v8js_php_callback, v8::External::New((isolate), mptr), v8::Signature::New((isolate), tmpl))->GetFunction()
  240. static void v8js_named_property_enumerator(const v8::PropertyCallbackInfo<v8::Array> &info) /* {{{ */
  241. {
  242. // note: 'special' properties like 'constructor' are not enumerated.
  243. v8::Isolate *isolate = info.GetIsolate();
  244. v8::Local<v8::Object> self = info.Holder();
  245. v8::Local<v8::Array> result = v8::Array::New(isolate, 0);
  246. uint32_t result_len = 0;
  247. V8JS_TSRMLS_FETCH();
  248. zend_class_entry *ce;
  249. void *ptr;
  250. HashTable *proptable;
  251. HashPosition pos;
  252. zend_string *key;
  253. ulong index;
  254. zend_object *object = reinterpret_cast<zend_object *>(v8::External::Cast(*self->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY)))->Value());
  255. ce = object->ce;
  256. /* enumerate all methods */
  257. ZEND_HASH_FOREACH_STR_KEY_PTR(&ce->function_table, key, ptr) {
  258. zend_function *method_ptr = reinterpret_cast<zend_function *>(ptr);
  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_ZSTR(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. } ZEND_HASH_FOREACH_END();
  287. /* enumerate all properties */
  288. /* Z_OBJPROP uses the get_properties handler */
  289. zval tmp_zv;
  290. ZVAL_OBJ(&tmp_zv, object);
  291. proptable = Z_OBJPROP(tmp_zv);
  292. zval *data;
  293. ZEND_HASH_FOREACH_KEY_VAL(proptable, index, key, data) {
  294. if(key) {
  295. /* skip protected and private members */
  296. if(ZSTR_VAL(key)[0] == '\0') {
  297. continue;
  298. }
  299. // prefix enumerated property names with '$' so they can be
  300. // dereferenced unambiguously (ie, don't conflict with method
  301. // names)
  302. char *prefixed = static_cast<char *>(emalloc(ZSTR_LEN(key) + 2));
  303. prefixed[0] = '$';
  304. strncpy(prefixed + 1, ZSTR_VAL(key), ZSTR_LEN(key) + 1);
  305. result->Set(result_len++, V8JS_STRL(prefixed, ZSTR_LEN(key) + 1));
  306. efree(prefixed);
  307. } else {
  308. // even numeric indices are enumerated as strings in JavaScript
  309. result->Set(result_len++, V8JS_FLOAT((double) index)->ToString());
  310. }
  311. } ZEND_HASH_FOREACH_END();
  312. /* done */
  313. info.GetReturnValue().Set(result);
  314. }
  315. /* }}} */
  316. static void v8js_invoke_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  317. {
  318. v8::Isolate *isolate = info.GetIsolate();
  319. v8::Local<v8::Object> self = info.Holder();
  320. v8::Local<v8::Function> cb = v8::Local<v8::Function>::Cast(info.Data());
  321. int argc = info.Length(), i;
  322. v8::Local<v8::Value> *argv = static_cast<v8::Local<v8::Value> *>(alloca(sizeof(v8::Local<v8::Value>) * argc));
  323. v8::Local<v8::Value> result;
  324. V8JS_TSRMLS_FETCH();
  325. for (i=0; i<argc; i++) {
  326. new(&argv[i]) v8::Local<v8::Value>;
  327. argv[i] = info[i];
  328. }
  329. if (info.IsConstructCall()) {
  330. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  331. v8::Local<v8::String> str = self->GetConstructorName()->ToString();
  332. v8::String::Utf8Value str_value(str);
  333. zend_string *constructor_name = zend_string_init(ToCString(str_value), str->Utf8Length(), 0);
  334. zend_class_entry *ce = zend_lookup_class(constructor_name TSRMLS_CC);
  335. zend_string_release(constructor_name);
  336. v8::Local<v8::FunctionTemplate> new_tpl;
  337. new_tpl = v8::Local<v8::FunctionTemplate>::New
  338. (isolate, ctx->template_cache.at(ce->name));
  339. result = new_tpl->GetFunction()->NewInstance(argc, argv);
  340. } else {
  341. result = cb->Call(self, argc, argv);
  342. }
  343. info.GetReturnValue().Set(result);
  344. }
  345. /* }}} */
  346. // this is a magic '__call' implementation for PHP classes which don't actually
  347. // have a '__call' magic function. This way we can always force a method
  348. // call (as opposed to a property get) from JavaScript using __call.
  349. static void v8js_fake_call_impl(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  350. {
  351. v8::Isolate *isolate = info.GetIsolate();
  352. v8::Local<v8::Object> self = info.Holder();
  353. v8::Handle<v8::Value> return_value;
  354. char *error;
  355. int error_len;
  356. V8JS_TSRMLS_FETCH();
  357. zend_class_entry *ce;
  358. zend_object *object = reinterpret_cast<zend_object *>(v8::External::Cast(*self->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY)))->Value());
  359. ce = object->ce;
  360. // first arg is method name, second arg is array of args.
  361. if (info.Length() < 2) {
  362. error_len = spprintf(&error, 0,
  363. "%s::__call expects 2 parameters, %d given",
  364. ce->name, (int) info.Length());
  365. return_value = V8JS_THROW(isolate, TypeError, error, error_len);
  366. efree(error);
  367. info.GetReturnValue().Set(return_value);
  368. return;
  369. }
  370. if (!info[1]->IsArray()) {
  371. error_len = spprintf(&error, 0,
  372. "%s::__call expects 2nd parameter to be an array",
  373. ce->name);
  374. return_value = V8JS_THROW(isolate, TypeError, error, error_len);
  375. efree(error);
  376. info.GetReturnValue().Set(return_value);
  377. return;
  378. }
  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(isolate, TypeError, error, error_len);
  387. efree(error);
  388. info.GetReturnValue().Set(return_value);
  389. return;
  390. }
  391. v8::Local<v8::String> str = info[0]->ToString();
  392. v8::String::Utf8Value str_value(str);
  393. const char *method_c_name = ToCString(str_value);
  394. zend_string *method_name = zend_string_init(method_c_name, str->Utf8Length(), 0);
  395. // okay, look up the method name and manually invoke it.
  396. const zend_object_handlers *h = object->handlers;
  397. zend_function *method_ptr = h->get_method(&object, method_name, NULL TSRMLS_CC);
  398. zend_string_release(method_name);
  399. if (method_ptr == NULL ||
  400. (method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) == 0 ||
  401. (method_ptr->common.fn_flags & (ZEND_ACC_CTOR|ZEND_ACC_DTOR|ZEND_ACC_CLONE)) != 0) {
  402. error_len = spprintf(&error, 0,
  403. "%s::__call to %s method %s", ce->name,
  404. (method_ptr == NULL) ? "undefined" : "non-public", method_name);
  405. return_value = V8JS_THROW(isolate, TypeError, error, error_len);
  406. efree(error);
  407. info.GetReturnValue().Set(return_value);
  408. return;
  409. }
  410. v8::Local<v8::FunctionTemplate> tmpl =
  411. v8::Local<v8::FunctionTemplate>::New
  412. (isolate, *reinterpret_cast<v8js_tmpl_t *>(self->GetAlignedPointerFromInternalField(0)));
  413. // use v8js_php_callback to actually execute the method
  414. v8::Local<v8::Function> cb = PHP_V8JS_CALLBACK(isolate, method_ptr, tmpl);
  415. uint32_t i, argc = args->Length();
  416. v8::Local<v8::Value> *argv = static_cast<v8::Local<v8::Value> *>(alloca(sizeof(v8::Local<v8::Value>) * argc));
  417. for (i=0; i<argc; i++) {
  418. new(&argv[i]) v8::Local<v8::Value>;
  419. argv[i] = args->Get(i);
  420. }
  421. return_value = cb->Call(info.This(), (int) argc, argv);
  422. info.GetReturnValue().Set(return_value);
  423. }
  424. /* }}} */
  425. /* This method handles named property and method get/set/query/delete. */
  426. template<typename T>
  427. inline v8::Local<v8::Value> 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) /* {{{ */
  428. {
  429. v8::Isolate *isolate = info.GetIsolate();
  430. v8::String::Utf8Value cstr(property);
  431. const char *name = ToCString(cstr);
  432. uint name_len = property->Utf8Length();
  433. char *lower = estrndup(name, name_len);
  434. zend_string *method_name;
  435. v8::Local<v8::Object> self = info.Holder();
  436. v8::Local<v8::Value> ret_value;
  437. v8::Local<v8::Function> cb;
  438. V8JS_TSRMLS_FETCH();
  439. zend_class_entry *scope, *ce;
  440. zend_function *method_ptr = NULL;
  441. zval php_value;
  442. zend_object *object = reinterpret_cast<zend_object *>(v8::External::Cast(*self->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY)))->Value());
  443. zval zobject;
  444. ZVAL_OBJ(&zobject, object);
  445. v8::Local<v8::FunctionTemplate> tmpl =
  446. v8::Local<v8::FunctionTemplate>::New
  447. (isolate, *reinterpret_cast<v8js_tmpl_t *>(self->GetAlignedPointerFromInternalField(0)));
  448. ce = scope = object->ce;
  449. /* First, check the (case-insensitive) method table */
  450. php_strtolower(lower, name_len);
  451. method_name = zend_string_init(lower, name_len, 0);
  452. // toString() -> __tostring()
  453. if (name_len == 8 && strcmp(name, "toString") == 0) {
  454. zend_string_release(method_name);
  455. method_name = zend_string_init(ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME) - 1, 0);
  456. }
  457. bool is_constructor = (name_len == 11 && strcmp(name, "constructor") == 0);
  458. bool is_magic_call = (ZSTR_LEN(method_name) == 6 && strcmp(ZSTR_VAL(method_name), "__call") == 0);
  459. if (is_constructor ||
  460. (name[0] != '$' /* leading '$' means property, not method */ &&
  461. (method_ptr = reinterpret_cast<zend_function *>
  462. (zend_hash_find_ptr(&ce->function_table, method_name))) &&
  463. ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) != 0) && /* Allow only public methods */
  464. ((method_ptr->common.fn_flags & (ZEND_ACC_CTOR|ZEND_ACC_DTOR|ZEND_ACC_CLONE)) == 0) /* no __construct, __destruct(), or __clone() functions */
  465. ) || (method_ptr=NULL, is_magic_call)
  466. ) {
  467. if (callback_type == V8JS_PROP_GETTER) {
  468. if (is_constructor) {
  469. // Don't set a return value here, i.e. indicate that we don't
  470. // have a special value. V8 "knows" the constructor anyways
  471. // (from the template) and will use that.
  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(isolate,
  479. v8js_fake_call_impl, V8JS_NULL,
  480. v8::Signature::New(isolate, tmpl))->GetFunction();
  481. cb->SetName(property);
  482. ret_value = cb;
  483. } else {
  484. ret_value = PHP_V8JS_CALLBACK(isolate, method_ptr, tmpl);
  485. }
  486. }
  487. } else if (callback_type == V8JS_PROP_QUERY) {
  488. // methods are not enumerable
  489. ret_value = V8JS_UINT(v8::ReadOnly|v8::DontEnum|v8::DontDelete);
  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. zval zname;
  504. ZVAL_STRINGL(&zname, name, name_len);
  505. if (callback_type == V8JS_PROP_GETTER) {
  506. /* Nope, not a method -- must be a (case-sensitive) property */
  507. zend_property_info *property_info = zend_get_property_info(ce, Z_STR(zname), 1 TSRMLS_CC);
  508. if(property_info &&
  509. property_info != ZEND_WRONG_PROPERTY_INFO &&
  510. property_info->flags & ZEND_ACC_PUBLIC) {
  511. zval *property_val = zend_read_property(NULL, &zobject, V8JS_CONST name, name_len, true, &php_value TSRMLS_CC);
  512. // special case uninitialized_zval_ptr and return an empty value
  513. // (indicating that we don't intercept this property) if the
  514. // property doesn't exist.
  515. if (property_val == &EG(uninitialized_zval)) {
  516. ret_value = v8::Handle<v8::Value>();
  517. } else {
  518. // wrap it
  519. ret_value = zval_to_v8js(property_val, isolate TSRMLS_CC);
  520. /* We don't own the reference to php_value... unless the
  521. * returned refcount was 0, in which case the below code
  522. * will free it. */
  523. zval_add_ref(property_val);
  524. zval_ptr_dtor(property_val);
  525. }
  526. }
  527. else if (ce->__get
  528. /* Allow only public methods */
  529. && ((ce->__get->common.fn_flags & ZEND_ACC_PUBLIC) != 0)) {
  530. /* Okay, let's call __get. */
  531. zend_call_method_with_1_params(&zobject, ce, &ce->__get, ZEND_GET_FUNC_NAME, &php_value, &zname);
  532. ret_value = zval_to_v8js(&php_value, isolate TSRMLS_CC);
  533. zval_dtor(&php_value);
  534. }
  535. } else if (callback_type == V8JS_PROP_SETTER) {
  536. int flags = V8JS_GLOBAL_GET_FLAGS(isolate);
  537. if (v8js_to_zval(set_value, &php_value, flags, isolate TSRMLS_CC) != SUCCESS) {
  538. ret_value = v8::Handle<v8::Value>();
  539. }
  540. else {
  541. zend_property_info *property_info = zend_get_property_info(ce, Z_STR(zname), 1 TSRMLS_CC);
  542. if(property_info &&
  543. property_info != ZEND_WRONG_PROPERTY_INFO &&
  544. property_info->flags & ZEND_ACC_PUBLIC) {
  545. zend_update_property(scope, &zobject, V8JS_CONST name, name_len, &php_value TSRMLS_CC);
  546. ret_value = set_value;
  547. }
  548. else if (ce->__set
  549. /* Allow only public methods */
  550. && ((ce->__set->common.fn_flags & ZEND_ACC_PUBLIC) != 0)) {
  551. /* Okay, let's call __set. */
  552. zval php_ret_value;
  553. zend_call_method_with_2_params(&zobject, ce, &ce->__set, ZEND_SET_FUNC_NAME, &php_ret_value, &zname, &php_value);
  554. ret_value = zval_to_v8js(&php_ret_value, isolate TSRMLS_CC);
  555. zval_ptr_dtor(&php_value);
  556. }
  557. }
  558. // if PHP wanted to hold on to this value, update_property would
  559. // have bumped the refcount
  560. zval_ptr_dtor(&php_value);
  561. } else if (callback_type == V8JS_PROP_QUERY ||
  562. callback_type == V8JS_PROP_DELETER) {
  563. const zend_object_handlers *h = object->handlers;
  564. if (callback_type == V8JS_PROP_QUERY) {
  565. if (h->has_property(&zobject, &zname, 0, NULL TSRMLS_CC)) {
  566. ret_value = V8JS_UINT(v8::None);
  567. } else {
  568. ret_value = v8::Handle<v8::Value>(); // empty handle
  569. }
  570. } else {
  571. zend_property_info *property_info = zend_get_property_info(ce, Z_STR(zname), 1 TSRMLS_CC);
  572. if(property_info &&
  573. property_info != ZEND_WRONG_PROPERTY_INFO &&
  574. property_info->flags & ZEND_ACC_PUBLIC) {
  575. h->unset_property(&zobject, &zname, NULL TSRMLS_CC);
  576. ret_value = V8JS_TRUE();
  577. }
  578. else {
  579. ret_value = v8::Handle<v8::Value>(); // empty handle
  580. }
  581. }
  582. } else {
  583. /* shouldn't reach here! but bail safely */
  584. ret_value = v8::Handle<v8::Value>();
  585. }
  586. zval_dtor(&zname);
  587. }
  588. zend_string_release(method_name);
  589. efree(lower);
  590. return ret_value;
  591. }
  592. /* }}} */
  593. static void v8js_named_property_getter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */
  594. {
  595. info.GetReturnValue().Set(v8js_named_property_callback(property, info, V8JS_PROP_GETTER));
  596. }
  597. /* }}} */
  598. static void v8js_named_property_setter(v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */
  599. {
  600. info.GetReturnValue().Set(v8js_named_property_callback(property, info, V8JS_PROP_SETTER, value));
  601. }
  602. /* }}} */
  603. static void v8js_named_property_query(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Integer> &info) /* {{{ */
  604. {
  605. v8::Local<v8::Value> r = v8js_named_property_callback(property, info, V8JS_PROP_QUERY);
  606. if (!r.IsEmpty()) {
  607. info.GetReturnValue().Set(r->ToInteger());
  608. }
  609. }
  610. /* }}} */
  611. static void v8js_named_property_deleter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Boolean> &info) /* {{{ */
  612. {
  613. v8::Local<v8::Value> r = v8js_named_property_callback(property, info, V8JS_PROP_DELETER);
  614. if (!r.IsEmpty()) {
  615. info.GetReturnValue().Set(r->ToBoolean());
  616. }
  617. }
  618. /* }}} */
  619. static v8::Handle<v8::Object> v8js_wrap_object(v8::Isolate *isolate, zend_class_entry *ce, zval *value TSRMLS_DC) /* {{{ */
  620. {
  621. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  622. v8::Local<v8::FunctionTemplate> new_tpl;
  623. v8js_tmpl_t *persist_tpl_;
  624. try {
  625. new_tpl = v8::Local<v8::FunctionTemplate>::New
  626. (isolate, ctx->template_cache.at(ce->name));
  627. }
  628. catch (const std::out_of_range &) {
  629. /* No cached v8::FunctionTemplate available as of yet, create one. */
  630. new_tpl = v8::FunctionTemplate::New(isolate, 0);
  631. new_tpl->SetClassName(V8JS_ZSTR(ce->name));
  632. new_tpl->InstanceTemplate()->SetInternalFieldCount(1);
  633. if (ce == zend_ce_closure) {
  634. /* Got a closure, mustn't cache ... */
  635. persist_tpl_ = new v8js_tmpl_t(isolate, new_tpl);
  636. /* We'll free persist_tpl_ via v8js_weak_closure_callback, below */
  637. new_tpl->InstanceTemplate()->SetCallAsFunctionHandler(v8js_php_callback);
  638. } else {
  639. /* Add new v8::FunctionTemplate to tpl_map, as long as it is not a closure. */
  640. persist_tpl_ = &ctx->template_cache[ce->name];
  641. persist_tpl_->Reset(isolate, new_tpl);
  642. /* We'll free persist_tpl_ when template_cache is destroyed */
  643. v8::Local<v8::ObjectTemplate> inst_tpl = new_tpl->InstanceTemplate();
  644. v8::NamedPropertyGetterCallback getter = v8js_named_property_getter;
  645. v8::NamedPropertyEnumeratorCallback enumerator = v8js_named_property_enumerator;
  646. /* Check for ArrayAccess object */
  647. if (V8JSG(use_array_access) && ce) {
  648. bool has_array_access = false;
  649. bool has_countable = false;
  650. for (int i = 0; i < ce->num_interfaces; i ++) {
  651. if (strcmp (ZSTR_VAL(ce->interfaces[i]->name), "ArrayAccess") == 0) {
  652. has_array_access = true;
  653. }
  654. else if (strcmp (ZSTR_VAL(ce->interfaces[i]->name), "Countable") == 0) {
  655. has_countable = true;
  656. }
  657. }
  658. if(has_array_access && has_countable) {
  659. inst_tpl->SetIndexedPropertyHandler(v8js_array_access_getter,
  660. v8js_array_access_setter,
  661. v8js_array_access_query,
  662. v8js_array_access_deleter,
  663. v8js_array_access_enumerator);
  664. /* Switch to special ArrayAccess getter, which falls back to
  665. * v8js_named_property_getter, but possibly bridges the
  666. * call to Array.prototype functions. */
  667. getter = v8js_array_access_named_getter;
  668. /* Overwrite enumerator, since for(... in ...) loop should
  669. * not see the methods but iterate over the elements. */
  670. enumerator = 0;
  671. }
  672. }
  673. // Finish setup of new_tpl
  674. inst_tpl->SetNamedPropertyHandler
  675. (getter, /* getter */
  676. v8js_named_property_setter, /* setter */
  677. v8js_named_property_query, /* query */
  678. v8js_named_property_deleter, /* deleter */
  679. enumerator, /* enumerator */
  680. V8JS_NULL /* data */
  681. );
  682. // add __invoke() handler
  683. zend_string *invoke_str = zend_string_init
  684. (ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME) - 1, 0);
  685. zend_function *invoke_method_ptr = reinterpret_cast<zend_function *>
  686. (zend_hash_find_ptr(&ce->function_table, invoke_str));
  687. if (invoke_method_ptr &&
  688. invoke_method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) {
  689. new_tpl->InstanceTemplate()->SetCallAsFunctionHandler(v8js_invoke_callback, PHP_V8JS_CALLBACK(isolate, invoke_method_ptr, new_tpl));
  690. }
  691. zend_string_release(invoke_str);
  692. }
  693. v8::Local<v8::Array> call_handler_data = v8::Array::New(isolate, 2);
  694. call_handler_data->Set(0, v8::External::New(isolate, persist_tpl_));
  695. call_handler_data->Set(1, v8::External::New(isolate, ce));
  696. new_tpl->SetCallHandler(v8js_construct_callback, call_handler_data);
  697. }
  698. // Create v8 wrapper object
  699. v8::Handle<v8::Value> external = v8::External::New(isolate, Z_OBJ_P(value));
  700. v8::Handle<v8::Object> newobj = new_tpl->GetFunction()->NewInstance(1, &external);
  701. if (ce == zend_ce_closure) {
  702. // free uncached function template when object is freed
  703. ctx->weak_closures[persist_tpl_].Reset(isolate, newobj);
  704. ctx->weak_closures[persist_tpl_].SetWeak(persist_tpl_, v8js_weak_closure_callback);
  705. }
  706. return newobj;
  707. }
  708. /* }}} */
  709. static v8::Handle<v8::Object> v8js_wrap_array_to_object(v8::Isolate *isolate, zval *value TSRMLS_DC) /* {{{ */
  710. {
  711. int i;
  712. HashPosition pos;
  713. zend_string *key;
  714. ulong index;
  715. // @todo re-use template likewise
  716. v8::Local<v8::FunctionTemplate> new_tpl = v8::FunctionTemplate::New(isolate, 0);
  717. /* Call it Array, but it is not a native array, especially it doesn't have
  718. * have the typical Array.prototype functions. */
  719. new_tpl->SetClassName(V8JS_SYM("Array"));
  720. v8::Handle<v8::Object> newobj = new_tpl->InstanceTemplate()->NewInstance();
  721. HashTable *myht = HASH_OF(value);
  722. i = myht ? zend_hash_num_elements(myht) : 0;
  723. if (i > 0)
  724. {
  725. zval *data;
  726. HashTable *tmp_ht;
  727. ZEND_HASH_FOREACH_KEY_VAL(myht, index, key, data) {
  728. tmp_ht = HASH_OF(data);
  729. if (tmp_ht) {
  730. ZEND_HASH_INC_APPLY_COUNT(tmp_ht);
  731. }
  732. if (key) {
  733. if (ZSTR_VAL(key)[0] == '\0' && Z_TYPE_P(value) == IS_OBJECT) {
  734. /* Skip protected and private members. */
  735. if (tmp_ht) {
  736. ZEND_HASH_DEC_APPLY_COUNT(tmp_ht);
  737. }
  738. continue;
  739. }
  740. newobj->Set(V8JS_ZSTR(key), zval_to_v8js(data, isolate TSRMLS_CC));
  741. } else {
  742. newobj->Set(index, zval_to_v8js(data, isolate TSRMLS_CC));
  743. }
  744. if (tmp_ht) {
  745. ZEND_HASH_DEC_APPLY_COUNT(tmp_ht);
  746. }
  747. } ZEND_HASH_FOREACH_END();
  748. }
  749. return newobj;
  750. }
  751. /* }}} */
  752. v8::Handle<v8::Value> v8js_hash_to_jsobj(zval *value, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  753. {
  754. HashTable *myht;
  755. zend_class_entry *ce = NULL;
  756. if (Z_TYPE_P(value) == IS_ARRAY) {
  757. myht = HASH_OF(value);
  758. } else {
  759. myht = Z_OBJPROP_P(value);
  760. ce = Z_OBJCE_P(value);
  761. }
  762. /* Prevent recursion */
  763. if (myht && ZEND_HASH_GET_APPLY_COUNT(myht) > 1) {
  764. return V8JS_NULL;
  765. }
  766. /* Special case, passing back object originating from JS to JS */
  767. if (ce == php_ce_v8function) {
  768. v8js_v8object *c = Z_V8JS_V8OBJECT_OBJ_P(value);
  769. if(isolate != c->ctx->isolate) {
  770. php_error_docref(NULL TSRMLS_CC, E_WARNING, "V8Function object passed to wrong V8Js instance");
  771. return V8JS_NULL;
  772. }
  773. return v8::Local<v8::Value>::New(isolate, c->v8obj);
  774. }
  775. /* If it's a PHP object, wrap it */
  776. if (ce) {
  777. return v8js_wrap_object(isolate, ce, value TSRMLS_CC);
  778. }
  779. /* Associative PHP arrays cannot be wrapped to JS arrays, convert them to
  780. * JS objects and attach all their array keys as properties. */
  781. return v8js_wrap_array_to_object(isolate, value TSRMLS_CC);
  782. }
  783. /* }}} */
  784. /*
  785. * Local variables:
  786. * tab-width: 4
  787. * c-basic-offset: 4
  788. * End:
  789. * vim600: noet sw=4 ts=4 fdm=marker
  790. * vim<600: noet sw=4 ts=4
  791. */