1 /*
2 * Copyright (c) 2021-2022 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 "inspector.h"
17
18 #include <shared_mutex>
19 #if defined(OHOS_PLATFORM)
20 #include <syscall.h>
21 #endif
22 #include <thread>
23 #if defined(OHOS_PLATFORM)
24 #include <unistd.h>
25 #endif
26
27 #include "common/log_wrapper.h"
28 #include "library_loader.h"
29
30 #if defined(IOS_PLATFORM)
31 #include "tooling/debugger_service.h"
32 #endif
33
34 #if defined(ENABLE_FFRT_INTERFACES)
35 #include "ffrt.h"
36 #endif
37
38 namespace OHOS::ArkCompiler::Toolchain {
39 namespace {
40 enum DispatchStatus : int32_t {
41 UNKNOWN = 0,
42 DISPATCHING,
43 DISPATCHED
44 };
45
46 using InitializeDebugger = void(*)(void*, const std::function<void(const void*, const std::string&)>&);
47 using UninitializeDebugger = void(*)(void*);
48 using WaitForDebugger = void(*)(void*);
49 using OnMessage = void(*)(void*, std::string&&);
50 using ProcessMessage = void(*)(void*);
51 using GetDispatchStatus = int32_t(*)(void*);
52 using GetCallFrames = char*(*)(void*);
53
54 OnMessage g_onMessage = nullptr;
55 InitializeDebugger g_initializeDebugger = nullptr;
56 UninitializeDebugger g_uninitializeDebugger = nullptr;
57 WaitForDebugger g_waitForDebugger = nullptr;
58 ProcessMessage g_processMessage = nullptr;
59 GetDispatchStatus g_getDispatchStatus = nullptr;
60 GetCallFrames g_getCallFrames = nullptr;
61
62 std::atomic<bool> g_hasArkFuncsInited = false;
63 std::unordered_map<const void*, Inspector*> g_inspectors;
64 std::unordered_map<int, std::pair<void*, const DebuggerPostTask>> g_debuggerInfo;
65 std::shared_mutex g_mutex;
66
67 #if !defined(IOS_PLATFORM)
68 thread_local void* g_handle = nullptr;
69 #endif
70 thread_local void* g_vm = nullptr;
71
72 #if !defined(IOS_PLATFORM)
73 #if defined(WINDOWS_PLATFORM)
74 constexpr char ARK_DEBUGGER_SHARED_LIB[] = "libark_tooling.dll";
75 #elif defined(MAC_PLATFORM)
76 constexpr char ARK_DEBUGGER_SHARED_LIB[] = "libark_tooling.dylib";
77 #else
78 constexpr char ARK_DEBUGGER_SHARED_LIB[] = "libark_tooling.so";
79 #endif
80 #endif
81
HandleClient(void * const server)82 void* HandleClient(void* const server)
83 {
84 LOGI("HandleClient");
85 if (server == nullptr) {
86 LOGE("HandleClient server nullptr");
87 return nullptr;
88 }
89
90 #if defined(IOS_PLATFORM) || defined(MAC_PLATFORM)
91 pthread_setname_np("OS_DebugThread");
92 #else
93 pthread_setname_np(pthread_self(), "OS_DebugThread");
94 #endif
95
96 static_cast<WsServer*>(server)->RunServer();
97 return nullptr;
98 }
99
100 #if !defined(IOS_PLATFORM)
LoadArkDebuggerLibrary()101 bool LoadArkDebuggerLibrary()
102 {
103 if (g_handle != nullptr) {
104 LOGI("LoadArkDebuggerLibrary, handle has already loaded");
105 return true;
106 }
107 g_handle = Load(ARK_DEBUGGER_SHARED_LIB);
108 if (g_handle == nullptr) {
109 LOGE("LoadArkDebuggerLibrary, handle load failed");
110 return false;
111 }
112 return true;
113 }
114
GetArkDynFunction(const char * symbol)115 void* GetArkDynFunction(const char* symbol)
116 {
117 return ResolveSymbol(g_handle, symbol);
118 }
119 #endif
120
SendReply(const void * vm,const std::string & message)121 void SendReply(const void* vm, const std::string& message)
122 {
123 std::shared_lock<std::shared_mutex> lock(g_mutex);
124 auto iter = g_inspectors.find(vm);
125 if (iter != g_inspectors.end() && iter->second != nullptr &&
126 iter->second->websocketServer_ != nullptr) {
127 iter->second->websocketServer_->SendReply(message);
128 }
129 }
130
ResetServiceLocked(void * vm,bool isCloseHandle)131 void ResetServiceLocked(void *vm, bool isCloseHandle)
132 {
133 auto iter = g_inspectors.find(vm);
134 if (iter != g_inspectors.end() && iter->second != nullptr &&
135 iter->second->websocketServer_ != nullptr) {
136 iter->second->websocketServer_->StopServer();
137 delete iter->second;
138 iter->second = nullptr;
139 g_inspectors.erase(iter);
140 }
141 #if !defined(IOS_PLATFORM)
142 if (g_handle != nullptr && isCloseHandle) {
143 CloseHandle(g_handle);
144 g_handle = nullptr;
145 }
146 #endif
147 }
148
InitializeInspector(void * vm,const DebuggerPostTask & debuggerPostTask,const DebugInfo & debugInfo,int tidForSocketPair=0)149 bool InitializeInspector(
150 void* vm, const DebuggerPostTask& debuggerPostTask, const DebugInfo& debugInfo, int tidForSocketPair = 0)
151 {
152 std::unique_lock<std::shared_mutex> lock(g_mutex);
153 auto iter = g_inspectors.find(vm);
154 if (iter != g_inspectors.end()) {
155 LOGW("Inspector already exist!");
156 return true;
157 }
158
159 Inspector *newInspector = new Inspector();
160 g_inspectors.emplace(vm, newInspector);
161
162 newInspector->tidForSocketPair_ = tidForSocketPair;
163 newInspector->tid_ = pthread_self();
164 newInspector->vm_ = vm;
165 newInspector->debuggerPostTask_ = debuggerPostTask;
166 newInspector->websocketServer_ = std::make_unique<WsServer>(debugInfo,
167 std::bind(&Inspector::OnMessage, newInspector, std::placeholders::_1));
168
169 pthread_t tid;
170 if (pthread_create(&tid, nullptr, &HandleClient, static_cast<void *>(
171 newInspector->websocketServer_.get())) != 0) {
172 LOGE("Create inspector thread failed");
173 return false;
174 }
175 newInspector->websocketServer_->tid_ = tid;
176
177 return true;
178 }
179
180 #if !defined(IOS_PLATFORM)
InitializeArkFunctionsOthers()181 bool InitializeArkFunctionsOthers()
182 {
183 g_initializeDebugger = reinterpret_cast<InitializeDebugger>(
184 GetArkDynFunction("InitializeDebugger"));
185 if (g_initializeDebugger == nullptr) {
186 ResetServiceLocked(g_vm, true);
187 return false;
188 }
189 g_uninitializeDebugger = reinterpret_cast<UninitializeDebugger>(
190 GetArkDynFunction("UninitializeDebugger"));
191 if (g_uninitializeDebugger == nullptr) {
192 ResetServiceLocked(g_vm, true);
193 return false;
194 }
195 g_waitForDebugger = reinterpret_cast<WaitForDebugger>(
196 GetArkDynFunction("WaitForDebugger"));
197 if (g_waitForDebugger == nullptr) {
198 ResetServiceLocked(g_vm, true);
199 return false;
200 }
201 g_onMessage = reinterpret_cast<OnMessage>(
202 GetArkDynFunction("OnMessage"));
203 if (g_onMessage == nullptr) {
204 ResetServiceLocked(g_vm, true);
205 return false;
206 }
207 g_getDispatchStatus = reinterpret_cast<GetDispatchStatus>(
208 GetArkDynFunction("GetDispatchStatus"));
209 if (g_getDispatchStatus == nullptr) {
210 ResetServiceLocked(g_vm, true);
211 return false;
212 }
213 g_processMessage = reinterpret_cast<ProcessMessage>(
214 GetArkDynFunction("ProcessMessage"));
215 if (g_processMessage == nullptr) {
216 ResetServiceLocked(g_vm, true);
217 return false;
218 }
219 g_getCallFrames = reinterpret_cast<GetCallFrames>(
220 GetArkDynFunction("GetCallFrames"));
221 if (g_getCallFrames == nullptr) {
222 ResetServiceLocked(g_vm, true);
223 return false;
224 }
225 return true;
226 }
227 #else
InitializeArkFunctionsIOS()228 bool InitializeArkFunctionsIOS()
229 {
230 using namespace panda::ecmascript;
231 g_initializeDebugger = reinterpret_cast<InitializeDebugger>(&tooling::InitializeDebugger);
232 g_uninitializeDebugger = reinterpret_cast<UninitializeDebugger>(&tooling::UninitializeDebugger);
233 g_waitForDebugger = reinterpret_cast<WaitForDebugger>(&tooling::WaitForDebugger);
234 g_onMessage = reinterpret_cast<OnMessage>(&tooling::OnMessage);
235 g_getDispatchStatus = reinterpret_cast<GetDispatchStatus>(&tooling::GetDispatchStatus);
236 g_processMessage = reinterpret_cast<ProcessMessage>(&tooling::ProcessMessage);
237 g_getCallFrames = reinterpret_cast<GetCallFrames>(&tooling::GetCallFrames);
238 return true;
239 }
240 #endif
241
InitializeArkFunctions()242 bool InitializeArkFunctions()
243 {
244 // no need to initialize again in case of multi-instance
245 if (g_hasArkFuncsInited) {
246 return true;
247 }
248
249 std::unique_lock<std::shared_mutex> lock(g_mutex);
250 if (g_hasArkFuncsInited) {
251 return true;
252 }
253 #if !defined(IOS_PLATFORM)
254 if (!InitializeArkFunctionsOthers()) {
255 return false;
256 }
257 #else
258 InitializeArkFunctionsIOS()
259 #endif
260
261 g_hasArkFuncsInited = true;
262 return true;
263 }
264
265 } // namespace
266
OnMessage(std::string && msg)267 void Inspector::OnMessage(std::string&& msg)
268 {
269 g_onMessage(vm_, std::move(msg));
270
271 // message will be processed soon if the debugger thread is in running or waiting status
272 if (g_getDispatchStatus(vm_) != DispatchStatus::UNKNOWN) {
273 return;
274 }
275 std::this_thread::sleep_for(std::chrono::microseconds(DELAY_CHECK_DISPATCH_STATUS));
276 if (g_getDispatchStatus(vm_) != DispatchStatus::UNKNOWN) {
277 return;
278 }
279
280 // the debugger thread maybe in idle status, so try to post a task to wake it up
281 if (debuggerPostTask_ != nullptr) {
282 if (tidForSocketPair_ == 0) {
283 debuggerPostTask_([tid = tid_, vm = vm_] {
284 if (tid != pthread_self()) {
285 LOGE("Task not in debugger thread");
286 return;
287 }
288 g_processMessage(vm);
289 });
290 } else {
291 #if defined(OHOS_PLATFORM)
292 debuggerPostTask_([tid = tidForSocketPair_, vm = vm_] {
293 uint64_t threadOrTaskId = GetThreadOrTaskId();
294 if (tid != static_cast<pid_t>(threadOrTaskId)) {
295 LOGE("Task not in debugger thread for socketpair");
296 return;
297 }
298 g_processMessage(vm);
299 });
300 #endif // defined(OHOS_PLATFORM)
301 }
302 } else {
303 LOGW("No debuggerPostTask provided");
304 }
305 }
306
307 #if defined(OHOS_PLATFORM)
GetThreadOrTaskId()308 uint64_t Inspector::GetThreadOrTaskId()
309 {
310 #if defined(ENABLE_FFRT_INTERFACES)
311 uint64_t threadOrTaskId = ffrt_this_task_get_id();
312 if (threadOrTaskId != 0) {
313 return threadOrTaskId;
314 } else {
315 return static_cast<uint64_t>(getproctid());
316 }
317 #else
318 return static_cast<uint64_t>(getproctid());
319 #endif // defined(ENABLE_FFRT_INTERFACES)
320 }
321 #endif // defined(OHOS_PLATFORM)
322
GetDebuggerPostTask(int tid)323 const DebuggerPostTask &GetDebuggerPostTask(int tid)
324 {
325 std::shared_lock<std::shared_mutex> lock(g_mutex);
326 if (g_debuggerInfo.find(tid) == g_debuggerInfo.end()) {
327 static DebuggerPostTask tempTask;
328 return tempTask;
329 }
330 return g_debuggerInfo[tid].second;
331 }
332
GetEcmaVM(int tid)333 void *GetEcmaVM(int tid)
334 {
335 std::shared_lock<std::shared_mutex> lock(g_mutex);
336 if (g_debuggerInfo.find(tid) == g_debuggerInfo.end()) {
337 return nullptr;
338 }
339 return g_debuggerInfo[tid].first;
340 }
341
InitializeDebuggerForSocketpair(void * vm)342 bool InitializeDebuggerForSocketpair(void* vm)
343 {
344 #if !defined(IOS_PLATFORM)
345 if (!LoadArkDebuggerLibrary()) {
346 return false;
347 }
348 #endif
349 if (!InitializeArkFunctions()) {
350 LOGE("Initialize ark functions failed");
351 return false;
352 }
353 g_initializeDebugger(vm, std::bind(&SendReply, vm, std::placeholders::_2));
354 return true;
355 }
356
357 // for ohos platform.
StartDebugForSocketpair(int tid,int socketfd)358 bool StartDebugForSocketpair(int tid, int socketfd)
359 {
360 LOGI("StartDebugForSocketpair, tid = %{private}d, socketfd = %{private}d", tid, socketfd);
361 void* vm = GetEcmaVM(tid);
362 if (vm == nullptr) {
363 LOGD("VM has already been destroyed");
364 return false;
365 }
366 g_vm = vm;
367 if (!InitializeDebuggerForSocketpair(vm)) {
368 return false;
369 }
370 const DebuggerPostTask &debuggerPostTask = GetDebuggerPostTask(tid);
371 DebugInfo debugInfo = {socketfd};
372 if (!InitializeInspector(vm, debuggerPostTask, debugInfo, tid)) {
373 LOGE("Initialize inspector failed");
374 return false;
375 }
376
377 return true;
378 }
379
380 // for cross-platform, previewer and old process of StartDebugger.
StartDebug(const std::string & componentName,void * vm,bool isDebugMode,int32_t instanceId,const DebuggerPostTask & debuggerPostTask,int port)381 bool StartDebug(const std::string& componentName, void* vm, bool isDebugMode,
382 int32_t instanceId, const DebuggerPostTask& debuggerPostTask, int port)
383 {
384 LOGI("StartDebug, componentName = %{private}s, isDebugMode = %{private}d, instanceId = %{private}d",
385 componentName.c_str(), isDebugMode, instanceId);
386 g_vm = vm;
387 #if !defined(IOS_PLATFORM)
388 if (!LoadArkDebuggerLibrary()) {
389 return false;
390 }
391 #endif
392 if (!InitializeArkFunctions()) {
393 LOGE("Initialize ark functions failed");
394 return false;
395 }
396
397 g_initializeDebugger(vm, std::bind(&SendReply, vm, std::placeholders::_2));
398
399 int startDebugInOldProcess = -2; // start debug in old process.
400 DebugInfo debugInfo = {startDebugInOldProcess, componentName, instanceId, port};
401 if (!InitializeInspector(vm, debuggerPostTask, debugInfo)) {
402 LOGE("Initialize inspector failed");
403 return false;
404 }
405
406 if (isDebugMode && port > 0) {
407 LOGI("Wait for debugger for previewer");
408 g_waitForDebugger(vm);
409 }
410 return true;
411 }
412
WaitForDebugger(void * vm)413 void WaitForDebugger(void* vm)
414 {
415 LOGI("WaitForDebugger");
416 g_waitForDebugger(vm);
417 }
418
StopDebug(void * vm)419 void StopDebug(void* vm)
420 {
421 LOGI("StopDebug start, vm is %{private}p", vm);
422 std::unique_lock<std::shared_mutex> lock(g_mutex);
423 auto iter = g_inspectors.find(vm);
424 if (iter == g_inspectors.end() || iter->second == nullptr) {
425 return;
426 }
427 #ifdef PANDA_TARGET_MACOS
428 uint32_t tid = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(g_inspectors[vm]->tid_));
429 #else
430 uint32_t tid = g_inspectors[vm]->tid_;
431 #endif
432 auto debuggerInfo = g_debuggerInfo.find(tid);
433 if (debuggerInfo != g_debuggerInfo.end()) {
434 g_debuggerInfo.erase(debuggerInfo);
435 }
436 g_uninitializeDebugger(vm);
437 ResetServiceLocked(vm, true);
438 LOGI("StopDebug end");
439 }
440
StopOldDebug(int tid,const std::string & componentName)441 void StopOldDebug(int tid, const std::string& componentName)
442 {
443 LOGI("StopDebug start, componentName = %{private}s, tid = %{private}d", componentName.c_str(), tid);
444 void* vm = GetEcmaVM(tid);
445 if (vm == nullptr) {
446 return;
447 }
448 std::unique_lock<std::shared_mutex> lock(g_mutex);
449 auto iter = g_inspectors.find(vm);
450 if (iter == g_inspectors.end() || iter->second == nullptr) {
451 return;
452 }
453
454 ResetServiceLocked(vm, false);
455 LOGI("StopDebug end");
456 }
457
458 // for socketpair process.
StoreDebuggerInfo(int tid,void * vm,const DebuggerPostTask & debuggerPostTask)459 void StoreDebuggerInfo(int tid, void* vm, const DebuggerPostTask& debuggerPostTask)
460 {
461 std::unique_lock<std::shared_mutex> lock(g_mutex);
462 if (g_debuggerInfo.find(tid) == g_debuggerInfo.end()) {
463 g_debuggerInfo.emplace(tid, std::make_pair(vm, debuggerPostTask));
464 }
465 }
466
467 // The returned pointer must be released using free() after it is no longer needed.
468 // Failure to release the memory will result in memory leaks.
GetJsBacktrace()469 const char* GetJsBacktrace()
470 {
471 #if defined(OHOS_PLATFORM)
472 void* vm = GetEcmaVM(Inspector::GetThreadOrTaskId());
473 if (g_getCallFrames == nullptr) {
474 LOGE("GetCallFrames symbol resolve failed");
475 return "";
476 }
477 return g_getCallFrames(vm);
478 #else
479 return "";
480 #endif
481 }
482 } // namespace OHOS::ArkCompiler::Toolchain
483