-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathdart_api_impl.cc
6977 lines (6357 loc) · 243 KB
/
dart_api_impl.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
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "include/dart_api.h"
#include "include/dart_native_api.h"
#include <cstring>
#include <memory>
#include <utility>
#include "lib/stacktrace.h"
#include "platform/assert.h"
#include "platform/unicode.h"
#include "vm/app_snapshot.h"
#include "vm/class_finalizer.h"
#include "vm/compiler/jit/compiler.h"
#include "vm/dart.h"
#include "vm/dart_api_impl.h"
#include "vm/dart_api_message.h"
#include "vm/dart_api_state.h"
#include "vm/dart_entry.h"
#include "vm/debugger.h"
#include "vm/dwarf.h"
#include "vm/elf.h"
#include "vm/exceptions.h"
#include "vm/flags.h"
#include "vm/growable_array.h"
#include "vm/heap/verifier.h"
#include "vm/image_snapshot.h"
#include "vm/isolate_reload.h"
#include "vm/kernel_isolate.h"
#include "vm/lockers.h"
#include "vm/message.h"
#include "vm/message_handler.h"
#include "vm/message_snapshot.h"
#include "vm/native_entry.h"
#include "vm/native_symbol.h"
#include "vm/object.h"
#include "vm/object_graph.h"
#include "vm/object_store.h"
#include "vm/os.h"
#include "vm/os_thread.h"
#include "vm/port.h"
#include "vm/profiler.h"
#include "vm/profiler_service.h"
#include "vm/program_visitor.h"
#include "vm/resolver.h"
#include "vm/reusable_handles.h"
#include "vm/service.h"
#include "vm/service_event.h"
#include "vm/service_isolate.h"
#include "vm/stack_frame.h"
#include "vm/symbols.h"
#include "vm/tags.h"
#include "vm/version.h"
#include "vm/zone_text_buffer.h"
#if !defined(DART_PRECOMPILED_RUNTIME)
#include "vm/compiler/aot/precompiler.h"
#include "vm/kernel_loader.h"
#endif // !defined(DART_PRECOMPILED_RUNTIME)
namespace dart {
// Facilitate quick access to the current zone once we have the current thread.
#define Z (T->zone())
DECLARE_FLAG(bool, print_class_table);
#if defined(DEBUG) && !defined(DART_PRECOMPILED_RUNTIME)
DEFINE_FLAG(bool,
check_function_fingerprints,
true,
"Check function fingerprints");
#endif // defined(DEBUG) && !defined(DART_PRECOMPILED_RUNTIME).
DEFINE_FLAG(bool,
verify_acquired_data,
false,
"Verify correct API acquire/release of typed data.");
DEFINE_FLAG(bool,
dump_tables,
false,
"Dump common hash tables before snapshotting.");
DEFINE_FLAG(bool,
enable_deprecated_wait_for,
false,
"Enable deprecated dart:cli waitFor. "
"This feature will be fully removed in Dart 3.4 release. "
"See https://dartbug.com/52121.");
#define CHECK_ERROR_HANDLE(error) \
{ \
ErrorPtr err = (error); \
if (err != Error::null()) { \
return Api::NewHandle(T, err); \
} \
}
ThreadLocalKey Api::api_native_key_ = kUnsetThreadLocalKey;
Dart_Handle Api::true_handle_ = nullptr;
Dart_Handle Api::false_handle_ = nullptr;
Dart_Handle Api::null_handle_ = nullptr;
Dart_Handle Api::empty_string_handle_ = nullptr;
Dart_Handle Api::no_callbacks_error_handle_ = nullptr;
Dart_Handle Api::unwind_in_progress_error_handle_ = nullptr;
const char* CanonicalFunction(const char* func) {
if (strncmp(func, "dart::", 6) == 0) {
return func + 6;
} else {
return func;
}
}
#if defined(DEBUG)
// An object visitor which will iterate over all the function objects in the
// heap and check if the result type and parameter types are canonicalized
// or not. An assertion is raised if a type is not canonicalized.
class CheckFunctionTypesVisitor : public ObjectVisitor {
public:
explicit CheckFunctionTypesVisitor(Thread* thread)
: classHandle_(Class::Handle(thread->zone())),
funcHandle_(Function::Handle(thread->zone())),
typeHandle_(AbstractType::Handle(thread->zone())) {}
void VisitObject(ObjectPtr obj) override {
if (obj->IsFunction()) {
funcHandle_ ^= obj;
classHandle_ ^= funcHandle_.Owner();
// Verify that the result type of a function is canonical or a
// TypeParameter.
typeHandle_ ^= funcHandle_.result_type();
ASSERT(typeHandle_.IsTypeParameter() || typeHandle_.IsCanonical());
// Verify that the types in the function signature are all canonical or
// a TypeParameter.
const intptr_t num_parameters = funcHandle_.NumParameters();
for (intptr_t i = 0; i < num_parameters; i++) {
typeHandle_ = funcHandle_.ParameterTypeAt(i);
ASSERT(typeHandle_.IsTypeParameter() || typeHandle_.IsCanonical());
}
}
}
private:
Class& classHandle_;
Function& funcHandle_;
AbstractType& typeHandle_;
};
#endif // #if defined(DEBUG).
static InstancePtr GetListInstance(Zone* zone, const Object& obj) {
if (obj.IsInstance()) {
ObjectStore* object_store = IsolateGroup::Current()->object_store();
const Type& list_rare_type =
Type::Handle(zone, object_store->non_nullable_list_rare_type());
ASSERT(!list_rare_type.IsNull());
const Instance& instance = Instance::Cast(obj);
const Class& obj_class = Class::Handle(zone, obj.clazz());
if (Class::IsSubtypeOf(obj_class, Object::null_type_arguments(),
Nullability::kNonNullable, list_rare_type,
Heap::kNew)) {
return instance.ptr();
}
}
return Instance::null();
}
static InstancePtr GetMapInstance(Zone* zone, const Object& obj) {
if (obj.IsInstance()) {
ObjectStore* object_store = IsolateGroup::Current()->object_store();
const Type& map_rare_type =
Type::Handle(zone, object_store->non_nullable_map_rare_type());
ASSERT(!map_rare_type.IsNull());
const Instance& instance = Instance::Cast(obj);
const Class& obj_class = Class::Handle(zone, obj.clazz());
if (Class::IsSubtypeOf(obj_class, Object::null_type_arguments(),
Nullability::kNonNullable, map_rare_type,
Heap::kNew)) {
return instance.ptr();
}
}
return Instance::null();
}
static bool IsCompiletimeErrorObject(Zone* zone, const Object& obj) {
#if defined(DART_PRECOMPILED_RUNTIME)
// All compile-time errors were handled at snapshot generation time and
// compiletime_error_class was removed.
return false;
#else
auto isolate_group = Thread::Current()->isolate_group();
const Class& error_class = Class::Handle(
zone, isolate_group->object_store()->compiletime_error_class());
ASSERT(!error_class.IsNull());
return (obj.GetClassId() == error_class.id());
#endif
}
static bool GetNativeStringArgument(NativeArguments* arguments,
int arg_index,
Dart_Handle* str,
void** peer) {
ASSERT(peer != nullptr);
if (Api::StringGetPeerHelper(arguments, arg_index, peer)) {
*str = nullptr;
return true;
}
Thread* thread = arguments->thread();
ASSERT(thread == Thread::Current());
*peer = nullptr;
REUSABLE_OBJECT_HANDLESCOPE(thread);
Object& obj = thread->ObjectHandle();
obj = arguments->NativeArgAt(arg_index);
if (IsStringClassId(obj.GetClassId())) {
ASSERT(thread->api_top_scope() != nullptr);
*str = Api::NewHandle(thread, obj.ptr());
return true;
}
if (obj.IsNull()) {
*str = Api::Null();
return true;
}
return false;
}
static bool GetNativeIntegerArgument(NativeArguments* arguments,
int arg_index,
int64_t* value) {
ASSERT(value != nullptr);
return Api::GetNativeIntegerArgument(arguments, arg_index, value);
}
static bool GetNativeUnsignedIntegerArgument(NativeArguments* arguments,
int arg_index,
uint64_t* value) {
ASSERT(value != nullptr);
int64_t arg_value = 0;
if (Api::GetNativeIntegerArgument(arguments, arg_index, &arg_value)) {
*value = static_cast<uint64_t>(arg_value);
return true;
}
return false;
}
static bool GetNativeDoubleArgument(NativeArguments* arguments,
int arg_index,
double* value) {
ASSERT(value != nullptr);
return Api::GetNativeDoubleArgument(arguments, arg_index, value);
}
static Dart_Handle GetNativeFieldsOfArgument(NativeArguments* arguments,
int arg_index,
int num_fields,
intptr_t* field_values,
const char* current_func) {
ASSERT(field_values != nullptr);
if (Api::GetNativeFieldsOfArgument(arguments, arg_index, num_fields,
field_values)) {
return Api::Success();
}
Thread* thread = arguments->thread();
ASSERT(thread == Thread::Current());
REUSABLE_OBJECT_HANDLESCOPE(thread);
Object& obj = thread->ObjectHandle();
obj = arguments->NativeArgAt(arg_index);
if (obj.IsNull()) {
memset(field_values, 0, (num_fields * sizeof(field_values[0])));
return Api::Success();
}
// We did not succeed in extracting the native fields report the
// appropriate error.
if (!obj.IsInstance()) {
return Api::NewError(
"%s expects argument at index '%d' to be of"
" type Instance.",
current_func, arg_index);
}
const Instance& instance = Instance::Cast(obj);
int field_count = instance.NumNativeFields();
ASSERT(num_fields != field_count);
return Api::NewError("%s: expected %d 'num_fields' but was passed in %d.",
current_func, field_count, num_fields);
}
static FunctionPtr FindCoreLibPrivateFunction(Zone* zone, const String& name) {
const Library& core_lib = Library::Handle(zone, Library::CoreLibrary());
ASSERT(!core_lib.IsNull());
const Function& function =
Function::Handle(zone, core_lib.LookupFunctionAllowPrivate(name));
ASSERT(!function.IsNull());
return function.ptr();
}
static ObjectPtr CallStatic1Arg(Zone* zone,
const String& name,
const Instance& arg0) {
const intptr_t kNumArgs = 1;
const Function& function =
Function::Handle(zone, FindCoreLibPrivateFunction(zone, name));
const Array& args = Array::Handle(zone, Array::New(kNumArgs));
args.SetAt(0, arg0);
return DartEntry::InvokeFunction(function, args);
}
static ObjectPtr CallStatic2Args(Zone* zone,
const String& name,
const Instance& arg0,
const Instance& arg1) {
const intptr_t kNumArgs = 2;
const Function& function =
Function::Handle(zone, FindCoreLibPrivateFunction(zone, name));
const Array& args = Array::Handle(zone, Array::New(kNumArgs));
args.SetAt(0, arg0);
args.SetAt(1, arg1);
return DartEntry::InvokeFunction(function, args);
}
static ObjectPtr CallStatic3Args(Zone* zone,
const String& name,
const Instance& arg0,
const Instance& arg1,
const Instance& arg2) {
const intptr_t kNumArgs = 3;
const Function& function =
Function::Handle(zone, FindCoreLibPrivateFunction(zone, name));
const Array& args = Array::Handle(Array::New(kNumArgs));
args.SetAt(0, arg0);
args.SetAt(1, arg1);
args.SetAt(2, arg2);
return DartEntry::InvokeFunction(function, args);
}
static const char* GetErrorString(Thread* thread, const Object& obj) {
// This function requires an API scope to be present.
if (obj.IsError()) {
ASSERT(thread->api_top_scope() != nullptr);
const Error& error = Error::Cast(obj);
const char* str = error.ToErrorCString();
intptr_t len = strlen(str) + 1;
char* str_copy = Api::TopScope(thread)->zone()->Alloc<char>(len);
strncpy(str_copy, str, len);
// Strip a possible trailing '\n'.
if ((len > 1) && (str_copy[len - 2] == '\n')) {
str_copy[len - 2] = '\0';
}
return str_copy;
} else {
return "";
}
}
Dart_Handle Api::InitNewHandle(Thread* thread, ObjectPtr raw) {
LocalHandles* local_handles = Api::TopScope(thread)->local_handles();
ASSERT(local_handles != nullptr);
LocalHandle* ref = local_handles->AllocateHandle();
ref->set_ptr(raw);
return ref->apiHandle();
}
Dart_Handle Api::NewHandle(Thread* thread, ObjectPtr raw) {
if (raw == Object::null()) {
return Null();
}
if (raw == Bool::True().ptr()) {
return True();
}
if (raw == Bool::False().ptr()) {
return False();
}
ASSERT(thread->execution_state() == Thread::kThreadInVM);
return InitNewHandle(thread, raw);
}
ObjectPtr Api::UnwrapHandle(Dart_Handle object) {
#if defined(DEBUG)
Thread* thread = Thread::Current();
ASSERT(thread->execution_state() == Thread::kThreadInVM);
ASSERT(thread->IsDartMutatorThread());
ASSERT(thread->isolate() != nullptr);
ASSERT(FinalizablePersistentHandle::ptr_offset() == 0 &&
PersistentHandle::ptr_offset() == 0 && LocalHandle::ptr_offset() == 0);
#endif
return (reinterpret_cast<LocalHandle*>(object))->ptr();
}
#define DEFINE_UNWRAP(type) \
const type& Api::Unwrap##type##Handle(Zone* zone, Dart_Handle dart_handle) { \
const Object& obj = Object::Handle(zone, Api::UnwrapHandle(dart_handle)); \
if (obj.Is##type()) { \
return type::Cast(obj); \
} \
return type::Handle(zone); \
}
CLASS_LIST_FOR_HANDLES(DEFINE_UNWRAP)
#undef DEFINE_UNWRAP
const String& Api::UnwrapStringHandle(const ReusableObjectHandleScope& reuse,
Dart_Handle dart_handle) {
Object& ref = reuse.Handle();
ref = Api::UnwrapHandle(dart_handle);
if (ref.IsString()) {
return String::Cast(ref);
}
return Object::null_string();
}
const Instance& Api::UnwrapInstanceHandle(
const ReusableObjectHandleScope& reuse,
Dart_Handle dart_handle) {
Object& ref = reuse.Handle();
ref = Api::UnwrapHandle(dart_handle);
if (ref.IsInstance()) {
return Instance::Cast(ref);
}
return Object::null_instance();
}
Dart_Handle Api::CheckAndFinalizePendingClasses(Thread* thread) {
Isolate* isolate = thread->isolate();
if (!isolate->AllowClassFinalization()) {
// Class finalization is blocked for the isolate. Do nothing.
return Api::Success();
}
if (ClassFinalizer::ProcessPendingClasses()) {
return Api::Success();
}
ASSERT(thread->sticky_error() != Object::null());
return Api::NewHandle(thread, thread->sticky_error());
}
Dart_Isolate Api::CastIsolate(Isolate* isolate) {
return reinterpret_cast<Dart_Isolate>(isolate);
}
Dart_IsolateGroup Api::CastIsolateGroup(IsolateGroup* isolate_group) {
return reinterpret_cast<Dart_IsolateGroup>(isolate_group);
}
Dart_Handle Api::NewError(const char* format, ...) {
Thread* T = Thread::Current();
CHECK_API_SCOPE(T);
CHECK_CALLBACK_STATE(T);
// Ensure we transition safepoint state to VM if we are not already in
// that state.
TransitionToVM transition(T);
HANDLESCOPE(T);
va_list args;
va_start(args, format);
char* buffer = OS::VSCreate(Z, format, args);
va_end(args);
const String& message = String::Handle(Z, String::New(buffer));
return Api::NewHandle(T, ApiError::New(message));
}
Dart_Handle Api::NewArgumentError(const char* format, ...) {
Thread* T = Thread::Current();
CHECK_API_SCOPE(T);
CHECK_CALLBACK_STATE(T);
// Ensure we transition safepoint state to VM if we are not already in
// that state.
TransitionToVM transition(T);
HANDLESCOPE(T);
va_list args;
va_start(args, format);
char* buffer = OS::VSCreate(Z, format, args);
va_end(args);
const String& message = String::Handle(Z, String::New(buffer));
const Array& arguments = Array::Handle(Z, Array::New(1));
arguments.SetAt(0, message);
Object& error = Object::Handle(
Z, DartLibraryCalls::InstanceCreate(
Library::Handle(Z, Library::CoreLibrary()),
Symbols::ArgumentError(), Symbols::Dot(), arguments));
if (!error.IsError()) {
error = UnhandledException::New(Instance::Cast(error), Instance::Handle());
}
return Api::NewHandle(T, error.ptr());
}
bool Api::IsValid(Dart_Handle handle) {
Isolate* isolate = Isolate::Current();
Thread* thread = Thread::Current();
ASSERT(thread->IsDartMutatorThread());
CHECK_ISOLATE(isolate);
// Check against all of the handles in the current isolate as well as the
// read-only handles.
return thread->IsValidHandle(handle) ||
isolate->group()->api_state()->IsActivePersistentHandle(
reinterpret_cast<Dart_PersistentHandle>(handle)) ||
isolate->group()->api_state()->IsActiveWeakPersistentHandle(
reinterpret_cast<Dart_WeakPersistentHandle>(handle)) ||
Dart::IsReadOnlyApiHandle(handle) ||
Dart::IsReadOnlyHandle(reinterpret_cast<uword>(handle));
}
ApiLocalScope* Api::TopScope(Thread* thread) {
ASSERT(thread != nullptr);
ApiLocalScope* scope = thread->api_top_scope();
ASSERT(scope != nullptr);
return scope;
}
void Api::Init() {
if (api_native_key_ == kUnsetThreadLocalKey) {
api_native_key_ = OSThread::CreateThreadLocal();
}
ASSERT(api_native_key_ != kUnsetThreadLocalKey);
}
static Dart_Handle InitNewReadOnlyApiHandle(ObjectPtr raw) {
ASSERT(raw->untag()->InVMIsolateHeap());
LocalHandle* ref = Dart::AllocateReadOnlyApiHandle();
ref->set_ptr(raw);
return ref->apiHandle();
}
void Api::InitHandles() {
Isolate* isolate = Isolate::Current();
ASSERT(isolate != nullptr);
ASSERT(isolate == Dart::vm_isolate());
ApiState* state = isolate->group()->api_state();
ASSERT(state != nullptr);
ASSERT(true_handle_ == nullptr);
true_handle_ = InitNewReadOnlyApiHandle(Bool::True().ptr());
ASSERT(false_handle_ == nullptr);
false_handle_ = InitNewReadOnlyApiHandle(Bool::False().ptr());
ASSERT(null_handle_ == nullptr);
null_handle_ = InitNewReadOnlyApiHandle(Object::null());
ASSERT(empty_string_handle_ == nullptr);
empty_string_handle_ = InitNewReadOnlyApiHandle(Symbols::Empty().ptr());
ASSERT(no_callbacks_error_handle_ == nullptr);
no_callbacks_error_handle_ =
InitNewReadOnlyApiHandle(Object::no_callbacks_error().ptr());
ASSERT(unwind_in_progress_error_handle_ == nullptr);
unwind_in_progress_error_handle_ =
InitNewReadOnlyApiHandle(Object::unwind_in_progress_error().ptr());
}
void Api::Cleanup() {
true_handle_ = nullptr;
false_handle_ = nullptr;
null_handle_ = nullptr;
empty_string_handle_ = nullptr;
no_callbacks_error_handle_ = nullptr;
unwind_in_progress_error_handle_ = nullptr;
}
bool Api::StringGetPeerHelper(NativeArguments* arguments,
int arg_index,
void** peer) {
NoSafepointScope no_safepoint_scope;
ObjectPtr raw_obj = arguments->NativeArgAt(arg_index);
intptr_t cid = raw_obj->GetClassId();
if (cid == kOneByteStringCid || cid == kTwoByteStringCid) {
auto isolate_group = arguments->thread()->isolate_group();
*peer = isolate_group->heap()->GetPeer(raw_obj);
return (*peer != nullptr);
}
return false;
}
bool Api::GetNativeReceiver(NativeArguments* arguments, intptr_t* value) {
NoSafepointScope no_safepoint_scope;
ObjectPtr raw_obj = arguments->NativeArg0();
intptr_t cid = raw_obj->GetClassId();
if (cid >= kNumPredefinedCids) {
ASSERT(Instance::Cast(Object::Handle(raw_obj)).IsValidNativeIndex(0));
TypedDataPtr native_fields =
reinterpret_cast<CompressedTypedDataPtr*>(
UntaggedObject::ToAddr(raw_obj) + sizeof(UntaggedObject))
->Decompress(raw_obj->heap_base());
if (native_fields == TypedData::null()) {
*value = 0;
} else {
*value = *bit_cast<intptr_t*, uint8_t*>(native_fields->untag()->data());
}
return true;
}
return false;
}
bool Api::GetNativeBooleanArgument(NativeArguments* arguments,
int arg_index,
bool* value) {
NoSafepointScope no_safepoint_scope;
ObjectPtr raw_obj = arguments->NativeArgAt(arg_index);
intptr_t cid = raw_obj->GetClassId();
if (cid == kBoolCid) {
*value = (raw_obj == Object::bool_true().ptr());
return true;
}
if (cid == kNullCid) {
*value = false;
return true;
}
return false;
}
bool Api::GetNativeIntegerArgument(NativeArguments* arguments,
int arg_index,
int64_t* value) {
NoSafepointScope no_safepoint_scope;
ObjectPtr raw_obj = arguments->NativeArgAt(arg_index);
intptr_t cid = raw_obj->GetClassId();
if (cid == kSmiCid) {
*value = Smi::Value(static_cast<SmiPtr>(raw_obj));
return true;
}
if (cid == kMintCid) {
*value = static_cast<MintPtr>(raw_obj)->untag()->value_;
return true;
}
return false;
}
bool Api::GetNativeDoubleArgument(NativeArguments* arguments,
int arg_index,
double* value) {
NoSafepointScope no_safepoint_scope;
ObjectPtr raw_obj = arguments->NativeArgAt(arg_index);
intptr_t cid = raw_obj->GetClassId();
if (cid == kDoubleCid) {
*value = static_cast<DoublePtr>(raw_obj)->untag()->value_;
return true;
}
if (cid == kSmiCid) {
*value = static_cast<double>(Smi::Value(static_cast<SmiPtr>(raw_obj)));
return true;
}
if (cid == kMintCid) {
*value =
static_cast<double>(static_cast<MintPtr>(raw_obj)->untag()->value_);
return true;
}
return false;
}
bool Api::GetNativeFieldsOfArgument(NativeArguments* arguments,
int arg_index,
int num_fields,
intptr_t* field_values) {
NoSafepointScope no_safepoint_scope;
ObjectPtr raw_obj = arguments->NativeArgAt(arg_index);
intptr_t cid = raw_obj->GetClassId();
int class_num_fields = arguments->thread()
->isolate_group()
->class_table()
->At(cid)
->untag()
->num_native_fields_;
if (num_fields != class_num_fields) {
// No native fields or mismatched native field count.
return false;
}
TypedDataPtr native_fields =
reinterpret_cast<CompressedTypedDataPtr*>(
UntaggedObject::ToAddr(raw_obj) + sizeof(UntaggedObject))
->Decompress(raw_obj->heap_base());
if (native_fields == TypedData::null()) {
// Native fields not initialized.
memset(field_values, 0, (num_fields * sizeof(field_values[0])));
return true;
}
ASSERT(class_num_fields == Smi::Value(native_fields->untag()->length()));
intptr_t* native_values =
reinterpret_cast<intptr_t*>(native_fields->untag()->data());
memmove(field_values, native_values, (num_fields * sizeof(field_values[0])));
return true;
}
void Api::SetWeakHandleReturnValue(NativeArguments* args,
Dart_WeakPersistentHandle retval) {
args->SetReturnUnsafe(FinalizablePersistentHandle::Cast(retval)->ptr());
}
PersistentHandle* PersistentHandle::Cast(Dart_PersistentHandle handle) {
ASSERT(IsolateGroup::Current()->api_state()->IsValidPersistentHandle(handle));
return reinterpret_cast<PersistentHandle*>(handle);
}
FinalizablePersistentHandle* FinalizablePersistentHandle::Cast(
Dart_WeakPersistentHandle handle) {
#if defined(DEBUG)
ApiState* state = IsolateGroup::Current()->api_state();
ASSERT(state->IsValidWeakPersistentHandle(handle));
#endif
return reinterpret_cast<FinalizablePersistentHandle*>(handle);
}
FinalizablePersistentHandle* FinalizablePersistentHandle::Cast(
Dart_FinalizableHandle handle) {
#if defined(DEBUG)
ApiState* state = IsolateGroup::Current()->api_state();
ASSERT(state->IsValidFinalizableHandle(handle));
#endif
return reinterpret_cast<FinalizablePersistentHandle*>(handle);
}
void FinalizablePersistentHandle::Finalize(
IsolateGroup* isolate_group,
FinalizablePersistentHandle* handle) {
if (!handle->ptr()->IsHeapObject()) {
return; // Free handle.
}
Dart_HandleFinalizer callback = handle->callback();
ASSERT(callback != nullptr);
void* peer = handle->peer();
ApiState* state = isolate_group->api_state();
ASSERT(state != nullptr);
if (!handle->auto_delete()) {
// Clear handle before running finalizer, finalizer can free the handle.
state->ClearWeakPersistentHandle(handle);
}
(*callback)(isolate_group->embedder_data(), peer);
if (handle->auto_delete()) {
state->FreeWeakPersistentHandle(handle);
}
}
// --- Handles ---
DART_EXPORT bool Dart_IsError(Dart_Handle handle) {
Thread* thread = Thread::Current();
TransitionNativeToVM transition(thread);
return Api::IsError(handle);
}
DART_EXPORT void Dart_KillIsolate(Dart_Isolate handle) {
Isolate* isolate = reinterpret_cast<Isolate*>(handle);
CHECK_ISOLATE(isolate);
Isolate::KillIfExists(isolate, Isolate::kKillMsg);
}
DART_EXPORT bool Dart_IsApiError(Dart_Handle object) {
Thread* thread = Thread::Current();
TransitionNativeToVM transition(thread);
return Api::ClassId(object) == kApiErrorCid;
}
DART_EXPORT bool Dart_IsUnhandledExceptionError(Dart_Handle object) {
Thread* thread = Thread::Current();
TransitionNativeToVM transition(thread);
return Api::ClassId(object) == kUnhandledExceptionCid;
}
DART_EXPORT bool Dart_IsCompilationError(Dart_Handle object) {
if (::Dart_IsUnhandledExceptionError(object)) {
DARTSCOPE(Thread::Current());
const UnhandledException& error =
UnhandledException::Cast(Object::Handle(Z, Api::UnwrapHandle(object)));
const Instance& exc = Instance::Handle(Z, error.exception());
return IsCompiletimeErrorObject(Z, exc);
}
Thread* thread = Thread::Current();
TransitionNativeToVM transition(thread);
return Api::ClassId(object) == kLanguageErrorCid;
}
DART_EXPORT bool Dart_IsFatalError(Dart_Handle object) {
Thread* thread = Thread::Current();
TransitionNativeToVM transition(thread);
return Api::ClassId(object) == kUnwindErrorCid;
}
DART_EXPORT const char* Dart_GetError(Dart_Handle handle) {
DARTSCOPE(Thread::Current());
API_TIMELINE_DURATION(T);
const Object& obj = Object::Handle(Z, Api::UnwrapHandle(handle));
return GetErrorString(T, obj);
}
DART_EXPORT bool Dart_ErrorHasException(Dart_Handle handle) {
DARTSCOPE(Thread::Current());
const Object& obj = Object::Handle(Z, Api::UnwrapHandle(handle));
return obj.IsUnhandledException();
}
DART_EXPORT Dart_Handle Dart_ErrorGetException(Dart_Handle handle) {
DARTSCOPE(Thread::Current());
const Object& obj = Object::Handle(Z, Api::UnwrapHandle(handle));
if (obj.IsUnhandledException()) {
const UnhandledException& error = UnhandledException::Cast(obj);
return Api::NewHandle(T, error.exception());
} else if (obj.IsError()) {
return Api::NewError("This error is not an unhandled exception error.");
} else {
return Api::NewError("Can only get exceptions from error handles.");
}
}
DART_EXPORT Dart_Handle Dart_ErrorGetStackTrace(Dart_Handle handle) {
DARTSCOPE(Thread::Current());
const Object& obj = Object::Handle(Z, Api::UnwrapHandle(handle));
if (obj.IsUnhandledException()) {
const UnhandledException& error = UnhandledException::Cast(obj);
return Api::NewHandle(T, error.stacktrace());
} else if (obj.IsError()) {
return Api::NewError("This error is not an unhandled exception error.");
} else {
return Api::NewError("Can only get stacktraces from error handles.");
}
}
DART_EXPORT Dart_Handle Dart_NewApiError(const char* error) {
DARTSCOPE(Thread::Current());
CHECK_CALLBACK_STATE(T);
const String& message = String::Handle(Z, String::New(error));
return Api::NewHandle(T, ApiError::New(message));
}
DART_EXPORT Dart_Handle Dart_NewCompilationError(const char* error) {
DARTSCOPE(Thread::Current());
CHECK_CALLBACK_STATE(T);
const String& message = String::Handle(Z, String::New(error));
return Api::NewHandle(T, LanguageError::New(message));
}
DART_EXPORT Dart_Handle Dart_NewUnhandledExceptionError(Dart_Handle exception) {
DARTSCOPE(Thread::Current());
CHECK_CALLBACK_STATE(T);
Instance& obj = Instance::Handle(Z);
intptr_t class_id = Api::ClassId(exception);
if ((class_id == kApiErrorCid) || (class_id == kLanguageErrorCid)) {
const Object& excp = Object::Handle(Z, Api::UnwrapHandle(exception));
obj = String::New(GetErrorString(T, excp));
} else {
obj = Api::UnwrapInstanceHandle(Z, exception).ptr();
if (obj.IsNull()) {
RETURN_TYPE_ERROR(Z, exception, Instance);
}
}
const StackTrace& stacktrace = StackTrace::Handle(Z);
return Api::NewHandle(T, UnhandledException::New(obj, stacktrace));
}
DART_EXPORT void Dart_PropagateError(Dart_Handle handle) {
Thread* thread = Thread::Current();
CHECK_ISOLATE(thread->isolate());
TransitionNativeToVM transition(thread);
const Object& obj = Object::Handle(thread->zone(), Api::UnwrapHandle(handle));
if (!obj.IsError()) {
FATAL(
"%s expects argument 'handle' to be an error handle. "
"Did you forget to check Dart_IsError first?",
CURRENT_FUNC);
}
if (thread->top_exit_frame_info() == 0) {
// There are no dart frames on the stack so it would be illegal to
// propagate an error here.
FATAL("No Dart frames on stack, cannot propagate error.");
}
// Unwind all the API scopes till the exit frame before propagating.
const Error* error;
{
// We need to preserve the error object across the destruction of zones
// when the ApiScopes are unwound. By using NoSafepointScope, we can ensure
// that GC won't touch the raw error object before creating a valid
// handle for it in the surviving zone.
NoSafepointScope no_safepoint;
ErrorPtr raw_error = Api::UnwrapErrorHandle(thread->zone(), handle).ptr();
thread->UnwindScopes(thread->top_exit_frame_info());
// Note that thread's zone is different here than at the beginning of this
// function.
error = &Error::Handle(thread->zone(), raw_error);
}
Exceptions::PropagateError(*error);
UNREACHABLE();
}
DART_EXPORT Dart_Handle Dart_ToString(Dart_Handle object) {
DARTSCOPE(Thread::Current());
const Object& obj = Object::Handle(Z, Api::UnwrapHandle(object));
if (obj.IsString()) {
return Api::NewHandle(T, obj.ptr());
} else if (obj.IsInstance()) {
CHECK_CALLBACK_STATE(T);
const Instance& receiver = Instance::Cast(obj);
return Api::NewHandle(T, DartLibraryCalls::ToString(receiver));
} else {
CHECK_CALLBACK_STATE(T);
// This is a VM internal object. Call the C++ method of printing.
return Api::NewHandle(T, String::New(obj.ToCString()));
}
}
DART_EXPORT bool Dart_IdentityEquals(Dart_Handle obj1, Dart_Handle obj2) {
DARTSCOPE(Thread::Current());
{
NoSafepointScope no_safepoint_scope;
if (Api::UnwrapHandle(obj1) == Api::UnwrapHandle(obj2)) {
return true;
}
}
const Object& object1 = Object::Handle(Z, Api::UnwrapHandle(obj1));
const Object& object2 = Object::Handle(Z, Api::UnwrapHandle(obj2));
if (object1.IsInstance() && object2.IsInstance()) {
return Instance::Cast(object1).IsIdenticalTo(Instance::Cast(object2));
}
return false;
}
DART_EXPORT Dart_Handle
Dart_HandleFromPersistent(Dart_PersistentHandle object) {
Thread* thread = Thread::Current();
Isolate* isolate = thread->isolate();
CHECK_ISOLATE(isolate);
ApiState* state = isolate->group()->api_state();
ASSERT(state != nullptr);
TransitionNativeToVM transition(thread);
NoSafepointScope no_safepoint_scope;
PersistentHandle* ref = PersistentHandle::Cast(object);
return Api::NewHandle(thread, ref->ptr());
}
DART_EXPORT Dart_Handle
Dart_HandleFromWeakPersistent(Dart_WeakPersistentHandle object) {
Thread* thread = Thread::Current();
Isolate* isolate = thread->isolate();
CHECK_ISOLATE(isolate);
ApiState* state = isolate->group()->api_state();
ASSERT(state != nullptr);
TransitionNativeToVM transition(thread);
NoSafepointScope no_safepoint_scope;
FinalizablePersistentHandle* weak_ref =
FinalizablePersistentHandle::Cast(object);
if (weak_ref->IsFinalizedNotFreed()) {
return Dart_Null();
}
return Api::NewHandle(thread, weak_ref->ptr());
}
static Dart_Handle HandleFromFinalizable(Dart_FinalizableHandle object) {
Thread* thread = Thread::Current();
Isolate* isolate = thread->isolate();
CHECK_ISOLATE(isolate);
ApiState* state = isolate->group()->api_state();
ASSERT(state != nullptr);
TransitionNativeToVM transition(thread);
NoSafepointScope no_safepoint_scope;
FinalizablePersistentHandle* weak_ref =
FinalizablePersistentHandle::Cast(object);
return Api::NewHandle(thread, weak_ref->ptr());
}
DART_EXPORT Dart_PersistentHandle Dart_NewPersistentHandle(Dart_Handle object) {
DARTSCOPE(Thread::Current());
Isolate* I = T->isolate();
ApiState* state = I->group()->api_state();
ASSERT(state != nullptr);
const Object& old_ref = Object::Handle(Z, Api::UnwrapHandle(object));
PersistentHandle* new_ref = state->AllocatePersistentHandle();
new_ref->set_ptr(old_ref);
return new_ref->apiHandle();
}
DART_EXPORT void Dart_SetPersistentHandle(Dart_PersistentHandle obj1,
Dart_Handle obj2) {
DARTSCOPE(Thread::Current());
Isolate* I = T->isolate();
ApiState* state = I->group()->api_state();
ASSERT(state != nullptr);
ASSERT(state->IsValidPersistentHandle(obj1));
const Object& obj2_ref = Object::Handle(Z, Api::UnwrapHandle(obj2));
PersistentHandle* obj1_ref = PersistentHandle::Cast(obj1);
obj1_ref->set_ptr(obj2_ref);
}
static bool IsFfiCompound(Thread* T, const Object& obj) {
if (obj.IsNull()) {
return false;
}
// CFE guarantees we can only have direct subclasses of `Struct` and `Union`
// (no implementations or indirect subclasses are allowed).
const auto& klass = Class::Handle(Z, obj.clazz());
const auto& super_klass = Class::Handle(Z, klass.SuperClass());
if (super_klass.IsNull()) {
// This means klass is Object.
return false;
}
if (super_klass.Name() != Symbols::Struct().ptr() &&
super_klass.Name() != Symbols::Union().ptr()) {