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