v8js_convert.cc 32 KB

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