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/Log.h"
14 #include "lldb/Core/ModuleSpec.h"
15 #include "lldb/Core/State.h"
16 #include "lldb/Host/Host.h"
17 #include "lldb/Host/common/NativeRegisterContext.h"
18 #include "lldb/Host/common/NativeThreadProtocol.h"
19 #include "lldb/Host/common/SoftwareBreakpoint.h"
20 #include "lldb/Symbol/ObjectFile.h"
21 #include "lldb/Target/Process.h"
22 #include "lldb/Utility/LLDBAssert.h"
23 #include "lldb/lldb-enumerations.h"
26 using namespace lldb_private;
28 // -----------------------------------------------------------------------------
29 // NativeProcessProtocol Members
30 // -----------------------------------------------------------------------------
32 NativeProcessProtocol::NativeProcessProtocol(lldb::pid_t pid)
33 : m_pid(pid), m_threads(), m_current_thread_id(LLDB_INVALID_THREAD_ID),
34 m_threads_mutex(), m_state(lldb::eStateInvalid), m_state_mutex(),
35 m_exit_type(eExitTypeInvalid), m_exit_status(0), m_exit_description(),
36 m_delegates_mutex(), m_delegates(), m_breakpoint_list(),
37 m_watchpoint_list(), m_terminal_fd(-1), m_stop_id(0) {}
39 lldb_private::Error NativeProcessProtocol::Interrupt() {
42 error.SetErrorString("local host does not support signaling");
45 return Signal(SIGSTOP);
50 NativeProcessProtocol::GetMemoryRegionInfo(lldb::addr_t load_addr,
51 MemoryRegionInfo &range_info) {
52 // Default: not implemented.
53 return Error("not implemented");
56 bool NativeProcessProtocol::GetExitStatus(ExitType *exit_type, int *status,
57 std::string &exit_description) {
58 if (m_state == lldb::eStateExited) {
59 *exit_type = m_exit_type;
60 *status = m_exit_status;
61 exit_description = m_exit_description;
69 bool NativeProcessProtocol::SetExitStatus(ExitType exit_type, int status,
70 const char *exit_description,
71 bool bNotifyStateChange) {
72 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
74 log->Printf("NativeProcessProtocol::%s(%d, %d, %s, %s) called",
75 __FUNCTION__, exit_type, status,
76 exit_description ? exit_description : "nullptr",
77 bNotifyStateChange ? "true" : "false");
79 // Exit status already set
80 if (m_state == lldb::eStateExited) {
82 log->Printf("NativeProcessProtocol::%s exit status already set to %d, "
83 "ignoring new set to %d",
84 __FUNCTION__, m_exit_status, status);
88 m_state = lldb::eStateExited;
90 m_exit_type = exit_type;
91 m_exit_status = status;
92 if (exit_description && exit_description[0])
93 m_exit_description = exit_description;
95 m_exit_description.clear();
97 if (bNotifyStateChange)
98 SynchronouslyNotifyProcessStateChanged(lldb::eStateExited);
103 NativeThreadProtocolSP NativeProcessProtocol::GetThreadAtIndex(uint32_t idx) {
104 std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
105 if (idx < m_threads.size())
106 return m_threads[idx];
107 return NativeThreadProtocolSP();
110 NativeThreadProtocolSP
111 NativeProcessProtocol::GetThreadByIDUnlocked(lldb::tid_t tid) {
112 for (auto thread_sp : m_threads) {
113 if (thread_sp->GetID() == tid)
116 return NativeThreadProtocolSP();
119 NativeThreadProtocolSP NativeProcessProtocol::GetThreadByID(lldb::tid_t tid) {
120 std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
121 return GetThreadByIDUnlocked(tid);
124 bool NativeProcessProtocol::IsAlive() const {
125 return m_state != eStateDetached && m_state != eStateExited &&
126 m_state != eStateInvalid && m_state != eStateUnloaded;
129 bool NativeProcessProtocol::GetByteOrder(lldb::ByteOrder &byte_order) const {
130 ArchSpec process_arch;
131 if (!GetArchitecture(process_arch))
133 byte_order = process_arch.GetByteOrder();
137 const NativeWatchpointList::WatchpointMap &
138 NativeProcessProtocol::GetWatchpointMap() const {
139 return m_watchpoint_list.GetWatchpointMap();
142 uint32_t NativeProcessProtocol::GetMaxWatchpoints() const {
143 // This default implementation will return the number of
144 // *hardware* breakpoints available. MacOSX and other OS
145 // implementations that support software breakpoints will want to
146 // override this correctly for their implementation.
147 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
150 NativeThreadProtocolSP thread_sp(
151 const_cast<NativeProcessProtocol *>(this)->GetThreadAtIndex(0));
154 log->Warning("NativeProcessProtocol::%s (): failed to find a thread to "
155 "grab a NativeRegisterContext!",
160 NativeRegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
163 log->Warning("NativeProcessProtocol::%s (): failed to get a "
164 "RegisterContextNativeProcess from the first thread!",
169 return reg_ctx_sp->NumSupportedHardwareWatchpoints();
172 Error NativeProcessProtocol::SetWatchpoint(lldb::addr_t addr, size_t size,
173 uint32_t watch_flags,
175 // This default implementation assumes setting the watchpoint for
176 // the process will require setting the watchpoint for each of the
177 // threads. Furthermore, it will track watchpoints set for the
178 // process and will add them to each thread that is attached to
179 // via the (FIXME implement) OnThreadAttached () method.
181 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
183 // Update the thread list
186 // Keep track of the threads we successfully set the watchpoint
187 // for. If one of the thread watchpoint setting operations fails,
188 // back off and remove the watchpoint for all the threads that
189 // were successfully set so we get back to a consistent state.
190 std::vector<NativeThreadProtocolSP> watchpoint_established_threads;
192 // Tell each thread to set a watchpoint. In the event that
193 // hardware watchpoints are requested but the SetWatchpoint fails,
194 // try to set a software watchpoint as a fallback. It's
195 // conceivable that if there are more threads than hardware
196 // watchpoints available, some of the threads will fail to set
197 // hardware watchpoints while software ones may be available.
198 std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
199 for (auto thread_sp : m_threads) {
200 assert(thread_sp && "thread list should not have a NULL thread!");
205 thread_sp->SetWatchpoint(addr, size, watch_flags, hardware);
206 if (thread_error.Fail() && hardware) {
207 // Try software watchpoints since we failed on hardware watchpoint setting
208 // and we may have just run out of hardware watchpoints.
209 thread_error = thread_sp->SetWatchpoint(addr, size, watch_flags, false);
210 if (thread_error.Success()) {
213 "hardware watchpoint requested but software watchpoint set");
217 if (thread_error.Success()) {
218 // Remember that we set this watchpoint successfully in
219 // case we need to clear it later.
220 watchpoint_established_threads.push_back(thread_sp);
222 // Unset the watchpoint for each thread we successfully
223 // set so that we get back to a consistent state of "not
224 // set" for the watchpoint.
225 for (auto unwatch_thread_sp : watchpoint_established_threads) {
226 Error remove_error = unwatch_thread_sp->RemoveWatchpoint(addr);
227 if (remove_error.Fail() && log) {
228 log->Warning("NativeProcessProtocol::%s (): RemoveWatchpoint failed "
229 "for pid=%" PRIu64 ", tid=%" PRIu64 ": %s",
230 __FUNCTION__, GetID(), unwatch_thread_sp->GetID(),
231 remove_error.AsCString());
238 return m_watchpoint_list.Add(addr, size, watch_flags, hardware);
241 Error NativeProcessProtocol::RemoveWatchpoint(lldb::addr_t addr) {
242 // Update the thread list
247 std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
248 for (auto thread_sp : m_threads) {
249 assert(thread_sp && "thread list should not have a NULL thread!");
253 const Error thread_error = thread_sp->RemoveWatchpoint(addr);
254 if (thread_error.Fail()) {
255 // Keep track of the first thread error if any threads
256 // fail. We want to try to remove the watchpoint from
257 // every thread, though, even if one or more have errors.
258 if (!overall_error.Fail())
259 overall_error = thread_error;
262 const Error error = m_watchpoint_list.Remove(addr);
263 return overall_error.Fail() ? overall_error : error;
266 bool NativeProcessProtocol::RegisterNativeDelegate(
267 NativeDelegate &native_delegate) {
268 std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
269 if (std::find(m_delegates.begin(), m_delegates.end(), &native_delegate) !=
273 m_delegates.push_back(&native_delegate);
274 native_delegate.InitializeDelegate(this);
278 bool NativeProcessProtocol::UnregisterNativeDelegate(
279 NativeDelegate &native_delegate) {
280 std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
282 const auto initial_size = m_delegates.size();
284 remove(m_delegates.begin(), m_delegates.end(), &native_delegate),
287 // We removed the delegate if the count of delegates shrank after
288 // removing all copies of the given native_delegate from the vector.
289 return m_delegates.size() < initial_size;
292 void NativeProcessProtocol::SynchronouslyNotifyProcessStateChanged(
293 lldb::StateType state) {
294 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
296 std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
297 for (auto native_delegate : m_delegates)
298 native_delegate->ProcessStateChanged(this, state);
301 if (!m_delegates.empty()) {
302 log->Printf("NativeProcessProtocol::%s: sent state notification [%s] "
303 "from process %" PRIu64,
304 __FUNCTION__, lldb_private::StateAsCString(state), GetID());
306 log->Printf("NativeProcessProtocol::%s: would send state notification "
307 "[%s] from process %" PRIu64 ", but no delegates",
308 __FUNCTION__, lldb_private::StateAsCString(state), GetID());
313 void NativeProcessProtocol::NotifyDidExec() {
314 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
316 log->Printf("NativeProcessProtocol::%s - preparing to call delegates",
320 std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
321 for (auto native_delegate : m_delegates)
322 native_delegate->DidExec(this);
326 Error NativeProcessProtocol::SetSoftwareBreakpoint(lldb::addr_t addr,
327 uint32_t size_hint) {
328 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
330 log->Printf("NativeProcessProtocol::%s addr = 0x%" PRIx64, __FUNCTION__,
333 return m_breakpoint_list.AddRef(
334 addr, size_hint, false,
335 [this](lldb::addr_t addr, size_t size_hint, bool /* hardware */,
336 NativeBreakpointSP &breakpoint_sp) -> Error {
337 return SoftwareBreakpoint::CreateSoftwareBreakpoint(
338 *this, addr, size_hint, breakpoint_sp);
342 Error NativeProcessProtocol::RemoveBreakpoint(lldb::addr_t addr) {
343 return m_breakpoint_list.DecRef(addr);
346 Error NativeProcessProtocol::EnableBreakpoint(lldb::addr_t addr) {
347 return m_breakpoint_list.EnableBreakpoint(addr);
350 Error NativeProcessProtocol::DisableBreakpoint(lldb::addr_t addr) {
351 return m_breakpoint_list.DisableBreakpoint(addr);
354 lldb::StateType NativeProcessProtocol::GetState() const {
355 std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
359 void NativeProcessProtocol::SetState(lldb::StateType state,
360 bool notify_delegates) {
361 std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
363 if (state == m_state)
368 if (StateIsStoppedState(state, false)) {
371 // Give process a chance to do any stop id bump processing, such as
372 // clearing cached data that is invalidated each time the process runs.
373 // Note if/when we support some threads running, we'll end up needing
374 // to manage this per thread and per process.
375 DoStopIDBumped(m_stop_id);
378 // Optionally notify delegates of the state change.
379 if (notify_delegates)
380 SynchronouslyNotifyProcessStateChanged(state);
383 uint32_t NativeProcessProtocol::GetStopID() const {
384 std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
388 void NativeProcessProtocol::DoStopIDBumped(uint32_t /* newBumpId */) {
389 // Default implementation does nothing.
392 Error NativeProcessProtocol::ResolveProcessArchitecture(lldb::pid_t pid,
394 // Grab process info for the running process.
395 ProcessInstanceInfo process_info;
396 if (!Host::GetProcessInfo(pid, process_info))
397 return Error("failed to get process info");
399 // Resolve the executable module.
400 ModuleSpecList module_specs;
401 if (!ObjectFile::GetModuleSpecifications(process_info.GetExecutableFile(), 0,
403 return Error("failed to get module specifications");
404 lldbassert(module_specs.GetSize() == 1);
406 arch = module_specs.GetModuleSpecRefAtIndex(0).GetArchitecture();
410 return Error("failed to retrieve a valid architecture from the exe module");
414 // These need to be implemented to support lldb-gdb-server on a given platform.
416 // provided to make the rest of the code link on non-supported platforms.
418 Error NativeProcessProtocol::Launch(ProcessLaunchInfo &launch_info,
419 NativeDelegate &native_delegate,
421 NativeProcessProtocolSP &process_sp) {
422 llvm_unreachable("Platform has no NativeProcessProtocol support");
425 Error NativeProcessProtocol::Attach(lldb::pid_t pid,
426 NativeDelegate &native_delegate,
428 NativeProcessProtocolSP &process_sp) {
429 llvm_unreachable("Platform has no NativeProcessProtocol support");