v8js_object_export.cc 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  1. /*
  2. +----------------------------------------------------------------------+
  3. | PHP Version 5 |
  4. +----------------------------------------------------------------------+
  5. | Copyright (c) 1997-2016 The PHP Group |
  6. +----------------------------------------------------------------------+
  7. | http://www.opensource.org/licenses/mit-license.php MIT License |
  8. +----------------------------------------------------------------------+
  9. | Author: Jani Taskinen <[email protected]> |
  10. | Author: Patrick Reilly <[email protected]> |
  11. | Author: Stefan Siegl <[email protected]> |
  12. +----------------------------------------------------------------------+
  13. */
  14. #ifdef HAVE_CONFIG_H
  15. #include "config.h"
  16. #endif
  17. extern "C" {
  18. #include "php.h"
  19. #include "ext/date/php_date.h"
  20. #include "ext/standard/php_string.h"
  21. #include "zend_interfaces.h"
  22. #include "zend_closures.h"
  23. #include "zend_exceptions.h"
  24. }
  25. #include "php_v8js_macros.h"
  26. #include "v8js_array_access.h"
  27. #include "v8js_object_export.h"
  28. #include "v8js_v8object_class.h"
  29. static void v8js_weak_object_callback(const v8::WeakCallbackInfo<zval> &data);
  30. /* Callback for PHP methods and functions */
  31. 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) /* {{{ */
  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_ptr = NULL, **argv = NULL;
  37. zend_uint 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. INIT_ZVAL(fname);
  46. ZVAL_STRING(&fname, method_ptr->common.function_name, 0);
  47. /* zend_fcall_info */
  48. fci.size = sizeof(fci);
  49. fci.function_table = &ce->function_table;
  50. fci.function_name = &fname;
  51. fci.symbol_table = NULL;
  52. fci.object_ptr = value;
  53. fci.retval_ptr_ptr = &retval_ptr;
  54. fci.param_count = 0;
  55. /* Check for passed vs required number of arguments */
  56. if (argc < min_num_args)
  57. {
  58. error_len = spprintf(&error, 0,
  59. "%s::%s() expects %s %d parameter%s, %d given",
  60. ce->name,
  61. method_ptr->common.function_name,
  62. min_num_args == max_num_args ? "exactly" : argc < min_num_args ? "at least" : "at most",
  63. argc < min_num_args ? min_num_args : max_num_args,
  64. (argc < min_num_args ? min_num_args : max_num_args) == 1 ? "" : "s",
  65. argc);
  66. return_value = V8JS_THROW(isolate, TypeError, error, error_len);
  67. if (ce == zend_ce_closure) {
  68. efree(const_cast<char*>(method_ptr->internal_function.function_name));
  69. efree(method_ptr);
  70. }
  71. efree(error);
  72. info.GetReturnValue().Set(return_value);
  73. return;
  74. }
  75. /* Convert parameters passed from V8 */
  76. if (argc) {
  77. fci.params = (zval ***) safe_emalloc(argc, sizeof(zval **), 0);
  78. argv = (zval **) safe_emalloc(argc, sizeof(zval *), 0);
  79. for (i = 0; i < argc; i++) {
  80. if (info[i]->IsObject() && info[i]->ToObject()->InternalFieldCount() == 2) {
  81. /* This is a PHP object, passed to JS and back. */
  82. argv[i] = reinterpret_cast<zval *>(info[i]->ToObject()->GetAlignedPointerFromInternalField(1));
  83. Z_ADDREF_P(argv[i]);
  84. } else {
  85. MAKE_STD_ZVAL(argv[i]);
  86. if (v8js_to_zval(info[i], argv[i], ctx->flags, isolate TSRMLS_CC) == FAILURE) {
  87. fci.param_count++;
  88. error_len = spprintf(&error, 0, "converting parameter #%d passed to %s() failed", i + 1, method_ptr->common.function_name);
  89. return_value = V8JS_THROW(isolate, Error, error, error_len);
  90. efree(error);
  91. goto failure;
  92. }
  93. }
  94. fci.params[fci.param_count++] = &argv[i];
  95. }
  96. } else {
  97. fci.params = NULL;
  98. }
  99. fci.no_separation = 1;
  100. info.GetReturnValue().Set(V8JS_NULL);
  101. zend_try {
  102. {
  103. isolate->Exit();
  104. v8::Unlocker unlocker(isolate);
  105. /* zend_fcall_info_cache */
  106. fcc.initialized = 1;
  107. fcc.function_handler = method_ptr;
  108. fcc.calling_scope = ce;
  109. fcc.called_scope = ce;
  110. fcc.object_ptr = value;
  111. zend_call_function(&fci, &fcc TSRMLS_CC);
  112. }
  113. isolate->Enter();
  114. }
  115. zend_catch {
  116. v8js_terminate_execution(isolate);
  117. V8JSG(fatal_error_abort) = 1;
  118. }
  119. zend_end_try();
  120. failure:
  121. /* Cleanup */
  122. if (argc) {
  123. for (i = 0; i < fci.param_count; i++) {
  124. zval_ptr_dtor(&argv[i]);
  125. }
  126. efree(argv);
  127. efree(fci.params);
  128. }
  129. if(EG(exception) && !V8JSG(compat_php_exceptions)) {
  130. if(ctx->flags & V8JS_FLAG_PROPAGATE_PHP_EXCEPTIONS) {
  131. return_value = isolate->ThrowException(zval_to_v8js(EG(exception), isolate TSRMLS_CC));
  132. zend_clear_exception(TSRMLS_C);
  133. } else {
  134. v8js_terminate_execution(isolate);
  135. }
  136. } else if (retval_ptr == value) {
  137. // special case: "return $this"
  138. return_value = info.Holder();
  139. } else if (retval_ptr != NULL) {
  140. return_value = zval_to_v8js(retval_ptr, isolate TSRMLS_CC);
  141. }
  142. if (retval_ptr != NULL) {
  143. zval_ptr_dtor(&retval_ptr);
  144. }
  145. info.GetReturnValue().Set(return_value);
  146. }
  147. /* }}} */
  148. /* Callback for PHP methods and functions */
  149. void v8js_php_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  150. {
  151. v8::Isolate *isolate = info.GetIsolate();
  152. v8::Local<v8::Object> self = info.Holder();
  153. V8JS_TSRMLS_FETCH();
  154. zval *value = reinterpret_cast<zval *>(self->GetAlignedPointerFromInternalField(1));
  155. zend_function *method_ptr;
  156. zend_class_entry *ce = Z_OBJCE_P(value);
  157. /* Set method_ptr from v8::External or fetch the closure invoker */
  158. if (!info.Data().IsEmpty() && info.Data()->IsExternal()) {
  159. method_ptr = static_cast<zend_function *>(v8::External::Cast(*info.Data())->Value());
  160. } else {
  161. method_ptr = zend_get_closure_invoke_method(value TSRMLS_CC);
  162. }
  163. return v8js_call_php_func(value, ce, method_ptr, isolate, info TSRMLS_CC);
  164. }
  165. /* Callback for PHP constructor calls */
  166. static void v8js_construct_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  167. {
  168. v8::Isolate *isolate = info.GetIsolate();
  169. info.GetReturnValue().Set(V8JS_UNDEFINED);
  170. v8::Handle<v8::Object> newobj = info.This();
  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. v8::Local<v8::External> php_object = v8::Local<v8::External>::Cast(info[0]);
  182. value = reinterpret_cast<zval *>(php_object->Value());
  183. if(ctx->weak_objects.count(value)) {
  184. // We already exported this object, hence no need to add another
  185. // ref, v8 won't give us a second weak-object callback anyways.
  186. newobj->SetAlignedPointerInInternalField(0, ext_tmpl->Value());
  187. newobj->SetAlignedPointerInInternalField(1, value);
  188. return;
  189. }
  190. // Increase the reference count of this value because we're storing it internally for use later
  191. // See https://github.com/preillyme/v8js/issues/6
  192. Z_ADDREF_P(value);
  193. } else {
  194. // Object created from JavaScript context. Need to create PHP object first.
  195. V8JS_TSRMLS_FETCH();
  196. zend_class_entry *ce = static_cast<zend_class_entry *>(ext_ce->Value());
  197. zend_function *ctor_ptr = ce->constructor;
  198. // Check access on __construct function, if any
  199. if (ctor_ptr != NULL && (ctor_ptr->common.fn_flags & ZEND_ACC_PUBLIC) == 0) {
  200. info.GetReturnValue().Set(isolate->ThrowException(V8JS_SYM("Call to protected __construct() not allowed")));
  201. return;
  202. }
  203. MAKE_STD_ZVAL(value);
  204. object_init_ex(value, ce);
  205. // Call __construct function
  206. if (ctor_ptr != NULL) {
  207. v8js_call_php_func(value, ce, ctor_ptr, isolate, info TSRMLS_CC);
  208. }
  209. }
  210. newobj->SetAlignedPointerInInternalField(0, ext_tmpl->Value());
  211. newobj->SetAlignedPointerInInternalField(1, value);
  212. // Since we got to decrease the reference count again, in case v8 garbage collector
  213. // decides to dispose the JS object, we add a weak persistent handle and register
  214. // a callback function that removes the reference.
  215. ctx->weak_objects[value].Reset(isolate, newobj);
  216. ctx->weak_objects[value].SetWeak(value, v8js_weak_object_callback, v8::WeakCallbackType::kParameter);
  217. // Just tell v8 that we're allocating some external memory
  218. // (for the moment we just always tell 1k instead of trying to find out actual values)
  219. isolate->AdjustAmountOfExternalAllocatedMemory(ctx->average_object_size);
  220. }
  221. /* }}} */
  222. static void v8js_weak_object_callback(const v8::WeakCallbackInfo<zval> &data) {
  223. v8::Isolate *isolate = data.GetIsolate();
  224. zval *value = data.GetParameter();
  225. zval_ptr_dtor(&value);
  226. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  227. ctx->weak_objects.at(value).Reset();
  228. ctx->weak_objects.erase(value);
  229. isolate->AdjustAmountOfExternalAllocatedMemory(-ctx->average_object_size);
  230. }
  231. static void v8js_weak_closure_callback(const v8::WeakCallbackInfo<v8js_tmpl_t> &data) {
  232. v8::Isolate *isolate = data.GetIsolate();
  233. v8js_tmpl_t *persist_tpl_ = data.GetParameter();
  234. persist_tpl_->Reset();
  235. delete persist_tpl_;
  236. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  237. ctx->weak_closures.at(persist_tpl_).Reset();
  238. ctx->weak_closures.erase(persist_tpl_);
  239. };
  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 *>(self->GetAlignedPointerFromInternalField(1));
  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 *>(self->GetAlignedPointerFromInternalField(1));
  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 *>(self->GetAlignedPointerFromInternalField(1));
  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. MAKE_STD_ZVAL(php_value);
  588. if (v8js_to_zval(set_value, php_value, ctx->flags, isolate TSRMLS_CC) != SUCCESS) {
  589. ret_value = v8::Handle<v8::Value>();
  590. }
  591. else {
  592. zval zname;
  593. INIT_ZVAL(zname);
  594. ZVAL_STRINGL(&zname, name, name_len, 0);
  595. zend_property_info *property_info = zend_get_property_info(ce, &zname, 1 TSRMLS_CC);
  596. if(property_info && property_info->flags & ZEND_ACC_PUBLIC) {
  597. zend_update_property(scope, object, V8JS_CONST name, name_len, php_value TSRMLS_CC);
  598. ret_value = set_value;
  599. }
  600. else if (zend_hash_find(&ce->function_table, "__set", 6, (void**)&method_ptr) == SUCCESS
  601. /* Allow only public methods */
  602. && ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) != 0)) {
  603. /* Okay, let's call __set. */
  604. zend_fcall_info fci;
  605. zval fmember;
  606. INIT_ZVAL(fmember);
  607. ZVAL_STRING(&fmember, "__set", 0);
  608. zval *php_ret_value;
  609. fci.size = sizeof(fci);
  610. fci.function_table = &ce->function_table;
  611. fci.function_name = &fmember;
  612. fci.symbol_table = NULL;
  613. fci.retval_ptr_ptr = &php_ret_value;
  614. zval *zname_ptr = &zname;
  615. zval **params[2];
  616. fci.param_count = 2;
  617. fci.params = params;
  618. fci.params[0] = &zname_ptr;
  619. fci.params[1] = &php_value;
  620. fci.object_ptr = object;
  621. fci.no_separation = 1;
  622. zend_call_function(&fci, NULL TSRMLS_CC);
  623. ret_value = zval_to_v8js(php_ret_value, isolate TSRMLS_CC);
  624. zval_ptr_dtor(&php_ret_value);
  625. }
  626. }
  627. // if PHP wanted to hold on to this value, update_property would
  628. // have bumped the refcount
  629. zval_ptr_dtor(&php_value);
  630. } else if (callback_type == V8JS_PROP_QUERY ||
  631. callback_type == V8JS_PROP_DELETER) {
  632. const zend_object_handlers *h = Z_OBJ_HT_P(object);
  633. zval *prop;
  634. MAKE_STD_ZVAL(prop);
  635. ZVAL_STRINGL(prop, name, name_len, 1);
  636. if (callback_type == V8JS_PROP_QUERY) {
  637. if (h->has_property(object, prop, 0 ZEND_HASH_KEY_NULL TSRMLS_CC)) {
  638. ret_value = V8JS_UINT(v8::None);
  639. } else {
  640. ret_value = v8::Handle<v8::Value>(); // empty handle
  641. }
  642. } else {
  643. zend_property_info *property_info = zend_get_property_info(ce, prop, 1 TSRMLS_CC);
  644. if(property_info && property_info->flags & ZEND_ACC_PUBLIC) {
  645. h->unset_property(object, prop ZEND_HASH_KEY_NULL TSRMLS_CC);
  646. ret_value = V8JS_BOOL(true);
  647. }
  648. else {
  649. ret_value = v8::Handle<v8::Value>(); // empty handle
  650. }
  651. }
  652. zval_ptr_dtor(&prop);
  653. } else {
  654. /* shouldn't reach here! but bail safely */
  655. ret_value = v8::Handle<v8::Value>();
  656. }
  657. }
  658. efree(lower);
  659. return ret_value;
  660. }
  661. /* }}} */
  662. static void v8js_named_property_getter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */
  663. {
  664. info.GetReturnValue().Set(v8js_named_property_callback(property, info, V8JS_PROP_GETTER));
  665. }
  666. /* }}} */
  667. static void v8js_named_property_setter(v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */
  668. {
  669. info.GetReturnValue().Set(v8js_named_property_callback(property, info, V8JS_PROP_SETTER, value));
  670. }
  671. /* }}} */
  672. static void v8js_named_property_query(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Integer> &info) /* {{{ */
  673. {
  674. v8::Local<v8::Value> r = v8js_named_property_callback(property, info, V8JS_PROP_QUERY);
  675. if (!r.IsEmpty()) {
  676. info.GetReturnValue().Set(r->ToInteger());
  677. }
  678. }
  679. /* }}} */
  680. static void v8js_named_property_deleter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Boolean> &info) /* {{{ */
  681. {
  682. v8::Local<v8::Value> r = v8js_named_property_callback(property, info, V8JS_PROP_DELETER);
  683. if (!r.IsEmpty()) {
  684. info.GetReturnValue().Set(r->ToBoolean());
  685. }
  686. }
  687. /* }}} */
  688. static v8::Handle<v8::Object> v8js_wrap_object(v8::Isolate *isolate, zend_class_entry *ce, zval *value TSRMLS_DC) /* {{{ */
  689. {
  690. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  691. v8::Local<v8::FunctionTemplate> new_tpl;
  692. v8js_tmpl_t *persist_tpl_;
  693. try {
  694. new_tpl = v8::Local<v8::FunctionTemplate>::New
  695. (isolate, ctx->template_cache.at(ce->name));
  696. }
  697. catch (const std::out_of_range &) {
  698. /* No cached v8::FunctionTemplate available as of yet, create one. */
  699. new_tpl = v8::FunctionTemplate::New(isolate, 0);
  700. new_tpl->SetClassName(V8JS_STRL(ce->name, ce->name_length));
  701. new_tpl->InstanceTemplate()->SetInternalFieldCount(2);
  702. if (ce == zend_ce_closure) {
  703. /* Got a closure, mustn't cache ... */
  704. persist_tpl_ = new v8js_tmpl_t(isolate, new_tpl);
  705. /* We'll free persist_tpl_ via v8js_weak_closure_callback, below */
  706. new_tpl->InstanceTemplate()->SetCallAsFunctionHandler(v8js_php_callback);
  707. } else {
  708. /* Add new v8::FunctionTemplate to tpl_map, as long as it is not a closure. */
  709. persist_tpl_ = &ctx->template_cache[ce->name];
  710. persist_tpl_->Reset(isolate, new_tpl);
  711. /* We'll free persist_tpl_ when template_cache is destroyed */
  712. v8::Local<v8::ObjectTemplate> inst_tpl = new_tpl->InstanceTemplate();
  713. v8::NamedPropertyGetterCallback getter = v8js_named_property_getter;
  714. v8::NamedPropertyEnumeratorCallback enumerator = v8js_named_property_enumerator;
  715. /* Check for ArrayAccess object */
  716. if (V8JSG(use_array_access) && ce) {
  717. bool has_array_access = false;
  718. bool has_countable = false;
  719. for (int i = 0; i < ce->num_interfaces; i ++) {
  720. if (strcmp (ce->interfaces[i]->name, "ArrayAccess") == 0) {
  721. has_array_access = true;
  722. }
  723. else if (strcmp (ce->interfaces[i]->name, "Countable") == 0) {
  724. has_countable = true;
  725. }
  726. }
  727. if(has_array_access && has_countable) {
  728. inst_tpl->SetIndexedPropertyHandler(v8js_array_access_getter,
  729. v8js_array_access_setter,
  730. v8js_array_access_query,
  731. v8js_array_access_deleter,
  732. v8js_array_access_enumerator);
  733. /* Switch to special ArrayAccess getter, which falls back to
  734. * v8js_named_property_getter, but possibly bridges the
  735. * call to Array.prototype functions. */
  736. getter = v8js_array_access_named_getter;
  737. /* Overwrite enumerator, since for(... in ...) loop should
  738. * not see the methods but iterate over the elements. */
  739. enumerator = 0;
  740. }
  741. }
  742. // Finish setup of new_tpl
  743. inst_tpl->SetNamedPropertyHandler
  744. (getter, /* getter */
  745. v8js_named_property_setter, /* setter */
  746. v8js_named_property_query, /* query */
  747. v8js_named_property_deleter, /* deleter */
  748. enumerator, /* enumerator */
  749. V8JS_NULL /* data */
  750. );
  751. // add __invoke() handler
  752. zend_function *invoke_method_ptr;
  753. if (zend_hash_find(&ce->function_table, ZEND_INVOKE_FUNC_NAME,
  754. sizeof(ZEND_INVOKE_FUNC_NAME),
  755. (void**)&invoke_method_ptr) == SUCCESS &&
  756. invoke_method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) {
  757. new_tpl->InstanceTemplate()->SetCallAsFunctionHandler(v8js_invoke_callback, PHP_V8JS_CALLBACK(isolate, invoke_method_ptr, new_tpl));
  758. }
  759. }
  760. v8::Local<v8::Array> call_handler_data = v8::Array::New(isolate, 2);
  761. call_handler_data->Set(0, v8::External::New(isolate, persist_tpl_));
  762. call_handler_data->Set(1, v8::External::New(isolate, ce));
  763. new_tpl->SetCallHandler(v8js_construct_callback, call_handler_data);
  764. }
  765. // Create v8 wrapper object
  766. v8::Handle<v8::Value> external = v8::External::New(isolate, value);
  767. v8::Handle<v8::Object> newobj = new_tpl->GetFunction()->NewInstance(1, &external);
  768. if (ce == zend_ce_closure) {
  769. // free uncached function template when object is freed
  770. ctx->weak_closures[persist_tpl_].Reset(isolate, newobj);
  771. ctx->weak_closures[persist_tpl_].SetWeak(persist_tpl_, v8js_weak_closure_callback, v8::WeakCallbackType::kParameter);
  772. }
  773. return newobj;
  774. }
  775. /* }}} */
  776. static v8::Handle<v8::Object> v8js_wrap_array_to_object(v8::Isolate *isolate, zval *value TSRMLS_DC) /* {{{ */
  777. {
  778. int i;
  779. HashPosition pos;
  780. char *key = NULL;
  781. uint key_len;
  782. ulong index;
  783. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  784. v8::Local<v8::FunctionTemplate> new_tpl;
  785. if(ctx->array_tmpl.IsEmpty()) {
  786. new_tpl = v8::FunctionTemplate::New(isolate, 0);
  787. /* Call it Array, but it is not a native array, especially it doesn't have
  788. * have the typical Array.prototype functions. */
  789. new_tpl->SetClassName(V8JS_SYM("Array"));
  790. /* Store for later re-use */
  791. ctx->array_tmpl.Reset(isolate, new_tpl);
  792. }
  793. else {
  794. new_tpl = v8::Local<v8::FunctionTemplate>::New(isolate, ctx->array_tmpl);
  795. }
  796. v8::Handle<v8::Object> newobj = new_tpl->InstanceTemplate()->NewInstance();
  797. HashTable *myht = HASH_OF(value);
  798. i = myht ? zend_hash_num_elements(myht) : 0;
  799. if (i > 0)
  800. {
  801. zval **data;
  802. HashTable *tmp_ht;
  803. zend_hash_internal_pointer_reset_ex(myht, &pos);
  804. for (;; zend_hash_move_forward_ex(myht, &pos)) {
  805. i = zend_hash_get_current_key_ex(myht, &key, &key_len, &index, 0, &pos);
  806. if (i == HASH_KEY_NON_EXISTANT)
  807. break;
  808. if (zend_hash_get_current_data_ex(myht, (void **) &data, &pos) == SUCCESS)
  809. {
  810. tmp_ht = HASH_OF(*data);
  811. if (tmp_ht) {
  812. tmp_ht->nApplyCount++;
  813. }
  814. if (i == HASH_KEY_IS_STRING)
  815. {
  816. if (key[0] == '\0' && Z_TYPE_P(value) == IS_OBJECT) {
  817. /* Skip protected and private members. */
  818. if (tmp_ht) {
  819. tmp_ht->nApplyCount--;
  820. }
  821. continue;
  822. }
  823. newobj->Set(V8JS_STRL(key, key_len - 1), zval_to_v8js(*data, isolate TSRMLS_CC));
  824. } else {
  825. newobj->Set(index, zval_to_v8js(*data, isolate TSRMLS_CC));
  826. }
  827. if (tmp_ht) {
  828. tmp_ht->nApplyCount--;
  829. }
  830. }
  831. }
  832. }
  833. return newobj;
  834. }
  835. /* }}} */
  836. v8::Handle<v8::Value> v8js_hash_to_jsobj(zval *value, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  837. {
  838. HashTable *myht;
  839. zend_class_entry *ce = NULL;
  840. if (Z_TYPE_P(value) == IS_ARRAY) {
  841. myht = HASH_OF(value);
  842. } else {
  843. myht = Z_OBJPROP_P(value);
  844. ce = Z_OBJCE_P(value);
  845. }
  846. /* Prevent recursion */
  847. if (myht && myht->nApplyCount > 1) {
  848. return V8JS_NULL;
  849. }
  850. /* Special case, passing back object originating from JS to JS */
  851. if (ce == php_ce_v8function || ce == php_ce_v8object) {
  852. v8js_v8object *c = (v8js_v8object *) zend_object_store_get_object(value TSRMLS_CC);
  853. if(isolate != c->ctx->isolate) {
  854. php_error_docref(NULL TSRMLS_CC, E_WARNING, "V8Function object passed to wrong V8Js instance");
  855. return V8JS_NULL;
  856. }
  857. return v8::Local<v8::Value>::New(isolate, c->v8obj);
  858. }
  859. /* If it's a PHP object, wrap it */
  860. if (ce) {
  861. return v8js_wrap_object(isolate, ce, value TSRMLS_CC);
  862. }
  863. /* Associative PHP arrays cannot be wrapped to JS arrays, convert them to
  864. * JS objects and attach all their array keys as properties. */
  865. return v8js_wrap_array_to_object(isolate, value TSRMLS_CC);
  866. }
  867. /* }}} */
  868. /*
  869. * Local variables:
  870. * tab-width: 4
  871. * c-basic-offset: 4
  872. * indent-tabs-mode: t
  873. * End:
  874. * vim600: noet sw=4 ts=4 fdm=marker
  875. * vim<600: noet sw=4 ts=4
  876. */