1 //===-- GDBRemoteCommunicationClient.h --------------------------*- C++ -*-===// 2 // 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 6 // 7 //===----------------------------------------------------------------------===// 8 9 #ifndef liblldb_GDBRemoteCommunicationClient_h_ 10 #define liblldb_GDBRemoteCommunicationClient_h_ 11 12 #include "GDBRemoteClientBase.h" 13 14 #include <chrono> 15 #include <map> 16 #include <mutex> 17 #include <string> 18 #include <vector> 19 20 #include "lldb/Utility/ArchSpec.h" 21 #include "lldb/Utility/StreamGDBRemote.h" 22 #include "lldb/Utility/StructuredData.h" 23 #if defined(_WIN32) 24 #include "lldb/Host/windows/PosixApi.h" 25 #endif 26 27 #include "llvm/ADT/Optional.h" 28 #include "llvm/Support/VersionTuple.h" 29 30 namespace lldb_private { 31 namespace process_gdb_remote { 32 33 class GDBRemoteCommunicationClient : public GDBRemoteClientBase { 34 public: 35 GDBRemoteCommunicationClient(); 36 37 ~GDBRemoteCommunicationClient() override; 38 39 // After connecting, send the handshake to the server to make sure 40 // we are communicating with it. 41 bool HandshakeWithServer(Status *error_ptr); 42 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 45 // <prefix>0,<size> 46 // <prefix><size>,<size> 47 // <prefix><size>*2,<size> 48 // <prefix><size>*3,<size> 49 // ... 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. 60 PacketResult 61 SendPacketsAndConcatenateResponses(const char *send_payload_prefix, 62 std::string &response_string); 63 64 bool GetThreadSuffixSupported(); 65 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 71 // server 72 bool QueryNoAckModeSupported(); 73 74 void GetListThreadsInStopReplySupported(); 75 76 lldb::pid_t GetCurrentProcessID(bool allow_lazy = true); 77 78 bool GetLaunchSuccess(std::string &error_str); 79 80 bool LaunchGDBServer(const char *remote_accept_hostname, lldb::pid_t &pid, 81 uint16_t &port, std::string &socket_name); 82 83 size_t QueryGDBServer( 84 std::vector<std::pair<uint16_t, std::string>> &connection_urls); 85 86 bool KillSpawnedProcess(lldb::pid_t pid); 87 88 /// Sends a GDB remote protocol 'A' packet that delivers program 89 /// arguments to the remote server. 90 /// 91 /// \param[in] argv 92 /// A NULL terminated array of const C strings to use as the 93 /// arguments. 94 /// 95 /// \return 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); 101 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. 107 /// 108 /// \param[in] name_equal_value 109 /// A NULL terminated C string that contains a single environment 110 /// in the format "NAME=VALUE". 111 /// 112 /// \return 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); 119 120 int SendLaunchArchPacket(const char *arch); 121 122 int SendLaunchEventDataPacket(const char *data, 123 bool *was_supported = nullptr); 124 125 /// Sends a "vAttach:PID" where PID is in hex. 126 /// 127 /// \param[in] pid 128 /// A process ID for the remote gdb server to attach to. 129 /// 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 133 /// packet. 134 /// 135 /// \return 136 /// Zero if the attach was successful, or an error indicating 137 /// an error code. 138 int SendAttach(lldb::pid_t pid, StringExtractorGDBRemote &response); 139 140 /// Sends a GDB remote protocol 'I' packet that delivers stdin 141 /// data to the remote process. 142 /// 143 /// \param[in] data 144 /// A pointer to stdin data. 145 /// 146 /// \param[in] data_len 147 /// The number of bytes available at \a data. 148 /// 149 /// \return 150 /// Zero if the attach was successful, or an error indicating 151 /// an error code. 152 int SendStdinNotification(const char *data, size_t data_len); 153 154 /// Sets the path to use for stdin/out/err for a process 155 /// that will be launched with the 'A' packet. 156 /// 157 /// \param[in] path 158 /// The path to use for stdin/out/err 159 /// 160 /// \return 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); 165 166 /// Sets the disable ASLR flag to \a enable for a process that will 167 /// be launched with the 'A' packet. 168 /// 169 /// \param[in] enable 170 /// A boolean value indicating whether to disable ASLR or not. 171 /// 172 /// \return 173 /// Zero if the for success, or an error code for failure. 174 int SetDisableASLR(bool enable); 175 176 /// Sets the DetachOnError flag to \a enable for the process controlled by the 177 /// stub. 178 /// 179 /// \param[in] enable 180 /// A boolean value indicating whether to detach on error or not. 181 /// 182 /// \return 183 /// Zero if the for success, or an error code for failure. 184 int SetDetachOnError(bool enable); 185 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. 191 /// 192 /// \param[in] working_dir 193 /// The path to a directory to use when launching our process 194 /// 195 /// \return 196 /// Zero if the for success, or an error code for failure. 197 int SetWorkingDir(const FileSpec &working_dir); 198 199 /// Gets the current working directory of a remote platform GDB 200 /// server. 201 /// 202 /// \param[out] working_dir 203 /// The current working directory on the remote platform. 204 /// 205 /// \return 206 /// Boolean for success 207 bool GetWorkingDir(FileSpec &working_dir); 208 209 lldb::addr_t AllocateMemory(size_t size, uint32_t permissions); 210 211 bool DeallocateMemory(lldb::addr_t addr); 212 213 Status Detach(bool keep_stopped); 214 215 Status GetMemoryRegionInfo(lldb::addr_t addr, MemoryRegionInfo &range_info); 216 217 Status GetWatchpointSupportInfo(uint32_t &num); 218 219 Status GetWatchpointSupportInfo(uint32_t &num, bool &after, 220 const ArchSpec &arch); 221 222 Status GetWatchpointsTriggerAfterInstruction(bool &after, 223 const ArchSpec &arch); 224 225 const ArchSpec &GetHostArchitecture(); 226 227 std::chrono::seconds GetHostDefaultPacketTimeout(); 228 229 const ArchSpec &GetProcessArchitecture(); 230 231 void GetRemoteQSupported(); 232 233 bool GetVContSupported(char flavor); 234 235 bool GetpPacketSupported(lldb::tid_t tid); 236 237 bool GetxPacketSupported(); 238 239 bool GetVAttachOrWaitSupported(); 240 241 bool GetSyncThreadStateSupported(); 242 243 void ResetDiscoverableSettings(bool did_exec); 244 245 bool GetHostInfo(bool force = false); 246 247 bool GetDefaultThreadId(lldb::tid_t &tid); 248 249 llvm::VersionTuple GetOSVersion(); 250 251 bool GetOSBuildString(std::string &s); 252 253 bool GetOSKernelDescription(std::string &s); 254 255 ArchSpec GetSystemArchitecture(); 256 257 bool GetHostname(std::string &s); 258 259 lldb::addr_t GetShlibInfoAddr(); 260 261 bool GetSupportsThreadSuffix(); 262 263 bool GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &process_info); 264 265 uint32_t FindProcesses(const ProcessInstanceInfoMatch &process_match_info, 266 ProcessInstanceInfoList &process_infos); 267 268 bool GetUserName(uint32_t uid, std::string &name); 269 270 bool GetGroupName(uint32_t gid, std::string &name); 271 272 bool HasFullVContSupport() { return GetVContSupported('A'); } 273 274 bool HasAnyVContSupport() { return GetVContSupported('a'); } 275 276 bool GetStopReply(StringExtractorGDBRemote &response); 277 278 bool GetThreadStopInfo(lldb::tid_t tid, StringExtractorGDBRemote &response); 279 280 bool SupportsGDBStoppointPacket(GDBStoppointType type) { 281 switch (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; 292 default: 293 return false; 294 } 295 } 296 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 302 303 bool SetNonStopMode(const bool enable); 304 305 void TestPacketSpeed(const uint32_t num_packets, uint32_t max_send, 306 uint32_t max_recv, uint64_t recv_amount, bool json, 307 Stream &strm); 308 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); 315 316 bool SetCurrentThread(uint64_t tid); 317 318 bool SetCurrentThreadForRun(uint64_t tid); 319 320 bool GetQXferAuxvReadSupported(); 321 322 void EnableErrorStringInPacket(); 323 324 bool GetQXferLibrariesReadSupported(); 325 326 bool GetQXferLibrariesSVR4ReadSupported(); 327 328 uint64_t GetRemoteMaxPacketSize(); 329 330 bool GetEchoSupported(); 331 332 bool GetQPassSignalsSupported(); 333 334 bool GetAugmentedLibrariesSVR4ReadSupported(); 335 336 bool GetQXferFeaturesReadSupported(); 337 338 bool GetQXferMemoryMapReadSupported(); 339 340 LazyBool SupportsAllocDeallocMemory() // const 341 { 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; 346 } 347 348 size_t GetCurrentThreadIDs(std::vector<lldb::tid_t> &thread_ids, 349 bool &sequence_mutex_unavailable); 350 351 lldb::user_id_t OpenFile(const FileSpec &file_spec, uint32_t flags, 352 mode_t mode, Status &error); 353 354 bool CloseFile(lldb::user_id_t fd, Status &error); 355 356 lldb::user_id_t GetFileSize(const FileSpec &file_spec); 357 358 Status GetFilePermissions(const FileSpec &file_spec, 359 uint32_t &file_permissions); 360 361 Status SetFilePermissions(const FileSpec &file_spec, 362 uint32_t file_permissions); 363 364 uint64_t ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst, 365 uint64_t dst_len, Status &error); 366 367 uint64_t WriteFile(lldb::user_id_t fd, uint64_t offset, const void *src, 368 uint64_t src_len, Status &error); 369 370 Status CreateSymlink(const FileSpec &src, const FileSpec &dst); 371 372 Status Unlink(const FileSpec &file_spec); 373 374 Status MakeDirectory(const FileSpec &file_spec, uint32_t mode); 375 376 bool GetFileExists(const FileSpec &file_spec); 377 378 Status RunShellCommand( 379 const char *command, // Shouldn't be nullptr 380 const FileSpec &working_dir, // Pass empty FileSpec to use the current 381 // working directory 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 385 std::string 386 *command_output, // Pass nullptr if you don't want the command output 387 const Timeout<std::micro> &timeout); 388 389 bool CalculateMD5(const FileSpec &file_spec, uint64_t &high, uint64_t &low); 390 391 lldb::DataBufferSP ReadRegister( 392 lldb::tid_t tid, 393 uint32_t 394 reg_num); // Must be the eRegisterKindProcessPlugin register number 395 396 lldb::DataBufferSP ReadAllRegisters(lldb::tid_t tid); 397 398 bool 399 WriteRegister(lldb::tid_t tid, 400 uint32_t reg_num, // eRegisterKindProcessPlugin register number 401 llvm::ArrayRef<uint8_t> data); 402 403 bool WriteAllRegisters(lldb::tid_t tid, llvm::ArrayRef<uint8_t> data); 404 405 bool SaveRegisterState(lldb::tid_t tid, uint32_t &save_id); 406 407 bool RestoreRegisterState(lldb::tid_t tid, uint32_t save_id); 408 409 bool SyncThreadState(lldb::tid_t tid); 410 411 const char *GetGDBServerProgramName(); 412 413 uint32_t GetGDBServerProgramVersion(); 414 415 bool AvoidGPackets(ProcessGDBRemote *process); 416 417 StructuredData::ObjectSP GetThreadsInfo(); 418 419 bool GetThreadExtendedInfoSupported(); 420 421 bool GetLoadedDynamicLibrariesInfosSupported(); 422 423 bool GetSharedCacheInfoSupported(); 424 425 bool GetModuleInfo(const FileSpec &module_file_spec, 426 const ArchSpec &arch_spec, ModuleSpec &module_spec); 427 428 llvm::Optional<std::vector<ModuleSpec>> 429 GetModulesInfo(llvm::ArrayRef<FileSpec> module_file_specs, 430 const llvm::Triple &triple); 431 432 bool ReadExtFeature(const lldb_private::ConstString object, 433 const lldb_private::ConstString annex, std::string &out, 434 lldb_private::Status &err); 435 436 void ServeSymbolLookups(lldb_private::Process *process); 437 438 // Sends QPassSignals packet to the server with given signals to ignore. 439 Status SendSignalsToIgnore(llvm::ArrayRef<int32_t> signals); 440 441 /// Return the feature set supported by the gdb-remote server. 442 /// 443 /// This method returns the remote side's response to the qSupported 444 /// packet. The response is the complete string payload returned 445 /// to the client. 446 /// 447 /// \return 448 /// The string returned by the server to the qSupported query. 449 const std::string &GetServerSupportedFeatures() const { 450 return m_qSupported_response; 451 } 452 453 /// Return the array of async JSON packet types supported by the remote. 454 /// 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. 463 /// 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. 467 /// 468 /// \return 469 /// The string returned by the server to the qSupported query. 470 lldb_private::StructuredData::Array *GetSupportedStructuredDataPlugins(); 471 472 /// Configure a StructuredData feature on the remote end. 473 /// 474 /// \see \b Process::ConfigureStructuredData(...) for details. 475 Status 476 ConfigureRemoteStructuredData(ConstString type_name, 477 const StructuredData::ObjectSP &config_sp); 478 479 lldb::user_id_t SendStartTracePacket(const TraceOptions &options, 480 Status &error); 481 482 Status SendStopTracePacket(lldb::user_id_t uid, lldb::tid_t thread_id); 483 484 Status SendGetDataPacket(lldb::user_id_t uid, lldb::tid_t thread_id, 485 llvm::MutableArrayRef<uint8_t> &buffer, 486 size_t offset = 0); 487 488 Status SendGetMetaDataPacket(lldb::user_id_t uid, lldb::tid_t thread_id, 489 llvm::MutableArrayRef<uint8_t> &buffer, 490 size_t offset = 0); 491 492 Status SendGetTraceConfigPacket(lldb::user_id_t uid, TraceOptions &options); 493 494 protected: 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; 530 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; 539 540 lldb::pid_t m_curr_pid; 541 lldb::tid_t m_curr_tid; // Current gdb remote protocol thread index for all 542 // other operations 543 lldb::tid_t m_curr_tid_run; // Current gdb remote protocol thread index for 544 // continue, step, etc 545 546 uint32_t m_num_supported_hardware_watchpoints; 547 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 561 562 bool m_supported_async_json_packets_is_valid; 563 lldb_private::StructuredData::ObjectSP m_supported_async_json_packets_sp; 564 565 std::vector<MemoryRegionInfo> m_qXfer_memory_map; 566 bool m_qXfer_memory_map_loaded; 567 568 bool GetCurrentProcessInfo(bool allow_lazy_pid = true); 569 570 bool GetGDBServerVersion(); 571 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); 575 576 bool DecodeProcessInfoResponse(StringExtractorGDBRemote &response, 577 ProcessInstanceInfo &process_info); 578 579 void OnRunPacketSent(bool first) override; 580 581 PacketResult SendThreadSpecificPacketAndWaitForResponse( 582 lldb::tid_t tid, StreamString &&payload, 583 StringExtractorGDBRemote &response, bool send_async); 584 585 Status SendGetTraceDataPacket(StreamGDBRemote &packet, lldb::user_id_t uid, 586 lldb::tid_t thread_id, 587 llvm::MutableArrayRef<uint8_t> &buffer, 588 size_t offset); 589 590 Status LoadQXferMemoryMap(); 591 592 Status GetQXferMemoryMapRegionInfo(lldb::addr_t addr, 593 MemoryRegionInfo ®ion); 594 595 private: 596 DISALLOW_COPY_AND_ASSIGN(GDBRemoteCommunicationClient); 597 }; 598 599 } // namespace process_gdb_remote 600 } // namespace lldb_private 601 602 #endif // liblldb_GDBRemoteCommunicationClient_h_ 603