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