v8js_convert.cc 38 KB

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