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_x86_64.h"
17 
18 #include "lldb/Core/Log.h"
19 #include "lldb/Core/State.h"
20 #include "lldb/Host/Host.h"
21 #include "lldb/Host/HostInfo.h"
22 #include "lldb/Host/HostNativeThread.h"
23 #include "lldb/lldb-enumerations.h"
24 #include "lldb/lldb-private-log.h"
25 
26 #include "llvm/ADT/SmallString.h"
27 
28 #include "Plugins/Process/POSIX/CrashReason.h"
29 
30 #include "Plugins/Process/Utility/RegisterContextLinux_arm64.h"
31 #include "Plugins/Process/Utility/RegisterContextLinux_i386.h"
32 #include "Plugins/Process/Utility/RegisterContextLinux_x86_64.h"
33 #include "Plugins/Process/Utility/RegisterInfoInterface.h"
34 
35 using namespace lldb;
36 using namespace lldb_private;
37 
38 namespace
39 {
40     void LogThreadStopInfo (Log &log, const ThreadStopInfo &stop_info, const char *const header)
41     {
42         switch (stop_info.reason)
43         {
44             case eStopReasonSignal:
45                 log.Printf ("%s: %s signal 0x%02" PRIx32, __FUNCTION__, header, stop_info.details.signal.signo);
46                 return;
47             case eStopReasonException:
48                 log.Printf ("%s: %s exception type 0x%02" PRIx64, __FUNCTION__, header, stop_info.details.exception.type);
49                 return;
50             case eStopReasonExec:
51                 log.Printf ("%s: %s exec, stopping signal 0x%" PRIx32, __FUNCTION__, header, stop_info.details.signal.signo);
52                 return;
53             default:
54                 log.Printf ("%s: %s invalid stop reason %" PRIu32, __FUNCTION__, header, static_cast<uint32_t> (stop_info.reason));
55         }
56     }
57 }
58 
59 NativeThreadLinux::NativeThreadLinux (NativeProcessLinux *process, lldb::tid_t tid) :
60     NativeThreadProtocol (process, tid),
61     m_state (StateType::eStateInvalid),
62     m_stop_info (),
63     m_reg_context_sp (),
64     m_stop_description ()
65 {
66 }
67 
68 std::string
69 NativeThreadLinux::GetName()
70 {
71     NativeProcessProtocolSP process_sp = m_process_wp.lock ();
72     if (!process_sp)
73         return "<unknown: no process>";
74 
75     // const NativeProcessLinux *const process = reinterpret_cast<NativeProcessLinux*> (process_sp->get ());
76     llvm::SmallString<32> thread_name;
77     HostNativeThread::GetName(GetID(), thread_name);
78     return thread_name.c_str();
79 }
80 
81 lldb::StateType
82 NativeThreadLinux::GetState ()
83 {
84     return m_state;
85 }
86 
87 
88 bool
89 NativeThreadLinux::GetStopReason (ThreadStopInfo &stop_info, std::string& description)
90 {
91     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
92 
93     description.clear();
94 
95     switch (m_state)
96     {
97     case eStateStopped:
98     case eStateCrashed:
99     case eStateExited:
100     case eStateSuspended:
101     case eStateUnloaded:
102         if (log)
103             LogThreadStopInfo (*log, m_stop_info, "m_stop_info in thread:");
104         stop_info = m_stop_info;
105         switch (m_stop_info.reason)
106         {
107             case StopReason::eStopReasonException:
108             case StopReason::eStopReasonBreakpoint:
109             case StopReason::eStopReasonWatchpoint:
110                 description = m_stop_description;
111             default:
112                 break;
113         }
114         if (log)
115             LogThreadStopInfo (*log, stop_info, "returned stop_info:");
116 
117         return true;
118 
119     case eStateInvalid:
120     case eStateConnected:
121     case eStateAttaching:
122     case eStateLaunching:
123     case eStateRunning:
124     case eStateStepping:
125     case eStateDetached:
126         if (log)
127         {
128             log->Printf ("NativeThreadLinux::%s tid %" PRIu64 " in state %s cannot answer stop reason",
129                     __FUNCTION__, GetID (), StateAsCString (m_state));
130         }
131         return false;
132     }
133     llvm_unreachable("unhandled StateType!");
134 }
135 
136 lldb_private::NativeRegisterContextSP
137 NativeThreadLinux::GetRegisterContext ()
138 {
139     // Return the register context if we already created it.
140     if (m_reg_context_sp)
141         return m_reg_context_sp;
142 
143     // First select the appropriate RegisterInfoInterface.
144     RegisterInfoInterface *reg_interface = nullptr;
145     NativeProcessProtocolSP m_process_sp = m_process_wp.lock ();
146     if (!m_process_sp)
147         return NativeRegisterContextSP ();
148 
149     ArchSpec target_arch;
150     if (!m_process_sp->GetArchitecture (target_arch))
151         return NativeRegisterContextSP ();
152 
153     switch (target_arch.GetTriple().getOS())
154     {
155         case llvm::Triple::Linux:
156             switch (target_arch.GetMachine())
157             {
158             case llvm::Triple::aarch64:
159                 assert((HostInfo::GetArchitecture ().GetAddressByteSize() == 8) && "Register setting path assumes this is a 64-bit host");
160                 reg_interface = static_cast<RegisterInfoInterface*>(new RegisterContextLinux_arm64(target_arch));
161                 break;
162             case llvm::Triple::x86:
163             case llvm::Triple::x86_64:
164                 if (HostInfo::GetArchitecture().GetAddressByteSize() == 4)
165                 {
166                     // 32-bit hosts run with a RegisterContextLinux_i386 context.
167                     reg_interface = static_cast<RegisterInfoInterface*>(new RegisterContextLinux_i386(target_arch));
168                 }
169                 else
170                 {
171                     assert((HostInfo::GetArchitecture().GetAddressByteSize() == 8) &&
172                            "Register setting path assumes this is a 64-bit host");
173                     // X86_64 hosts know how to work with 64-bit and 32-bit EXEs using the x86_64 register context.
174                     reg_interface = static_cast<RegisterInfoInterface*> (new RegisterContextLinux_x86_64 (target_arch));
175                 }
176                 break;
177             default:
178                 break;
179             }
180             break;
181         default:
182             break;
183     }
184 
185     assert(reg_interface && "OS or CPU not supported!");
186     if (!reg_interface)
187         return NativeRegisterContextSP ();
188 
189     // Now create the register context.
190     switch (target_arch.GetMachine())
191     {
192 #if 0
193         case llvm::Triple::mips64:
194         {
195             RegisterContextPOSIXProcessMonitor_mips64 *reg_ctx = new RegisterContextPOSIXProcessMonitor_mips64(*this, 0, reg_interface);
196             m_posix_thread = reg_ctx;
197             m_reg_context_sp.reset(reg_ctx);
198             break;
199         }
200 #endif
201 #if 0
202         case llvm::Triple::x86:
203 #endif
204         case llvm::Triple::x86_64:
205         {
206             const uint32_t concrete_frame_idx = 0;
207             m_reg_context_sp.reset (new NativeRegisterContextLinux_x86_64(*this, concrete_frame_idx, reg_interface));
208             break;
209         }
210         default:
211             break;
212     }
213 
214     return m_reg_context_sp;
215 }
216 
217 Error
218 NativeThreadLinux::SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware)
219 {
220     if (!hardware)
221         return Error ("not implemented");
222     Error error = RemoveWatchpoint(addr);
223     if (error.Fail()) return error;
224     NativeRegisterContextSP reg_ctx = GetRegisterContext ();
225     uint32_t wp_index =
226         reg_ctx->SetHardwareWatchpoint (addr, size, watch_flags);
227     if (wp_index == LLDB_INVALID_INDEX32)
228         return Error ("Setting hardware watchpoint failed.");
229     m_watchpoint_index_map.insert({addr, wp_index});
230     return Error ();
231 }
232 
233 Error
234 NativeThreadLinux::RemoveWatchpoint (lldb::addr_t addr)
235 {
236     auto wp = m_watchpoint_index_map.find(addr);
237     if (wp == m_watchpoint_index_map.end())
238         return Error ();
239     uint32_t wp_index = wp->second;
240     m_watchpoint_index_map.erase(wp);
241     if (GetRegisterContext()->ClearHardwareWatchpoint(wp_index))
242         return Error ();
243     return Error ("Clearing hardware watchpoint failed.");
244 }
245 
246 void
247 NativeThreadLinux::SetLaunching ()
248 {
249     const StateType new_state = StateType::eStateLaunching;
250     MaybeLogStateChange (new_state);
251     m_state = new_state;
252 
253     // Also mark it as stopped since launching temporarily stops the newly created thread
254     // in the ptrace machinery.
255     m_stop_info.reason = StopReason::eStopReasonSignal;
256     m_stop_info.details.signal.signo = SIGSTOP;
257 }
258 
259 
260 void
261 NativeThreadLinux::SetRunning ()
262 {
263     const StateType new_state = StateType::eStateRunning;
264     MaybeLogStateChange (new_state);
265     m_state = new_state;
266 
267     m_stop_info.reason = StopReason::eStopReasonNone;
268     m_stop_description.clear();
269 
270     // If watchpoints have been set, but none on this thread,
271     // then this is a new thread. So set all existing watchpoints.
272     if (m_watchpoint_index_map.empty())
273     {
274         const auto &watchpoint_map = GetProcess()->GetWatchpointMap();
275         if (watchpoint_map.empty()) return;
276         GetRegisterContext()->ClearAllHardwareWatchpoints();
277         for (const auto &pair : watchpoint_map)
278         {
279             const auto& wp = pair.second;
280             SetWatchpoint(wp.m_addr, wp.m_size, wp.m_watch_flags, wp.m_hardware);
281         }
282     }
283 }
284 
285 void
286 NativeThreadLinux::SetStepping ()
287 {
288     const StateType new_state = StateType::eStateStepping;
289     MaybeLogStateChange (new_state);
290     m_state = new_state;
291 
292     m_stop_info.reason = StopReason::eStopReasonNone;
293 }
294 
295 void
296 NativeThreadLinux::SetStoppedBySignal (uint32_t signo)
297 {
298     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
299     if (log)
300         log->Printf ("NativeThreadLinux::%s called with signal 0x%02" PRIx32, __FUNCTION__, signo);
301 
302     const StateType new_state = StateType::eStateStopped;
303     MaybeLogStateChange (new_state);
304     m_state = new_state;
305 
306     m_stop_info.reason = StopReason::eStopReasonSignal;
307     m_stop_info.details.signal.signo = signo;
308 }
309 
310 bool
311 NativeThreadLinux::IsStopped (int *signo)
312 {
313     if (!StateIsStoppedState (m_state, false))
314         return false;
315 
316     // If we are stopped by a signal, return the signo.
317     if (signo &&
318         m_state == StateType::eStateStopped &&
319         m_stop_info.reason == StopReason::eStopReasonSignal)
320     {
321         *signo = m_stop_info.details.signal.signo;
322     }
323 
324     // Regardless, we are stopped.
325     return true;
326 }
327 
328 
329 void
330 NativeThreadLinux::SetStoppedByExec ()
331 {
332     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
333     if (log)
334         log->Printf ("NativeThreadLinux::%s()", __FUNCTION__);
335 
336     const StateType new_state = StateType::eStateStopped;
337     MaybeLogStateChange (new_state);
338     m_state = new_state;
339 
340     m_stop_info.reason = StopReason::eStopReasonExec;
341     m_stop_info.details.signal.signo = SIGSTOP;
342 }
343 
344 void
345 NativeThreadLinux::SetStoppedByBreakpoint ()
346 {
347     const StateType new_state = StateType::eStateStopped;
348     MaybeLogStateChange (new_state);
349     m_state = new_state;
350 
351     m_stop_info.reason = StopReason::eStopReasonBreakpoint;
352     m_stop_info.details.signal.signo = SIGTRAP;
353     m_stop_description.clear();
354 }
355 
356 void
357 NativeThreadLinux::SetStoppedByWatchpoint ()
358 {
359     const StateType new_state = StateType::eStateStopped;
360     MaybeLogStateChange (new_state);
361     m_state = new_state;
362 
363     m_stop_info.reason = StopReason::eStopReasonWatchpoint;
364     m_stop_info.details.signal.signo = SIGTRAP;
365 
366     NativeRegisterContextLinux_x86_64 *reg_ctx =
367         reinterpret_cast<NativeRegisterContextLinux_x86_64*> (GetRegisterContext().get());
368     const uint32_t num_hw_watchpoints =
369         reg_ctx->NumSupportedHardwareWatchpoints();
370 
371     m_stop_description.clear ();
372     for (uint32_t wp_index = 0; wp_index < num_hw_watchpoints; ++wp_index)
373         if (reg_ctx->IsWatchpointHit(wp_index).Success())
374         {
375             std::ostringstream ostr;
376             ostr << reg_ctx->GetWatchpointAddress(wp_index) << " " << wp_index;
377             m_stop_description = ostr.str();
378             return;
379         }
380     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
381     if (log)
382     {
383         NativeProcessProtocolSP m_process_sp = m_process_wp.lock ();
384         lldb::pid_t pid = m_process_sp ? m_process_sp->GetID () : LLDB_INVALID_PROCESS_ID;
385         log->Printf ("NativeThreadLinux: thread (pid=%" PRIu64 ", tid=%" PRIu64 ") "
386                 "stopped by a watchpoint, but failed to find it",
387                 pid, GetID ());
388     }
389 }
390 
391 bool
392 NativeThreadLinux::IsStoppedAtBreakpoint ()
393 {
394     return GetState () == StateType::eStateStopped &&
395         m_stop_info.reason == StopReason::eStopReasonBreakpoint;
396 }
397 
398 bool
399 NativeThreadLinux::IsStoppedAtWatchpoint ()
400 {
401     return GetState () == StateType::eStateStopped &&
402         m_stop_info.reason == StopReason::eStopReasonWatchpoint;
403 }
404 
405 void
406 NativeThreadLinux::SetStoppedByTrace ()
407 {
408     const StateType new_state = StateType::eStateStopped;
409     MaybeLogStateChange (new_state);
410     m_state = new_state;
411 
412     m_stop_info.reason = StopReason::eStopReasonTrace;
413     m_stop_info.details.signal.signo = SIGTRAP;
414 }
415 
416 void
417 NativeThreadLinux::SetCrashedWithException (const siginfo_t& info)
418 {
419     const StateType new_state = StateType::eStateCrashed;
420     MaybeLogStateChange (new_state);
421     m_state = new_state;
422 
423     m_stop_info.reason = StopReason::eStopReasonException;
424     m_stop_info.details.signal.signo = info.si_signo;
425 
426     const auto reason = GetCrashReason (info);
427     m_stop_description = GetCrashReasonString (reason, reinterpret_cast<lldb::addr_t> (info.si_addr));
428 }
429 
430 void
431 NativeThreadLinux::SetSuspended ()
432 {
433     const StateType new_state = StateType::eStateSuspended;
434     MaybeLogStateChange (new_state);
435     m_state = new_state;
436 
437     // FIXME what makes sense here? Do we need a suspended StopReason?
438     m_stop_info.reason = StopReason::eStopReasonNone;
439 }
440 
441 void
442 NativeThreadLinux::SetExited ()
443 {
444     const StateType new_state = StateType::eStateExited;
445     MaybeLogStateChange (new_state);
446     m_state = new_state;
447 
448     m_stop_info.reason = StopReason::eStopReasonThreadExiting;
449 }
450 
451 void
452 NativeThreadLinux::MaybeLogStateChange (lldb::StateType new_state)
453 {
454     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
455     // If we're not logging, we're done.
456     if (!log)
457         return;
458 
459     // If this is a state change to the same state, we're done.
460     lldb::StateType old_state = m_state;
461     if (new_state == old_state)
462         return;
463 
464     NativeProcessProtocolSP m_process_sp = m_process_wp.lock ();
465     lldb::pid_t pid = m_process_sp ? m_process_sp->GetID () : LLDB_INVALID_PROCESS_ID;
466 
467     // Log it.
468     log->Printf ("NativeThreadLinux: thread (pid=%" PRIu64 ", tid=%" PRIu64 ") changing from state %s to %s", pid, GetID (), StateAsCString (old_state), StateAsCString (new_state));
469 }
470