1 /*
2  * Copyright (c) 2023 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 "js_environment.h"
17 
18 #include "ffrt.h"
19 #include "hilog_tag_wrapper.h"
20 #include "js_environment_impl.h"
21 #include "native_engine/impl/ark/ark_native_engine.h"
22 #include "uncaught_exception_callback.h"
23 #include "commonlibrary/ets_utils/js_sys_module/console/console.h"
24 
25 namespace OHOS {
26 namespace JsEnv {
27 namespace {
28 static const std::string DEBUGGER = "@Debugger";
29 static const std::string NOT_INIT = "SourceMap is not initialized yet \n";
30 }
31 
ConvertProfilerType(JsEnvironment::PROFILERTYPE type)32 static panda::DFXJSNApi::ProfilerType ConvertProfilerType(JsEnvironment::PROFILERTYPE type)
33 {
34     if (type == JsEnvironment::PROFILERTYPE::PROFILERTYPE_CPU) {
35         return panda::DFXJSNApi::ProfilerType::CPU_PROFILER;
36     } else {
37         return panda::DFXJSNApi::ProfilerType::HEAP_PROFILER;
38     }
39 }
40 
JsEnvironment(std::unique_ptr<JsEnvironmentImpl> impl)41 JsEnvironment::JsEnvironment(std::unique_ptr<JsEnvironmentImpl> impl) : impl_(std::move(impl))
42 {}
43 
~JsEnvironment()44 JsEnvironment::~JsEnvironment()
45 {
46     TAG_LOGD(AAFwkTag::JSENV, "called");
47 
48     if (engine_ != nullptr) {
49         delete engine_;
50         engine_ = nullptr;
51     }
52 
53     if (vm_ != nullptr) {
54         panda::JSNApi::DestroyJSVM(vm_);
55         vm_ = nullptr;
56     }
57 }
58 
Initialize(const panda::RuntimeOption & pandaOption,void * jsEngine)59 bool JsEnvironment::Initialize(const panda::RuntimeOption& pandaOption, void* jsEngine)
60 {
61     TAG_LOGD(AAFwkTag::JSENV, "Js environment initialize");
62     vm_ = panda::JSNApi::CreateJSVM(pandaOption);
63     if (vm_ == nullptr) {
64         TAG_LOGE(AAFwkTag::JSENV, "Create vm failed");
65         return false;
66     }
67 
68     engine_ = new ArkNativeEngine(vm_, jsEngine);
69     return true;
70 }
71 
InitTimerModule()72 void JsEnvironment::InitTimerModule()
73 {
74     if (engine_ == nullptr) {
75         TAG_LOGE(AAFwkTag::JSENV, "Invalid native engine");
76         return;
77     }
78 
79     if (impl_ != nullptr) {
80         impl_->InitTimerModule(engine_);
81     }
82 }
83 
InitWorkerModule(std::shared_ptr<WorkerInfo> workerInfo)84 void JsEnvironment::InitWorkerModule(std::shared_ptr<WorkerInfo> workerInfo)
85 {
86     if (engine_ == nullptr) {
87         TAG_LOGE(AAFwkTag::JSENV, "Invalid native engine");
88         return;
89     }
90 
91     if (impl_ != nullptr) {
92         impl_->InitWorkerModule(engine_, workerInfo);
93     }
94 }
95 
InitSyscapModule()96 void JsEnvironment::InitSyscapModule()
97 {
98     if (impl_ != nullptr) {
99         impl_->InitSyscapModule();
100     }
101 }
102 
PostTask(const std::function<void ()> & task,const std::string & name,int64_t delayTime)103 void JsEnvironment::PostTask(const std::function<void()>& task, const std::string& name, int64_t delayTime)
104 {
105     if (impl_ != nullptr) {
106         impl_->PostTask(task, name, delayTime);
107     }
108 }
109 
PostSyncTask(const std::function<void ()> & task,const std::string & name)110 void JsEnvironment::PostSyncTask(const std::function<void()>& task, const std::string& name)
111 {
112     if (impl_ != nullptr) {
113         impl_->PostSyncTask(task, name);
114     }
115 }
116 
RemoveTask(const std::string & name)117 void JsEnvironment::RemoveTask(const std::string& name)
118 {
119     if (impl_ != nullptr) {
120         impl_->RemoveTask(name);
121     }
122 }
123 
InitSourceMap(const std::shared_ptr<JsEnv::SourceMapOperator> operatorObj)124 void JsEnvironment::InitSourceMap(const std::shared_ptr<JsEnv::SourceMapOperator> operatorObj)
125 {
126     sourceMapOperator_ = operatorObj;
127     if (engine_ == nullptr) {
128         TAG_LOGE(AAFwkTag::JSENV, "Invalid Native Engine");
129         return;
130     }
131 
132     if (sourceMapOperator_ != nullptr) {
133         sourceMapOperator_->InitSourceMap();
134     }
135 
136     auto translateBySourceMapFunc = [&](const std::string& rawStack) -> std::string {
137         if (sourceMapOperator_ != nullptr && sourceMapOperator_->GetInitStatus()) {
138             return sourceMapOperator_->TranslateBySourceMap(rawStack);
139         } else {
140             return NOT_INIT + rawStack;
141         }
142     };
143     engine_->RegisterTranslateBySourceMap(translateBySourceMapFunc);
144 
145     auto translateUrlBySourceMapFunc = [&](std::string& url, int& line, int& column) -> bool {
146         if (sourceMapOperator_ != nullptr && sourceMapOperator_->GetInitStatus()) {
147             return sourceMapOperator_->TranslateUrlPositionBySourceMap(url, line, column);
148         }
149         return false;
150     };
151     engine_->RegisterSourceMapTranslateCallback(translateUrlBySourceMapFunc);
152 }
153 
RegisterUncaughtExceptionHandler(const JsEnv::UncaughtExceptionInfo & uncaughtExceptionInfo)154 void JsEnvironment::RegisterUncaughtExceptionHandler(const JsEnv::UncaughtExceptionInfo& uncaughtExceptionInfo)
155 {
156     if (engine_ == nullptr) {
157         TAG_LOGE(AAFwkTag::JSENV, "Invalid Native Engine");
158         return;
159     }
160 
161     engine_->RegisterNapiUncaughtExceptionHandler(NapiUncaughtExceptionCallback(uncaughtExceptionInfo.uncaughtTask,
162         sourceMapOperator_, reinterpret_cast<napi_env>(engine_)));
163 }
164 
LoadScript(const std::string & path,std::vector<uint8_t> * buffer,bool isBundle)165 bool JsEnvironment::LoadScript(const std::string& path, std::vector<uint8_t>* buffer, bool isBundle)
166 {
167     if (engine_ == nullptr) {
168         TAG_LOGE(AAFwkTag::JSENV, "Invalid Native Engine");
169         return false;
170     }
171 
172     if (buffer == nullptr) {
173         return engine_->RunScriptPath(path.c_str());
174     }
175 
176     return engine_->RunScriptBuffer(path.c_str(), *buffer, isBundle) != nullptr;
177 }
178 
StartDebugger(std::string & option,uint32_t socketFd,bool isDebugApp)179 bool JsEnvironment::StartDebugger(
180     std::string& option, uint32_t socketFd, bool isDebugApp)
181 {
182     TAG_LOGD(AAFwkTag::JSENV, "call");
183     if (vm_ == nullptr) {
184         TAG_LOGE(AAFwkTag::JSENV, "Invalid vm");
185         return false;
186     }
187     int32_t identifierId = ParseHdcRegisterOption(option);
188     if (identifierId == -1) {
189         TAG_LOGE(AAFwkTag::JSENV, "Abnormal parsing of tid results");
190         return false;
191     }
192     debugMode_ = panda::JSNApi::StartDebuggerForSocketPair(identifierId, socketFd);
193     return debugMode_;
194 }
195 
StopDebugger()196 void JsEnvironment::StopDebugger()
197 {
198     if (vm_ == nullptr) {
199         TAG_LOGE(AAFwkTag::JSENV, "Invalid vm");
200         return;
201     }
202 
203     (void)panda::JSNApi::StopDebugger(vm_);
204 }
205 
StopDebugger(std::string & option)206 void JsEnvironment::StopDebugger(std::string& option)
207 {
208     int32_t identifierId = ParseHdcRegisterOption(option);
209     if (identifierId == -1) {
210         TAG_LOGE(AAFwkTag::JSENV, "Abnormal parsing of tid results");
211         return;
212     }
213     panda::JSNApi::StopDebugger(identifierId);
214 }
215 
InitConsoleModule()216 void JsEnvironment::InitConsoleModule()
217 {
218     if (engine_ == nullptr) {
219         TAG_LOGE(AAFwkTag::JSENV, "Invalid Native Engine");
220         return;
221     }
222 
223     if (impl_ != nullptr) {
224         impl_->InitConsoleModule(engine_);
225     }
226 }
227 
InitLoop(bool isStage)228 bool JsEnvironment::InitLoop(bool isStage)
229 {
230     if (engine_ == nullptr) {
231         TAG_LOGE(AAFwkTag::JSENV, "Invalid Native Engine");
232         return false;
233     }
234 
235     if (impl_ != nullptr) {
236         impl_->InitLoop(engine_, isStage);
237     }
238     return true;
239 }
240 
DeInitLoop()241 void JsEnvironment::DeInitLoop()
242 {
243     if (engine_ == nullptr) {
244         TAG_LOGE(AAFwkTag::JSENV, "Invalid Native Engine");
245         return;
246     }
247 
248     if (impl_ != nullptr) {
249         impl_->DeInitLoop(engine_);
250     }
251 }
252 
LoadScript(const std::string & path,uint8_t * buffer,size_t len,bool isBundle)253 bool JsEnvironment::LoadScript(const std::string& path, uint8_t* buffer, size_t len, bool isBundle)
254 {
255     if (engine_ == nullptr) {
256         TAG_LOGE(AAFwkTag::JSENV, "Invalid Native Engine");
257         return false;
258     }
259 
260     return engine_->RunScriptBuffer(path, buffer, len, isBundle);
261 }
262 
StartProfiler(const char * libraryPath,uint32_t instanceId,PROFILERTYPE profiler,int32_t interval,int tid,bool isDebugApp)263 void JsEnvironment::StartProfiler(const char* libraryPath, uint32_t instanceId, PROFILERTYPE profiler,
264     int32_t interval, int tid, bool isDebugApp)
265 {
266     if (vm_ == nullptr) {
267         TAG_LOGE(AAFwkTag::JSENV, "Invalid vm");
268         return;
269     }
270 
271     auto debuggerPostTask = [weak = weak_from_this()](std::function<void()>&& task) {
272         auto jsEnv = weak.lock();
273         if (jsEnv == nullptr) {
274             TAG_LOGE(AAFwkTag::JSENV, "JsEnv is invalid");
275             return;
276         }
277         jsEnv->PostTask(task, "JsEnvironment::StartProfiler");
278     };
279 
280     panda::DFXJSNApi::ProfilerOption option;
281     option.libraryPath = libraryPath;
282     option.profilerType = ConvertProfilerType(profiler);
283     option.interval = interval;
284 
285     panda::DFXJSNApi::StartProfiler(vm_, option, tid, instanceId, debuggerPostTask, isDebugApp);
286 }
287 
DestroyHeapProfiler()288 void JsEnvironment::DestroyHeapProfiler()
289 {
290     if (vm_ == nullptr) {
291         TAG_LOGE(AAFwkTag::JSENV, "Invalid vm");
292         return;
293     }
294     panda::DFXJSNApi::DestroyHeapProfiler(vm_);
295 }
296 
GetHeapPrepare()297 void JsEnvironment::GetHeapPrepare()
298 {
299     if (vm_ == nullptr) {
300         TAG_LOGE(AAFwkTag::JSENV, "Invalid vm");
301         return;
302     }
303     panda::DFXJSNApi::GetHeapPrepare(vm_);
304 }
305 
SetModuleLoadChecker(const std::shared_ptr<ModuleCheckerDelegate> moduleCheckerDelegate)306 void JsEnvironment::SetModuleLoadChecker(const std::shared_ptr<ModuleCheckerDelegate> moduleCheckerDelegate)
307 {
308     if (engine_ == nullptr) {
309         TAG_LOGE(AAFwkTag::JSENV, "Invalid native engine");
310         return;
311     }
312 
313     engine_->SetModuleLoadChecker(moduleCheckerDelegate);
314 }
315 
ReInitJsEnvImpl(std::unique_ptr<JsEnvironmentImpl> impl)316 void JsEnvironment::ReInitJsEnvImpl(std::unique_ptr<JsEnvironmentImpl> impl)
317 {
318     TAG_LOGD(AAFwkTag::JSENV, "ReInit jsenv impl.");
319     impl_ = std::move(impl);
320 }
321 
SetRequestAotCallback(const RequestAotCallback & cb)322 void JsEnvironment::SetRequestAotCallback(const RequestAotCallback& cb)
323 {
324     if (vm_ == nullptr) {
325         TAG_LOGE(AAFwkTag::JSENV, "Invalid vm");
326         return;
327     }
328 
329     panda::JSNApi::SetRequestAotCallback(vm_, cb);
330 }
331 
SetDeviceDisconnectCallback(const std::function<bool ()> & cb)332 void JsEnvironment::SetDeviceDisconnectCallback(const std::function<bool()> &cb)
333 {
334     panda::JSNApi::SetDeviceDisconnectCallback(vm_, std::move(cb));
335 }
336 
GetDebuggerPostTask()337 DebuggerPostTask JsEnvironment::GetDebuggerPostTask()
338 {
339     auto debuggerPostTask = [weak = weak_from_this()](std::function<void()>&& task) {
340         auto jsEnv = weak.lock();
341         if (jsEnv == nullptr) {
342             TAG_LOGE(AAFwkTag::JSENV, "JsEnv is invalid");
343             return;
344         }
345         jsEnv->PostTask(task, "JsEnvironment:GetDebuggerPostTask");
346     };
347     return debuggerPostTask;
348 }
349 
NotifyDebugMode(int tid,const char * libraryPath,uint32_t instanceId,bool debug,bool debugMode)350 void JsEnvironment::NotifyDebugMode(
351     int tid, const char* libraryPath, uint32_t instanceId, bool debug, bool debugMode)
352 {
353     if (vm_ == nullptr) {
354         TAG_LOGE(AAFwkTag::JSENV, "Invalid vm");
355         return;
356     }
357     panda::JSNApi::DebugOption debugOption = {libraryPath, debug ? debugMode : false};
358     auto debuggerPostTask = [weak = weak_from_this()](std::function<void()>&& task) {
359         auto jsEnv = weak.lock();
360         if (jsEnv == nullptr) {
361             TAG_LOGE(AAFwkTag::JSENV, "JsEnv is invalid");
362             return;
363         }
364         jsEnv->PostTask(task, "JsEnvironment:NotifyDebugMode");
365     };
366     panda::JSNApi::NotifyDebugMode(tid, vm_, debugOption, instanceId, debuggerPostTask, debug);
367 }
368 
ParseHdcRegisterOption(std::string & option)369 int32_t JsEnvironment::ParseHdcRegisterOption(std::string& option)
370 {
371     TAG_LOGD(AAFwkTag::JSENV, "Start");
372     std::size_t pos = option.find_first_of(":");
373     if (pos == std::string::npos) {
374         return -1;
375     }
376     std::string idStr = option.substr(pos + 1);
377     pos = idStr.find(DEBUGGER);
378     if (pos == std::string::npos) {
379         return -1;
380     }
381     idStr = idStr.substr(0, pos);
382     pos = idStr.find("@");
383     if (pos != std::string::npos) {
384         idStr = idStr.substr(pos + 1);
385     }
386     return std::atoi(idStr.c_str());
387 }
388 
GetDebugMode() const389 bool JsEnvironment::GetDebugMode() const
390 {
391     return debugMode_;
392 }
393 } // namespace JsEnv
394 } // namespace OHOS
395