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