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