]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Host/common/NativeProcessProtocol.cpp
Update tcpdump to 4.9.2
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / Host / common / NativeProcessProtocol.cpp
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 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();
98 }
99
100 NativeThreadProtocolSP
101 NativeProcessProtocol::GetThreadByIDUnlocked(lldb::tid_t tid) {
102   for (auto thread_sp : m_threads) {
103     if (thread_sp->GetID() == tid)
104       return thread_sp;
105   }
106   return NativeThreadProtocolSP();
107 }
108
109 NativeThreadProtocolSP 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   NativeThreadProtocolSP thread_sp(
138       const_cast<NativeProcessProtocol *>(this)->GetThreadAtIndex(0));
139   if (!thread_sp) {
140     if (log)
141       log->Warning("NativeProcessProtocol::%s (): failed to find a thread to "
142                    "grab a NativeRegisterContext!",
143                    __FUNCTION__);
144     return llvm::None;
145   }
146
147   NativeRegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
148   if (!reg_ctx_sp) {
149     if (log)
150       log->Warning("NativeProcessProtocol::%s (): failed to get a "
151                    "RegisterContextNativeProcess from the first thread!",
152                    __FUNCTION__);
153     return llvm::None;
154   }
155
156   return std::make_pair(reg_ctx_sp->NumSupportedHardwareBreakpoints(),
157                         reg_ctx_sp->NumSupportedHardwareWatchpoints());
158 }
159
160 Status NativeProcessProtocol::SetWatchpoint(lldb::addr_t addr, size_t size,
161                                             uint32_t watch_flags,
162                                             bool hardware) {
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.
168
169   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
170
171   // Update the thread list
172   UpdateThreads();
173
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;
179
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!");
189     if (!thread_sp)
190       continue;
191
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()) {
199         if (log)
200           log->Warning(
201               "hardware watchpoint requested but software watchpoint set");
202       }
203     }
204
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);
209     } else {
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());
220         }
221       }
222
223       return thread_error;
224     }
225   }
226   return m_watchpoint_list.Add(addr, size, watch_flags, hardware);
227 }
228
229 Status NativeProcessProtocol::RemoveWatchpoint(lldb::addr_t addr) {
230   // Update the thread list
231   UpdateThreads();
232
233   Status overall_error;
234
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!");
238     if (!thread_sp)
239       continue;
240
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;
248     }
249   }
250   const Status error = m_watchpoint_list.Remove(addr);
251   return overall_error.Fail() ? overall_error : error;
252 }
253
254 const HardwareBreakpointMap &
255 NativeProcessProtocol::GetHardwareBreakpointMap() const {
256   return m_hw_breakpoints_map;
257 }
258
259 Status NativeProcessProtocol::SetHardwareBreakpoint(lldb::addr_t addr,
260                                                     size_t size) {
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));
265
266   // Update the thread list
267   UpdateThreads();
268
269   // Exit here if target does not have required hardware breakpoint capability.
270   auto hw_debug_cap = GetHardwareDebugSupportInfo();
271
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");
275
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;
281
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!");
286     if (!thread_sp)
287       continue;
288
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);
294     } else {
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());
306         }
307       }
308
309       return thread_error;
310     }
311   }
312
313   // Register new hardware breakpoint into hardware breakpoints map of current
314   // process.
315   m_hw_breakpoints_map[addr] = {addr, size};
316
317   return Status();
318 }
319
320 Status NativeProcessProtocol::RemoveHardwareBreakpoint(lldb::addr_t addr) {
321   // Update the thread list
322   UpdateThreads();
323
324   Status error;
325
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!");
329     if (!thread_sp)
330       continue;
331
332     error = thread_sp->RemoveHardwareBreakpoint(addr);
333   }
334
335   // Also remove from hardware breakpoint map of current process.
336   m_hw_breakpoints_map.erase(addr);
337
338   return error;
339 }
340
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) !=
345       m_delegates.end())
346     return false;
347
348   m_delegates.push_back(&native_delegate);
349   native_delegate.InitializeDelegate(this);
350   return true;
351 }
352
353 bool NativeProcessProtocol::UnregisterNativeDelegate(
354     NativeDelegate &native_delegate) {
355   std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
356
357   const auto initial_size = m_delegates.size();
358   m_delegates.erase(
359       remove(m_delegates.begin(), m_delegates.end(), &native_delegate),
360       m_delegates.end());
361
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;
365 }
366
367 void NativeProcessProtocol::SynchronouslyNotifyProcessStateChanged(
368     lldb::StateType state) {
369   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
370
371   std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
372   for (auto native_delegate : m_delegates)
373     native_delegate->ProcessStateChanged(this, state);
374
375   if (log) {
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());
380     } else {
381       log->Printf("NativeProcessProtocol::%s: would send state notification "
382                   "[%s] from process %" PRIu64 ", but no delegates",
383                   __FUNCTION__, lldb_private::StateAsCString(state), GetID());
384     }
385   }
386 }
387
388 void NativeProcessProtocol::NotifyDidExec() {
389   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
390   if (log)
391     log->Printf("NativeProcessProtocol::%s - preparing to call delegates",
392                 __FUNCTION__);
393
394   {
395     std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
396     for (auto native_delegate : m_delegates)
397       native_delegate->DidExec(this);
398   }
399 }
400
401 Status NativeProcessProtocol::SetSoftwareBreakpoint(lldb::addr_t addr,
402                                                     uint32_t size_hint) {
403   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
404   if (log)
405     log->Printf("NativeProcessProtocol::%s addr = 0x%" PRIx64, __FUNCTION__,
406                 addr);
407
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);
414       });
415 }
416
417 Status NativeProcessProtocol::RemoveBreakpoint(lldb::addr_t addr,
418                                                bool hardware) {
419   if (hardware)
420     return RemoveHardwareBreakpoint(addr);
421   else
422     return m_breakpoint_list.DecRef(addr);
423 }
424
425 Status NativeProcessProtocol::EnableBreakpoint(lldb::addr_t addr) {
426   return m_breakpoint_list.EnableBreakpoint(addr);
427 }
428
429 Status NativeProcessProtocol::DisableBreakpoint(lldb::addr_t addr) {
430   return m_breakpoint_list.DisableBreakpoint(addr);
431 }
432
433 lldb::StateType NativeProcessProtocol::GetState() const {
434   std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
435   return m_state;
436 }
437
438 void NativeProcessProtocol::SetState(lldb::StateType state,
439                                      bool notify_delegates) {
440   std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
441
442   if (state == m_state)
443     return;
444
445   m_state = state;
446
447   if (StateIsStoppedState(state, false)) {
448     ++m_stop_id;
449
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);
455   }
456
457   // Optionally notify delegates of the state change.
458   if (notify_delegates)
459     SynchronouslyNotifyProcessStateChanged(state);
460 }
461
462 uint32_t NativeProcessProtocol::GetStopID() const {
463   std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
464   return m_stop_id;
465 }
466
467 void NativeProcessProtocol::DoStopIDBumped(uint32_t /* newBumpId */) {
468   // Default implementation does nothing.
469 }
470
471 Status NativeProcessProtocol::ResolveProcessArchitecture(lldb::pid_t pid,
472                                                          ArchSpec &arch) {
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");
477
478   // Resolve the executable module.
479   ModuleSpecList module_specs;
480   if (!ObjectFile::GetModuleSpecifications(process_info.GetExecutableFile(), 0,
481                                            0, module_specs))
482     return Status("failed to get module specifications");
483   lldbassert(module_specs.GetSize() == 1);
484
485   arch = module_specs.GetModuleSpecRefAtIndex(0).GetArchitecture();
486   if (arch.IsValid())
487     return Status();
488   else
489     return Status(
490         "failed to retrieve a valid architecture from the exe module");
491 }
492
493 NativeProcessProtocol::Factory::~Factory() = default;