v8js_object_export.cc 33 KB

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