v8js_object_export.cc 35 KB

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