1 //===-- NativeProcessProtocol.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 "lldb/Host/common/NativeProcessProtocol.h" 10 #include "lldb/Host/Host.h" 11 #include "lldb/Host/common/NativeBreakpointList.h" 12 #include "lldb/Host/common/NativeRegisterContext.h" 13 #include "lldb/Host/common/NativeThreadProtocol.h" 14 #include "lldb/Utility/LLDBAssert.h" 15 #include "lldb/Utility/LLDBLog.h" 16 #include "lldb/Utility/Log.h" 17 #include "lldb/Utility/State.h" 18 #include "lldb/lldb-enumerations.h" 19 20 #include "llvm/Support/Process.h" 21 22 using namespace lldb; 23 using namespace lldb_private; 24 25 // NativeProcessProtocol Members 26 27 NativeProcessProtocol::NativeProcessProtocol(lldb::pid_t pid, int terminal_fd, 28 NativeDelegate &delegate) 29 : m_pid(pid), m_delegate(delegate), m_terminal_fd(terminal_fd) { 30 delegate.InitializeDelegate(this); 31 } 32 33 lldb_private::Status NativeProcessProtocol::Interrupt() { 34 Status error; 35 #if !defined(SIGSTOP) 36 error.SetErrorString("local host does not support signaling"); 37 return error; 38 #else 39 return Signal(SIGSTOP); 40 #endif 41 } 42 43 Status NativeProcessProtocol::IgnoreSignals(llvm::ArrayRef<int> signals) { 44 m_signals_to_ignore.clear(); 45 m_signals_to_ignore.insert(signals.begin(), signals.end()); 46 return Status(); 47 } 48 49 lldb_private::Status 50 NativeProcessProtocol::GetMemoryRegionInfo(lldb::addr_t load_addr, 51 MemoryRegionInfo &range_info) { 52 // Default: not implemented. 53 return Status("not implemented"); 54 } 55 56 lldb_private::Status 57 NativeProcessProtocol::ReadMemoryTags(int32_t type, lldb::addr_t addr, 58 size_t len, std::vector<uint8_t> &tags) { 59 return Status("not implemented"); 60 } 61 62 lldb_private::Status 63 NativeProcessProtocol::WriteMemoryTags(int32_t type, lldb::addr_t addr, 64 size_t len, 65 const std::vector<uint8_t> &tags) { 66 return Status("not implemented"); 67 } 68 69 llvm::Optional<WaitStatus> NativeProcessProtocol::GetExitStatus() { 70 if (m_state == lldb::eStateExited) 71 return m_exit_status; 72 73 return llvm::None; 74 } 75 76 bool NativeProcessProtocol::SetExitStatus(WaitStatus status, 77 bool bNotifyStateChange) { 78 Log *log = GetLog(LLDBLog::Process); 79 LLDB_LOG(log, "status = {0}, notify = {1}", status, bNotifyStateChange); 80 81 // Exit status already set 82 if (m_state == lldb::eStateExited) { 83 if (m_exit_status) 84 LLDB_LOG(log, "exit status already set to {0}", *m_exit_status); 85 else 86 LLDB_LOG(log, "state is exited, but status not set"); 87 return false; 88 } 89 90 m_state = lldb::eStateExited; 91 m_exit_status = status; 92 93 if (bNotifyStateChange) 94 SynchronouslyNotifyProcessStateChanged(lldb::eStateExited); 95 96 return true; 97 } 98 99 NativeThreadProtocol *NativeProcessProtocol::GetThreadAtIndex(uint32_t idx) { 100 std::lock_guard<std::recursive_mutex> guard(m_threads_mutex); 101 if (idx < m_threads.size()) 102 return m_threads[idx].get(); 103 return nullptr; 104 } 105 106 NativeThreadProtocol * 107 NativeProcessProtocol::GetThreadByIDUnlocked(lldb::tid_t tid) { 108 for (const auto &thread : m_threads) { 109 if (thread->GetID() == tid) 110 return thread.get(); 111 } 112 return nullptr; 113 } 114 115 NativeThreadProtocol *NativeProcessProtocol::GetThreadByID(lldb::tid_t tid) { 116 std::lock_guard<std::recursive_mutex> guard(m_threads_mutex); 117 return GetThreadByIDUnlocked(tid); 118 } 119 120 bool NativeProcessProtocol::IsAlive() const { 121 return m_state != eStateDetached && m_state != eStateExited && 122 m_state != eStateInvalid && m_state != eStateUnloaded; 123 } 124 125 const NativeWatchpointList::WatchpointMap & 126 NativeProcessProtocol::GetWatchpointMap() const { 127 return m_watchpoint_list.GetWatchpointMap(); 128 } 129 130 llvm::Optional<std::pair<uint32_t, uint32_t>> 131 NativeProcessProtocol::GetHardwareDebugSupportInfo() const { 132 Log *log = GetLog(LLDBLog::Process); 133 134 // get any thread 135 NativeThreadProtocol *thread( 136 const_cast<NativeProcessProtocol *>(this)->GetThreadAtIndex(0)); 137 if (!thread) { 138 LLDB_LOG(log, "failed to find a thread to grab a NativeRegisterContext!"); 139 return llvm::None; 140 } 141 142 NativeRegisterContext ®_ctx = thread->GetRegisterContext(); 143 return std::make_pair(reg_ctx.NumSupportedHardwareBreakpoints(), 144 reg_ctx.NumSupportedHardwareWatchpoints()); 145 } 146 147 Status NativeProcessProtocol::SetWatchpoint(lldb::addr_t addr, size_t size, 148 uint32_t watch_flags, 149 bool hardware) { 150 // This default implementation assumes setting the watchpoint for the process 151 // will require setting the watchpoint for each of the threads. Furthermore, 152 // it will track watchpoints set for the process and will add them to each 153 // thread that is attached to via the (FIXME implement) OnThreadAttached () 154 // method. 155 156 Log *log = GetLog(LLDBLog::Process); 157 158 // Update the thread list 159 UpdateThreads(); 160 161 // Keep track of the threads we successfully set the watchpoint for. If one 162 // of the thread watchpoint setting operations fails, back off and remove the 163 // watchpoint for all the threads that were successfully set so we get back 164 // to a consistent state. 165 std::vector<NativeThreadProtocol *> watchpoint_established_threads; 166 167 // Tell each thread to set a watchpoint. In the event that hardware 168 // watchpoints are requested but the SetWatchpoint fails, try to set a 169 // software watchpoint as a fallback. It's conceivable that if there are 170 // more threads than hardware watchpoints available, some of the threads will 171 // fail to set hardware watchpoints while software ones may be available. 172 std::lock_guard<std::recursive_mutex> guard(m_threads_mutex); 173 for (const auto &thread : m_threads) { 174 assert(thread && "thread list should not have a NULL thread!"); 175 176 Status thread_error = 177 thread->SetWatchpoint(addr, size, watch_flags, hardware); 178 if (thread_error.Fail() && hardware) { 179 // Try software watchpoints since we failed on hardware watchpoint 180 // setting and we may have just run out of hardware watchpoints. 181 thread_error = thread->SetWatchpoint(addr, size, watch_flags, false); 182 if (thread_error.Success()) 183 LLDB_LOG(log, 184 "hardware watchpoint requested but software watchpoint set"); 185 } 186 187 if (thread_error.Success()) { 188 // Remember that we set this watchpoint successfully in case we need to 189 // clear it later. 190 watchpoint_established_threads.push_back(thread.get()); 191 } else { 192 // Unset the watchpoint for each thread we successfully set so that we 193 // get back to a consistent state of "not set" for the watchpoint. 194 for (auto unwatch_thread_sp : watchpoint_established_threads) { 195 Status remove_error = unwatch_thread_sp->RemoveWatchpoint(addr); 196 if (remove_error.Fail()) 197 LLDB_LOG(log, "RemoveWatchpoint failed for pid={0}, tid={1}: {2}", 198 GetID(), unwatch_thread_sp->GetID(), remove_error); 199 } 200 201 return thread_error; 202 } 203 } 204 return m_watchpoint_list.Add(addr, size, watch_flags, hardware); 205 } 206 207 Status NativeProcessProtocol::RemoveWatchpoint(lldb::addr_t addr) { 208 // Update the thread list 209 UpdateThreads(); 210 211 Status overall_error; 212 213 std::lock_guard<std::recursive_mutex> guard(m_threads_mutex); 214 for (const auto &thread : m_threads) { 215 assert(thread && "thread list should not have a NULL thread!"); 216 217 const Status thread_error = thread->RemoveWatchpoint(addr); 218 if (thread_error.Fail()) { 219 // Keep track of the first thread error if any threads fail. We want to 220 // try to remove the watchpoint from every thread, though, even if one or 221 // more have errors. 222 if (!overall_error.Fail()) 223 overall_error = thread_error; 224 } 225 } 226 const Status error = m_watchpoint_list.Remove(addr); 227 return overall_error.Fail() ? overall_error : error; 228 } 229 230 const HardwareBreakpointMap & 231 NativeProcessProtocol::GetHardwareBreakpointMap() const { 232 return m_hw_breakpoints_map; 233 } 234 235 Status NativeProcessProtocol::SetHardwareBreakpoint(lldb::addr_t addr, 236 size_t size) { 237 // This default implementation assumes setting a hardware breakpoint for this 238 // process will require setting same hardware breakpoint for each of its 239 // existing threads. New thread will do the same once created. 240 Log *log = GetLog(LLDBLog::Process); 241 242 // Update the thread list 243 UpdateThreads(); 244 245 // Exit here if target does not have required hardware breakpoint capability. 246 auto hw_debug_cap = GetHardwareDebugSupportInfo(); 247 248 if (hw_debug_cap == llvm::None || hw_debug_cap->first == 0 || 249 hw_debug_cap->first <= m_hw_breakpoints_map.size()) 250 return Status("Target does not have required no of hardware breakpoints"); 251 252 // Vector below stores all thread pointer for which we have we successfully 253 // set this hardware breakpoint. If any of the current process threads fails 254 // to set this hardware breakpoint then roll back and remove this breakpoint 255 // for all the threads that had already set it successfully. 256 std::vector<NativeThreadProtocol *> breakpoint_established_threads; 257 258 // Request to set a hardware breakpoint for each of current process threads. 259 std::lock_guard<std::recursive_mutex> guard(m_threads_mutex); 260 for (const auto &thread : m_threads) { 261 assert(thread && "thread list should not have a NULL thread!"); 262 263 Status thread_error = thread->SetHardwareBreakpoint(addr, size); 264 if (thread_error.Success()) { 265 // Remember that we set this breakpoint successfully in case we need to 266 // clear it later. 267 breakpoint_established_threads.push_back(thread.get()); 268 } else { 269 // Unset the breakpoint for each thread we successfully set so that we 270 // get back to a consistent state of "not set" for this hardware 271 // breakpoint. 272 for (auto rollback_thread_sp : breakpoint_established_threads) { 273 Status remove_error = 274 rollback_thread_sp->RemoveHardwareBreakpoint(addr); 275 if (remove_error.Fail()) 276 LLDB_LOG(log, 277 "RemoveHardwareBreakpoint failed for pid={0}, tid={1}: {2}", 278 GetID(), rollback_thread_sp->GetID(), remove_error); 279 } 280 281 return thread_error; 282 } 283 } 284 285 // Register new hardware breakpoint into hardware breakpoints map of current 286 // process. 287 m_hw_breakpoints_map[addr] = {addr, size}; 288 289 return Status(); 290 } 291 292 Status NativeProcessProtocol::RemoveHardwareBreakpoint(lldb::addr_t addr) { 293 // Update the thread list 294 UpdateThreads(); 295 296 Status error; 297 298 std::lock_guard<std::recursive_mutex> guard(m_threads_mutex); 299 for (const auto &thread : m_threads) { 300 assert(thread && "thread list should not have a NULL thread!"); 301 error = thread->RemoveHardwareBreakpoint(addr); 302 } 303 304 // Also remove from hardware breakpoint map of current process. 305 m_hw_breakpoints_map.erase(addr); 306 307 return error; 308 } 309 310 void NativeProcessProtocol::SynchronouslyNotifyProcessStateChanged( 311 lldb::StateType state) { 312 Log *log = GetLog(LLDBLog::Process); 313 314 m_delegate.ProcessStateChanged(this, state); 315 NotifyTracersProcessStateChanged(state); 316 317 LLDB_LOG(log, "sent state notification [{0}] from process {1}", state, 318 GetID()); 319 } 320 321 void NativeProcessProtocol::NotifyDidExec() { 322 Log *log = GetLog(LLDBLog::Process); 323 LLDB_LOG(log, "process {0} exec()ed", GetID()); 324 325 m_delegate.DidExec(this); 326 } 327 328 Status NativeProcessProtocol::SetSoftwareBreakpoint(lldb::addr_t addr, 329 uint32_t size_hint) { 330 Log *log = GetLog(LLDBLog::Breakpoints); 331 LLDB_LOG(log, "addr = {0:x}, size_hint = {1}", addr, size_hint); 332 333 auto it = m_software_breakpoints.find(addr); 334 if (it != m_software_breakpoints.end()) { 335 ++it->second.ref_count; 336 return Status(); 337 } 338 auto expected_bkpt = EnableSoftwareBreakpoint(addr, size_hint); 339 if (!expected_bkpt) 340 return Status(expected_bkpt.takeError()); 341 342 m_software_breakpoints.emplace(addr, std::move(*expected_bkpt)); 343 return Status(); 344 } 345 346 Status NativeProcessProtocol::RemoveSoftwareBreakpoint(lldb::addr_t addr) { 347 Log *log = GetLog(LLDBLog::Breakpoints); 348 LLDB_LOG(log, "addr = {0:x}", addr); 349 auto it = m_software_breakpoints.find(addr); 350 if (it == m_software_breakpoints.end()) 351 return Status("Breakpoint not found."); 352 assert(it->second.ref_count > 0); 353 if (--it->second.ref_count > 0) 354 return Status(); 355 356 // This is the last reference. Let's remove the breakpoint. 357 Status error; 358 359 // Clear a software breakpoint instruction 360 llvm::SmallVector<uint8_t, 4> curr_break_op( 361 it->second.breakpoint_opcodes.size(), 0); 362 363 // Read the breakpoint opcode 364 size_t bytes_read = 0; 365 error = 366 ReadMemory(addr, curr_break_op.data(), curr_break_op.size(), bytes_read); 367 if (error.Fail() || bytes_read < curr_break_op.size()) { 368 return Status("addr=0x%" PRIx64 369 ": tried to read %zu bytes but only read %zu", 370 addr, curr_break_op.size(), bytes_read); 371 } 372 const auto &saved = it->second.saved_opcodes; 373 // Make sure the breakpoint opcode exists at this address 374 if (makeArrayRef(curr_break_op) != it->second.breakpoint_opcodes) { 375 if (curr_break_op != it->second.saved_opcodes) 376 return Status("Original breakpoint trap is no longer in memory."); 377 LLDB_LOG(log, 378 "Saved opcodes ({0:@[x]}) have already been restored at {1:x}.", 379 llvm::make_range(saved.begin(), saved.end()), addr); 380 } else { 381 // We found a valid breakpoint opcode at this address, now restore the 382 // saved opcode. 383 size_t bytes_written = 0; 384 error = WriteMemory(addr, saved.data(), saved.size(), bytes_written); 385 if (error.Fail() || bytes_written < saved.size()) { 386 return Status("addr=0x%" PRIx64 387 ": tried to write %zu bytes but only wrote %zu", 388 addr, saved.size(), bytes_written); 389 } 390 391 // Verify that our original opcode made it back to the inferior 392 llvm::SmallVector<uint8_t, 4> verify_opcode(saved.size(), 0); 393 size_t verify_bytes_read = 0; 394 error = ReadMemory(addr, verify_opcode.data(), verify_opcode.size(), 395 verify_bytes_read); 396 if (error.Fail() || verify_bytes_read < verify_opcode.size()) { 397 return Status("addr=0x%" PRIx64 398 ": tried to read %zu verification bytes but only read %zu", 399 addr, verify_opcode.size(), verify_bytes_read); 400 } 401 if (verify_opcode != saved) 402 LLDB_LOG(log, "Restoring bytes at {0:x}: {1:@[x]}", addr, 403 llvm::make_range(saved.begin(), saved.end())); 404 } 405 406 m_software_breakpoints.erase(it); 407 return Status(); 408 } 409 410 llvm::Expected<NativeProcessProtocol::SoftwareBreakpoint> 411 NativeProcessProtocol::EnableSoftwareBreakpoint(lldb::addr_t addr, 412 uint32_t size_hint) { 413 Log *log = GetLog(LLDBLog::Breakpoints); 414 415 auto expected_trap = GetSoftwareBreakpointTrapOpcode(size_hint); 416 if (!expected_trap) 417 return expected_trap.takeError(); 418 419 llvm::SmallVector<uint8_t, 4> saved_opcode_bytes(expected_trap->size(), 0); 420 // Save the original opcodes by reading them so we can restore later. 421 size_t bytes_read = 0; 422 Status error = ReadMemory(addr, saved_opcode_bytes.data(), 423 saved_opcode_bytes.size(), bytes_read); 424 if (error.Fail()) 425 return error.ToError(); 426 427 // Ensure we read as many bytes as we expected. 428 if (bytes_read != saved_opcode_bytes.size()) { 429 return llvm::createStringError( 430 llvm::inconvertibleErrorCode(), 431 "Failed to read memory while attempting to set breakpoint: attempted " 432 "to read {0} bytes but only read {1}.", 433 saved_opcode_bytes.size(), bytes_read); 434 } 435 436 LLDB_LOG( 437 log, "Overwriting bytes at {0:x}: {1:@[x]}", addr, 438 llvm::make_range(saved_opcode_bytes.begin(), saved_opcode_bytes.end())); 439 440 // Write a software breakpoint in place of the original opcode. 441 size_t bytes_written = 0; 442 error = WriteMemory(addr, expected_trap->data(), expected_trap->size(), 443 bytes_written); 444 if (error.Fail()) 445 return error.ToError(); 446 447 // Ensure we wrote as many bytes as we expected. 448 if (bytes_written != expected_trap->size()) { 449 return llvm::createStringError( 450 llvm::inconvertibleErrorCode(), 451 "Failed write memory while attempting to set " 452 "breakpoint: attempted to write {0} bytes but only wrote {1}", 453 expected_trap->size(), bytes_written); 454 } 455 456 llvm::SmallVector<uint8_t, 4> verify_bp_opcode_bytes(expected_trap->size(), 457 0); 458 size_t verify_bytes_read = 0; 459 error = ReadMemory(addr, verify_bp_opcode_bytes.data(), 460 verify_bp_opcode_bytes.size(), verify_bytes_read); 461 if (error.Fail()) 462 return error.ToError(); 463 464 // Ensure we read as many verification bytes as we expected. 465 if (verify_bytes_read != verify_bp_opcode_bytes.size()) { 466 return llvm::createStringError( 467 llvm::inconvertibleErrorCode(), 468 "Failed to read memory while " 469 "attempting to verify breakpoint: attempted to read {0} bytes " 470 "but only read {1}", 471 verify_bp_opcode_bytes.size(), verify_bytes_read); 472 } 473 474 if (llvm::makeArrayRef(verify_bp_opcode_bytes.data(), verify_bytes_read) != 475 *expected_trap) { 476 return llvm::createStringError( 477 llvm::inconvertibleErrorCode(), 478 "Verification of software breakpoint " 479 "writing failed - trap opcodes not successfully read back " 480 "after writing when setting breakpoint at {0:x}", 481 addr); 482 } 483 484 LLDB_LOG(log, "addr = {0:x}: SUCCESS", addr); 485 return SoftwareBreakpoint{1, saved_opcode_bytes, *expected_trap}; 486 } 487 488 llvm::Expected<llvm::ArrayRef<uint8_t>> 489 NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_t size_hint) { 490 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4}; 491 static const uint8_t g_i386_opcode[] = {0xCC}; 492 static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d}; 493 static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00}; 494 static const uint8_t g_s390x_opcode[] = {0x00, 0x01}; 495 static const uint8_t g_ppc_opcode[] = {0x7f, 0xe0, 0x00, 0x08}; // trap 496 static const uint8_t g_ppcle_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap 497 498 switch (GetArchitecture().GetMachine()) { 499 case llvm::Triple::aarch64: 500 case llvm::Triple::aarch64_32: 501 return llvm::makeArrayRef(g_aarch64_opcode); 502 503 case llvm::Triple::x86: 504 case llvm::Triple::x86_64: 505 return llvm::makeArrayRef(g_i386_opcode); 506 507 case llvm::Triple::mips: 508 case llvm::Triple::mips64: 509 return llvm::makeArrayRef(g_mips64_opcode); 510 511 case llvm::Triple::mipsel: 512 case llvm::Triple::mips64el: 513 return llvm::makeArrayRef(g_mips64el_opcode); 514 515 case llvm::Triple::systemz: 516 return llvm::makeArrayRef(g_s390x_opcode); 517 518 case llvm::Triple::ppc: 519 case llvm::Triple::ppc64: 520 return llvm::makeArrayRef(g_ppc_opcode); 521 522 case llvm::Triple::ppc64le: 523 return llvm::makeArrayRef(g_ppcle_opcode); 524 525 default: 526 return llvm::createStringError(llvm::inconvertibleErrorCode(), 527 "CPU type not supported!"); 528 } 529 } 530 531 size_t NativeProcessProtocol::GetSoftwareBreakpointPCOffset() { 532 switch (GetArchitecture().GetMachine()) { 533 case llvm::Triple::x86: 534 case llvm::Triple::x86_64: 535 case llvm::Triple::systemz: 536 // These architectures report increment the PC after breakpoint is hit. 537 return cantFail(GetSoftwareBreakpointTrapOpcode(0)).size(); 538 539 case llvm::Triple::arm: 540 case llvm::Triple::aarch64: 541 case llvm::Triple::aarch64_32: 542 case llvm::Triple::mips64: 543 case llvm::Triple::mips64el: 544 case llvm::Triple::mips: 545 case llvm::Triple::mipsel: 546 case llvm::Triple::ppc: 547 case llvm::Triple::ppc64: 548 case llvm::Triple::ppc64le: 549 // On these architectures the PC doesn't get updated for breakpoint hits. 550 return 0; 551 552 default: 553 llvm_unreachable("CPU type not supported!"); 554 } 555 } 556 557 void NativeProcessProtocol::FixupBreakpointPCAsNeeded( 558 NativeThreadProtocol &thread) { 559 Log *log = GetLog(LLDBLog::Breakpoints); 560 561 Status error; 562 563 // Find out the size of a breakpoint (might depend on where we are in the 564 // code). 565 NativeRegisterContext &context = thread.GetRegisterContext(); 566 567 uint32_t breakpoint_size = GetSoftwareBreakpointPCOffset(); 568 LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size); 569 if (breakpoint_size == 0) 570 return; 571 572 // First try probing for a breakpoint at a software breakpoint location: PC - 573 // breakpoint size. 574 const lldb::addr_t initial_pc_addr = context.GetPCfromBreakpointLocation(); 575 lldb::addr_t breakpoint_addr = initial_pc_addr; 576 // Do not allow breakpoint probe to wrap around. 577 if (breakpoint_addr >= breakpoint_size) 578 breakpoint_addr -= breakpoint_size; 579 580 if (m_software_breakpoints.count(breakpoint_addr) == 0) { 581 // We didn't find one at a software probe location. Nothing to do. 582 LLDB_LOG(log, 583 "pid {0} no lldb software breakpoint found at current pc with " 584 "adjustment: {1}", 585 GetID(), breakpoint_addr); 586 return; 587 } 588 589 // 590 // We have a software breakpoint and need to adjust the PC. 591 // 592 593 // Change the program counter. 594 LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(), 595 thread.GetID(), initial_pc_addr, breakpoint_addr); 596 597 error = context.SetPC(breakpoint_addr); 598 if (error.Fail()) { 599 // This can happen in case the process was killed between the time we read 600 // the PC and when we are updating it. There's nothing better to do than to 601 // swallow the error. 602 LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(), 603 thread.GetID(), error); 604 } 605 } 606 607 Status NativeProcessProtocol::RemoveBreakpoint(lldb::addr_t addr, 608 bool hardware) { 609 if (hardware) 610 return RemoveHardwareBreakpoint(addr); 611 else 612 return RemoveSoftwareBreakpoint(addr); 613 } 614 615 Status NativeProcessProtocol::ReadMemoryWithoutTrap(lldb::addr_t addr, 616 void *buf, size_t size, 617 size_t &bytes_read) { 618 Status error = ReadMemory(addr, buf, size, bytes_read); 619 if (error.Fail()) 620 return error; 621 622 auto data = 623 llvm::makeMutableArrayRef(static_cast<uint8_t *>(buf), bytes_read); 624 for (const auto &pair : m_software_breakpoints) { 625 lldb::addr_t bp_addr = pair.first; 626 auto saved_opcodes = makeArrayRef(pair.second.saved_opcodes); 627 628 if (bp_addr + saved_opcodes.size() < addr || addr + bytes_read <= bp_addr) 629 continue; // Breakpoint not in range, ignore 630 631 if (bp_addr < addr) { 632 saved_opcodes = saved_opcodes.drop_front(addr - bp_addr); 633 bp_addr = addr; 634 } 635 auto bp_data = data.drop_front(bp_addr - addr); 636 std::copy_n(saved_opcodes.begin(), 637 std::min(saved_opcodes.size(), bp_data.size()), 638 bp_data.begin()); 639 } 640 return Status(); 641 } 642 643 llvm::Expected<llvm::StringRef> 644 NativeProcessProtocol::ReadCStringFromMemory(lldb::addr_t addr, char *buffer, 645 size_t max_size, 646 size_t &total_bytes_read) { 647 static const size_t cache_line_size = 648 llvm::sys::Process::getPageSizeEstimate(); 649 size_t bytes_read = 0; 650 size_t bytes_left = max_size; 651 addr_t curr_addr = addr; 652 size_t string_size; 653 char *curr_buffer = buffer; 654 total_bytes_read = 0; 655 Status status; 656 657 while (bytes_left > 0 && status.Success()) { 658 addr_t cache_line_bytes_left = 659 cache_line_size - (curr_addr % cache_line_size); 660 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left); 661 status = ReadMemory(curr_addr, static_cast<void *>(curr_buffer), 662 bytes_to_read, bytes_read); 663 664 if (bytes_read == 0) 665 break; 666 667 void *str_end = std::memchr(curr_buffer, '\0', bytes_read); 668 if (str_end != nullptr) { 669 total_bytes_read = 670 static_cast<size_t>((static_cast<char *>(str_end) - buffer + 1)); 671 status.Clear(); 672 break; 673 } 674 675 total_bytes_read += bytes_read; 676 curr_buffer += bytes_read; 677 curr_addr += bytes_read; 678 bytes_left -= bytes_read; 679 } 680 681 string_size = total_bytes_read - 1; 682 683 // Make sure we return a null terminated string. 684 if (bytes_left == 0 && max_size > 0 && buffer[max_size - 1] != '\0') { 685 buffer[max_size - 1] = '\0'; 686 total_bytes_read--; 687 } 688 689 if (!status.Success()) 690 return status.ToError(); 691 692 return llvm::StringRef(buffer, string_size); 693 } 694 695 lldb::StateType NativeProcessProtocol::GetState() const { 696 std::lock_guard<std::recursive_mutex> guard(m_state_mutex); 697 return m_state; 698 } 699 700 void NativeProcessProtocol::SetState(lldb::StateType state, 701 bool notify_delegates) { 702 std::lock_guard<std::recursive_mutex> guard(m_state_mutex); 703 704 if (state == m_state) 705 return; 706 707 m_state = state; 708 709 if (StateIsStoppedState(state, false)) { 710 ++m_stop_id; 711 712 // Give process a chance to do any stop id bump processing, such as 713 // clearing cached data that is invalidated each time the process runs. 714 // Note if/when we support some threads running, we'll end up needing to 715 // manage this per thread and per process. 716 DoStopIDBumped(m_stop_id); 717 } 718 719 // Optionally notify delegates of the state change. 720 if (notify_delegates) 721 SynchronouslyNotifyProcessStateChanged(state); 722 } 723 724 uint32_t NativeProcessProtocol::GetStopID() const { 725 std::lock_guard<std::recursive_mutex> guard(m_state_mutex); 726 return m_stop_id; 727 } 728 729 void NativeProcessProtocol::DoStopIDBumped(uint32_t /* newBumpId */) { 730 // Default implementation does nothing. 731 } 732 733 NativeProcessProtocol::Factory::~Factory() = default; 734