v8js_object_export.cc 34 KB

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