LLDB mainline
NativeProcessProtocol.cpp
Go to the documentation of this file.
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
10#include "lldb/Host/Host.h"
16#include "lldb/Utility/Log.h"
17#include "lldb/Utility/State.h"
19
20#include "llvm/Support/Process.h"
21#include <iterator>
22#include <optional>
23
24using namespace lldb;
25using namespace lldb_private;
26
27// NativeProcessProtocol Members
28
30 NativeDelegate &delegate)
31 : m_pid(pid), m_delegate(delegate), m_terminal_fd(terminal_fd) {
32 delegate.InitializeDelegate(this);
33}
34
37#if !defined(SIGSTOP)
38 error = Status::FromErrorString("local host does not support signaling");
39 return error;
40#else
41 return Signal(SIGSTOP);
42#endif
43}
44
45Status NativeProcessProtocol::IgnoreSignals(llvm::ArrayRef<int> signals) {
46 m_signals_to_ignore.clear();
47 m_signals_to_ignore.insert_range(signals);
48 return Status();
49}
50
53 MemoryRegionInfo &range_info) {
54 // Default: not implemented.
55 return Status::FromErrorString("not implemented");
56}
57
60 size_t len, std::vector<uint8_t> &tags) {
61 return Status::FromErrorString("not implemented");
62}
63
66 size_t len,
67 const std::vector<uint8_t> &tags) {
68 return Status::FromErrorString("not implemented");
69}
70
71std::optional<WaitStatus> NativeProcessProtocol::GetExitStatus() {
73 return m_exit_status;
74
75 return std::nullopt;
76}
77
79 bool bNotifyStateChange) {
81 LLDB_LOG(log, "status = {0}, notify = {1}", status, bNotifyStateChange);
82
83 // Exit status already set
85 if (m_exit_status)
86 LLDB_LOG(log, "exit status already set to {0}", *m_exit_status);
87 else
88 LLDB_LOG(log, "state is exited, but status not set");
89 return false;
90 }
91
93 m_exit_status = status;
94
95 if (bNotifyStateChange)
97
98 return true;
99}
100
102 std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
103 if (idx < m_threads.size())
104 return m_threads[idx].get();
105 return nullptr;
106}
107
110 for (const auto &thread : m_threads) {
111 if (thread->GetID() == tid)
112 return thread.get();
113 }
114 return nullptr;
115}
116
118 std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
119 return GetThreadByIDUnlocked(tid);
120}
121
126
129 return m_watchpoint_list.GetWatchpointMap();
130}
131
132std::optional<std::pair<uint32_t, uint32_t>>
135
136 // get any thread
137 NativeThreadProtocol *thread(
138 const_cast<NativeProcessProtocol *>(this)->GetThreadAtIndex(0));
139 if (!thread) {
140 LLDB_LOG(log, "failed to find a thread to grab a NativeRegisterContext!");
141 return std::nullopt;
142 }
143
144 NativeRegisterContext &reg_ctx = thread->GetRegisterContext();
145 return std::make_pair(reg_ctx.NumSupportedHardwareBreakpoints(),
147}
148
150 uint32_t watch_flags,
151 bool hardware) {
152 // This default implementation assumes setting the watchpoint for the process
153 // will require setting the watchpoint for each of the threads. Furthermore,
154 // it will track watchpoints set for the process and will add them to each
155 // thread that is attached to via the (FIXME implement) OnThreadAttached ()
156 // method.
157
159
160 // Update the thread list
162
163 // Keep track of the threads we successfully set the watchpoint for. If one
164 // of the thread watchpoint setting operations fails, back off and remove the
165 // watchpoint for all the threads that were successfully set so we get back
166 // to a consistent state.
167 std::vector<NativeThreadProtocol *> watchpoint_established_threads;
168
169 // Tell each thread to set a watchpoint. In the event that hardware
170 // watchpoints are requested but the SetWatchpoint fails, try to set a
171 // software watchpoint as a fallback. It's conceivable that if there are
172 // more threads than hardware watchpoints available, some of the threads will
173 // fail to set hardware watchpoints while software ones may be available.
174 std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
175 for (const auto &thread : m_threads) {
176 assert(thread && "thread list should not have a NULL thread!");
177
178 Status thread_error =
179 thread->SetWatchpoint(addr, size, watch_flags, hardware);
180 if (thread_error.Fail() && hardware) {
181 // Try software watchpoints since we failed on hardware watchpoint
182 // setting and we may have just run out of hardware watchpoints.
183 thread_error = thread->SetWatchpoint(addr, size, watch_flags, false);
184 if (thread_error.Success())
185 LLDB_LOG(log,
186 "hardware watchpoint requested but software watchpoint set");
187 }
188
189 if (thread_error.Success()) {
190 // Remember that we set this watchpoint successfully in case we need to
191 // clear it later.
192 watchpoint_established_threads.push_back(thread.get());
193 } else {
194 // Unset the watchpoint for each thread we successfully set so that we
195 // get back to a consistent state of "not set" for the watchpoint.
196 for (auto unwatch_thread_sp : watchpoint_established_threads) {
197 Status remove_error = unwatch_thread_sp->RemoveWatchpoint(addr);
198 if (remove_error.Fail())
199 LLDB_LOG(log, "RemoveWatchpoint failed for pid={0}, tid={1}: {2}",
200 GetID(), unwatch_thread_sp->GetID(), remove_error);
201 }
202
203 return thread_error;
204 }
205 }
206 return m_watchpoint_list.Add(addr, size, watch_flags, hardware);
207}
208
210 // Update the thread list
212
213 Status overall_error;
214
215 std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
216 for (const auto &thread : m_threads) {
217 assert(thread && "thread list should not have a NULL thread!");
218
219 Status thread_error = thread->RemoveWatchpoint(addr);
220 if (thread_error.Fail()) {
221 // Keep track of the first thread error if any threads fail. We want to
222 // try to remove the watchpoint from every thread, though, even if one or
223 // more have errors.
224 if (!overall_error.Fail())
225 overall_error = std::move(thread_error);
226 }
227 }
228 Status error = m_watchpoint_list.Remove(addr);
229 return overall_error.Fail() ? std::move(overall_error) : std::move(error);
230}
231
236
238 size_t size) {
239 // This default implementation assumes setting a hardware breakpoint for this
240 // process will require setting same hardware breakpoint for each of its
241 // existing threads. New thread will do the same once created.
243
244 // Update the thread list
246
247 // Exit here if target does not have required hardware breakpoint capability.
248 auto hw_debug_cap = GetHardwareDebugSupportInfo();
249
250 if (hw_debug_cap == std::nullopt || hw_debug_cap->first == 0 ||
251 hw_debug_cap->first <= m_hw_breakpoints_map.size())
253 "Target does not have required no of hardware breakpoints");
254
255 // Vector below stores all thread pointer for which we have we successfully
256 // set this hardware breakpoint. If any of the current process threads fails
257 // to set this hardware breakpoint then roll back and remove this breakpoint
258 // for all the threads that had already set it successfully.
259 std::vector<NativeThreadProtocol *> breakpoint_established_threads;
260
261 // Request to set a hardware breakpoint for each of current process threads.
262 std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
263 for (const auto &thread : m_threads) {
264 assert(thread && "thread list should not have a NULL thread!");
265
266 Status thread_error = thread->SetHardwareBreakpoint(addr, size);
267 if (thread_error.Success()) {
268 // Remember that we set this breakpoint successfully in case we need to
269 // clear it later.
270 breakpoint_established_threads.push_back(thread.get());
271 } else {
272 // Unset the breakpoint for each thread we successfully set so that we
273 // get back to a consistent state of "not set" for this hardware
274 // breakpoint.
275 for (auto rollback_thread_sp : breakpoint_established_threads) {
276 Status remove_error =
277 rollback_thread_sp->RemoveHardwareBreakpoint(addr);
278 if (remove_error.Fail())
279 LLDB_LOG(log,
280 "RemoveHardwareBreakpoint failed for pid={0}, tid={1}: {2}",
281 GetID(), rollback_thread_sp->GetID(), remove_error);
282 }
283
284 return thread_error;
285 }
286 }
287
288 // Register new hardware breakpoint into hardware breakpoints map of current
289 // process.
290 m_hw_breakpoints_map[addr] = {addr, size};
291
292 return Status();
293}
294
296 // Update the thread list
298
300
301 std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
302 for (const auto &thread : m_threads) {
303 assert(thread && "thread list should not have a NULL thread!");
304 error = thread->RemoveHardwareBreakpoint(addr);
305 }
306
307 // Also remove from hardware breakpoint map of current process.
308 m_hw_breakpoints_map.erase(addr);
309
310 return error;
311}
312
314 lldb::StateType state) {
316
317 m_delegate.ProcessStateChanged(this, state);
318
319 switch (state) {
320 case eStateStopped:
321 case eStateExited:
322 case eStateCrashed:
324 break;
325 default:
326 break;
327 }
328
329 LLDB_LOG(log, "sent state notification [{0}] from process {1}", state,
330 GetID());
331}
332
335 LLDB_LOG(log, "process {0} exec()ed", GetID());
336
338
339 m_delegate.DidExec(this);
340}
341
343 uint32_t size_hint) {
345 LLDB_LOG(log, "addr = {0:x}, size_hint = {1}", addr, size_hint);
346
347 auto it = m_software_breakpoints.find(addr);
348 if (it != m_software_breakpoints.end())
349 return Status();
350 auto expected_bkpt = EnableSoftwareBreakpoint(addr, size_hint);
351 if (!expected_bkpt)
352 return Status::FromError(expected_bkpt.takeError());
353
354 m_software_breakpoints.emplace(addr, std::move(*expected_bkpt));
355 return Status();
356}
357
360 LLDB_LOG(log, "addr = {0:x}", addr);
361 auto it = m_software_breakpoints.find(addr);
362 if (it == m_software_breakpoints.end())
363 return Status::FromErrorString("Breakpoint not found.");
364
365 // Remove the entry from m_software_breakpoints rightaway, so that we don't
366 // leave behind an entry in case one of the following conditions returns an
367 // error. The breakpoint is moved so that it can be accessed below.
368 SoftwareBreakpoint bkpt = std::move(it->second);
369 m_software_breakpoints.erase(it);
370
371 // This is the last reference. Let's remove the breakpoint.
373
374 // Clear a software breakpoint instruction
375 llvm::SmallVector<uint8_t, 4> curr_break_op(bkpt.breakpoint_opcodes.size(),
376 0);
377
378 // Read the breakpoint opcode
379 size_t bytes_read = 0;
380 error =
381 ReadMemory(addr, curr_break_op.data(), curr_break_op.size(), bytes_read);
382 if (error.Fail() || bytes_read < curr_break_op.size()) {
384 "addr=0x%" PRIx64 ": tried to read %zu bytes but only read %zu", addr,
385 curr_break_op.size(), bytes_read);
386 }
387 const auto &saved = bkpt.saved_opcodes;
388 // Make sure the breakpoint opcode exists at this address
389 if (llvm::ArrayRef(curr_break_op) != bkpt.breakpoint_opcodes) {
390 if (curr_break_op != bkpt.saved_opcodes)
392 "Original breakpoint trap is no longer in memory.");
393 LLDB_LOG(log,
394 "Saved opcodes ({0:@[x]}) have already been restored at {1:x}.",
395 llvm::make_range(saved.begin(), saved.end()), addr);
396 } else {
397 // We found a valid breakpoint opcode at this address, now restore the
398 // saved opcode.
399 size_t bytes_written = 0;
400 error = DoWriteMemory(addr, saved.data(), saved.size(), bytes_written);
401 if (error.Fail() || bytes_written < saved.size()) {
403 "addr=0x%" PRIx64 ": tried to write %zu bytes but only wrote %zu",
404 addr, saved.size(), bytes_written);
405 }
406
407 // Verify that our original opcode made it back to the inferior
408 llvm::SmallVector<uint8_t, 4> verify_opcode(saved.size(), 0);
409 size_t verify_bytes_read = 0;
410 error = ReadMemory(addr, verify_opcode.data(), verify_opcode.size(),
411 verify_bytes_read);
412 if (error.Fail() || verify_bytes_read < verify_opcode.size()) {
414 "addr=0x%" PRIx64
415 ": tried to read %zu verification bytes but only read %zu",
416 addr, verify_opcode.size(), verify_bytes_read);
417 }
418 if (verify_opcode != saved)
419 LLDB_LOG(log, "Restoring bytes at {0:x}: {1:@[x]}", addr,
420 llvm::make_range(saved.begin(), saved.end()));
421 }
422
423 return Status();
424}
425
426llvm::Expected<NativeProcessProtocol::SoftwareBreakpoint>
428 uint32_t size_hint) {
430
431 auto expected_trap = GetSoftwareBreakpointTrapOpcode(size_hint);
432 if (!expected_trap)
433 return expected_trap.takeError();
434
435 llvm::SmallVector<uint8_t, 4> saved_opcode_bytes(expected_trap->size(), 0);
436 // Save the original opcodes by reading them so we can restore later.
437 size_t bytes_read = 0;
438 Status error = ReadMemory(addr, saved_opcode_bytes.data(),
439 saved_opcode_bytes.size(), bytes_read);
440 if (error.Fail())
441 return error.ToError();
442
443 // Ensure we read as many bytes as we expected.
444 if (bytes_read != saved_opcode_bytes.size()) {
445 return llvm::createStringError(
446 llvm::inconvertibleErrorCode(),
447 "Failed to read memory while attempting to set breakpoint: attempted "
448 "to read {0} bytes but only read {1}.",
449 saved_opcode_bytes.size(), bytes_read);
450 }
451
452 LLDB_LOG(
453 log, "Overwriting bytes at {0:x}: {1:@[x]}", addr,
454 llvm::make_range(saved_opcode_bytes.begin(), saved_opcode_bytes.end()));
455
456 // Write a software breakpoint in place of the original opcode.
457 size_t bytes_written = 0;
458 error = DoWriteMemory(addr, expected_trap->data(), expected_trap->size(),
459 bytes_written);
460 if (error.Fail())
461 return error.ToError();
462
463 // Ensure we wrote as many bytes as we expected.
464 if (bytes_written != expected_trap->size()) {
465 return llvm::createStringError(
466 llvm::inconvertibleErrorCode(),
467 "Failed write memory while attempting to set "
468 "breakpoint: attempted to write {0} bytes but only wrote {1}",
469 expected_trap->size(), bytes_written);
470 }
471
472 llvm::SmallVector<uint8_t, 4> verify_bp_opcode_bytes(expected_trap->size(),
473 0);
474 size_t verify_bytes_read = 0;
475 error = ReadMemory(addr, verify_bp_opcode_bytes.data(),
476 verify_bp_opcode_bytes.size(), verify_bytes_read);
477 if (error.Fail())
478 return error.ToError();
479
480 // Ensure we read as many verification bytes as we expected.
481 if (verify_bytes_read != verify_bp_opcode_bytes.size()) {
482 return llvm::createStringError(
483 llvm::inconvertibleErrorCode(),
484 "Failed to read memory while "
485 "attempting to verify breakpoint: attempted to read {0} bytes "
486 "but only read {1}",
487 verify_bp_opcode_bytes.size(), verify_bytes_read);
488 }
489
490 if (llvm::ArrayRef(verify_bp_opcode_bytes.data(), verify_bytes_read) !=
491 *expected_trap) {
492 return llvm::createStringError(
493 llvm::inconvertibleErrorCode(),
494 "Verification of software breakpoint "
495 "writing failed - trap opcodes not successfully read back "
496 "after writing when setting breakpoint at {0:x}",
497 addr);
498 }
499
500 LLDB_LOG(log, "addr = {0:x}: SUCCESS", addr);
501 return SoftwareBreakpoint{saved_opcode_bytes, *expected_trap};
502}
503
504llvm::Expected<llvm::ArrayRef<uint8_t>>
506 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
507 static const uint8_t g_i386_opcode[] = {0xCC};
508 static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};
509 static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};
510 static const uint8_t g_msp430_opcode[] = {0x43, 0x43};
511 static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
512 static const uint8_t g_ppc_opcode[] = {0x7f, 0xe0, 0x00, 0x08}; // trap
513 static const uint8_t g_ppcle_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap
514 static const uint8_t g_riscv_opcode[] = {0x73, 0x00, 0x10, 0x00}; // ebreak
515 static const uint8_t g_riscv_opcode_c[] = {0x02, 0x90}; // c.ebreak
516 static const uint8_t g_loongarch_opcode[] = {0x05, 0x00, 0x2a,
517 0x00}; // break 0x5
518
519 switch (GetArchitecture().GetMachine()) {
520 case llvm::Triple::aarch64:
521 case llvm::Triple::aarch64_32:
522 return llvm::ArrayRef(g_aarch64_opcode);
523
524 case llvm::Triple::x86:
525 case llvm::Triple::x86_64:
526 return llvm::ArrayRef(g_i386_opcode);
527
528 case llvm::Triple::mips:
529 case llvm::Triple::mips64:
530 return llvm::ArrayRef(g_mips64_opcode);
531
532 case llvm::Triple::mipsel:
533 case llvm::Triple::mips64el:
534 return llvm::ArrayRef(g_mips64el_opcode);
535
536 case llvm::Triple::msp430:
537 return llvm::ArrayRef(g_msp430_opcode);
538
539 case llvm::Triple::systemz:
540 return llvm::ArrayRef(g_s390x_opcode);
541
542 case llvm::Triple::ppc:
543 case llvm::Triple::ppc64:
544 return llvm::ArrayRef(g_ppc_opcode);
545
546 case llvm::Triple::ppc64le:
547 return llvm::ArrayRef(g_ppcle_opcode);
548
549 case llvm::Triple::riscv32:
550 case llvm::Triple::riscv64: {
551 return size_hint == 2 ? llvm::ArrayRef(g_riscv_opcode_c)
552 : llvm::ArrayRef(g_riscv_opcode);
553 }
554
555 case llvm::Triple::loongarch32:
556 case llvm::Triple::loongarch64:
557 return llvm::ArrayRef(g_loongarch_opcode);
558
559 default:
560 return llvm::createStringError(llvm::inconvertibleErrorCode(),
561 "CPU type not supported!");
562 }
563}
564
566 switch (GetArchitecture().GetMachine()) {
567 case llvm::Triple::x86:
568 case llvm::Triple::x86_64:
569 case llvm::Triple::systemz:
570 // These architectures report increment the PC after breakpoint is hit.
571 return cantFail(GetSoftwareBreakpointTrapOpcode(0)).size();
572
573 case llvm::Triple::arm:
574 case llvm::Triple::aarch64:
575 case llvm::Triple::aarch64_32:
576 case llvm::Triple::mips64:
577 case llvm::Triple::mips64el:
578 case llvm::Triple::mips:
579 case llvm::Triple::mipsel:
580 case llvm::Triple::ppc:
581 case llvm::Triple::ppc64:
582 case llvm::Triple::ppc64le:
583 case llvm::Triple::riscv32:
584 case llvm::Triple::riscv64:
585 case llvm::Triple::loongarch32:
586 case llvm::Triple::loongarch64:
587 // On these architectures the PC doesn't get updated for breakpoint hits.
588 return 0;
589
590 default:
591 llvm_unreachable("CPU type not supported!");
592 }
593}
594
596 NativeThreadProtocol &thread) {
598
600
601 // Find out the size of a breakpoint (might depend on where we are in the
602 // code).
603 NativeRegisterContext &context = thread.GetRegisterContext();
604
605 uint32_t breakpoint_size = GetSoftwareBreakpointPCOffset();
606 LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
607 if (breakpoint_size == 0)
608 return;
609
610 // First try probing for a breakpoint at a software breakpoint location: PC -
611 // breakpoint size.
612 const lldb::addr_t initial_pc_addr = context.GetPCfromBreakpointLocation();
613 lldb::addr_t breakpoint_addr = initial_pc_addr;
614 // Do not allow breakpoint probe to wrap around.
615 if (breakpoint_addr >= breakpoint_size)
616 breakpoint_addr -= breakpoint_size;
617
618 if (m_software_breakpoints.count(breakpoint_addr) == 0) {
619 // We didn't find one at a software probe location. Nothing to do.
620 LLDB_LOG(log,
621 "pid {0} no lldb software breakpoint found at current pc with "
622 "adjustment: {1}",
623 GetID(), breakpoint_addr);
624 return;
625 }
626
627 //
628 // We have a software breakpoint and need to adjust the PC.
629 //
630
631 // Change the program counter.
632 LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
633 thread.GetID(), initial_pc_addr, breakpoint_addr);
634
635 error = context.SetPC(breakpoint_addr);
636 if (error.Fail()) {
637 // This can happen in case the process was killed between the time we read
638 // the PC and when we are updating it. There's nothing better to do than to
639 // swallow the error.
640 LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
641 thread.GetID(), error);
642 }
643}
644
646 bool hardware) {
647 if (hardware)
648 return RemoveHardwareBreakpoint(addr);
649 else
650 return RemoveSoftwareBreakpoint(addr);
651}
652
654 size_t size, size_t &bytes_written) {
656 bytes_written = 0;
657
658 if (!size)
659 return error;
660
661 if (m_software_breakpoints.empty())
662 return DoWriteMemory(addr, buf, size, bytes_written);
663
664 // Find first breakpoint that starts >= addr.
665 std::map<lldb::addr_t, SoftwareBreakpoint>::iterator bkpt =
666 m_software_breakpoints.lower_bound(addr);
667
668 // it points to the first breakpoint starting at >= addr, but the one
669 // immediately before it may extend over addr, or begin exactly at addr.
670 if (bkpt != m_software_breakpoints.begin())
671 bkpt = std::prev(bkpt);
672
673 const uint8_t *byte_buf = static_cast<const uint8_t *>(buf);
674 for (; bkpt != m_software_breakpoints.end(); ++bkpt) {
675 auto &[sbp_addr, sbp_data] = *bkpt;
676 // If the address is before a breakpoint site, write up to the site, or to
677 // the end of the write. Whichever comes first.
678 if (addr < sbp_addr) {
679 const size_t to_write =
680 std::min(static_cast<addr_t>(size), sbp_addr - addr);
681 size_t part_bytes_written = 0;
682 error = DoWriteMemory(addr, byte_buf, to_write, part_bytes_written);
683 bytes_written += part_bytes_written;
684
685 if (error.Fail() || part_bytes_written < to_write) {
687 "addr=0x%" PRIx64 ": tried to write %zu bytes but only wrote %zu",
688 addr, to_write, part_bytes_written);
689 }
690
691 byte_buf += to_write;
692 addr += to_write;
693 size -= to_write;
694
695 if (!size)
696 break;
697 }
698
699 // If the address is within a breakpoint site, update the saved opcodes
700 // for that site.
701 if ((addr >= sbp_addr) &&
702 (addr < (sbp_addr + sbp_data.saved_opcodes.size()))) {
703 // Instead of writing this chunk, update the saved bytes in the
704 // breakpoint.
705 const size_t idx = addr - sbp_addr;
706 const size_t to_write =
707 std::min(size, sbp_data.saved_opcodes.size() - idx);
708 for (size_t copied = 0; copied < to_write;
709 ++bytes_written, ++byte_buf, ++addr, --size, ++copied)
710 sbp_data.saved_opcodes[idx + copied] = *byte_buf;
711 }
712
713 if (!size)
714 break;
715 }
716
717 // If the write range extends beyond the last breakpoint site, write the
718 // remaining data.
719 if (size) {
720 // Write the remaining part after the last breakpoint, or the whole range
721 // in the case that there were no breakpoints.
722 size_t part_bytes_written = 0;
723 error = DoWriteMemory(addr, byte_buf, size, part_bytes_written);
724 bytes_written += part_bytes_written;
725 if (error.Fail() || part_bytes_written < size) {
727 "addr=0x%" PRIx64 ": tried to write %zu bytes but only wrote %zu",
728 addr, size, part_bytes_written);
729 }
730 }
731
732 return Status();
733}
734
735Status
737 void *buf, size_t size,
738 size_t &bytes_read) {
739 Status error = ReadMemory(process_addr, buf, size, bytes_read);
740 if (error.Fail())
741 return error;
742
743 lldb::addr_t addr = process_addr.GetValue();
744 llvm::MutableArrayRef data(static_cast<uint8_t *>(buf), bytes_read);
745 for (const auto &pair : m_software_breakpoints) {
746 lldb::addr_t bp_addr = pair.first;
747 auto saved_opcodes = llvm::ArrayRef(pair.second.saved_opcodes);
748
749 if (bp_addr + saved_opcodes.size() < addr || addr + bytes_read <= bp_addr)
750 continue; // Breakpoint not in range, ignore
751
752 if (bp_addr < addr) {
753 saved_opcodes = saved_opcodes.drop_front(addr - bp_addr);
754 bp_addr = addr;
755 }
756 auto bp_data = data.drop_front(bp_addr - addr);
757 std::copy_n(saved_opcodes.begin(),
758 std::min(saved_opcodes.size(), bp_data.size()),
759 bp_data.begin());
760 }
761 return Status();
762}
763
764llvm::Expected<llvm::StringRef>
766 size_t max_size,
767 size_t &total_bytes_read) {
768 static const size_t cache_line_size =
769 llvm::sys::Process::getPageSizeEstimate();
770 size_t bytes_read = 0;
771 size_t bytes_left = max_size;
772 addr_t curr_addr = addr;
773 size_t string_size;
774 char *curr_buffer = buffer;
775 total_bytes_read = 0;
776 Status status;
777
778 while (bytes_left > 0 && status.Success()) {
779 addr_t cache_line_bytes_left =
780 cache_line_size - (curr_addr % cache_line_size);
781 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
782 status = ReadMemory(curr_addr, static_cast<void *>(curr_buffer),
783 bytes_to_read, bytes_read);
784
785 if (bytes_read == 0)
786 break;
787
788 void *str_end = std::memchr(curr_buffer, '\0', bytes_read);
789 if (str_end != nullptr) {
790 total_bytes_read =
791 static_cast<size_t>((static_cast<char *>(str_end) - buffer + 1));
792 status.Clear();
793 break;
794 }
795
796 total_bytes_read += bytes_read;
797 curr_buffer += bytes_read;
798 curr_addr += bytes_read;
799 bytes_left -= bytes_read;
800 }
801
802 string_size = total_bytes_read - 1;
803
804 // Make sure we return a null terminated string.
805 if (bytes_left == 0 && max_size > 0 && buffer[max_size - 1] != '\0') {
806 buffer[max_size - 1] = '\0';
807 total_bytes_read--;
808 }
809
810 if (!status.Success())
811 return status.ToError();
812
813 return llvm::StringRef(buffer, string_size);
814}
815
817 std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
818 return m_state;
819}
820
822 bool notify_delegates) {
823 std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
824
825 if (state == m_state)
826 return;
827
828 m_state = state;
829
830 if (StateIsStoppedState(state, false)) {
831 ++m_stop_id;
832
833 // Give process a chance to do any stop id bump processing, such as
834 // clearing cached data that is invalidated each time the process runs.
835 // Note if/when we support some threads running, we'll end up needing to
836 // manage this per thread and per process.
838 }
839
840 // Optionally notify delegates of the state change.
841 if (notify_delegates)
843}
844
846 std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
847 return m_stop_id;
848}
849
850void NativeProcessProtocol::DoStopIDBumped(uint32_t /* newBumpId */) {
851 // Default implementation does nothing.
852}
853
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
virtual void InitializeDelegate(NativeProcessProtocol *process)=0
virtual Status SetWatchpoint(lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware)
virtual Status ReadMemoryTags(int32_t type, lldb::addr_t addr, size_t len, std::vector< uint8_t > &tags)
llvm::Expected< SoftwareBreakpoint > EnableSoftwareBreakpoint(lldb::addr_t addr, uint32_t size_hint)
virtual Status GetMemoryRegionInfo(lldb::addr_t load_addr, MemoryRegionInfo &range_info)
virtual void NotifyTracersProcessDidStop()
Notify tracers that the target process just stopped.
virtual std::optional< WaitStatus > GetExitStatus()
virtual Status RemoveWatchpoint(lldb::addr_t addr)
virtual Status Interrupt()
Tells a process to interrupt all operations as if by a Ctrl-C.
virtual Status WriteMemoryTags(int32_t type, lldb::addr_t addr, size_t len, const std::vector< uint8_t > &tags)
virtual void DoStopIDBumped(uint32_t newBumpId)
NativeProcessProtocol(lldb::pid_t pid, int terminal_fd, NativeDelegate &delegate)
virtual size_t GetSoftwareBreakpointPCOffset()
Return the offset of the PC relative to the software breakpoint that was hit.
virtual const HardwareBreakpointMap & GetHardwareBreakpointMap() const
Status SetSoftwareBreakpoint(lldb::addr_t addr, uint32_t size_hint)
virtual Status IgnoreSignals(llvm::ArrayRef< int > signals)
NativeThreadProtocol * GetThreadByIDUnlocked(lldb::tid_t tid)
virtual const ArchSpec & GetArchitecture() const =0
virtual const NativeWatchpointList::WatchpointMap & GetWatchpointMap() const
void SetState(lldb::StateType state, bool notify_delegates=true)
llvm::Expected< llvm::StringRef > ReadCStringFromMemory(lldb::addr_t addr, char *buffer, size_t max_size, size_t &total_bytes_read)
Reads a null terminated string from memory.
virtual Status DoWriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)=0
NativeThreadProtocol * GetThreadByID(lldb::tid_t tid)
Status ReadMemoryWithoutTrap(const ProcessAddress &addr, void *buf, size_t size, size_t &bytes_read)
void SynchronouslyNotifyProcessStateChanged(lldb::StateType state)
Status WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
Write memory while not overwriting breakpoints in memory.
std::vector< std::unique_ptr< NativeThreadProtocol > > m_threads
std::optional< WaitStatus > m_exit_status
virtual bool SetExitStatus(WaitStatus status, bool bNotifyStateChange)
virtual Status RemoveBreakpoint(lldb::addr_t addr, bool hardware=false)
virtual Status Signal(int signo)=0
Sends a process a UNIX signal signal.
Status RemoveSoftwareBreakpoint(lldb::addr_t addr)
void FixupBreakpointPCAsNeeded(NativeThreadProtocol &thread)
NativeThreadProtocol * GetThreadAtIndex(uint32_t idx)
virtual void NotifyDidExec()
Notify the delegate that an exec occurred.
virtual Status ReadMemory(const ProcessAddress &addr, void *buf, size_t size, size_t &bytes_read)=0
virtual Status SetHardwareBreakpoint(lldb::addr_t addr, size_t size)
std::map< lldb::addr_t, SoftwareBreakpoint > m_software_breakpoints
virtual std::optional< std::pair< uint32_t, uint32_t > > GetHardwareDebugSupportInfo() const
virtual llvm::Expected< llvm::ArrayRef< uint8_t > > GetSoftwareBreakpointTrapOpcode(size_t size_hint)
virtual Status RemoveHardwareBreakpoint(lldb::addr_t addr)
virtual lldb::addr_t GetPCfromBreakpointLocation(lldb::addr_t fail_value=LLDB_INVALID_ADDRESS)
std::map< lldb::addr_t, NativeWatchpoint > WatchpointMap
An address in a process, qualified by an address space.
lldb::addr_t GetValue() const
An error handling class.
Definition Status.h:118
void Clear()
Clear the object state.
Definition Status.cpp:214
llvm::Error ToError() const
FIXME: Replace all uses with takeError() instead.
Definition Status.cpp:138
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
bool Fail() const
Test for error condition.
Definition Status.cpp:293
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
bool Success() const
Test for success condition.
Definition Status.cpp:303
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:338
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
std::map< lldb::addr_t, HardwareBreakpoint > HardwareBreakpointMap
StateType
Process and Thread States.
@ eStateUnloaded
Process is object is valid, but not currently loaded.
@ eStateDetached
Process has been detached and can't be examined.
@ eStateStopped
Process or thread is stopped and can be examined.
@ eStateExited
Process has exited and can't be examined.
@ eStateCrashed
Process or thread has crashed and can be examined.
uint64_t pid_t
Definition lldb-types.h:84
uint64_t addr_t
Definition lldb-types.h:80
uint64_t tid_t
Definition lldb-types.h:85
#define SIGSTOP