v8js_object_export.cc 38 KB

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