v8js_object_export.cc 38 KB

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