1 //===-- ProcessGDBRemote.h --------------------------------------*- 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 #ifndef liblldb_ProcessGDBRemote_h_
11 #define liblldb_ProcessGDBRemote_h_
12 
13 // C Includes
14 // C++ Includes
15 #include <atomic>
16 #include <map>
17 #include <string>
18 #include <vector>
19 
20 // Other libraries and framework includes
21 // Project includes
22 #include "lldb/Core/ArchSpec.h"
23 #include "lldb/Core/Broadcaster.h"
24 #include "lldb/Core/ConstString.h"
25 #include "lldb/Core/Error.h"
26 #include "lldb/Core/StreamString.h"
27 #include "lldb/Core/StringList.h"
28 #include "lldb/Core/StructuredData.h"
29 #include "lldb/Core/ThreadSafeValue.h"
30 #include "lldb/Core/LoadedModuleInfoList.h"
31 #include "lldb/Host/HostThread.h"
32 #include "lldb/lldb-private-forward.h"
33 #include "lldb/Utility/StringExtractor.h"
34 #include "lldb/Target/Process.h"
35 #include "lldb/Target/Thread.h"
36 
37 #include "GDBRemoteCommunicationClient.h"
38 #include "GDBRemoteRegisterContext.h"
39 
40 namespace lldb_private {
41 namespace process_gdb_remote {
42 
43 class ThreadGDBRemote;
44 
45 class ProcessGDBRemote : public Process
46 {
47 public:
48     ProcessGDBRemote(lldb::TargetSP target_sp, Listener &listener);
49 
50     ~ProcessGDBRemote() override;
51 
52     static lldb::ProcessSP
53     CreateInstance (lldb::TargetSP target_sp,
54                     Listener &listener,
55                     const FileSpec *crash_file_path);
56 
57     static void
58     Initialize();
59 
60     static void
61     DebuggerInitialize (Debugger &debugger);
62 
63     static void
64     Terminate();
65 
66     static ConstString
67     GetPluginNameStatic();
68 
69     static const char *
70     GetPluginDescriptionStatic();
71 
72     //------------------------------------------------------------------
73     // Check if a given Process
74     //------------------------------------------------------------------
75     bool
76     CanDebug (lldb::TargetSP target_sp, bool plugin_specified_by_name) override;
77 
78     CommandObject *
79     GetPluginCommandObject() override;
80 
81     //------------------------------------------------------------------
82     // Creating a new process, or attaching to an existing one
83     //------------------------------------------------------------------
84     Error
85     WillLaunch (Module* module) override;
86 
87     Error
88     DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info) override;
89 
90     void
91     DidLaunch () override;
92 
93     Error
94     WillAttachToProcessWithID (lldb::pid_t pid) override;
95 
96     Error
97     WillAttachToProcessWithName (const char *process_name, bool wait_for_launch) override;
98 
99     Error
100     DoConnectRemote (Stream *strm, const char *remote_url) override;
101 
102     Error
103     WillLaunchOrAttach ();
104 
105     Error
106     DoAttachToProcessWithID (lldb::pid_t pid, const ProcessAttachInfo &attach_info) override;
107 
108     Error
109     DoAttachToProcessWithName (const char *process_name,
110                                const ProcessAttachInfo &attach_info) override;
111 
112     void
113     DidAttach (ArchSpec &process_arch) override;
114 
115     //------------------------------------------------------------------
116     // PluginInterface protocol
117     //------------------------------------------------------------------
118     ConstString
119     GetPluginName() override;
120 
121     uint32_t
122     GetPluginVersion() override;
123 
124     //------------------------------------------------------------------
125     // Process Control
126     //------------------------------------------------------------------
127     Error
128     WillResume () override;
129 
130     Error
131     DoResume () override;
132 
133     Error
134     DoHalt (bool &caused_stop) override;
135 
136     Error
137     DoDetach (bool keep_stopped) override;
138 
139     bool
140     DetachRequiresHalt() override { return true; }
141 
142     Error
143     DoSignal (int signal) override;
144 
145     Error
146     DoDestroy () override;
147 
148     void
149     RefreshStateAfterStop() override;
150 
151     void
152     SetUnixSignals(const lldb::UnixSignalsSP &signals_sp);
153 
154     //------------------------------------------------------------------
155     // Process Queries
156     //------------------------------------------------------------------
157     bool
158     IsAlive () override;
159 
160     lldb::addr_t
161     GetImageInfoAddress() override;
162 
163     void
164     WillPublicStop () override;
165 
166     //------------------------------------------------------------------
167     // Process Memory
168     //------------------------------------------------------------------
169     size_t
170     DoReadMemory (lldb::addr_t addr, void *buf, size_t size, Error &error) override;
171 
172     size_t
173     DoWriteMemory (lldb::addr_t addr, const void *buf, size_t size, Error &error) override;
174 
175     lldb::addr_t
176     DoAllocateMemory (size_t size, uint32_t permissions, Error &error) override;
177 
178     Error
179     GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &region_info) override;
180 
181     Error
182     DoDeallocateMemory (lldb::addr_t ptr) override;
183 
184     //------------------------------------------------------------------
185     // Process STDIO
186     //------------------------------------------------------------------
187     size_t
188     PutSTDIN (const char *buf, size_t buf_size, Error &error) override;
189 
190     //----------------------------------------------------------------------
191     // Process Breakpoints
192     //----------------------------------------------------------------------
193     Error
194     EnableBreakpointSite (BreakpointSite *bp_site) override;
195 
196     Error
197     DisableBreakpointSite (BreakpointSite *bp_site) override;
198 
199     //----------------------------------------------------------------------
200     // Process Watchpoints
201     //----------------------------------------------------------------------
202     Error
203     EnableWatchpoint (Watchpoint *wp, bool notify = true) override;
204 
205     Error
206     DisableWatchpoint (Watchpoint *wp, bool notify = true) override;
207 
208     Error
209     GetWatchpointSupportInfo (uint32_t &num) override;
210 
211     Error
212     GetWatchpointSupportInfo (uint32_t &num, bool& after) override;
213 
214     bool
215     StartNoticingNewThreads() override;
216 
217     bool
218     StopNoticingNewThreads() override;
219 
220     GDBRemoteCommunicationClient &
221     GetGDBRemote()
222     {
223         return m_gdb_comm;
224     }
225 
226     Error
227     SendEventData(const char *data) override;
228 
229     //----------------------------------------------------------------------
230     // Override DidExit so we can disconnect from the remote GDB server
231     //----------------------------------------------------------------------
232     void
233     DidExit () override;
234 
235     void
236     SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max);
237 
238     bool
239     GetModuleSpec(const FileSpec& module_file_spec,
240                   const ArchSpec& arch,
241                   ModuleSpec &module_spec) override;
242 
243     bool
244     GetHostOSVersion(uint32_t &major,
245                      uint32_t &minor,
246                      uint32_t &update) override;
247 
248     size_t
249     LoadModules(LoadedModuleInfoList &module_list) override;
250 
251     size_t
252     LoadModules() override;
253 
254     Error
255     GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr) override;
256 
257     void
258     ModulesDidLoad (ModuleList &module_list) override;
259 
260     StructuredData::ObjectSP
261     GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count) override;
262 
263 protected:
264     friend class ThreadGDBRemote;
265     friend class GDBRemoteCommunicationClient;
266     friend class GDBRemoteRegisterContext;
267 
268     //------------------------------------------------------------------
269     /// Broadcaster event bits definitions.
270     //------------------------------------------------------------------
271     enum
272     {
273         eBroadcastBitAsyncContinue                  = (1 << 0),
274         eBroadcastBitAsyncThreadShouldExit          = (1 << 1),
275         eBroadcastBitAsyncThreadDidExit             = (1 << 2)
276     };
277 
278     Flags m_flags;            // Process specific flags (see eFlags enums)
279     GDBRemoteCommunicationClient m_gdb_comm;
280     std::atomic<lldb::pid_t> m_debugserver_pid;
281     std::vector<StringExtractorGDBRemote> m_stop_packet_stack;  // The stop packet stack replaces the last stop packet variable
282     Mutex m_last_stop_packet_mutex;
283     GDBRemoteDynamicRegisterInfo m_register_info;
284     Broadcaster m_async_broadcaster;
285     Listener m_async_listener;
286     HostThread m_async_thread;
287     Mutex m_async_thread_state_mutex;
288     typedef std::vector<lldb::tid_t> tid_collection;
289     typedef std::vector< std::pair<lldb::tid_t,int> > tid_sig_collection;
290     typedef std::map<lldb::addr_t, lldb::addr_t> MMapMap;
291     typedef std::map<uint32_t, std::string> ExpeditedRegisterMap;
292     tid_collection m_thread_ids; // Thread IDs for all threads. This list gets updated after stopping
293     std::vector<lldb::addr_t> m_thread_pcs; // PC values for all the threads.
294     StructuredData::ObjectSP m_jstopinfo_sp; // Stop info only for any threads that have valid stop infos
295     StructuredData::ObjectSP m_jthreadsinfo_sp; // Full stop info, expedited registers and memory for all threads if "jThreadsInfo" packet is supported
296     tid_collection m_continue_c_tids;                  // 'c' for continue
297     tid_sig_collection m_continue_C_tids; // 'C' for continue with signal
298     tid_collection m_continue_s_tids;                  // 's' for step
299     tid_sig_collection m_continue_S_tids; // 'S' for step with signal
300     uint64_t m_max_memory_size;       // The maximum number of bytes to read/write when reading and writing memory
301     uint64_t m_remote_stub_max_memory_size;    // The maximum memory size the remote gdb stub can handle
302     MMapMap m_addr_to_mmap_size;
303     lldb::BreakpointSP m_thread_create_bp_sp;
304     bool m_waiting_for_attach;
305     bool m_destroy_tried_resuming;
306     lldb::CommandObjectSP m_command_sp;
307     int64_t m_breakpoint_pc_offset;
308     lldb::tid_t m_initial_tid; // The initial thread ID, given by stub on attach
309 
310     //----------------------------------------------------------------------
311     // Accessors
312     //----------------------------------------------------------------------
313     bool
314     IsRunning ( lldb::StateType state )
315     {
316         return state == lldb::eStateRunning || IsStepping(state);
317     }
318 
319     bool
320     IsStepping ( lldb::StateType state)
321     {
322         return state == lldb::eStateStepping;
323     }
324 
325     bool
326     CanResume ( lldb::StateType state)
327     {
328         return state == lldb::eStateStopped;
329     }
330 
331     bool
332     HasExited (lldb::StateType state)
333     {
334         return state == lldb::eStateExited;
335     }
336 
337     bool
338     ProcessIDIsValid ( ) const;
339 
340     void
341     Clear ( );
342 
343     Flags &
344     GetFlags ()
345     {
346         return m_flags;
347     }
348 
349     const Flags &
350     GetFlags () const
351     {
352         return m_flags;
353     }
354 
355     bool
356     UpdateThreadList (ThreadList &old_thread_list,
357                       ThreadList &new_thread_list) override;
358 
359     Error
360     EstablishConnectionIfNeeded (const ProcessInfo &process_info);
361 
362     Error
363     LaunchAndConnectToDebugserver (const ProcessInfo &process_info);
364 
365     void
366     KillDebugserverProcess ();
367 
368     void
369     BuildDynamicRegisterInfo (bool force);
370 
371     void
372     SetLastStopPacket (const StringExtractorGDBRemote &response);
373 
374     bool
375     ParsePythonTargetDefinition(const FileSpec &target_definition_fspec);
376 
377     const lldb::DataBufferSP
378     GetAuxvData() override;
379 
380     StructuredData::ObjectSP
381     GetExtendedInfoForThread (lldb::tid_t tid);
382 
383     void
384     GetMaxMemorySize();
385 
386     bool
387     CalculateThreadStopInfo (ThreadGDBRemote *thread);
388 
389     size_t
390     UpdateThreadPCsFromStopReplyThreadsValue (std::string &value);
391 
392     size_t
393     UpdateThreadIDsFromStopReplyThreadsValue (std::string &value);
394 
395     bool
396     HandleNotifyPacket(StringExtractorGDBRemote &packet);
397 
398     bool
399     StartAsyncThread ();
400 
401     void
402     StopAsyncThread ();
403 
404     static lldb::thread_result_t
405     AsyncThread (void *arg);
406 
407     static bool
408     MonitorDebugserverProcess (void *callback_baton,
409                                lldb::pid_t pid,
410                                bool exited,
411                                int signo,
412                                int exit_status);
413 
414     lldb::StateType
415     SetThreadStopInfo (StringExtractor& stop_packet);
416 
417     bool
418     GetThreadStopInfoFromJSON (ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp);
419 
420     lldb::ThreadSP
421     SetThreadStopInfo (StructuredData::Dictionary *thread_dict);
422 
423     lldb::ThreadSP
424     SetThreadStopInfo (lldb::tid_t tid,
425                        ExpeditedRegisterMap &expedited_register_map,
426                        uint8_t signo,
427                        const std::string &thread_name,
428                        const std::string &reason,
429                        const std::string &description,
430                        uint32_t exc_type,
431                        const std::vector<lldb::addr_t> &exc_data,
432                        lldb::addr_t thread_dispatch_qaddr,
433                        bool queue_vars_valid,
434                        lldb_private::LazyBool associated_with_libdispatch_queue,
435                        lldb::addr_t dispatch_queue_t,
436                        std::string &queue_name,
437                        lldb::QueueKind queue_kind,
438                        uint64_t queue_serial);
439 
440     void
441     HandleStopReplySequence ();
442 
443     void
444     ClearThreadIDList ();
445 
446     bool
447     UpdateThreadIDList ();
448 
449     void
450     DidLaunchOrAttach (ArchSpec& process_arch);
451 
452     Error
453     ConnectToDebugserver (const char *host_port);
454 
455     const char *
456     GetDispatchQueueNameForThread (lldb::addr_t thread_dispatch_qaddr,
457                                    std::string &dispatch_queue_name);
458 
459     DynamicLoader *
460     GetDynamicLoader () override;
461 
462     // Query remote GDBServer for register information
463     bool
464     GetGDBServerRegisterInfo ();
465 
466     // Query remote GDBServer for a detailed loaded library list
467     Error
468     GetLoadedModuleList (LoadedModuleInfoList &);
469 
470     lldb::ModuleSP
471     LoadModuleAtAddress (const FileSpec &file, lldb::addr_t base_addr, bool value_is_offset);
472 
473 private:
474     //------------------------------------------------------------------
475     // For ProcessGDBRemote only
476     //------------------------------------------------------------------
477     static bool
478     NewThreadNotifyBreakpointHit (void *baton,
479                          StoppointCallbackContext *context,
480                          lldb::user_id_t break_id,
481                          lldb::user_id_t break_loc_id);
482 
483     DISALLOW_COPY_AND_ASSIGN (ProcessGDBRemote);
484 };
485 
486 } // namespace process_gdb_remote
487 } // namespace lldb_private
488 
489 #endif // liblldb_ProcessGDBRemote_h_
490