v8js_object_export.cc 39 KB

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