LLDB  mainline
NativeThreadLinux.cpp
Go to the documentation of this file.
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 <signal.h>
12 #include <sstream>
13 
14 #include "NativeProcessLinux.h"
16 #include "SingleStepCheck.h"
17 
19 #include "lldb/Host/linux/Ptrace.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 
29 
30 #include <sys/syscall.h>
31 // Try to define a macro to encapsulate the tgkill syscall
32 #define tgkill(pid, tid, sig) \
33  syscall(__NR_tgkill, static_cast<::pid_t>(pid), static_cast<::pid_t>(tid), \
34  sig)
35 
36 using namespace lldb;
37 using namespace lldb_private;
38 using namespace lldb_private::process_linux;
39 
40 namespace {
41 void LogThreadStopInfo(Log &log, const ThreadStopInfo &stop_info,
42  const char *const header) {
43  switch (stop_info.reason) {
44  case eStopReasonNone:
45  log.Printf("%s: %s no stop reason", __FUNCTION__, header);
46  return;
47  case eStopReasonTrace:
48  log.Printf("%s: %s trace, stopping signal 0x%" PRIx32, __FUNCTION__, header,
49  stop_info.details.signal.signo);
50  return;
52  log.Printf("%s: %s breakpoint, stopping signal 0x%" PRIx32, __FUNCTION__,
53  header, stop_info.details.signal.signo);
54  return;
56  log.Printf("%s: %s watchpoint, stopping signal 0x%" PRIx32, __FUNCTION__,
57  header, stop_info.details.signal.signo);
58  return;
59  case eStopReasonSignal:
60  log.Printf("%s: %s signal 0x%02" PRIx32, __FUNCTION__, header,
61  stop_info.details.signal.signo);
62  return;
64  log.Printf("%s: %s exception type 0x%02" PRIx64, __FUNCTION__, header,
65  stop_info.details.exception.type);
66  return;
67  case eStopReasonExec:
68  log.Printf("%s: %s exec, stopping signal 0x%" PRIx32, __FUNCTION__, header,
69  stop_info.details.signal.signo);
70  return;
72  log.Printf("%s: %s plan complete", __FUNCTION__, header);
73  return;
75  log.Printf("%s: %s thread exiting", __FUNCTION__, header);
76  return;
78  log.Printf("%s: %s instrumentation", __FUNCTION__, header);
79  return;
80  default:
81  log.Printf("%s: %s invalid stop reason %" PRIu32, __FUNCTION__, header,
82  static_cast<uint32_t>(stop_info.reason));
83  }
84 }
85 }
86 
87 NativeThreadLinux::NativeThreadLinux(NativeProcessLinux &process,
88  lldb::tid_t tid)
89  : NativeThreadProtocol(process, tid), m_state(StateType::eStateInvalid),
90  m_stop_info(),
91  m_reg_context_up(
92  NativeRegisterContextLinux::CreateHostNativeRegisterContextLinux(
93  process.GetArchitecture(), *this)),
94  m_stop_description() {}
95 
97  NativeProcessLinux &process = GetProcess();
98 
99  auto BufferOrError = getProcFile(process.GetID(), GetID(), "comm");
100  if (!BufferOrError)
101  return "";
102  return std::string(BufferOrError.get()->getBuffer().rtrim('\n'));
103 }
104 
106 
108  std::string &description) {
110 
111  description.clear();
112 
113  switch (m_state) {
114  case eStateStopped:
115  case eStateCrashed:
116  case eStateExited:
117  case eStateSuspended:
118  case eStateUnloaded:
119  if (log)
120  LogThreadStopInfo(*log, m_stop_info, "m_stop_info in thread:");
121  stop_info = m_stop_info;
122  description = m_stop_description;
123  if (log)
124  LogThreadStopInfo(*log, stop_info, "returned stop_info:");
125 
126  return true;
127 
128  case eStateInvalid:
129  case eStateConnected:
130  case eStateAttaching:
131  case eStateLaunching:
132  case eStateRunning:
133  case eStateStepping:
134  case eStateDetached:
135  if (log) {
136  LLDB_LOGF(log,
137  "NativeThreadLinux::%s tid %" PRIu64
138  " in state %s cannot answer stop reason",
139  __FUNCTION__, GetID(), StateAsCString(m_state));
140  }
141  return false;
142  }
143  llvm_unreachable("unhandled StateType!");
144 }
145 
147  uint32_t watch_flags, bool hardware) {
148  if (!hardware)
149  return Status("not implemented");
150  if (m_state == eStateLaunching)
151  return Status();
152  Status error = RemoveWatchpoint(addr);
153  if (error.Fail())
154  return error;
155  uint32_t wp_index =
156  m_reg_context_up->SetHardwareWatchpoint(addr, size, watch_flags);
157  if (wp_index == LLDB_INVALID_INDEX32)
158  return Status("Setting hardware watchpoint failed.");
159  m_watchpoint_index_map.insert({addr, wp_index});
160  return Status();
161 }
162 
164  auto wp = m_watchpoint_index_map.find(addr);
165  if (wp == m_watchpoint_index_map.end())
166  return Status();
167  uint32_t wp_index = wp->second;
168  m_watchpoint_index_map.erase(wp);
169  if (m_reg_context_up->ClearHardwareWatchpoint(wp_index))
170  return Status();
171  return Status("Clearing hardware watchpoint failed.");
172 }
173 
175  size_t size) {
176  if (m_state == eStateLaunching)
177  return Status();
178 
180  if (error.Fail())
181  return error;
182 
183  uint32_t bp_index = m_reg_context_up->SetHardwareBreakpoint(addr, size);
184 
185  if (bp_index == LLDB_INVALID_INDEX32)
186  return Status("Setting hardware breakpoint failed.");
187 
188  m_hw_break_index_map.insert({addr, bp_index});
189  return Status();
190 }
191 
193  auto bp = m_hw_break_index_map.find(addr);
194  if (bp == m_hw_break_index_map.end())
195  return Status();
196 
197  uint32_t bp_index = bp->second;
198  if (m_reg_context_up->ClearHardwareBreakpoint(bp_index)) {
199  m_hw_break_index_map.erase(bp);
200  return Status();
201  }
202 
203  return Status("Clearing hardware breakpoint failed.");
204 }
205 
207  const StateType new_state = StateType::eStateRunning;
208  MaybeLogStateChange(new_state);
209  m_state = new_state;
210 
212  m_stop_description.clear();
213 
214  // If watchpoints have been set, but none on this thread, then this is a new
215  // thread. So set all existing watchpoints.
216  if (m_watchpoint_index_map.empty()) {
217  NativeProcessLinux &process = GetProcess();
218 
219  const auto &watchpoint_map = process.GetWatchpointMap();
220  m_reg_context_up->ClearAllHardwareWatchpoints();
221  for (const auto &pair : watchpoint_map) {
222  const auto &wp = pair.second;
223  SetWatchpoint(wp.m_addr, wp.m_size, wp.m_watch_flags, wp.m_hardware);
224  }
225  }
226 
227  // Set all active hardware breakpoint on all threads.
228  if (m_hw_break_index_map.empty()) {
229  NativeProcessLinux &process = GetProcess();
230 
231  const auto &hw_breakpoint_map = process.GetHardwareBreakpointMap();
232  m_reg_context_up->ClearAllHardwareBreakpoints();
233  for (const auto &pair : hw_breakpoint_map) {
234  const auto &bp = pair.second;
235  SetHardwareBreakpoint(bp.m_addr, bp.m_size);
236  }
237  }
238 
239  intptr_t data = 0;
240 
241  if (signo != LLDB_INVALID_SIGNAL_NUMBER)
242  data = signo;
243 
244  // Before thread resumes, clear any cached register data structures
246 
247  return NativeProcessLinux::PtraceWrapper(PTRACE_CONT, GetID(), nullptr,
248  reinterpret_cast<void *>(data));
249 }
250 
252  const StateType new_state = StateType::eStateStepping;
253  MaybeLogStateChange(new_state);
254  m_state = new_state;
256 
257  if(!m_step_workaround) {
258  // If we already hava a workaround inplace, don't reset it. Otherwise, the
259  // destructor of the existing instance will run after the new instance has
260  // fetched the cpu mask, and the thread will end up with the wrong mask.
262  }
263 
264  intptr_t data = 0;
265  if (signo != LLDB_INVALID_SIGNAL_NUMBER)
266  data = signo;
267 
268  // Before thread resumes, clear any cached register data structures
270 
271  // If hardware single-stepping is not supported, we just do a continue. The
272  // breakpoint on the next instruction has been setup in
273  // NativeProcessLinux::Resume.
275  GetProcess().SupportHardwareSingleStepping() ? PTRACE_SINGLESTEP
276  : PTRACE_CONT,
277  m_tid, nullptr, reinterpret_cast<void *>(data));
278 }
279 
281  const siginfo_t *info) {
283  LLDB_LOGF(log, "NativeThreadLinux::%s called with signal 0x%02" PRIx32,
284  __FUNCTION__, signo);
285 
286  SetStopped();
287 
289  m_stop_info.details.signal.signo = signo;
290 
291  m_stop_description.clear();
292  if (info) {
293  switch (signo) {
294  case SIGSEGV:
295  case SIGBUS:
296  case SIGFPE:
297  case SIGILL:
298  // In case of MIPS64 target, SI_KERNEL is generated for invalid 64bit
299  // address.
300  const auto reason =
301  (info->si_signo == SIGBUS && info->si_code == SI_KERNEL)
303  : GetCrashReason(*info);
304  m_stop_description = GetCrashReasonString(reason, *info);
305  break;
306  }
307  }
308 }
309 
311  if (!StateIsStoppedState(m_state, false))
312  return false;
313 
314  // If we are stopped by a signal, return the signo.
315  if (signo && m_state == StateType::eStateStopped &&
317  *signo = m_stop_info.details.signal.signo;
318  }
319 
320  // Regardless, we are stopped.
321  return true;
322 }
323 
326  m_step_workaround.reset();
327 
328  const StateType new_state = StateType::eStateStopped;
329  MaybeLogStateChange(new_state);
330  m_state = new_state;
331  m_stop_description.clear();
332 }
333 
336  LLDB_LOGF(log, "NativeThreadLinux::%s()", __FUNCTION__);
337 
338  SetStopped();
339 
342 }
343 
345  SetStopped();
346 
349  m_stop_description.clear();
350 }
351 
353  SetStopped();
354 
355  lldbassert(wp_index != LLDB_INVALID_INDEX32 && "wp_index cannot be invalid");
356 
357  std::ostringstream ostr;
358  ostr << m_reg_context_up->GetWatchpointAddress(wp_index) << " ";
359  ostr << wp_index;
360 
361  /*
362  * MIPS: Last 3bits of the watchpoint address are masked by the kernel. For
363  * example:
364  * 'n' is at 0x120010d00 and 'm' is 0x120010d04. When a watchpoint is set at
365  * 'm', then
366  * watch exception is generated even when 'n' is read/written. To handle this
367  * case,
368  * find the base address of the load/store instruction and append it in the
369  * stop-info
370  * packet.
371  */
372  ostr << " " << m_reg_context_up->GetWatchpointHitAddress(wp_index);
373 
374  m_stop_description = ostr.str();
375 
378 }
379 
381  return GetState() == StateType::eStateStopped &&
383 }
384 
386  return GetState() == StateType::eStateStopped &&
388 }
389 
391  SetStopped();
392 
395 }
396 
398  SetStopped();
399 
401  m_stop_info.details.signal.signo = 0;
402 }
403 
405  const StateType new_state = StateType::eStateExited;
406  MaybeLogStateChange(new_state);
407  m_state = new_state;
408 
410 }
411 
414 
415  NativeProcessLinux &process = GetProcess();
416 
417  lldb::pid_t pid = process.GetID();
418  lldb::tid_t tid = GetID();
419 
420  LLDB_LOGF(log,
421  "NativeThreadLinux::%s requesting thread stop(pid: %" PRIu64
422  ", tid: %" PRIu64 ")",
423  __FUNCTION__, pid, tid);
424 
425  Status err;
426  errno = 0;
427  if (::tgkill(pid, tid, SIGSTOP) != 0) {
428  err.SetErrorToErrno();
429  LLDB_LOGF(log,
430  "NativeThreadLinux::%s tgkill(%" PRIu64 ", %" PRIu64
431  ", SIGSTOP) failed: %s",
432  __FUNCTION__, pid, tid, err.AsCString());
433  }
434 
435  return err;
436 }
437 
440  // If we're not logging, we're done.
441  if (!log)
442  return;
443 
444  // If this is a state change to the same state, we're done.
445  lldb::StateType old_state = m_state;
446  if (new_state == old_state)
447  return;
448 
449  LLDB_LOG(log, "pid={0}, tid={1}: changing from state {2} to {3}",
450  m_process.GetID(), GetID(), old_state, new_state);
451 }
452 
454  return static_cast<NativeProcessLinux &>(m_process);
455 }
const char * StateAsCString(lldb::StateType state)
Converts a StateType to a C string.
Definition: State.cpp:14
A class that represents a running process on the host machine.
virtual const NativeWatchpointList::WatchpointMap & GetWatchpointMap() const
#define lldbassert(x)
Definition: LLDBAssert.h:15
Process is currently trying to attach.
#define LLDB_INVALID_SIGNAL_NUMBER
Definition: lldb-defines.h:95
CrashReason GetCrashReason(const siginfo_t &info)
virtual const HardwareBreakpointMap & GetHardwareBreakpointMap() const
NativeRegisterContextLinux & GetRegisterContext() override
Process or thread is stopped and can be examined.
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition: Log.h:242
Process or thread has crashed and can be examined.
struct lldb_private::ThreadStopInfo::@12::@14 exception
#define SIGSTOP
void SetErrorToErrno()
Set the current error to errno.
Definition: Status.cpp:224
std::unique_ptr< NativeRegisterContextLinux > m_reg_context_up
Process has exited and can&#39;t be examined.
Status RemoveHardwareBreakpoint(lldb::addr_t addr) override
#define LLDB_INVALID_INDEX32
Definition: lldb-defines.h:86
bool StateIsStoppedState(lldb::StateType state, bool must_exist)
Check if a state represents a state where the process or thread is stopped.
Definition: State.cpp:89
static llvm::raw_ostream & error(Stream &strm)
Log * GetLogIfAllCategoriesSet(uint32_t mask)
Definition: Logging.cpp:58
bool GetStopReason(ThreadStopInfo &stop_info, std::string &description) override
#define LIBLLDB_LOG_THREAD
Definition: Logging.h:16
Process is connected to remote debug services, but not launched or attached to anything yet...
Process has been detached and can&#39;t be examined.
StateType
Process and Thread States.
#define tgkill(pid, tid, sig)
Process is in the process of launching.
uint64_t tid_t
Definition: lldb-types.h:86
Status SetWatchpoint(lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware) override
Manages communication with the inferior (debugee) process.
Program was re-exec&#39;ed.
Process or thread is in the process of stepping and can not be examined.
Process is object is valid, but not currently loaded.
void SetStoppedBySignal(uint32_t signo, const siginfo_t *info=nullptr)
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getProcFile(::pid_t pid, ::pid_t tid, const llvm::Twine &file)
Definition: Support.cpp:14
static std::unique_ptr< SingleStepWorkaround > Get(::pid_t tid)
std::unique_ptr< SingleStepWorkaround > m_step_workaround
Process or thread is in a suspended state as far as the debugger is concerned while other processes o...
lldb::StopReason reason
Definition: Debug.h:134
#define LLDB_LOGF(log,...)
Definition: Log.h:249
uint64_t addr_t
Definition: lldb-types.h:83
bool IsStopped(int *signo)
Return true if the thread is stopped.
bool Fail() const
Test for error condition.
Definition: Status.cpp:182
static Status PtraceWrapper(int req, lldb::pid_t pid, void *addr=nullptr, void *data=nullptr, size_t data_size=0, long *result=nullptr)
Status SetHardwareBreakpoint(lldb::addr_t addr, size_t size) override
Definition: SBAddress.h:15
uint64_t pid_t
Definition: lldb-types.h:85
std::string GetCrashReasonString(CrashReason reason, const siginfo_t &info)
#define SIGTRAP
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition: Status.cpp:131
Status RemoveWatchpoint(lldb::addr_t addr) override
Status SingleStep(uint32_t signo)
Single steps the thread.
union lldb_private::ThreadStopInfo::@12 details
void Printf(const char *format,...) __attribute__((format(printf
Prefer using LLDB_LOGF whenever possible.
Definition: Log.cpp:121
void MaybeLogStateChange(lldb::StateType new_state)
Status Resume(uint32_t signo)
Resumes the thread.
struct lldb_private::ThreadStopInfo::@12::@13 signal
An error handling class.
Definition: Status.h:44
Process or thread is running and can&#39;t be examined.