v8js_object_export.cc 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  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. IS_MAGIC_FUNC("__serialize") ||
  332. IS_MAGIC_FUNC("__unserialize")) {
  333. continue;
  334. }
  335. v8::Local<v8::String> method_name;
  336. // rename PHP special method names to JS equivalents.
  337. if (IS_MAGIC_FUNC(ZEND_TOSTRING_FUNC_NAME)) {
  338. method_name = V8JS_SYM("toString");
  339. }
  340. else {
  341. if (ZSTR_LEN(method_ptr->common.function_name) > std::numeric_limits<int>::max()) {
  342. zend_throw_exception(php_ce_v8js_exception,
  343. "Method name length exceeds maximum supported length", 0);
  344. return;
  345. }
  346. method_name = V8JS_STRL(ZSTR_VAL(method_ptr->common.function_name), static_cast<int>(ZSTR_LEN(method_ptr->common.function_name)));
  347. }
  348. result->Set(v8_context, result_len++, method_name);
  349. } ZEND_HASH_FOREACH_END();
  350. /* enumerate all properties */
  351. /* Z_OBJPROP uses the get_properties handler */
  352. zval tmp_zv;
  353. ZVAL_OBJ(&tmp_zv, object);
  354. proptable = Z_OBJPROP(tmp_zv);
  355. ZEND_HASH_FOREACH_KEY(proptable, index, key) {
  356. if(key) {
  357. /* skip protected and private members */
  358. if(ZSTR_VAL(key)[0] == '\0') {
  359. continue;
  360. }
  361. if (ZSTR_LEN(key) + 1 > std::numeric_limits<int>::max()) {
  362. zend_throw_exception(php_ce_v8js_exception,
  363. "Object key length exceeds maximum supported length", 0);
  364. continue;
  365. }
  366. // prefix enumerated property names with '$' so they can be
  367. // dereferenced unambiguously (ie, don't conflict with method
  368. // names)
  369. char *prefixed = static_cast<char *>(emalloc(ZSTR_LEN(key) + 2));
  370. prefixed[0] = '$';
  371. strncpy(prefixed + 1, ZSTR_VAL(key), ZSTR_LEN(key) + 1);
  372. result->Set(v8_context, result_len++, V8JS_STRL(prefixed, static_cast<int>(ZSTR_LEN(key) + 1)));
  373. efree(prefixed);
  374. } else {
  375. // even numeric indices are enumerated as strings in JavaScript
  376. result->Set(v8_context, result_len++, V8JS_FLOAT((double) index)->ToString(v8_context).ToLocalChecked());
  377. }
  378. } ZEND_HASH_FOREACH_END();
  379. /* done */
  380. info.GetReturnValue().Set(result);
  381. }
  382. /* }}} */
  383. static void v8js_invoke_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  384. {
  385. v8::Isolate *isolate = info.GetIsolate();
  386. v8::Local<v8::Context> v8_context = isolate->GetEnteredOrMicrotaskContext();
  387. v8::Local<v8::Object> self = info.Holder();
  388. v8::Local<v8::Function> cb = v8::Local<v8::Function>::Cast(info.Data());
  389. int argc = info.Length(), i;
  390. v8::Local<v8::Value> *argv = static_cast<v8::Local<v8::Value> *>(alloca(sizeof(v8::Local<v8::Value>) * argc));
  391. v8::Local<v8::Value> result;
  392. for (i=0; i<argc; i++) {
  393. new(&argv[i]) v8::Local<v8::Value>;
  394. argv[i] = info[i];
  395. }
  396. if (info.IsConstructCall()) {
  397. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  398. v8::Local<v8::String> str = self->GetConstructorName()->ToString(v8_context).ToLocalChecked();
  399. v8::String::Utf8Value str_value(isolate, str);
  400. zend_string *constructor_name = zend_string_init(ToCString(str_value), str_value.length(), 0);
  401. zend_class_entry *ce = zend_lookup_class(constructor_name);
  402. zend_string_release(constructor_name);
  403. v8::Local<v8::FunctionTemplate> new_tpl;
  404. new_tpl = v8::Local<v8::FunctionTemplate>::New
  405. (isolate, ctx->template_cache.at(ce->name));
  406. v8::Local<v8::Function> fn;
  407. if (!new_tpl->GetFunction(v8_context).ToLocal(&fn) || !fn->NewInstance(v8_context, argc, argv).ToLocal(&result))
  408. {
  409. result = V8JS_UNDEFINED;
  410. }
  411. } else {
  412. cb->Call(v8_context, self, argc, argv).ToLocal(&result);
  413. }
  414. info.GetReturnValue().Set(result);
  415. }
  416. /* }}} */
  417. // this is a magic '__call' implementation for PHP classes which don't actually
  418. // have a '__call' magic function. This way we can always force a method
  419. // call (as opposed to a property get) from JavaScript using __call.
  420. static void v8js_fake_call_impl(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  421. {
  422. v8::Isolate *isolate = info.GetIsolate();
  423. v8::Local<v8::Context> v8_context = isolate->GetEnteredOrMicrotaskContext();
  424. v8::Local<v8::Object> self = info.Holder();
  425. v8::Local<v8::Value> return_value = V8JS_NULL;
  426. char *error;
  427. size_t error_len;
  428. zend_class_entry *ce;
  429. zend_object *object = reinterpret_cast<zend_object *>(self->GetAlignedPointerFromInternalField(1));
  430. ce = object->ce;
  431. // first arg is method name, second arg is array of args.
  432. if (info.Length() < 2) {
  433. error_len = spprintf(&error, 0,
  434. "%s::__call expects 2 parameters, %d given",
  435. ZSTR_VAL(ce->name), (int) info.Length());
  436. if (error_len > std::numeric_limits<int>::max()) {
  437. zend_throw_exception(php_ce_v8js_exception,
  438. "Generated error message length exceeds maximum supported length", 0);
  439. }
  440. else {
  441. return_value = V8JS_THROW(isolate, TypeError, error, static_cast<int>(error_len));
  442. }
  443. efree(error);
  444. info.GetReturnValue().Set(return_value);
  445. return;
  446. }
  447. if (!info[1]->IsArray()) {
  448. error_len = spprintf(&error, 0,
  449. "%s::__call expects 2nd parameter to be an array",
  450. ce->name);
  451. if (error_len > std::numeric_limits<int>::max()) {
  452. zend_throw_exception(php_ce_v8js_exception,
  453. "Generated error message length exceeds maximum supported length", 0);
  454. }
  455. else {
  456. return_value = V8JS_THROW(isolate, TypeError, error, static_cast<int>(error_len));
  457. }
  458. efree(error);
  459. info.GetReturnValue().Set(return_value);
  460. return;
  461. }
  462. v8::Local<v8::Array> args = v8::Local<v8::Array>::Cast(info[1]);
  463. if (args->Length() > 1000000) {
  464. // prevent overflow, since args->Length() is a uint32_t and args
  465. // in the Function->Call method below is a (signed) int.
  466. error_len = spprintf(&error, 0,
  467. "%s::__call expects fewer than a million arguments",
  468. ZSTR_VAL(ce->name));
  469. if (error_len > std::numeric_limits<int>::max()) {
  470. zend_throw_exception(php_ce_v8js_exception,
  471. "Generated error message length exceeds maximum supported length", 0);
  472. }
  473. else {
  474. return_value = V8JS_THROW(isolate, TypeError, error, static_cast<int>(error_len));
  475. }
  476. efree(error);
  477. info.GetReturnValue().Set(return_value);
  478. return;
  479. }
  480. v8::MaybeLocal<v8::String> str = info[0]->ToString(v8_context);
  481. if (str.IsEmpty())
  482. {
  483. error_len = spprintf(&error, 0,
  484. "%s::__call expects 1st parameter to be valid function name, toString() invocation failed.",
  485. ZSTR_VAL(ce->name));
  486. if (error_len > std::numeric_limits<int>::max()) {
  487. zend_throw_exception(php_ce_v8js_exception,
  488. "Generated error message length exceeds maximum supported length", 0);
  489. }
  490. else {
  491. return_value = V8JS_THROW(isolate, TypeError, error, static_cast<int>(error_len));
  492. }
  493. efree(error);
  494. info.GetReturnValue().Set(return_value);
  495. return;
  496. }
  497. v8::String::Utf8Value str_value(isolate, str.ToLocalChecked());
  498. const char *method_c_name = ToCString(str_value);
  499. zend_string *method_name = zend_string_init(method_c_name, str_value.length(), 0);
  500. // okay, look up the method name and manually invoke it.
  501. const zend_object_handlers *h = object->handlers;
  502. zend_function *method_ptr = h->get_method(&object, method_name, NULL);
  503. zend_string_release(method_name);
  504. if (method_ptr == NULL ||
  505. (method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) == 0 ||
  506. (method_ptr->common.fn_flags & (ZEND_ACC_CTOR|ZEND_ACC_DTOR)) != 0) {
  507. error_len = spprintf(&error, 0,
  508. "%s::__call to %s method %s", ZSTR_VAL(ce->name),
  509. (method_ptr == NULL) ? "undefined" : "non-public", method_name);
  510. if (error_len > std::numeric_limits<int>::max()) {
  511. zend_throw_exception(php_ce_v8js_exception,
  512. "Generated error message length exceeds maximum supported length", 0);
  513. }
  514. else {
  515. return_value = V8JS_THROW(isolate, TypeError, error, static_cast<int>(error_len));
  516. }
  517. efree(error);
  518. info.GetReturnValue().Set(return_value);
  519. return;
  520. }
  521. v8::Local<v8::FunctionTemplate> tmpl =
  522. v8::Local<v8::FunctionTemplate>::New
  523. (isolate, *reinterpret_cast<v8js_function_tmpl_t *>(self->GetAlignedPointerFromInternalField(0)));
  524. // use v8js_php_callback to actually execute the method
  525. v8::Local<v8::Function> cb = PHP_V8JS_CALLBACK(isolate, method_ptr, tmpl);
  526. uint32_t i, argc = args->Length();
  527. v8::Local<v8::Value> *argv = static_cast<v8::Local<v8::Value> *>(alloca(sizeof(v8::Local<v8::Value>) * argc));
  528. for (i=0; i<argc; i++) {
  529. new(&argv[i]) v8::Local<v8::Value>;
  530. args->Get(v8_context, i).ToLocal(&argv[i]);
  531. }
  532. cb->Call(v8_context, info.This(), (int) argc, argv).ToLocal(&return_value);
  533. info.GetReturnValue().Set(return_value);
  534. }
  535. /* }}} */
  536. /* This method handles named property and method get/set/query/delete. */
  537. template<typename T>
  538. 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) /* {{{ */
  539. {
  540. v8::Local<v8::String> property = v8::Local<v8::String>::Cast(property_name);
  541. v8::Isolate *isolate = info.GetIsolate();
  542. v8::Local<v8::Context> v8_context = isolate->GetEnteredOrMicrotaskContext();
  543. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  544. v8::String::Utf8Value cstr(isolate, property);
  545. const char *name = ToCString(cstr);
  546. uint32_t name_len = cstr.length();
  547. char *lower = estrndup(name, name_len);
  548. zend_string *method_name;
  549. v8::Local<v8::Object> self = info.Holder();
  550. v8::Local<v8::Value> ret_value;
  551. v8::Local<v8::Function> cb;
  552. zend_class_entry *scope, *ce;
  553. zend_function *method_ptr = NULL;
  554. zval php_value;
  555. zend_object *object = reinterpret_cast<zend_object *>(self->GetAlignedPointerFromInternalField(1));
  556. zend_object &zobject = *object;
  557. v8js_function_tmpl_t *tmpl_ptr = reinterpret_cast<v8js_function_tmpl_t *>(self->GetAlignedPointerFromInternalField(0));
  558. v8::Local<v8::FunctionTemplate> tmpl = v8::Local<v8::FunctionTemplate>::New(isolate, *tmpl_ptr);
  559. ce = scope = object->ce;
  560. /* First, check the (case-insensitive) method table */
  561. php_strtolower(lower, name_len);
  562. method_name = zend_string_init(lower, name_len, 0);
  563. // toString() -> __tostring()
  564. if (name_len == 8 && strcmp(name, "toString") == 0) {
  565. zend_string_release(method_name);
  566. method_name = zend_string_init(ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME) - 1, 0);
  567. }
  568. bool is_constructor = (name_len == 11 && strcmp(name, "constructor") == 0);
  569. bool is_magic_call = (ZSTR_LEN(method_name) == 6 && strcmp(ZSTR_VAL(method_name), "__call") == 0);
  570. if (is_constructor ||
  571. (name[0] != '$' /* leading '$' means property, not method */ &&
  572. (method_ptr = reinterpret_cast<zend_function *>
  573. (zend_hash_find_ptr(&ce->function_table, method_name))) &&
  574. ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) != 0) && /* Allow only public methods */
  575. ((method_ptr->common.fn_flags & (ZEND_ACC_CTOR|ZEND_ACC_DTOR)) == 0) /* no __construct, __destruct(), or __clone() functions */
  576. ) || (method_ptr=NULL, is_magic_call)
  577. ) {
  578. if (callback_type == V8JS_PROP_GETTER) {
  579. if (is_constructor) {
  580. // Don't set a return value here, i.e. indicate that we don't
  581. // have a special value. V8 "knows" the constructor anyways
  582. // (from the template) and will use that.
  583. } else {
  584. if (is_magic_call && method_ptr==NULL) {
  585. // Fake __call implementation
  586. // (only use this if method_ptr==NULL, which means
  587. // there is no actual PHP __call() implementation)
  588. v8::Local<v8::FunctionTemplate> ft;
  589. try {
  590. ft = v8::Local<v8::FunctionTemplate>::New
  591. (isolate, ctx->call_impls.at(tmpl_ptr));
  592. }
  593. catch (const std::out_of_range &) {
  594. ft = v8::FunctionTemplate::New(isolate,
  595. v8js_fake_call_impl, V8JS_NULL,
  596. v8::Signature::New(isolate, tmpl));
  597. v8js_function_tmpl_t *persistent_ft = &ctx->call_impls[tmpl_ptr];
  598. persistent_ft->Reset(isolate, ft);
  599. }
  600. v8::Local<v8::Function> fn;
  601. if (ft->GetFunction(v8_context).ToLocal(&fn))
  602. {
  603. fn->SetName(property);
  604. ret_value = fn;
  605. }
  606. } else {
  607. v8::Local<v8::FunctionTemplate> ft;
  608. try {
  609. ft = v8::Local<v8::FunctionTemplate>::New
  610. (isolate, ctx->method_tmpls.at(std::make_pair(ce, method_ptr)));
  611. }
  612. catch (const std::out_of_range &) {
  613. ft = v8::FunctionTemplate::New(isolate, v8js_php_callback,
  614. v8::External::New((isolate), method_ptr),
  615. v8::Signature::New((isolate), tmpl));
  616. v8js_function_tmpl_t *persistent_ft = &ctx->method_tmpls[std::make_pair(ce, method_ptr)];
  617. persistent_ft->Reset(isolate, ft);
  618. }
  619. ft->GetFunction(v8_context).ToLocal(&ret_value);
  620. }
  621. }
  622. } else if (callback_type == V8JS_PROP_QUERY) {
  623. ret_value = V8JS_UINT(v8::ReadOnly|v8::DontDelete);
  624. } else if (callback_type == V8JS_PROP_SETTER) {
  625. ret_value = set_value; // lie. this field is read-only.
  626. } else if (callback_type == V8JS_PROP_DELETER) {
  627. ret_value = V8JS_BOOL(false);
  628. } else {
  629. /* shouldn't reach here! but bail safely */
  630. ret_value = v8::Local<v8::Value>();
  631. }
  632. } else {
  633. if (name[0]=='$') {
  634. // this is a property (not a method)
  635. name++; name_len--;
  636. }
  637. zval zname;
  638. ZVAL_STRINGL(&zname, name, name_len);
  639. if (callback_type == V8JS_PROP_GETTER) {
  640. /* Nope, not a method -- must be a (case-sensitive) property */
  641. zend_property_info *property_info = zend_get_property_info(ce, Z_STR(zname), 1);
  642. if(!property_info ||
  643. (property_info != ZEND_WRONG_PROPERTY_INFO &&
  644. property_info->flags & ZEND_ACC_PUBLIC)) {
  645. zval *property_val = zend_read_property(NULL, &zobject, name, name_len, true, &php_value);
  646. if(EG(exception)) {
  647. ret_value = v8js_propagate_exception(ctx);
  648. } else if (property_val == &EG(uninitialized_zval)) {
  649. // special case uninitialized_zval_ptr and return an empty value
  650. // (indicating that we don't intercept this property) if the
  651. // property doesn't exist.
  652. ret_value = v8::Local<v8::Value>();
  653. } else {
  654. // wrap it
  655. ret_value = zval_to_v8js(property_val, isolate);
  656. /* We don't own the reference to php_value... unless the
  657. * returned refcount was 0, in which case the below code
  658. * will free it. */
  659. zval_add_ref(property_val);
  660. zval_ptr_dtor(property_val);
  661. }
  662. }
  663. else if (ce->__get
  664. /* Allow only public methods */
  665. && ((ce->__get->common.fn_flags & ZEND_ACC_PUBLIC) != 0)) {
  666. /* Okay, let's call __get. */
  667. zend_call_method_with_1_params(&zobject, ce, &ce->__get, ZEND_GET_FUNC_NAME, &php_value, &zname);
  668. ret_value = zval_to_v8js(&php_value, isolate);
  669. zval_ptr_dtor(&php_value);
  670. }
  671. } else if (callback_type == V8JS_PROP_SETTER) {
  672. if (v8js_to_zval(set_value, &php_value, ctx->flags, isolate) != SUCCESS) {
  673. ret_value = v8::Local<v8::Value>();
  674. }
  675. else {
  676. zend_property_info *property_info = zend_get_property_info(ce, Z_STR(zname), 1);
  677. if(!property_info ||
  678. (property_info != ZEND_WRONG_PROPERTY_INFO &&
  679. property_info->flags & ZEND_ACC_PUBLIC)) {
  680. zend_update_property(scope, &zobject, name, name_len, &php_value);
  681. ret_value = set_value;
  682. }
  683. else if (ce->__set
  684. /* Allow only public methods */
  685. && ((ce->__set->common.fn_flags & ZEND_ACC_PUBLIC) != 0)) {
  686. /* Okay, let's call __set. */
  687. zval php_ret_value;
  688. zend_call_method_with_2_params(&zobject, ce, &ce->__set, ZEND_SET_FUNC_NAME, &php_ret_value, &zname, &php_value);
  689. ret_value = zval_to_v8js(&php_ret_value, isolate);
  690. zval_ptr_dtor(&php_ret_value);
  691. }
  692. }
  693. // if PHP wanted to hold on to this value, update_property would
  694. // have bumped the refcount
  695. zval_ptr_dtor(&php_value);
  696. } else if (callback_type == V8JS_PROP_QUERY ||
  697. callback_type == V8JS_PROP_DELETER) {
  698. const zend_object_handlers *h = object->handlers;
  699. if (callback_type == V8JS_PROP_QUERY) {
  700. if (h->has_property(&zobject, Z_STR_P(&zname), 0, NULL)) {
  701. ret_value = V8JS_UINT(v8::None);
  702. } else {
  703. ret_value = v8::Local<v8::Value>(); // empty handle
  704. }
  705. } else {
  706. zend_property_info *property_info = zend_get_property_info(ce, Z_STR(zname), 1);
  707. if(!property_info ||
  708. (property_info != ZEND_WRONG_PROPERTY_INFO &&
  709. property_info->flags & ZEND_ACC_PUBLIC)) {
  710. h->unset_property(&zobject, Z_STR_P(&zname), NULL);
  711. ret_value = V8JS_TRUE();
  712. }
  713. else {
  714. ret_value = v8::Local<v8::Value>(); // empty handle
  715. }
  716. }
  717. } else {
  718. /* shouldn't reach here! but bail safely */
  719. ret_value = v8::Local<v8::Value>();
  720. }
  721. zval_ptr_dtor(&zname);
  722. }
  723. zend_string_release(method_name);
  724. efree(lower);
  725. return ret_value;
  726. }
  727. /* }}} */
  728. static void v8js_named_property_getter(v8::Local<v8::Name> property, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */
  729. {
  730. info.GetReturnValue().Set(v8js_named_property_callback(property, info, V8JS_PROP_GETTER));
  731. }
  732. /* }}} */
  733. static void v8js_named_property_setter(v8::Local<v8::Name> property, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */
  734. {
  735. info.GetReturnValue().Set(v8js_named_property_callback(property, info, V8JS_PROP_SETTER, value));
  736. }
  737. /* }}} */
  738. static void v8js_named_property_query(v8::Local<v8::Name> property, const v8::PropertyCallbackInfo<v8::Integer> &info) /* {{{ */
  739. {
  740. v8::Local<v8::Value> r = v8js_named_property_callback(property, info, V8JS_PROP_QUERY);
  741. if (r.IsEmpty()) {
  742. return;
  743. }
  744. v8::Isolate *isolate = info.GetIsolate();
  745. v8::MaybeLocal<v8::Integer> value = r->ToInteger(isolate->GetEnteredOrMicrotaskContext());
  746. if (!value.IsEmpty()) {
  747. info.GetReturnValue().Set(value.ToLocalChecked());
  748. }
  749. }
  750. /* }}} */
  751. static void v8js_named_property_deleter(v8::Local<v8::Name> property, const v8::PropertyCallbackInfo<v8::Boolean> &info) /* {{{ */
  752. {
  753. v8::Local<v8::Value> r = v8js_named_property_callback(property, info, V8JS_PROP_DELETER);
  754. if (r.IsEmpty()) {
  755. return;
  756. }
  757. v8::Isolate *isolate = info.GetIsolate();
  758. v8::Local<v8::Boolean> value = r->ToBoolean(isolate);
  759. if (!value.IsEmpty()) {
  760. info.GetReturnValue().Set(value);
  761. }
  762. }
  763. /* }}} */
  764. static v8::MaybeLocal<v8::Object> v8js_wrap_object(v8::Isolate *isolate, zend_class_entry *ce, zval *value) /* {{{ */
  765. {
  766. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  767. v8::Local<v8::Context> v8_context = v8::Local<v8::Context>::New(isolate, ctx->context);
  768. v8::Local<v8::FunctionTemplate> new_tpl;
  769. v8js_function_tmpl_t *persist_tpl_;
  770. try {
  771. new_tpl = v8::Local<v8::FunctionTemplate>::New
  772. (isolate, ctx->template_cache.at(ce->name));
  773. }
  774. catch (const std::out_of_range &) {
  775. /* No cached v8::FunctionTemplate available as of yet, create one. */
  776. new_tpl = v8::FunctionTemplate::New(isolate, 0);
  777. if (ZSTR_LEN(ce->name) > std::numeric_limits<int>::max()) {
  778. zend_throw_exception(php_ce_v8js_exception,
  779. "Class name length exceeds maximum supported length", 0);
  780. return v8::Local<v8::Object>();
  781. }
  782. new_tpl->SetClassName(V8JS_STRL(ZSTR_VAL(ce->name), static_cast<int>(ZSTR_LEN(ce->name))));
  783. new_tpl->InstanceTemplate()->SetInternalFieldCount(2);
  784. if (ce == zend_ce_closure) {
  785. /* Got a closure, mustn't cache ... */
  786. persist_tpl_ = new v8js_function_tmpl_t(isolate, new_tpl);
  787. /* We'll free persist_tpl_ via v8js_weak_closure_callback, below */
  788. new_tpl->InstanceTemplate()->SetCallAsFunctionHandler(v8js_php_callback);
  789. } else {
  790. /* Add new v8::FunctionTemplate to tpl_map, as long as it is not a closure. */
  791. persist_tpl_ = &ctx->template_cache[ce->name];
  792. persist_tpl_->Reset(isolate, new_tpl);
  793. /* We'll free persist_tpl_ when template_cache is destroyed */
  794. v8::Local<v8::ObjectTemplate> inst_tpl = new_tpl->InstanceTemplate();
  795. v8::GenericNamedPropertyGetterCallback getter = v8js_named_property_getter;
  796. v8::GenericNamedPropertyEnumeratorCallback enumerator = v8js_named_property_enumerator;
  797. /* Check for ArrayAccess object */
  798. if (V8JSG(use_array_access) && ce) {
  799. bool has_array_access = false;
  800. bool has_countable = false;
  801. for (unsigned int i = 0; i < ce->num_interfaces; i ++) {
  802. if (strcmp (ZSTR_VAL(ce->interfaces[i]->name), "ArrayAccess") == 0) {
  803. has_array_access = true;
  804. }
  805. else if (strcmp (ZSTR_VAL(ce->interfaces[i]->name), "Countable") == 0) {
  806. has_countable = true;
  807. }
  808. }
  809. if(has_array_access && has_countable) {
  810. inst_tpl->SetIndexedPropertyHandler(v8js_array_access_getter,
  811. v8js_array_access_setter,
  812. v8js_array_access_query,
  813. v8js_array_access_deleter,
  814. v8js_array_access_enumerator);
  815. /* Switch to special ArrayAccess getter, which falls back to
  816. * v8js_named_property_getter, but possibly bridges the
  817. * call to Array.prototype functions. */
  818. getter = v8js_array_access_named_getter;
  819. /* Overwrite enumerator, since for(... in ...) loop should
  820. * not see the methods but iterate over the elements. */
  821. enumerator = 0;
  822. }
  823. }
  824. // Finish setup of new_tpl
  825. inst_tpl->SetHandler(v8::NamedPropertyHandlerConfiguration
  826. (getter, /* getter */
  827. v8js_named_property_setter, /* setter */
  828. v8js_named_property_query, /* query */
  829. v8js_named_property_deleter, /* deleter */
  830. enumerator, /* enumerator */
  831. V8JS_NULL /* data */
  832. ));
  833. // add __invoke() handler
  834. zend_string *invoke_str = zend_string_init
  835. (ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME) - 1, 0);
  836. zend_function *invoke_method_ptr = reinterpret_cast<zend_function *>
  837. (zend_hash_find_ptr(&ce->function_table, invoke_str));
  838. if (invoke_method_ptr &&
  839. invoke_method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) {
  840. new_tpl->InstanceTemplate()->SetCallAsFunctionHandler(v8js_invoke_callback, PHP_V8JS_CALLBACK(isolate, invoke_method_ptr, new_tpl));
  841. }
  842. zend_string_release(invoke_str);
  843. }
  844. v8::Local<v8::Array> call_handler_data = v8::Array::New(isolate, 2);
  845. call_handler_data->Set(v8_context, 0, v8::External::New(isolate, persist_tpl_));
  846. call_handler_data->Set(v8_context, 1, v8::External::New(isolate, ce));
  847. new_tpl->SetCallHandler(v8js_construct_callback, call_handler_data);
  848. }
  849. // Create v8 wrapper object
  850. v8::Local<v8::Value> external = v8::External::New(isolate, Z_OBJ_P(value));
  851. v8::Local<v8::Function> constr;
  852. if (!new_tpl->GetFunction(v8_context).ToLocal(&constr)) {
  853. return v8::MaybeLocal<v8::Object>();
  854. }
  855. v8::MaybeLocal<v8::Object> newobj = constr->NewInstance(v8_context, 1, &external);
  856. bool has_json_serializable = false;
  857. for (unsigned int i = 0; i < ce->num_interfaces; i ++) {
  858. if (strcmp (ZSTR_VAL(ce->interfaces[i]->name), "JsonSerializable") == 0) {
  859. has_json_serializable = true;
  860. break;
  861. }
  862. }
  863. if (has_json_serializable) {
  864. void *ptr;
  865. zend_string *key;
  866. ZEND_HASH_FOREACH_STR_KEY_PTR(&ce->function_table, key, ptr) {
  867. zend_function *method_ptr = reinterpret_cast<zend_function *>(ptr);
  868. if (strcmp(ZSTR_VAL(method_ptr->common.function_name), "jsonSerialize") == 0) {
  869. v8::Local<v8::String> method_name = V8JS_SYM("toJSON");
  870. v8::Local<v8::FunctionTemplate> ft;
  871. ft = v8::FunctionTemplate::New(isolate, v8js_php_callback,
  872. v8::External::New((isolate), method_ptr));
  873. v8js_function_tmpl_t *persistent_ft = &ctx->method_tmpls[std::make_pair(ce, method_ptr)];
  874. persistent_ft->Reset(isolate, ft);
  875. newobj.ToLocalChecked()->CreateDataProperty(v8_context, method_name, ft->GetFunction(v8_context).ToLocalChecked());
  876. }
  877. } ZEND_HASH_FOREACH_END();
  878. }
  879. if (ce == zend_ce_closure && !newobj.IsEmpty()) {
  880. // free uncached function template when object is freed
  881. ctx->weak_closures[persist_tpl_].Reset(isolate, newobj.ToLocalChecked());
  882. ctx->weak_closures[persist_tpl_].SetWeak(persist_tpl_, v8js_weak_closure_callback, v8::WeakCallbackType::kParameter);
  883. }
  884. return newobj;
  885. }
  886. /* }}} */
  887. static v8::Local<v8::Object> v8js_wrap_array_to_object(v8::Isolate *isolate, zval *value) /* {{{ */
  888. {
  889. int i;
  890. zend_string *key;
  891. zend_ulong index;
  892. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  893. v8::Local<v8::Context> v8_context = v8::Local<v8::Context>::New(isolate, ctx->context);
  894. v8::Local<v8::FunctionTemplate> new_tpl;
  895. if(ctx->array_tmpl.IsEmpty()) {
  896. new_tpl = v8::FunctionTemplate::New(isolate, 0);
  897. /* Call it Array, but it is not a native array, especially it doesn't have
  898. * have the typical Array.prototype functions. */
  899. new_tpl->SetClassName(V8JS_SYM("Array"));
  900. /* Store for later re-use */
  901. ctx->array_tmpl.Reset(isolate, new_tpl);
  902. }
  903. else {
  904. new_tpl = v8::Local<v8::FunctionTemplate>::New(isolate, ctx->array_tmpl);
  905. }
  906. v8::Local<v8::Object> newobj = new_tpl->InstanceTemplate()->NewInstance(v8_context).ToLocalChecked();
  907. HashTable *myht = HASH_OF(value);
  908. i = myht ? zend_hash_num_elements(myht) : 0;
  909. if (i > 0)
  910. {
  911. zval *data;
  912. if (myht && !(GC_FLAGS(myht) & GC_IMMUTABLE)) {
  913. GC_PROTECT_RECURSION(myht);
  914. }
  915. ZEND_HASH_FOREACH_KEY_VAL(myht, index, key, data) {
  916. if (key) {
  917. if (ZSTR_VAL(key)[0] == '\0' && Z_TYPE_P(value) == IS_OBJECT) {
  918. /* Skip protected and private members. */
  919. continue;
  920. }
  921. if (ZSTR_LEN(key) > std::numeric_limits<int>::max()) {
  922. zend_throw_exception(php_ce_v8js_exception,
  923. "Object key length exceeds maximum supported length", 0);
  924. continue;
  925. }
  926. newobj->Set(v8_context, V8JS_STRL(ZSTR_VAL(key), static_cast<int>(ZSTR_LEN(key))),
  927. zval_to_v8js(data, isolate));
  928. } else {
  929. if (index > std::numeric_limits<uint32_t>::max()) {
  930. zend_throw_exception(php_ce_v8js_exception,
  931. "Array index exceeds maximum supported bound", 0);
  932. continue;
  933. }
  934. newobj->Set(v8_context, static_cast<uint32_t>(index), zval_to_v8js(data, isolate));
  935. }
  936. } ZEND_HASH_FOREACH_END();
  937. if (myht && !(GC_FLAGS(myht) & GC_IMMUTABLE)) {
  938. GC_UNPROTECT_RECURSION(myht);
  939. }
  940. }
  941. return newobj;
  942. }
  943. /* }}} */
  944. v8::Local<v8::Value> v8js_hash_to_jsobj(zval *value, v8::Isolate *isolate) /* {{{ */
  945. {
  946. HashTable *myht;
  947. zend_class_entry *ce = NULL;
  948. if (Z_TYPE_P(value) == IS_ARRAY) {
  949. myht = HASH_OF(value);
  950. } else {
  951. myht = Z_OBJPROP_P(value);
  952. ce = Z_OBJCE_P(value);
  953. }
  954. /* Prevent recursion */
  955. if (myht && GC_IS_RECURSIVE(myht)) {
  956. return V8JS_NULL;
  957. }
  958. /* Special case, passing back object originating from JS to JS */
  959. if (ce == php_ce_v8function || ce == php_ce_v8object || ce == php_ce_v8generator) {
  960. v8js_v8object *c = Z_V8JS_V8OBJECT_OBJ_P(value);
  961. if(isolate != c->ctx->isolate) {
  962. php_error_docref(NULL, E_WARNING, "V8Function object passed to wrong V8Js instance");
  963. return V8JS_NULL;
  964. }
  965. return v8::Local<v8::Value>::New(isolate, c->v8obj);
  966. }
  967. /* If it's a PHP object, wrap it */
  968. if (ce) {
  969. v8::MaybeLocal<v8::Object> wrapped_object = v8js_wrap_object(isolate, ce, value);
  970. if (wrapped_object.IsEmpty()) {
  971. return V8JS_UNDEFINED;
  972. }
  973. if (ce == zend_ce_generator) {
  974. /* Wrap PHP Generator object in a wrapper function that provides
  975. * ES6 style behaviour. */
  976. return v8js_wrap_generator(isolate, wrapped_object.ToLocalChecked());
  977. }
  978. return wrapped_object.ToLocalChecked();
  979. }
  980. /* Associative PHP arrays cannot be wrapped to JS arrays, convert them to
  981. * JS objects and attach all their array keys as properties. */
  982. return v8js_wrap_array_to_object(isolate, value);
  983. }
  984. /* }}} */
  985. /*
  986. * Local variables:
  987. * tab-width: 4
  988. * c-basic-offset: 4
  989. * indent-tabs-mode: t
  990. * End:
  991. * vim600: noet sw=4 ts=4 fdm=marker
  992. * vim<600: noet sw=4 ts=4
  993. */