1 /**
2 * Copyright (c) 2022-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "plugins/ets/runtime/ets_coroutine.h"
17 #include "runtime/include/object_header.h"
18 #include "plugins/ets/runtime/types/ets_promise.h"
19 #include "plugins/ets/runtime/ets_vm.h"
20 #include "runtime/include/panda_vm.h"
21 #include "plugins/ets/runtime/ets_class_linker_extension.h"
22 #include "plugins/ets/runtime/types/ets_object.h"
23 #include "plugins/ets/runtime/types/ets_box_primitive-inl.h"
24 #include "intrinsics.h"
25
26 namespace ark::ets {
27
EtsCoroutine(ThreadId id,mem::InternalAllocatorPtr allocator,PandaVM * vm,PandaString name,CoroutineContext * context,CallbackQueue * queue,std::optional<EntrypointInfo> && epInfo)28 EtsCoroutine::EtsCoroutine(ThreadId id, mem::InternalAllocatorPtr allocator, PandaVM *vm, PandaString name,
29 CoroutineContext *context, CallbackQueue *queue, std::optional<EntrypointInfo> &&epInfo)
30 : Coroutine(id, allocator, vm, ark::panda_file::SourceLang::ETS, std::move(name), context, queue, std::move(epInfo))
31 {
32 ASSERT(vm != nullptr);
33 }
34
GetPandaVM() const35 PandaEtsVM *EtsCoroutine::GetPandaVM() const
36 {
37 return static_cast<PandaEtsVM *>(GetVM());
38 }
39
GetCoroutineManager() const40 CoroutineManager *EtsCoroutine::GetCoroutineManager() const
41 {
42 return GetPandaVM()->GetCoroutineManager();
43 }
44
Initialize()45 void EtsCoroutine::Initialize()
46 {
47 auto allocator = GetVM()->GetHeapManager()->GetInternalAllocator();
48 auto etsNapiEnv = PandaEtsNapiEnv::Create(this, allocator);
49 if (!etsNapiEnv) {
50 LOG(FATAL, RUNTIME) << "Cannot create PandaEtsNapiEnv: " << etsNapiEnv.Error();
51 }
52 etsNapiEnv_ = std::move(etsNapiEnv.Value());
53 // Main EtsCoroutine is Initialized before class linker and promise_class_ptr_ will be set after creating the class
54 if (HasManagedEntrypoint()) {
55 promiseClassPtr_ = GetPandaVM()->GetClassLinker()->GetPromiseClass()->GetRuntimeClass();
56 undefinedObj_ = GetPandaVM()->GetUndefinedObject();
57 // NOTE (electronick, #15938): Refactor the managed class-related pseudo TLS fields
58 // initialization in MT ManagedThread ctor and EtsCoroutine::Initialize
59 auto *linkExt = GetPandaVM()->GetClassLinker()->GetEtsClassLinkerExtension();
60 SetStringClassPtr(linkExt->GetClassRoot(ClassRoot::STRING));
61 SetArrayU16ClassPtr(linkExt->GetClassRoot(ClassRoot::ARRAY_U16));
62 }
63 ASSERT(promiseClassPtr_ != nullptr || !HasManagedEntrypoint());
64
65 Coroutine::Initialize();
66 }
67
FreeInternalMemory()68 void EtsCoroutine::FreeInternalMemory()
69 {
70 etsNapiEnv_->FreeInternalMemory();
71 ManagedThread::FreeInternalMemory();
72 }
73
RequestCompletion(Value returnValue)74 void EtsCoroutine::RequestCompletion(Value returnValue)
75 {
76 EtsPromise *promise = nullptr;
77 {
78 auto *coroEvent = GetCompletionEvent();
79 auto *storage = GetVM()->GetGlobalObjectStorage();
80 os::memory::LockHolder lh(*coroEvent);
81 auto *promiseRef = coroEvent->ReleasePromise();
82 ASSERT(promiseRef != nullptr);
83 promise = reinterpret_cast<EtsPromise *>(storage->Get(promiseRef));
84 storage->Remove(promiseRef);
85 }
86 if (promise == nullptr) {
87 LOG(DEBUG, COROUTINES)
88 << "Coroutine " << GetName()
89 << " has completed, but the associated promise has been already collected by the GC. Exception thrown: "
90 << HasPendingException();
91 Coroutine::RequestCompletion(returnValue);
92 return;
93 }
94 [[maybe_unused]] EtsHandleScope scope(this);
95 EtsHandle<EtsPromise> hpromise(this, promise);
96 EtsObject *retObject = nullptr;
97 if (!HasPendingException()) {
98 panda_file::Type returnType = GetReturnType();
99 retObject = GetReturnValueAsObject(returnType, returnValue);
100 if (retObject != nullptr) {
101 if (returnType.IsVoid()) {
102 LOG(DEBUG, COROUTINES) << "Coroutine " << GetName() << " has completed";
103 } else if (returnType.IsPrimitive()) {
104 LOG(DEBUG, COROUTINES) << "Coroutine " << GetName() << " has completed with return value 0x" << std::hex
105 << returnValue.GetAs<uint64_t>();
106 } else {
107 LOG(DEBUG, COROUTINES) << "Coroutine " << GetName() << " has completed with return value = ObjectPtr<"
108 << returnValue.GetAs<ObjectHeader *>() << ">";
109 }
110 }
111 }
112 if (HasPendingException()) {
113 // An exception may occur while boxin primitive return value in GetReturnValueAsObject
114 auto *exc = GetException();
115 ClearException();
116 LOG(INFO, COROUTINES) << "Coroutine " << GetName()
117 << " completed with an exception: " << exc->ClassAddr<Class>()->GetName();
118 intrinsics::EtsPromiseReject(hpromise.GetPtr(), EtsObject::FromCoreType(exc));
119 return;
120 }
121 if (retObject != nullptr && retObject->IsInstanceOf(GetPandaVM()->GetClassLinker()->GetPromiseClass())) {
122 retObject = GetValueFromPromiseSync(EtsPromise::FromEtsObject(retObject));
123 }
124 intrinsics::EtsPromiseResolve(hpromise.GetPtr(), retObject);
125 }
126
GetValueFromPromiseSync(EtsPromise * promise)127 EtsObject *EtsCoroutine::GetValueFromPromiseSync(EtsPromise *promise)
128 {
129 return intrinsics::EtsAwaitPromise(promise);
130 }
131
GetReturnType()132 panda_file::Type EtsCoroutine::GetReturnType()
133 {
134 Method *entrypoint = GetManagedEntrypoint();
135 ASSERT(entrypoint != nullptr);
136 return entrypoint->GetReturnType();
137 }
138
GetReturnValueAsObject(panda_file::Type returnType,Value returnValue)139 EtsObject *EtsCoroutine::GetReturnValueAsObject(panda_file::Type returnType, Value returnValue)
140 {
141 switch (returnType.GetId()) {
142 case panda_file::Type::TypeId::VOID:
143 return EtsObject::FromCoreType(undefinedObj_);
144 case panda_file::Type::TypeId::U1:
145 return EtsBoxPrimitive<EtsBoolean>::Create(this, returnValue.GetAs<EtsBoolean>());
146 case panda_file::Type::TypeId::I8:
147 return EtsBoxPrimitive<EtsByte>::Create(this, returnValue.GetAs<EtsByte>());
148 case panda_file::Type::TypeId::I16:
149 return EtsBoxPrimitive<EtsShort>::Create(this, returnValue.GetAs<EtsShort>());
150 case panda_file::Type::TypeId::U16:
151 return EtsBoxPrimitive<EtsChar>::Create(this, returnValue.GetAs<EtsChar>());
152 case panda_file::Type::TypeId::I32:
153 return EtsBoxPrimitive<EtsInt>::Create(this, returnValue.GetAs<EtsInt>());
154 case panda_file::Type::TypeId::F32:
155 return EtsBoxPrimitive<EtsFloat>::Create(this, returnValue.GetAs<EtsFloat>());
156 case panda_file::Type::TypeId::F64:
157 return EtsBoxPrimitive<EtsDouble>::Create(this, returnValue.GetAs<EtsDouble>());
158 case panda_file::Type::TypeId::I64:
159 return EtsBoxPrimitive<EtsLong>::Create(this, returnValue.GetAs<EtsLong>());
160 case panda_file::Type::TypeId::REFERENCE:
161 return EtsObject::FromCoreType(returnValue.GetAs<ObjectHeader *>());
162 default:
163 LOG(FATAL, COROUTINES) << "Unsupported return type: " << returnType;
164 break;
165 }
166 return nullptr;
167 }
168 } // namespace ark::ets
169