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