1 //===-- NativeThreadLinux.cpp --------------------------------- -*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "NativeThreadLinux.h"
11 
12 #include <signal.h>
13 #include <sstream>
14 
15 #include "NativeProcessLinux.h"
16 #include "NativeRegisterContextLinux.h"
17 #include "SingleStepCheck.h"
18 
19 #include "lldb/Core/State.h"
20 #include "lldb/Host/HostNativeThread.h"
21 #include "lldb/Host/linux/Ptrace.h"
22 #include "lldb/Host/linux/Support.h"
23 #include "lldb/Utility/LLDBAssert.h"
24 #include "lldb/Utility/Log.h"
25 #include "lldb/lldb-enumerations.h"
26 
27 #include "llvm/ADT/SmallString.h"
28 
29 #include "Plugins/Process/POSIX/CrashReason.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   default:
82     log.Printf("%s: %s invalid stop reason %" PRIu32, __FUNCTION__, header,
83                static_cast<uint32_t>(stop_info.reason));
84   }
85 }
86 }
87 
88 NativeThreadLinux::NativeThreadLinux(NativeProcessLinux &process,
89                                      lldb::tid_t tid)
90     : NativeThreadProtocol(process, tid), m_state(StateType::eStateInvalid),
91       m_stop_info(), m_reg_context_sp(), m_stop_description() {}
92 
93 std::string NativeThreadLinux::GetName() {
94   NativeProcessLinux &process = GetProcess();
95 
96   auto BufferOrError = getProcFile(process.GetID(), GetID(), "comm");
97   if (!BufferOrError)
98     return "";
99   return BufferOrError.get()->getBuffer().rtrim('\n');
100 }
101 
102 lldb::StateType NativeThreadLinux::GetState() { return m_state; }
103 
104 bool NativeThreadLinux::GetStopReason(ThreadStopInfo &stop_info,
105                                       std::string &description) {
106   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
107 
108   description.clear();
109 
110   switch (m_state) {
111   case eStateStopped:
112   case eStateCrashed:
113   case eStateExited:
114   case eStateSuspended:
115   case eStateUnloaded:
116     if (log)
117       LogThreadStopInfo(*log, m_stop_info, "m_stop_info in thread:");
118     stop_info = m_stop_info;
119     description = m_stop_description;
120     if (log)
121       LogThreadStopInfo(*log, stop_info, "returned stop_info:");
122 
123     return true;
124 
125   case eStateInvalid:
126   case eStateConnected:
127   case eStateAttaching:
128   case eStateLaunching:
129   case eStateRunning:
130   case eStateStepping:
131   case eStateDetached:
132     if (log) {
133       log->Printf("NativeThreadLinux::%s tid %" PRIu64
134                   " in state %s cannot answer stop reason",
135                   __FUNCTION__, GetID(), StateAsCString(m_state));
136     }
137     return false;
138   }
139   llvm_unreachable("unhandled StateType!");
140 }
141 
142 NativeRegisterContextSP NativeThreadLinux::GetRegisterContext() {
143   // Return the register context if we already created it.
144   if (m_reg_context_sp)
145     return m_reg_context_sp;
146 
147   ArchSpec target_arch;
148   if (!m_process.GetArchitecture(target_arch))
149     return NativeRegisterContextSP();
150 
151   const uint32_t concrete_frame_idx = 0;
152   m_reg_context_sp.reset(
153       NativeRegisterContextLinux::CreateHostNativeRegisterContextLinux(
154           target_arch, *this, concrete_frame_idx));
155 
156   return m_reg_context_sp;
157 }
158 
159 Status NativeThreadLinux::SetWatchpoint(lldb::addr_t addr, size_t size,
160                                         uint32_t watch_flags, bool hardware) {
161   if (!hardware)
162     return Status("not implemented");
163   if (m_state == eStateLaunching)
164     return Status();
165   Status error = RemoveWatchpoint(addr);
166   if (error.Fail())
167     return error;
168   NativeRegisterContextSP reg_ctx = GetRegisterContext();
169   uint32_t wp_index = reg_ctx->SetHardwareWatchpoint(addr, size, watch_flags);
170   if (wp_index == LLDB_INVALID_INDEX32)
171     return Status("Setting hardware watchpoint failed.");
172   m_watchpoint_index_map.insert({addr, wp_index});
173   return Status();
174 }
175 
176 Status NativeThreadLinux::RemoveWatchpoint(lldb::addr_t addr) {
177   auto wp = m_watchpoint_index_map.find(addr);
178   if (wp == m_watchpoint_index_map.end())
179     return Status();
180   uint32_t wp_index = wp->second;
181   m_watchpoint_index_map.erase(wp);
182   if (GetRegisterContext()->ClearHardwareWatchpoint(wp_index))
183     return Status();
184   return Status("Clearing hardware watchpoint failed.");
185 }
186 
187 Status NativeThreadLinux::SetHardwareBreakpoint(lldb::addr_t addr,
188                                                 size_t size) {
189   if (m_state == eStateLaunching)
190     return Status();
191 
192   Status error = RemoveHardwareBreakpoint(addr);
193   if (error.Fail())
194     return error;
195 
196   NativeRegisterContextSP reg_ctx = GetRegisterContext();
197   uint32_t bp_index = reg_ctx->SetHardwareBreakpoint(addr, size);
198 
199   if (bp_index == LLDB_INVALID_INDEX32)
200     return Status("Setting hardware breakpoint failed.");
201 
202   m_hw_break_index_map.insert({addr, bp_index});
203   return Status();
204 }
205 
206 Status NativeThreadLinux::RemoveHardwareBreakpoint(lldb::addr_t addr) {
207   auto bp = m_hw_break_index_map.find(addr);
208   if (bp == m_hw_break_index_map.end())
209     return Status();
210 
211   uint32_t bp_index = bp->second;
212   if (GetRegisterContext()->ClearHardwareBreakpoint(bp_index)) {
213     m_hw_break_index_map.erase(bp);
214     return Status();
215   }
216 
217   return Status("Clearing hardware breakpoint failed.");
218 }
219 
220 Status NativeThreadLinux::Resume(uint32_t signo) {
221   const StateType new_state = StateType::eStateRunning;
222   MaybeLogStateChange(new_state);
223   m_state = new_state;
224 
225   m_stop_info.reason = StopReason::eStopReasonNone;
226   m_stop_description.clear();
227 
228   // If watchpoints have been set, but none on this thread,
229   // then this is a new thread. So set all existing watchpoints.
230   if (m_watchpoint_index_map.empty()) {
231     NativeProcessLinux &process = GetProcess();
232 
233     const auto &watchpoint_map = process.GetWatchpointMap();
234     GetRegisterContext()->ClearAllHardwareWatchpoints();
235     for (const auto &pair : watchpoint_map) {
236       const auto &wp = pair.second;
237       SetWatchpoint(wp.m_addr, wp.m_size, wp.m_watch_flags, wp.m_hardware);
238     }
239   }
240 
241   // Set all active hardware breakpoint on all threads.
242   if (m_hw_break_index_map.empty()) {
243     NativeProcessLinux &process = GetProcess();
244 
245     const auto &hw_breakpoint_map = process.GetHardwareBreakpointMap();
246     GetRegisterContext()->ClearAllHardwareBreakpoints();
247     for (const auto &pair : hw_breakpoint_map) {
248       const auto &bp = pair.second;
249       SetHardwareBreakpoint(bp.m_addr, bp.m_size);
250     }
251   }
252 
253   intptr_t data = 0;
254 
255   if (signo != LLDB_INVALID_SIGNAL_NUMBER)
256     data = signo;
257 
258   return NativeProcessLinux::PtraceWrapper(PTRACE_CONT, GetID(), nullptr,
259                                            reinterpret_cast<void *>(data));
260 }
261 
262 Status NativeThreadLinux::SingleStep(uint32_t signo) {
263   const StateType new_state = StateType::eStateStepping;
264   MaybeLogStateChange(new_state);
265   m_state = new_state;
266   m_stop_info.reason = StopReason::eStopReasonNone;
267 
268   if(!m_step_workaround) {
269     // If we already hava a workaround inplace, don't reset it. Otherwise, the
270     // destructor of the existing instance will run after the new instance has
271     // fetched the cpu mask, and the thread will end up with the wrong mask.
272     m_step_workaround = SingleStepWorkaround::Get(m_tid);
273   }
274 
275   intptr_t data = 0;
276   if (signo != LLDB_INVALID_SIGNAL_NUMBER)
277     data = signo;
278 
279   // If hardware single-stepping is not supported, we just do a continue. The
280   // breakpoint on the
281   // next instruction has been setup in NativeProcessLinux::Resume.
282   return NativeProcessLinux::PtraceWrapper(
283       GetProcess().SupportHardwareSingleStepping() ? PTRACE_SINGLESTEP
284                                                    : PTRACE_CONT,
285       m_tid, nullptr, reinterpret_cast<void *>(data));
286 }
287 
288 void NativeThreadLinux::SetStoppedBySignal(uint32_t signo,
289                                            const siginfo_t *info) {
290   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
291   if (log)
292     log->Printf("NativeThreadLinux::%s called with signal 0x%02" PRIx32,
293                 __FUNCTION__, signo);
294 
295   SetStopped();
296 
297   m_stop_info.reason = StopReason::eStopReasonSignal;
298   m_stop_info.details.signal.signo = signo;
299 
300   m_stop_description.clear();
301   if (info) {
302     switch (signo) {
303     case SIGSEGV:
304     case SIGBUS:
305     case SIGFPE:
306     case SIGILL:
307       // In case of MIPS64 target, SI_KERNEL is generated for invalid 64bit
308       // address.
309       const auto reason =
310           (info->si_signo == SIGBUS && info->si_code == SI_KERNEL)
311               ? CrashReason::eInvalidAddress
312               : GetCrashReason(*info);
313       m_stop_description = GetCrashReasonString(reason, *info);
314       break;
315     }
316   }
317 }
318 
319 bool NativeThreadLinux::IsStopped(int *signo) {
320   if (!StateIsStoppedState(m_state, false))
321     return false;
322 
323   // If we are stopped by a signal, return the signo.
324   if (signo && m_state == StateType::eStateStopped &&
325       m_stop_info.reason == StopReason::eStopReasonSignal) {
326     *signo = m_stop_info.details.signal.signo;
327   }
328 
329   // Regardless, we are stopped.
330   return true;
331 }
332 
333 void NativeThreadLinux::SetStopped() {
334   if (m_state == StateType::eStateStepping)
335     m_step_workaround.reset();
336 
337   const StateType new_state = StateType::eStateStopped;
338   MaybeLogStateChange(new_state);
339   m_state = new_state;
340   m_stop_description.clear();
341 }
342 
343 void NativeThreadLinux::SetStoppedByExec() {
344   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
345   if (log)
346     log->Printf("NativeThreadLinux::%s()", __FUNCTION__);
347 
348   SetStopped();
349 
350   m_stop_info.reason = StopReason::eStopReasonExec;
351   m_stop_info.details.signal.signo = SIGSTOP;
352 }
353 
354 void NativeThreadLinux::SetStoppedByBreakpoint() {
355   SetStopped();
356 
357   m_stop_info.reason = StopReason::eStopReasonBreakpoint;
358   m_stop_info.details.signal.signo = SIGTRAP;
359   m_stop_description.clear();
360 }
361 
362 void NativeThreadLinux::SetStoppedByWatchpoint(uint32_t wp_index) {
363   SetStopped();
364 
365   lldbassert(wp_index != LLDB_INVALID_INDEX32 && "wp_index cannot be invalid");
366 
367   std::ostringstream ostr;
368   ostr << GetRegisterContext()->GetWatchpointAddress(wp_index) << " ";
369   ostr << wp_index;
370 
371   /*
372    * MIPS: Last 3bits of the watchpoint address are masked by the kernel. For
373    * example:
374    * 'n' is at 0x120010d00 and 'm' is 0x120010d04. When a watchpoint is set at
375    * 'm', then
376    * watch exception is generated even when 'n' is read/written. To handle this
377    * case,
378    * find the base address of the load/store instruction and append it in the
379    * stop-info
380    * packet.
381   */
382   ostr << " " << GetRegisterContext()->GetWatchpointHitAddress(wp_index);
383 
384   m_stop_description = ostr.str();
385 
386   m_stop_info.reason = StopReason::eStopReasonWatchpoint;
387   m_stop_info.details.signal.signo = SIGTRAP;
388 }
389 
390 bool NativeThreadLinux::IsStoppedAtBreakpoint() {
391   return GetState() == StateType::eStateStopped &&
392          m_stop_info.reason == StopReason::eStopReasonBreakpoint;
393 }
394 
395 bool NativeThreadLinux::IsStoppedAtWatchpoint() {
396   return GetState() == StateType::eStateStopped &&
397          m_stop_info.reason == StopReason::eStopReasonWatchpoint;
398 }
399 
400 void NativeThreadLinux::SetStoppedByTrace() {
401   SetStopped();
402 
403   m_stop_info.reason = StopReason::eStopReasonTrace;
404   m_stop_info.details.signal.signo = SIGTRAP;
405 }
406 
407 void NativeThreadLinux::SetStoppedWithNoReason() {
408   SetStopped();
409 
410   m_stop_info.reason = StopReason::eStopReasonNone;
411   m_stop_info.details.signal.signo = 0;
412 }
413 
414 void NativeThreadLinux::SetExited() {
415   const StateType new_state = StateType::eStateExited;
416   MaybeLogStateChange(new_state);
417   m_state = new_state;
418 
419   m_stop_info.reason = StopReason::eStopReasonThreadExiting;
420 }
421 
422 Status NativeThreadLinux::RequestStop() {
423   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
424 
425   NativeProcessLinux &process = GetProcess();
426 
427   lldb::pid_t pid = process.GetID();
428   lldb::tid_t tid = GetID();
429 
430   if (log)
431     log->Printf("NativeThreadLinux::%s requesting thread stop(pid: %" PRIu64
432                 ", tid: %" PRIu64 ")",
433                 __FUNCTION__, pid, tid);
434 
435   Status err;
436   errno = 0;
437   if (::tgkill(pid, tid, SIGSTOP) != 0) {
438     err.SetErrorToErrno();
439     if (log)
440       log->Printf("NativeThreadLinux::%s tgkill(%" PRIu64 ", %" PRIu64
441                   ", SIGSTOP) failed: %s",
442                   __FUNCTION__, pid, tid, err.AsCString());
443   }
444 
445   return err;
446 }
447 
448 void NativeThreadLinux::MaybeLogStateChange(lldb::StateType new_state) {
449   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
450   // If we're not logging, we're done.
451   if (!log)
452     return;
453 
454   // If this is a state change to the same state, we're done.
455   lldb::StateType old_state = m_state;
456   if (new_state == old_state)
457     return;
458 
459   LLDB_LOG(log, "pid={0}, tid={1}: changing from state {2} to {3}",
460            m_process.GetID(), GetID(), old_state, new_state);
461 }
462 
463 NativeProcessLinux &NativeThreadLinux::GetProcess() {
464   return static_cast<NativeProcessLinux &>(m_process);
465 }
466