1 //===-- NativeProcessProtocol.cpp -------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "lldb/Host/common/NativeProcessProtocol.h"
11 
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"
24 
25 using namespace lldb;
26 using namespace lldb_private;
27 
28 // -----------------------------------------------------------------------------
29 // NativeProcessProtocol Members
30 // -----------------------------------------------------------------------------
31 
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);
36   assert(registered);
37   (void)registered;
38 }
39 
40 lldb_private::Status NativeProcessProtocol::Interrupt() {
41   Status error;
42 #if !defined(SIGSTOP)
43   error.SetErrorString("local host does not support signaling");
44   return error;
45 #else
46   return Signal(SIGSTOP);
47 #endif
48 }
49 
50 Status NativeProcessProtocol::IgnoreSignals(llvm::ArrayRef<int> signals) {
51   m_signals_to_ignore.clear();
52   m_signals_to_ignore.insert(signals.begin(), signals.end());
53   return Status();
54 }
55 
56 lldb_private::Status
57 NativeProcessProtocol::GetMemoryRegionInfo(lldb::addr_t load_addr,
58                                            MemoryRegionInfo &range_info) {
59   // Default: not implemented.
60   return Status("not implemented");
61 }
62 
63 llvm::Optional<WaitStatus> NativeProcessProtocol::GetExitStatus() {
64   if (m_state == lldb::eStateExited)
65     return m_exit_status;
66 
67   return llvm::None;
68 }
69 
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);
74 
75   // Exit status already set
76   if (m_state == lldb::eStateExited) {
77     if (m_exit_status)
78       LLDB_LOG(log, "exit status already set to {0}", *m_exit_status);
79     else
80       LLDB_LOG(log, "state is exited, but status not set");
81     return false;
82   }
83 
84   m_state = lldb::eStateExited;
85   m_exit_status = status;
86 
87   if (bNotifyStateChange)
88     SynchronouslyNotifyProcessStateChanged(lldb::eStateExited);
89 
90   return true;
91 }
92 
93 NativeThreadProtocol *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].get();
97   return nullptr;
98 }
99 
100 NativeThreadProtocol *
101 NativeProcessProtocol::GetThreadByIDUnlocked(lldb::tid_t tid) {
102   for (const auto &thread : m_threads) {
103     if (thread->GetID() == tid)
104       return thread.get();
105   }
106   return nullptr;
107 }
108 
109 NativeThreadProtocol *NativeProcessProtocol::GetThreadByID(lldb::tid_t tid) {
110   std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
111   return GetThreadByIDUnlocked(tid);
112 }
113 
114 bool NativeProcessProtocol::IsAlive() const {
115   return m_state != eStateDetached && m_state != eStateExited &&
116          m_state != eStateInvalid && m_state != eStateUnloaded;
117 }
118 
119 bool NativeProcessProtocol::GetByteOrder(lldb::ByteOrder &byte_order) const {
120   ArchSpec process_arch;
121   if (!GetArchitecture(process_arch))
122     return false;
123   byte_order = process_arch.GetByteOrder();
124   return true;
125 }
126 
127 const NativeWatchpointList::WatchpointMap &
128 NativeProcessProtocol::GetWatchpointMap() const {
129   return m_watchpoint_list.GetWatchpointMap();
130 }
131 
132 llvm::Optional<std::pair<uint32_t, uint32_t>>
133 NativeProcessProtocol::GetHardwareDebugSupportInfo() const {
134   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
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 llvm::None;
142   }
143 
144   NativeRegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
145   if (!reg_ctx_sp) {
146     LLDB_LOG(
147         log,
148         "failed to get a RegisterContextNativeProcess from the first thread!");
149     return llvm::None;
150   }
151 
152   return std::make_pair(reg_ctx_sp->NumSupportedHardwareBreakpoints(),
153                         reg_ctx_sp->NumSupportedHardwareWatchpoints());
154 }
155 
156 Status NativeProcessProtocol::SetWatchpoint(lldb::addr_t addr, size_t size,
157                                             uint32_t watch_flags,
158                                             bool hardware) {
159   // This default implementation assumes setting the watchpoint for
160   // the process will require setting the watchpoint for each of the
161   // threads.  Furthermore, it will track watchpoints set for the
162   // process and will add them to each thread that is attached to
163   // via the (FIXME implement) OnThreadAttached () method.
164 
165   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
166 
167   // Update the thread list
168   UpdateThreads();
169 
170   // Keep track of the threads we successfully set the watchpoint
171   // for.  If one of the thread watchpoint setting operations fails,
172   // back off and remove the watchpoint for all the threads that
173   // were successfully set so we get back to a consistent state.
174   std::vector<NativeThreadProtocol *> watchpoint_established_threads;
175 
176   // Tell each thread to set a watchpoint.  In the event that
177   // hardware watchpoints are requested but the SetWatchpoint fails,
178   // try to set a software watchpoint as a fallback.  It's
179   // conceivable that if there are more threads than hardware
180   // watchpoints available, some of the threads will fail to set
181   // hardware watchpoints while software ones may be available.
182   std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
183   for (const auto &thread : m_threads) {
184     assert(thread && "thread list should not have a NULL thread!");
185 
186     Status thread_error =
187         thread->SetWatchpoint(addr, size, watch_flags, hardware);
188     if (thread_error.Fail() && hardware) {
189       // Try software watchpoints since we failed on hardware watchpoint setting
190       // and we may have just run out of hardware watchpoints.
191       thread_error = thread->SetWatchpoint(addr, size, watch_flags, false);
192       if (thread_error.Success())
193         LLDB_LOG(log,
194                  "hardware watchpoint requested but software watchpoint set");
195     }
196 
197     if (thread_error.Success()) {
198       // Remember that we set this watchpoint successfully in
199       // case we need to clear it later.
200       watchpoint_established_threads.push_back(thread.get());
201     } else {
202       // Unset the watchpoint for each thread we successfully
203       // set so that we get back to a consistent state of "not
204       // set" for the watchpoint.
205       for (auto unwatch_thread_sp : watchpoint_established_threads) {
206         Status remove_error = unwatch_thread_sp->RemoveWatchpoint(addr);
207         if (remove_error.Fail())
208           LLDB_LOG(log, "RemoveWatchpoint failed for pid={0}, tid={1}: {2}",
209                    GetID(), unwatch_thread_sp->GetID(), remove_error);
210       }
211 
212       return thread_error;
213     }
214   }
215   return m_watchpoint_list.Add(addr, size, watch_flags, hardware);
216 }
217 
218 Status NativeProcessProtocol::RemoveWatchpoint(lldb::addr_t addr) {
219   // Update the thread list
220   UpdateThreads();
221 
222   Status overall_error;
223 
224   std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
225   for (const auto &thread : m_threads) {
226     assert(thread && "thread list should not have a NULL thread!");
227 
228     const Status thread_error = thread->RemoveWatchpoint(addr);
229     if (thread_error.Fail()) {
230       // Keep track of the first thread error if any threads
231       // fail. We want to try to remove the watchpoint from
232       // every thread, though, even if one or more have errors.
233       if (!overall_error.Fail())
234         overall_error = thread_error;
235     }
236   }
237   const Status error = m_watchpoint_list.Remove(addr);
238   return overall_error.Fail() ? overall_error : error;
239 }
240 
241 const HardwareBreakpointMap &
242 NativeProcessProtocol::GetHardwareBreakpointMap() const {
243   return m_hw_breakpoints_map;
244 }
245 
246 Status NativeProcessProtocol::SetHardwareBreakpoint(lldb::addr_t addr,
247                                                     size_t size) {
248   // This default implementation assumes setting a hardware breakpoint for
249   // this process will require setting same hardware breakpoint for each
250   // of its existing threads. New thread will do the same once created.
251   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
252 
253   // Update the thread list
254   UpdateThreads();
255 
256   // Exit here if target does not have required hardware breakpoint capability.
257   auto hw_debug_cap = GetHardwareDebugSupportInfo();
258 
259   if (hw_debug_cap == llvm::None || hw_debug_cap->first == 0 ||
260       hw_debug_cap->first <= m_hw_breakpoints_map.size())
261     return Status("Target does not have required no of hardware breakpoints");
262 
263   // Vector below stores all thread pointer for which we have we successfully
264   // set this hardware breakpoint. If any of the current process threads fails
265   // to set this hardware breakpoint then roll back and remove this breakpoint
266   // for all the threads that had already set it successfully.
267   std::vector<NativeThreadProtocol *> breakpoint_established_threads;
268 
269   // Request to set a hardware breakpoint for each of current process threads.
270   std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
271   for (const auto &thread : m_threads) {
272     assert(thread && "thread list should not have a NULL thread!");
273 
274     Status thread_error = thread->SetHardwareBreakpoint(addr, size);
275     if (thread_error.Success()) {
276       // Remember that we set this breakpoint successfully in
277       // case we need to clear it later.
278       breakpoint_established_threads.push_back(thread.get());
279     } else {
280       // Unset the breakpoint for each thread we successfully
281       // set so that we get back to a consistent state of "not
282       // set" for this hardware breakpoint.
283       for (auto rollback_thread_sp : breakpoint_established_threads) {
284         Status remove_error =
285             rollback_thread_sp->RemoveHardwareBreakpoint(addr);
286         if (remove_error.Fail())
287           LLDB_LOG(log,
288                    "RemoveHardwareBreakpoint failed for pid={0}, tid={1}: {2}",
289                    GetID(), rollback_thread_sp->GetID(), remove_error);
290       }
291 
292       return thread_error;
293     }
294   }
295 
296   // Register new hardware breakpoint into hardware breakpoints map of current
297   // process.
298   m_hw_breakpoints_map[addr] = {addr, size};
299 
300   return Status();
301 }
302 
303 Status NativeProcessProtocol::RemoveHardwareBreakpoint(lldb::addr_t addr) {
304   // Update the thread list
305   UpdateThreads();
306 
307   Status error;
308 
309   std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
310   for (const auto &thread : m_threads) {
311     assert(thread && "thread list should not have a NULL thread!");
312     error = thread->RemoveHardwareBreakpoint(addr);
313   }
314 
315   // Also remove from hardware breakpoint map of current process.
316   m_hw_breakpoints_map.erase(addr);
317 
318   return error;
319 }
320 
321 bool NativeProcessProtocol::RegisterNativeDelegate(
322     NativeDelegate &native_delegate) {
323   std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
324   if (std::find(m_delegates.begin(), m_delegates.end(), &native_delegate) !=
325       m_delegates.end())
326     return false;
327 
328   m_delegates.push_back(&native_delegate);
329   native_delegate.InitializeDelegate(this);
330   return true;
331 }
332 
333 bool NativeProcessProtocol::UnregisterNativeDelegate(
334     NativeDelegate &native_delegate) {
335   std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
336 
337   const auto initial_size = m_delegates.size();
338   m_delegates.erase(
339       remove(m_delegates.begin(), m_delegates.end(), &native_delegate),
340       m_delegates.end());
341 
342   // We removed the delegate if the count of delegates shrank after
343   // removing all copies of the given native_delegate from the vector.
344   return m_delegates.size() < initial_size;
345 }
346 
347 void NativeProcessProtocol::SynchronouslyNotifyProcessStateChanged(
348     lldb::StateType state) {
349   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
350 
351   std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
352   for (auto native_delegate : m_delegates)
353     native_delegate->ProcessStateChanged(this, state);
354 
355   if (log) {
356     if (!m_delegates.empty()) {
357       log->Printf("NativeProcessProtocol::%s: sent state notification [%s] "
358                   "from process %" PRIu64,
359                   __FUNCTION__, lldb_private::StateAsCString(state), GetID());
360     } else {
361       log->Printf("NativeProcessProtocol::%s: would send state notification "
362                   "[%s] from process %" PRIu64 ", but no delegates",
363                   __FUNCTION__, lldb_private::StateAsCString(state), GetID());
364     }
365   }
366 }
367 
368 void NativeProcessProtocol::NotifyDidExec() {
369   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
370   if (log)
371     log->Printf("NativeProcessProtocol::%s - preparing to call delegates",
372                 __FUNCTION__);
373 
374   {
375     std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
376     for (auto native_delegate : m_delegates)
377       native_delegate->DidExec(this);
378   }
379 }
380 
381 Status NativeProcessProtocol::SetSoftwareBreakpoint(lldb::addr_t addr,
382                                                     uint32_t size_hint) {
383   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
384   if (log)
385     log->Printf("NativeProcessProtocol::%s addr = 0x%" PRIx64, __FUNCTION__,
386                 addr);
387 
388   return m_breakpoint_list.AddRef(
389       addr, size_hint, false,
390       [this](lldb::addr_t addr, size_t size_hint, bool /* hardware */,
391              NativeBreakpointSP &breakpoint_sp) -> Status {
392         return SoftwareBreakpoint::CreateSoftwareBreakpoint(
393             *this, addr, size_hint, breakpoint_sp);
394       });
395 }
396 
397 Status NativeProcessProtocol::RemoveBreakpoint(lldb::addr_t addr,
398                                                bool hardware) {
399   if (hardware)
400     return RemoveHardwareBreakpoint(addr);
401   else
402     return m_breakpoint_list.DecRef(addr);
403 }
404 
405 Status NativeProcessProtocol::EnableBreakpoint(lldb::addr_t addr) {
406   return m_breakpoint_list.EnableBreakpoint(addr);
407 }
408 
409 Status NativeProcessProtocol::DisableBreakpoint(lldb::addr_t addr) {
410   return m_breakpoint_list.DisableBreakpoint(addr);
411 }
412 
413 lldb::StateType NativeProcessProtocol::GetState() const {
414   std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
415   return m_state;
416 }
417 
418 void NativeProcessProtocol::SetState(lldb::StateType state,
419                                      bool notify_delegates) {
420   std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
421 
422   if (state == m_state)
423     return;
424 
425   m_state = state;
426 
427   if (StateIsStoppedState(state, false)) {
428     ++m_stop_id;
429 
430     // Give process a chance to do any stop id bump processing, such as
431     // clearing cached data that is invalidated each time the process runs.
432     // Note if/when we support some threads running, we'll end up needing
433     // to manage this per thread and per process.
434     DoStopIDBumped(m_stop_id);
435   }
436 
437   // Optionally notify delegates of the state change.
438   if (notify_delegates)
439     SynchronouslyNotifyProcessStateChanged(state);
440 }
441 
442 uint32_t NativeProcessProtocol::GetStopID() const {
443   std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
444   return m_stop_id;
445 }
446 
447 void NativeProcessProtocol::DoStopIDBumped(uint32_t /* newBumpId */) {
448   // Default implementation does nothing.
449 }
450 
451 Status NativeProcessProtocol::ResolveProcessArchitecture(lldb::pid_t pid,
452                                                          ArchSpec &arch) {
453   // Grab process info for the running process.
454   ProcessInstanceInfo process_info;
455   if (!Host::GetProcessInfo(pid, process_info))
456     return Status("failed to get process info");
457 
458   // Resolve the executable module.
459   ModuleSpecList module_specs;
460   if (!ObjectFile::GetModuleSpecifications(process_info.GetExecutableFile(), 0,
461                                            0, module_specs))
462     return Status("failed to get module specifications");
463   lldbassert(module_specs.GetSize() == 1);
464 
465   arch = module_specs.GetModuleSpecRefAtIndex(0).GetArchitecture();
466   if (arch.IsValid())
467     return Status();
468   else
469     return Status(
470         "failed to retrieve a valid architecture from the exe module");
471 }
472 
473 NativeProcessProtocol::Factory::~Factory() = default;
474