v8js_object_export.cc 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  1. /*
  2. +----------------------------------------------------------------------+
  3. | PHP Version 7 |
  4. +----------------------------------------------------------------------+
  5. | Copyright (c) 1997-2017 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. | Author: Stefan Siegl <[email protected]> |
  12. +----------------------------------------------------------------------+
  13. */
  14. #ifdef HAVE_CONFIG_H
  15. #include "config.h"
  16. #endif
  17. #include "php_v8js_macros.h"
  18. #include "v8js_array_access.h"
  19. #include "v8js_exceptions.h"
  20. #include "v8js_generator_export.h"
  21. #include "v8js_object_export.h"
  22. #include "v8js_v8object_class.h"
  23. extern "C" {
  24. #include "ext/date/php_date.h"
  25. #include "ext/standard/php_string.h"
  26. #include "zend_interfaces.h"
  27. #include "zend_closures.h"
  28. #include "zend_exceptions.h"
  29. #include "zend_generators.h"
  30. }
  31. static void v8js_weak_object_callback(const v8::WeakCallbackInfo<zend_object> &data);
  32. /* Callback for PHP methods and functions */
  33. static void v8js_call_php_func(zend_object *object, zend_function *method_ptr, const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  34. {
  35. v8::Isolate *isolate = info.GetIsolate();
  36. v8::Local<v8::Context> v8_context = isolate->GetEnteredOrMicrotaskContext();
  37. v8::Local<v8::Value> return_value = V8JS_NULL;
  38. zend_fcall_info fci;
  39. zend_fcall_info_cache fcc;
  40. zval fname, retval;
  41. unsigned int argc = info.Length(), min_num_args = 0, max_num_args = 0;
  42. char *error;
  43. zend_ulong error_len;
  44. unsigned int i;
  45. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  46. /* Set parameter limits */
  47. min_num_args = method_ptr->common.required_num_args;
  48. max_num_args = method_ptr->common.num_args;
  49. /* Function name to call */
  50. ZVAL_STR_COPY(&fname, method_ptr->common.function_name);
  51. /* zend_fcall_info */
  52. fci.size = sizeof(fci);
  53. #if (PHP_MAJOR_VERSION == 7 && PHP_MINOR_VERSION == 0)
  54. fci.function_table = &object->ce->function_table;
  55. fci.symbol_table = NULL;
  56. #endif
  57. fci.function_name = fname;
  58. fci.object = object;
  59. fci.retval = &retval;
  60. fci.param_count = 0;
  61. /* Check for passed vs required number of arguments */
  62. if (argc < min_num_args)
  63. {
  64. error_len = spprintf(&error, 0,
  65. "%s::%s() expects %s %d parameter%s, %d given",
  66. ZSTR_VAL(object->ce->name),
  67. ZSTR_VAL(method_ptr->common.function_name),
  68. min_num_args == max_num_args ? "exactly" : argc < min_num_args ? "at least" : "at most",
  69. argc < min_num_args ? min_num_args : max_num_args,
  70. (argc < min_num_args ? min_num_args : max_num_args) == 1 ? "" : "s",
  71. argc);
  72. if (error_len > std::numeric_limits<int>::max()) {
  73. zend_throw_exception(php_ce_v8js_exception,
  74. "Generated error message length exceeds maximum supported length", 0);
  75. }
  76. else {
  77. return_value = V8JS_THROW(isolate, TypeError, error, static_cast<int>(error_len));
  78. }
  79. if (object->ce == zend_ce_closure) {
  80. zend_string_release(method_ptr->internal_function.function_name);
  81. efree(method_ptr);
  82. }
  83. efree(error);
  84. info.GetReturnValue().Set(return_value);
  85. zval_ptr_dtor(&fname);
  86. return;
  87. }
  88. /* Convert parameters passed from V8 */
  89. if (argc)
  90. {
  91. fci.params = (zval *) safe_emalloc(argc, sizeof(zval), 0);
  92. for (i = 0; i < argc; i++)
  93. {
  94. v8::Local<v8::Object> param_object;
  95. if (info[i]->IsObject() && info[i]->ToObject(v8_context).ToLocal(&param_object) && param_object->InternalFieldCount() == 2)
  96. {
  97. /* This is a PHP object, passed to JS and back. */
  98. zend_object *object = reinterpret_cast<zend_object *>(param_object->GetAlignedPointerFromInternalField(1));
  99. ZVAL_OBJ(&fci.params[i], object);
  100. Z_ADDREF_P(&fci.params[i]);
  101. }
  102. else
  103. {
  104. if (v8js_to_zval(info[i], &fci.params[i], ctx->flags, isolate) == FAILURE)
  105. {
  106. error_len = spprintf(&error, 0, "converting parameter #%d passed to %s() failed", i + 1, ZSTR_VAL(method_ptr->common.function_name));
  107. if (error_len > std::numeric_limits<int>::max()) {
  108. zend_throw_exception(php_ce_v8js_exception,
  109. "Generated error message length exceeds maximum supported length", 0);
  110. }
  111. else {
  112. return_value = V8JS_THROW(isolate, Error, error, static_cast<int>(error_len));
  113. }
  114. efree(error);
  115. goto failure;
  116. }
  117. }
  118. fci.param_count++;
  119. }
  120. } else {
  121. fci.params = NULL;
  122. }
  123. fci.no_separation = 1;
  124. info.GetReturnValue().Set(V8JS_NULL);
  125. {
  126. isolate->Exit();
  127. v8::Unlocker unlocker(isolate);
  128. zend_try {
  129. /* zend_fcall_info_cache */
  130. #if PHP_VERSION_ID < 70300
  131. fcc.initialized = 1;
  132. #endif
  133. fcc.function_handler = method_ptr;
  134. fcc.calling_scope = object->ce;
  135. fcc.called_scope = object->ce;
  136. fcc.object = object;
  137. zend_call_function(&fci, &fcc);
  138. }
  139. zend_catch {
  140. v8js_terminate_execution(isolate);
  141. V8JSG(fatal_error_abort) = 1;
  142. }
  143. zend_end_try();
  144. }
  145. isolate->Enter();
  146. failure:
  147. /* Cleanup */
  148. if (argc) {
  149. for (i = 0; i < fci.param_count; i++) {
  150. zval_ptr_dtor(&fci.params[i]);
  151. }
  152. efree(fci.params);
  153. }
  154. if(EG(exception)) {
  155. if(ctx->flags & V8JS_FLAG_PROPAGATE_PHP_EXCEPTIONS) {
  156. zval tmp_zv;
  157. ZVAL_OBJ(&tmp_zv, EG(exception));
  158. return_value = isolate->ThrowException(zval_to_v8js(&tmp_zv, isolate));
  159. zend_clear_exception();
  160. } else {
  161. v8js_terminate_execution(isolate);
  162. }
  163. } else if (Z_TYPE(retval) == IS_OBJECT && Z_OBJ(retval) == object) {
  164. // special case: "return $this"
  165. return_value = info.Holder();
  166. } else {
  167. return_value = zval_to_v8js(&retval, isolate);
  168. }
  169. zval_ptr_dtor(&retval);
  170. zval_ptr_dtor(&fname);
  171. info.GetReturnValue().Set(return_value);
  172. }
  173. /* }}} */
  174. /* Callback for PHP methods and functions */
  175. void v8js_php_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  176. {
  177. v8::Local<v8::Object> self = info.Holder();
  178. zend_object *object = reinterpret_cast<zend_object *>(self->GetAlignedPointerFromInternalField(1));
  179. zend_function *method_ptr;
  180. /* Set method_ptr from v8::External or fetch the closure invoker */
  181. if (!info.Data().IsEmpty() && info.Data()->IsExternal()) {
  182. method_ptr = static_cast<zend_function *>(v8::External::Cast(*info.Data())->Value());
  183. } else {
  184. method_ptr = zend_get_closure_invoke_method(object);
  185. }
  186. return v8js_call_php_func(object, method_ptr, info);
  187. }
  188. /* Callback for PHP constructor calls */
  189. static void v8js_construct_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  190. {
  191. v8::Isolate *isolate = info.GetIsolate();
  192. info.GetReturnValue().Set(V8JS_UNDEFINED);
  193. v8::Local<v8::Object> newobj = info.This();
  194. zval value;
  195. if (!info.IsConstructCall()) {
  196. return;
  197. }
  198. v8::Local<v8::Array> cons_data = v8::Local<v8::Array>::Cast(info.Data());
  199. v8::Local<v8::Value> cons_tmpl, cons_ce;
  200. if (!cons_data->Get(isolate->GetEnteredOrMicrotaskContext(), 0).ToLocal(&cons_tmpl)
  201. ||!cons_data->Get(isolate->GetEnteredOrMicrotaskContext(), 1).ToLocal(&cons_ce))
  202. {
  203. return;
  204. }
  205. v8::Local<v8::External> ext_tmpl = v8::Local<v8::External>::Cast(cons_tmpl);
  206. v8::Local<v8::External> ext_ce = v8::Local<v8::External>::Cast(cons_ce);
  207. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  208. if (info[0]->IsExternal()) {
  209. // Object created by v8js in v8js_hash_to_jsobj, PHP object passed as v8::External.
  210. v8::Local<v8::External> php_object = v8::Local<v8::External>::Cast(info[0]);
  211. zend_object *object = reinterpret_cast<zend_object *>(php_object->Value());
  212. ZVAL_OBJ(&value, object);
  213. if(ctx->weak_objects.count(object)) {
  214. // We already exported this object, hence no need to add another
  215. // ref, v8 won't give us a second weak-object callback anyways.
  216. newobj->SetAlignedPointerInInternalField(0, ext_tmpl->Value());
  217. newobj->SetAlignedPointerInInternalField(1, object);
  218. return;
  219. }
  220. // Increase the reference count of this value because we're storing it internally for use later
  221. // See https://github.com/phpv8/v8js/issues/6
  222. Z_ADDREF_P(&value);
  223. } else {
  224. // Object created from JavaScript context. Need to create PHP object first.
  225. zend_class_entry *ce = static_cast<zend_class_entry *>(ext_ce->Value());
  226. zend_function *ctor_ptr = ce->constructor;
  227. // Check access on __construct function, if any
  228. if (ctor_ptr != NULL && (ctor_ptr->common.fn_flags & ZEND_ACC_PUBLIC) == 0) {
  229. info.GetReturnValue().Set(isolate->ThrowException(V8JS_SYM("Call to protected __construct() not allowed")));
  230. return;
  231. }
  232. object_init_ex(&value, ce);
  233. // Call __construct function
  234. if (ctor_ptr != NULL) {
  235. v8js_call_php_func(Z_OBJ(value), ctor_ptr, info);
  236. }
  237. }
  238. newobj->SetAlignedPointerInInternalField(0, ext_tmpl->Value());
  239. newobj->SetAlignedPointerInInternalField(1, Z_OBJ(value));
  240. // Since we got to decrease the reference count again, in case v8 garbage collector
  241. // decides to dispose the JS object, we add a weak persistent handle and register
  242. // a callback function that removes the reference.
  243. ctx->weak_objects[Z_OBJ(value)].Reset(isolate, newobj);
  244. ctx->weak_objects[Z_OBJ(value)].SetWeak(Z_OBJ(value), v8js_weak_object_callback, v8::WeakCallbackType::kParameter);
  245. // Just tell v8 that we're allocating some external memory
  246. // (for the moment we just always tell 1k instead of trying to find out actual values)
  247. isolate->AdjustAmountOfExternalAllocatedMemory(ctx->average_object_size);
  248. }
  249. /* }}} */
  250. static void v8js_weak_object_callback(const v8::WeakCallbackInfo<zend_object> &data) {
  251. v8::Isolate *isolate = data.GetIsolate();
  252. zend_object *object = data.GetParameter();
  253. zval value;
  254. ZVAL_OBJ(&value, object);
  255. zval_ptr_dtor(&value);
  256. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  257. ctx->weak_objects.at(object).Reset();
  258. ctx->weak_objects.erase(object);
  259. isolate->AdjustAmountOfExternalAllocatedMemory(-ctx->average_object_size);
  260. }
  261. static void v8js_weak_closure_callback(const v8::WeakCallbackInfo<v8js_function_tmpl_t> &data) {
  262. v8::Isolate *isolate = data.GetIsolate();
  263. v8js_function_tmpl_t *persist_tpl_ = data.GetParameter();
  264. persist_tpl_->Reset();
  265. delete persist_tpl_;
  266. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  267. ctx->weak_closures.at(persist_tpl_).Reset();
  268. ctx->weak_closures.erase(persist_tpl_);
  269. };
  270. #define IS_MAGIC_FUNC(mname) \
  271. ((ZSTR_LEN(key) == sizeof(mname) - 1) && \
  272. !strncasecmp(ZSTR_VAL(key), mname, ZSTR_LEN(key)))
  273. #define PHP_V8JS_CALLBACK(isolate, mptr, tmpl) \
  274. (v8::FunctionTemplate::New((isolate), v8js_php_callback, v8::External::New((isolate), mptr), v8::Signature::New((isolate), tmpl))->GetFunction(isolate->GetEnteredOrMicrotaskContext()).ToLocalChecked())
  275. static void v8js_named_property_enumerator(const v8::PropertyCallbackInfo<v8::Array> &info) /* {{{ */
  276. {
  277. // note: 'special' properties like 'constructor' are not enumerated.
  278. v8::Isolate *isolate = info.GetIsolate();
  279. v8::Local<v8::Context> v8_context = isolate->GetEnteredOrMicrotaskContext();
  280. v8::Local<v8::Object> self = info.Holder();
  281. v8::Local<v8::Array> result = v8::Array::New(isolate, 0);
  282. uint32_t result_len = 0;
  283. zend_class_entry *ce;
  284. void *ptr;
  285. HashTable *proptable;
  286. zend_string *key;
  287. zend_ulong index;
  288. zend_object *object = reinterpret_cast<zend_object *>(self->GetAlignedPointerFromInternalField(1));
  289. ce = object->ce;
  290. /* enumerate all methods */
  291. ZEND_HASH_FOREACH_STR_KEY_PTR(&ce->function_table, key, ptr) {
  292. zend_function *method_ptr = reinterpret_cast<zend_function *>(ptr);
  293. if ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) == 0) {
  294. /* Allow only public methods */
  295. continue;
  296. }
  297. if ((method_ptr->common.fn_flags & (ZEND_ACC_CTOR|ZEND_ACC_DTOR)) != 0) {
  298. /* no __construct, __destruct(), or __clone() functions */
  299. continue;
  300. }
  301. // hide (do not enumerate) other PHP magic functions
  302. if (IS_MAGIC_FUNC(ZEND_CALLSTATIC_FUNC_NAME) ||
  303. IS_MAGIC_FUNC(ZEND_SLEEP_FUNC_NAME) ||
  304. IS_MAGIC_FUNC(ZEND_WAKEUP_FUNC_NAME) ||
  305. IS_MAGIC_FUNC(ZEND_SET_STATE_FUNC_NAME) ||
  306. IS_MAGIC_FUNC(ZEND_GET_FUNC_NAME) ||
  307. IS_MAGIC_FUNC(ZEND_SET_FUNC_NAME) ||
  308. IS_MAGIC_FUNC(ZEND_UNSET_FUNC_NAME) ||
  309. IS_MAGIC_FUNC(ZEND_CALL_FUNC_NAME) ||
  310. IS_MAGIC_FUNC(ZEND_INVOKE_FUNC_NAME) ||
  311. IS_MAGIC_FUNC(ZEND_ISSET_FUNC_NAME)) {
  312. continue;
  313. }
  314. v8::Local<v8::String> method_name;
  315. // rename PHP special method names to JS equivalents.
  316. if (IS_MAGIC_FUNC(ZEND_TOSTRING_FUNC_NAME)) {
  317. method_name = V8JS_SYM("toString");
  318. }
  319. else {
  320. if (ZSTR_LEN(method_ptr->common.function_name) > std::numeric_limits<int>::max()) {
  321. zend_throw_exception(php_ce_v8js_exception,
  322. "Method name length exceeds maximum supported length", 0);
  323. return;
  324. }
  325. method_name = V8JS_STRL(ZSTR_VAL(method_ptr->common.function_name), static_cast<int>(ZSTR_LEN(method_ptr->common.function_name)));
  326. }
  327. result->Set(v8_context, result_len++, method_name);
  328. } ZEND_HASH_FOREACH_END();
  329. /* enumerate all properties */
  330. /* Z_OBJPROP uses the get_properties handler */
  331. zval tmp_zv;
  332. ZVAL_OBJ(&tmp_zv, object);
  333. proptable = Z_OBJPROP(tmp_zv);
  334. ZEND_HASH_FOREACH_KEY(proptable, index, key) {
  335. if(key) {
  336. /* skip protected and private members */
  337. if(ZSTR_VAL(key)[0] == '\0') {
  338. continue;
  339. }
  340. if (ZSTR_LEN(key) + 1 > std::numeric_limits<int>::max()) {
  341. zend_throw_exception(php_ce_v8js_exception,
  342. "Object key length exceeds maximum supported length", 0);
  343. continue;
  344. }
  345. // prefix enumerated property names with '$' so they can be
  346. // dereferenced unambiguously (ie, don't conflict with method
  347. // names)
  348. char *prefixed = static_cast<char *>(emalloc(ZSTR_LEN(key) + 2));
  349. prefixed[0] = '$';
  350. strncpy(prefixed + 1, ZSTR_VAL(key), ZSTR_LEN(key) + 1);
  351. result->Set(v8_context, result_len++, V8JS_STRL(prefixed, static_cast<int>(ZSTR_LEN(key) + 1)));
  352. efree(prefixed);
  353. } else {
  354. // even numeric indices are enumerated as strings in JavaScript
  355. result->Set(v8_context, result_len++, V8JS_FLOAT((double) index)->ToString(v8_context).ToLocalChecked());
  356. }
  357. } ZEND_HASH_FOREACH_END();
  358. /* done */
  359. info.GetReturnValue().Set(result);
  360. }
  361. /* }}} */
  362. static void v8js_invoke_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  363. {
  364. v8::Isolate *isolate = info.GetIsolate();
  365. v8::Local<v8::Context> v8_context = isolate->GetEnteredOrMicrotaskContext();
  366. v8::Local<v8::Object> self = info.Holder();
  367. v8::Local<v8::Function> cb = v8::Local<v8::Function>::Cast(info.Data());
  368. int argc = info.Length(), i;
  369. v8::Local<v8::Value> *argv = static_cast<v8::Local<v8::Value> *>(alloca(sizeof(v8::Local<v8::Value>) * argc));
  370. v8::Local<v8::Value> result;
  371. for (i=0; i<argc; i++) {
  372. new(&argv[i]) v8::Local<v8::Value>;
  373. argv[i] = info[i];
  374. }
  375. if (info.IsConstructCall()) {
  376. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  377. v8::Local<v8::String> str = self->GetConstructorName()->ToString(v8_context).ToLocalChecked();
  378. v8::String::Utf8Value str_value(isolate, str);
  379. zend_string *constructor_name = zend_string_init(ToCString(str_value), str_value.length(), 0);
  380. zend_class_entry *ce = zend_lookup_class(constructor_name);
  381. zend_string_release(constructor_name);
  382. v8::Local<v8::FunctionTemplate> new_tpl;
  383. new_tpl = v8::Local<v8::FunctionTemplate>::New
  384. (isolate, ctx->template_cache.at(ce->name));
  385. v8::Local<v8::Function> fn;
  386. if (!new_tpl->GetFunction(v8_context).ToLocal(&fn) || !fn->NewInstance(v8_context, argc, argv).ToLocal(&result))
  387. {
  388. result = V8JS_UNDEFINED;
  389. }
  390. } else {
  391. cb->Call(v8_context, self, argc, argv).ToLocal(&result);
  392. }
  393. info.GetReturnValue().Set(result);
  394. }
  395. /* }}} */
  396. // this is a magic '__call' implementation for PHP classes which don't actually
  397. // have a '__call' magic function. This way we can always force a method
  398. // call (as opposed to a property get) from JavaScript using __call.
  399. static void v8js_fake_call_impl(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  400. {
  401. v8::Isolate *isolate = info.GetIsolate();
  402. v8::Local<v8::Context> v8_context = isolate->GetEnteredOrMicrotaskContext();
  403. v8::Local<v8::Object> self = info.Holder();
  404. v8::Local<v8::Value> return_value = V8JS_NULL;
  405. char *error;
  406. size_t error_len;
  407. zend_class_entry *ce;
  408. zend_object *object = reinterpret_cast<zend_object *>(self->GetAlignedPointerFromInternalField(1));
  409. ce = object->ce;
  410. // first arg is method name, second arg is array of args.
  411. if (info.Length() < 2) {
  412. error_len = spprintf(&error, 0,
  413. "%s::__call expects 2 parameters, %d given",
  414. ZSTR_VAL(ce->name), (int) info.Length());
  415. if (error_len > std::numeric_limits<int>::max()) {
  416. zend_throw_exception(php_ce_v8js_exception,
  417. "Generated error message length exceeds maximum supported length", 0);
  418. }
  419. else {
  420. return_value = V8JS_THROW(isolate, TypeError, error, static_cast<int>(error_len));
  421. }
  422. efree(error);
  423. info.GetReturnValue().Set(return_value);
  424. return;
  425. }
  426. if (!info[1]->IsArray()) {
  427. error_len = spprintf(&error, 0,
  428. "%s::__call expects 2nd parameter to be an array",
  429. ce->name);
  430. if (error_len > std::numeric_limits<int>::max()) {
  431. zend_throw_exception(php_ce_v8js_exception,
  432. "Generated error message length exceeds maximum supported length", 0);
  433. }
  434. else {
  435. return_value = V8JS_THROW(isolate, TypeError, error, static_cast<int>(error_len));
  436. }
  437. efree(error);
  438. info.GetReturnValue().Set(return_value);
  439. return;
  440. }
  441. v8::Local<v8::Array> args = v8::Local<v8::Array>::Cast(info[1]);
  442. if (args->Length() > 1000000) {
  443. // prevent overflow, since args->Length() is a uint32_t and args
  444. // in the Function->Call method below is a (signed) int.
  445. error_len = spprintf(&error, 0,
  446. "%s::__call expects fewer than a million arguments",
  447. ZSTR_VAL(ce->name));
  448. if (error_len > std::numeric_limits<int>::max()) {
  449. zend_throw_exception(php_ce_v8js_exception,
  450. "Generated error message length exceeds maximum supported length", 0);
  451. }
  452. else {
  453. return_value = V8JS_THROW(isolate, TypeError, error, static_cast<int>(error_len));
  454. }
  455. efree(error);
  456. info.GetReturnValue().Set(return_value);
  457. return;
  458. }
  459. v8::MaybeLocal<v8::String> str = info[0]->ToString(v8_context);
  460. if (str.IsEmpty())
  461. {
  462. error_len = spprintf(&error, 0,
  463. "%s::__call expects 1st parameter to be valid function name, toString() invocation failed.",
  464. ZSTR_VAL(ce->name));
  465. if (error_len > std::numeric_limits<int>::max()) {
  466. zend_throw_exception(php_ce_v8js_exception,
  467. "Generated error message length exceeds maximum supported length", 0);
  468. }
  469. else {
  470. return_value = V8JS_THROW(isolate, TypeError, error, static_cast<int>(error_len));
  471. }
  472. efree(error);
  473. info.GetReturnValue().Set(return_value);
  474. return;
  475. }
  476. v8::String::Utf8Value str_value(isolate, str.ToLocalChecked());
  477. const char *method_c_name = ToCString(str_value);
  478. zend_string *method_name = zend_string_init(method_c_name, str_value.length(), 0);
  479. // okay, look up the method name and manually invoke it.
  480. const zend_object_handlers *h = object->handlers;
  481. zend_function *method_ptr = h->get_method(&object, method_name, NULL);
  482. zend_string_release(method_name);
  483. if (method_ptr == NULL ||
  484. (method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) == 0 ||
  485. (method_ptr->common.fn_flags & (ZEND_ACC_CTOR|ZEND_ACC_DTOR)) != 0) {
  486. error_len = spprintf(&error, 0,
  487. "%s::__call to %s method %s", ZSTR_VAL(ce->name),
  488. (method_ptr == NULL) ? "undefined" : "non-public", method_name);
  489. if (error_len > std::numeric_limits<int>::max()) {
  490. zend_throw_exception(php_ce_v8js_exception,
  491. "Generated error message length exceeds maximum supported length", 0);
  492. }
  493. else {
  494. return_value = V8JS_THROW(isolate, TypeError, error, static_cast<int>(error_len));
  495. }
  496. efree(error);
  497. info.GetReturnValue().Set(return_value);
  498. return;
  499. }
  500. v8::Local<v8::FunctionTemplate> tmpl =
  501. v8::Local<v8::FunctionTemplate>::New
  502. (isolate, *reinterpret_cast<v8js_function_tmpl_t *>(self->GetAlignedPointerFromInternalField(0)));
  503. // use v8js_php_callback to actually execute the method
  504. v8::Local<v8::Function> cb = PHP_V8JS_CALLBACK(isolate, method_ptr, tmpl);
  505. uint32_t i, argc = args->Length();
  506. v8::Local<v8::Value> *argv = static_cast<v8::Local<v8::Value> *>(alloca(sizeof(v8::Local<v8::Value>) * argc));
  507. for (i=0; i<argc; i++) {
  508. new(&argv[i]) v8::Local<v8::Value>;
  509. args->Get(v8_context, i).ToLocal(&argv[i]);
  510. }
  511. cb->Call(v8_context, info.This(), (int) argc, argv).ToLocal(&return_value);
  512. info.GetReturnValue().Set(return_value);
  513. }
  514. /* }}} */
  515. /* This method handles named property and method get/set/query/delete. */
  516. template<typename T>
  517. v8::Local<v8::Value> v8js_named_property_callback(v8::Local<v8::Name> property_name, const v8::PropertyCallbackInfo<T> &info, property_op_t callback_type, v8::Local<v8::Value> set_value) /* {{{ */
  518. {
  519. v8::Local<v8::String> property = v8::Local<v8::String>::Cast(property_name);
  520. v8::Isolate *isolate = info.GetIsolate();
  521. v8::Local<v8::Context> v8_context = isolate->GetEnteredOrMicrotaskContext();
  522. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  523. v8::String::Utf8Value cstr(isolate, property);
  524. const char *name = ToCString(cstr);
  525. uint32_t name_len = cstr.length();
  526. char *lower = estrndup(name, name_len);
  527. zend_string *method_name;
  528. v8::Local<v8::Object> self = info.Holder();
  529. v8::Local<v8::Value> ret_value;
  530. v8::Local<v8::Function> cb;
  531. zend_class_entry *scope, *ce;
  532. zend_function *method_ptr = NULL;
  533. zval php_value;
  534. zend_object *object = reinterpret_cast<zend_object *>(self->GetAlignedPointerFromInternalField(1));
  535. zval zobject;
  536. ZVAL_OBJ(&zobject, object);
  537. v8js_function_tmpl_t *tmpl_ptr = reinterpret_cast<v8js_function_tmpl_t *>(self->GetAlignedPointerFromInternalField(0));
  538. v8::Local<v8::FunctionTemplate> tmpl = v8::Local<v8::FunctionTemplate>::New(isolate, *tmpl_ptr);
  539. ce = scope = object->ce;
  540. /* First, check the (case-insensitive) method table */
  541. php_strtolower(lower, name_len);
  542. method_name = zend_string_init(lower, name_len, 0);
  543. // toString() -> __tostring()
  544. if (name_len == 8 && strcmp(name, "toString") == 0) {
  545. zend_string_release(method_name);
  546. method_name = zend_string_init(ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME) - 1, 0);
  547. }
  548. bool is_constructor = (name_len == 11 && strcmp(name, "constructor") == 0);
  549. bool is_magic_call = (ZSTR_LEN(method_name) == 6 && strcmp(ZSTR_VAL(method_name), "__call") == 0);
  550. if (is_constructor ||
  551. (name[0] != '$' /* leading '$' means property, not method */ &&
  552. (method_ptr = reinterpret_cast<zend_function *>
  553. (zend_hash_find_ptr(&ce->function_table, method_name))) &&
  554. ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) != 0) && /* Allow only public methods */
  555. ((method_ptr->common.fn_flags & (ZEND_ACC_CTOR|ZEND_ACC_DTOR)) == 0) /* no __construct, __destruct(), or __clone() functions */
  556. ) || (method_ptr=NULL, is_magic_call)
  557. ) {
  558. if (callback_type == V8JS_PROP_GETTER) {
  559. if (is_constructor) {
  560. // Don't set a return value here, i.e. indicate that we don't
  561. // have a special value. V8 "knows" the constructor anyways
  562. // (from the template) and will use that.
  563. } else {
  564. if (is_magic_call && method_ptr==NULL) {
  565. // Fake __call implementation
  566. // (only use this if method_ptr==NULL, which means
  567. // there is no actual PHP __call() implementation)
  568. v8::Local<v8::FunctionTemplate> ft;
  569. try {
  570. ft = v8::Local<v8::FunctionTemplate>::New
  571. (isolate, ctx->call_impls.at(tmpl_ptr));
  572. }
  573. catch (const std::out_of_range &) {
  574. ft = v8::FunctionTemplate::New(isolate,
  575. v8js_fake_call_impl, V8JS_NULL,
  576. v8::Signature::New(isolate, tmpl));
  577. v8js_function_tmpl_t *persistent_ft = &ctx->call_impls[tmpl_ptr];
  578. persistent_ft->Reset(isolate, ft);
  579. }
  580. v8::Local<v8::Function> fn;
  581. if (ft->GetFunction(v8_context).ToLocal(&fn))
  582. {
  583. fn->SetName(property);
  584. ret_value = fn;
  585. }
  586. } else {
  587. v8::Local<v8::FunctionTemplate> ft;
  588. try {
  589. ft = v8::Local<v8::FunctionTemplate>::New
  590. (isolate, ctx->method_tmpls.at(std::make_pair(ce, method_ptr)));
  591. }
  592. catch (const std::out_of_range &) {
  593. ft = v8::FunctionTemplate::New(isolate, v8js_php_callback,
  594. v8::External::New((isolate), method_ptr),
  595. v8::Signature::New((isolate), tmpl));
  596. v8js_function_tmpl_t *persistent_ft = &ctx->method_tmpls[std::make_pair(ce, method_ptr)];
  597. persistent_ft->Reset(isolate, ft);
  598. }
  599. ft->GetFunction(v8_context).ToLocal(&ret_value);
  600. }
  601. }
  602. } else if (callback_type == V8JS_PROP_QUERY) {
  603. ret_value = V8JS_UINT(v8::ReadOnly|v8::DontDelete);
  604. } else if (callback_type == V8JS_PROP_SETTER) {
  605. ret_value = set_value; // lie. this field is read-only.
  606. } else if (callback_type == V8JS_PROP_DELETER) {
  607. ret_value = V8JS_BOOL(false);
  608. } else {
  609. /* shouldn't reach here! but bail safely */
  610. ret_value = v8::Local<v8::Value>();
  611. }
  612. } else {
  613. if (name[0]=='$') {
  614. // this is a property (not a method)
  615. name++; name_len--;
  616. }
  617. zval zname;
  618. ZVAL_STRINGL(&zname, name, name_len);
  619. if (callback_type == V8JS_PROP_GETTER) {
  620. /* Nope, not a method -- must be a (case-sensitive) property */
  621. zend_property_info *property_info = zend_get_property_info(ce, Z_STR(zname), 1);
  622. if(!property_info ||
  623. (property_info != ZEND_WRONG_PROPERTY_INFO &&
  624. property_info->flags & ZEND_ACC_PUBLIC)) {
  625. zval *property_val = zend_read_property(NULL, &zobject, name, name_len, true, &php_value);
  626. // special case uninitialized_zval_ptr and return an empty value
  627. // (indicating that we don't intercept this property) if the
  628. // property doesn't exist.
  629. if (property_val == &EG(uninitialized_zval)) {
  630. ret_value = v8::Local<v8::Value>();
  631. } else {
  632. // wrap it
  633. ret_value = zval_to_v8js(property_val, isolate);
  634. /* We don't own the reference to php_value... unless the
  635. * returned refcount was 0, in which case the below code
  636. * will free it. */
  637. zval_add_ref(property_val);
  638. zval_ptr_dtor(property_val);
  639. }
  640. }
  641. else if (ce->__get
  642. /* Allow only public methods */
  643. && ((ce->__get->common.fn_flags & ZEND_ACC_PUBLIC) != 0)) {
  644. /* Okay, let's call __get. */
  645. zend_call_method_with_1_params(&zobject, ce, &ce->__get, ZEND_GET_FUNC_NAME, &php_value, &zname);
  646. ret_value = zval_to_v8js(&php_value, isolate);
  647. zval_ptr_dtor(&php_value);
  648. }
  649. } else if (callback_type == V8JS_PROP_SETTER) {
  650. if (v8js_to_zval(set_value, &php_value, ctx->flags, isolate) != SUCCESS) {
  651. ret_value = v8::Local<v8::Value>();
  652. }
  653. else {
  654. zend_property_info *property_info = zend_get_property_info(ce, Z_STR(zname), 1);
  655. if(!property_info ||
  656. (property_info != ZEND_WRONG_PROPERTY_INFO &&
  657. property_info->flags & ZEND_ACC_PUBLIC)) {
  658. zend_update_property(scope, &zobject, name, name_len, &php_value);
  659. ret_value = set_value;
  660. }
  661. else if (ce->__set
  662. /* Allow only public methods */
  663. && ((ce->__set->common.fn_flags & ZEND_ACC_PUBLIC) != 0)) {
  664. /* Okay, let's call __set. */
  665. zval php_ret_value;
  666. zend_call_method_with_2_params(&zobject, ce, &ce->__set, ZEND_SET_FUNC_NAME, &php_ret_value, &zname, &php_value);
  667. ret_value = zval_to_v8js(&php_ret_value, isolate);
  668. zval_ptr_dtor(&php_ret_value);
  669. }
  670. }
  671. // if PHP wanted to hold on to this value, update_property would
  672. // have bumped the refcount
  673. zval_ptr_dtor(&php_value);
  674. } else if (callback_type == V8JS_PROP_QUERY ||
  675. callback_type == V8JS_PROP_DELETER) {
  676. const zend_object_handlers *h = object->handlers;
  677. if (callback_type == V8JS_PROP_QUERY) {
  678. if (h->has_property(&zobject, &zname, 0, NULL)) {
  679. ret_value = V8JS_UINT(v8::None);
  680. } else {
  681. ret_value = v8::Local<v8::Value>(); // empty handle
  682. }
  683. } else {
  684. zend_property_info *property_info = zend_get_property_info(ce, Z_STR(zname), 1);
  685. if(!property_info ||
  686. (property_info != ZEND_WRONG_PROPERTY_INFO &&
  687. property_info->flags & ZEND_ACC_PUBLIC)) {
  688. h->unset_property(&zobject, &zname, NULL);
  689. ret_value = V8JS_TRUE();
  690. }
  691. else {
  692. ret_value = v8::Local<v8::Value>(); // empty handle
  693. }
  694. }
  695. } else {
  696. /* shouldn't reach here! but bail safely */
  697. ret_value = v8::Local<v8::Value>();
  698. }
  699. zval_ptr_dtor(&zname);
  700. }
  701. zend_string_release(method_name);
  702. efree(lower);
  703. return ret_value;
  704. }
  705. /* }}} */
  706. static void v8js_named_property_getter(v8::Local<v8::Name> property, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */
  707. {
  708. info.GetReturnValue().Set(v8js_named_property_callback(property, info, V8JS_PROP_GETTER));
  709. }
  710. /* }}} */
  711. static void v8js_named_property_setter(v8::Local<v8::Name> property, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */
  712. {
  713. info.GetReturnValue().Set(v8js_named_property_callback(property, info, V8JS_PROP_SETTER, value));
  714. }
  715. /* }}} */
  716. static void v8js_named_property_query(v8::Local<v8::Name> property, const v8::PropertyCallbackInfo<v8::Integer> &info) /* {{{ */
  717. {
  718. v8::Local<v8::Value> r = v8js_named_property_callback(property, info, V8JS_PROP_QUERY);
  719. if (r.IsEmpty()) {
  720. return;
  721. }
  722. v8::Isolate *isolate = info.GetIsolate();
  723. v8::MaybeLocal<v8::Integer> value = r->ToInteger(isolate->GetEnteredOrMicrotaskContext());
  724. if (!value.IsEmpty()) {
  725. info.GetReturnValue().Set(value.ToLocalChecked());
  726. }
  727. }
  728. /* }}} */
  729. static void v8js_named_property_deleter(v8::Local<v8::Name> property, const v8::PropertyCallbackInfo<v8::Boolean> &info) /* {{{ */
  730. {
  731. v8::Local<v8::Value> r = v8js_named_property_callback(property, info, V8JS_PROP_DELETER);
  732. if (r.IsEmpty()) {
  733. return;
  734. }
  735. v8::Isolate *isolate = info.GetIsolate();
  736. v8::Local<v8::Boolean> value = r->ToBoolean(isolate);
  737. if (!value.IsEmpty()) {
  738. info.GetReturnValue().Set(value);
  739. }
  740. }
  741. /* }}} */
  742. static v8::MaybeLocal<v8::Object> v8js_wrap_object(v8::Isolate *isolate, zend_class_entry *ce, zval *value) /* {{{ */
  743. {
  744. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  745. v8::Local<v8::Context> v8_context = v8::Local<v8::Context>::New(isolate, ctx->context);
  746. v8::Local<v8::FunctionTemplate> new_tpl;
  747. v8js_function_tmpl_t *persist_tpl_;
  748. try {
  749. new_tpl = v8::Local<v8::FunctionTemplate>::New
  750. (isolate, ctx->template_cache.at(ce->name));
  751. }
  752. catch (const std::out_of_range &) {
  753. /* No cached v8::FunctionTemplate available as of yet, create one. */
  754. new_tpl = v8::FunctionTemplate::New(isolate, 0);
  755. if (ZSTR_LEN(ce->name) > std::numeric_limits<int>::max()) {
  756. zend_throw_exception(php_ce_v8js_exception,
  757. "Class name length exceeds maximum supported length", 0);
  758. return v8::Local<v8::Object>();
  759. }
  760. new_tpl->SetClassName(V8JS_STRL(ZSTR_VAL(ce->name), static_cast<int>(ZSTR_LEN(ce->name))));
  761. new_tpl->InstanceTemplate()->SetInternalFieldCount(2);
  762. if (ce == zend_ce_closure) {
  763. /* Got a closure, mustn't cache ... */
  764. persist_tpl_ = new v8js_function_tmpl_t(isolate, new_tpl);
  765. /* We'll free persist_tpl_ via v8js_weak_closure_callback, below */
  766. new_tpl->InstanceTemplate()->SetCallAsFunctionHandler(v8js_php_callback);
  767. } else {
  768. /* Add new v8::FunctionTemplate to tpl_map, as long as it is not a closure. */
  769. persist_tpl_ = &ctx->template_cache[ce->name];
  770. persist_tpl_->Reset(isolate, new_tpl);
  771. /* We'll free persist_tpl_ when template_cache is destroyed */
  772. v8::Local<v8::ObjectTemplate> inst_tpl = new_tpl->InstanceTemplate();
  773. v8::GenericNamedPropertyGetterCallback getter = v8js_named_property_getter;
  774. v8::GenericNamedPropertyEnumeratorCallback enumerator = v8js_named_property_enumerator;
  775. /* Check for ArrayAccess object */
  776. if (V8JSG(use_array_access) && ce) {
  777. bool has_array_access = false;
  778. bool has_countable = false;
  779. for (unsigned int i = 0; i < ce->num_interfaces; i ++) {
  780. if (strcmp (ZSTR_VAL(ce->interfaces[i]->name), "ArrayAccess") == 0) {
  781. has_array_access = true;
  782. }
  783. else if (strcmp (ZSTR_VAL(ce->interfaces[i]->name), "Countable") == 0) {
  784. has_countable = true;
  785. }
  786. }
  787. if(has_array_access && has_countable) {
  788. inst_tpl->SetIndexedPropertyHandler(v8js_array_access_getter,
  789. v8js_array_access_setter,
  790. v8js_array_access_query,
  791. v8js_array_access_deleter,
  792. v8js_array_access_enumerator);
  793. /* Switch to special ArrayAccess getter, which falls back to
  794. * v8js_named_property_getter, but possibly bridges the
  795. * call to Array.prototype functions. */
  796. getter = v8js_array_access_named_getter;
  797. /* Overwrite enumerator, since for(... in ...) loop should
  798. * not see the methods but iterate over the elements. */
  799. enumerator = 0;
  800. }
  801. }
  802. // Finish setup of new_tpl
  803. inst_tpl->SetHandler(v8::NamedPropertyHandlerConfiguration
  804. (getter, /* getter */
  805. v8js_named_property_setter, /* setter */
  806. v8js_named_property_query, /* query */
  807. v8js_named_property_deleter, /* deleter */
  808. enumerator, /* enumerator */
  809. V8JS_NULL /* data */
  810. ));
  811. // add __invoke() handler
  812. zend_string *invoke_str = zend_string_init
  813. (ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME) - 1, 0);
  814. zend_function *invoke_method_ptr = reinterpret_cast<zend_function *>
  815. (zend_hash_find_ptr(&ce->function_table, invoke_str));
  816. if (invoke_method_ptr &&
  817. invoke_method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) {
  818. new_tpl->InstanceTemplate()->SetCallAsFunctionHandler(v8js_invoke_callback, PHP_V8JS_CALLBACK(isolate, invoke_method_ptr, new_tpl));
  819. }
  820. zend_string_release(invoke_str);
  821. }
  822. v8::Local<v8::Array> call_handler_data = v8::Array::New(isolate, 2);
  823. call_handler_data->Set(v8_context, 0, v8::External::New(isolate, persist_tpl_));
  824. call_handler_data->Set(v8_context, 1, v8::External::New(isolate, ce));
  825. new_tpl->SetCallHandler(v8js_construct_callback, call_handler_data);
  826. }
  827. // Create v8 wrapper object
  828. v8::Local<v8::Value> external = v8::External::New(isolate, Z_OBJ_P(value));
  829. v8::Local<v8::Function> constr;
  830. if (!new_tpl->GetFunction(v8_context).ToLocal(&constr)) {
  831. return v8::MaybeLocal<v8::Object>();
  832. }
  833. v8::MaybeLocal<v8::Object> newobj = constr->NewInstance(v8_context, 1, &external);
  834. if (ce == zend_ce_closure && !newobj.IsEmpty()) {
  835. // free uncached function template when object is freed
  836. ctx->weak_closures[persist_tpl_].Reset(isolate, newobj.ToLocalChecked());
  837. ctx->weak_closures[persist_tpl_].SetWeak(persist_tpl_, v8js_weak_closure_callback, v8::WeakCallbackType::kParameter);
  838. }
  839. return newobj;
  840. }
  841. /* }}} */
  842. static v8::Local<v8::Object> v8js_wrap_array_to_object(v8::Isolate *isolate, zval *value) /* {{{ */
  843. {
  844. int i;
  845. zend_string *key;
  846. zend_ulong index;
  847. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  848. v8::Local<v8::Context> v8_context = v8::Local<v8::Context>::New(isolate, ctx->context);
  849. v8::Local<v8::FunctionTemplate> new_tpl;
  850. if(ctx->array_tmpl.IsEmpty()) {
  851. new_tpl = v8::FunctionTemplate::New(isolate, 0);
  852. /* Call it Array, but it is not a native array, especially it doesn't have
  853. * have the typical Array.prototype functions. */
  854. new_tpl->SetClassName(V8JS_SYM("Array"));
  855. /* Store for later re-use */
  856. ctx->array_tmpl.Reset(isolate, new_tpl);
  857. }
  858. else {
  859. new_tpl = v8::Local<v8::FunctionTemplate>::New(isolate, ctx->array_tmpl);
  860. }
  861. v8::Local<v8::Object> newobj = new_tpl->InstanceTemplate()->NewInstance(v8_context).ToLocalChecked();
  862. HashTable *myht = HASH_OF(value);
  863. i = myht ? zend_hash_num_elements(myht) : 0;
  864. if (i > 0)
  865. {
  866. zval *data;
  867. #if PHP_VERSION_ID >= 70300
  868. if (myht && !(GC_FLAGS(myht) & GC_IMMUTABLE)) {
  869. #else
  870. if (myht) {
  871. #endif
  872. GC_PROTECT_RECURSION(myht);
  873. }
  874. ZEND_HASH_FOREACH_KEY_VAL(myht, index, key, data) {
  875. if (key) {
  876. if (ZSTR_VAL(key)[0] == '\0' && Z_TYPE_P(value) == IS_OBJECT) {
  877. /* Skip protected and private members. */
  878. continue;
  879. }
  880. if (ZSTR_LEN(key) > std::numeric_limits<int>::max()) {
  881. zend_throw_exception(php_ce_v8js_exception,
  882. "Object key length exceeds maximum supported length", 0);
  883. continue;
  884. }
  885. newobj->Set(v8_context, V8JS_STRL(ZSTR_VAL(key), static_cast<int>(ZSTR_LEN(key))),
  886. zval_to_v8js(data, isolate));
  887. } else {
  888. if (index > std::numeric_limits<uint32_t>::max()) {
  889. zend_throw_exception(php_ce_v8js_exception,
  890. "Array index exceeds maximum supported bound", 0);
  891. continue;
  892. }
  893. newobj->Set(v8_context, static_cast<uint32_t>(index), zval_to_v8js(data, isolate));
  894. }
  895. } ZEND_HASH_FOREACH_END();
  896. #if PHP_VERSION_ID >= 70300
  897. if (myht && !(GC_FLAGS(myht) & GC_IMMUTABLE)) {
  898. #else
  899. if (myht) {
  900. #endif
  901. GC_UNPROTECT_RECURSION(myht);
  902. }
  903. }
  904. return newobj;
  905. }
  906. /* }}} */
  907. v8::Local<v8::Value> v8js_hash_to_jsobj(zval *value, v8::Isolate *isolate) /* {{{ */
  908. {
  909. HashTable *myht;
  910. zend_class_entry *ce = NULL;
  911. if (Z_TYPE_P(value) == IS_ARRAY) {
  912. myht = HASH_OF(value);
  913. } else {
  914. myht = Z_OBJPROP_P(value);
  915. ce = Z_OBJCE_P(value);
  916. }
  917. /* Prevent recursion */
  918. #if PHP_VERSION_ID >= 70300
  919. if (myht && GC_IS_RECURSIVE(myht)) {
  920. #else
  921. if (myht && ZEND_HASH_GET_APPLY_COUNT(myht) > 1) {
  922. #endif
  923. return V8JS_NULL;
  924. }
  925. /* Special case, passing back object originating from JS to JS */
  926. if (ce == php_ce_v8function || ce == php_ce_v8object || ce == php_ce_v8generator) {
  927. v8js_v8object *c = Z_V8JS_V8OBJECT_OBJ_P(value);
  928. if(isolate != c->ctx->isolate) {
  929. php_error_docref(NULL, E_WARNING, "V8Function object passed to wrong V8Js instance");
  930. return V8JS_NULL;
  931. }
  932. return v8::Local<v8::Value>::New(isolate, c->v8obj);
  933. }
  934. /* If it's a PHP object, wrap it */
  935. if (ce) {
  936. v8::MaybeLocal<v8::Object> wrapped_object = v8js_wrap_object(isolate, ce, value);
  937. if (wrapped_object.IsEmpty()) {
  938. return V8JS_UNDEFINED;
  939. }
  940. if (ce == zend_ce_generator) {
  941. /* Wrap PHP Generator object in a wrapper function that provides
  942. * ES6 style behaviour. */
  943. return v8js_wrap_generator(isolate, wrapped_object.ToLocalChecked());
  944. }
  945. return wrapped_object.ToLocalChecked();
  946. }
  947. /* Associative PHP arrays cannot be wrapped to JS arrays, convert them to
  948. * JS objects and attach all their array keys as properties. */
  949. return v8js_wrap_array_to_object(isolate, value);
  950. }
  951. /* }}} */
  952. /*
  953. * Local variables:
  954. * tab-width: 4
  955. * c-basic-offset: 4
  956. * indent-tabs-mode: t
  957. * End:
  958. * vim600: noet sw=4 ts=4 fdm=marker
  959. * vim<600: noet sw=4 ts=4
  960. */