v8js_object_export.cc 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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) && !V8JSG(compat_php_exceptions)) {
  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_tmpl_t> &data) {
  246. v8::Isolate *isolate = data.GetIsolate();
  247. v8js_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|ZEND_ACC_CLONE)) != 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|ZEND_ACC_CLONE)) != 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_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_tmpl_t *tmpl_ptr = reinterpret_cast<v8js_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|ZEND_ACC_CLONE)) == 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_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_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. // methods are not enumerable
  565. ret_value = V8JS_UINT(v8::ReadOnly|v8::DontEnum|v8::DontDelete);
  566. } else if (callback_type == V8JS_PROP_SETTER) {
  567. ret_value = set_value; // lie. this field is read-only.
  568. } else if (callback_type == V8JS_PROP_DELETER) {
  569. ret_value = V8JS_BOOL(false);
  570. } else {
  571. /* shouldn't reach here! but bail safely */
  572. ret_value = v8::Local<v8::Value>();
  573. }
  574. } else {
  575. if (name[0]=='$') {
  576. // this is a property (not a method)
  577. name++; name_len--;
  578. }
  579. zval zname;
  580. ZVAL_STRINGL(&zname, name, name_len);
  581. if (callback_type == V8JS_PROP_GETTER) {
  582. /* Nope, not a method -- must be a (case-sensitive) property */
  583. zend_property_info *property_info = zend_get_property_info(ce, Z_STR(zname), 1);
  584. if(!property_info ||
  585. (property_info != ZEND_WRONG_PROPERTY_INFO &&
  586. property_info->flags & ZEND_ACC_PUBLIC)) {
  587. zval *property_val = zend_read_property(NULL, &zobject, name, name_len, true, &php_value);
  588. // special case uninitialized_zval_ptr and return an empty value
  589. // (indicating that we don't intercept this property) if the
  590. // property doesn't exist.
  591. if (property_val == &EG(uninitialized_zval)) {
  592. ret_value = v8::Local<v8::Value>();
  593. } else {
  594. // wrap it
  595. ret_value = zval_to_v8js(property_val, isolate);
  596. /* We don't own the reference to php_value... unless the
  597. * returned refcount was 0, in which case the below code
  598. * will free it. */
  599. zval_add_ref(property_val);
  600. zval_ptr_dtor(property_val);
  601. }
  602. }
  603. else if (ce->__get
  604. /* Allow only public methods */
  605. && ((ce->__get->common.fn_flags & ZEND_ACC_PUBLIC) != 0)) {
  606. /* Okay, let's call __get. */
  607. zend_call_method_with_1_params(&zobject, ce, &ce->__get, ZEND_GET_FUNC_NAME, &php_value, &zname);
  608. ret_value = zval_to_v8js(&php_value, isolate);
  609. zval_ptr_dtor(&php_value);
  610. }
  611. } else if (callback_type == V8JS_PROP_SETTER) {
  612. if (v8js_to_zval(set_value, &php_value, ctx->flags, isolate) != SUCCESS) {
  613. ret_value = v8::Local<v8::Value>();
  614. }
  615. else {
  616. zend_property_info *property_info = zend_get_property_info(ce, Z_STR(zname), 1);
  617. if(!property_info ||
  618. (property_info != ZEND_WRONG_PROPERTY_INFO &&
  619. property_info->flags & ZEND_ACC_PUBLIC)) {
  620. zend_update_property(scope, &zobject, name, name_len, &php_value);
  621. ret_value = set_value;
  622. }
  623. else if (ce->__set
  624. /* Allow only public methods */
  625. && ((ce->__set->common.fn_flags & ZEND_ACC_PUBLIC) != 0)) {
  626. /* Okay, let's call __set. */
  627. zval php_ret_value;
  628. zend_call_method_with_2_params(&zobject, ce, &ce->__set, ZEND_SET_FUNC_NAME, &php_ret_value, &zname, &php_value);
  629. ret_value = zval_to_v8js(&php_ret_value, isolate);
  630. zval_ptr_dtor(&php_ret_value);
  631. }
  632. }
  633. // if PHP wanted to hold on to this value, update_property would
  634. // have bumped the refcount
  635. zval_ptr_dtor(&php_value);
  636. } else if (callback_type == V8JS_PROP_QUERY ||
  637. callback_type == V8JS_PROP_DELETER) {
  638. const zend_object_handlers *h = object->handlers;
  639. if (callback_type == V8JS_PROP_QUERY) {
  640. if (h->has_property(&zobject, &zname, 0, NULL)) {
  641. ret_value = V8JS_UINT(v8::None);
  642. } else {
  643. ret_value = v8::Local<v8::Value>(); // empty handle
  644. }
  645. } else {
  646. zend_property_info *property_info = zend_get_property_info(ce, Z_STR(zname), 1);
  647. if(!property_info ||
  648. (property_info != ZEND_WRONG_PROPERTY_INFO &&
  649. property_info->flags & ZEND_ACC_PUBLIC)) {
  650. h->unset_property(&zobject, &zname, NULL);
  651. ret_value = V8JS_TRUE();
  652. }
  653. else {
  654. ret_value = v8::Local<v8::Value>(); // empty handle
  655. }
  656. }
  657. } else {
  658. /* shouldn't reach here! but bail safely */
  659. ret_value = v8::Local<v8::Value>();
  660. }
  661. zval_ptr_dtor(&zname);
  662. }
  663. zend_string_release(method_name);
  664. efree(lower);
  665. return ret_value;
  666. }
  667. /* }}} */
  668. static void v8js_named_property_getter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */
  669. {
  670. info.GetReturnValue().Set(v8js_named_property_callback(property, info, V8JS_PROP_GETTER));
  671. }
  672. /* }}} */
  673. static void v8js_named_property_setter(v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */
  674. {
  675. info.GetReturnValue().Set(v8js_named_property_callback(property, info, V8JS_PROP_SETTER, value));
  676. }
  677. /* }}} */
  678. static void v8js_named_property_query(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Integer> &info) /* {{{ */
  679. {
  680. v8::Local<v8::Value> r = v8js_named_property_callback(property, info, V8JS_PROP_QUERY);
  681. if (!r.IsEmpty()) {
  682. info.GetReturnValue().Set(r->ToInteger());
  683. }
  684. }
  685. /* }}} */
  686. static void v8js_named_property_deleter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Boolean> &info) /* {{{ */
  687. {
  688. v8::Local<v8::Value> r = v8js_named_property_callback(property, info, V8JS_PROP_DELETER);
  689. if (!r.IsEmpty()) {
  690. info.GetReturnValue().Set(r->ToBoolean());
  691. }
  692. }
  693. /* }}} */
  694. static v8::MaybeLocal<v8::Object> v8js_wrap_object(v8::Isolate *isolate, zend_class_entry *ce, zval *value) /* {{{ */
  695. {
  696. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  697. v8::Local<v8::FunctionTemplate> new_tpl;
  698. v8js_tmpl_t *persist_tpl_;
  699. try {
  700. new_tpl = v8::Local<v8::FunctionTemplate>::New
  701. (isolate, ctx->template_cache.at(ce->name));
  702. }
  703. catch (const std::out_of_range &) {
  704. /* No cached v8::FunctionTemplate available as of yet, create one. */
  705. new_tpl = v8::FunctionTemplate::New(isolate, 0);
  706. if (ZSTR_LEN(ce->name) > std::numeric_limits<int>::max()) {
  707. zend_throw_exception(php_ce_v8js_exception,
  708. "Class name length exceeds maximum supported length", 0);
  709. return v8::Local<v8::Object>();
  710. }
  711. new_tpl->SetClassName(V8JS_STRL(ZSTR_VAL(ce->name), static_cast<int>(ZSTR_LEN(ce->name))));
  712. new_tpl->InstanceTemplate()->SetInternalFieldCount(2);
  713. if (ce == zend_ce_closure) {
  714. /* Got a closure, mustn't cache ... */
  715. persist_tpl_ = new v8js_tmpl_t(isolate, new_tpl);
  716. /* We'll free persist_tpl_ via v8js_weak_closure_callback, below */
  717. new_tpl->InstanceTemplate()->SetCallAsFunctionHandler(v8js_php_callback);
  718. } else {
  719. /* Add new v8::FunctionTemplate to tpl_map, as long as it is not a closure. */
  720. persist_tpl_ = &ctx->template_cache[ce->name];
  721. persist_tpl_->Reset(isolate, new_tpl);
  722. /* We'll free persist_tpl_ when template_cache is destroyed */
  723. v8::Local<v8::ObjectTemplate> inst_tpl = new_tpl->InstanceTemplate();
  724. v8::NamedPropertyGetterCallback getter = v8js_named_property_getter;
  725. v8::NamedPropertyEnumeratorCallback enumerator = v8js_named_property_enumerator;
  726. /* Check for ArrayAccess object */
  727. if (V8JSG(use_array_access) && ce) {
  728. bool has_array_access = false;
  729. bool has_countable = false;
  730. for (unsigned int i = 0; i < ce->num_interfaces; i ++) {
  731. if (strcmp (ZSTR_VAL(ce->interfaces[i]->name), "ArrayAccess") == 0) {
  732. has_array_access = true;
  733. }
  734. else if (strcmp (ZSTR_VAL(ce->interfaces[i]->name), "Countable") == 0) {
  735. has_countable = true;
  736. }
  737. }
  738. if(has_array_access && has_countable) {
  739. inst_tpl->SetIndexedPropertyHandler(v8js_array_access_getter,
  740. v8js_array_access_setter,
  741. v8js_array_access_query,
  742. v8js_array_access_deleter,
  743. v8js_array_access_enumerator);
  744. /* Switch to special ArrayAccess getter, which falls back to
  745. * v8js_named_property_getter, but possibly bridges the
  746. * call to Array.prototype functions. */
  747. getter = v8js_array_access_named_getter;
  748. /* Overwrite enumerator, since for(... in ...) loop should
  749. * not see the methods but iterate over the elements. */
  750. enumerator = 0;
  751. }
  752. }
  753. // Finish setup of new_tpl
  754. inst_tpl->SetNamedPropertyHandler
  755. (getter, /* getter */
  756. v8js_named_property_setter, /* setter */
  757. v8js_named_property_query, /* query */
  758. v8js_named_property_deleter, /* deleter */
  759. enumerator, /* enumerator */
  760. V8JS_NULL /* data */
  761. );
  762. // add __invoke() handler
  763. zend_string *invoke_str = zend_string_init
  764. (ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME) - 1, 0);
  765. zend_function *invoke_method_ptr = reinterpret_cast<zend_function *>
  766. (zend_hash_find_ptr(&ce->function_table, invoke_str));
  767. if (invoke_method_ptr &&
  768. invoke_method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) {
  769. new_tpl->InstanceTemplate()->SetCallAsFunctionHandler(v8js_invoke_callback, PHP_V8JS_CALLBACK(isolate, invoke_method_ptr, new_tpl));
  770. }
  771. zend_string_release(invoke_str);
  772. }
  773. v8::Local<v8::Array> call_handler_data = v8::Array::New(isolate, 2);
  774. call_handler_data->Set(0, v8::External::New(isolate, persist_tpl_));
  775. call_handler_data->Set(1, v8::External::New(isolate, ce));
  776. new_tpl->SetCallHandler(v8js_construct_callback, call_handler_data);
  777. }
  778. // Create v8 wrapper object
  779. v8::Local<v8::Value> external = v8::External::New(isolate, Z_OBJ_P(value));
  780. v8::MaybeLocal<v8::Object> newobj = new_tpl->GetFunction()->NewInstance(isolate->GetEnteredContext(), 1, &external);
  781. if (ce == zend_ce_closure && !newobj.IsEmpty()) {
  782. // free uncached function template when object is freed
  783. ctx->weak_closures[persist_tpl_].Reset(isolate, newobj.ToLocalChecked());
  784. ctx->weak_closures[persist_tpl_].SetWeak(persist_tpl_, v8js_weak_closure_callback, v8::WeakCallbackType::kParameter);
  785. }
  786. return newobj;
  787. }
  788. /* }}} */
  789. static v8::Local<v8::Object> v8js_wrap_array_to_object(v8::Isolate *isolate, zval *value) /* {{{ */
  790. {
  791. int i;
  792. zend_string *key;
  793. zend_ulong index;
  794. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  795. v8::Local<v8::FunctionTemplate> new_tpl;
  796. if(ctx->array_tmpl.IsEmpty()) {
  797. new_tpl = v8::FunctionTemplate::New(isolate, 0);
  798. /* Call it Array, but it is not a native array, especially it doesn't have
  799. * have the typical Array.prototype functions. */
  800. new_tpl->SetClassName(V8JS_SYM("Array"));
  801. /* Store for later re-use */
  802. ctx->array_tmpl.Reset(isolate, new_tpl);
  803. }
  804. else {
  805. new_tpl = v8::Local<v8::FunctionTemplate>::New(isolate, ctx->array_tmpl);
  806. }
  807. v8::Local<v8::Object> newobj = new_tpl->InstanceTemplate()->NewInstance();
  808. HashTable *myht = HASH_OF(value);
  809. i = myht ? zend_hash_num_elements(myht) : 0;
  810. if (i > 0)
  811. {
  812. zval *data;
  813. HashTable *tmp_ht;
  814. ZEND_HASH_FOREACH_KEY_VAL(myht, index, key, data) {
  815. tmp_ht = HASH_OF(data);
  816. if (tmp_ht) {
  817. ZEND_HASH_INC_APPLY_COUNT(tmp_ht);
  818. }
  819. if (key) {
  820. if (ZSTR_VAL(key)[0] == '\0' && Z_TYPE_P(value) == IS_OBJECT) {
  821. /* Skip protected and private members. */
  822. if (tmp_ht) {
  823. ZEND_HASH_DEC_APPLY_COUNT(tmp_ht);
  824. }
  825. continue;
  826. }
  827. if (ZSTR_LEN(key) > std::numeric_limits<int>::max()) {
  828. zend_throw_exception(php_ce_v8js_exception,
  829. "Object key length exceeds maximum supported length", 0);
  830. continue;
  831. }
  832. newobj->Set(V8JS_STRL(ZSTR_VAL(key), static_cast<int>(ZSTR_LEN(key))),
  833. zval_to_v8js(data, isolate));
  834. } else {
  835. if (index > std::numeric_limits<uint32_t>::max()) {
  836. zend_throw_exception(php_ce_v8js_exception,
  837. "Array index exceeds maximum supported bound", 0);
  838. continue;
  839. }
  840. newobj->Set(static_cast<uint32_t>(index), zval_to_v8js(data, isolate));
  841. }
  842. if (tmp_ht) {
  843. ZEND_HASH_DEC_APPLY_COUNT(tmp_ht);
  844. }
  845. } ZEND_HASH_FOREACH_END();
  846. }
  847. return newobj;
  848. }
  849. /* }}} */
  850. v8::Local<v8::Value> v8js_hash_to_jsobj(zval *value, v8::Isolate *isolate) /* {{{ */
  851. {
  852. HashTable *myht;
  853. zend_class_entry *ce = NULL;
  854. if (Z_TYPE_P(value) == IS_ARRAY) {
  855. myht = HASH_OF(value);
  856. } else {
  857. myht = Z_OBJPROP_P(value);
  858. ce = Z_OBJCE_P(value);
  859. }
  860. /* Prevent recursion */
  861. if (myht && ZEND_HASH_GET_APPLY_COUNT(myht) > 1) {
  862. return V8JS_NULL;
  863. }
  864. /* Special case, passing back object originating from JS to JS */
  865. if (ce == php_ce_v8function || ce == php_ce_v8object || ce == php_ce_v8generator) {
  866. v8js_v8object *c = Z_V8JS_V8OBJECT_OBJ_P(value);
  867. if(isolate != c->ctx->isolate) {
  868. php_error_docref(NULL, E_WARNING, "V8Function object passed to wrong V8Js instance");
  869. return V8JS_NULL;
  870. }
  871. return v8::Local<v8::Value>::New(isolate, c->v8obj);
  872. }
  873. /* If it's a PHP object, wrap it */
  874. if (ce) {
  875. v8::MaybeLocal<v8::Object> wrapped_object = v8js_wrap_object(isolate, ce, value);
  876. if (wrapped_object.IsEmpty()) {
  877. return V8JS_UNDEFINED;
  878. }
  879. if (ce == zend_ce_generator) {
  880. /* Wrap PHP Generator object in a wrapper function that provides
  881. * ES6 style behaviour. */
  882. return v8js_wrap_generator(isolate, wrapped_object.ToLocalChecked());
  883. }
  884. return wrapped_object.ToLocalChecked();
  885. }
  886. /* Associative PHP arrays cannot be wrapped to JS arrays, convert them to
  887. * JS objects and attach all their array keys as properties. */
  888. return v8js_wrap_array_to_object(isolate, value);
  889. }
  890. /* }}} */
  891. /*
  892. * Local variables:
  893. * tab-width: 4
  894. * c-basic-offset: 4
  895. * indent-tabs-mode: t
  896. * End:
  897. * vim600: noet sw=4 ts=4 fdm=marker
  898. * vim<600: noet sw=4 ts=4
  899. */