v8js_convert.cc 37 KB

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