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