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