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" 15 #include "NativeRegisterContextLinux.h" 16 #include "SingleStepCheck.h" 17 18 #include "lldb/Host/HostNativeThread.h" 19 #include "lldb/Host/linux/Ptrace.h" 20 #include "lldb/Host/linux/Support.h" 21 #include "lldb/Utility/LLDBAssert.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 28 #include "Plugins/Process/POSIX/CrashReason.h" 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; 51 case eStopReasonBreakpoint: 52 log.Printf("%s: %s breakpoint, stopping signal 0x%" PRIx32, __FUNCTION__, 53 header, stop_info.details.signal.signo); 54 return; 55 case eStopReasonWatchpoint: 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; 63 case eStopReasonException: 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; 71 case eStopReasonPlanComplete: 72 log.Printf("%s: %s plan complete", __FUNCTION__, header); 73 return; 74 case eStopReasonThreadExiting: 75 log.Printf("%s: %s thread exiting", __FUNCTION__, header); 76 return; 77 case eStopReasonInstrumentation: 78 log.Printf("%s: %s instrumentation", __FUNCTION__, header); 79 return; 80 case eStopReasonProcessorTrace: 81 log.Printf("%s: %s processor trace", __FUNCTION__, header); 82 return; 83 default: 84 log.Printf("%s: %s invalid stop reason %" PRIu32, __FUNCTION__, header, 85 static_cast<uint32_t>(stop_info.reason)); 86 } 87 } 88 } 89 90 NativeThreadLinux::NativeThreadLinux(NativeProcessLinux &process, 91 lldb::tid_t tid) 92 : NativeThreadProtocol(process, tid), m_state(StateType::eStateInvalid), 93 m_stop_info(), 94 m_reg_context_up( 95 NativeRegisterContextLinux::CreateHostNativeRegisterContextLinux( 96 process.GetArchitecture(), *this)), 97 m_stop_description() {} 98 99 std::string NativeThreadLinux::GetName() { 100 NativeProcessLinux &process = GetProcess(); 101 102 auto BufferOrError = getProcFile(process.GetID(), GetID(), "comm"); 103 if (!BufferOrError) 104 return ""; 105 return std::string(BufferOrError.get()->getBuffer().rtrim('\n')); 106 } 107 108 lldb::StateType NativeThreadLinux::GetState() { return m_state; } 109 110 bool NativeThreadLinux::GetStopReason(ThreadStopInfo &stop_info, 111 std::string &description) { 112 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD)); 113 114 description.clear(); 115 116 switch (m_state) { 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 LLDB_LOGF(log, 140 "NativeThreadLinux::%s tid %" PRIu64 141 " in state %s cannot answer stop reason", 142 __FUNCTION__, GetID(), StateAsCString(m_state)); 143 } 144 return false; 145 } 146 llvm_unreachable("unhandled StateType!"); 147 } 148 149 Status NativeThreadLinux::SetWatchpoint(lldb::addr_t addr, size_t size, 150 uint32_t watch_flags, bool hardware) { 151 if (!hardware) 152 return Status("not implemented"); 153 if (m_state == eStateLaunching) 154 return Status(); 155 Status error = RemoveWatchpoint(addr); 156 if (error.Fail()) 157 return error; 158 uint32_t wp_index = 159 m_reg_context_up->SetHardwareWatchpoint(addr, size, watch_flags); 160 if (wp_index == LLDB_INVALID_INDEX32) 161 return Status("Setting hardware watchpoint failed."); 162 m_watchpoint_index_map.insert({addr, wp_index}); 163 return Status(); 164 } 165 166 Status NativeThreadLinux::RemoveWatchpoint(lldb::addr_t addr) { 167 auto wp = m_watchpoint_index_map.find(addr); 168 if (wp == m_watchpoint_index_map.end()) 169 return Status(); 170 uint32_t wp_index = wp->second; 171 m_watchpoint_index_map.erase(wp); 172 if (m_reg_context_up->ClearHardwareWatchpoint(wp_index)) 173 return Status(); 174 return Status("Clearing hardware watchpoint failed."); 175 } 176 177 Status NativeThreadLinux::SetHardwareBreakpoint(lldb::addr_t addr, 178 size_t size) { 179 if (m_state == eStateLaunching) 180 return Status(); 181 182 Status error = RemoveHardwareBreakpoint(addr); 183 if (error.Fail()) 184 return error; 185 186 uint32_t bp_index = m_reg_context_up->SetHardwareBreakpoint(addr, size); 187 188 if (bp_index == LLDB_INVALID_INDEX32) 189 return Status("Setting hardware breakpoint failed."); 190 191 m_hw_break_index_map.insert({addr, bp_index}); 192 return Status(); 193 } 194 195 Status NativeThreadLinux::RemoveHardwareBreakpoint(lldb::addr_t addr) { 196 auto bp = m_hw_break_index_map.find(addr); 197 if (bp == m_hw_break_index_map.end()) 198 return Status(); 199 200 uint32_t bp_index = bp->second; 201 if (m_reg_context_up->ClearHardwareBreakpoint(bp_index)) { 202 m_hw_break_index_map.erase(bp); 203 return Status(); 204 } 205 206 return Status("Clearing hardware breakpoint failed."); 207 } 208 209 Status NativeThreadLinux::Resume(uint32_t signo) { 210 const StateType new_state = StateType::eStateRunning; 211 MaybeLogStateChange(new_state); 212 m_state = new_state; 213 214 m_stop_info.reason = StopReason::eStopReasonNone; 215 m_stop_description.clear(); 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 251 Status NativeThreadLinux::SingleStep(uint32_t signo) { 252 const StateType new_state = StateType::eStateStepping; 253 MaybeLogStateChange(new_state); 254 m_state = new_state; 255 m_stop_info.reason = StopReason::eStopReasonNone; 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. 261 m_step_workaround = SingleStepWorkaround::Get(m_tid); 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. 271 return NativeProcessLinux::PtraceWrapper( 272 GetProcess().SupportHardwareSingleStepping() ? PTRACE_SINGLESTEP 273 : PTRACE_CONT, 274 m_tid, nullptr, reinterpret_cast<void *>(data)); 275 } 276 277 void NativeThreadLinux::SetStoppedBySignal(uint32_t signo, 278 const siginfo_t *info) { 279 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD)); 280 LLDB_LOGF(log, "NativeThreadLinux::%s called with signal 0x%02" PRIx32, 281 __FUNCTION__, signo); 282 283 SetStopped(); 284 285 m_stop_info.reason = StopReason::eStopReasonSignal; 286 m_stop_info.details.signal.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: 295 // In case of MIPS64 target, SI_KERNEL is generated for invalid 64bit 296 // address. 297 const auto reason = 298 (info->si_signo == SIGBUS && info->si_code == SI_KERNEL) 299 ? CrashReason::eInvalidAddress 300 : GetCrashReason(*info); 301 m_stop_description = GetCrashReasonString(reason, *info); 302 break; 303 } 304 } 305 } 306 307 bool NativeThreadLinux::IsStopped(int *signo) { 308 if (!StateIsStoppedState(m_state, false)) 309 return false; 310 311 // If we are stopped by a signal, return the signo. 312 if (signo && m_state == StateType::eStateStopped && 313 m_stop_info.reason == StopReason::eStopReasonSignal) { 314 *signo = m_stop_info.details.signal.signo; 315 } 316 317 // Regardless, we are stopped. 318 return true; 319 } 320 321 void NativeThreadLinux::SetStopped() { 322 if (m_state == StateType::eStateStepping) 323 m_step_workaround.reset(); 324 325 // On every stop, clear any cached register data structures 326 GetRegisterContext().InvalidateAllRegisters(); 327 328 const StateType new_state = StateType::eStateStopped; 329 MaybeLogStateChange(new_state); 330 m_state = new_state; 331 m_stop_description.clear(); 332 } 333 334 void NativeThreadLinux::SetStoppedByExec() { 335 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD)); 336 LLDB_LOGF(log, "NativeThreadLinux::%s()", __FUNCTION__); 337 338 SetStopped(); 339 340 m_stop_info.reason = StopReason::eStopReasonExec; 341 m_stop_info.details.signal.signo = SIGSTOP; 342 } 343 344 void NativeThreadLinux::SetStoppedByBreakpoint() { 345 SetStopped(); 346 347 m_stop_info.reason = StopReason::eStopReasonBreakpoint; 348 m_stop_info.details.signal.signo = SIGTRAP; 349 m_stop_description.clear(); 350 } 351 352 void NativeThreadLinux::SetStoppedByWatchpoint(uint32_t wp_index) { 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 376 m_stop_info.reason = StopReason::eStopReasonWatchpoint; 377 m_stop_info.details.signal.signo = SIGTRAP; 378 } 379 380 bool NativeThreadLinux::IsStoppedAtBreakpoint() { 381 return GetState() == StateType::eStateStopped && 382 m_stop_info.reason == StopReason::eStopReasonBreakpoint; 383 } 384 385 bool NativeThreadLinux::IsStoppedAtWatchpoint() { 386 return GetState() == StateType::eStateStopped && 387 m_stop_info.reason == StopReason::eStopReasonWatchpoint; 388 } 389 390 void NativeThreadLinux::SetStoppedByTrace() { 391 SetStopped(); 392 393 m_stop_info.reason = StopReason::eStopReasonTrace; 394 m_stop_info.details.signal.signo = SIGTRAP; 395 } 396 397 void NativeThreadLinux::SetStoppedByFork(bool is_vfork, lldb::pid_t child_pid) { 398 SetStopped(); 399 400 m_stop_info.reason = 401 is_vfork ? StopReason::eStopReasonVFork : StopReason::eStopReasonFork; 402 m_stop_info.details.fork.child_pid = child_pid; 403 m_stop_info.details.fork.child_tid = child_pid; 404 } 405 406 void NativeThreadLinux::SetStoppedByVForkDone() { 407 SetStopped(); 408 409 m_stop_info.reason = StopReason::eStopReasonVForkDone; 410 } 411 412 void NativeThreadLinux::SetStoppedWithNoReason() { 413 SetStopped(); 414 415 m_stop_info.reason = StopReason::eStopReasonNone; 416 m_stop_info.details.signal.signo = 0; 417 } 418 419 void NativeThreadLinux::SetStoppedByProcessorTrace( 420 llvm::StringRef description) { 421 SetStopped(); 422 423 m_stop_info.reason = StopReason::eStopReasonProcessorTrace; 424 m_stop_info.details.signal.signo = 0; 425 m_stop_description = description.str(); 426 } 427 428 void NativeThreadLinux::SetExited() { 429 const StateType new_state = StateType::eStateExited; 430 MaybeLogStateChange(new_state); 431 m_state = new_state; 432 433 m_stop_info.reason = StopReason::eStopReasonThreadExiting; 434 } 435 436 Status NativeThreadLinux::RequestStop() { 437 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD)); 438 439 NativeProcessLinux &process = GetProcess(); 440 441 lldb::pid_t pid = process.GetID(); 442 lldb::tid_t tid = GetID(); 443 444 LLDB_LOGF(log, 445 "NativeThreadLinux::%s requesting thread stop(pid: %" PRIu64 446 ", tid: %" PRIu64 ")", 447 __FUNCTION__, pid, tid); 448 449 Status err; 450 errno = 0; 451 if (::tgkill(pid, tid, SIGSTOP) != 0) { 452 err.SetErrorToErrno(); 453 LLDB_LOGF(log, 454 "NativeThreadLinux::%s tgkill(%" PRIu64 ", %" PRIu64 455 ", SIGSTOP) failed: %s", 456 __FUNCTION__, pid, tid, err.AsCString()); 457 } 458 459 return err; 460 } 461 462 void NativeThreadLinux::MaybeLogStateChange(lldb::StateType new_state) { 463 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD)); 464 // If we're not logging, we're done. 465 if (!log) 466 return; 467 468 // If this is a state change to the same state, we're done. 469 lldb::StateType old_state = m_state; 470 if (new_state == old_state) 471 return; 472 473 LLDB_LOG(log, "pid={0}, tid={1}: changing from state {2} to {3}", 474 m_process.GetID(), GetID(), old_state, new_state); 475 } 476 477 NativeProcessLinux &NativeThreadLinux::GetProcess() { 478 return static_cast<NativeProcessLinux &>(m_process); 479 } 480