1 //===-- GDBRemoteCommunicationClient.h --------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef liblldb_GDBRemoteCommunicationClient_h_
11 #define liblldb_GDBRemoteCommunicationClient_h_
13 #include "GDBRemoteClientBase.h"
23 #include "lldb/Target/Process.h"
24 #include "lldb/Utility/ArchSpec.h"
25 #include "lldb/Utility/StreamGDBRemote.h"
26 #include "lldb/Utility/StructuredData.h"
28 #include "llvm/ADT/Optional.h"
30 namespace lldb_private {
31 namespace process_gdb_remote {
33 class GDBRemoteCommunicationClient : public GDBRemoteClientBase {
35 GDBRemoteCommunicationClient();
37 ~GDBRemoteCommunicationClient() override;
39 //------------------------------------------------------------------
40 // After connecting, send the handshake to the server to make sure
41 // we are communicating with it.
42 //------------------------------------------------------------------
43 bool HandshakeWithServer(Status *error_ptr);
45 // For packets which specify a range of output to be returned,
46 // return all of the output via a series of request packets of the form
48 // <prefix><size>,<size>
49 // <prefix><size>*2,<size>
50 // <prefix><size>*3,<size>
52 // until a "$l..." packet is received, indicating the end.
53 // (size is in hex; this format is used by a standard gdbserver to
54 // return the given portion of the output specified by <prefix>;
55 // for example, "qXfer:libraries-svr4:read::fff,1000" means
56 // "return a chunk of the xml description file for shared
57 // library load addresses, where the chunk starts at offset 0xfff
58 // and continues for 0x1000 bytes").
59 // Concatenate the resulting server response packets together and
60 // return in response_string. If any packet fails, the return value
61 // indicates that failure and the returned string value is undefined.
63 SendPacketsAndConcatenateResponses(const char *send_payload_prefix,
64 std::string &response_string);
66 bool GetThreadSuffixSupported();
68 // This packet is usually sent first and the boolean return value
69 // indicates if the packet was send and any response was received
70 // even in the response is UNIMPLEMENTED. If the packet failed to
71 // get a response, then false is returned. This quickly tells us
72 // if we were able to connect and communicate with the remote GDB
74 bool QueryNoAckModeSupported();
76 void GetListThreadsInStopReplySupported();
78 lldb::pid_t GetCurrentProcessID(bool allow_lazy = true);
80 bool GetLaunchSuccess(std::string &error_str);
82 bool LaunchGDBServer(const char *remote_accept_hostname, lldb::pid_t &pid,
83 uint16_t &port, std::string &socket_name);
85 size_t QueryGDBServer(
86 std::vector<std::pair<uint16_t, std::string>> &connection_urls);
88 bool KillSpawnedProcess(lldb::pid_t pid);
90 //------------------------------------------------------------------
91 /// Sends a GDB remote protocol 'A' packet that delivers program
92 /// arguments to the remote server.
95 /// A NULL terminated array of const C strings to use as the
99 /// Zero if the response was "OK", a positive value if the
100 /// the response was "Exx" where xx are two hex digits, or
101 /// -1 if the call is unsupported or any other unexpected
102 /// response was received.
103 //------------------------------------------------------------------
104 int SendArgumentsPacket(const ProcessLaunchInfo &launch_info);
106 //------------------------------------------------------------------
107 /// Sends a "QEnvironment:NAME=VALUE" packet that will build up the
108 /// environment that will get used when launching an application
109 /// in conjunction with the 'A' packet. This function can be called
110 /// multiple times in a row in order to pass on the desired
111 /// environment that the inferior should be launched with.
113 /// @param[in] name_equal_value
114 /// A NULL terminated C string that contains a single environment
115 /// in the format "NAME=VALUE".
118 /// Zero if the response was "OK", a positive value if the
119 /// the response was "Exx" where xx are two hex digits, or
120 /// -1 if the call is unsupported or any other unexpected
121 /// response was received.
122 //------------------------------------------------------------------
123 int SendEnvironmentPacket(char const *name_equal_value);
125 int SendLaunchArchPacket(const char *arch);
127 int SendLaunchEventDataPacket(const char *data,
128 bool *was_supported = nullptr);
130 //------------------------------------------------------------------
131 /// Sends a "vAttach:PID" where PID is in hex.
134 /// A process ID for the remote gdb server to attach to.
136 /// @param[out] response
137 /// The response received from the gdb server. If the return
138 /// value is zero, \a response will contain a stop reply
142 /// Zero if the attach was successful, or an error indicating
144 //------------------------------------------------------------------
145 int SendAttach(lldb::pid_t pid, StringExtractorGDBRemote &response);
147 //------------------------------------------------------------------
148 /// Sends a GDB remote protocol 'I' packet that delivers stdin
149 /// data to the remote process.
152 /// A pointer to stdin data.
154 /// @param[in] data_len
155 /// The number of bytes available at \a data.
158 /// Zero if the attach was successful, or an error indicating
160 //------------------------------------------------------------------
161 int SendStdinNotification(const char *data, size_t data_len);
163 //------------------------------------------------------------------
164 /// Sets the path to use for stdin/out/err for a process
165 /// that will be launched with the 'A' packet.
168 /// The path to use for stdin/out/err
171 /// Zero if the for success, or an error code for failure.
172 //------------------------------------------------------------------
173 int SetSTDIN(const FileSpec &file_spec);
174 int SetSTDOUT(const FileSpec &file_spec);
175 int SetSTDERR(const FileSpec &file_spec);
177 //------------------------------------------------------------------
178 /// Sets the disable ASLR flag to \a enable for a process that will
179 /// be launched with the 'A' packet.
181 /// @param[in] enable
182 /// A boolean value indicating whether to disable ASLR or not.
185 /// Zero if the for success, or an error code for failure.
186 //------------------------------------------------------------------
187 int SetDisableASLR(bool enable);
189 //------------------------------------------------------------------
190 /// Sets the DetachOnError flag to \a enable for the process controlled by the
193 /// @param[in] enable
194 /// A boolean value indicating whether to detach on error or not.
197 /// Zero if the for success, or an error code for failure.
198 //------------------------------------------------------------------
199 int SetDetachOnError(bool enable);
201 //------------------------------------------------------------------
202 /// Sets the working directory to \a path for a process that will
203 /// be launched with the 'A' packet for non platform based
204 /// connections. If this packet is sent to a GDB server that
205 /// implements the platform, it will change the current working
206 /// directory for the platform process.
208 /// @param[in] working_dir
209 /// The path to a directory to use when launching our process
212 /// Zero if the for success, or an error code for failure.
213 //------------------------------------------------------------------
214 int SetWorkingDir(const FileSpec &working_dir);
216 //------------------------------------------------------------------
217 /// Gets the current working directory of a remote platform GDB
220 /// @param[out] working_dir
221 /// The current working directory on the remote platform.
224 /// Boolean for success
225 //------------------------------------------------------------------
226 bool GetWorkingDir(FileSpec &working_dir);
228 lldb::addr_t AllocateMemory(size_t size, uint32_t permissions);
230 bool DeallocateMemory(lldb::addr_t addr);
232 Status Detach(bool keep_stopped);
234 Status GetMemoryRegionInfo(lldb::addr_t addr, MemoryRegionInfo &range_info);
236 Status GetWatchpointSupportInfo(uint32_t &num);
238 Status GetWatchpointSupportInfo(uint32_t &num, bool &after,
239 const ArchSpec &arch);
241 Status GetWatchpointsTriggerAfterInstruction(bool &after,
242 const ArchSpec &arch);
244 const ArchSpec &GetHostArchitecture();
246 std::chrono::seconds GetHostDefaultPacketTimeout();
248 const ArchSpec &GetProcessArchitecture();
250 void GetRemoteQSupported();
252 bool GetVContSupported(char flavor);
254 bool GetpPacketSupported(lldb::tid_t tid);
256 bool GetxPacketSupported();
258 bool GetVAttachOrWaitSupported();
260 bool GetSyncThreadStateSupported();
262 void ResetDiscoverableSettings(bool did_exec);
264 bool GetHostInfo(bool force = false);
266 bool GetDefaultThreadId(lldb::tid_t &tid);
268 bool GetOSVersion(uint32_t &major, uint32_t &minor, uint32_t &update);
270 bool GetOSBuildString(std::string &s);
272 bool GetOSKernelDescription(std::string &s);
274 ArchSpec GetSystemArchitecture();
276 bool GetHostname(std::string &s);
278 lldb::addr_t GetShlibInfoAddr();
280 bool GetSupportsThreadSuffix();
282 bool GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &process_info);
284 uint32_t FindProcesses(const ProcessInstanceInfoMatch &process_match_info,
285 ProcessInstanceInfoList &process_infos);
287 bool GetUserName(uint32_t uid, std::string &name);
289 bool GetGroupName(uint32_t gid, std::string &name);
291 bool HasFullVContSupport() { return GetVContSupported('A'); }
293 bool HasAnyVContSupport() { return GetVContSupported('a'); }
295 bool GetStopReply(StringExtractorGDBRemote &response);
297 bool GetThreadStopInfo(lldb::tid_t tid, StringExtractorGDBRemote &response);
299 bool SupportsGDBStoppointPacket(GDBStoppointType type) {
301 case eBreakpointSoftware:
302 return m_supports_z0;
303 case eBreakpointHardware:
304 return m_supports_z1;
305 case eWatchpointWrite:
306 return m_supports_z2;
307 case eWatchpointRead:
308 return m_supports_z3;
309 case eWatchpointReadWrite:
310 return m_supports_z4;
316 uint8_t SendGDBStoppointTypePacket(
317 GDBStoppointType type, // Type of breakpoint or watchpoint
318 bool insert, // Insert or remove?
319 lldb::addr_t addr, // Address of breakpoint or watchpoint
320 uint32_t length); // Byte Size of breakpoint or watchpoint
322 bool SetNonStopMode(const bool enable);
324 void TestPacketSpeed(const uint32_t num_packets, uint32_t max_send,
325 uint32_t max_recv, uint64_t recv_amount, bool json,
328 // This packet is for testing the speed of the interface only. Both
329 // the client and server need to support it, but this allows us to
330 // measure the packet speed without any other work being done on the
331 // other end and avoids any of that work affecting the packet send
332 // and response times.
333 bool SendSpeedTestPacket(uint32_t send_size, uint32_t recv_size);
335 bool SetCurrentThread(uint64_t tid);
337 bool SetCurrentThreadForRun(uint64_t tid);
339 bool GetQXferAuxvReadSupported();
341 void EnableErrorStringInPacket();
343 bool GetQXferLibrariesReadSupported();
345 bool GetQXferLibrariesSVR4ReadSupported();
347 uint64_t GetRemoteMaxPacketSize();
349 bool GetEchoSupported();
351 bool GetQPassSignalsSupported();
353 bool GetAugmentedLibrariesSVR4ReadSupported();
355 bool GetQXferFeaturesReadSupported();
357 LazyBool SupportsAllocDeallocMemory() // const
359 // Uncomment this to have lldb pretend the debug server doesn't respond to
360 // alloc/dealloc memory packets.
361 // m_supports_alloc_dealloc_memory = lldb_private::eLazyBoolNo;
362 return m_supports_alloc_dealloc_memory;
365 size_t GetCurrentThreadIDs(std::vector<lldb::tid_t> &thread_ids,
366 bool &sequence_mutex_unavailable);
368 lldb::user_id_t OpenFile(const FileSpec &file_spec, uint32_t flags,
369 mode_t mode, Status &error);
371 bool CloseFile(lldb::user_id_t fd, Status &error);
373 lldb::user_id_t GetFileSize(const FileSpec &file_spec);
375 Status GetFilePermissions(const FileSpec &file_spec,
376 uint32_t &file_permissions);
378 Status SetFilePermissions(const FileSpec &file_spec,
379 uint32_t file_permissions);
381 uint64_t ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst,
382 uint64_t dst_len, Status &error);
384 uint64_t WriteFile(lldb::user_id_t fd, uint64_t offset, const void *src,
385 uint64_t src_len, Status &error);
387 Status CreateSymlink(const FileSpec &src, const FileSpec &dst);
389 Status Unlink(const FileSpec &file_spec);
391 Status MakeDirectory(const FileSpec &file_spec, uint32_t mode);
393 bool GetFileExists(const FileSpec &file_spec);
395 Status RunShellCommand(
396 const char *command, // Shouldn't be nullptr
397 const FileSpec &working_dir, // Pass empty FileSpec to use the current
399 int *status_ptr, // Pass nullptr if you don't want the process exit status
400 int *signo_ptr, // Pass nullptr if you don't want the signal that caused
401 // the process to exit
403 *command_output, // Pass nullptr if you don't want the command output
404 uint32_t timeout_sec); // Timeout in seconds to wait for shell program to
407 bool CalculateMD5(const FileSpec &file_spec, uint64_t &high, uint64_t &low);
409 lldb::DataBufferSP ReadRegister(
412 reg_num); // Must be the eRegisterKindProcessPlugin register number
414 lldb::DataBufferSP ReadAllRegisters(lldb::tid_t tid);
417 WriteRegister(lldb::tid_t tid,
418 uint32_t reg_num, // eRegisterKindProcessPlugin register number
419 llvm::ArrayRef<uint8_t> data);
421 bool WriteAllRegisters(lldb::tid_t tid, llvm::ArrayRef<uint8_t> data);
423 bool SaveRegisterState(lldb::tid_t tid, uint32_t &save_id);
425 bool RestoreRegisterState(lldb::tid_t tid, uint32_t save_id);
427 bool SyncThreadState(lldb::tid_t tid);
429 const char *GetGDBServerProgramName();
431 uint32_t GetGDBServerProgramVersion();
433 bool AvoidGPackets(ProcessGDBRemote *process);
435 StructuredData::ObjectSP GetThreadsInfo();
437 bool GetThreadExtendedInfoSupported();
439 bool GetLoadedDynamicLibrariesInfosSupported();
441 bool GetSharedCacheInfoSupported();
443 bool GetModuleInfo(const FileSpec &module_file_spec,
444 const ArchSpec &arch_spec, ModuleSpec &module_spec);
446 llvm::Optional<std::vector<ModuleSpec>>
447 GetModulesInfo(llvm::ArrayRef<FileSpec> module_file_specs,
448 const llvm::Triple &triple);
450 bool ReadExtFeature(const lldb_private::ConstString object,
451 const lldb_private::ConstString annex, std::string &out,
452 lldb_private::Status &err);
454 void ServeSymbolLookups(lldb_private::Process *process);
456 // Sends QPassSignals packet to the server with given signals to ignore.
457 Status SendSignalsToIgnore(llvm::ArrayRef<int32_t> signals);
459 //------------------------------------------------------------------
460 /// Return the feature set supported by the gdb-remote server.
462 /// This method returns the remote side's response to the qSupported
463 /// packet. The response is the complete string payload returned
467 /// The string returned by the server to the qSupported query.
468 //------------------------------------------------------------------
469 const std::string &GetServerSupportedFeatures() const {
470 return m_qSupported_response;
473 //------------------------------------------------------------------
474 /// Return the array of async JSON packet types supported by the remote.
476 /// This method returns the remote side's array of supported JSON
477 /// packet types as a list of type names. Each of the results are
478 /// expected to have an Enable{type_name} command to enable and configure
479 /// the related feature. Each type_name for an enabled feature will
480 /// possibly send async-style packets that contain a payload of a
481 /// binhex-encoded JSON dictionary. The dictionary will have a
482 /// string field named 'type', that contains the type_name of the
483 /// supported packet type.
485 /// There is a Plugin category called structured-data plugins.
486 /// A plugin indicates whether it knows how to handle a type_name.
487 /// If so, it can be used to process the async JSON packet.
490 /// The string returned by the server to the qSupported query.
491 //------------------------------------------------------------------
492 lldb_private::StructuredData::Array *GetSupportedStructuredDataPlugins();
494 //------------------------------------------------------------------
495 /// Configure a StructuredData feature on the remote end.
497 /// @see \b Process::ConfigureStructuredData(...) for details.
498 //------------------------------------------------------------------
500 ConfigureRemoteStructuredData(const ConstString &type_name,
501 const StructuredData::ObjectSP &config_sp);
503 lldb::user_id_t SendStartTracePacket(const TraceOptions &options,
506 Status SendStopTracePacket(lldb::user_id_t uid, lldb::tid_t thread_id);
508 Status SendGetDataPacket(lldb::user_id_t uid, lldb::tid_t thread_id,
509 llvm::MutableArrayRef<uint8_t> &buffer,
512 Status SendGetMetaDataPacket(lldb::user_id_t uid, lldb::tid_t thread_id,
513 llvm::MutableArrayRef<uint8_t> &buffer,
516 Status SendGetTraceConfigPacket(lldb::user_id_t uid, TraceOptions &options);
519 LazyBool m_supports_not_sending_acks;
520 LazyBool m_supports_thread_suffix;
521 LazyBool m_supports_threads_in_stop_reply;
522 LazyBool m_supports_vCont_all;
523 LazyBool m_supports_vCont_any;
524 LazyBool m_supports_vCont_c;
525 LazyBool m_supports_vCont_C;
526 LazyBool m_supports_vCont_s;
527 LazyBool m_supports_vCont_S;
528 LazyBool m_qHostInfo_is_valid;
529 LazyBool m_curr_pid_is_valid;
530 LazyBool m_qProcessInfo_is_valid;
531 LazyBool m_qGDBServerVersion_is_valid;
532 LazyBool m_supports_alloc_dealloc_memory;
533 LazyBool m_supports_memory_region_info;
534 LazyBool m_supports_watchpoint_support_info;
535 LazyBool m_supports_detach_stay_stopped;
536 LazyBool m_watchpoints_trigger_after_instruction;
537 LazyBool m_attach_or_wait_reply;
538 LazyBool m_prepare_for_reg_writing_reply;
539 LazyBool m_supports_p;
540 LazyBool m_supports_x;
541 LazyBool m_avoid_g_packets;
542 LazyBool m_supports_QSaveRegisterState;
543 LazyBool m_supports_qXfer_auxv_read;
544 LazyBool m_supports_qXfer_libraries_read;
545 LazyBool m_supports_qXfer_libraries_svr4_read;
546 LazyBool m_supports_qXfer_features_read;
547 LazyBool m_supports_augmented_libraries_svr4_read;
548 LazyBool m_supports_jThreadExtendedInfo;
549 LazyBool m_supports_jLoadedDynamicLibrariesInfos;
550 LazyBool m_supports_jGetSharedCacheInfo;
551 LazyBool m_supports_QPassSignals;
552 LazyBool m_supports_error_string_reply;
554 bool m_supports_qProcessInfoPID : 1, m_supports_qfProcessInfo : 1,
555 m_supports_qUserName : 1, m_supports_qGroupName : 1,
556 m_supports_qThreadStopInfo : 1, m_supports_z0 : 1, m_supports_z1 : 1,
557 m_supports_z2 : 1, m_supports_z3 : 1, m_supports_z4 : 1,
558 m_supports_QEnvironment : 1, m_supports_QEnvironmentHexEncoded : 1,
559 m_supports_qSymbol : 1, m_qSymbol_requests_done : 1,
560 m_supports_qModuleInfo : 1, m_supports_jThreadsInfo : 1,
561 m_supports_jModulesInfo : 1;
563 lldb::pid_t m_curr_pid;
564 lldb::tid_t m_curr_tid; // Current gdb remote protocol thread index for all
566 lldb::tid_t m_curr_tid_run; // Current gdb remote protocol thread index for
567 // continue, step, etc
569 uint32_t m_num_supported_hardware_watchpoints;
571 ArchSpec m_host_arch;
572 ArchSpec m_process_arch;
573 uint32_t m_os_version_major;
574 uint32_t m_os_version_minor;
575 uint32_t m_os_version_update;
576 std::string m_os_build;
577 std::string m_os_kernel;
578 std::string m_hostname;
579 std::string m_gdb_server_name; // from reply to qGDBServerVersion, empty if
580 // qGDBServerVersion is not supported
581 uint32_t m_gdb_server_version; // from reply to qGDBServerVersion, zero if
582 // qGDBServerVersion is not supported
583 std::chrono::seconds m_default_packet_timeout;
584 uint64_t m_max_packet_size; // as returned by qSupported
585 std::string m_qSupported_response; // the complete response to qSupported
587 bool m_supported_async_json_packets_is_valid;
588 lldb_private::StructuredData::ObjectSP m_supported_async_json_packets_sp;
590 bool GetCurrentProcessInfo(bool allow_lazy_pid = true);
592 bool GetGDBServerVersion();
594 // Given the list of compression types that the remote debug stub can support,
595 // possibly enable compression if we find an encoding we can handle.
596 void MaybeEnableCompression(std::vector<std::string> supported_compressions);
598 bool DecodeProcessInfoResponse(StringExtractorGDBRemote &response,
599 ProcessInstanceInfo &process_info);
601 void OnRunPacketSent(bool first) override;
603 PacketResult SendThreadSpecificPacketAndWaitForResponse(
604 lldb::tid_t tid, StreamString &&payload,
605 StringExtractorGDBRemote &response, bool send_async);
607 Status SendGetTraceDataPacket(StreamGDBRemote &packet, lldb::user_id_t uid,
608 lldb::tid_t thread_id,
609 llvm::MutableArrayRef<uint8_t> &buffer,
613 DISALLOW_COPY_AND_ASSIGN(GDBRemoteCommunicationClient);
616 } // namespace process_gdb_remote
617 } // namespace lldb_private
619 #endif // liblldb_GDBRemoteCommunicationClient_h_