xref: /openbsd-src/gnu/llvm/lldb/source/Plugins/Process/Linux/NativeThreadLinux.cpp (revision 5a38ef86d0b61900239c7913d24a05e7b88a58f0)
1 //===-- NativeThreadLinux.cpp ---------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "NativeThreadLinux.h"
10 
11 #include <csignal>
12 #include <sstream>
13 
14 #include "NativeProcessLinux.h"
15 #include "NativeRegisterContextLinux.h"
16 #include "SingleStepCheck.h"
17 
18 #include "lldb/Host/HostNativeThread.h"
19 #include "lldb/Host/linux/Ptrace.h"
20 #include "lldb/Host/linux/Support.h"
21 #include "lldb/Utility/LLDBAssert.h"
22 #include "lldb/Utility/Log.h"
23 #include "lldb/Utility/State.h"
24 #include "lldb/lldb-enumerations.h"
25 
26 #include "llvm/ADT/SmallString.h"
27 
28 #include "Plugins/Process/POSIX/CrashReason.h"
29 #include "Plugins/Process/Utility/MemoryTagManagerAArch64MTE.h"
30 
31 #include <sys/syscall.h>
32 // Try to define a macro to encapsulate the tgkill syscall
33 #define tgkill(pid, tid, sig)                                                  \
34   syscall(__NR_tgkill, static_cast<::pid_t>(pid), static_cast<::pid_t>(tid),   \
35           sig)
36 
37 using namespace lldb;
38 using namespace lldb_private;
39 using namespace lldb_private::process_linux;
40 
41 namespace {
42 void LogThreadStopInfo(Log &log, const ThreadStopInfo &stop_info,
43                        const char *const header) {
44   switch (stop_info.reason) {
45   case eStopReasonNone:
46     log.Printf("%s: %s no stop reason", __FUNCTION__, header);
47     return;
48   case eStopReasonTrace:
49     log.Printf("%s: %s trace, stopping signal 0x%" PRIx32, __FUNCTION__, header,
50                stop_info.details.signal.signo);
51     return;
52   case eStopReasonBreakpoint:
53     log.Printf("%s: %s breakpoint, stopping signal 0x%" PRIx32, __FUNCTION__,
54                header, stop_info.details.signal.signo);
55     return;
56   case eStopReasonWatchpoint:
57     log.Printf("%s: %s watchpoint, stopping signal 0x%" PRIx32, __FUNCTION__,
58                header, stop_info.details.signal.signo);
59     return;
60   case eStopReasonSignal:
61     log.Printf("%s: %s signal 0x%02" PRIx32, __FUNCTION__, header,
62                stop_info.details.signal.signo);
63     return;
64   case eStopReasonException:
65     log.Printf("%s: %s exception type 0x%02" PRIx64, __FUNCTION__, header,
66                stop_info.details.exception.type);
67     return;
68   case eStopReasonExec:
69     log.Printf("%s: %s exec, stopping signal 0x%" PRIx32, __FUNCTION__, header,
70                stop_info.details.signal.signo);
71     return;
72   case eStopReasonPlanComplete:
73     log.Printf("%s: %s plan complete", __FUNCTION__, header);
74     return;
75   case eStopReasonThreadExiting:
76     log.Printf("%s: %s thread exiting", __FUNCTION__, header);
77     return;
78   case eStopReasonInstrumentation:
79     log.Printf("%s: %s instrumentation", __FUNCTION__, header);
80     return;
81   case eStopReasonProcessorTrace:
82     log.Printf("%s: %s processor trace", __FUNCTION__, header);
83     return;
84   default:
85     log.Printf("%s: %s invalid stop reason %" PRIu32, __FUNCTION__, header,
86                static_cast<uint32_t>(stop_info.reason));
87   }
88 }
89 }
90 
91 NativeThreadLinux::NativeThreadLinux(NativeProcessLinux &process,
92                                      lldb::tid_t tid)
93     : NativeThreadProtocol(process, tid), m_state(StateType::eStateInvalid),
94       m_stop_info(),
95       m_reg_context_up(
96           NativeRegisterContextLinux::CreateHostNativeRegisterContextLinux(
97               process.GetArchitecture(), *this)),
98       m_stop_description() {}
99 
100 std::string NativeThreadLinux::GetName() {
101   NativeProcessLinux &process = GetProcess();
102 
103   auto BufferOrError = getProcFile(process.GetID(), GetID(), "comm");
104   if (!BufferOrError)
105     return "";
106   return std::string(BufferOrError.get()->getBuffer().rtrim('\n'));
107 }
108 
109 lldb::StateType NativeThreadLinux::GetState() { return m_state; }
110 
111 bool NativeThreadLinux::GetStopReason(ThreadStopInfo &stop_info,
112                                       std::string &description) {
113   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
114 
115   description.clear();
116 
117   switch (m_state) {
118   case eStateStopped:
119   case eStateCrashed:
120   case eStateExited:
121   case eStateSuspended:
122   case eStateUnloaded:
123     if (log)
124       LogThreadStopInfo(*log, m_stop_info, "m_stop_info in thread:");
125     stop_info = m_stop_info;
126     description = m_stop_description;
127     if (log)
128       LogThreadStopInfo(*log, stop_info, "returned stop_info:");
129 
130     return true;
131 
132   case eStateInvalid:
133   case eStateConnected:
134   case eStateAttaching:
135   case eStateLaunching:
136   case eStateRunning:
137   case eStateStepping:
138   case eStateDetached:
139     if (log) {
140       LLDB_LOGF(log,
141                 "NativeThreadLinux::%s tid %" PRIu64
142                 " in state %s cannot answer stop reason",
143                 __FUNCTION__, GetID(), StateAsCString(m_state));
144     }
145     return false;
146   }
147   llvm_unreachable("unhandled StateType!");
148 }
149 
150 Status NativeThreadLinux::SetWatchpoint(lldb::addr_t addr, size_t size,
151                                         uint32_t watch_flags, bool hardware) {
152   if (!hardware)
153     return Status("not implemented");
154   if (m_state == eStateLaunching)
155     return Status();
156   Status error = RemoveWatchpoint(addr);
157   if (error.Fail())
158     return error;
159   uint32_t wp_index =
160       m_reg_context_up->SetHardwareWatchpoint(addr, size, watch_flags);
161   if (wp_index == LLDB_INVALID_INDEX32)
162     return Status("Setting hardware watchpoint failed.");
163   m_watchpoint_index_map.insert({addr, wp_index});
164   return Status();
165 }
166 
167 Status NativeThreadLinux::RemoveWatchpoint(lldb::addr_t addr) {
168   auto wp = m_watchpoint_index_map.find(addr);
169   if (wp == m_watchpoint_index_map.end())
170     return Status();
171   uint32_t wp_index = wp->second;
172   m_watchpoint_index_map.erase(wp);
173   if (m_reg_context_up->ClearHardwareWatchpoint(wp_index))
174     return Status();
175   return Status("Clearing hardware watchpoint failed.");
176 }
177 
178 Status NativeThreadLinux::SetHardwareBreakpoint(lldb::addr_t addr,
179                                                 size_t size) {
180   if (m_state == eStateLaunching)
181     return Status();
182 
183   Status error = RemoveHardwareBreakpoint(addr);
184   if (error.Fail())
185     return error;
186 
187   uint32_t bp_index = m_reg_context_up->SetHardwareBreakpoint(addr, size);
188 
189   if (bp_index == LLDB_INVALID_INDEX32)
190     return Status("Setting hardware breakpoint failed.");
191 
192   m_hw_break_index_map.insert({addr, bp_index});
193   return Status();
194 }
195 
196 Status NativeThreadLinux::RemoveHardwareBreakpoint(lldb::addr_t addr) {
197   auto bp = m_hw_break_index_map.find(addr);
198   if (bp == m_hw_break_index_map.end())
199     return Status();
200 
201   uint32_t bp_index = bp->second;
202   if (m_reg_context_up->ClearHardwareBreakpoint(bp_index)) {
203     m_hw_break_index_map.erase(bp);
204     return Status();
205   }
206 
207   return Status("Clearing hardware breakpoint failed.");
208 }
209 
210 Status NativeThreadLinux::Resume(uint32_t signo) {
211   const StateType new_state = StateType::eStateRunning;
212   MaybeLogStateChange(new_state);
213   m_state = new_state;
214 
215   m_stop_info.reason = StopReason::eStopReasonNone;
216   m_stop_description.clear();
217 
218   // If watchpoints have been set, but none on this thread, then this is a new
219   // thread. So set all existing watchpoints.
220   if (m_watchpoint_index_map.empty()) {
221     NativeProcessLinux &process = GetProcess();
222 
223     const auto &watchpoint_map = process.GetWatchpointMap();
224     m_reg_context_up->ClearAllHardwareWatchpoints();
225     for (const auto &pair : watchpoint_map) {
226       const auto &wp = pair.second;
227       SetWatchpoint(wp.m_addr, wp.m_size, wp.m_watch_flags, wp.m_hardware);
228     }
229   }
230 
231   // Set all active hardware breakpoint on all threads.
232   if (m_hw_break_index_map.empty()) {
233     NativeProcessLinux &process = GetProcess();
234 
235     const auto &hw_breakpoint_map = process.GetHardwareBreakpointMap();
236     m_reg_context_up->ClearAllHardwareBreakpoints();
237     for (const auto &pair : hw_breakpoint_map) {
238       const auto &bp = pair.second;
239       SetHardwareBreakpoint(bp.m_addr, bp.m_size);
240     }
241   }
242 
243   intptr_t data = 0;
244 
245   if (signo != LLDB_INVALID_SIGNAL_NUMBER)
246     data = signo;
247 
248   return NativeProcessLinux::PtraceWrapper(PTRACE_CONT, GetID(), nullptr,
249                                            reinterpret_cast<void *>(data));
250 }
251 
252 Status NativeThreadLinux::SingleStep(uint32_t signo) {
253   const StateType new_state = StateType::eStateStepping;
254   MaybeLogStateChange(new_state);
255   m_state = new_state;
256   m_stop_info.reason = StopReason::eStopReasonNone;
257 
258   if(!m_step_workaround) {
259     // If we already hava a workaround inplace, don't reset it. Otherwise, the
260     // destructor of the existing instance will run after the new instance has
261     // fetched the cpu mask, and the thread will end up with the wrong mask.
262     m_step_workaround = SingleStepWorkaround::Get(m_tid);
263   }
264 
265   intptr_t data = 0;
266   if (signo != LLDB_INVALID_SIGNAL_NUMBER)
267     data = signo;
268 
269   // If hardware single-stepping is not supported, we just do a continue. The
270   // breakpoint on the next instruction has been setup in
271   // NativeProcessLinux::Resume.
272   return NativeProcessLinux::PtraceWrapper(
273       GetProcess().SupportHardwareSingleStepping() ? PTRACE_SINGLESTEP
274                                                    : PTRACE_CONT,
275       m_tid, nullptr, reinterpret_cast<void *>(data));
276 }
277 
278 void NativeThreadLinux::SetStoppedBySignal(uint32_t signo,
279                                            const siginfo_t *info) {
280   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
281   LLDB_LOGF(log, "NativeThreadLinux::%s called with signal 0x%02" PRIx32,
282             __FUNCTION__, signo);
283 
284   SetStopped();
285 
286   m_stop_info.reason = StopReason::eStopReasonSignal;
287   m_stop_info.details.signal.signo = signo;
288 
289   m_stop_description.clear();
290   if (info) {
291     switch (signo) {
292     case SIGSEGV:
293     case SIGBUS:
294     case SIGFPE:
295     case SIGILL:
296       // In case of MIPS64 target, SI_KERNEL is generated for invalid 64bit
297       // address.
298       const auto reason =
299           (info->si_signo == SIGBUS && info->si_code == SI_KERNEL)
300               ? CrashReason::eInvalidAddress
301               : GetCrashReason(*info);
302       m_stop_description = GetCrashReasonString(reason, *info);
303 
304       if (reason == CrashReason::eSyncTagCheckFault) {
305         AnnotateSyncTagCheckFault(info);
306       }
307 
308       break;
309     }
310   }
311 }
312 
313 void NativeThreadLinux::AnnotateSyncTagCheckFault(const siginfo_t *info) {
314   int32_t allocation_tag_type = 0;
315   switch (GetProcess().GetArchitecture().GetMachine()) {
316   // aarch64_32 deliberately not here because there's no 32 bit MTE
317   case llvm::Triple::aarch64:
318   case llvm::Triple::aarch64_be:
319     allocation_tag_type = MemoryTagManagerAArch64MTE::eMTE_allocation;
320     break;
321   default:
322     return;
323   }
324 
325   auto details =
326       GetRegisterContext().GetMemoryTaggingDetails(allocation_tag_type);
327   if (!details) {
328     llvm::consumeError(details.takeError());
329     return;
330   }
331 
332   // We assume that the stop description is currently:
333   // signal SIGSEGV: sync tag check fault (fault address: <addr>)
334   // Remove the closing )
335   m_stop_description.pop_back();
336 
337   std::stringstream ss;
338   lldb::addr_t fault_addr = reinterpret_cast<uintptr_t>(info->si_addr);
339   std::unique_ptr<MemoryTagManager> manager(std::move(details->manager));
340 
341   ss << " logical tag: 0x" << std::hex << manager->GetLogicalTag(fault_addr);
342 
343   std::vector<uint8_t> allocation_tag_data;
344   // The fault address may not be granule aligned. ReadMemoryTags will granule
345   // align any range you give it, potentially making it larger.
346   // To prevent this set len to 1. This always results in a range that is at
347   // most 1 granule in size and includes fault_addr.
348   Status status = GetProcess().ReadMemoryTags(allocation_tag_type, fault_addr,
349                                               1, allocation_tag_data);
350 
351   if (status.Success()) {
352     llvm::Expected<std::vector<lldb::addr_t>> allocation_tag =
353         manager->UnpackTagsData(allocation_tag_data, 1);
354     if (allocation_tag) {
355       ss << " allocation tag: 0x" << std::hex << allocation_tag->front() << ")";
356     } else {
357       llvm::consumeError(allocation_tag.takeError());
358       ss << ")";
359     }
360   } else
361     ss << ")";
362 
363   m_stop_description += ss.str();
364 }
365 
366 bool NativeThreadLinux::IsStopped(int *signo) {
367   if (!StateIsStoppedState(m_state, false))
368     return false;
369 
370   // If we are stopped by a signal, return the signo.
371   if (signo && m_state == StateType::eStateStopped &&
372       m_stop_info.reason == StopReason::eStopReasonSignal) {
373     *signo = m_stop_info.details.signal.signo;
374   }
375 
376   // Regardless, we are stopped.
377   return true;
378 }
379 
380 void NativeThreadLinux::SetStopped() {
381   if (m_state == StateType::eStateStepping)
382     m_step_workaround.reset();
383 
384   // On every stop, clear any cached register data structures
385   GetRegisterContext().InvalidateAllRegisters();
386 
387   const StateType new_state = StateType::eStateStopped;
388   MaybeLogStateChange(new_state);
389   m_state = new_state;
390   m_stop_description.clear();
391 }
392 
393 void NativeThreadLinux::SetStoppedByExec() {
394   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
395   LLDB_LOGF(log, "NativeThreadLinux::%s()", __FUNCTION__);
396 
397   SetStopped();
398 
399   m_stop_info.reason = StopReason::eStopReasonExec;
400   m_stop_info.details.signal.signo = SIGSTOP;
401 }
402 
403 void NativeThreadLinux::SetStoppedByBreakpoint() {
404   SetStopped();
405 
406   m_stop_info.reason = StopReason::eStopReasonBreakpoint;
407   m_stop_info.details.signal.signo = SIGTRAP;
408   m_stop_description.clear();
409 }
410 
411 void NativeThreadLinux::SetStoppedByWatchpoint(uint32_t wp_index) {
412   SetStopped();
413 
414   lldbassert(wp_index != LLDB_INVALID_INDEX32 && "wp_index cannot be invalid");
415 
416   std::ostringstream ostr;
417   ostr << m_reg_context_up->GetWatchpointAddress(wp_index) << " ";
418   ostr << wp_index;
419 
420   /*
421    * MIPS: Last 3bits of the watchpoint address are masked by the kernel. For
422    * example:
423    * 'n' is at 0x120010d00 and 'm' is 0x120010d04. When a watchpoint is set at
424    * 'm', then
425    * watch exception is generated even when 'n' is read/written. To handle this
426    * case,
427    * find the base address of the load/store instruction and append it in the
428    * stop-info
429    * packet.
430   */
431   ostr << " " << m_reg_context_up->GetWatchpointHitAddress(wp_index);
432 
433   m_stop_description = ostr.str();
434 
435   m_stop_info.reason = StopReason::eStopReasonWatchpoint;
436   m_stop_info.details.signal.signo = SIGTRAP;
437 }
438 
439 bool NativeThreadLinux::IsStoppedAtBreakpoint() {
440   return GetState() == StateType::eStateStopped &&
441          m_stop_info.reason == StopReason::eStopReasonBreakpoint;
442 }
443 
444 bool NativeThreadLinux::IsStoppedAtWatchpoint() {
445   return GetState() == StateType::eStateStopped &&
446          m_stop_info.reason == StopReason::eStopReasonWatchpoint;
447 }
448 
449 void NativeThreadLinux::SetStoppedByTrace() {
450   SetStopped();
451 
452   m_stop_info.reason = StopReason::eStopReasonTrace;
453   m_stop_info.details.signal.signo = SIGTRAP;
454 }
455 
456 void NativeThreadLinux::SetStoppedByFork(bool is_vfork, lldb::pid_t child_pid) {
457   SetStopped();
458 
459   m_stop_info.reason =
460       is_vfork ? StopReason::eStopReasonVFork : StopReason::eStopReasonFork;
461   m_stop_info.details.fork.child_pid = child_pid;
462   m_stop_info.details.fork.child_tid = child_pid;
463 }
464 
465 void NativeThreadLinux::SetStoppedByVForkDone() {
466   SetStopped();
467 
468   m_stop_info.reason = StopReason::eStopReasonVForkDone;
469 }
470 
471 void NativeThreadLinux::SetStoppedWithNoReason() {
472   SetStopped();
473 
474   m_stop_info.reason = StopReason::eStopReasonNone;
475   m_stop_info.details.signal.signo = 0;
476 }
477 
478 void NativeThreadLinux::SetStoppedByProcessorTrace(
479     llvm::StringRef description) {
480   SetStopped();
481 
482   m_stop_info.reason = StopReason::eStopReasonProcessorTrace;
483   m_stop_info.details.signal.signo = 0;
484   m_stop_description = description.str();
485 }
486 
487 void NativeThreadLinux::SetExited() {
488   const StateType new_state = StateType::eStateExited;
489   MaybeLogStateChange(new_state);
490   m_state = new_state;
491 
492   m_stop_info.reason = StopReason::eStopReasonThreadExiting;
493 }
494 
495 Status NativeThreadLinux::RequestStop() {
496   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
497 
498   NativeProcessLinux &process = GetProcess();
499 
500   lldb::pid_t pid = process.GetID();
501   lldb::tid_t tid = GetID();
502 
503   LLDB_LOGF(log,
504             "NativeThreadLinux::%s requesting thread stop(pid: %" PRIu64
505             ", tid: %" PRIu64 ")",
506             __FUNCTION__, pid, tid);
507 
508   Status err;
509   errno = 0;
510   if (::tgkill(pid, tid, SIGSTOP) != 0) {
511     err.SetErrorToErrno();
512     LLDB_LOGF(log,
513               "NativeThreadLinux::%s tgkill(%" PRIu64 ", %" PRIu64
514               ", SIGSTOP) failed: %s",
515               __FUNCTION__, pid, tid, err.AsCString());
516   }
517 
518   return err;
519 }
520 
521 void NativeThreadLinux::MaybeLogStateChange(lldb::StateType new_state) {
522   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
523   // If we're not logging, we're done.
524   if (!log)
525     return;
526 
527   // If this is a state change to the same state, we're done.
528   lldb::StateType old_state = m_state;
529   if (new_state == old_state)
530     return;
531 
532   LLDB_LOG(log, "pid={0}, tid={1}: changing from state {2} to {3}",
533            m_process.GetID(), GetID(), old_state, new_state);
534 }
535 
536 NativeProcessLinux &NativeThreadLinux::GetProcess() {
537   return static_cast<NativeProcessLinux &>(m_process);
538 }
539