v8js_object_export.cc 34 KB

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