1 //===-- GDBRemoteCommunicationClient.h --------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #ifndef liblldb_GDBRemoteCommunicationClient_h_
10 #define liblldb_GDBRemoteCommunicationClient_h_
12 #include "GDBRemoteClientBase.h"
20 #include "lldb/Utility/ArchSpec.h"
21 #include "lldb/Utility/StreamGDBRemote.h"
22 #include "lldb/Utility/StructuredData.h"
24 #include "lldb/Host/windows/PosixApi.h"
27 #include "llvm/ADT/Optional.h"
28 #include "llvm/Support/VersionTuple.h"
30 namespace lldb_private {
31 namespace process_gdb_remote {
33 class GDBRemoteCommunicationClient : public GDBRemoteClientBase {
35 GDBRemoteCommunicationClient();
37 ~GDBRemoteCommunicationClient() override;
39 // After connecting, send the handshake to the server to make sure
40 // we are communicating with it.
41 bool HandshakeWithServer(Status *error_ptr);
43 // For packets which specify a range of output to be returned,
44 // return all of the output via a series of request packets of the form
46 // <prefix><size>,<size>
47 // <prefix><size>*2,<size>
48 // <prefix><size>*3,<size>
50 // until a "$l..." packet is received, indicating the end.
51 // (size is in hex; this format is used by a standard gdbserver to
52 // return the given portion of the output specified by <prefix>;
53 // for example, "qXfer:libraries-svr4:read::fff,1000" means
54 // "return a chunk of the xml description file for shared
55 // library load addresses, where the chunk starts at offset 0xfff
56 // and continues for 0x1000 bytes").
57 // Concatenate the resulting server response packets together and
58 // return in response_string. If any packet fails, the return value
59 // indicates that failure and the returned string value is undefined.
61 SendPacketsAndConcatenateResponses(const char *send_payload_prefix,
62 std::string &response_string);
64 bool GetThreadSuffixSupported();
66 // This packet is usually sent first and the boolean return value
67 // indicates if the packet was send and any response was received
68 // even in the response is UNIMPLEMENTED. If the packet failed to
69 // get a response, then false is returned. This quickly tells us
70 // if we were able to connect and communicate with the remote GDB
72 bool QueryNoAckModeSupported();
74 void GetListThreadsInStopReplySupported();
76 lldb::pid_t GetCurrentProcessID(bool allow_lazy = true);
78 bool GetLaunchSuccess(std::string &error_str);
80 bool LaunchGDBServer(const char *remote_accept_hostname, lldb::pid_t &pid,
81 uint16_t &port, std::string &socket_name);
83 size_t QueryGDBServer(
84 std::vector<std::pair<uint16_t, std::string>> &connection_urls);
86 bool KillSpawnedProcess(lldb::pid_t pid);
88 /// Sends a GDB remote protocol 'A' packet that delivers program
89 /// arguments to the remote server.
92 /// A NULL terminated array of const C strings to use as the
96 /// Zero if the response was "OK", a positive value if the
97 /// the response was "Exx" where xx are two hex digits, or
98 /// -1 if the call is unsupported or any other unexpected
99 /// response was received.
100 int SendArgumentsPacket(const ProcessLaunchInfo &launch_info);
102 /// Sends a "QEnvironment:NAME=VALUE" packet that will build up the
103 /// environment that will get used when launching an application
104 /// in conjunction with the 'A' packet. This function can be called
105 /// multiple times in a row in order to pass on the desired
106 /// environment that the inferior should be launched with.
108 /// \param[in] name_equal_value
109 /// A NULL terminated C string that contains a single environment
110 /// in the format "NAME=VALUE".
113 /// Zero if the response was "OK", a positive value if the
114 /// the response was "Exx" where xx are two hex digits, or
115 /// -1 if the call is unsupported or any other unexpected
116 /// response was received.
117 int SendEnvironmentPacket(char const *name_equal_value);
118 int SendEnvironment(const Environment &env);
120 int SendLaunchArchPacket(const char *arch);
122 int SendLaunchEventDataPacket(const char *data,
123 bool *was_supported = nullptr);
125 /// Sends a "vAttach:PID" where PID is in hex.
128 /// A process ID for the remote gdb server to attach to.
130 /// \param[out] response
131 /// The response received from the gdb server. If the return
132 /// value is zero, \a response will contain a stop reply
136 /// Zero if the attach was successful, or an error indicating
138 int SendAttach(lldb::pid_t pid, StringExtractorGDBRemote &response);
140 /// Sends a GDB remote protocol 'I' packet that delivers stdin
141 /// data to the remote process.
144 /// A pointer to stdin data.
146 /// \param[in] data_len
147 /// The number of bytes available at \a data.
150 /// Zero if the attach was successful, or an error indicating
152 int SendStdinNotification(const char *data, size_t data_len);
154 /// Sets the path to use for stdin/out/err for a process
155 /// that will be launched with the 'A' packet.
158 /// The path to use for stdin/out/err
161 /// Zero if the for success, or an error code for failure.
162 int SetSTDIN(const FileSpec &file_spec);
163 int SetSTDOUT(const FileSpec &file_spec);
164 int SetSTDERR(const FileSpec &file_spec);
166 /// Sets the disable ASLR flag to \a enable for a process that will
167 /// be launched with the 'A' packet.
169 /// \param[in] enable
170 /// A boolean value indicating whether to disable ASLR or not.
173 /// Zero if the for success, or an error code for failure.
174 int SetDisableASLR(bool enable);
176 /// Sets the DetachOnError flag to \a enable for the process controlled by the
179 /// \param[in] enable
180 /// A boolean value indicating whether to detach on error or not.
183 /// Zero if the for success, or an error code for failure.
184 int SetDetachOnError(bool enable);
186 /// Sets the working directory to \a path for a process that will
187 /// be launched with the 'A' packet for non platform based
188 /// connections. If this packet is sent to a GDB server that
189 /// implements the platform, it will change the current working
190 /// directory for the platform process.
192 /// \param[in] working_dir
193 /// The path to a directory to use when launching our process
196 /// Zero if the for success, or an error code for failure.
197 int SetWorkingDir(const FileSpec &working_dir);
199 /// Gets the current working directory of a remote platform GDB
202 /// \param[out] working_dir
203 /// The current working directory on the remote platform.
206 /// Boolean for success
207 bool GetWorkingDir(FileSpec &working_dir);
209 lldb::addr_t AllocateMemory(size_t size, uint32_t permissions);
211 bool DeallocateMemory(lldb::addr_t addr);
213 Status Detach(bool keep_stopped);
215 Status GetMemoryRegionInfo(lldb::addr_t addr, MemoryRegionInfo &range_info);
217 Status GetWatchpointSupportInfo(uint32_t &num);
219 Status GetWatchpointSupportInfo(uint32_t &num, bool &after,
220 const ArchSpec &arch);
222 Status GetWatchpointsTriggerAfterInstruction(bool &after,
223 const ArchSpec &arch);
225 const ArchSpec &GetHostArchitecture();
227 std::chrono::seconds GetHostDefaultPacketTimeout();
229 const ArchSpec &GetProcessArchitecture();
231 void GetRemoteQSupported();
233 bool GetVContSupported(char flavor);
235 bool GetpPacketSupported(lldb::tid_t tid);
237 bool GetxPacketSupported();
239 bool GetVAttachOrWaitSupported();
241 bool GetSyncThreadStateSupported();
243 void ResetDiscoverableSettings(bool did_exec);
245 bool GetHostInfo(bool force = false);
247 bool GetDefaultThreadId(lldb::tid_t &tid);
249 llvm::VersionTuple GetOSVersion();
251 bool GetOSBuildString(std::string &s);
253 bool GetOSKernelDescription(std::string &s);
255 ArchSpec GetSystemArchitecture();
257 bool GetHostname(std::string &s);
259 lldb::addr_t GetShlibInfoAddr();
261 bool GetSupportsThreadSuffix();
263 bool GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &process_info);
265 uint32_t FindProcesses(const ProcessInstanceInfoMatch &process_match_info,
266 ProcessInstanceInfoList &process_infos);
268 bool GetUserName(uint32_t uid, std::string &name);
270 bool GetGroupName(uint32_t gid, std::string &name);
272 bool HasFullVContSupport() { return GetVContSupported('A'); }
274 bool HasAnyVContSupport() { return GetVContSupported('a'); }
276 bool GetStopReply(StringExtractorGDBRemote &response);
278 bool GetThreadStopInfo(lldb::tid_t tid, StringExtractorGDBRemote &response);
280 bool SupportsGDBStoppointPacket(GDBStoppointType type) {
282 case eBreakpointSoftware:
283 return m_supports_z0;
284 case eBreakpointHardware:
285 return m_supports_z1;
286 case eWatchpointWrite:
287 return m_supports_z2;
288 case eWatchpointRead:
289 return m_supports_z3;
290 case eWatchpointReadWrite:
291 return m_supports_z4;
297 uint8_t SendGDBStoppointTypePacket(
298 GDBStoppointType type, // Type of breakpoint or watchpoint
299 bool insert, // Insert or remove?
300 lldb::addr_t addr, // Address of breakpoint or watchpoint
301 uint32_t length); // Byte Size of breakpoint or watchpoint
303 bool SetNonStopMode(const bool enable);
305 void TestPacketSpeed(const uint32_t num_packets, uint32_t max_send,
306 uint32_t max_recv, uint64_t recv_amount, bool json,
309 // This packet is for testing the speed of the interface only. Both
310 // the client and server need to support it, but this allows us to
311 // measure the packet speed without any other work being done on the
312 // other end and avoids any of that work affecting the packet send
313 // and response times.
314 bool SendSpeedTestPacket(uint32_t send_size, uint32_t recv_size);
316 bool SetCurrentThread(uint64_t tid);
318 bool SetCurrentThreadForRun(uint64_t tid);
320 bool GetQXferAuxvReadSupported();
322 void EnableErrorStringInPacket();
324 bool GetQXferLibrariesReadSupported();
326 bool GetQXferLibrariesSVR4ReadSupported();
328 uint64_t GetRemoteMaxPacketSize();
330 bool GetEchoSupported();
332 bool GetQPassSignalsSupported();
334 bool GetAugmentedLibrariesSVR4ReadSupported();
336 bool GetQXferFeaturesReadSupported();
338 bool GetQXferMemoryMapReadSupported();
340 LazyBool SupportsAllocDeallocMemory() // const
342 // Uncomment this to have lldb pretend the debug server doesn't respond to
343 // alloc/dealloc memory packets.
344 // m_supports_alloc_dealloc_memory = lldb_private::eLazyBoolNo;
345 return m_supports_alloc_dealloc_memory;
348 size_t GetCurrentThreadIDs(std::vector<lldb::tid_t> &thread_ids,
349 bool &sequence_mutex_unavailable);
351 lldb::user_id_t OpenFile(const FileSpec &file_spec, uint32_t flags,
352 mode_t mode, Status &error);
354 bool CloseFile(lldb::user_id_t fd, Status &error);
356 lldb::user_id_t GetFileSize(const FileSpec &file_spec);
358 Status GetFilePermissions(const FileSpec &file_spec,
359 uint32_t &file_permissions);
361 Status SetFilePermissions(const FileSpec &file_spec,
362 uint32_t file_permissions);
364 uint64_t ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst,
365 uint64_t dst_len, Status &error);
367 uint64_t WriteFile(lldb::user_id_t fd, uint64_t offset, const void *src,
368 uint64_t src_len, Status &error);
370 Status CreateSymlink(const FileSpec &src, const FileSpec &dst);
372 Status Unlink(const FileSpec &file_spec);
374 Status MakeDirectory(const FileSpec &file_spec, uint32_t mode);
376 bool GetFileExists(const FileSpec &file_spec);
378 Status RunShellCommand(
379 const char *command, // Shouldn't be nullptr
380 const FileSpec &working_dir, // Pass empty FileSpec to use the current
382 int *status_ptr, // Pass nullptr if you don't want the process exit status
383 int *signo_ptr, // Pass nullptr if you don't want the signal that caused
384 // the process to exit
386 *command_output, // Pass nullptr if you don't want the command output
387 const Timeout<std::micro> &timeout);
389 bool CalculateMD5(const FileSpec &file_spec, uint64_t &high, uint64_t &low);
391 lldb::DataBufferSP ReadRegister(
394 reg_num); // Must be the eRegisterKindProcessPlugin register number
396 lldb::DataBufferSP ReadAllRegisters(lldb::tid_t tid);
399 WriteRegister(lldb::tid_t tid,
400 uint32_t reg_num, // eRegisterKindProcessPlugin register number
401 llvm::ArrayRef<uint8_t> data);
403 bool WriteAllRegisters(lldb::tid_t tid, llvm::ArrayRef<uint8_t> data);
405 bool SaveRegisterState(lldb::tid_t tid, uint32_t &save_id);
407 bool RestoreRegisterState(lldb::tid_t tid, uint32_t save_id);
409 bool SyncThreadState(lldb::tid_t tid);
411 const char *GetGDBServerProgramName();
413 uint32_t GetGDBServerProgramVersion();
415 bool AvoidGPackets(ProcessGDBRemote *process);
417 StructuredData::ObjectSP GetThreadsInfo();
419 bool GetThreadExtendedInfoSupported();
421 bool GetLoadedDynamicLibrariesInfosSupported();
423 bool GetSharedCacheInfoSupported();
425 bool GetModuleInfo(const FileSpec &module_file_spec,
426 const ArchSpec &arch_spec, ModuleSpec &module_spec);
428 llvm::Optional<std::vector<ModuleSpec>>
429 GetModulesInfo(llvm::ArrayRef<FileSpec> module_file_specs,
430 const llvm::Triple &triple);
432 bool ReadExtFeature(const lldb_private::ConstString object,
433 const lldb_private::ConstString annex, std::string &out,
434 lldb_private::Status &err);
436 void ServeSymbolLookups(lldb_private::Process *process);
438 // Sends QPassSignals packet to the server with given signals to ignore.
439 Status SendSignalsToIgnore(llvm::ArrayRef<int32_t> signals);
441 /// Return the feature set supported by the gdb-remote server.
443 /// This method returns the remote side's response to the qSupported
444 /// packet. The response is the complete string payload returned
448 /// The string returned by the server to the qSupported query.
449 const std::string &GetServerSupportedFeatures() const {
450 return m_qSupported_response;
453 /// Return the array of async JSON packet types supported by the remote.
455 /// This method returns the remote side's array of supported JSON
456 /// packet types as a list of type names. Each of the results are
457 /// expected to have an Enable{type_name} command to enable and configure
458 /// the related feature. Each type_name for an enabled feature will
459 /// possibly send async-style packets that contain a payload of a
460 /// binhex-encoded JSON dictionary. The dictionary will have a
461 /// string field named 'type', that contains the type_name of the
462 /// supported packet type.
464 /// There is a Plugin category called structured-data plugins.
465 /// A plugin indicates whether it knows how to handle a type_name.
466 /// If so, it can be used to process the async JSON packet.
469 /// The string returned by the server to the qSupported query.
470 lldb_private::StructuredData::Array *GetSupportedStructuredDataPlugins();
472 /// Configure a StructuredData feature on the remote end.
474 /// \see \b Process::ConfigureStructuredData(...) for details.
476 ConfigureRemoteStructuredData(ConstString type_name,
477 const StructuredData::ObjectSP &config_sp);
479 lldb::user_id_t SendStartTracePacket(const TraceOptions &options,
482 Status SendStopTracePacket(lldb::user_id_t uid, lldb::tid_t thread_id);
484 Status SendGetDataPacket(lldb::user_id_t uid, lldb::tid_t thread_id,
485 llvm::MutableArrayRef<uint8_t> &buffer,
488 Status SendGetMetaDataPacket(lldb::user_id_t uid, lldb::tid_t thread_id,
489 llvm::MutableArrayRef<uint8_t> &buffer,
492 Status SendGetTraceConfigPacket(lldb::user_id_t uid, TraceOptions &options);
495 LazyBool m_supports_not_sending_acks;
496 LazyBool m_supports_thread_suffix;
497 LazyBool m_supports_threads_in_stop_reply;
498 LazyBool m_supports_vCont_all;
499 LazyBool m_supports_vCont_any;
500 LazyBool m_supports_vCont_c;
501 LazyBool m_supports_vCont_C;
502 LazyBool m_supports_vCont_s;
503 LazyBool m_supports_vCont_S;
504 LazyBool m_qHostInfo_is_valid;
505 LazyBool m_curr_pid_is_valid;
506 LazyBool m_qProcessInfo_is_valid;
507 LazyBool m_qGDBServerVersion_is_valid;
508 LazyBool m_supports_alloc_dealloc_memory;
509 LazyBool m_supports_memory_region_info;
510 LazyBool m_supports_watchpoint_support_info;
511 LazyBool m_supports_detach_stay_stopped;
512 LazyBool m_watchpoints_trigger_after_instruction;
513 LazyBool m_attach_or_wait_reply;
514 LazyBool m_prepare_for_reg_writing_reply;
515 LazyBool m_supports_p;
516 LazyBool m_supports_x;
517 LazyBool m_avoid_g_packets;
518 LazyBool m_supports_QSaveRegisterState;
519 LazyBool m_supports_qXfer_auxv_read;
520 LazyBool m_supports_qXfer_libraries_read;
521 LazyBool m_supports_qXfer_libraries_svr4_read;
522 LazyBool m_supports_qXfer_features_read;
523 LazyBool m_supports_qXfer_memory_map_read;
524 LazyBool m_supports_augmented_libraries_svr4_read;
525 LazyBool m_supports_jThreadExtendedInfo;
526 LazyBool m_supports_jLoadedDynamicLibrariesInfos;
527 LazyBool m_supports_jGetSharedCacheInfo;
528 LazyBool m_supports_QPassSignals;
529 LazyBool m_supports_error_string_reply;
531 bool m_supports_qProcessInfoPID : 1, m_supports_qfProcessInfo : 1,
532 m_supports_qUserName : 1, m_supports_qGroupName : 1,
533 m_supports_qThreadStopInfo : 1, m_supports_z0 : 1, m_supports_z1 : 1,
534 m_supports_z2 : 1, m_supports_z3 : 1, m_supports_z4 : 1,
535 m_supports_QEnvironment : 1, m_supports_QEnvironmentHexEncoded : 1,
536 m_supports_qSymbol : 1, m_qSymbol_requests_done : 1,
537 m_supports_qModuleInfo : 1, m_supports_jThreadsInfo : 1,
538 m_supports_jModulesInfo : 1;
540 lldb::pid_t m_curr_pid;
541 lldb::tid_t m_curr_tid; // Current gdb remote protocol thread index for all
543 lldb::tid_t m_curr_tid_run; // Current gdb remote protocol thread index for
544 // continue, step, etc
546 uint32_t m_num_supported_hardware_watchpoints;
548 ArchSpec m_host_arch;
549 ArchSpec m_process_arch;
550 llvm::VersionTuple m_os_version;
551 std::string m_os_build;
552 std::string m_os_kernel;
553 std::string m_hostname;
554 std::string m_gdb_server_name; // from reply to qGDBServerVersion, empty if
555 // qGDBServerVersion is not supported
556 uint32_t m_gdb_server_version; // from reply to qGDBServerVersion, zero if
557 // qGDBServerVersion is not supported
558 std::chrono::seconds m_default_packet_timeout;
559 uint64_t m_max_packet_size; // as returned by qSupported
560 std::string m_qSupported_response; // the complete response to qSupported
562 bool m_supported_async_json_packets_is_valid;
563 lldb_private::StructuredData::ObjectSP m_supported_async_json_packets_sp;
565 std::vector<MemoryRegionInfo> m_qXfer_memory_map;
566 bool m_qXfer_memory_map_loaded;
568 bool GetCurrentProcessInfo(bool allow_lazy_pid = true);
570 bool GetGDBServerVersion();
572 // Given the list of compression types that the remote debug stub can support,
573 // possibly enable compression if we find an encoding we can handle.
574 void MaybeEnableCompression(std::vector<std::string> supported_compressions);
576 bool DecodeProcessInfoResponse(StringExtractorGDBRemote &response,
577 ProcessInstanceInfo &process_info);
579 void OnRunPacketSent(bool first) override;
581 PacketResult SendThreadSpecificPacketAndWaitForResponse(
582 lldb::tid_t tid, StreamString &&payload,
583 StringExtractorGDBRemote &response, bool send_async);
585 Status SendGetTraceDataPacket(StreamGDBRemote &packet, lldb::user_id_t uid,
586 lldb::tid_t thread_id,
587 llvm::MutableArrayRef<uint8_t> &buffer,
590 Status LoadQXferMemoryMap();
592 Status GetQXferMemoryMapRegionInfo(lldb::addr_t addr,
593 MemoryRegionInfo ®ion);
596 DISALLOW_COPY_AND_ASSIGN(GDBRemoteCommunicationClient);
599 } // namespace process_gdb_remote
600 } // namespace lldb_private
602 #endif // liblldb_GDBRemoteCommunicationClient_h_