v8js_object_export.cc 33 KB

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