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,std::optional<EntrypointInfo> && epInfo)28 EtsCoroutine::EtsCoroutine(ThreadId id, mem::InternalAllocatorPtr allocator, PandaVM *vm, PandaString name,
29 CoroutineContext *context, std::optional<EntrypointInfo> &&epInfo)
30 : Coroutine(id, allocator, vm, ark::panda_file::SourceLang::ETS, std::move(name), context, 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 SetArrayU8ClassPtr(linkExt->GetClassRoot(ClassRoot::ARRAY_U8));
63 }
64 ASSERT(promiseClassPtr_ != nullptr || !HasManagedEntrypoint());
65
66 Coroutine::Initialize();
67 }
68
FreeInternalMemory()69 void EtsCoroutine::FreeInternalMemory()
70 {
71 etsNapiEnv_->FreeInternalMemory();
72 ManagedThread::FreeInternalMemory();
73 }
74
RequestCompletion(Value returnValue)75 void EtsCoroutine::RequestCompletion(Value returnValue)
76 {
77 auto *promiseRef = GetCompletionEvent()->ReleasePromise();
78 if (promiseRef == nullptr) {
79 Coroutine::RequestCompletion(returnValue);
80 return;
81 }
82 auto *storage = GetVM()->GetGlobalObjectStorage();
83 auto *promise = EtsPromise::FromCoreType(storage->Get(promiseRef));
84 storage->Remove(promiseRef);
85 if (promise == nullptr) {
86 LOG(DEBUG, COROUTINES)
87 << "Coroutine " << GetName()
88 << " has completed, but the associated promise has been already collected by the GC. Exception thrown: "
89 << HasPendingException();
90 Coroutine::RequestCompletion(returnValue);
91 return;
92 }
93 [[maybe_unused]] EtsHandleScope scope(this);
94 EtsHandle<EtsPromise> hpromise(this, promise);
95 EtsObject *retObject = nullptr;
96 if (!HasPendingException()) {
97 panda_file::Type returnType = GetReturnType();
98 retObject = GetReturnValueAsObject(returnType, returnValue);
99 if (retObject != nullptr) {
100 LOG_IF(returnType.IsVoid(), DEBUG, COROUTINES) << "Coroutine " << GetName() << " has completed";
101 LOG_IF(returnType.IsPrimitive(), DEBUG, COROUTINES)
102 << "Coroutine " << GetName() << " has completed with return value 0x" << std::hex
103 << returnValue.GetAs<uint64_t>();
104 LOG_IF(returnType.IsReference(), DEBUG, COROUTINES)
105 << "Coroutine " << GetName() << " has completed with return value = ObjectPtr<"
106 << returnValue.GetAs<ObjectHeader *>() << ">";
107 }
108 }
109 if (HasPendingException()) {
110 // An exception may occur while boxin primitive return value in GetReturnValueAsObject
111 auto *exc = GetException();
112 ClearException();
113 LOG(INFO, COROUTINES) << "Coroutine " << GetName()
114 << " completed with an exception: " << exc->ClassAddr<Class>()->GetName();
115 intrinsics::EtsPromiseReject(hpromise.GetPtr(), EtsObject::FromCoreType(exc));
116 return;
117 }
118 if (retObject != nullptr && retObject->IsInstanceOf(GetPandaVM()->GetClassLinker()->GetPromiseClass())) {
119 retObject = GetValueFromPromiseSync(EtsPromise::FromEtsObject(retObject));
120 }
121 intrinsics::EtsPromiseResolve(hpromise.GetPtr(), retObject);
122 }
123
GetValueFromPromiseSync(EtsPromise * promise)124 EtsObject *EtsCoroutine::GetValueFromPromiseSync(EtsPromise *promise)
125 {
126 return intrinsics::EtsAwaitPromise(promise);
127 }
128
GetReturnType()129 panda_file::Type EtsCoroutine::GetReturnType()
130 {
131 Method *entrypoint = GetManagedEntrypoint();
132 ASSERT(entrypoint != nullptr);
133 return entrypoint->GetReturnType();
134 }
135
GetReturnValueAsObject(panda_file::Type returnType,Value returnValue)136 EtsObject *EtsCoroutine::GetReturnValueAsObject(panda_file::Type returnType, Value returnValue)
137 {
138 switch (returnType.GetId()) {
139 case panda_file::Type::TypeId::VOID:
140 return EtsObject::FromCoreType(undefinedObj_);
141 case panda_file::Type::TypeId::U1:
142 return EtsBoxPrimitive<EtsBoolean>::Create(this, returnValue.GetAs<EtsBoolean>());
143 case panda_file::Type::TypeId::I8:
144 return EtsBoxPrimitive<EtsByte>::Create(this, returnValue.GetAs<EtsByte>());
145 case panda_file::Type::TypeId::I16:
146 return EtsBoxPrimitive<EtsShort>::Create(this, returnValue.GetAs<EtsShort>());
147 case panda_file::Type::TypeId::U16:
148 return EtsBoxPrimitive<EtsChar>::Create(this, returnValue.GetAs<EtsChar>());
149 case panda_file::Type::TypeId::I32:
150 return EtsBoxPrimitive<EtsInt>::Create(this, returnValue.GetAs<EtsInt>());
151 case panda_file::Type::TypeId::F32:
152 return EtsBoxPrimitive<EtsFloat>::Create(this, returnValue.GetAs<EtsFloat>());
153 case panda_file::Type::TypeId::F64:
154 return EtsBoxPrimitive<EtsDouble>::Create(this, returnValue.GetAs<EtsDouble>());
155 case panda_file::Type::TypeId::I64:
156 return EtsBoxPrimitive<EtsLong>::Create(this, returnValue.GetAs<EtsLong>());
157 case panda_file::Type::TypeId::REFERENCE:
158 return EtsObject::FromCoreType(returnValue.GetAs<ObjectHeader *>());
159 default:
160 LOG(FATAL, COROUTINES) << "Unsupported return type: " << returnType;
161 break;
162 }
163 return nullptr;
164 }
165 } // namespace ark::ets
166