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 
18 #include "lldb/Core/Log.h"
19 #include "lldb/Core/State.h"
20 #include "lldb/Host/HostNativeThread.h"
21 #include "lldb/Utility/LLDBAssert.h"
22 #include "lldb/lldb-enumerations.h"
23 
24 #include "llvm/ADT/SmallString.h"
25 
26 #include "Plugins/Process/POSIX/CrashReason.h"
27 
28 #include <sys/syscall.h>
29 // Try to define a macro to encapsulate the tgkill syscall
30 #define tgkill(pid, tid, sig) \
31     syscall(SYS_tgkill, static_cast< ::pid_t>(pid), static_cast< ::pid_t>(tid), sig)
32 
33 using namespace lldb;
34 using namespace lldb_private;
35 using namespace lldb_private::process_linux;
36 
37 namespace
38 {
39     void LogThreadStopInfo (Log &log, const ThreadStopInfo &stop_info, const char *const header)
40     {
41         switch (stop_info.reason)
42         {
43             case eStopReasonNone:
44                 log.Printf ("%s: %s no stop reason", __FUNCTION__, header);
45                 return;
46             case eStopReasonTrace:
47                 log.Printf ("%s: %s trace, stopping signal 0x%" PRIx32, __FUNCTION__, header, stop_info.details.signal.signo);
48                 return;
49             case eStopReasonBreakpoint:
50                 log.Printf ("%s: %s breakpoint, stopping signal 0x%" PRIx32, __FUNCTION__, header, stop_info.details.signal.signo);
51                 return;
52             case eStopReasonWatchpoint:
53                 log.Printf ("%s: %s watchpoint, stopping signal 0x%" PRIx32, __FUNCTION__, header, stop_info.details.signal.signo);
54                 return;
55             case eStopReasonSignal:
56                 log.Printf ("%s: %s signal 0x%02" PRIx32, __FUNCTION__, header, stop_info.details.signal.signo);
57                 return;
58             case eStopReasonException:
59                 log.Printf ("%s: %s exception type 0x%02" PRIx64, __FUNCTION__, header, stop_info.details.exception.type);
60                 return;
61             case eStopReasonExec:
62                 log.Printf ("%s: %s exec, stopping signal 0x%" PRIx32, __FUNCTION__, header, stop_info.details.signal.signo);
63                 return;
64             case eStopReasonPlanComplete:
65                 log.Printf ("%s: %s plan complete", __FUNCTION__, header);
66                 return;
67             case eStopReasonThreadExiting:
68                 log.Printf ("%s: %s thread exiting", __FUNCTION__, header);
69                 return;
70             case eStopReasonInstrumentation:
71                 log.Printf ("%s: %s instrumentation", __FUNCTION__, header);
72                 return;
73             default:
74                 log.Printf ("%s: %s invalid stop reason %" PRIu32, __FUNCTION__, header, static_cast<uint32_t> (stop_info.reason));
75         }
76     }
77 }
78 
79 NativeThreadLinux::NativeThreadLinux (NativeProcessLinux *process, lldb::tid_t tid) :
80     NativeThreadProtocol (process, tid),
81     m_state (StateType::eStateInvalid),
82     m_stop_info (),
83     m_reg_context_sp (),
84     m_stop_description ()
85 {
86 }
87 
88 std::string
89 NativeThreadLinux::GetName()
90 {
91     NativeProcessProtocolSP process_sp = m_process_wp.lock ();
92     if (!process_sp)
93         return "<unknown: no process>";
94 
95     // const NativeProcessLinux *const process = reinterpret_cast<NativeProcessLinux*> (process_sp->get ());
96     llvm::SmallString<32> thread_name;
97     HostNativeThread::GetName(GetID(), thread_name);
98     return thread_name.c_str();
99 }
100 
101 lldb::StateType
102 NativeThreadLinux::GetState ()
103 {
104     return m_state;
105 }
106 
107 
108 bool
109 NativeThreadLinux::GetStopReason (ThreadStopInfo &stop_info, std::string& description)
110 {
111     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
112 
113     description.clear();
114 
115     switch (m_state)
116     {
117     case eStateStopped:
118     case eStateCrashed:
119     case eStateExited:
120     case eStateSuspended:
121     case eStateUnloaded:
122         if (log)
123             LogThreadStopInfo (*log, m_stop_info, "m_stop_info in thread:");
124         stop_info = m_stop_info;
125         description = m_stop_description;
126         if (log)
127             LogThreadStopInfo (*log, stop_info, "returned stop_info:");
128 
129         return true;
130 
131     case eStateInvalid:
132     case eStateConnected:
133     case eStateAttaching:
134     case eStateLaunching:
135     case eStateRunning:
136     case eStateStepping:
137     case eStateDetached:
138         if (log)
139         {
140             log->Printf ("NativeThreadLinux::%s tid %" PRIu64 " in state %s cannot answer stop reason",
141                     __FUNCTION__, GetID (), StateAsCString (m_state));
142         }
143         return false;
144     }
145     llvm_unreachable("unhandled StateType!");
146 }
147 
148 NativeRegisterContextSP
149 NativeThreadLinux::GetRegisterContext ()
150 {
151     // Return the register context if we already created it.
152     if (m_reg_context_sp)
153         return m_reg_context_sp;
154 
155     NativeProcessProtocolSP m_process_sp = m_process_wp.lock ();
156     if (!m_process_sp)
157         return NativeRegisterContextSP ();
158 
159     ArchSpec target_arch;
160     if (!m_process_sp->GetArchitecture (target_arch))
161         return NativeRegisterContextSP ();
162 
163     const uint32_t concrete_frame_idx = 0;
164     m_reg_context_sp.reset (NativeRegisterContextLinux::CreateHostNativeRegisterContextLinux(target_arch,
165                                                                                              *this,
166                                                                                              concrete_frame_idx));
167 
168     return m_reg_context_sp;
169 }
170 
171 Error
172 NativeThreadLinux::SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware)
173 {
174     if (!hardware)
175         return Error ("not implemented");
176     if (m_state == eStateLaunching)
177         return Error ();
178     Error error = RemoveWatchpoint(addr);
179     if (error.Fail()) return error;
180     NativeRegisterContextSP reg_ctx = GetRegisterContext ();
181     uint32_t wp_index =
182         reg_ctx->SetHardwareWatchpoint (addr, size, watch_flags);
183     if (wp_index == LLDB_INVALID_INDEX32)
184         return Error ("Setting hardware watchpoint failed.");
185     m_watchpoint_index_map.insert({addr, wp_index});
186     return Error ();
187 }
188 
189 Error
190 NativeThreadLinux::RemoveWatchpoint (lldb::addr_t addr)
191 {
192     auto wp = m_watchpoint_index_map.find(addr);
193     if (wp == m_watchpoint_index_map.end())
194         return Error ();
195     uint32_t wp_index = wp->second;
196     m_watchpoint_index_map.erase(wp);
197     if (GetRegisterContext()->ClearHardwareWatchpoint(wp_index))
198         return Error ();
199     return Error ("Clearing hardware watchpoint failed.");
200 }
201 
202 void
203 NativeThreadLinux::SetRunning ()
204 {
205     const StateType new_state = StateType::eStateRunning;
206     MaybeLogStateChange (new_state);
207     m_state = new_state;
208 
209     m_stop_info.reason = StopReason::eStopReasonNone;
210     m_stop_description.clear();
211 
212     // If watchpoints have been set, but none on this thread,
213     // then this is a new thread. So set all existing watchpoints.
214     if (m_watchpoint_index_map.empty())
215     {
216         const auto process_sp = GetProcess();
217         if (process_sp)
218         {
219             const auto &watchpoint_map = process_sp->GetWatchpointMap();
220             if (watchpoint_map.empty()) return;
221             GetRegisterContext()->ClearAllHardwareWatchpoints();
222             for (const auto &pair : watchpoint_map)
223             {
224                 const auto& wp = pair.second;
225                 SetWatchpoint(wp.m_addr, wp.m_size, wp.m_watch_flags, wp.m_hardware);
226             }
227         }
228     }
229 }
230 
231 void
232 NativeThreadLinux::SetStepping ()
233 {
234     const StateType new_state = StateType::eStateStepping;
235     MaybeLogStateChange (new_state);
236     m_state = new_state;
237 
238     m_stop_info.reason = StopReason::eStopReasonNone;
239 }
240 
241 void
242 NativeThreadLinux::SetStoppedBySignal(uint32_t signo, const siginfo_t *info)
243 {
244     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
245     if (log)
246         log->Printf ("NativeThreadLinux::%s called with signal 0x%02" PRIx32, __FUNCTION__, signo);
247 
248     const StateType new_state = StateType::eStateStopped;
249     MaybeLogStateChange (new_state);
250     m_state = new_state;
251 
252     m_stop_info.reason = StopReason::eStopReasonSignal;
253     m_stop_info.details.signal.signo = signo;
254 
255     m_stop_description.clear();
256     if (info)
257     {
258         switch (signo)
259         {
260         case SIGSEGV:
261         case SIGBUS:
262         case SIGFPE:
263         case SIGILL:
264              //In case of MIPS64 target, SI_KERNEL is generated for invalid 64bit address.
265              const auto reason = (info->si_signo == SIGBUS && info->si_code == SI_KERNEL) ?
266                                   CrashReason::eInvalidAddress : GetCrashReason(*info);
267              m_stop_description = GetCrashReasonString(reason, reinterpret_cast<uintptr_t>(info->si_addr));
268              break;
269         }
270     }
271 }
272 
273 bool
274 NativeThreadLinux::IsStopped (int *signo)
275 {
276     if (!StateIsStoppedState (m_state, false))
277         return false;
278 
279     // If we are stopped by a signal, return the signo.
280     if (signo &&
281         m_state == StateType::eStateStopped &&
282         m_stop_info.reason == StopReason::eStopReasonSignal)
283     {
284         *signo = m_stop_info.details.signal.signo;
285     }
286 
287     // Regardless, we are stopped.
288     return true;
289 }
290 
291 
292 void
293 NativeThreadLinux::SetStoppedByExec ()
294 {
295     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
296     if (log)
297         log->Printf ("NativeThreadLinux::%s()", __FUNCTION__);
298 
299     const StateType new_state = StateType::eStateStopped;
300     MaybeLogStateChange (new_state);
301     m_state = new_state;
302 
303     m_stop_info.reason = StopReason::eStopReasonExec;
304     m_stop_info.details.signal.signo = SIGSTOP;
305 }
306 
307 void
308 NativeThreadLinux::SetStoppedByBreakpoint ()
309 {
310     const StateType new_state = StateType::eStateStopped;
311     MaybeLogStateChange (new_state);
312     m_state = new_state;
313 
314     m_stop_info.reason = StopReason::eStopReasonBreakpoint;
315     m_stop_info.details.signal.signo = SIGTRAP;
316     m_stop_description.clear();
317 }
318 
319 void
320 NativeThreadLinux::SetStoppedByWatchpoint (uint32_t wp_index)
321 {
322     const StateType new_state = StateType::eStateStopped;
323     MaybeLogStateChange (new_state);
324     m_state = new_state;
325     m_stop_description.clear ();
326 
327     lldbassert(wp_index != LLDB_INVALID_INDEX32 &&
328                "wp_index cannot be invalid");
329 
330     std::ostringstream ostr;
331     ostr << GetRegisterContext()->GetWatchpointAddress(wp_index) << " ";
332     ostr << wp_index;
333 
334     /*
335      * MIPS: Last 3bits of the watchpoint address are masked by the kernel. For example:
336      * 'n' is at 0x120010d00 and 'm' is 0x120010d04. When a watchpoint is set at 'm', then
337      * watch exception is generated even when 'n' is read/written. To handle this case,
338      * find the base address of the load/store instruction and append it in the stop-info
339      * packet.
340     */
341     ostr << " " << GetRegisterContext()->GetWatchpointHitAddress(wp_index);
342 
343     m_stop_description = ostr.str();
344 
345     m_stop_info.reason = StopReason::eStopReasonWatchpoint;
346     m_stop_info.details.signal.signo = SIGTRAP;
347 }
348 
349 bool
350 NativeThreadLinux::IsStoppedAtBreakpoint ()
351 {
352     return GetState () == StateType::eStateStopped &&
353         m_stop_info.reason == StopReason::eStopReasonBreakpoint;
354 }
355 
356 bool
357 NativeThreadLinux::IsStoppedAtWatchpoint ()
358 {
359     return GetState () == StateType::eStateStopped &&
360         m_stop_info.reason == StopReason::eStopReasonWatchpoint;
361 }
362 
363 void
364 NativeThreadLinux::SetStoppedByTrace ()
365 {
366     const StateType new_state = StateType::eStateStopped;
367     MaybeLogStateChange (new_state);
368     m_state = new_state;
369 
370     m_stop_info.reason = StopReason::eStopReasonTrace;
371     m_stop_info.details.signal.signo = SIGTRAP;
372 }
373 
374 void
375 NativeThreadLinux::SetStoppedWithNoReason ()
376 {
377     const StateType new_state = StateType::eStateStopped;
378     MaybeLogStateChange (new_state);
379     m_state = new_state;
380 
381     m_stop_info.reason = StopReason::eStopReasonNone;
382     m_stop_info.details.signal.signo = 0;
383 }
384 
385 void
386 NativeThreadLinux::SetExited ()
387 {
388     const StateType new_state = StateType::eStateExited;
389     MaybeLogStateChange (new_state);
390     m_state = new_state;
391 
392     m_stop_info.reason = StopReason::eStopReasonThreadExiting;
393 }
394 
395 Error
396 NativeThreadLinux::RequestStop ()
397 {
398     Log* log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
399 
400     const auto process_sp = GetProcess();
401     if (! process_sp)
402         return Error("Process is null.");
403 
404     lldb::pid_t pid = process_sp->GetID();
405     lldb::tid_t tid = GetID();
406 
407     if (log)
408         log->Printf ("NativeThreadLinux::%s requesting thread stop(pid: %" PRIu64 ", tid: %" PRIu64 ")", __FUNCTION__, pid, tid);
409 
410     Error err;
411     errno = 0;
412     if (::tgkill (pid, tid, SIGSTOP) != 0)
413     {
414         err.SetErrorToErrno ();
415         if (log)
416             log->Printf ("NativeThreadLinux::%s tgkill(%" PRIu64 ", %" PRIu64 ", SIGSTOP) failed: %s", __FUNCTION__, pid, tid, err.AsCString ());
417     }
418 
419     return err;
420 }
421 
422 void
423 NativeThreadLinux::MaybeLogStateChange (lldb::StateType new_state)
424 {
425     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
426     // If we're not logging, we're done.
427     if (!log)
428         return;
429 
430     // If this is a state change to the same state, we're done.
431     lldb::StateType old_state = m_state;
432     if (new_state == old_state)
433         return;
434 
435     NativeProcessProtocolSP m_process_sp = m_process_wp.lock ();
436     lldb::pid_t pid = m_process_sp ? m_process_sp->GetID () : LLDB_INVALID_PROCESS_ID;
437 
438     // Log it.
439     log->Printf ("NativeThreadLinux: thread (pid=%" PRIu64 ", tid=%" PRIu64 ") changing from state %s to %s", pid, GetID (), StateAsCString (old_state), StateAsCString (new_state));
440 }
441