v8js_object_export.cc 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170
  1. /*
  2. +----------------------------------------------------------------------+
  3. | PHP Version 7 |
  4. +----------------------------------------------------------------------+
  5. | Copyright (c) 1997-2017 The PHP Group |
  6. +----------------------------------------------------------------------+
  7. | http://www.opensource.org/licenses/mit-license.php MIT License |
  8. +----------------------------------------------------------------------+
  9. | Author: Jani Taskinen <[email protected]> |
  10. | Author: Patrick Reilly <[email protected]> |
  11. | Author: Stefan Siegl <[email protected]> |
  12. +----------------------------------------------------------------------+
  13. */
  14. #ifdef HAVE_CONFIG_H
  15. #include "config.h"
  16. #endif
  17. #include "php_v8js_macros.h"
  18. #include "v8js_array_access.h"
  19. #include "v8js_exceptions.h"
  20. #include "v8js_generator_export.h"
  21. #include "v8js_object_export.h"
  22. #include "v8js_v8object_class.h"
  23. extern "C" {
  24. #include "ext/date/php_date.h"
  25. #include "ext/standard/php_string.h"
  26. #include "zend_interfaces.h"
  27. #include "zend_closures.h"
  28. #include "zend_exceptions.h"
  29. #include "zend_generators.h"
  30. }
  31. static void v8js_weak_object_callback(const v8::WeakCallbackInfo<zend_object> &data);
  32. v8::Local<v8::Value> v8js_propagate_exception(v8js_ctx *ctx) /* {{{ */
  33. {
  34. v8::Local<v8::Value> return_value = v8::Null(ctx->isolate);
  35. if (!(ctx->flags & V8JS_FLAG_PROPAGATE_PHP_EXCEPTIONS)) {
  36. v8js_terminate_execution(ctx->isolate);
  37. return return_value;
  38. }
  39. zval tmp_zv;
  40. if (Z_TYPE(ctx->exception_filter) != IS_NULL) {
  41. zval params[1];
  42. ZVAL_OBJ(&params[0], EG(exception));
  43. Z_ADDREF_P(&params[0]);
  44. zend_clear_exception();
  45. call_user_function(EG(function_table), NULL, &ctx->exception_filter, &tmp_zv, 1, params);
  46. zval_ptr_dtor(&params[0]);
  47. if(EG(exception)) {
  48. // exception proxy threw exception itself, don't forward, just stop execution.
  49. v8js_terminate_execution(ctx->isolate);
  50. } else {
  51. return_value = ctx->isolate->ThrowException(zval_to_v8js(&tmp_zv, ctx->isolate));
  52. }
  53. } else {
  54. ZVAL_OBJ(&tmp_zv, EG(exception));
  55. return_value = ctx->isolate->ThrowException(zval_to_v8js(&tmp_zv, ctx->isolate));
  56. zend_clear_exception();
  57. }
  58. return return_value;
  59. }
  60. /* }}} */
  61. /* Callback for PHP methods and functions */
  62. static void v8js_call_php_func(zend_object *object, zend_function *method_ptr, const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  63. {
  64. v8::Isolate *isolate = info.GetIsolate();
  65. v8::Local<v8::Context> v8_context = isolate->GetEnteredOrMicrotaskContext();
  66. v8::Local<v8::Value> return_value = V8JS_NULL;
  67. zend_fcall_info fci;
  68. zend_fcall_info_cache fcc;
  69. zval fname, retval;
  70. unsigned int argc = info.Length(), min_num_args = 0, max_num_args = 0;
  71. char *error;
  72. zend_ulong error_len;
  73. unsigned int i;
  74. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  75. /* Set parameter limits */
  76. min_num_args = method_ptr->common.required_num_args;
  77. max_num_args = method_ptr->common.num_args;
  78. /* Function name to call */
  79. ZVAL_STR_COPY(&fname, method_ptr->common.function_name);
  80. /* zend_fcall_info */
  81. fci.size = sizeof(fci);
  82. #if (PHP_MAJOR_VERSION == 7 && PHP_MINOR_VERSION == 0)
  83. fci.function_table = &object->ce->function_table;
  84. fci.symbol_table = NULL;
  85. #endif
  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.no_separation = 1;
  153. info.GetReturnValue().Set(V8JS_NULL);
  154. {
  155. isolate->Exit();
  156. v8::Unlocker unlocker(isolate);
  157. zend_try {
  158. /* zend_fcall_info_cache */
  159. #if PHP_VERSION_ID < 70300
  160. fcc.initialized = 1;
  161. #endif
  162. fcc.function_handler = method_ptr;
  163. fcc.calling_scope = object->ce;
  164. fcc.called_scope = object->ce;
  165. fcc.object = object;
  166. zend_call_function(&fci, &fcc);
  167. }
  168. zend_catch {
  169. v8js_terminate_execution(isolate);
  170. V8JSG(fatal_error_abort) = 1;
  171. }
  172. zend_end_try();
  173. }
  174. isolate->Enter();
  175. failure:
  176. /* Cleanup */
  177. if (argc) {
  178. for (i = 0; i < fci.param_count; i++) {
  179. zval_ptr_dtor(&fci.params[i]);
  180. }
  181. efree(fci.params);
  182. }
  183. if(EG(exception)) {
  184. return_value = v8js_propagate_exception(ctx);
  185. } else if (Z_TYPE(retval) == IS_OBJECT && Z_OBJ(retval) == object) {
  186. // special case: "return $this"
  187. return_value = info.Holder();
  188. } else {
  189. return_value = zval_to_v8js(&retval, isolate);
  190. }
  191. zval_ptr_dtor(&retval);
  192. zval_ptr_dtor(&fname);
  193. info.GetReturnValue().Set(return_value);
  194. }
  195. /* }}} */
  196. /* Callback for PHP methods and functions */
  197. void v8js_php_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  198. {
  199. v8::Local<v8::Object> self = info.Holder();
  200. zend_object *object = reinterpret_cast<zend_object *>(self->GetAlignedPointerFromInternalField(1));
  201. zend_function *method_ptr;
  202. /* Set method_ptr from v8::External or fetch the closure invoker */
  203. if (!info.Data().IsEmpty() && info.Data()->IsExternal()) {
  204. method_ptr = static_cast<zend_function *>(v8::External::Cast(*info.Data())->Value());
  205. } else {
  206. method_ptr = zend_get_closure_invoke_method(object);
  207. }
  208. return v8js_call_php_func(object, method_ptr, info);
  209. }
  210. /* Callback for PHP constructor calls */
  211. static void v8js_construct_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  212. {
  213. v8::Isolate *isolate = info.GetIsolate();
  214. info.GetReturnValue().Set(V8JS_UNDEFINED);
  215. v8::Local<v8::Object> newobj = info.This();
  216. zval value;
  217. if (!info.IsConstructCall()) {
  218. return;
  219. }
  220. v8::Local<v8::Array> cons_data = v8::Local<v8::Array>::Cast(info.Data());
  221. v8::Local<v8::Value> cons_tmpl, cons_ce;
  222. if (!cons_data->Get(isolate->GetEnteredOrMicrotaskContext(), 0).ToLocal(&cons_tmpl)
  223. ||!cons_data->Get(isolate->GetEnteredOrMicrotaskContext(), 1).ToLocal(&cons_ce))
  224. {
  225. return;
  226. }
  227. v8::Local<v8::External> ext_tmpl = v8::Local<v8::External>::Cast(cons_tmpl);
  228. v8::Local<v8::External> ext_ce = v8::Local<v8::External>::Cast(cons_ce);
  229. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  230. if (info[0]->IsExternal()) {
  231. // Object created by v8js in v8js_hash_to_jsobj, PHP object passed as v8::External.
  232. v8::Local<v8::External> php_object = v8::Local<v8::External>::Cast(info[0]);
  233. zend_object *object = reinterpret_cast<zend_object *>(php_object->Value());
  234. ZVAL_OBJ(&value, object);
  235. if(ctx->weak_objects.count(object)) {
  236. // We already exported this object, hence no need to add another
  237. // ref, v8 won't give us a second weak-object callback anyways.
  238. newobj->SetAlignedPointerInInternalField(0, ext_tmpl->Value());
  239. newobj->SetAlignedPointerInInternalField(1, object);
  240. return;
  241. }
  242. // Increase the reference count of this value because we're storing it internally for use later
  243. // See https://github.com/phpv8/v8js/issues/6
  244. Z_ADDREF_P(&value);
  245. } else {
  246. // Object created from JavaScript context. Need to create PHP object first.
  247. zend_class_entry *ce = static_cast<zend_class_entry *>(ext_ce->Value());
  248. zend_function *ctor_ptr = ce->constructor;
  249. // Check access on __construct function, if any
  250. if (ctor_ptr != NULL && (ctor_ptr->common.fn_flags & ZEND_ACC_PUBLIC) == 0) {
  251. info.GetReturnValue().Set(isolate->ThrowException(V8JS_SYM("Call to protected __construct() not allowed")));
  252. return;
  253. }
  254. object_init_ex(&value, ce);
  255. // Call __construct function
  256. if (ctor_ptr != NULL) {
  257. v8js_call_php_func(Z_OBJ(value), ctor_ptr, info);
  258. }
  259. }
  260. newobj->SetAlignedPointerInInternalField(0, ext_tmpl->Value());
  261. newobj->SetAlignedPointerInInternalField(1, Z_OBJ(value));
  262. // Since we got to decrease the reference count again, in case v8 garbage collector
  263. // decides to dispose the JS object, we add a weak persistent handle and register
  264. // a callback function that removes the reference.
  265. ctx->weak_objects[Z_OBJ(value)].Reset(isolate, newobj);
  266. ctx->weak_objects[Z_OBJ(value)].SetWeak(Z_OBJ(value), v8js_weak_object_callback, v8::WeakCallbackType::kParameter);
  267. // Just tell v8 that we're allocating some external memory
  268. // (for the moment we just always tell 1k instead of trying to find out actual values)
  269. isolate->AdjustAmountOfExternalAllocatedMemory(ctx->average_object_size);
  270. }
  271. /* }}} */
  272. static void v8js_weak_object_callback(const v8::WeakCallbackInfo<zend_object> &data) {
  273. v8::Isolate *isolate = data.GetIsolate();
  274. zend_object *object = data.GetParameter();
  275. zval value;
  276. ZVAL_OBJ(&value, object);
  277. zval_ptr_dtor(&value);
  278. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  279. ctx->weak_objects.at(object).Reset();
  280. ctx->weak_objects.erase(object);
  281. isolate->AdjustAmountOfExternalAllocatedMemory(-ctx->average_object_size);
  282. }
  283. static void v8js_weak_closure_callback(const v8::WeakCallbackInfo<v8js_function_tmpl_t> &data) {
  284. v8::Isolate *isolate = data.GetIsolate();
  285. v8js_function_tmpl_t *persist_tpl_ = data.GetParameter();
  286. persist_tpl_->Reset();
  287. delete persist_tpl_;
  288. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  289. ctx->weak_closures.at(persist_tpl_).Reset();
  290. ctx->weak_closures.erase(persist_tpl_);
  291. };
  292. #define IS_MAGIC_FUNC(mname) \
  293. ((ZSTR_LEN(key) == sizeof(mname) - 1) && \
  294. !strncasecmp(ZSTR_VAL(key), mname, ZSTR_LEN(key)))
  295. #define PHP_V8JS_CALLBACK(isolate, mptr, tmpl) \
  296. (v8::FunctionTemplate::New((isolate), v8js_php_callback, v8::External::New((isolate), mptr), v8::Signature::New((isolate), tmpl))->GetFunction(isolate->GetEnteredOrMicrotaskContext()).ToLocalChecked())
  297. static void v8js_named_property_enumerator(const v8::PropertyCallbackInfo<v8::Array> &info) /* {{{ */
  298. {
  299. // note: 'special' properties like 'constructor' are not enumerated.
  300. v8::Isolate *isolate = info.GetIsolate();
  301. v8::Local<v8::Context> v8_context = isolate->GetEnteredOrMicrotaskContext();
  302. v8::Local<v8::Object> self = info.Holder();
  303. v8::Local<v8::Array> result = v8::Array::New(isolate, 0);
  304. uint32_t result_len = 0;
  305. zend_class_entry *ce;
  306. void *ptr;
  307. HashTable *proptable;
  308. zend_string *key;
  309. zend_ulong index;
  310. zend_object *object = reinterpret_cast<zend_object *>(self->GetAlignedPointerFromInternalField(1));
  311. ce = object->ce;
  312. /* enumerate all methods */
  313. ZEND_HASH_FOREACH_STR_KEY_PTR(&ce->function_table, key, ptr) {
  314. zend_function *method_ptr = reinterpret_cast<zend_function *>(ptr);
  315. if ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) == 0) {
  316. /* Allow only public methods */
  317. continue;
  318. }
  319. if ((method_ptr->common.fn_flags & (ZEND_ACC_CTOR|ZEND_ACC_DTOR)) != 0) {
  320. /* no __construct, __destruct(), or __clone() functions */
  321. continue;
  322. }
  323. // hide (do not enumerate) other PHP magic functions
  324. if (IS_MAGIC_FUNC(ZEND_CALLSTATIC_FUNC_NAME) ||
  325. IS_MAGIC_FUNC(ZEND_SLEEP_FUNC_NAME) ||
  326. IS_MAGIC_FUNC(ZEND_WAKEUP_FUNC_NAME) ||
  327. IS_MAGIC_FUNC(ZEND_SET_STATE_FUNC_NAME) ||
  328. IS_MAGIC_FUNC(ZEND_GET_FUNC_NAME) ||
  329. IS_MAGIC_FUNC(ZEND_SET_FUNC_NAME) ||
  330. IS_MAGIC_FUNC(ZEND_UNSET_FUNC_NAME) ||
  331. IS_MAGIC_FUNC(ZEND_CALL_FUNC_NAME) ||
  332. IS_MAGIC_FUNC(ZEND_INVOKE_FUNC_NAME) ||
  333. IS_MAGIC_FUNC(ZEND_ISSET_FUNC_NAME)) {
  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. zval zobject;
  558. ZVAL_OBJ(&zobject, object);
  559. v8js_function_tmpl_t *tmpl_ptr = reinterpret_cast<v8js_function_tmpl_t *>(self->GetAlignedPointerFromInternalField(0));
  560. v8::Local<v8::FunctionTemplate> tmpl = v8::Local<v8::FunctionTemplate>::New(isolate, *tmpl_ptr);
  561. ce = scope = object->ce;
  562. /* First, check the (case-insensitive) method table */
  563. php_strtolower(lower, name_len);
  564. method_name = zend_string_init(lower, name_len, 0);
  565. // toString() -> __tostring()
  566. if (name_len == 8 && strcmp(name, "toString") == 0) {
  567. zend_string_release(method_name);
  568. method_name = zend_string_init(ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME) - 1, 0);
  569. }
  570. bool is_constructor = (name_len == 11 && strcmp(name, "constructor") == 0);
  571. bool is_magic_call = (ZSTR_LEN(method_name) == 6 && strcmp(ZSTR_VAL(method_name), "__call") == 0);
  572. if (is_constructor ||
  573. (name[0] != '$' /* leading '$' means property, not method */ &&
  574. (method_ptr = reinterpret_cast<zend_function *>
  575. (zend_hash_find_ptr(&ce->function_table, method_name))) &&
  576. ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) != 0) && /* Allow only public methods */
  577. ((method_ptr->common.fn_flags & (ZEND_ACC_CTOR|ZEND_ACC_DTOR)) == 0) /* no __construct, __destruct(), or __clone() functions */
  578. ) || (method_ptr=NULL, is_magic_call)
  579. ) {
  580. if (callback_type == V8JS_PROP_GETTER) {
  581. if (is_constructor) {
  582. // Don't set a return value here, i.e. indicate that we don't
  583. // have a special value. V8 "knows" the constructor anyways
  584. // (from the template) and will use that.
  585. } else {
  586. if (is_magic_call && method_ptr==NULL) {
  587. // Fake __call implementation
  588. // (only use this if method_ptr==NULL, which means
  589. // there is no actual PHP __call() implementation)
  590. v8::Local<v8::FunctionTemplate> ft;
  591. try {
  592. ft = v8::Local<v8::FunctionTemplate>::New
  593. (isolate, ctx->call_impls.at(tmpl_ptr));
  594. }
  595. catch (const std::out_of_range &) {
  596. ft = v8::FunctionTemplate::New(isolate,
  597. v8js_fake_call_impl, V8JS_NULL,
  598. v8::Signature::New(isolate, tmpl));
  599. v8js_function_tmpl_t *persistent_ft = &ctx->call_impls[tmpl_ptr];
  600. persistent_ft->Reset(isolate, ft);
  601. }
  602. v8::Local<v8::Function> fn;
  603. if (ft->GetFunction(v8_context).ToLocal(&fn))
  604. {
  605. fn->SetName(property);
  606. ret_value = fn;
  607. }
  608. } else {
  609. v8::Local<v8::FunctionTemplate> ft;
  610. try {
  611. ft = v8::Local<v8::FunctionTemplate>::New
  612. (isolate, ctx->method_tmpls.at(std::make_pair(ce, method_ptr)));
  613. }
  614. catch (const std::out_of_range &) {
  615. ft = v8::FunctionTemplate::New(isolate, v8js_php_callback,
  616. v8::External::New((isolate), method_ptr),
  617. v8::Signature::New((isolate), tmpl));
  618. v8js_function_tmpl_t *persistent_ft = &ctx->method_tmpls[std::make_pair(ce, method_ptr)];
  619. persistent_ft->Reset(isolate, ft);
  620. }
  621. ft->GetFunction(v8_context).ToLocal(&ret_value);
  622. }
  623. }
  624. } else if (callback_type == V8JS_PROP_QUERY) {
  625. ret_value = V8JS_UINT(v8::ReadOnly|v8::DontDelete);
  626. } else if (callback_type == V8JS_PROP_SETTER) {
  627. ret_value = set_value; // lie. this field is read-only.
  628. } else if (callback_type == V8JS_PROP_DELETER) {
  629. ret_value = V8JS_BOOL(false);
  630. } else {
  631. /* shouldn't reach here! but bail safely */
  632. ret_value = v8::Local<v8::Value>();
  633. }
  634. } else {
  635. if (name[0]=='$') {
  636. // this is a property (not a method)
  637. name++; name_len--;
  638. }
  639. zval zname;
  640. ZVAL_STRINGL(&zname, name, name_len);
  641. if (callback_type == V8JS_PROP_GETTER) {
  642. /* Nope, not a method -- must be a (case-sensitive) property */
  643. zend_property_info *property_info = zend_get_property_info(ce, Z_STR(zname), 1);
  644. if(!property_info ||
  645. (property_info != ZEND_WRONG_PROPERTY_INFO &&
  646. property_info->flags & ZEND_ACC_PUBLIC)) {
  647. zval *property_val = zend_read_property(NULL, &zobject, name, name_len, true, &php_value);
  648. // special case uninitialized_zval_ptr and return an empty value
  649. // (indicating that we don't intercept this property) if the
  650. // property doesn't exist.
  651. if (property_val == &EG(uninitialized_zval)) {
  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, &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, &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. if (ce == zend_ce_closure && !newobj.IsEmpty()) {
  857. // free uncached function template when object is freed
  858. ctx->weak_closures[persist_tpl_].Reset(isolate, newobj.ToLocalChecked());
  859. ctx->weak_closures[persist_tpl_].SetWeak(persist_tpl_, v8js_weak_closure_callback, v8::WeakCallbackType::kParameter);
  860. }
  861. return newobj;
  862. }
  863. /* }}} */
  864. static v8::Local<v8::Object> v8js_wrap_array_to_object(v8::Isolate *isolate, zval *value) /* {{{ */
  865. {
  866. int i;
  867. zend_string *key;
  868. zend_ulong index;
  869. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  870. v8::Local<v8::Context> v8_context = v8::Local<v8::Context>::New(isolate, ctx->context);
  871. v8::Local<v8::FunctionTemplate> new_tpl;
  872. if(ctx->array_tmpl.IsEmpty()) {
  873. new_tpl = v8::FunctionTemplate::New(isolate, 0);
  874. /* Call it Array, but it is not a native array, especially it doesn't have
  875. * have the typical Array.prototype functions. */
  876. new_tpl->SetClassName(V8JS_SYM("Array"));
  877. /* Store for later re-use */
  878. ctx->array_tmpl.Reset(isolate, new_tpl);
  879. }
  880. else {
  881. new_tpl = v8::Local<v8::FunctionTemplate>::New(isolate, ctx->array_tmpl);
  882. }
  883. v8::Local<v8::Object> newobj = new_tpl->InstanceTemplate()->NewInstance(v8_context).ToLocalChecked();
  884. HashTable *myht = HASH_OF(value);
  885. i = myht ? zend_hash_num_elements(myht) : 0;
  886. if (i > 0)
  887. {
  888. zval *data;
  889. #if PHP_VERSION_ID >= 70300
  890. if (myht && !(GC_FLAGS(myht) & GC_IMMUTABLE)) {
  891. #else
  892. if (myht) {
  893. #endif
  894. GC_PROTECT_RECURSION(myht);
  895. }
  896. ZEND_HASH_FOREACH_KEY_VAL(myht, index, key, data) {
  897. if (key) {
  898. if (ZSTR_VAL(key)[0] == '\0' && Z_TYPE_P(value) == IS_OBJECT) {
  899. /* Skip protected and private members. */
  900. continue;
  901. }
  902. if (ZSTR_LEN(key) > std::numeric_limits<int>::max()) {
  903. zend_throw_exception(php_ce_v8js_exception,
  904. "Object key length exceeds maximum supported length", 0);
  905. continue;
  906. }
  907. newobj->Set(v8_context, V8JS_STRL(ZSTR_VAL(key), static_cast<int>(ZSTR_LEN(key))),
  908. zval_to_v8js(data, isolate));
  909. } else {
  910. if (index > std::numeric_limits<uint32_t>::max()) {
  911. zend_throw_exception(php_ce_v8js_exception,
  912. "Array index exceeds maximum supported bound", 0);
  913. continue;
  914. }
  915. newobj->Set(v8_context, static_cast<uint32_t>(index), zval_to_v8js(data, isolate));
  916. }
  917. } ZEND_HASH_FOREACH_END();
  918. #if PHP_VERSION_ID >= 70300
  919. if (myht && !(GC_FLAGS(myht) & GC_IMMUTABLE)) {
  920. #else
  921. if (myht) {
  922. #endif
  923. GC_UNPROTECT_RECURSION(myht);
  924. }
  925. }
  926. return newobj;
  927. }
  928. /* }}} */
  929. v8::Local<v8::Value> v8js_hash_to_jsobj(zval *value, v8::Isolate *isolate) /* {{{ */
  930. {
  931. HashTable *myht;
  932. zend_class_entry *ce = NULL;
  933. if (Z_TYPE_P(value) == IS_ARRAY) {
  934. myht = HASH_OF(value);
  935. } else {
  936. myht = Z_OBJPROP_P(value);
  937. ce = Z_OBJCE_P(value);
  938. }
  939. /* Prevent recursion */
  940. #if PHP_VERSION_ID >= 70300
  941. if (myht && GC_IS_RECURSIVE(myht)) {
  942. #else
  943. if (myht && ZEND_HASH_GET_APPLY_COUNT(myht) > 1) {
  944. #endif
  945. return V8JS_NULL;
  946. }
  947. /* Special case, passing back object originating from JS to JS */
  948. if (ce == php_ce_v8function || ce == php_ce_v8object || ce == php_ce_v8generator) {
  949. v8js_v8object *c = Z_V8JS_V8OBJECT_OBJ_P(value);
  950. if(isolate != c->ctx->isolate) {
  951. php_error_docref(NULL, E_WARNING, "V8Function object passed to wrong V8Js instance");
  952. return V8JS_NULL;
  953. }
  954. return v8::Local<v8::Value>::New(isolate, c->v8obj);
  955. }
  956. /* If it's a PHP object, wrap it */
  957. if (ce) {
  958. v8::MaybeLocal<v8::Object> wrapped_object = v8js_wrap_object(isolate, ce, value);
  959. if (wrapped_object.IsEmpty()) {
  960. return V8JS_UNDEFINED;
  961. }
  962. if (ce == zend_ce_generator) {
  963. /* Wrap PHP Generator object in a wrapper function that provides
  964. * ES6 style behaviour. */
  965. return v8js_wrap_generator(isolate, wrapped_object.ToLocalChecked());
  966. }
  967. return wrapped_object.ToLocalChecked();
  968. }
  969. /* Associative PHP arrays cannot be wrapped to JS arrays, convert them to
  970. * JS objects and attach all their array keys as properties. */
  971. return v8js_wrap_array_to_object(isolate, value);
  972. }
  973. /* }}} */
  974. /*
  975. * Local variables:
  976. * tab-width: 4
  977. * c-basic-offset: 4
  978. * indent-tabs-mode: t
  979. * End:
  980. * vim600: noet sw=4 ts=4 fdm=marker
  981. * vim<600: noet sw=4 ts=4
  982. */