1 //===-- NativeProcessProtocol.cpp -------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Host/common/NativeProcessProtocol.h"
12 #include "lldb/Core/ArchSpec.h"
13 #include "lldb/Core/ModuleSpec.h"
14 #include "lldb/Core/State.h"
15 #include "lldb/Host/Host.h"
16 #include "lldb/Host/common/NativeRegisterContext.h"
17 #include "lldb/Host/common/NativeThreadProtocol.h"
18 #include "lldb/Host/common/SoftwareBreakpoint.h"
19 #include "lldb/Symbol/ObjectFile.h"
20 #include "lldb/Target/Process.h"
21 #include "lldb/Utility/LLDBAssert.h"
22 #include "lldb/Utility/Log.h"
23 #include "lldb/lldb-enumerations.h"
26 using namespace lldb_private;
28 // -----------------------------------------------------------------------------
29 // NativeProcessProtocol Members
30 // -----------------------------------------------------------------------------
32 NativeProcessProtocol::NativeProcessProtocol(lldb::pid_t pid, int terminal_fd,
33 NativeDelegate &delegate)
34 : m_pid(pid), m_terminal_fd(terminal_fd) {
35 bool registered = RegisterNativeDelegate(delegate);
40 lldb_private::Status NativeProcessProtocol::Interrupt() {
43 error.SetErrorString("local host does not support signaling");
46 return Signal(SIGSTOP);
50 Status NativeProcessProtocol::IgnoreSignals(llvm::ArrayRef<int> signals) {
51 m_signals_to_ignore.clear();
52 m_signals_to_ignore.insert(signals.begin(), signals.end());
57 NativeProcessProtocol::GetMemoryRegionInfo(lldb::addr_t load_addr,
58 MemoryRegionInfo &range_info) {
59 // Default: not implemented.
60 return Status("not implemented");
63 llvm::Optional<WaitStatus> NativeProcessProtocol::GetExitStatus() {
64 if (m_state == lldb::eStateExited)
70 bool NativeProcessProtocol::SetExitStatus(WaitStatus status,
71 bool bNotifyStateChange) {
72 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
73 LLDB_LOG(log, "status = {0}, notify = {1}", status, bNotifyStateChange);
75 // Exit status already set
76 if (m_state == lldb::eStateExited) {
78 LLDB_LOG(log, "exit status already set to {0}", *m_exit_status);
80 LLDB_LOG(log, "state is exited, but status not set");
84 m_state = lldb::eStateExited;
85 m_exit_status = status;
87 if (bNotifyStateChange)
88 SynchronouslyNotifyProcessStateChanged(lldb::eStateExited);
93 NativeThreadProtocolSP NativeProcessProtocol::GetThreadAtIndex(uint32_t idx) {
94 std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
95 if (idx < m_threads.size())
96 return m_threads[idx];
97 return NativeThreadProtocolSP();
100 NativeThreadProtocolSP
101 NativeProcessProtocol::GetThreadByIDUnlocked(lldb::tid_t tid) {
102 for (auto thread_sp : m_threads) {
103 if (thread_sp->GetID() == tid)
106 return NativeThreadProtocolSP();
109 NativeThreadProtocolSP NativeProcessProtocol::GetThreadByID(lldb::tid_t tid) {
110 std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
111 return GetThreadByIDUnlocked(tid);
114 bool NativeProcessProtocol::IsAlive() const {
115 return m_state != eStateDetached && m_state != eStateExited &&
116 m_state != eStateInvalid && m_state != eStateUnloaded;
119 bool NativeProcessProtocol::GetByteOrder(lldb::ByteOrder &byte_order) const {
120 ArchSpec process_arch;
121 if (!GetArchitecture(process_arch))
123 byte_order = process_arch.GetByteOrder();
127 const NativeWatchpointList::WatchpointMap &
128 NativeProcessProtocol::GetWatchpointMap() const {
129 return m_watchpoint_list.GetWatchpointMap();
132 llvm::Optional<std::pair<uint32_t, uint32_t>>
133 NativeProcessProtocol::GetHardwareDebugSupportInfo() const {
134 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
137 NativeThreadProtocolSP thread_sp(
138 const_cast<NativeProcessProtocol *>(this)->GetThreadAtIndex(0));
141 log->Warning("NativeProcessProtocol::%s (): failed to find a thread to "
142 "grab a NativeRegisterContext!",
147 NativeRegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
150 log->Warning("NativeProcessProtocol::%s (): failed to get a "
151 "RegisterContextNativeProcess from the first thread!",
156 return std::make_pair(reg_ctx_sp->NumSupportedHardwareBreakpoints(),
157 reg_ctx_sp->NumSupportedHardwareWatchpoints());
160 Status NativeProcessProtocol::SetWatchpoint(lldb::addr_t addr, size_t size,
161 uint32_t watch_flags,
163 // This default implementation assumes setting the watchpoint for
164 // the process will require setting the watchpoint for each of the
165 // threads. Furthermore, it will track watchpoints set for the
166 // process and will add them to each thread that is attached to
167 // via the (FIXME implement) OnThreadAttached () method.
169 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
171 // Update the thread list
174 // Keep track of the threads we successfully set the watchpoint
175 // for. If one of the thread watchpoint setting operations fails,
176 // back off and remove the watchpoint for all the threads that
177 // were successfully set so we get back to a consistent state.
178 std::vector<NativeThreadProtocolSP> watchpoint_established_threads;
180 // Tell each thread to set a watchpoint. In the event that
181 // hardware watchpoints are requested but the SetWatchpoint fails,
182 // try to set a software watchpoint as a fallback. It's
183 // conceivable that if there are more threads than hardware
184 // watchpoints available, some of the threads will fail to set
185 // hardware watchpoints while software ones may be available.
186 std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
187 for (auto thread_sp : m_threads) {
188 assert(thread_sp && "thread list should not have a NULL thread!");
192 Status thread_error =
193 thread_sp->SetWatchpoint(addr, size, watch_flags, hardware);
194 if (thread_error.Fail() && hardware) {
195 // Try software watchpoints since we failed on hardware watchpoint setting
196 // and we may have just run out of hardware watchpoints.
197 thread_error = thread_sp->SetWatchpoint(addr, size, watch_flags, false);
198 if (thread_error.Success()) {
201 "hardware watchpoint requested but software watchpoint set");
205 if (thread_error.Success()) {
206 // Remember that we set this watchpoint successfully in
207 // case we need to clear it later.
208 watchpoint_established_threads.push_back(thread_sp);
210 // Unset the watchpoint for each thread we successfully
211 // set so that we get back to a consistent state of "not
212 // set" for the watchpoint.
213 for (auto unwatch_thread_sp : watchpoint_established_threads) {
214 Status remove_error = unwatch_thread_sp->RemoveWatchpoint(addr);
215 if (remove_error.Fail() && log) {
216 log->Warning("NativeProcessProtocol::%s (): RemoveWatchpoint failed "
217 "for pid=%" PRIu64 ", tid=%" PRIu64 ": %s",
218 __FUNCTION__, GetID(), unwatch_thread_sp->GetID(),
219 remove_error.AsCString());
226 return m_watchpoint_list.Add(addr, size, watch_flags, hardware);
229 Status NativeProcessProtocol::RemoveWatchpoint(lldb::addr_t addr) {
230 // Update the thread list
233 Status overall_error;
235 std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
236 for (auto thread_sp : m_threads) {
237 assert(thread_sp && "thread list should not have a NULL thread!");
241 const Status thread_error = thread_sp->RemoveWatchpoint(addr);
242 if (thread_error.Fail()) {
243 // Keep track of the first thread error if any threads
244 // fail. We want to try to remove the watchpoint from
245 // every thread, though, even if one or more have errors.
246 if (!overall_error.Fail())
247 overall_error = thread_error;
250 const Status error = m_watchpoint_list.Remove(addr);
251 return overall_error.Fail() ? overall_error : error;
254 const HardwareBreakpointMap &
255 NativeProcessProtocol::GetHardwareBreakpointMap() const {
256 return m_hw_breakpoints_map;
259 Status NativeProcessProtocol::SetHardwareBreakpoint(lldb::addr_t addr,
261 // This default implementation assumes setting a hardware breakpoint for
262 // this process will require setting same hardware breakpoint for each
263 // of its existing threads. New thread will do the same once created.
264 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
266 // Update the thread list
269 // Exit here if target does not have required hardware breakpoint capability.
270 auto hw_debug_cap = GetHardwareDebugSupportInfo();
272 if (hw_debug_cap == llvm::None || hw_debug_cap->first == 0 ||
273 hw_debug_cap->first <= m_hw_breakpoints_map.size())
274 return Status("Target does not have required no of hardware breakpoints");
276 // Vector below stores all thread pointer for which we have we successfully
277 // set this hardware breakpoint. If any of the current process threads fails
278 // to set this hardware breakpoint then roll back and remove this breakpoint
279 // for all the threads that had already set it successfully.
280 std::vector<NativeThreadProtocolSP> breakpoint_established_threads;
282 // Request to set a hardware breakpoint for each of current process threads.
283 std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
284 for (auto thread_sp : m_threads) {
285 assert(thread_sp && "thread list should not have a NULL thread!");
289 Status thread_error = thread_sp->SetHardwareBreakpoint(addr, size);
290 if (thread_error.Success()) {
291 // Remember that we set this breakpoint successfully in
292 // case we need to clear it later.
293 breakpoint_established_threads.push_back(thread_sp);
295 // Unset the breakpoint for each thread we successfully
296 // set so that we get back to a consistent state of "not
297 // set" for this hardware breakpoint.
298 for (auto rollback_thread_sp : breakpoint_established_threads) {
299 Status remove_error =
300 rollback_thread_sp->RemoveHardwareBreakpoint(addr);
301 if (remove_error.Fail() && log) {
302 log->Warning("NativeProcessProtocol::%s (): RemoveHardwareBreakpoint"
303 " failed for pid=%" PRIu64 ", tid=%" PRIu64 ": %s",
304 __FUNCTION__, GetID(), rollback_thread_sp->GetID(),
305 remove_error.AsCString());
313 // Register new hardware breakpoint into hardware breakpoints map of current
315 m_hw_breakpoints_map[addr] = {addr, size};
320 Status NativeProcessProtocol::RemoveHardwareBreakpoint(lldb::addr_t addr) {
321 // Update the thread list
326 std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
327 for (auto thread_sp : m_threads) {
328 assert(thread_sp && "thread list should not have a NULL thread!");
332 error = thread_sp->RemoveHardwareBreakpoint(addr);
335 // Also remove from hardware breakpoint map of current process.
336 m_hw_breakpoints_map.erase(addr);
341 bool NativeProcessProtocol::RegisterNativeDelegate(
342 NativeDelegate &native_delegate) {
343 std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
344 if (std::find(m_delegates.begin(), m_delegates.end(), &native_delegate) !=
348 m_delegates.push_back(&native_delegate);
349 native_delegate.InitializeDelegate(this);
353 bool NativeProcessProtocol::UnregisterNativeDelegate(
354 NativeDelegate &native_delegate) {
355 std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
357 const auto initial_size = m_delegates.size();
359 remove(m_delegates.begin(), m_delegates.end(), &native_delegate),
362 // We removed the delegate if the count of delegates shrank after
363 // removing all copies of the given native_delegate from the vector.
364 return m_delegates.size() < initial_size;
367 void NativeProcessProtocol::SynchronouslyNotifyProcessStateChanged(
368 lldb::StateType state) {
369 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
371 std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
372 for (auto native_delegate : m_delegates)
373 native_delegate->ProcessStateChanged(this, state);
376 if (!m_delegates.empty()) {
377 log->Printf("NativeProcessProtocol::%s: sent state notification [%s] "
378 "from process %" PRIu64,
379 __FUNCTION__, lldb_private::StateAsCString(state), GetID());
381 log->Printf("NativeProcessProtocol::%s: would send state notification "
382 "[%s] from process %" PRIu64 ", but no delegates",
383 __FUNCTION__, lldb_private::StateAsCString(state), GetID());
388 void NativeProcessProtocol::NotifyDidExec() {
389 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
391 log->Printf("NativeProcessProtocol::%s - preparing to call delegates",
395 std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
396 for (auto native_delegate : m_delegates)
397 native_delegate->DidExec(this);
401 Status NativeProcessProtocol::SetSoftwareBreakpoint(lldb::addr_t addr,
402 uint32_t size_hint) {
403 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
405 log->Printf("NativeProcessProtocol::%s addr = 0x%" PRIx64, __FUNCTION__,
408 return m_breakpoint_list.AddRef(
409 addr, size_hint, false,
410 [this](lldb::addr_t addr, size_t size_hint, bool /* hardware */,
411 NativeBreakpointSP &breakpoint_sp) -> Status {
412 return SoftwareBreakpoint::CreateSoftwareBreakpoint(
413 *this, addr, size_hint, breakpoint_sp);
417 Status NativeProcessProtocol::RemoveBreakpoint(lldb::addr_t addr,
420 return RemoveHardwareBreakpoint(addr);
422 return m_breakpoint_list.DecRef(addr);
425 Status NativeProcessProtocol::EnableBreakpoint(lldb::addr_t addr) {
426 return m_breakpoint_list.EnableBreakpoint(addr);
429 Status NativeProcessProtocol::DisableBreakpoint(lldb::addr_t addr) {
430 return m_breakpoint_list.DisableBreakpoint(addr);
433 lldb::StateType NativeProcessProtocol::GetState() const {
434 std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
438 void NativeProcessProtocol::SetState(lldb::StateType state,
439 bool notify_delegates) {
440 std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
442 if (state == m_state)
447 if (StateIsStoppedState(state, false)) {
450 // Give process a chance to do any stop id bump processing, such as
451 // clearing cached data that is invalidated each time the process runs.
452 // Note if/when we support some threads running, we'll end up needing
453 // to manage this per thread and per process.
454 DoStopIDBumped(m_stop_id);
457 // Optionally notify delegates of the state change.
458 if (notify_delegates)
459 SynchronouslyNotifyProcessStateChanged(state);
462 uint32_t NativeProcessProtocol::GetStopID() const {
463 std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
467 void NativeProcessProtocol::DoStopIDBumped(uint32_t /* newBumpId */) {
468 // Default implementation does nothing.
471 Status NativeProcessProtocol::ResolveProcessArchitecture(lldb::pid_t pid,
473 // Grab process info for the running process.
474 ProcessInstanceInfo process_info;
475 if (!Host::GetProcessInfo(pid, process_info))
476 return Status("failed to get process info");
478 // Resolve the executable module.
479 ModuleSpecList module_specs;
480 if (!ObjectFile::GetModuleSpecifications(process_info.GetExecutableFile(), 0,
482 return Status("failed to get module specifications");
483 lldbassert(module_specs.GetSize() == 1);
485 arch = module_specs.GetModuleSpecRefAtIndex(0).GetArchitecture();
490 "failed to retrieve a valid architecture from the exe module");
493 NativeProcessProtocol::Factory::~Factory() = default;