1 //===-- GDBRemoteCommunicationClient.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_GDBRemoteCommunicationClient_h_
11 #define liblldb_GDBRemoteCommunicationClient_h_
12 
13 // C Includes
14 // C++ Includes
15 #include <vector>
16 
17 // Other libraries and framework includes
18 // Project includes
19 #include "lldb/Core/ArchSpec.h"
20 #include "lldb/Target/Process.h"
21 
22 #include "GDBRemoteCommunication.h"
23 
24 typedef enum
25 {
26     eBreakpointSoftware = 0,
27     eBreakpointHardware,
28     eWatchpointWrite,
29     eWatchpointRead,
30     eWatchpointReadWrite
31 } GDBStoppointType;
32 
33 class GDBRemoteCommunicationClient : public GDBRemoteCommunication
34 {
35 public:
36     //------------------------------------------------------------------
37     // Constructors and Destructors
38     //------------------------------------------------------------------
39     GDBRemoteCommunicationClient(bool is_platform);
40 
41     ~GDBRemoteCommunicationClient();
42 
43     //------------------------------------------------------------------
44     // After connecting, send the handshake to the server to make sure
45     // we are communicating with it.
46     //------------------------------------------------------------------
47     bool
48     HandshakeWithServer (lldb_private::Error *error_ptr);
49 
50     PacketResult
51     SendPacketAndWaitForResponse (const char *send_payload,
52                                   StringExtractorGDBRemote &response,
53                                   bool send_async);
54 
55     PacketResult
56     SendPacketAndWaitForResponse (const char *send_payload,
57                                   size_t send_length,
58                                   StringExtractorGDBRemote &response,
59                                   bool send_async);
60 
61     // For packets which specify a range of output to be returned,
62     // return all of the output via a series of request packets of the form
63     // <prefix>0,<size>
64     // <prefix><size>,<size>
65     // <prefix><size>*2,<size>
66     // <prefix><size>*3,<size>
67     // ...
68     // until a "$l..." packet is received, indicating the end.
69     // (size is in hex; this format is used by a standard gdbserver to
70     // return the given portion of the output specified by <prefix>;
71     // for example, "qXfer:libraries-svr4:read::fff,1000" means
72     // "return a chunk of the xml description file for shared
73     // library load addresses, where the chunk starts at offset 0xfff
74     // and continues for 0x1000 bytes").
75     // Concatenate the resulting server response packets together and
76     // return in response_string.  If any packet fails, the return value
77     // indicates that failure and the returned string value is undefined.
78     PacketResult
79     SendPacketsAndConcatenateResponses (const char *send_payload_prefix,
80                                         std::string &response_string);
81 
82     lldb::StateType
83     SendContinuePacketAndWaitForResponse (ProcessGDBRemote *process,
84                                           const char *packet_payload,
85                                           size_t packet_length,
86                                           StringExtractorGDBRemote &response);
87 
88     bool
89     GetThreadSuffixSupported ();
90 
91     // This packet is usually sent first and the boolean return value
92     // indicates if the packet was send and any response was received
93     // even in the response is UNIMPLEMENTED. If the packet failed to
94     // get a response, then false is returned. This quickly tells us
95     // if we were able to connect and communicte with the remote GDB
96     // server
97     bool
98     QueryNoAckModeSupported ();
99 
100     void
101     GetListThreadsInStopReplySupported ();
102 
103     bool
104     SendAsyncSignal (int signo);
105 
106     bool
107     SendInterrupt (lldb_private::Mutex::Locker &locker,
108                    uint32_t seconds_to_wait_for_stop,
109                    bool &timed_out);
110 
111     lldb::pid_t
112     GetCurrentProcessID ();
113 
114     bool
115     GetLaunchSuccess (std::string &error_str);
116 
117     uint16_t
118     LaunchGDBserverAndGetPort (lldb::pid_t &pid, const char *remote_accept_hostname);
119 
120     bool
121     KillSpawnedProcess (lldb::pid_t pid);
122 
123     //------------------------------------------------------------------
124     /// Sends a GDB remote protocol 'A' packet that delivers program
125     /// arguments to the remote server.
126     ///
127     /// @param[in] argv
128     ///     A NULL terminated array of const C strings to use as the
129     ///     arguments.
130     ///
131     /// @return
132     ///     Zero if the response was "OK", a positive value if the
133     ///     the response was "Exx" where xx are two hex digits, or
134     ///     -1 if the call is unsupported or any other unexpected
135     ///     response was received.
136     //------------------------------------------------------------------
137     int
138     SendArgumentsPacket (const lldb_private::ProcessLaunchInfo &launch_info);
139 
140     //------------------------------------------------------------------
141     /// Sends a "QEnvironment:NAME=VALUE" packet that will build up the
142     /// environment that will get used when launching an application
143     /// in conjunction with the 'A' packet. This function can be called
144     /// multiple times in a row in order to pass on the desired
145     /// environment that the inferior should be launched with.
146     ///
147     /// @param[in] name_equal_value
148     ///     A NULL terminated C string that contains a single environment
149     ///     in the format "NAME=VALUE".
150     ///
151     /// @return
152     ///     Zero if the response was "OK", a positive value if the
153     ///     the response was "Exx" where xx are two hex digits, or
154     ///     -1 if the call is unsupported or any other unexpected
155     ///     response was received.
156     //------------------------------------------------------------------
157     int
158     SendEnvironmentPacket (char const *name_equal_value);
159 
160     int
161     SendLaunchArchPacket (const char *arch);
162 
163     int
164     SendLaunchEventDataPacket (const char *data, bool *was_supported = NULL);
165 
166     //------------------------------------------------------------------
167     /// Sends a "vAttach:PID" where PID is in hex.
168     ///
169     /// @param[in] pid
170     ///     A process ID for the remote gdb server to attach to.
171     ///
172     /// @param[out] response
173     ///     The response received from the gdb server. If the return
174     ///     value is zero, \a response will contain a stop reply
175     ///     packet.
176     ///
177     /// @return
178     ///     Zero if the attach was successful, or an error indicating
179     ///     an error code.
180     //------------------------------------------------------------------
181     int
182     SendAttach (lldb::pid_t pid,
183                 StringExtractorGDBRemote& response);
184 
185 
186     //------------------------------------------------------------------
187     /// Sets the path to use for stdin/out/err for a process
188     /// that will be launched with the 'A' packet.
189     ///
190     /// @param[in] path
191     ///     The path to use for stdin/out/err
192     ///
193     /// @return
194     ///     Zero if the for success, or an error code for failure.
195     //------------------------------------------------------------------
196     int
197     SetSTDIN (char const *path);
198     int
199     SetSTDOUT (char const *path);
200     int
201     SetSTDERR (char const *path);
202 
203     //------------------------------------------------------------------
204     /// Sets the disable ASLR flag to \a enable for a process that will
205     /// be launched with the 'A' packet.
206     ///
207     /// @param[in] enable
208     ///     A boolean value indicating wether to disable ASLR or not.
209     ///
210     /// @return
211     ///     Zero if the for success, or an error code for failure.
212     //------------------------------------------------------------------
213     int
214     SetDisableASLR (bool enable);
215 
216     //------------------------------------------------------------------
217     /// Sets the working directory to \a path for a process that will
218     /// be launched with the 'A' packet for non platform based
219     /// connections. If this packet is sent to a GDB server that
220     /// implements the platform, it will change the current working
221     /// directory for the platform process.
222     ///
223     /// @param[in] path
224     ///     The path to a directory to use when launching our processs
225     ///
226     /// @return
227     ///     Zero if the for success, or an error code for failure.
228     //------------------------------------------------------------------
229     int
230     SetWorkingDir (char const *path);
231 
232     //------------------------------------------------------------------
233     /// Gets the current working directory of a remote platform GDB
234     /// server.
235     ///
236     /// @param[out] cwd
237     ///     The current working directory on the remote platform.
238     ///
239     /// @return
240     ///     Boolean for success
241     //------------------------------------------------------------------
242     bool
243     GetWorkingDir (std::string &cwd);
244 
245     lldb::addr_t
246     AllocateMemory (size_t size, uint32_t permissions);
247 
248     bool
249     DeallocateMemory (lldb::addr_t addr);
250 
251     lldb_private::Error
252     Detach (bool keep_stopped);
253 
254     lldb_private::Error
255     GetMemoryRegionInfo (lldb::addr_t addr,
256                         lldb_private::MemoryRegionInfo &range_info);
257 
258     lldb_private::Error
259     GetWatchpointSupportInfo (uint32_t &num);
260 
261     lldb_private::Error
262     GetWatchpointSupportInfo (uint32_t &num, bool& after);
263 
264     lldb_private::Error
265     GetWatchpointsTriggerAfterInstruction (bool &after);
266 
267     const lldb_private::ArchSpec &
268     GetHostArchitecture ();
269 
270     uint32_t
271     GetHostDefaultPacketTimeout();
272 
273     const lldb_private::ArchSpec &
274     GetProcessArchitecture ();
275 
276     void
277     GetRemoteQSupported();
278 
279     bool
280     GetVContSupported (char flavor);
281 
282     bool
283     GetpPacketSupported (lldb::tid_t tid);
284 
285     bool
286     GetVAttachOrWaitSupported ();
287 
288     bool
289     GetSyncThreadStateSupported();
290 
291     void
292     ResetDiscoverableSettings();
293 
294     bool
295     GetHostInfo (bool force = false);
296 
297     bool
298     GetOSVersion (uint32_t &major,
299                   uint32_t &minor,
300                   uint32_t &update);
301 
302     bool
303     GetOSBuildString (std::string &s);
304 
305     bool
306     GetOSKernelDescription (std::string &s);
307 
308     lldb_private::ArchSpec
309     GetSystemArchitecture ();
310 
311     bool
312     GetHostname (std::string &s);
313 
314     lldb::addr_t
315     GetShlibInfoAddr();
316 
317     bool
318     GetSupportsThreadSuffix ();
319 
320     bool
321     GetProcessInfo (lldb::pid_t pid,
322                     lldb_private::ProcessInstanceInfo &process_info);
323 
324     uint32_t
325     FindProcesses (const lldb_private::ProcessInstanceInfoMatch &process_match_info,
326                    lldb_private::ProcessInstanceInfoList &process_infos);
327 
328     bool
329     GetUserName (uint32_t uid, std::string &name);
330 
331     bool
332     GetGroupName (uint32_t gid, std::string &name);
333 
334     bool
335     HasFullVContSupport ()
336     {
337         return GetVContSupported ('A');
338     }
339 
340     bool
341     HasAnyVContSupport ()
342     {
343         return GetVContSupported ('a');
344     }
345 
346     bool
347     GetStopReply (StringExtractorGDBRemote &response);
348 
349     bool
350     GetThreadStopInfo (lldb::tid_t tid,
351                        StringExtractorGDBRemote &response);
352 
353     bool
354     SupportsGDBStoppointPacket (GDBStoppointType type)
355     {
356         switch (type)
357         {
358         case eBreakpointSoftware:   return m_supports_z0;
359         case eBreakpointHardware:   return m_supports_z1;
360         case eWatchpointWrite:      return m_supports_z2;
361         case eWatchpointRead:       return m_supports_z3;
362         case eWatchpointReadWrite:  return m_supports_z4;
363         }
364         return false;
365     }
366     uint8_t
367     SendGDBStoppointTypePacket (GDBStoppointType type,   // Type of breakpoint or watchpoint
368                                 bool insert,              // Insert or remove?
369                                 lldb::addr_t addr,        // Address of breakpoint or watchpoint
370                                 uint32_t length);         // Byte Size of breakpoint or watchpoint
371 
372     void
373     TestPacketSpeed (const uint32_t num_packets);
374 
375     // This packet is for testing the speed of the interface only. Both
376     // the client and server need to support it, but this allows us to
377     // measure the packet speed without any other work being done on the
378     // other end and avoids any of that work affecting the packet send
379     // and response times.
380     bool
381     SendSpeedTestPacket (uint32_t send_size,
382                          uint32_t recv_size);
383 
384     bool
385     SetCurrentThread (uint64_t tid);
386 
387     bool
388     SetCurrentThreadForRun (uint64_t tid);
389 
390     bool
391     GetQXferAuxvReadSupported ();
392 
393     bool
394     GetQXferLibrariesReadSupported ();
395 
396     bool
397     GetQXferLibrariesSVR4ReadSupported ();
398 
399     uint64_t
400     GetRemoteMaxPacketSize();
401 
402     bool
403     GetAugmentedLibrariesSVR4ReadSupported ();
404 
405     lldb_private::LazyBool
406     SupportsAllocDeallocMemory () // const
407     {
408         // Uncomment this to have lldb pretend the debug server doesn't respond to alloc/dealloc memory packets.
409         // m_supports_alloc_dealloc_memory = lldb_private::eLazyBoolNo;
410         return m_supports_alloc_dealloc_memory;
411     }
412 
413     size_t
414     GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
415                          bool &sequence_mutex_unavailable);
416 
417     bool
418     GetInterruptWasSent () const
419     {
420         return m_interrupt_sent;
421     }
422 
423     lldb::user_id_t
424     OpenFile (const lldb_private::FileSpec& file_spec,
425               uint32_t flags,
426               mode_t mode,
427               lldb_private::Error &error);
428 
429     bool
430     CloseFile (lldb::user_id_t fd,
431                lldb_private::Error &error);
432 
433     lldb::user_id_t
434     GetFileSize (const lldb_private::FileSpec& file_spec);
435 
436     lldb_private::Error
437     GetFilePermissions(const char *path, uint32_t &file_permissions);
438 
439     lldb_private::Error
440     SetFilePermissions(const char *path, uint32_t file_permissions);
441 
442     uint64_t
443     ReadFile (lldb::user_id_t fd,
444               uint64_t offset,
445               void *dst,
446               uint64_t dst_len,
447               lldb_private::Error &error);
448 
449     uint64_t
450     WriteFile (lldb::user_id_t fd,
451                uint64_t offset,
452                const void* src,
453                uint64_t src_len,
454                lldb_private::Error &error);
455 
456     lldb_private::Error
457     CreateSymlink (const char *src,
458                    const char *dst);
459 
460     lldb_private::Error
461     Unlink (const char *path);
462 
463     lldb_private::Error
464     MakeDirectory (const char *path,
465                    uint32_t mode);
466 
467     bool
468     GetFileExists (const lldb_private::FileSpec& file_spec);
469 
470     lldb_private::Error
471     RunShellCommand (const char *command,           // Shouldn't be NULL
472                      const char *working_dir,       // Pass NULL to use the current working directory
473                      int *status_ptr,               // Pass NULL if you don't want the process exit status
474                      int *signo_ptr,                // Pass NULL if you don't want the signal that caused the process to exit
475                      std::string *command_output,   // Pass NULL if you don't want the command output
476                      uint32_t timeout_sec);         // Timeout in seconds to wait for shell program to finish
477 
478     bool
479     CalculateMD5 (const lldb_private::FileSpec& file_spec,
480                   uint64_t &high,
481                   uint64_t &low);
482 
483     std::string
484     HarmonizeThreadIdsForProfileData (ProcessGDBRemote *process,
485                                       StringExtractorGDBRemote &inputStringExtractor);
486 
487     bool
488     ReadRegister(lldb::tid_t tid,
489                  uint32_t reg_num,
490                  StringExtractorGDBRemote &response);
491 
492     bool
493     ReadAllRegisters (lldb::tid_t tid,
494                       StringExtractorGDBRemote &response);
495 
496     bool
497     SaveRegisterState (lldb::tid_t tid, uint32_t &save_id);
498 
499     bool
500     RestoreRegisterState (lldb::tid_t tid, uint32_t save_id);
501 
502     const char *
503     GetGDBServerProgramName();
504 
505     uint32_t
506     GetGDBServerProgramVersion();
507 
508     bool
509     AvoidGPackets(ProcessGDBRemote *process);
510 
511 protected:
512 
513     PacketResult
514     SendPacketAndWaitForResponseNoLock (const char *payload,
515                                         size_t payload_length,
516                                         StringExtractorGDBRemote &response);
517 
518     bool
519     GetCurrentProcessInfo ();
520 
521     bool
522     GetGDBServerVersion();
523 
524     //------------------------------------------------------------------
525     // Classes that inherit from GDBRemoteCommunicationClient can see and modify these
526     //------------------------------------------------------------------
527     lldb_private::LazyBool m_supports_not_sending_acks;
528     lldb_private::LazyBool m_supports_thread_suffix;
529     lldb_private::LazyBool m_supports_threads_in_stop_reply;
530     lldb_private::LazyBool m_supports_vCont_all;
531     lldb_private::LazyBool m_supports_vCont_any;
532     lldb_private::LazyBool m_supports_vCont_c;
533     lldb_private::LazyBool m_supports_vCont_C;
534     lldb_private::LazyBool m_supports_vCont_s;
535     lldb_private::LazyBool m_supports_vCont_S;
536     lldb_private::LazyBool m_qHostInfo_is_valid;
537     lldb_private::LazyBool m_qProcessInfo_is_valid;
538     lldb_private::LazyBool m_qGDBServerVersion_is_valid;
539     lldb_private::LazyBool m_supports_alloc_dealloc_memory;
540     lldb_private::LazyBool m_supports_memory_region_info;
541     lldb_private::LazyBool m_supports_watchpoint_support_info;
542     lldb_private::LazyBool m_supports_detach_stay_stopped;
543     lldb_private::LazyBool m_watchpoints_trigger_after_instruction;
544     lldb_private::LazyBool m_attach_or_wait_reply;
545     lldb_private::LazyBool m_prepare_for_reg_writing_reply;
546     lldb_private::LazyBool m_supports_p;
547     lldb_private::LazyBool m_avoid_g_packets;
548     lldb_private::LazyBool m_supports_QSaveRegisterState;
549     lldb_private::LazyBool m_supports_qXfer_auxv_read;
550     lldb_private::LazyBool m_supports_qXfer_libraries_read;
551     lldb_private::LazyBool m_supports_qXfer_libraries_svr4_read;
552     lldb_private::LazyBool m_supports_augmented_libraries_svr4_read;
553 
554     bool
555         m_supports_qProcessInfoPID:1,
556         m_supports_qfProcessInfo:1,
557         m_supports_qUserName:1,
558         m_supports_qGroupName:1,
559         m_supports_qThreadStopInfo:1,
560         m_supports_z0:1,
561         m_supports_z1:1,
562         m_supports_z2:1,
563         m_supports_z3:1,
564         m_supports_z4:1,
565         m_supports_QEnvironment:1,
566         m_supports_QEnvironmentHexEncoded:1;
567 
568 
569     lldb::tid_t m_curr_tid;         // Current gdb remote protocol thread index for all other operations
570     lldb::tid_t m_curr_tid_run;     // Current gdb remote protocol thread index for continue, step, etc
571 
572 
573     uint32_t m_num_supported_hardware_watchpoints;
574 
575     // If we need to send a packet while the target is running, the m_async_XXX
576     // member variables take care of making this happen.
577     lldb_private::Mutex m_async_mutex;
578     lldb_private::Predicate<bool> m_async_packet_predicate;
579     std::string m_async_packet;
580     PacketResult m_async_result;
581     StringExtractorGDBRemote m_async_response;
582     int m_async_signal; // We were asked to deliver a signal to the inferior process.
583     bool m_interrupt_sent;
584     std::string m_partial_profile_data;
585     std::map<uint64_t, uint32_t> m_thread_id_to_used_usec_map;
586 
587     lldb_private::ArchSpec m_host_arch;
588     lldb_private::ArchSpec m_process_arch;
589     uint32_t m_os_version_major;
590     uint32_t m_os_version_minor;
591     uint32_t m_os_version_update;
592     std::string m_os_build;
593     std::string m_os_kernel;
594     std::string m_hostname;
595     std::string m_gdb_server_name; // from reply to qGDBServerVersion, empty if qGDBServerVersion is not supported
596     uint32_t m_gdb_server_version; // from reply to qGDBServerVersion, zero if qGDBServerVersion is not supported
597     uint32_t m_default_packet_timeout;
598     uint64_t m_max_packet_size;  // as returned by qSupported
599 
600     bool
601     DecodeProcessInfoResponse (StringExtractorGDBRemote &response,
602                                lldb_private::ProcessInstanceInfo &process_info);
603 private:
604     //------------------------------------------------------------------
605     // For GDBRemoteCommunicationClient only
606     //------------------------------------------------------------------
607     DISALLOW_COPY_AND_ASSIGN (GDBRemoteCommunicationClient);
608 };
609 
610 #endif  // liblldb_GDBRemoteCommunicationClient_h_
611