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 <csignal>
12#include <sstream>
13
14#include "NativeProcessLinux.h"
16#include "SingleStepCheck.h"
17
23#include "lldb/Utility/Log.h"
24#include "lldb/Utility/State.h"
26
27#include "llvm/ADT/SmallString.h"
28
31
32#include <sys/syscall.h>
33// Try to define a macro to encapsulate the tgkill syscall
34#define tgkill(pid, tid, sig) \
35 syscall(__NR_tgkill, static_cast<::pid_t>(pid), static_cast<::pid_t>(tid), \
36 sig)
37
38using namespace lldb;
39using namespace lldb_private;
40using namespace lldb_private::process_linux;
41
42namespace {
43void LogThreadStopInfo(Log &log, const ThreadStopInfo &stop_info,
44 const char *const header) {
45 switch (stop_info.reason) {
46 case eStopReasonNone:
47 log.Printf("%s: %s no stop reason", __FUNCTION__, header);
48 return;
50 log.Printf("%s: %s trace, stopping signal 0x%" PRIx32, __FUNCTION__, header,
51 stop_info.signo);
52 return;
54 log.Printf("%s: %s breakpoint, stopping signal 0x%" PRIx32, __FUNCTION__,
55 header, stop_info.signo);
56 return;
58 log.Printf("%s: %s watchpoint, stopping signal 0x%" PRIx32, __FUNCTION__,
59 header, stop_info.signo);
60 return;
62 log.Printf("%s: %s signal 0x%02" PRIx32, __FUNCTION__, header,
63 stop_info.signo);
64 return;
66 log.Printf("%s: %s exception type 0x%02" PRIx64, __FUNCTION__, header,
67 stop_info.details.exception.type);
68 return;
69 case eStopReasonExec:
70 log.Printf("%s: %s exec, stopping signal 0x%" PRIx32, __FUNCTION__, header,
71 stop_info.signo);
72 return;
74 log.Printf("%s: %s plan complete", __FUNCTION__, header);
75 return;
77 log.Printf("%s: %s thread exiting", __FUNCTION__, header);
78 return;
80 log.Printf("%s: %s instrumentation", __FUNCTION__, header);
81 return;
83 log.Printf("%s: %s processor trace", __FUNCTION__, header);
84 return;
86 log.Printf("%s: %s history boundary", __FUNCTION__, header);
87 return;
88 default:
89 log.Printf("%s: %s invalid stop reason %" PRIu32, __FUNCTION__, header,
90 static_cast<uint32_t>(stop_info.reason));
91 }
92}
93}
94
96 lldb::tid_t tid)
99 NativeRegisterContextLinux::CreateHostNativeRegisterContextLinux(
100 process.GetArchitecture(), *this)) {}
101
103 NativeProcessLinux &process = GetProcess();
104
105 auto BufferOrError = getProcFile(process.GetID(), GetID(), "comm");
106 if (!BufferOrError)
107 return "";
108 return std::string(BufferOrError.get()->getBuffer().rtrim('\n'));
109}
110
112
114 std::string &description) {
115 Log *log = GetLog(LLDBLog::Thread);
116
117 description.clear();
118
119 switch (m_state) {
120 case eStateStopped:
121 case eStateCrashed:
122 case eStateExited:
123 case eStateSuspended:
124 case eStateUnloaded:
125 if (log)
126 LogThreadStopInfo(*log, m_stop_info, "m_stop_info in thread:");
127 stop_info = m_stop_info;
128 description = m_stop_description;
129 if (log)
130 LogThreadStopInfo(*log, stop_info, "returned stop_info:");
131
132 return true;
133
134 case eStateInvalid:
135 case eStateConnected:
136 case eStateAttaching:
137 case eStateLaunching:
138 case eStateRunning:
139 case eStateStepping:
140 case eStateDetached:
141 LLDB_LOGF(log,
142 "NativeThreadLinux::%s tid %" PRIu64
143 " in state %s cannot answer stop reason",
144 __FUNCTION__, GetID(), StateAsCString(m_state));
145 return false;
146 }
147 llvm_unreachable("unhandled StateType!");
148}
149
151 uint32_t watch_flags, bool hardware) {
152 if (!hardware)
153 return Status::FromErrorString("not implemented");
155 return Status();
157 if (error.Fail())
158 return error;
159 uint32_t wp_index =
160 m_reg_context_up->SetHardwareWatchpoint(addr, size, watch_flags);
161 if (wp_index == LLDB_INVALID_INDEX32)
162 return Status::FromErrorString("Setting hardware watchpoint failed.");
163 m_watchpoint_index_map.insert({addr, wp_index});
164 return Status();
165}
166
168 auto wp = m_watchpoint_index_map.find(addr);
169 if (wp == m_watchpoint_index_map.end())
170 return Status();
171 uint32_t wp_index = wp->second;
172 m_watchpoint_index_map.erase(wp);
173 if (m_reg_context_up->ClearHardwareWatchpoint(wp_index))
174 return Status();
175 return Status::FromErrorString("Clearing hardware watchpoint failed.");
176}
177
179 size_t size) {
181 return Status();
182
184 if (error.Fail())
185 return error;
186
187 uint32_t bp_index = m_reg_context_up->SetHardwareBreakpoint(addr, size);
188
189 if (bp_index == LLDB_INVALID_INDEX32)
190 return Status::FromErrorString("Setting hardware breakpoint failed.");
191
192 m_hw_break_index_map.insert({addr, bp_index});
193 return Status();
194}
195
197 auto bp = m_hw_break_index_map.find(addr);
198 if (bp == m_hw_break_index_map.end())
199 return Status();
200
201 uint32_t bp_index = bp->second;
202 if (m_reg_context_up->ClearHardwareBreakpoint(bp_index)) {
203 m_hw_break_index_map.erase(bp);
204 return Status();
205 }
206
207 return Status::FromErrorString("Clearing hardware breakpoint failed.");
208}
209
211 const StateType new_state = StateType::eStateRunning;
212 MaybeLogStateChange(new_state);
213 m_state = new_state;
214
216
217 // If watchpoints have been set, but none on this thread, then this is a new
218 // thread. So set all existing watchpoints.
219 if (m_watchpoint_index_map.empty()) {
220 NativeProcessLinux &process = GetProcess();
221
222 const auto &watchpoint_map = process.GetWatchpointMap();
223 m_reg_context_up->ClearAllHardwareWatchpoints();
224 for (const auto &pair : watchpoint_map) {
225 const auto &wp = pair.second;
226 SetWatchpoint(wp.m_addr, wp.m_size, wp.m_watch_flags, wp.m_hardware);
227 }
228 }
229
230 // Set all active hardware breakpoint on all threads.
231 if (m_hw_break_index_map.empty()) {
232 NativeProcessLinux &process = GetProcess();
233
234 const auto &hw_breakpoint_map = process.GetHardwareBreakpointMap();
235 m_reg_context_up->ClearAllHardwareBreakpoints();
236 for (const auto &pair : hw_breakpoint_map) {
237 const auto &bp = pair.second;
238 SetHardwareBreakpoint(bp.m_addr, bp.m_size);
239 }
240 }
241
242 intptr_t data = 0;
243
244 if (signo != LLDB_INVALID_SIGNAL_NUMBER)
245 data = signo;
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 // If hardware single-stepping is not supported, we just do a continue. The
269 // breakpoint on the next instruction has been setup in
270 // NativeProcessLinux::Resume.
272 GetProcess().SupportHardwareSingleStepping() ? PTRACE_SINGLESTEP
273 : PTRACE_CONT,
274 m_tid, nullptr, reinterpret_cast<void *>(data));
275}
276
278 const siginfo_t *info) {
279 Log *log = GetLog(LLDBLog::Thread);
280 LLDB_LOGF(log, "NativeThreadLinux::%s called with signal 0x%02" PRIx32,
281 __FUNCTION__, signo);
282
283 SetStopped();
284
286 m_stop_info.signo = signo;
287
288 m_stop_description.clear();
289 if (info) {
290 switch (signo) {
291 case SIGSEGV:
292 case SIGBUS:
293 case SIGFPE:
294 case SIGILL:
296#ifndef SEGV_MTESERR
297#define SEGV_MTESERR 9
298#endif
299 if (info->si_signo == SIGSEGV && info->si_code == SEGV_MTESERR)
301 reinterpret_cast<lldb::addr_t>(info->si_addr));
302 break;
303 }
304 }
305}
306
308 int32_t allocation_tag_type = 0;
309 switch (GetProcess().GetArchitecture().GetMachine()) {
310 // aarch64_32 deliberately not here because there's no 32 bit MTE
311 case llvm::Triple::aarch64:
312 case llvm::Triple::aarch64_be:
314 break;
315 default:
316 return;
317 }
318
319 auto details =
320 GetRegisterContext().GetMemoryTaggingDetails(allocation_tag_type);
321 if (!details) {
322 llvm::consumeError(details.takeError());
323 return;
324 }
325
326 // We assume that the stop description is currently:
327 // signal SIGSEGV: sync tag check fault (fault address=<addr>)
328 // Remove the closing )
329 m_stop_description.pop_back();
330
331 std::stringstream ss;
332 std::unique_ptr<MemoryTagManager> manager(std::move(details->manager));
333
334 ss << " logical tag=0x" << std::hex << manager->GetLogicalTag(fault_addr);
335
336 std::vector<uint8_t> allocation_tag_data;
337 // The fault address may not be granule aligned. ReadMemoryTags will granule
338 // align any range you give it, potentially making it larger.
339 // To prevent this set len to 1. This always results in a range that is at
340 // most 1 granule in size and includes fault_addr.
341 Status status = GetProcess().ReadMemoryTags(allocation_tag_type, fault_addr,
342 1, allocation_tag_data);
343
344 if (status.Success()) {
345 llvm::Expected<std::vector<lldb::addr_t>> allocation_tag =
346 manager->UnpackTagsData(allocation_tag_data, 1);
347 if (allocation_tag) {
348 ss << " allocation tag=0x" << std::hex << allocation_tag->front() << ")";
349 } else {
350 llvm::consumeError(allocation_tag.takeError());
351 ss << ")";
352 }
353 } else
354 ss << ")";
355
356 m_stop_description += ss.str();
357}
358
360 if (!StateIsStoppedState(m_state, false))
361 return false;
362
363 // If we are stopped by a signal, return the signo.
364 if (signo && m_state == StateType::eStateStopped &&
366 *signo = m_stop_info.signo;
367 }
368
369 // Regardless, we are stopped.
370 return true;
371}
372
375 m_step_workaround.reset();
376
377 // On every stop, clear any cached register data structures
379
380 const StateType new_state = StateType::eStateStopped;
381 MaybeLogStateChange(new_state);
382 m_state = new_state;
383 m_stop_description.clear();
384}
385
387 Log *log = GetLog(LLDBLog::Thread);
388 LLDB_LOGF(log, "NativeThreadLinux::%s()", __FUNCTION__);
389
390 SetStopped();
391
393 m_stop_info.signo = SIGSTOP;
394}
395
403
405 SetStopped();
406
407 lldbassert(wp_index != LLDB_INVALID_INDEX32 && "wp_index cannot be invalid");
408
409 std::ostringstream ostr;
410 ostr << m_reg_context_up->GetWatchpointAddress(wp_index) << " ";
411 ostr << wp_index;
412
413 /*
414 * MIPS: Last 3bits of the watchpoint address are masked by the kernel. For
415 * example:
416 * 'n' is at 0x120010d00 and 'm' is 0x120010d04. When a watchpoint is set at
417 * 'm', then
418 * watch exception is generated even when 'n' is read/written. To handle this
419 * case,
420 * find the base address of the load/store instruction and append it in the
421 * stop-info
422 * packet.
423 */
424 ostr << " " << m_reg_context_up->GetWatchpointHitAddress(wp_index);
425
426 m_stop_description = ostr.str();
427
429 m_stop_info.signo = SIGTRAP;
430}
431
436
441
448
449void NativeThreadLinux::SetStoppedByFork(bool is_vfork, lldb::pid_t child_pid) {
450 SetStopped();
451
452 m_stop_info.reason =
454 m_stop_info.signo = SIGTRAP;
455 m_stop_info.details.fork.child_pid = child_pid;
456 m_stop_info.details.fork.child_tid = child_pid;
457 m_stop_description = std::to_string(child_pid);
458 m_stop_description += " ";
459 m_stop_description += std::to_string(child_pid);
460}
461
468
475
477 llvm::StringRef description) {
478 SetStopped();
479
481 m_stop_info.signo = 0;
482 m_stop_description = description.str();
483}
484
486 const StateType new_state = StateType::eStateExited;
487 MaybeLogStateChange(new_state);
488 m_state = new_state;
489
491}
492
494 Log *log = GetLog(LLDBLog::Thread);
495
496 NativeProcessLinux &process = GetProcess();
497
498 lldb::pid_t pid = process.GetID();
499 lldb::tid_t tid = GetID();
500
501 LLDB_LOGF(log,
502 "NativeThreadLinux::%s requesting thread stop(pid: %" PRIu64
503 ", tid: %" PRIu64 ")",
504 __FUNCTION__, pid, tid);
505
506 Status err;
507 errno = 0;
508 if (::tgkill(pid, tid, SIGSTOP) != 0) {
509 err = Status::FromErrno();
510 LLDB_LOGF(log,
511 "NativeThreadLinux::%s tgkill(%" PRIu64 ", %" PRIu64
512 ", SIGSTOP) failed: %s",
513 __FUNCTION__, pid, tid, err.AsCString());
514 }
515
516 return err;
517}
518
520 Log *log = GetLog(LLDBLog::Thread);
521 // If we're not logging, we're done.
522 if (!log)
523 return;
524
525 // If this is a state change to the same state, we're done.
526 lldb::StateType old_state = m_state;
527 if (new_state == old_state)
528 return;
529
530 LLDB_LOG(log, "pid={0}, tid={1}: changing from state {2} to {3}",
531 m_process.GetID(), GetID(), old_state, new_state);
532}
533
537
539 return static_cast<const NativeProcessLinux &>(m_process);
540}
541
542llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
544 auto siginfo_buf =
545 llvm::WritableMemoryBuffer::getNewUninitMemBuffer(sizeof(siginfo_t));
546 Status error =
547 GetProcess().GetSignalInfo(GetID(), siginfo_buf->getBufferStart());
548 if (!error.Success())
549 return error.ToError();
550 return std::move(siginfo_buf);
551}
static llvm::raw_ostream & error(Stream &strm)
std::string GetCrashReasonString(const siginfo_t &info)
#define lldbassert(x)
Definition LLDBAssert.h:16
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:364
#define LLDB_LOGF(log,...)
Definition Log.h:378
#define SEGV_MTESERR
#define tgkill(pid, tid, sig)
#define SIGILL
#define SIGFPE
#define SIGSEGV
#define SIGBUS
void void Printf(const char *format,...) __attribute__((format(printf
Prefer using LLDB_LOGF whenever possible.
Definition Log.cpp:156
virtual const HardwareBreakpointMap & GetHardwareBreakpointMap() const
virtual const NativeWatchpointList::WatchpointMap & GetWatchpointMap() const
NativeThreadProtocol(NativeProcessProtocol &process, lldb::tid_t tid)
An error handling class.
Definition Status.h:118
static Status FromErrno()
Set the current error to errno.
Definition Status.cpp:299
static Status FromErrorString(const char *str)
Definition Status.h:141
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition Status.cpp:194
bool Success() const
Test for success condition.
Definition Status.cpp:303
Status GetSignalInfo(lldb::tid_t tid, void *siginfo) const
Writes a siginfo_t structure corresponding to the given thread ID to the memory region pointed to by ...
Status ReadMemoryTags(int32_t type, lldb::addr_t addr, size_t len, std::vector< uint8_t > &tags) override
static Status PtraceWrapper(int req, lldb::pid_t pid, void *addr=nullptr, void *data=nullptr, size_t data_size=0, long *result=nullptr)
}
virtual llvm::Expected< MemoryTaggingDetails > GetMemoryTaggingDetails(int32_t type)
Return architecture specific data needed to use memory tags, if they are supported.
NativeThreadLinux(NativeProcessLinux &process, lldb::tid_t tid)
void AnnotateSyncTagCheckFault(lldb::addr_t fault_addr)
Extend m_stop_description with logical and allocation tag values.
void MaybeLogStateChange(lldb::StateType new_state)
bool GetStopReason(ThreadStopInfo &stop_info, std::string &description) override
llvm::Expected< std::unique_ptr< llvm::MemoryBuffer > > GetSiginfo() const override
void SetStoppedBySignal(uint32_t signo, const siginfo_t *info=nullptr)
Status RemoveWatchpoint(lldb::addr_t addr) override
std::unique_ptr< NativeRegisterContextLinux > m_reg_context_up
Status SingleStep(uint32_t signo)
Single steps the thread.
std::unique_ptr< SingleStepWorkaround > m_step_workaround
Status SetWatchpoint(lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware) override
bool IsStopped(int *signo)
Return true if the thread is stopped.
Status RemoveHardwareBreakpoint(lldb::addr_t addr) override
Status SetHardwareBreakpoint(lldb::addr_t addr, size_t size) override
void SetStoppedByProcessorTrace(llvm::StringRef description)
NativeRegisterContextLinux & GetRegisterContext() override
Status Resume(uint32_t signo)
Resumes the thread.
void SetStoppedByFork(bool is_vfork, lldb::pid_t child_pid)
static std::unique_ptr< SingleStepWorkaround > Get(::pid_t tid)
#define LLDB_INVALID_SIGNAL_NUMBER
#define LLDB_INVALID_INDEX32
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:327
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getProcFile(::pid_t pid, ::pid_t tid, const llvm::Twine &file)
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
const char * StateAsCString(lldb::StateType state)
Converts a StateType to a C string.
Definition State.cpp:14
StateType
Process and Thread States.
@ eStateUnloaded
Process is object is valid, but not currently loaded.
@ eStateConnected
Process is connected to remote debug services, but not launched or attached to anything yet.
@ eStateDetached
Process has been detached and can't be examined.
@ eStateStopped
Process or thread is stopped and can be examined.
@ eStateSuspended
Process or thread is in a suspended state as far as the debugger is concerned while other processes o...
@ eStateRunning
Process or thread is running and can't be examined.
@ eStateLaunching
Process is in the process of launching.
@ eStateAttaching
Process is currently trying to attach.
@ eStateExited
Process has exited and can't be examined.
@ eStateStepping
Process or thread is in the process of stepping and can not be examined.
@ eStateCrashed
Process or thread has crashed and can be examined.
uint64_t pid_t
Definition lldb-types.h:83
uint64_t addr_t
Definition lldb-types.h:80
@ eStopReasonInstrumentation
@ eStopReasonPlanComplete
@ eStopReasonHistoryBoundary
@ eStopReasonBreakpoint
@ eStopReasonExec
Program was re-exec'ed.
@ eStopReasonVForkDone
@ eStopReasonProcessorTrace
@ eStopReasonThreadExiting
@ eStopReasonException
@ eStopReasonWatchpoint
uint64_t tid_t
Definition lldb-types.h:84
struct lldb_private::ThreadStopInfo::@116236113001137253323017204263037302160273237376::@034237007264067231263360140073224264215170222231 exception
lldb::StopReason reason
Definition Debug.h:132
union lldb_private::ThreadStopInfo::@116236113001137253323017204263037302160273237376 details
#define SIGSTOP
#define SIGTRAP