v8js_object_export.cc 34 KB

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