v8js_convert.cc 33 KB

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