1 //===-- NativeThreadLinux.cpp --------------------------------- -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "NativeThreadLinux.h"
15 #include "NativeProcessLinux.h"
16 #include "NativeRegisterContextLinux.h"
17 #include "SingleStepCheck.h"
19 #include "lldb/Core/Log.h"
20 #include "lldb/Core/State.h"
21 #include "lldb/Host/HostNativeThread.h"
22 #include "lldb/Host/linux/Ptrace.h"
23 #include "lldb/Utility/LLDBAssert.h"
24 #include "lldb/lldb-enumerations.h"
26 #include "llvm/ADT/SmallString.h"
28 #include "Plugins/Process/POSIX/CrashReason.h"
30 #include <sys/syscall.h>
31 // Try to define a macro to encapsulate the tgkill syscall
32 #define tgkill(pid, tid, sig) \
33 syscall(SYS_tgkill, static_cast< ::pid_t>(pid), static_cast< ::pid_t>(tid), sig)
36 using namespace lldb_private;
37 using namespace lldb_private::process_linux;
41 void LogThreadStopInfo (Log &log, const ThreadStopInfo &stop_info, const char *const header)
43 switch (stop_info.reason)
46 log.Printf ("%s: %s no stop reason", __FUNCTION__, header);
48 case eStopReasonTrace:
49 log.Printf ("%s: %s trace, stopping signal 0x%" PRIx32, __FUNCTION__, header, stop_info.details.signal.signo);
51 case eStopReasonBreakpoint:
52 log.Printf ("%s: %s breakpoint, stopping signal 0x%" PRIx32, __FUNCTION__, header, stop_info.details.signal.signo);
54 case eStopReasonWatchpoint:
55 log.Printf ("%s: %s watchpoint, stopping signal 0x%" PRIx32, __FUNCTION__, header, stop_info.details.signal.signo);
57 case eStopReasonSignal:
58 log.Printf ("%s: %s signal 0x%02" PRIx32, __FUNCTION__, header, stop_info.details.signal.signo);
60 case eStopReasonException:
61 log.Printf ("%s: %s exception type 0x%02" PRIx64, __FUNCTION__, header, stop_info.details.exception.type);
64 log.Printf ("%s: %s exec, stopping signal 0x%" PRIx32, __FUNCTION__, header, stop_info.details.signal.signo);
66 case eStopReasonPlanComplete:
67 log.Printf ("%s: %s plan complete", __FUNCTION__, header);
69 case eStopReasonThreadExiting:
70 log.Printf ("%s: %s thread exiting", __FUNCTION__, header);
72 case eStopReasonInstrumentation:
73 log.Printf ("%s: %s instrumentation", __FUNCTION__, header);
76 log.Printf ("%s: %s invalid stop reason %" PRIu32, __FUNCTION__, header, static_cast<uint32_t> (stop_info.reason));
81 NativeThreadLinux::NativeThreadLinux (NativeProcessLinux *process, lldb::tid_t tid) :
82 NativeThreadProtocol (process, tid),
83 m_state (StateType::eStateInvalid),
91 NativeThreadLinux::GetName()
93 NativeProcessProtocolSP process_sp = m_process_wp.lock ();
95 return "<unknown: no process>";
97 // const NativeProcessLinux *const process = reinterpret_cast<NativeProcessLinux*> (process_sp->get ());
98 llvm::SmallString<32> thread_name;
99 HostNativeThread::GetName(GetID(), thread_name);
100 return thread_name.c_str();
104 NativeThreadLinux::GetState ()
111 NativeThreadLinux::GetStopReason (ThreadStopInfo &stop_info, std::string& description)
113 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
122 case eStateSuspended:
125 LogThreadStopInfo (*log, m_stop_info, "m_stop_info in thread:");
126 stop_info = m_stop_info;
127 description = m_stop_description;
129 LogThreadStopInfo (*log, stop_info, "returned stop_info:");
134 case eStateConnected:
135 case eStateAttaching:
136 case eStateLaunching:
142 log->Printf ("NativeThreadLinux::%s tid %" PRIu64 " in state %s cannot answer stop reason",
143 __FUNCTION__, GetID (), StateAsCString (m_state));
147 llvm_unreachable("unhandled StateType!");
150 NativeRegisterContextSP
151 NativeThreadLinux::GetRegisterContext ()
153 // Return the register context if we already created it.
154 if (m_reg_context_sp)
155 return m_reg_context_sp;
157 NativeProcessProtocolSP m_process_sp = m_process_wp.lock ();
159 return NativeRegisterContextSP ();
161 ArchSpec target_arch;
162 if (!m_process_sp->GetArchitecture (target_arch))
163 return NativeRegisterContextSP ();
165 const uint32_t concrete_frame_idx = 0;
166 m_reg_context_sp.reset (NativeRegisterContextLinux::CreateHostNativeRegisterContextLinux(target_arch,
168 concrete_frame_idx));
170 return m_reg_context_sp;
174 NativeThreadLinux::SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware)
177 return Error ("not implemented");
178 if (m_state == eStateLaunching)
180 Error error = RemoveWatchpoint(addr);
181 if (error.Fail()) return error;
182 NativeRegisterContextSP reg_ctx = GetRegisterContext ();
184 reg_ctx->SetHardwareWatchpoint (addr, size, watch_flags);
185 if (wp_index == LLDB_INVALID_INDEX32)
186 return Error ("Setting hardware watchpoint failed.");
187 m_watchpoint_index_map.insert({addr, wp_index});
192 NativeThreadLinux::RemoveWatchpoint (lldb::addr_t addr)
194 auto wp = m_watchpoint_index_map.find(addr);
195 if (wp == m_watchpoint_index_map.end())
197 uint32_t wp_index = wp->second;
198 m_watchpoint_index_map.erase(wp);
199 if (GetRegisterContext()->ClearHardwareWatchpoint(wp_index))
201 return Error ("Clearing hardware watchpoint failed.");
205 NativeThreadLinux::Resume(uint32_t signo)
207 const StateType new_state = StateType::eStateRunning;
208 MaybeLogStateChange (new_state);
211 m_stop_info.reason = StopReason::eStopReasonNone;
212 m_stop_description.clear();
214 // If watchpoints have been set, but none on this thread,
215 // then this is a new thread. So set all existing watchpoints.
216 if (m_watchpoint_index_map.empty())
218 NativeProcessLinux &process = GetProcess();
220 const auto &watchpoint_map = process.GetWatchpointMap();
221 GetRegisterContext()->ClearAllHardwareWatchpoints();
222 for (const auto &pair : watchpoint_map)
224 const auto &wp = pair.second;
225 SetWatchpoint(wp.m_addr, wp.m_size, wp.m_watch_flags, wp.m_hardware);
231 if (signo != LLDB_INVALID_SIGNAL_NUMBER)
234 return NativeProcessLinux::PtraceWrapper(PTRACE_CONT, GetID(), nullptr, reinterpret_cast<void *>(data));
238 NativeThreadLinux::MaybePrepareSingleStepWorkaround()
240 if (!SingleStepWorkaroundNeeded())
243 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
245 if (sched_getaffinity(static_cast<::pid_t>(m_tid), sizeof m_original_cpu_set, &m_original_cpu_set) != 0)
247 // This should really not fail. But, just in case...
250 Error error(errno, eErrorTypePOSIX);
251 log->Printf("NativeThreadLinux::%s Unable to get cpu affinity for thread %" PRIx64 ": %s", __FUNCTION__,
252 m_tid, error.AsCString());
260 if (sched_setaffinity(static_cast<::pid_t>(m_tid), sizeof set, &set) != 0 && log)
262 // This may fail in very locked down systems, if the thread is not allowed to run on
263 // cpu 0. If that happens, only thing we can do is it log it and continue...
264 Error error(errno, eErrorTypePOSIX);
265 log->Printf("NativeThreadLinux::%s Unable to set cpu affinity for thread %" PRIx64 ": %s", __FUNCTION__, m_tid,
271 NativeThreadLinux::MaybeCleanupSingleStepWorkaround()
273 if (!SingleStepWorkaroundNeeded())
276 if (sched_setaffinity(static_cast<::pid_t>(m_tid), sizeof m_original_cpu_set, &m_original_cpu_set) != 0)
278 Error error(errno, eErrorTypePOSIX);
279 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
280 log->Printf("NativeThreadLinux::%s Unable to reset cpu affinity for thread %" PRIx64 ": %s", __FUNCTION__,
281 m_tid, error.AsCString());
286 NativeThreadLinux::SingleStep(uint32_t signo)
288 const StateType new_state = StateType::eStateStepping;
289 MaybeLogStateChange (new_state);
291 m_stop_info.reason = StopReason::eStopReasonNone;
293 MaybePrepareSingleStepWorkaround();
296 if (signo != LLDB_INVALID_SIGNAL_NUMBER)
299 // If hardware single-stepping is not supported, we just do a continue. The breakpoint on the
300 // next instruction has been setup in NativeProcessLinux::Resume.
301 return NativeProcessLinux::PtraceWrapper(GetProcess().SupportHardwareSingleStepping() ? PTRACE_SINGLESTEP
303 m_tid, nullptr, reinterpret_cast<void *>(data));
307 NativeThreadLinux::SetStoppedBySignal(uint32_t signo, const siginfo_t *info)
309 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
311 log->Printf ("NativeThreadLinux::%s called with signal 0x%02" PRIx32, __FUNCTION__, signo);
315 m_stop_info.reason = StopReason::eStopReasonSignal;
316 m_stop_info.details.signal.signo = signo;
318 m_stop_description.clear();
327 //In case of MIPS64 target, SI_KERNEL is generated for invalid 64bit address.
328 const auto reason = (info->si_signo == SIGBUS && info->si_code == SI_KERNEL) ?
329 CrashReason::eInvalidAddress : GetCrashReason(*info);
330 m_stop_description = GetCrashReasonString(reason, reinterpret_cast<uintptr_t>(info->si_addr));
337 NativeThreadLinux::IsStopped (int *signo)
339 if (!StateIsStoppedState (m_state, false))
342 // If we are stopped by a signal, return the signo.
344 m_state == StateType::eStateStopped &&
345 m_stop_info.reason == StopReason::eStopReasonSignal)
347 *signo = m_stop_info.details.signal.signo;
350 // Regardless, we are stopped.
355 NativeThreadLinux::SetStopped()
357 if (m_state == StateType::eStateStepping)
358 MaybeCleanupSingleStepWorkaround();
360 const StateType new_state = StateType::eStateStopped;
361 MaybeLogStateChange(new_state);
363 m_stop_description.clear();
367 NativeThreadLinux::SetStoppedByExec ()
369 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
371 log->Printf ("NativeThreadLinux::%s()", __FUNCTION__);
375 m_stop_info.reason = StopReason::eStopReasonExec;
376 m_stop_info.details.signal.signo = SIGSTOP;
380 NativeThreadLinux::SetStoppedByBreakpoint ()
384 m_stop_info.reason = StopReason::eStopReasonBreakpoint;
385 m_stop_info.details.signal.signo = SIGTRAP;
386 m_stop_description.clear();
390 NativeThreadLinux::SetStoppedByWatchpoint (uint32_t wp_index)
394 lldbassert(wp_index != LLDB_INVALID_INDEX32 &&
395 "wp_index cannot be invalid");
397 std::ostringstream ostr;
398 ostr << GetRegisterContext()->GetWatchpointAddress(wp_index) << " ";
402 * MIPS: Last 3bits of the watchpoint address are masked by the kernel. For example:
403 * 'n' is at 0x120010d00 and 'm' is 0x120010d04. When a watchpoint is set at 'm', then
404 * watch exception is generated even when 'n' is read/written. To handle this case,
405 * find the base address of the load/store instruction and append it in the stop-info
408 ostr << " " << GetRegisterContext()->GetWatchpointHitAddress(wp_index);
410 m_stop_description = ostr.str();
412 m_stop_info.reason = StopReason::eStopReasonWatchpoint;
413 m_stop_info.details.signal.signo = SIGTRAP;
417 NativeThreadLinux::IsStoppedAtBreakpoint ()
419 return GetState () == StateType::eStateStopped &&
420 m_stop_info.reason == StopReason::eStopReasonBreakpoint;
424 NativeThreadLinux::IsStoppedAtWatchpoint ()
426 return GetState () == StateType::eStateStopped &&
427 m_stop_info.reason == StopReason::eStopReasonWatchpoint;
431 NativeThreadLinux::SetStoppedByTrace ()
435 m_stop_info.reason = StopReason::eStopReasonTrace;
436 m_stop_info.details.signal.signo = SIGTRAP;
440 NativeThreadLinux::SetStoppedWithNoReason ()
444 m_stop_info.reason = StopReason::eStopReasonNone;
445 m_stop_info.details.signal.signo = 0;
449 NativeThreadLinux::SetExited ()
451 const StateType new_state = StateType::eStateExited;
452 MaybeLogStateChange (new_state);
455 m_stop_info.reason = StopReason::eStopReasonThreadExiting;
459 NativeThreadLinux::RequestStop ()
461 Log* log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
463 NativeProcessLinux &process = GetProcess();
465 lldb::pid_t pid = process.GetID();
466 lldb::tid_t tid = GetID();
469 log->Printf ("NativeThreadLinux::%s requesting thread stop(pid: %" PRIu64 ", tid: %" PRIu64 ")", __FUNCTION__, pid, tid);
473 if (::tgkill (pid, tid, SIGSTOP) != 0)
475 err.SetErrorToErrno ();
477 log->Printf ("NativeThreadLinux::%s tgkill(%" PRIu64 ", %" PRIu64 ", SIGSTOP) failed: %s", __FUNCTION__, pid, tid, err.AsCString ());
484 NativeThreadLinux::MaybeLogStateChange (lldb::StateType new_state)
486 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
487 // If we're not logging, we're done.
491 // If this is a state change to the same state, we're done.
492 lldb::StateType old_state = m_state;
493 if (new_state == old_state)
496 NativeProcessProtocolSP m_process_sp = m_process_wp.lock ();
497 lldb::pid_t pid = m_process_sp ? m_process_sp->GetID () : LLDB_INVALID_PROCESS_ID;
500 log->Printf ("NativeThreadLinux: thread (pid=%" PRIu64 ", tid=%" PRIu64 ") changing from state %s to %s", pid, GetID (), StateAsCString (old_state), StateAsCString (new_state));
504 NativeThreadLinux::GetProcess()
506 auto process_sp = std::static_pointer_cast<NativeProcessLinux>(NativeThreadProtocol::GetProcess());