v8js_object_export.cc 35 KB

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