v8js_convert.cc 31 KB

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