v8js_object_export.cc 33 KB

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