1 //===-- GDBRemoteCommunicationClient.cpp ------------------------*- 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 #include "GDBRemoteCommunicationClient.h" 11 12 // C Includes 13 #include <math.h> 14 #include <sys/stat.h> 15 16 // C++ Includes 17 #include <numeric> 18 #include <sstream> 19 20 // Other libraries and framework includes 21 #include "lldb/Core/ModuleSpec.h" 22 #include "lldb/Core/State.h" 23 #include "lldb/Host/HostInfo.h" 24 #include "lldb/Host/XML.h" 25 #include "lldb/Symbol/Symbol.h" 26 #include "lldb/Target/MemoryRegionInfo.h" 27 #include "lldb/Target/Target.h" 28 #include "lldb/Target/UnixSignals.h" 29 #include "lldb/Utility/Args.h" 30 #include "lldb/Utility/DataBufferHeap.h" 31 #include "lldb/Utility/JSON.h" 32 #include "lldb/Utility/LLDBAssert.h" 33 #include "lldb/Utility/Log.h" 34 #include "lldb/Utility/StreamString.h" 35 36 // Project includes 37 #include "ProcessGDBRemote.h" 38 #include "ProcessGDBRemoteLog.h" 39 #include "lldb/Host/Config.h" 40 #include "lldb/Utility/StringExtractorGDBRemote.h" 41 42 #include "llvm/ADT/StringSwitch.h" 43 44 #if defined(HAVE_LIBCOMPRESSION) 45 #include <compression.h> 46 #endif 47 48 using namespace lldb; 49 using namespace lldb_private; 50 using namespace lldb_private::process_gdb_remote; 51 using namespace std::chrono; 52 53 //---------------------------------------------------------------------- 54 // GDBRemoteCommunicationClient constructor 55 //---------------------------------------------------------------------- 56 GDBRemoteCommunicationClient::GDBRemoteCommunicationClient() 57 : GDBRemoteClientBase("gdb-remote.client", "gdb-remote.client.rx_packet"), 58 m_supports_not_sending_acks(eLazyBoolCalculate), 59 m_supports_thread_suffix(eLazyBoolCalculate), 60 m_supports_threads_in_stop_reply(eLazyBoolCalculate), 61 m_supports_vCont_all(eLazyBoolCalculate), 62 m_supports_vCont_any(eLazyBoolCalculate), 63 m_supports_vCont_c(eLazyBoolCalculate), 64 m_supports_vCont_C(eLazyBoolCalculate), 65 m_supports_vCont_s(eLazyBoolCalculate), 66 m_supports_vCont_S(eLazyBoolCalculate), 67 m_qHostInfo_is_valid(eLazyBoolCalculate), 68 m_curr_pid_is_valid(eLazyBoolCalculate), 69 m_qProcessInfo_is_valid(eLazyBoolCalculate), 70 m_qGDBServerVersion_is_valid(eLazyBoolCalculate), 71 m_supports_alloc_dealloc_memory(eLazyBoolCalculate), 72 m_supports_memory_region_info(eLazyBoolCalculate), 73 m_supports_watchpoint_support_info(eLazyBoolCalculate), 74 m_supports_detach_stay_stopped(eLazyBoolCalculate), 75 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate), 76 m_attach_or_wait_reply(eLazyBoolCalculate), 77 m_prepare_for_reg_writing_reply(eLazyBoolCalculate), 78 m_supports_p(eLazyBoolCalculate), m_supports_x(eLazyBoolCalculate), 79 m_avoid_g_packets(eLazyBoolCalculate), 80 m_supports_QSaveRegisterState(eLazyBoolCalculate), 81 m_supports_qXfer_auxv_read(eLazyBoolCalculate), 82 m_supports_qXfer_libraries_read(eLazyBoolCalculate), 83 m_supports_qXfer_libraries_svr4_read(eLazyBoolCalculate), 84 m_supports_qXfer_features_read(eLazyBoolCalculate), 85 m_supports_qXfer_memory_map_read(eLazyBoolCalculate), 86 m_supports_augmented_libraries_svr4_read(eLazyBoolCalculate), 87 m_supports_jThreadExtendedInfo(eLazyBoolCalculate), 88 m_supports_jLoadedDynamicLibrariesInfos(eLazyBoolCalculate), 89 m_supports_jGetSharedCacheInfo(eLazyBoolCalculate), 90 m_supports_QPassSignals(eLazyBoolCalculate), 91 m_supports_error_string_reply(eLazyBoolCalculate), 92 m_supports_qProcessInfoPID(true), m_supports_qfProcessInfo(true), 93 m_supports_qUserName(true), m_supports_qGroupName(true), 94 m_supports_qThreadStopInfo(true), m_supports_z0(true), 95 m_supports_z1(true), m_supports_z2(true), m_supports_z3(true), 96 m_supports_z4(true), m_supports_QEnvironment(true), 97 m_supports_QEnvironmentHexEncoded(true), m_supports_qSymbol(true), 98 m_qSymbol_requests_done(false), m_supports_qModuleInfo(true), 99 m_supports_jThreadsInfo(true), m_supports_jModulesInfo(true), 100 m_curr_pid(LLDB_INVALID_PROCESS_ID), m_curr_tid(LLDB_INVALID_THREAD_ID), 101 m_curr_tid_run(LLDB_INVALID_THREAD_ID), 102 m_num_supported_hardware_watchpoints(0), m_host_arch(), m_process_arch(), 103 m_os_version_major(UINT32_MAX), m_os_version_minor(UINT32_MAX), 104 m_os_version_update(UINT32_MAX), m_os_build(), m_os_kernel(), 105 m_hostname(), m_gdb_server_name(), m_gdb_server_version(UINT32_MAX), 106 m_default_packet_timeout(0), m_max_packet_size(0), 107 m_qSupported_response(), m_supported_async_json_packets_is_valid(false), 108 m_supported_async_json_packets_sp(), m_qXfer_memory_map(), 109 m_qXfer_memory_map_loaded(false) {} 110 111 //---------------------------------------------------------------------- 112 // Destructor 113 //---------------------------------------------------------------------- 114 GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient() { 115 if (IsConnected()) 116 Disconnect(); 117 } 118 119 bool GDBRemoteCommunicationClient::HandshakeWithServer(Status *error_ptr) { 120 ResetDiscoverableSettings(false); 121 122 // Start the read thread after we send the handshake ack since if we fail to 123 // send the handshake ack, there is no reason to continue... 124 if (SendAck()) { 125 // Wait for any responses that might have been queued up in the remote 126 // GDB server and flush them all 127 StringExtractorGDBRemote response; 128 PacketResult packet_result = PacketResult::Success; 129 while (packet_result == PacketResult::Success) 130 packet_result = ReadPacket(response, milliseconds(10), false); 131 132 // The return value from QueryNoAckModeSupported() is true if the packet 133 // was sent and _any_ response (including UNIMPLEMENTED) was received), or 134 // false if no response was received. This quickly tells us if we have a 135 // live connection to a remote GDB server... 136 if (QueryNoAckModeSupported()) { 137 return true; 138 } else { 139 if (error_ptr) 140 error_ptr->SetErrorString("failed to get reply to handshake packet"); 141 } 142 } else { 143 if (error_ptr) 144 error_ptr->SetErrorString("failed to send the handshake ack"); 145 } 146 return false; 147 } 148 149 bool GDBRemoteCommunicationClient::GetEchoSupported() { 150 if (m_supports_qEcho == eLazyBoolCalculate) { 151 GetRemoteQSupported(); 152 } 153 return m_supports_qEcho == eLazyBoolYes; 154 } 155 156 bool GDBRemoteCommunicationClient::GetQPassSignalsSupported() { 157 if (m_supports_QPassSignals == eLazyBoolCalculate) { 158 GetRemoteQSupported(); 159 } 160 return m_supports_QPassSignals == eLazyBoolYes; 161 } 162 163 bool GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported() { 164 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate) { 165 GetRemoteQSupported(); 166 } 167 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes; 168 } 169 170 bool GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported() { 171 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate) { 172 GetRemoteQSupported(); 173 } 174 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes; 175 } 176 177 bool GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported() { 178 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate) { 179 GetRemoteQSupported(); 180 } 181 return m_supports_qXfer_libraries_read == eLazyBoolYes; 182 } 183 184 bool GDBRemoteCommunicationClient::GetQXferAuxvReadSupported() { 185 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate) { 186 GetRemoteQSupported(); 187 } 188 return m_supports_qXfer_auxv_read == eLazyBoolYes; 189 } 190 191 bool GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported() { 192 if (m_supports_qXfer_features_read == eLazyBoolCalculate) { 193 GetRemoteQSupported(); 194 } 195 return m_supports_qXfer_features_read == eLazyBoolYes; 196 } 197 198 bool GDBRemoteCommunicationClient::GetQXferMemoryMapReadSupported() { 199 if (m_supports_qXfer_memory_map_read == eLazyBoolCalculate) { 200 GetRemoteQSupported(); 201 } 202 return m_supports_qXfer_memory_map_read == eLazyBoolYes; 203 } 204 205 uint64_t GDBRemoteCommunicationClient::GetRemoteMaxPacketSize() { 206 if (m_max_packet_size == 0) { 207 GetRemoteQSupported(); 208 } 209 return m_max_packet_size; 210 } 211 212 bool GDBRemoteCommunicationClient::QueryNoAckModeSupported() { 213 if (m_supports_not_sending_acks == eLazyBoolCalculate) { 214 m_send_acks = true; 215 m_supports_not_sending_acks = eLazyBoolNo; 216 217 // This is the first real packet that we'll send in a debug session and it 218 // may take a little longer than normal to receive a reply. Wait at least 219 // 6 seconds for a reply to this packet. 220 221 ScopedTimeout timeout(*this, std::max(GetPacketTimeout(), seconds(6))); 222 223 StringExtractorGDBRemote response; 224 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) == 225 PacketResult::Success) { 226 if (response.IsOKResponse()) { 227 m_send_acks = false; 228 m_supports_not_sending_acks = eLazyBoolYes; 229 } 230 return true; 231 } 232 } 233 return false; 234 } 235 236 void GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported() { 237 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate) { 238 m_supports_threads_in_stop_reply = eLazyBoolNo; 239 240 StringExtractorGDBRemote response; 241 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, 242 false) == PacketResult::Success) { 243 if (response.IsOKResponse()) 244 m_supports_threads_in_stop_reply = eLazyBoolYes; 245 } 246 } 247 } 248 249 bool GDBRemoteCommunicationClient::GetVAttachOrWaitSupported() { 250 if (m_attach_or_wait_reply == eLazyBoolCalculate) { 251 m_attach_or_wait_reply = eLazyBoolNo; 252 253 StringExtractorGDBRemote response; 254 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, 255 false) == PacketResult::Success) { 256 if (response.IsOKResponse()) 257 m_attach_or_wait_reply = eLazyBoolYes; 258 } 259 } 260 if (m_attach_or_wait_reply == eLazyBoolYes) 261 return true; 262 else 263 return false; 264 } 265 266 bool GDBRemoteCommunicationClient::GetSyncThreadStateSupported() { 267 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate) { 268 m_prepare_for_reg_writing_reply = eLazyBoolNo; 269 270 StringExtractorGDBRemote response; 271 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, 272 false) == PacketResult::Success) { 273 if (response.IsOKResponse()) 274 m_prepare_for_reg_writing_reply = eLazyBoolYes; 275 } 276 } 277 if (m_prepare_for_reg_writing_reply == eLazyBoolYes) 278 return true; 279 else 280 return false; 281 } 282 283 void GDBRemoteCommunicationClient::ResetDiscoverableSettings(bool did_exec) { 284 if (did_exec == false) { 285 // Hard reset everything, this is when we first connect to a GDB server 286 m_supports_not_sending_acks = eLazyBoolCalculate; 287 m_supports_thread_suffix = eLazyBoolCalculate; 288 m_supports_threads_in_stop_reply = eLazyBoolCalculate; 289 m_supports_vCont_c = eLazyBoolCalculate; 290 m_supports_vCont_C = eLazyBoolCalculate; 291 m_supports_vCont_s = eLazyBoolCalculate; 292 m_supports_vCont_S = eLazyBoolCalculate; 293 m_supports_p = eLazyBoolCalculate; 294 m_supports_x = eLazyBoolCalculate; 295 m_supports_QSaveRegisterState = eLazyBoolCalculate; 296 m_qHostInfo_is_valid = eLazyBoolCalculate; 297 m_curr_pid_is_valid = eLazyBoolCalculate; 298 m_qGDBServerVersion_is_valid = eLazyBoolCalculate; 299 m_supports_alloc_dealloc_memory = eLazyBoolCalculate; 300 m_supports_memory_region_info = eLazyBoolCalculate; 301 m_prepare_for_reg_writing_reply = eLazyBoolCalculate; 302 m_attach_or_wait_reply = eLazyBoolCalculate; 303 m_avoid_g_packets = eLazyBoolCalculate; 304 m_supports_qXfer_auxv_read = eLazyBoolCalculate; 305 m_supports_qXfer_libraries_read = eLazyBoolCalculate; 306 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate; 307 m_supports_qXfer_features_read = eLazyBoolCalculate; 308 m_supports_qXfer_memory_map_read = eLazyBoolCalculate; 309 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate; 310 m_supports_qProcessInfoPID = true; 311 m_supports_qfProcessInfo = true; 312 m_supports_qUserName = true; 313 m_supports_qGroupName = true; 314 m_supports_qThreadStopInfo = true; 315 m_supports_z0 = true; 316 m_supports_z1 = true; 317 m_supports_z2 = true; 318 m_supports_z3 = true; 319 m_supports_z4 = true; 320 m_supports_QEnvironment = true; 321 m_supports_QEnvironmentHexEncoded = true; 322 m_supports_qSymbol = true; 323 m_qSymbol_requests_done = false; 324 m_supports_qModuleInfo = true; 325 m_host_arch.Clear(); 326 m_os_version_major = UINT32_MAX; 327 m_os_version_minor = UINT32_MAX; 328 m_os_version_update = UINT32_MAX; 329 m_os_build.clear(); 330 m_os_kernel.clear(); 331 m_hostname.clear(); 332 m_gdb_server_name.clear(); 333 m_gdb_server_version = UINT32_MAX; 334 m_default_packet_timeout = seconds(0); 335 m_max_packet_size = 0; 336 m_qSupported_response.clear(); 337 m_supported_async_json_packets_is_valid = false; 338 m_supported_async_json_packets_sp.reset(); 339 m_supports_jModulesInfo = true; 340 } 341 342 // These flags should be reset when we first connect to a GDB server and when 343 // our inferior process execs 344 m_qProcessInfo_is_valid = eLazyBoolCalculate; 345 m_process_arch.Clear(); 346 } 347 348 void GDBRemoteCommunicationClient::GetRemoteQSupported() { 349 // Clear out any capabilities we expect to see in the qSupported response 350 m_supports_qXfer_auxv_read = eLazyBoolNo; 351 m_supports_qXfer_libraries_read = eLazyBoolNo; 352 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo; 353 m_supports_augmented_libraries_svr4_read = eLazyBoolNo; 354 m_supports_qXfer_features_read = eLazyBoolNo; 355 m_supports_qXfer_memory_map_read = eLazyBoolNo; 356 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if 357 // not, we assume no limit 358 359 // build the qSupported packet 360 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"}; 361 StreamString packet; 362 packet.PutCString("qSupported"); 363 for (uint32_t i = 0; i < features.size(); ++i) { 364 packet.PutCString(i == 0 ? ":" : ";"); 365 packet.PutCString(features[i]); 366 } 367 368 StringExtractorGDBRemote response; 369 if (SendPacketAndWaitForResponse(packet.GetString(), response, 370 /*send_async=*/false) == 371 PacketResult::Success) { 372 const char *response_cstr = response.GetStringRef().c_str(); 373 374 // Hang on to the qSupported packet, so that platforms can do custom 375 // configuration of the transport before attaching/launching the process. 376 m_qSupported_response = response_cstr; 377 378 if (::strstr(response_cstr, "qXfer:auxv:read+")) 379 m_supports_qXfer_auxv_read = eLazyBoolYes; 380 if (::strstr(response_cstr, "qXfer:libraries-svr4:read+")) 381 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; 382 if (::strstr(response_cstr, "augmented-libraries-svr4-read")) { 383 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied 384 m_supports_augmented_libraries_svr4_read = eLazyBoolYes; 385 } 386 if (::strstr(response_cstr, "qXfer:libraries:read+")) 387 m_supports_qXfer_libraries_read = eLazyBoolYes; 388 if (::strstr(response_cstr, "qXfer:features:read+")) 389 m_supports_qXfer_features_read = eLazyBoolYes; 390 if (::strstr(response_cstr, "qXfer:memory-map:read+")) 391 m_supports_qXfer_memory_map_read = eLazyBoolYes; 392 393 // Look for a list of compressions in the features list e.g. 394 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib- 395 // deflate,lzma 396 const char *features_list = ::strstr(response_cstr, "qXfer:features:"); 397 if (features_list) { 398 const char *compressions = 399 ::strstr(features_list, "SupportedCompressions="); 400 if (compressions) { 401 std::vector<std::string> supported_compressions; 402 compressions += sizeof("SupportedCompressions=") - 1; 403 const char *end_of_compressions = strchr(compressions, ';'); 404 if (end_of_compressions == NULL) { 405 end_of_compressions = strchr(compressions, '\0'); 406 } 407 const char *current_compression = compressions; 408 while (current_compression < end_of_compressions) { 409 const char *next_compression_name = strchr(current_compression, ','); 410 const char *end_of_this_word = next_compression_name; 411 if (next_compression_name == NULL || 412 end_of_compressions < next_compression_name) { 413 end_of_this_word = end_of_compressions; 414 } 415 416 if (end_of_this_word) { 417 if (end_of_this_word == current_compression) { 418 current_compression++; 419 } else { 420 std::string this_compression( 421 current_compression, end_of_this_word - current_compression); 422 supported_compressions.push_back(this_compression); 423 current_compression = end_of_this_word + 1; 424 } 425 } else { 426 supported_compressions.push_back(current_compression); 427 current_compression = end_of_compressions; 428 } 429 } 430 431 if (supported_compressions.size() > 0) { 432 MaybeEnableCompression(supported_compressions); 433 } 434 } 435 } 436 437 if (::strstr(response_cstr, "qEcho")) 438 m_supports_qEcho = eLazyBoolYes; 439 else 440 m_supports_qEcho = eLazyBoolNo; 441 442 if (::strstr(response_cstr, "QPassSignals+")) 443 m_supports_QPassSignals = eLazyBoolYes; 444 else 445 m_supports_QPassSignals = eLazyBoolNo; 446 447 const char *packet_size_str = ::strstr(response_cstr, "PacketSize="); 448 if (packet_size_str) { 449 StringExtractorGDBRemote packet_response(packet_size_str + 450 strlen("PacketSize=")); 451 m_max_packet_size = 452 packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX); 453 if (m_max_packet_size == 0) { 454 m_max_packet_size = UINT64_MAX; // Must have been a garbled response 455 Log *log( 456 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 457 if (log) 458 log->Printf("Garbled PacketSize spec in qSupported response"); 459 } 460 } 461 } 462 } 463 464 bool GDBRemoteCommunicationClient::GetThreadSuffixSupported() { 465 if (m_supports_thread_suffix == eLazyBoolCalculate) { 466 StringExtractorGDBRemote response; 467 m_supports_thread_suffix = eLazyBoolNo; 468 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, 469 false) == PacketResult::Success) { 470 if (response.IsOKResponse()) 471 m_supports_thread_suffix = eLazyBoolYes; 472 } 473 } 474 return m_supports_thread_suffix; 475 } 476 bool GDBRemoteCommunicationClient::GetVContSupported(char flavor) { 477 if (m_supports_vCont_c == eLazyBoolCalculate) { 478 StringExtractorGDBRemote response; 479 m_supports_vCont_any = eLazyBoolNo; 480 m_supports_vCont_all = eLazyBoolNo; 481 m_supports_vCont_c = eLazyBoolNo; 482 m_supports_vCont_C = eLazyBoolNo; 483 m_supports_vCont_s = eLazyBoolNo; 484 m_supports_vCont_S = eLazyBoolNo; 485 if (SendPacketAndWaitForResponse("vCont?", response, false) == 486 PacketResult::Success) { 487 const char *response_cstr = response.GetStringRef().c_str(); 488 if (::strstr(response_cstr, ";c")) 489 m_supports_vCont_c = eLazyBoolYes; 490 491 if (::strstr(response_cstr, ";C")) 492 m_supports_vCont_C = eLazyBoolYes; 493 494 if (::strstr(response_cstr, ";s")) 495 m_supports_vCont_s = eLazyBoolYes; 496 497 if (::strstr(response_cstr, ";S")) 498 m_supports_vCont_S = eLazyBoolYes; 499 500 if (m_supports_vCont_c == eLazyBoolYes && 501 m_supports_vCont_C == eLazyBoolYes && 502 m_supports_vCont_s == eLazyBoolYes && 503 m_supports_vCont_S == eLazyBoolYes) { 504 m_supports_vCont_all = eLazyBoolYes; 505 } 506 507 if (m_supports_vCont_c == eLazyBoolYes || 508 m_supports_vCont_C == eLazyBoolYes || 509 m_supports_vCont_s == eLazyBoolYes || 510 m_supports_vCont_S == eLazyBoolYes) { 511 m_supports_vCont_any = eLazyBoolYes; 512 } 513 } 514 } 515 516 switch (flavor) { 517 case 'a': 518 return m_supports_vCont_any; 519 case 'A': 520 return m_supports_vCont_all; 521 case 'c': 522 return m_supports_vCont_c; 523 case 'C': 524 return m_supports_vCont_C; 525 case 's': 526 return m_supports_vCont_s; 527 case 'S': 528 return m_supports_vCont_S; 529 default: 530 break; 531 } 532 return false; 533 } 534 535 GDBRemoteCommunication::PacketResult 536 GDBRemoteCommunicationClient::SendThreadSpecificPacketAndWaitForResponse( 537 lldb::tid_t tid, StreamString &&payload, StringExtractorGDBRemote &response, 538 bool send_async) { 539 Lock lock(*this, send_async); 540 if (!lock) { 541 if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet( 542 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) 543 log->Printf("GDBRemoteCommunicationClient::%s: Didn't get sequence mutex " 544 "for %s packet.", 545 __FUNCTION__, payload.GetData()); 546 return PacketResult::ErrorNoSequenceLock; 547 } 548 549 if (GetThreadSuffixSupported()) 550 payload.Printf(";thread:%4.4" PRIx64 ";", tid); 551 else { 552 if (!SetCurrentThread(tid)) 553 return PacketResult::ErrorSendFailed; 554 } 555 556 return SendPacketAndWaitForResponseNoLock(payload.GetString(), response); 557 } 558 559 // Check if the target supports 'p' packet. It sends out a 'p' packet and 560 // checks the response. A normal packet will tell us that support is available. 561 // 562 // Takes a valid thread ID because p needs to apply to a thread. 563 bool GDBRemoteCommunicationClient::GetpPacketSupported(lldb::tid_t tid) { 564 if (m_supports_p == eLazyBoolCalculate) { 565 m_supports_p = eLazyBoolNo; 566 StreamString payload; 567 payload.PutCString("p0"); 568 StringExtractorGDBRemote response; 569 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), 570 response, false) == 571 PacketResult::Success && 572 response.IsNormalResponse()) { 573 m_supports_p = eLazyBoolYes; 574 } 575 } 576 return m_supports_p; 577 } 578 579 StructuredData::ObjectSP GDBRemoteCommunicationClient::GetThreadsInfo() { 580 // Get information on all threads at one using the "jThreadsInfo" packet 581 StructuredData::ObjectSP object_sp; 582 583 if (m_supports_jThreadsInfo) { 584 StringExtractorGDBRemote response; 585 response.SetResponseValidatorToJSON(); 586 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) == 587 PacketResult::Success) { 588 if (response.IsUnsupportedResponse()) { 589 m_supports_jThreadsInfo = false; 590 } else if (!response.Empty()) { 591 object_sp = StructuredData::ParseJSON(response.GetStringRef()); 592 } 593 } 594 } 595 return object_sp; 596 } 597 598 bool GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported() { 599 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate) { 600 StringExtractorGDBRemote response; 601 m_supports_jThreadExtendedInfo = eLazyBoolNo; 602 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) == 603 PacketResult::Success) { 604 if (response.IsOKResponse()) { 605 m_supports_jThreadExtendedInfo = eLazyBoolYes; 606 } 607 } 608 } 609 return m_supports_jThreadExtendedInfo; 610 } 611 612 void GDBRemoteCommunicationClient::EnableErrorStringInPacket() { 613 if (m_supports_error_string_reply == eLazyBoolCalculate) { 614 StringExtractorGDBRemote response; 615 // We try to enable error strings in remote packets but if we fail, we just 616 // work in the older way. 617 m_supports_error_string_reply = eLazyBoolNo; 618 if (SendPacketAndWaitForResponse("QEnableErrorStrings", response, false) == 619 PacketResult::Success) { 620 if (response.IsOKResponse()) { 621 m_supports_error_string_reply = eLazyBoolYes; 622 } 623 } 624 } 625 } 626 627 bool GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported() { 628 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate) { 629 StringExtractorGDBRemote response; 630 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo; 631 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:", 632 response, 633 false) == PacketResult::Success) { 634 if (response.IsOKResponse()) { 635 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes; 636 } 637 } 638 } 639 return m_supports_jLoadedDynamicLibrariesInfos; 640 } 641 642 bool GDBRemoteCommunicationClient::GetSharedCacheInfoSupported() { 643 if (m_supports_jGetSharedCacheInfo == eLazyBoolCalculate) { 644 StringExtractorGDBRemote response; 645 m_supports_jGetSharedCacheInfo = eLazyBoolNo; 646 if (SendPacketAndWaitForResponse("jGetSharedCacheInfo:", response, false) == 647 PacketResult::Success) { 648 if (response.IsOKResponse()) { 649 m_supports_jGetSharedCacheInfo = eLazyBoolYes; 650 } 651 } 652 } 653 return m_supports_jGetSharedCacheInfo; 654 } 655 656 bool GDBRemoteCommunicationClient::GetxPacketSupported() { 657 if (m_supports_x == eLazyBoolCalculate) { 658 StringExtractorGDBRemote response; 659 m_supports_x = eLazyBoolNo; 660 char packet[256]; 661 snprintf(packet, sizeof(packet), "x0,0"); 662 if (SendPacketAndWaitForResponse(packet, response, false) == 663 PacketResult::Success) { 664 if (response.IsOKResponse()) 665 m_supports_x = eLazyBoolYes; 666 } 667 } 668 return m_supports_x; 669 } 670 671 GDBRemoteCommunicationClient::PacketResult 672 GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses( 673 const char *payload_prefix, std::string &response_string) { 674 Lock lock(*this, false); 675 if (!lock) { 676 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS | 677 GDBR_LOG_PACKETS)); 678 if (log) 679 log->Printf("error: failed to get packet sequence mutex, not sending " 680 "packets with prefix '%s'", 681 payload_prefix); 682 return PacketResult::ErrorNoSequenceLock; 683 } 684 685 response_string = ""; 686 std::string payload_prefix_str(payload_prefix); 687 unsigned int response_size = 0x1000; 688 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet 689 response_size = GetRemoteMaxPacketSize(); 690 } 691 692 for (unsigned int offset = 0; true; offset += response_size) { 693 StringExtractorGDBRemote this_response; 694 // Construct payload 695 char sizeDescriptor[128]; 696 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset, 697 response_size); 698 PacketResult result = SendPacketAndWaitForResponseNoLock( 699 payload_prefix_str + sizeDescriptor, this_response); 700 if (result != PacketResult::Success) 701 return result; 702 703 const std::string &this_string = this_response.GetStringRef(); 704 705 // Check for m or l as first character; l seems to mean this is the last 706 // chunk 707 char first_char = *this_string.c_str(); 708 if (first_char != 'm' && first_char != 'l') { 709 return PacketResult::ErrorReplyInvalid; 710 } 711 // Concatenate the result so far (skipping 'm' or 'l') 712 response_string.append(this_string, 1, std::string::npos); 713 if (first_char == 'l') 714 // We're done 715 return PacketResult::Success; 716 } 717 } 718 719 lldb::pid_t GDBRemoteCommunicationClient::GetCurrentProcessID(bool allow_lazy) { 720 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes) 721 return m_curr_pid; 722 723 // First try to retrieve the pid via the qProcessInfo request. 724 GetCurrentProcessInfo(allow_lazy); 725 if (m_curr_pid_is_valid == eLazyBoolYes) { 726 // We really got it. 727 return m_curr_pid; 728 } else { 729 // If we don't get a response for qProcessInfo, check if $qC gives us a 730 // result. $qC only returns a real process id on older debugserver and 731 // lldb-platform stubs. The gdb remote protocol documents $qC as returning 732 // the thread id, which newer debugserver and lldb-gdbserver stubs return 733 // correctly. 734 StringExtractorGDBRemote response; 735 if (SendPacketAndWaitForResponse("qC", response, false) == 736 PacketResult::Success) { 737 if (response.GetChar() == 'Q') { 738 if (response.GetChar() == 'C') { 739 m_curr_pid = response.GetHexMaxU32(false, LLDB_INVALID_PROCESS_ID); 740 if (m_curr_pid != LLDB_INVALID_PROCESS_ID) { 741 m_curr_pid_is_valid = eLazyBoolYes; 742 return m_curr_pid; 743 } 744 } 745 } 746 } 747 748 // If we don't get a response for $qC, check if $qfThreadID gives us a 749 // result. 750 if (m_curr_pid == LLDB_INVALID_PROCESS_ID) { 751 std::vector<lldb::tid_t> thread_ids; 752 bool sequence_mutex_unavailable; 753 size_t size; 754 size = GetCurrentThreadIDs(thread_ids, sequence_mutex_unavailable); 755 if (size && sequence_mutex_unavailable == false) { 756 m_curr_pid = thread_ids.front(); 757 m_curr_pid_is_valid = eLazyBoolYes; 758 return m_curr_pid; 759 } 760 } 761 } 762 763 return LLDB_INVALID_PROCESS_ID; 764 } 765 766 bool GDBRemoteCommunicationClient::GetLaunchSuccess(std::string &error_str) { 767 error_str.clear(); 768 StringExtractorGDBRemote response; 769 if (SendPacketAndWaitForResponse("qLaunchSuccess", response, false) == 770 PacketResult::Success) { 771 if (response.IsOKResponse()) 772 return true; 773 if (response.GetChar() == 'E') { 774 // A string the describes what failed when launching... 775 error_str = response.GetStringRef().substr(1); 776 } else { 777 error_str.assign("unknown error occurred launching process"); 778 } 779 } else { 780 error_str.assign("timed out waiting for app to launch"); 781 } 782 return false; 783 } 784 785 int GDBRemoteCommunicationClient::SendArgumentsPacket( 786 const ProcessLaunchInfo &launch_info) { 787 // Since we don't get the send argv0 separate from the executable path, we 788 // need to make sure to use the actual executable path found in the 789 // launch_info... 790 std::vector<const char *> argv; 791 FileSpec exe_file = launch_info.GetExecutableFile(); 792 std::string exe_path; 793 const char *arg = NULL; 794 const Args &launch_args = launch_info.GetArguments(); 795 if (exe_file) 796 exe_path = exe_file.GetPath(false); 797 else { 798 arg = launch_args.GetArgumentAtIndex(0); 799 if (arg) 800 exe_path = arg; 801 } 802 if (!exe_path.empty()) { 803 argv.push_back(exe_path.c_str()); 804 for (uint32_t i = 1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; 805 ++i) { 806 if (arg) 807 argv.push_back(arg); 808 } 809 } 810 if (!argv.empty()) { 811 StreamString packet; 812 packet.PutChar('A'); 813 for (size_t i = 0, n = argv.size(); i < n; ++i) { 814 arg = argv[i]; 815 const int arg_len = strlen(arg); 816 if (i > 0) 817 packet.PutChar(','); 818 packet.Printf("%i,%i,", arg_len * 2, (int)i); 819 packet.PutBytesAsRawHex8(arg, arg_len); 820 } 821 822 StringExtractorGDBRemote response; 823 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) == 824 PacketResult::Success) { 825 if (response.IsOKResponse()) 826 return 0; 827 uint8_t error = response.GetError(); 828 if (error) 829 return error; 830 } 831 } 832 return -1; 833 } 834 835 int GDBRemoteCommunicationClient::SendEnvironment(const Environment &env) { 836 for (const auto &KV : env) { 837 int r = SendEnvironmentPacket(Environment::compose(KV).c_str()); 838 if (r != 0) 839 return r; 840 } 841 return 0; 842 } 843 844 int GDBRemoteCommunicationClient::SendEnvironmentPacket( 845 char const *name_equal_value) { 846 if (name_equal_value && name_equal_value[0]) { 847 StreamString packet; 848 bool send_hex_encoding = false; 849 for (const char *p = name_equal_value; 850 *p != '\0' && send_hex_encoding == false; ++p) { 851 if (isprint(*p)) { 852 switch (*p) { 853 case '$': 854 case '#': 855 case '*': 856 case '}': 857 send_hex_encoding = true; 858 break; 859 default: 860 break; 861 } 862 } else { 863 // We have non printable characters, lets hex encode this... 864 send_hex_encoding = true; 865 } 866 } 867 868 StringExtractorGDBRemote response; 869 if (send_hex_encoding) { 870 if (m_supports_QEnvironmentHexEncoded) { 871 packet.PutCString("QEnvironmentHexEncoded:"); 872 packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value)); 873 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) == 874 PacketResult::Success) { 875 if (response.IsOKResponse()) 876 return 0; 877 uint8_t error = response.GetError(); 878 if (error) 879 return error; 880 if (response.IsUnsupportedResponse()) 881 m_supports_QEnvironmentHexEncoded = false; 882 } 883 } 884 885 } else if (m_supports_QEnvironment) { 886 packet.Printf("QEnvironment:%s", name_equal_value); 887 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) == 888 PacketResult::Success) { 889 if (response.IsOKResponse()) 890 return 0; 891 uint8_t error = response.GetError(); 892 if (error) 893 return error; 894 if (response.IsUnsupportedResponse()) 895 m_supports_QEnvironment = false; 896 } 897 } 898 } 899 return -1; 900 } 901 902 int GDBRemoteCommunicationClient::SendLaunchArchPacket(char const *arch) { 903 if (arch && arch[0]) { 904 StreamString packet; 905 packet.Printf("QLaunchArch:%s", arch); 906 StringExtractorGDBRemote response; 907 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) == 908 PacketResult::Success) { 909 if (response.IsOKResponse()) 910 return 0; 911 uint8_t error = response.GetError(); 912 if (error) 913 return error; 914 } 915 } 916 return -1; 917 } 918 919 int GDBRemoteCommunicationClient::SendLaunchEventDataPacket( 920 char const *data, bool *was_supported) { 921 if (data && *data != '\0') { 922 StreamString packet; 923 packet.Printf("QSetProcessEvent:%s", data); 924 StringExtractorGDBRemote response; 925 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) == 926 PacketResult::Success) { 927 if (response.IsOKResponse()) { 928 if (was_supported) 929 *was_supported = true; 930 return 0; 931 } else if (response.IsUnsupportedResponse()) { 932 if (was_supported) 933 *was_supported = false; 934 return -1; 935 } else { 936 uint8_t error = response.GetError(); 937 if (was_supported) 938 *was_supported = true; 939 if (error) 940 return error; 941 } 942 } 943 } 944 return -1; 945 } 946 947 bool GDBRemoteCommunicationClient::GetOSVersion(uint32_t &major, 948 uint32_t &minor, 949 uint32_t &update) { 950 if (GetHostInfo()) { 951 if (m_os_version_major != UINT32_MAX) { 952 major = m_os_version_major; 953 minor = m_os_version_minor; 954 update = m_os_version_update; 955 return true; 956 } 957 } 958 return false; 959 } 960 961 bool GDBRemoteCommunicationClient::GetOSBuildString(std::string &s) { 962 if (GetHostInfo()) { 963 if (!m_os_build.empty()) { 964 s = m_os_build; 965 return true; 966 } 967 } 968 s.clear(); 969 return false; 970 } 971 972 bool GDBRemoteCommunicationClient::GetOSKernelDescription(std::string &s) { 973 if (GetHostInfo()) { 974 if (!m_os_kernel.empty()) { 975 s = m_os_kernel; 976 return true; 977 } 978 } 979 s.clear(); 980 return false; 981 } 982 983 bool GDBRemoteCommunicationClient::GetHostname(std::string &s) { 984 if (GetHostInfo()) { 985 if (!m_hostname.empty()) { 986 s = m_hostname; 987 return true; 988 } 989 } 990 s.clear(); 991 return false; 992 } 993 994 ArchSpec GDBRemoteCommunicationClient::GetSystemArchitecture() { 995 if (GetHostInfo()) 996 return m_host_arch; 997 return ArchSpec(); 998 } 999 1000 const lldb_private::ArchSpec & 1001 GDBRemoteCommunicationClient::GetProcessArchitecture() { 1002 if (m_qProcessInfo_is_valid == eLazyBoolCalculate) 1003 GetCurrentProcessInfo(); 1004 return m_process_arch; 1005 } 1006 1007 bool GDBRemoteCommunicationClient::GetGDBServerVersion() { 1008 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate) { 1009 m_gdb_server_name.clear(); 1010 m_gdb_server_version = 0; 1011 m_qGDBServerVersion_is_valid = eLazyBoolNo; 1012 1013 StringExtractorGDBRemote response; 1014 if (SendPacketAndWaitForResponse("qGDBServerVersion", response, false) == 1015 PacketResult::Success) { 1016 if (response.IsNormalResponse()) { 1017 llvm::StringRef name, value; 1018 bool success = false; 1019 while (response.GetNameColonValue(name, value)) { 1020 if (name.equals("name")) { 1021 success = true; 1022 m_gdb_server_name = value; 1023 } else if (name.equals("version")) { 1024 llvm::StringRef major, minor; 1025 std::tie(major, minor) = value.split('.'); 1026 if (!major.getAsInteger(0, m_gdb_server_version)) 1027 success = true; 1028 } 1029 } 1030 if (success) 1031 m_qGDBServerVersion_is_valid = eLazyBoolYes; 1032 } 1033 } 1034 } 1035 return m_qGDBServerVersion_is_valid == eLazyBoolYes; 1036 } 1037 1038 void GDBRemoteCommunicationClient::MaybeEnableCompression( 1039 std::vector<std::string> supported_compressions) { 1040 CompressionType avail_type = CompressionType::None; 1041 std::string avail_name; 1042 1043 #if defined(HAVE_LIBCOMPRESSION) 1044 if (avail_type == CompressionType::None) { 1045 for (auto compression : supported_compressions) { 1046 if (compression == "lzfse") { 1047 avail_type = CompressionType::LZFSE; 1048 avail_name = compression; 1049 break; 1050 } 1051 } 1052 } 1053 #endif 1054 1055 #if defined(HAVE_LIBCOMPRESSION) 1056 if (avail_type == CompressionType::None) { 1057 for (auto compression : supported_compressions) { 1058 if (compression == "zlib-deflate") { 1059 avail_type = CompressionType::ZlibDeflate; 1060 avail_name = compression; 1061 break; 1062 } 1063 } 1064 } 1065 #endif 1066 1067 #if defined(HAVE_LIBZ) 1068 if (avail_type == CompressionType::None) { 1069 for (auto compression : supported_compressions) { 1070 if (compression == "zlib-deflate") { 1071 avail_type = CompressionType::ZlibDeflate; 1072 avail_name = compression; 1073 break; 1074 } 1075 } 1076 } 1077 #endif 1078 1079 #if defined(HAVE_LIBCOMPRESSION) 1080 if (avail_type == CompressionType::None) { 1081 for (auto compression : supported_compressions) { 1082 if (compression == "lz4") { 1083 avail_type = CompressionType::LZ4; 1084 avail_name = compression; 1085 break; 1086 } 1087 } 1088 } 1089 #endif 1090 1091 #if defined(HAVE_LIBCOMPRESSION) 1092 if (avail_type == CompressionType::None) { 1093 for (auto compression : supported_compressions) { 1094 if (compression == "lzma") { 1095 avail_type = CompressionType::LZMA; 1096 avail_name = compression; 1097 break; 1098 } 1099 } 1100 } 1101 #endif 1102 1103 if (avail_type != CompressionType::None) { 1104 StringExtractorGDBRemote response; 1105 std::string packet = "QEnableCompression:type:" + avail_name + ";"; 1106 if (SendPacketAndWaitForResponse(packet, response, false) != 1107 PacketResult::Success) 1108 return; 1109 1110 if (response.IsOKResponse()) { 1111 m_compression_type = avail_type; 1112 } 1113 } 1114 } 1115 1116 const char *GDBRemoteCommunicationClient::GetGDBServerProgramName() { 1117 if (GetGDBServerVersion()) { 1118 if (!m_gdb_server_name.empty()) 1119 return m_gdb_server_name.c_str(); 1120 } 1121 return NULL; 1122 } 1123 1124 uint32_t GDBRemoteCommunicationClient::GetGDBServerProgramVersion() { 1125 if (GetGDBServerVersion()) 1126 return m_gdb_server_version; 1127 return 0; 1128 } 1129 1130 bool GDBRemoteCommunicationClient::GetDefaultThreadId(lldb::tid_t &tid) { 1131 StringExtractorGDBRemote response; 1132 if (SendPacketAndWaitForResponse("qC", response, false) != 1133 PacketResult::Success) 1134 return false; 1135 1136 if (!response.IsNormalResponse()) 1137 return false; 1138 1139 if (response.GetChar() == 'Q' && response.GetChar() == 'C') 1140 tid = response.GetHexMaxU32(true, -1); 1141 1142 return true; 1143 } 1144 1145 bool GDBRemoteCommunicationClient::GetHostInfo(bool force) { 1146 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS)); 1147 1148 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) { 1149 m_qHostInfo_is_valid = eLazyBoolNo; 1150 StringExtractorGDBRemote response; 1151 if (SendPacketAndWaitForResponse("qHostInfo", response, false) == 1152 PacketResult::Success) { 1153 if (response.IsNormalResponse()) { 1154 llvm::StringRef name; 1155 llvm::StringRef value; 1156 uint32_t cpu = LLDB_INVALID_CPUTYPE; 1157 uint32_t sub = 0; 1158 std::string arch_name; 1159 std::string os_name; 1160 std::string vendor_name; 1161 std::string triple; 1162 std::string distribution_id; 1163 uint32_t pointer_byte_size = 0; 1164 ByteOrder byte_order = eByteOrderInvalid; 1165 uint32_t num_keys_decoded = 0; 1166 while (response.GetNameColonValue(name, value)) { 1167 if (name.equals("cputype")) { 1168 // exception type in big endian hex 1169 if (!value.getAsInteger(0, cpu)) 1170 ++num_keys_decoded; 1171 } else if (name.equals("cpusubtype")) { 1172 // exception count in big endian hex 1173 if (!value.getAsInteger(0, sub)) 1174 ++num_keys_decoded; 1175 } else if (name.equals("arch")) { 1176 arch_name = value; 1177 ++num_keys_decoded; 1178 } else if (name.equals("triple")) { 1179 StringExtractor extractor(value); 1180 extractor.GetHexByteString(triple); 1181 ++num_keys_decoded; 1182 } else if (name.equals("distribution_id")) { 1183 StringExtractor extractor(value); 1184 extractor.GetHexByteString(distribution_id); 1185 ++num_keys_decoded; 1186 } else if (name.equals("os_build")) { 1187 StringExtractor extractor(value); 1188 extractor.GetHexByteString(m_os_build); 1189 ++num_keys_decoded; 1190 } else if (name.equals("hostname")) { 1191 StringExtractor extractor(value); 1192 extractor.GetHexByteString(m_hostname); 1193 ++num_keys_decoded; 1194 } else if (name.equals("os_kernel")) { 1195 StringExtractor extractor(value); 1196 extractor.GetHexByteString(m_os_kernel); 1197 ++num_keys_decoded; 1198 } else if (name.equals("ostype")) { 1199 os_name = value; 1200 ++num_keys_decoded; 1201 } else if (name.equals("vendor")) { 1202 vendor_name = value; 1203 ++num_keys_decoded; 1204 } else if (name.equals("endian")) { 1205 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value) 1206 .Case("little", eByteOrderLittle) 1207 .Case("big", eByteOrderBig) 1208 .Case("pdp", eByteOrderPDP) 1209 .Default(eByteOrderInvalid); 1210 if (byte_order != eByteOrderInvalid) 1211 ++num_keys_decoded; 1212 } else if (name.equals("ptrsize")) { 1213 if (!value.getAsInteger(0, pointer_byte_size)) 1214 ++num_keys_decoded; 1215 } else if (name.equals("os_version") || 1216 name.equals( 1217 "version")) // Older debugserver binaries used the 1218 // "version" key instead of 1219 // "os_version"... 1220 { 1221 Args::StringToVersion(value, m_os_version_major, m_os_version_minor, 1222 m_os_version_update); 1223 if (m_os_version_major != UINT32_MAX) 1224 ++num_keys_decoded; 1225 } else if (name.equals("watchpoint_exceptions_received")) { 1226 m_watchpoints_trigger_after_instruction = 1227 llvm::StringSwitch<LazyBool>(value) 1228 .Case("before", eLazyBoolNo) 1229 .Case("after", eLazyBoolYes) 1230 .Default(eLazyBoolCalculate); 1231 if (m_watchpoints_trigger_after_instruction != eLazyBoolCalculate) 1232 ++num_keys_decoded; 1233 } else if (name.equals("default_packet_timeout")) { 1234 uint32_t timeout_seconds; 1235 if (!value.getAsInteger(0, timeout_seconds)) { 1236 m_default_packet_timeout = seconds(timeout_seconds); 1237 SetPacketTimeout(m_default_packet_timeout); 1238 ++num_keys_decoded; 1239 } 1240 } 1241 } 1242 1243 if (num_keys_decoded > 0) 1244 m_qHostInfo_is_valid = eLazyBoolYes; 1245 1246 if (triple.empty()) { 1247 if (arch_name.empty()) { 1248 if (cpu != LLDB_INVALID_CPUTYPE) { 1249 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub); 1250 if (pointer_byte_size) { 1251 assert(pointer_byte_size == m_host_arch.GetAddressByteSize()); 1252 } 1253 if (byte_order != eByteOrderInvalid) { 1254 assert(byte_order == m_host_arch.GetByteOrder()); 1255 } 1256 1257 if (!vendor_name.empty()) 1258 m_host_arch.GetTriple().setVendorName( 1259 llvm::StringRef(vendor_name)); 1260 if (!os_name.empty()) 1261 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name)); 1262 } 1263 } else { 1264 std::string triple; 1265 triple += arch_name; 1266 if (!vendor_name.empty() || !os_name.empty()) { 1267 triple += '-'; 1268 if (vendor_name.empty()) 1269 triple += "unknown"; 1270 else 1271 triple += vendor_name; 1272 triple += '-'; 1273 if (os_name.empty()) 1274 triple += "unknown"; 1275 else 1276 triple += os_name; 1277 } 1278 m_host_arch.SetTriple(triple.c_str()); 1279 1280 llvm::Triple &host_triple = m_host_arch.GetTriple(); 1281 if (host_triple.getVendor() == llvm::Triple::Apple && 1282 host_triple.getOS() == llvm::Triple::Darwin) { 1283 switch (m_host_arch.GetMachine()) { 1284 case llvm::Triple::aarch64: 1285 case llvm::Triple::arm: 1286 case llvm::Triple::thumb: 1287 host_triple.setOS(llvm::Triple::IOS); 1288 break; 1289 default: 1290 host_triple.setOS(llvm::Triple::MacOSX); 1291 break; 1292 } 1293 } 1294 if (pointer_byte_size) { 1295 assert(pointer_byte_size == m_host_arch.GetAddressByteSize()); 1296 } 1297 if (byte_order != eByteOrderInvalid) { 1298 assert(byte_order == m_host_arch.GetByteOrder()); 1299 } 1300 } 1301 } else { 1302 m_host_arch.SetTriple(triple.c_str()); 1303 if (pointer_byte_size) { 1304 assert(pointer_byte_size == m_host_arch.GetAddressByteSize()); 1305 } 1306 if (byte_order != eByteOrderInvalid) { 1307 assert(byte_order == m_host_arch.GetByteOrder()); 1308 } 1309 1310 if (log) 1311 log->Printf("GDBRemoteCommunicationClient::%s parsed host " 1312 "architecture as %s, triple as %s from triple text %s", 1313 __FUNCTION__, m_host_arch.GetArchitectureName() 1314 ? m_host_arch.GetArchitectureName() 1315 : "<null-arch-name>", 1316 m_host_arch.GetTriple().getTriple().c_str(), 1317 triple.c_str()); 1318 } 1319 if (!distribution_id.empty()) 1320 m_host_arch.SetDistributionId(distribution_id.c_str()); 1321 } 1322 } 1323 } 1324 return m_qHostInfo_is_valid == eLazyBoolYes; 1325 } 1326 1327 int GDBRemoteCommunicationClient::SendAttach( 1328 lldb::pid_t pid, StringExtractorGDBRemote &response) { 1329 if (pid != LLDB_INVALID_PROCESS_ID) { 1330 char packet[64]; 1331 const int packet_len = 1332 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, pid); 1333 UNUSED_IF_ASSERT_DISABLED(packet_len); 1334 assert(packet_len < (int)sizeof(packet)); 1335 if (SendPacketAndWaitForResponse(packet, response, false) == 1336 PacketResult::Success) { 1337 if (response.IsErrorResponse()) 1338 return response.GetError(); 1339 return 0; 1340 } 1341 } 1342 return -1; 1343 } 1344 1345 int GDBRemoteCommunicationClient::SendStdinNotification(const char *data, 1346 size_t data_len) { 1347 StreamString packet; 1348 packet.PutCString("I"); 1349 packet.PutBytesAsRawHex8(data, data_len); 1350 StringExtractorGDBRemote response; 1351 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) == 1352 PacketResult::Success) { 1353 return 0; 1354 } 1355 return response.GetError(); 1356 } 1357 1358 const lldb_private::ArchSpec & 1359 GDBRemoteCommunicationClient::GetHostArchitecture() { 1360 if (m_qHostInfo_is_valid == eLazyBoolCalculate) 1361 GetHostInfo(); 1362 return m_host_arch; 1363 } 1364 1365 seconds GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout() { 1366 if (m_qHostInfo_is_valid == eLazyBoolCalculate) 1367 GetHostInfo(); 1368 return m_default_packet_timeout; 1369 } 1370 1371 addr_t GDBRemoteCommunicationClient::AllocateMemory(size_t size, 1372 uint32_t permissions) { 1373 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) { 1374 m_supports_alloc_dealloc_memory = eLazyBoolYes; 1375 char packet[64]; 1376 const int packet_len = ::snprintf( 1377 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size, 1378 permissions & lldb::ePermissionsReadable ? "r" : "", 1379 permissions & lldb::ePermissionsWritable ? "w" : "", 1380 permissions & lldb::ePermissionsExecutable ? "x" : ""); 1381 assert(packet_len < (int)sizeof(packet)); 1382 UNUSED_IF_ASSERT_DISABLED(packet_len); 1383 StringExtractorGDBRemote response; 1384 if (SendPacketAndWaitForResponse(packet, response, false) == 1385 PacketResult::Success) { 1386 if (response.IsUnsupportedResponse()) 1387 m_supports_alloc_dealloc_memory = eLazyBoolNo; 1388 else if (!response.IsErrorResponse()) 1389 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 1390 } else { 1391 m_supports_alloc_dealloc_memory = eLazyBoolNo; 1392 } 1393 } 1394 return LLDB_INVALID_ADDRESS; 1395 } 1396 1397 bool GDBRemoteCommunicationClient::DeallocateMemory(addr_t addr) { 1398 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) { 1399 m_supports_alloc_dealloc_memory = eLazyBoolYes; 1400 char packet[64]; 1401 const int packet_len = 1402 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr); 1403 assert(packet_len < (int)sizeof(packet)); 1404 UNUSED_IF_ASSERT_DISABLED(packet_len); 1405 StringExtractorGDBRemote response; 1406 if (SendPacketAndWaitForResponse(packet, response, false) == 1407 PacketResult::Success) { 1408 if (response.IsUnsupportedResponse()) 1409 m_supports_alloc_dealloc_memory = eLazyBoolNo; 1410 else if (response.IsOKResponse()) 1411 return true; 1412 } else { 1413 m_supports_alloc_dealloc_memory = eLazyBoolNo; 1414 } 1415 } 1416 return false; 1417 } 1418 1419 Status GDBRemoteCommunicationClient::Detach(bool keep_stopped) { 1420 Status error; 1421 1422 if (keep_stopped) { 1423 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) { 1424 char packet[64]; 1425 const int packet_len = 1426 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:"); 1427 assert(packet_len < (int)sizeof(packet)); 1428 UNUSED_IF_ASSERT_DISABLED(packet_len); 1429 StringExtractorGDBRemote response; 1430 if (SendPacketAndWaitForResponse(packet, response, false) == 1431 PacketResult::Success && 1432 response.IsOKResponse()) { 1433 m_supports_detach_stay_stopped = eLazyBoolYes; 1434 } else { 1435 m_supports_detach_stay_stopped = eLazyBoolNo; 1436 } 1437 } 1438 1439 if (m_supports_detach_stay_stopped == eLazyBoolNo) { 1440 error.SetErrorString("Stays stopped not supported by this target."); 1441 return error; 1442 } else { 1443 StringExtractorGDBRemote response; 1444 PacketResult packet_result = 1445 SendPacketAndWaitForResponse("D1", response, false); 1446 if (packet_result != PacketResult::Success) 1447 error.SetErrorString("Sending extended disconnect packet failed."); 1448 } 1449 } else { 1450 StringExtractorGDBRemote response; 1451 PacketResult packet_result = 1452 SendPacketAndWaitForResponse("D", response, false); 1453 if (packet_result != PacketResult::Success) 1454 error.SetErrorString("Sending disconnect packet failed."); 1455 } 1456 return error; 1457 } 1458 1459 Status GDBRemoteCommunicationClient::GetMemoryRegionInfo( 1460 lldb::addr_t addr, lldb_private::MemoryRegionInfo ®ion_info) { 1461 Status error; 1462 region_info.Clear(); 1463 1464 if (m_supports_memory_region_info != eLazyBoolNo) { 1465 m_supports_memory_region_info = eLazyBoolYes; 1466 char packet[64]; 1467 const int packet_len = ::snprintf( 1468 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr); 1469 assert(packet_len < (int)sizeof(packet)); 1470 UNUSED_IF_ASSERT_DISABLED(packet_len); 1471 StringExtractorGDBRemote response; 1472 if (SendPacketAndWaitForResponse(packet, response, false) == 1473 PacketResult::Success && 1474 response.GetResponseType() == StringExtractorGDBRemote::eResponse) { 1475 llvm::StringRef name; 1476 llvm::StringRef value; 1477 addr_t addr_value = LLDB_INVALID_ADDRESS; 1478 bool success = true; 1479 bool saw_permissions = false; 1480 while (success && response.GetNameColonValue(name, value)) { 1481 if (name.equals("start")) { 1482 if (!value.getAsInteger(16, addr_value)) 1483 region_info.GetRange().SetRangeBase(addr_value); 1484 } else if (name.equals("size")) { 1485 if (!value.getAsInteger(16, addr_value)) 1486 region_info.GetRange().SetByteSize(addr_value); 1487 } else if (name.equals("permissions") && 1488 region_info.GetRange().IsValid()) { 1489 saw_permissions = true; 1490 if (region_info.GetRange().Contains(addr)) { 1491 if (value.find('r') != llvm::StringRef::npos) 1492 region_info.SetReadable(MemoryRegionInfo::eYes); 1493 else 1494 region_info.SetReadable(MemoryRegionInfo::eNo); 1495 1496 if (value.find('w') != llvm::StringRef::npos) 1497 region_info.SetWritable(MemoryRegionInfo::eYes); 1498 else 1499 region_info.SetWritable(MemoryRegionInfo::eNo); 1500 1501 if (value.find('x') != llvm::StringRef::npos) 1502 region_info.SetExecutable(MemoryRegionInfo::eYes); 1503 else 1504 region_info.SetExecutable(MemoryRegionInfo::eNo); 1505 1506 region_info.SetMapped(MemoryRegionInfo::eYes); 1507 } else { 1508 // The reported region does not contain this address -- we're 1509 // looking at an unmapped page 1510 region_info.SetReadable(MemoryRegionInfo::eNo); 1511 region_info.SetWritable(MemoryRegionInfo::eNo); 1512 region_info.SetExecutable(MemoryRegionInfo::eNo); 1513 region_info.SetMapped(MemoryRegionInfo::eNo); 1514 } 1515 } else if (name.equals("name")) { 1516 StringExtractorGDBRemote name_extractor(value); 1517 std::string name; 1518 name_extractor.GetHexByteString(name); 1519 region_info.SetName(name.c_str()); 1520 } else if (name.equals("error")) { 1521 StringExtractorGDBRemote error_extractor(value); 1522 std::string error_string; 1523 // Now convert the HEX bytes into a string value 1524 error_extractor.GetHexByteString(error_string); 1525 error.SetErrorString(error_string.c_str()); 1526 } 1527 } 1528 1529 if (region_info.GetRange().IsValid()) { 1530 // We got a valid address range back but no permissions -- which means 1531 // this is an unmapped page 1532 if (!saw_permissions) { 1533 region_info.SetReadable(MemoryRegionInfo::eNo); 1534 region_info.SetWritable(MemoryRegionInfo::eNo); 1535 region_info.SetExecutable(MemoryRegionInfo::eNo); 1536 region_info.SetMapped(MemoryRegionInfo::eNo); 1537 } 1538 } else { 1539 // We got an invalid address range back 1540 error.SetErrorString("Server returned invalid range"); 1541 } 1542 } else { 1543 m_supports_memory_region_info = eLazyBoolNo; 1544 } 1545 } 1546 1547 if (m_supports_memory_region_info == eLazyBoolNo) { 1548 error.SetErrorString("qMemoryRegionInfo is not supported"); 1549 } 1550 1551 // Try qXfer:memory-map:read to get region information not included in 1552 // qMemoryRegionInfo 1553 MemoryRegionInfo qXfer_region_info; 1554 Status qXfer_error = GetQXferMemoryMapRegionInfo(addr, qXfer_region_info); 1555 1556 if (error.Fail()) { 1557 // If qMemoryRegionInfo failed, but qXfer:memory-map:read succeeded, use 1558 // the qXfer result as a fallback 1559 if (qXfer_error.Success()) { 1560 region_info = qXfer_region_info; 1561 error.Clear(); 1562 } else { 1563 region_info.Clear(); 1564 } 1565 } else if (qXfer_error.Success()) { 1566 // If both qMemoryRegionInfo and qXfer:memory-map:read succeeded, and if 1567 // both regions are the same range, update the result to include the flash- 1568 // memory information that is specific to the qXfer result. 1569 if (region_info.GetRange() == qXfer_region_info.GetRange()) { 1570 region_info.SetFlash(qXfer_region_info.GetFlash()); 1571 region_info.SetBlocksize(qXfer_region_info.GetBlocksize()); 1572 } 1573 } 1574 return error; 1575 } 1576 1577 Status GDBRemoteCommunicationClient::GetQXferMemoryMapRegionInfo( 1578 lldb::addr_t addr, MemoryRegionInfo ®ion) { 1579 Status error = LoadQXferMemoryMap(); 1580 if (!error.Success()) 1581 return error; 1582 for (const auto &map_region : m_qXfer_memory_map) { 1583 if (map_region.GetRange().Contains(addr)) { 1584 region = map_region; 1585 return error; 1586 } 1587 } 1588 error.SetErrorString("Region not found"); 1589 return error; 1590 } 1591 1592 Status GDBRemoteCommunicationClient::LoadQXferMemoryMap() { 1593 1594 Status error; 1595 1596 if (m_qXfer_memory_map_loaded) 1597 // Already loaded, return success 1598 return error; 1599 1600 if (!XMLDocument::XMLEnabled()) { 1601 error.SetErrorString("XML is not supported"); 1602 return error; 1603 } 1604 1605 if (!GetQXferMemoryMapReadSupported()) { 1606 error.SetErrorString("Memory map is not supported"); 1607 return error; 1608 } 1609 1610 std::string xml; 1611 lldb_private::Status lldberr; 1612 if (!ReadExtFeature(ConstString("memory-map"), ConstString(""), xml, 1613 lldberr)) { 1614 error.SetErrorString("Failed to read memory map"); 1615 return error; 1616 } 1617 1618 XMLDocument xml_document; 1619 1620 if (!xml_document.ParseMemory(xml.c_str(), xml.size())) { 1621 error.SetErrorString("Failed to parse memory map xml"); 1622 return error; 1623 } 1624 1625 XMLNode map_node = xml_document.GetRootElement("memory-map"); 1626 if (!map_node) { 1627 error.SetErrorString("Invalid root node in memory map xml"); 1628 return error; 1629 } 1630 1631 m_qXfer_memory_map.clear(); 1632 1633 map_node.ForEachChildElement([this](const XMLNode &memory_node) -> bool { 1634 if (!memory_node.IsElement()) 1635 return true; 1636 if (memory_node.GetName() != "memory") 1637 return true; 1638 auto type = memory_node.GetAttributeValue("type", ""); 1639 uint64_t start; 1640 uint64_t length; 1641 if (!memory_node.GetAttributeValueAsUnsigned("start", start)) 1642 return true; 1643 if (!memory_node.GetAttributeValueAsUnsigned("length", length)) 1644 return true; 1645 MemoryRegionInfo region; 1646 region.GetRange().SetRangeBase(start); 1647 region.GetRange().SetByteSize(length); 1648 if (type == "rom") { 1649 region.SetReadable(MemoryRegionInfo::eYes); 1650 this->m_qXfer_memory_map.push_back(region); 1651 } else if (type == "ram") { 1652 region.SetReadable(MemoryRegionInfo::eYes); 1653 region.SetWritable(MemoryRegionInfo::eYes); 1654 this->m_qXfer_memory_map.push_back(region); 1655 } else if (type == "flash") { 1656 region.SetFlash(MemoryRegionInfo::eYes); 1657 memory_node.ForEachChildElement( 1658 [®ion](const XMLNode &prop_node) -> bool { 1659 if (!prop_node.IsElement()) 1660 return true; 1661 if (prop_node.GetName() != "property") 1662 return true; 1663 auto propname = prop_node.GetAttributeValue("name", ""); 1664 if (propname == "blocksize") { 1665 uint64_t blocksize; 1666 if (prop_node.GetElementTextAsUnsigned(blocksize)) 1667 region.SetBlocksize(blocksize); 1668 } 1669 return true; 1670 }); 1671 this->m_qXfer_memory_map.push_back(region); 1672 } 1673 return true; 1674 }); 1675 1676 m_qXfer_memory_map_loaded = true; 1677 1678 return error; 1679 } 1680 1681 Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) { 1682 Status error; 1683 1684 if (m_supports_watchpoint_support_info == eLazyBoolYes) { 1685 num = m_num_supported_hardware_watchpoints; 1686 return error; 1687 } 1688 1689 // Set num to 0 first. 1690 num = 0; 1691 if (m_supports_watchpoint_support_info != eLazyBoolNo) { 1692 char packet[64]; 1693 const int packet_len = 1694 ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:"); 1695 assert(packet_len < (int)sizeof(packet)); 1696 UNUSED_IF_ASSERT_DISABLED(packet_len); 1697 StringExtractorGDBRemote response; 1698 if (SendPacketAndWaitForResponse(packet, response, false) == 1699 PacketResult::Success) { 1700 m_supports_watchpoint_support_info = eLazyBoolYes; 1701 llvm::StringRef name; 1702 llvm::StringRef value; 1703 while (response.GetNameColonValue(name, value)) { 1704 if (name.equals("num")) { 1705 value.getAsInteger(0, m_num_supported_hardware_watchpoints); 1706 num = m_num_supported_hardware_watchpoints; 1707 } 1708 } 1709 } else { 1710 m_supports_watchpoint_support_info = eLazyBoolNo; 1711 } 1712 } 1713 1714 if (m_supports_watchpoint_support_info == eLazyBoolNo) { 1715 error.SetErrorString("qWatchpointSupportInfo is not supported"); 1716 } 1717 return error; 1718 } 1719 1720 lldb_private::Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo( 1721 uint32_t &num, bool &after, const ArchSpec &arch) { 1722 Status error(GetWatchpointSupportInfo(num)); 1723 if (error.Success()) 1724 error = GetWatchpointsTriggerAfterInstruction(after, arch); 1725 return error; 1726 } 1727 1728 lldb_private::Status 1729 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction( 1730 bool &after, const ArchSpec &arch) { 1731 Status error; 1732 llvm::Triple::ArchType atype = arch.GetMachine(); 1733 1734 // we assume watchpoints will happen after running the relevant opcode and we 1735 // only want to override this behavior if we have explicitly received a 1736 // qHostInfo telling us otherwise 1737 if (m_qHostInfo_is_valid != eLazyBoolYes) { 1738 // On targets like MIPS and ppc64le, watchpoint exceptions are always 1739 // generated before the instruction is executed. The connected target may 1740 // not support qHostInfo or qWatchpointSupportInfo packets. 1741 if (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel || 1742 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el || 1743 atype == llvm::Triple::ppc64le) 1744 after = false; 1745 else 1746 after = true; 1747 } else { 1748 // For MIPS and ppc64le, set m_watchpoints_trigger_after_instruction to 1749 // eLazyBoolNo if it is not calculated before. 1750 if ((m_watchpoints_trigger_after_instruction == eLazyBoolCalculate && 1751 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel || 1752 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)) || 1753 atype == llvm::Triple::ppc64le) { 1754 m_watchpoints_trigger_after_instruction = eLazyBoolNo; 1755 } 1756 1757 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo); 1758 } 1759 return error; 1760 } 1761 1762 int GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec) { 1763 if (file_spec) { 1764 std::string path{file_spec.GetPath(false)}; 1765 StreamString packet; 1766 packet.PutCString("QSetSTDIN:"); 1767 packet.PutCStringAsRawHex8(path.c_str()); 1768 1769 StringExtractorGDBRemote response; 1770 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) == 1771 PacketResult::Success) { 1772 if (response.IsOKResponse()) 1773 return 0; 1774 uint8_t error = response.GetError(); 1775 if (error) 1776 return error; 1777 } 1778 } 1779 return -1; 1780 } 1781 1782 int GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec) { 1783 if (file_spec) { 1784 std::string path{file_spec.GetPath(false)}; 1785 StreamString packet; 1786 packet.PutCString("QSetSTDOUT:"); 1787 packet.PutCStringAsRawHex8(path.c_str()); 1788 1789 StringExtractorGDBRemote response; 1790 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) == 1791 PacketResult::Success) { 1792 if (response.IsOKResponse()) 1793 return 0; 1794 uint8_t error = response.GetError(); 1795 if (error) 1796 return error; 1797 } 1798 } 1799 return -1; 1800 } 1801 1802 int GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec) { 1803 if (file_spec) { 1804 std::string path{file_spec.GetPath(false)}; 1805 StreamString packet; 1806 packet.PutCString("QSetSTDERR:"); 1807 packet.PutCStringAsRawHex8(path.c_str()); 1808 1809 StringExtractorGDBRemote response; 1810 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) == 1811 PacketResult::Success) { 1812 if (response.IsOKResponse()) 1813 return 0; 1814 uint8_t error = response.GetError(); 1815 if (error) 1816 return error; 1817 } 1818 } 1819 return -1; 1820 } 1821 1822 bool GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir) { 1823 StringExtractorGDBRemote response; 1824 if (SendPacketAndWaitForResponse("qGetWorkingDir", response, false) == 1825 PacketResult::Success) { 1826 if (response.IsUnsupportedResponse()) 1827 return false; 1828 if (response.IsErrorResponse()) 1829 return false; 1830 std::string cwd; 1831 response.GetHexByteString(cwd); 1832 working_dir.SetFile(cwd, false, GetHostArchitecture().GetTriple()); 1833 return !cwd.empty(); 1834 } 1835 return false; 1836 } 1837 1838 int GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir) { 1839 if (working_dir) { 1840 std::string path{working_dir.GetPath(false)}; 1841 StreamString packet; 1842 packet.PutCString("QSetWorkingDir:"); 1843 packet.PutCStringAsRawHex8(path.c_str()); 1844 1845 StringExtractorGDBRemote response; 1846 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) == 1847 PacketResult::Success) { 1848 if (response.IsOKResponse()) 1849 return 0; 1850 uint8_t error = response.GetError(); 1851 if (error) 1852 return error; 1853 } 1854 } 1855 return -1; 1856 } 1857 1858 int GDBRemoteCommunicationClient::SetDisableASLR(bool enable) { 1859 char packet[32]; 1860 const int packet_len = 1861 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0); 1862 assert(packet_len < (int)sizeof(packet)); 1863 UNUSED_IF_ASSERT_DISABLED(packet_len); 1864 StringExtractorGDBRemote response; 1865 if (SendPacketAndWaitForResponse(packet, response, false) == 1866 PacketResult::Success) { 1867 if (response.IsOKResponse()) 1868 return 0; 1869 uint8_t error = response.GetError(); 1870 if (error) 1871 return error; 1872 } 1873 return -1; 1874 } 1875 1876 int GDBRemoteCommunicationClient::SetDetachOnError(bool enable) { 1877 char packet[32]; 1878 const int packet_len = ::snprintf(packet, sizeof(packet), 1879 "QSetDetachOnError:%i", enable ? 1 : 0); 1880 assert(packet_len < (int)sizeof(packet)); 1881 UNUSED_IF_ASSERT_DISABLED(packet_len); 1882 StringExtractorGDBRemote response; 1883 if (SendPacketAndWaitForResponse(packet, response, false) == 1884 PacketResult::Success) { 1885 if (response.IsOKResponse()) 1886 return 0; 1887 uint8_t error = response.GetError(); 1888 if (error) 1889 return error; 1890 } 1891 return -1; 1892 } 1893 1894 bool GDBRemoteCommunicationClient::DecodeProcessInfoResponse( 1895 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) { 1896 if (response.IsNormalResponse()) { 1897 llvm::StringRef name; 1898 llvm::StringRef value; 1899 StringExtractor extractor; 1900 1901 uint32_t cpu = LLDB_INVALID_CPUTYPE; 1902 uint32_t sub = 0; 1903 std::string vendor; 1904 std::string os_type; 1905 1906 while (response.GetNameColonValue(name, value)) { 1907 if (name.equals("pid")) { 1908 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; 1909 value.getAsInteger(0, pid); 1910 process_info.SetProcessID(pid); 1911 } else if (name.equals("ppid")) { 1912 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; 1913 value.getAsInteger(0, pid); 1914 process_info.SetParentProcessID(pid); 1915 } else if (name.equals("uid")) { 1916 uint32_t uid = UINT32_MAX; 1917 value.getAsInteger(0, uid); 1918 process_info.SetUserID(uid); 1919 } else if (name.equals("euid")) { 1920 uint32_t uid = UINT32_MAX; 1921 value.getAsInteger(0, uid); 1922 process_info.SetEffectiveGroupID(uid); 1923 } else if (name.equals("gid")) { 1924 uint32_t gid = UINT32_MAX; 1925 value.getAsInteger(0, gid); 1926 process_info.SetGroupID(gid); 1927 } else if (name.equals("egid")) { 1928 uint32_t gid = UINT32_MAX; 1929 value.getAsInteger(0, gid); 1930 process_info.SetEffectiveGroupID(gid); 1931 } else if (name.equals("triple")) { 1932 StringExtractor extractor(value); 1933 std::string triple; 1934 extractor.GetHexByteString(triple); 1935 process_info.GetArchitecture().SetTriple(triple.c_str()); 1936 } else if (name.equals("name")) { 1937 StringExtractor extractor(value); 1938 // The process name from ASCII hex bytes since we can't control the 1939 // characters in a process name 1940 std::string name; 1941 extractor.GetHexByteString(name); 1942 process_info.GetExecutableFile().SetFile(name, false, 1943 FileSpec::Style::native); 1944 } else if (name.equals("cputype")) { 1945 value.getAsInteger(0, cpu); 1946 } else if (name.equals("cpusubtype")) { 1947 value.getAsInteger(0, sub); 1948 } else if (name.equals("vendor")) { 1949 vendor = value; 1950 } else if (name.equals("ostype")) { 1951 os_type = value; 1952 } 1953 } 1954 1955 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) { 1956 if (vendor == "apple") { 1957 process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu, 1958 sub); 1959 process_info.GetArchitecture().GetTriple().setVendorName( 1960 llvm::StringRef(vendor)); 1961 process_info.GetArchitecture().GetTriple().setOSName( 1962 llvm::StringRef(os_type)); 1963 } 1964 } 1965 1966 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) 1967 return true; 1968 } 1969 return false; 1970 } 1971 1972 bool GDBRemoteCommunicationClient::GetProcessInfo( 1973 lldb::pid_t pid, ProcessInstanceInfo &process_info) { 1974 process_info.Clear(); 1975 1976 if (m_supports_qProcessInfoPID) { 1977 char packet[32]; 1978 const int packet_len = 1979 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid); 1980 assert(packet_len < (int)sizeof(packet)); 1981 UNUSED_IF_ASSERT_DISABLED(packet_len); 1982 StringExtractorGDBRemote response; 1983 if (SendPacketAndWaitForResponse(packet, response, false) == 1984 PacketResult::Success) { 1985 return DecodeProcessInfoResponse(response, process_info); 1986 } else { 1987 m_supports_qProcessInfoPID = false; 1988 return false; 1989 } 1990 } 1991 return false; 1992 } 1993 1994 bool GDBRemoteCommunicationClient::GetCurrentProcessInfo(bool allow_lazy) { 1995 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS | 1996 GDBR_LOG_PACKETS)); 1997 1998 if (allow_lazy) { 1999 if (m_qProcessInfo_is_valid == eLazyBoolYes) 2000 return true; 2001 if (m_qProcessInfo_is_valid == eLazyBoolNo) 2002 return false; 2003 } 2004 2005 GetHostInfo(); 2006 2007 StringExtractorGDBRemote response; 2008 if (SendPacketAndWaitForResponse("qProcessInfo", response, false) == 2009 PacketResult::Success) { 2010 if (response.IsNormalResponse()) { 2011 llvm::StringRef name; 2012 llvm::StringRef value; 2013 uint32_t cpu = LLDB_INVALID_CPUTYPE; 2014 uint32_t sub = 0; 2015 std::string arch_name; 2016 std::string os_name; 2017 std::string vendor_name; 2018 std::string triple; 2019 std::string elf_abi; 2020 uint32_t pointer_byte_size = 0; 2021 StringExtractor extractor; 2022 ByteOrder byte_order = eByteOrderInvalid; 2023 uint32_t num_keys_decoded = 0; 2024 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; 2025 while (response.GetNameColonValue(name, value)) { 2026 if (name.equals("cputype")) { 2027 if (!value.getAsInteger(16, cpu)) 2028 ++num_keys_decoded; 2029 } else if (name.equals("cpusubtype")) { 2030 if (!value.getAsInteger(16, sub)) 2031 ++num_keys_decoded; 2032 } else if (name.equals("triple")) { 2033 StringExtractor extractor(value); 2034 extractor.GetHexByteString(triple); 2035 ++num_keys_decoded; 2036 } else if (name.equals("ostype")) { 2037 os_name = value; 2038 ++num_keys_decoded; 2039 } else if (name.equals("vendor")) { 2040 vendor_name = value; 2041 ++num_keys_decoded; 2042 } else if (name.equals("endian")) { 2043 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value) 2044 .Case("little", eByteOrderLittle) 2045 .Case("big", eByteOrderBig) 2046 .Case("pdp", eByteOrderPDP) 2047 .Default(eByteOrderInvalid); 2048 if (byte_order != eByteOrderInvalid) 2049 ++num_keys_decoded; 2050 } else if (name.equals("ptrsize")) { 2051 if (!value.getAsInteger(16, pointer_byte_size)) 2052 ++num_keys_decoded; 2053 } else if (name.equals("pid")) { 2054 if (!value.getAsInteger(16, pid)) 2055 ++num_keys_decoded; 2056 } else if (name.equals("elf_abi")) { 2057 elf_abi = value; 2058 ++num_keys_decoded; 2059 } 2060 } 2061 if (num_keys_decoded > 0) 2062 m_qProcessInfo_is_valid = eLazyBoolYes; 2063 if (pid != LLDB_INVALID_PROCESS_ID) { 2064 m_curr_pid_is_valid = eLazyBoolYes; 2065 m_curr_pid = pid; 2066 } 2067 2068 // Set the ArchSpec from the triple if we have it. 2069 if (!triple.empty()) { 2070 m_process_arch.SetTriple(triple.c_str()); 2071 m_process_arch.SetFlags(elf_abi); 2072 if (pointer_byte_size) { 2073 assert(pointer_byte_size == m_process_arch.GetAddressByteSize()); 2074 } 2075 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && 2076 !vendor_name.empty()) { 2077 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name); 2078 2079 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat); 2080 assert(triple.getObjectFormat() != llvm::Triple::Wasm); 2081 switch (triple.getObjectFormat()) { 2082 case llvm::Triple::MachO: 2083 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub); 2084 break; 2085 case llvm::Triple::ELF: 2086 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub); 2087 break; 2088 case llvm::Triple::COFF: 2089 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub); 2090 break; 2091 case llvm::Triple::Wasm: 2092 if (log) 2093 log->Printf("error: not supported target architecture"); 2094 return false; 2095 case llvm::Triple::UnknownObjectFormat: 2096 if (log) 2097 log->Printf("error: failed to determine target architecture"); 2098 return false; 2099 } 2100 2101 if (pointer_byte_size) { 2102 assert(pointer_byte_size == m_process_arch.GetAddressByteSize()); 2103 } 2104 if (byte_order != eByteOrderInvalid) { 2105 assert(byte_order == m_process_arch.GetByteOrder()); 2106 } 2107 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name)); 2108 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name)); 2109 m_host_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name)); 2110 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name)); 2111 } 2112 return true; 2113 } 2114 } else { 2115 m_qProcessInfo_is_valid = eLazyBoolNo; 2116 } 2117 2118 return false; 2119 } 2120 2121 uint32_t GDBRemoteCommunicationClient::FindProcesses( 2122 const ProcessInstanceInfoMatch &match_info, 2123 ProcessInstanceInfoList &process_infos) { 2124 process_infos.Clear(); 2125 2126 if (m_supports_qfProcessInfo) { 2127 StreamString packet; 2128 packet.PutCString("qfProcessInfo"); 2129 if (!match_info.MatchAllProcesses()) { 2130 packet.PutChar(':'); 2131 const char *name = match_info.GetProcessInfo().GetName(); 2132 bool has_name_match = false; 2133 if (name && name[0]) { 2134 has_name_match = true; 2135 NameMatch name_match_type = match_info.GetNameMatchType(); 2136 switch (name_match_type) { 2137 case NameMatch::Ignore: 2138 has_name_match = false; 2139 break; 2140 2141 case NameMatch::Equals: 2142 packet.PutCString("name_match:equals;"); 2143 break; 2144 2145 case NameMatch::Contains: 2146 packet.PutCString("name_match:contains;"); 2147 break; 2148 2149 case NameMatch::StartsWith: 2150 packet.PutCString("name_match:starts_with;"); 2151 break; 2152 2153 case NameMatch::EndsWith: 2154 packet.PutCString("name_match:ends_with;"); 2155 break; 2156 2157 case NameMatch::RegularExpression: 2158 packet.PutCString("name_match:regex;"); 2159 break; 2160 } 2161 if (has_name_match) { 2162 packet.PutCString("name:"); 2163 packet.PutBytesAsRawHex8(name, ::strlen(name)); 2164 packet.PutChar(';'); 2165 } 2166 } 2167 2168 if (match_info.GetProcessInfo().ProcessIDIsValid()) 2169 packet.Printf("pid:%" PRIu64 ";", 2170 match_info.GetProcessInfo().GetProcessID()); 2171 if (match_info.GetProcessInfo().ParentProcessIDIsValid()) 2172 packet.Printf("parent_pid:%" PRIu64 ";", 2173 match_info.GetProcessInfo().GetParentProcessID()); 2174 if (match_info.GetProcessInfo().UserIDIsValid()) 2175 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID()); 2176 if (match_info.GetProcessInfo().GroupIDIsValid()) 2177 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID()); 2178 if (match_info.GetProcessInfo().EffectiveUserIDIsValid()) 2179 packet.Printf("euid:%u;", 2180 match_info.GetProcessInfo().GetEffectiveUserID()); 2181 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid()) 2182 packet.Printf("egid:%u;", 2183 match_info.GetProcessInfo().GetEffectiveGroupID()); 2184 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid()) 2185 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0); 2186 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) { 2187 const ArchSpec &match_arch = 2188 match_info.GetProcessInfo().GetArchitecture(); 2189 const llvm::Triple &triple = match_arch.GetTriple(); 2190 packet.PutCString("triple:"); 2191 packet.PutCString(triple.getTriple()); 2192 packet.PutChar(';'); 2193 } 2194 } 2195 StringExtractorGDBRemote response; 2196 // Increase timeout as the first qfProcessInfo packet takes a long time on 2197 // Android. The value of 1min was arrived at empirically. 2198 ScopedTimeout timeout(*this, minutes(1)); 2199 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) == 2200 PacketResult::Success) { 2201 do { 2202 ProcessInstanceInfo process_info; 2203 if (!DecodeProcessInfoResponse(response, process_info)) 2204 break; 2205 process_infos.Append(process_info); 2206 response.GetStringRef().clear(); 2207 response.SetFilePos(0); 2208 } while (SendPacketAndWaitForResponse("qsProcessInfo", response, false) == 2209 PacketResult::Success); 2210 } else { 2211 m_supports_qfProcessInfo = false; 2212 return 0; 2213 } 2214 } 2215 return process_infos.GetSize(); 2216 } 2217 2218 bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid, 2219 std::string &name) { 2220 if (m_supports_qUserName) { 2221 char packet[32]; 2222 const int packet_len = 2223 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid); 2224 assert(packet_len < (int)sizeof(packet)); 2225 UNUSED_IF_ASSERT_DISABLED(packet_len); 2226 StringExtractorGDBRemote response; 2227 if (SendPacketAndWaitForResponse(packet, response, false) == 2228 PacketResult::Success) { 2229 if (response.IsNormalResponse()) { 2230 // Make sure we parsed the right number of characters. The response is 2231 // the hex encoded user name and should make up the entire packet. If 2232 // there are any non-hex ASCII bytes, the length won't match below.. 2233 if (response.GetHexByteString(name) * 2 == 2234 response.GetStringRef().size()) 2235 return true; 2236 } 2237 } else { 2238 m_supports_qUserName = false; 2239 return false; 2240 } 2241 } 2242 return false; 2243 } 2244 2245 bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid, 2246 std::string &name) { 2247 if (m_supports_qGroupName) { 2248 char packet[32]; 2249 const int packet_len = 2250 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid); 2251 assert(packet_len < (int)sizeof(packet)); 2252 UNUSED_IF_ASSERT_DISABLED(packet_len); 2253 StringExtractorGDBRemote response; 2254 if (SendPacketAndWaitForResponse(packet, response, false) == 2255 PacketResult::Success) { 2256 if (response.IsNormalResponse()) { 2257 // Make sure we parsed the right number of characters. The response is 2258 // the hex encoded group name and should make up the entire packet. If 2259 // there are any non-hex ASCII bytes, the length won't match below.. 2260 if (response.GetHexByteString(name) * 2 == 2261 response.GetStringRef().size()) 2262 return true; 2263 } 2264 } else { 2265 m_supports_qGroupName = false; 2266 return false; 2267 } 2268 } 2269 return false; 2270 } 2271 2272 bool GDBRemoteCommunicationClient::SetNonStopMode(const bool enable) { 2273 // Form non-stop packet request 2274 char packet[32]; 2275 const int packet_len = 2276 ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable); 2277 assert(packet_len < (int)sizeof(packet)); 2278 UNUSED_IF_ASSERT_DISABLED(packet_len); 2279 2280 StringExtractorGDBRemote response; 2281 // Send to target 2282 if (SendPacketAndWaitForResponse(packet, response, false) == 2283 PacketResult::Success) 2284 if (response.IsOKResponse()) 2285 return true; 2286 2287 // Failed or not supported 2288 return false; 2289 } 2290 2291 static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size, 2292 uint32_t recv_size) { 2293 packet.Clear(); 2294 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size); 2295 uint32_t bytes_left = send_size; 2296 while (bytes_left > 0) { 2297 if (bytes_left >= 26) { 2298 packet.PutCString("abcdefghijklmnopqrstuvwxyz"); 2299 bytes_left -= 26; 2300 } else { 2301 packet.Printf("%*.*s;", bytes_left, bytes_left, 2302 "abcdefghijklmnopqrstuvwxyz"); 2303 bytes_left = 0; 2304 } 2305 } 2306 } 2307 2308 duration<float> 2309 calculate_standard_deviation(const std::vector<duration<float>> &v) { 2310 using Dur = duration<float>; 2311 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur()); 2312 Dur mean = sum / v.size(); 2313 float accum = 0; 2314 for (auto d : v) { 2315 float delta = (d - mean).count(); 2316 accum += delta * delta; 2317 }; 2318 2319 return Dur(sqrtf(accum / (v.size() - 1))); 2320 } 2321 2322 void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets, 2323 uint32_t max_send, 2324 uint32_t max_recv, 2325 uint64_t recv_amount, 2326 bool json, Stream &strm) { 2327 uint32_t i; 2328 if (SendSpeedTestPacket(0, 0)) { 2329 StreamString packet; 2330 if (json) 2331 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n " 2332 "\"results\" : [", 2333 num_packets); 2334 else 2335 strm.Printf("Testing sending %u packets of various sizes:\n", 2336 num_packets); 2337 strm.Flush(); 2338 2339 uint32_t result_idx = 0; 2340 uint32_t send_size; 2341 std::vector<duration<float>> packet_times; 2342 2343 for (send_size = 0; send_size <= max_send; 2344 send_size ? send_size *= 2 : send_size = 4) { 2345 for (uint32_t recv_size = 0; recv_size <= max_recv; 2346 recv_size ? recv_size *= 2 : recv_size = 4) { 2347 MakeSpeedTestPacket(packet, send_size, recv_size); 2348 2349 packet_times.clear(); 2350 // Test how long it takes to send 'num_packets' packets 2351 const auto start_time = steady_clock::now(); 2352 for (i = 0; i < num_packets; ++i) { 2353 const auto packet_start_time = steady_clock::now(); 2354 StringExtractorGDBRemote response; 2355 SendPacketAndWaitForResponse(packet.GetString(), response, false); 2356 const auto packet_end_time = steady_clock::now(); 2357 packet_times.push_back(packet_end_time - packet_start_time); 2358 } 2359 const auto end_time = steady_clock::now(); 2360 const auto total_time = end_time - start_time; 2361 2362 float packets_per_second = 2363 ((float)num_packets) / duration<float>(total_time).count(); 2364 auto average_per_packet = total_time / num_packets; 2365 const duration<float> standard_deviation = 2366 calculate_standard_deviation(packet_times); 2367 if (json) { 2368 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : " 2369 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, " 2370 "\"standard_deviation_nsec\" : {4,9:ns-f0}}", 2371 result_idx > 0 ? "," : "", send_size, recv_size, 2372 total_time, standard_deviation); 2373 ++result_idx; 2374 } else { 2375 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for " 2376 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with " 2377 "standard deviation of {5,10:ms+f6}\n", 2378 send_size, recv_size, duration<float>(total_time), 2379 packets_per_second, duration<float>(average_per_packet), 2380 standard_deviation); 2381 } 2382 strm.Flush(); 2383 } 2384 } 2385 2386 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f); 2387 if (json) 2388 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" " 2389 ": %" PRIu64 ",\n \"results\" : [", 2390 recv_amount); 2391 else 2392 strm.Printf("Testing receiving %2.1fMB of data using varying receive " 2393 "packet sizes:\n", 2394 k_recv_amount_mb); 2395 strm.Flush(); 2396 send_size = 0; 2397 result_idx = 0; 2398 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) { 2399 MakeSpeedTestPacket(packet, send_size, recv_size); 2400 2401 // If we have a receive size, test how long it takes to receive 4MB of 2402 // data 2403 if (recv_size > 0) { 2404 const auto start_time = steady_clock::now(); 2405 uint32_t bytes_read = 0; 2406 uint32_t packet_count = 0; 2407 while (bytes_read < recv_amount) { 2408 StringExtractorGDBRemote response; 2409 SendPacketAndWaitForResponse(packet.GetString(), response, false); 2410 bytes_read += recv_size; 2411 ++packet_count; 2412 } 2413 const auto end_time = steady_clock::now(); 2414 const auto total_time = end_time - start_time; 2415 float mb_second = ((float)recv_amount) / 2416 duration<float>(total_time).count() / 2417 (1024.0 * 1024.0); 2418 float packets_per_second = 2419 ((float)packet_count) / duration<float>(total_time).count(); 2420 const auto average_per_packet = total_time / packet_count; 2421 2422 if (json) { 2423 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : " 2424 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}", 2425 result_idx > 0 ? "," : "", send_size, recv_size, 2426 total_time); 2427 ++result_idx; 2428 } else { 2429 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed " 2430 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for " 2431 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n", 2432 send_size, recv_size, packet_count, k_recv_amount_mb, 2433 duration<float>(total_time), mb_second, 2434 packets_per_second, duration<float>(average_per_packet)); 2435 } 2436 strm.Flush(); 2437 } 2438 } 2439 if (json) 2440 strm.Printf("\n ]\n }\n}\n"); 2441 else 2442 strm.EOL(); 2443 } 2444 } 2445 2446 bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size, 2447 uint32_t recv_size) { 2448 StreamString packet; 2449 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size); 2450 uint32_t bytes_left = send_size; 2451 while (bytes_left > 0) { 2452 if (bytes_left >= 26) { 2453 packet.PutCString("abcdefghijklmnopqrstuvwxyz"); 2454 bytes_left -= 26; 2455 } else { 2456 packet.Printf("%*.*s;", bytes_left, bytes_left, 2457 "abcdefghijklmnopqrstuvwxyz"); 2458 bytes_left = 0; 2459 } 2460 } 2461 2462 StringExtractorGDBRemote response; 2463 return SendPacketAndWaitForResponse(packet.GetString(), response, false) == 2464 PacketResult::Success; 2465 } 2466 2467 bool GDBRemoteCommunicationClient::LaunchGDBServer( 2468 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port, 2469 std::string &socket_name) { 2470 pid = LLDB_INVALID_PROCESS_ID; 2471 port = 0; 2472 socket_name.clear(); 2473 2474 StringExtractorGDBRemote response; 2475 StreamString stream; 2476 stream.PutCString("qLaunchGDBServer;"); 2477 std::string hostname; 2478 if (remote_accept_hostname && remote_accept_hostname[0]) 2479 hostname = remote_accept_hostname; 2480 else { 2481 if (HostInfo::GetHostname(hostname)) { 2482 // Make the GDB server we launch only accept connections from this host 2483 stream.Printf("host:%s;", hostname.c_str()); 2484 } else { 2485 // Make the GDB server we launch accept connections from any host since 2486 // we can't figure out the hostname 2487 stream.Printf("host:*;"); 2488 } 2489 } 2490 // give the process a few seconds to startup 2491 ScopedTimeout timeout(*this, seconds(10)); 2492 2493 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2494 PacketResult::Success) { 2495 llvm::StringRef name; 2496 llvm::StringRef value; 2497 while (response.GetNameColonValue(name, value)) { 2498 if (name.equals("port")) 2499 value.getAsInteger(0, port); 2500 else if (name.equals("pid")) 2501 value.getAsInteger(0, pid); 2502 else if (name.compare("socket_name") == 0) { 2503 StringExtractor extractor(value); 2504 extractor.GetHexByteString(socket_name); 2505 } 2506 } 2507 return true; 2508 } 2509 return false; 2510 } 2511 2512 size_t GDBRemoteCommunicationClient::QueryGDBServer( 2513 std::vector<std::pair<uint16_t, std::string>> &connection_urls) { 2514 connection_urls.clear(); 2515 2516 StringExtractorGDBRemote response; 2517 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) != 2518 PacketResult::Success) 2519 return 0; 2520 2521 StructuredData::ObjectSP data = 2522 StructuredData::ParseJSON(response.GetStringRef()); 2523 if (!data) 2524 return 0; 2525 2526 StructuredData::Array *array = data->GetAsArray(); 2527 if (!array) 2528 return 0; 2529 2530 for (size_t i = 0, count = array->GetSize(); i < count; ++i) { 2531 StructuredData::Dictionary *element = nullptr; 2532 if (!array->GetItemAtIndexAsDictionary(i, element)) 2533 continue; 2534 2535 uint16_t port = 0; 2536 if (StructuredData::ObjectSP port_osp = 2537 element->GetValueForKey(llvm::StringRef("port"))) 2538 port = port_osp->GetIntegerValue(0); 2539 2540 std::string socket_name; 2541 if (StructuredData::ObjectSP socket_name_osp = 2542 element->GetValueForKey(llvm::StringRef("socket_name"))) 2543 socket_name = socket_name_osp->GetStringValue(); 2544 2545 if (port != 0 || !socket_name.empty()) 2546 connection_urls.emplace_back(port, socket_name); 2547 } 2548 return connection_urls.size(); 2549 } 2550 2551 bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) { 2552 StreamString stream; 2553 stream.Printf("qKillSpawnedProcess:%" PRId64, pid); 2554 2555 StringExtractorGDBRemote response; 2556 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2557 PacketResult::Success) { 2558 if (response.IsOKResponse()) 2559 return true; 2560 } 2561 return false; 2562 } 2563 2564 bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid) { 2565 if (m_curr_tid == tid) 2566 return true; 2567 2568 char packet[32]; 2569 int packet_len; 2570 if (tid == UINT64_MAX) 2571 packet_len = ::snprintf(packet, sizeof(packet), "Hg-1"); 2572 else 2573 packet_len = ::snprintf(packet, sizeof(packet), "Hg%" PRIx64, tid); 2574 assert(packet_len + 1 < (int)sizeof(packet)); 2575 UNUSED_IF_ASSERT_DISABLED(packet_len); 2576 StringExtractorGDBRemote response; 2577 if (SendPacketAndWaitForResponse(packet, response, false) == 2578 PacketResult::Success) { 2579 if (response.IsOKResponse()) { 2580 m_curr_tid = tid; 2581 return true; 2582 } 2583 2584 /* 2585 * Connected bare-iron target (like YAMON gdb-stub) may not have support for 2586 * Hg packet. 2587 * The reply from '?' packet could be as simple as 'S05'. There is no packet 2588 * which can 2589 * give us pid and/or tid. Assume pid=tid=1 in such cases. 2590 */ 2591 if (response.IsUnsupportedResponse() && IsConnected()) { 2592 m_curr_tid = 1; 2593 return true; 2594 } 2595 } 2596 return false; 2597 } 2598 2599 bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid) { 2600 if (m_curr_tid_run == tid) 2601 return true; 2602 2603 char packet[32]; 2604 int packet_len; 2605 if (tid == UINT64_MAX) 2606 packet_len = ::snprintf(packet, sizeof(packet), "Hc-1"); 2607 else 2608 packet_len = ::snprintf(packet, sizeof(packet), "Hc%" PRIx64, tid); 2609 2610 assert(packet_len + 1 < (int)sizeof(packet)); 2611 UNUSED_IF_ASSERT_DISABLED(packet_len); 2612 StringExtractorGDBRemote response; 2613 if (SendPacketAndWaitForResponse(packet, response, false) == 2614 PacketResult::Success) { 2615 if (response.IsOKResponse()) { 2616 m_curr_tid_run = tid; 2617 return true; 2618 } 2619 2620 /* 2621 * Connected bare-iron target (like YAMON gdb-stub) may not have support for 2622 * Hc packet. 2623 * The reply from '?' packet could be as simple as 'S05'. There is no packet 2624 * which can 2625 * give us pid and/or tid. Assume pid=tid=1 in such cases. 2626 */ 2627 if (response.IsUnsupportedResponse() && IsConnected()) { 2628 m_curr_tid_run = 1; 2629 return true; 2630 } 2631 } 2632 return false; 2633 } 2634 2635 bool GDBRemoteCommunicationClient::GetStopReply( 2636 StringExtractorGDBRemote &response) { 2637 if (SendPacketAndWaitForResponse("?", response, false) == 2638 PacketResult::Success) 2639 return response.IsNormalResponse(); 2640 return false; 2641 } 2642 2643 bool GDBRemoteCommunicationClient::GetThreadStopInfo( 2644 lldb::tid_t tid, StringExtractorGDBRemote &response) { 2645 if (m_supports_qThreadStopInfo) { 2646 char packet[256]; 2647 int packet_len = 2648 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid); 2649 assert(packet_len < (int)sizeof(packet)); 2650 UNUSED_IF_ASSERT_DISABLED(packet_len); 2651 if (SendPacketAndWaitForResponse(packet, response, false) == 2652 PacketResult::Success) { 2653 if (response.IsUnsupportedResponse()) 2654 m_supports_qThreadStopInfo = false; 2655 else if (response.IsNormalResponse()) 2656 return true; 2657 else 2658 return false; 2659 } else { 2660 m_supports_qThreadStopInfo = false; 2661 } 2662 } 2663 return false; 2664 } 2665 2666 uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket( 2667 GDBStoppointType type, bool insert, addr_t addr, uint32_t length) { 2668 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); 2669 if (log) 2670 log->Printf("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64, 2671 __FUNCTION__, insert ? "add" : "remove", addr); 2672 2673 // Check if the stub is known not to support this breakpoint type 2674 if (!SupportsGDBStoppointPacket(type)) 2675 return UINT8_MAX; 2676 // Construct the breakpoint packet 2677 char packet[64]; 2678 const int packet_len = 2679 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x", 2680 insert ? 'Z' : 'z', type, addr, length); 2681 // Check we haven't overwritten the end of the packet buffer 2682 assert(packet_len + 1 < (int)sizeof(packet)); 2683 UNUSED_IF_ASSERT_DISABLED(packet_len); 2684 StringExtractorGDBRemote response; 2685 // Make sure the response is either "OK", "EXX" where XX are two hex digits, 2686 // or "" (unsupported) 2687 response.SetResponseValidatorToOKErrorNotSupported(); 2688 // Try to send the breakpoint packet, and check that it was correctly sent 2689 if (SendPacketAndWaitForResponse(packet, response, true) == 2690 PacketResult::Success) { 2691 // Receive and OK packet when the breakpoint successfully placed 2692 if (response.IsOKResponse()) 2693 return 0; 2694 2695 // Status while setting breakpoint, send back specific error 2696 if (response.IsErrorResponse()) 2697 return response.GetError(); 2698 2699 // Empty packet informs us that breakpoint is not supported 2700 if (response.IsUnsupportedResponse()) { 2701 // Disable this breakpoint type since it is unsupported 2702 switch (type) { 2703 case eBreakpointSoftware: 2704 m_supports_z0 = false; 2705 break; 2706 case eBreakpointHardware: 2707 m_supports_z1 = false; 2708 break; 2709 case eWatchpointWrite: 2710 m_supports_z2 = false; 2711 break; 2712 case eWatchpointRead: 2713 m_supports_z3 = false; 2714 break; 2715 case eWatchpointReadWrite: 2716 m_supports_z4 = false; 2717 break; 2718 case eStoppointInvalid: 2719 return UINT8_MAX; 2720 } 2721 } 2722 } 2723 // Signal generic failure 2724 return UINT8_MAX; 2725 } 2726 2727 size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs( 2728 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) { 2729 thread_ids.clear(); 2730 2731 Lock lock(*this, false); 2732 if (lock) { 2733 sequence_mutex_unavailable = false; 2734 StringExtractorGDBRemote response; 2735 2736 PacketResult packet_result; 2737 for (packet_result = 2738 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response); 2739 packet_result == PacketResult::Success && response.IsNormalResponse(); 2740 packet_result = 2741 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) { 2742 char ch = response.GetChar(); 2743 if (ch == 'l') 2744 break; 2745 if (ch == 'm') { 2746 do { 2747 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID); 2748 2749 if (tid != LLDB_INVALID_THREAD_ID) { 2750 thread_ids.push_back(tid); 2751 } 2752 ch = response.GetChar(); // Skip the command separator 2753 } while (ch == ','); // Make sure we got a comma separator 2754 } 2755 } 2756 2757 /* 2758 * Connected bare-iron target (like YAMON gdb-stub) may not have support for 2759 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet 2760 * could 2761 * be as simple as 'S05'. There is no packet which can give us pid and/or 2762 * tid. 2763 * Assume pid=tid=1 in such cases. 2764 */ 2765 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) && 2766 thread_ids.size() == 0 && IsConnected()) { 2767 thread_ids.push_back(1); 2768 } 2769 } else { 2770 #if !defined(LLDB_CONFIGURATION_DEBUG) 2771 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS | 2772 GDBR_LOG_PACKETS)); 2773 if (log) 2774 log->Printf("error: failed to get packet sequence mutex, not sending " 2775 "packet 'qfThreadInfo'"); 2776 #endif 2777 sequence_mutex_unavailable = true; 2778 } 2779 return thread_ids.size(); 2780 } 2781 2782 lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() { 2783 StringExtractorGDBRemote response; 2784 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) != 2785 PacketResult::Success || 2786 !response.IsNormalResponse()) 2787 return LLDB_INVALID_ADDRESS; 2788 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 2789 } 2790 2791 lldb_private::Status GDBRemoteCommunicationClient::RunShellCommand( 2792 const char *command, // Shouldn't be NULL 2793 const FileSpec & 2794 working_dir, // Pass empty FileSpec to use the current working directory 2795 int *status_ptr, // Pass NULL if you don't want the process exit status 2796 int *signo_ptr, // Pass NULL if you don't want the signal that caused the 2797 // process to exit 2798 std::string 2799 *command_output, // Pass NULL if you don't want the command output 2800 const Timeout<std::micro> &timeout) { 2801 lldb_private::StreamString stream; 2802 stream.PutCString("qPlatform_shell:"); 2803 stream.PutBytesAsRawHex8(command, strlen(command)); 2804 stream.PutChar(','); 2805 uint32_t timeout_sec = UINT32_MAX; 2806 if (timeout) { 2807 // TODO: Use chrono version of std::ceil once c++17 is available. 2808 timeout_sec = std::ceil(std::chrono::duration<double>(*timeout).count()); 2809 } 2810 stream.PutHex32(timeout_sec); 2811 if (working_dir) { 2812 std::string path{working_dir.GetPath(false)}; 2813 stream.PutChar(','); 2814 stream.PutCStringAsRawHex8(path.c_str()); 2815 } 2816 StringExtractorGDBRemote response; 2817 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2818 PacketResult::Success) { 2819 if (response.GetChar() != 'F') 2820 return Status("malformed reply"); 2821 if (response.GetChar() != ',') 2822 return Status("malformed reply"); 2823 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX); 2824 if (exitcode == UINT32_MAX) 2825 return Status("unable to run remote process"); 2826 else if (status_ptr) 2827 *status_ptr = exitcode; 2828 if (response.GetChar() != ',') 2829 return Status("malformed reply"); 2830 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX); 2831 if (signo_ptr) 2832 *signo_ptr = signo; 2833 if (response.GetChar() != ',') 2834 return Status("malformed reply"); 2835 std::string output; 2836 response.GetEscapedBinaryData(output); 2837 if (command_output) 2838 command_output->assign(output); 2839 return Status(); 2840 } 2841 return Status("unable to send packet"); 2842 } 2843 2844 Status GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec, 2845 uint32_t file_permissions) { 2846 std::string path{file_spec.GetPath(false)}; 2847 lldb_private::StreamString stream; 2848 stream.PutCString("qPlatform_mkdir:"); 2849 stream.PutHex32(file_permissions); 2850 stream.PutChar(','); 2851 stream.PutCStringAsRawHex8(path.c_str()); 2852 llvm::StringRef packet = stream.GetString(); 2853 StringExtractorGDBRemote response; 2854 2855 if (SendPacketAndWaitForResponse(packet, response, false) != 2856 PacketResult::Success) 2857 return Status("failed to send '%s' packet", packet.str().c_str()); 2858 2859 if (response.GetChar() != 'F') 2860 return Status("invalid response to '%s' packet", packet.str().c_str()); 2861 2862 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX); 2863 } 2864 2865 Status 2866 GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec, 2867 uint32_t file_permissions) { 2868 std::string path{file_spec.GetPath(false)}; 2869 lldb_private::StreamString stream; 2870 stream.PutCString("qPlatform_chmod:"); 2871 stream.PutHex32(file_permissions); 2872 stream.PutChar(','); 2873 stream.PutCStringAsRawHex8(path.c_str()); 2874 llvm::StringRef packet = stream.GetString(); 2875 StringExtractorGDBRemote response; 2876 2877 if (SendPacketAndWaitForResponse(packet, response, false) != 2878 PacketResult::Success) 2879 return Status("failed to send '%s' packet", stream.GetData()); 2880 2881 if (response.GetChar() != 'F') 2882 return Status("invalid response to '%s' packet", stream.GetData()); 2883 2884 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX); 2885 } 2886 2887 static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response, 2888 uint64_t fail_result, Status &error) { 2889 response.SetFilePos(0); 2890 if (response.GetChar() != 'F') 2891 return fail_result; 2892 int32_t result = response.GetS32(-2); 2893 if (result == -2) 2894 return fail_result; 2895 if (response.GetChar() == ',') { 2896 int result_errno = response.GetS32(-2); 2897 if (result_errno != -2) 2898 error.SetError(result_errno, eErrorTypePOSIX); 2899 else 2900 error.SetError(-1, eErrorTypeGeneric); 2901 } else 2902 error.Clear(); 2903 return result; 2904 } 2905 lldb::user_id_t 2906 GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec, 2907 uint32_t flags, mode_t mode, 2908 Status &error) { 2909 std::string path(file_spec.GetPath(false)); 2910 lldb_private::StreamString stream; 2911 stream.PutCString("vFile:open:"); 2912 if (path.empty()) 2913 return UINT64_MAX; 2914 stream.PutCStringAsRawHex8(path.c_str()); 2915 stream.PutChar(','); 2916 stream.PutHex32(flags); 2917 stream.PutChar(','); 2918 stream.PutHex32(mode); 2919 StringExtractorGDBRemote response; 2920 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2921 PacketResult::Success) { 2922 return ParseHostIOPacketResponse(response, UINT64_MAX, error); 2923 } 2924 return UINT64_MAX; 2925 } 2926 2927 bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd, 2928 Status &error) { 2929 lldb_private::StreamString stream; 2930 stream.Printf("vFile:close:%i", (int)fd); 2931 StringExtractorGDBRemote response; 2932 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2933 PacketResult::Success) { 2934 return ParseHostIOPacketResponse(response, -1, error) == 0; 2935 } 2936 return false; 2937 } 2938 2939 // Extension of host I/O packets to get the file size. 2940 lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize( 2941 const lldb_private::FileSpec &file_spec) { 2942 std::string path(file_spec.GetPath(false)); 2943 lldb_private::StreamString stream; 2944 stream.PutCString("vFile:size:"); 2945 stream.PutCStringAsRawHex8(path.c_str()); 2946 StringExtractorGDBRemote response; 2947 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2948 PacketResult::Success) { 2949 if (response.GetChar() != 'F') 2950 return UINT64_MAX; 2951 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX); 2952 return retcode; 2953 } 2954 return UINT64_MAX; 2955 } 2956 2957 Status 2958 GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec, 2959 uint32_t &file_permissions) { 2960 std::string path{file_spec.GetPath(false)}; 2961 Status error; 2962 lldb_private::StreamString stream; 2963 stream.PutCString("vFile:mode:"); 2964 stream.PutCStringAsRawHex8(path.c_str()); 2965 StringExtractorGDBRemote response; 2966 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2967 PacketResult::Success) { 2968 if (response.GetChar() != 'F') { 2969 error.SetErrorStringWithFormat("invalid response to '%s' packet", 2970 stream.GetData()); 2971 } else { 2972 const uint32_t mode = response.GetS32(-1); 2973 if (static_cast<int32_t>(mode) == -1) { 2974 if (response.GetChar() == ',') { 2975 int response_errno = response.GetS32(-1); 2976 if (response_errno > 0) 2977 error.SetError(response_errno, lldb::eErrorTypePOSIX); 2978 else 2979 error.SetErrorToGenericError(); 2980 } else 2981 error.SetErrorToGenericError(); 2982 } else { 2983 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO); 2984 } 2985 } 2986 } else { 2987 error.SetErrorStringWithFormat("failed to send '%s' packet", 2988 stream.GetData()); 2989 } 2990 return error; 2991 } 2992 2993 uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd, 2994 uint64_t offset, void *dst, 2995 uint64_t dst_len, 2996 Status &error) { 2997 lldb_private::StreamString stream; 2998 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, 2999 offset); 3000 StringExtractorGDBRemote response; 3001 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 3002 PacketResult::Success) { 3003 if (response.GetChar() != 'F') 3004 return 0; 3005 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX); 3006 if (retcode == UINT32_MAX) 3007 return retcode; 3008 const char next = (response.Peek() ? *response.Peek() : 0); 3009 if (next == ',') 3010 return 0; 3011 if (next == ';') { 3012 response.GetChar(); // skip the semicolon 3013 std::string buffer; 3014 if (response.GetEscapedBinaryData(buffer)) { 3015 const uint64_t data_to_write = 3016 std::min<uint64_t>(dst_len, buffer.size()); 3017 if (data_to_write > 0) 3018 memcpy(dst, &buffer[0], data_to_write); 3019 return data_to_write; 3020 } 3021 } 3022 } 3023 return 0; 3024 } 3025 3026 uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd, 3027 uint64_t offset, 3028 const void *src, 3029 uint64_t src_len, 3030 Status &error) { 3031 lldb_private::StreamGDBRemote stream; 3032 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset); 3033 stream.PutEscapedBytes(src, src_len); 3034 StringExtractorGDBRemote response; 3035 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 3036 PacketResult::Success) { 3037 if (response.GetChar() != 'F') { 3038 error.SetErrorStringWithFormat("write file failed"); 3039 return 0; 3040 } 3041 uint64_t bytes_written = response.GetU64(UINT64_MAX); 3042 if (bytes_written == UINT64_MAX) { 3043 error.SetErrorToGenericError(); 3044 if (response.GetChar() == ',') { 3045 int response_errno = response.GetS32(-1); 3046 if (response_errno > 0) 3047 error.SetError(response_errno, lldb::eErrorTypePOSIX); 3048 } 3049 return 0; 3050 } 3051 return bytes_written; 3052 } else { 3053 error.SetErrorString("failed to send vFile:pwrite packet"); 3054 } 3055 return 0; 3056 } 3057 3058 Status GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, 3059 const FileSpec &dst) { 3060 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)}; 3061 Status error; 3062 lldb_private::StreamGDBRemote stream; 3063 stream.PutCString("vFile:symlink:"); 3064 // the unix symlink() command reverses its parameters where the dst if first, 3065 // so we follow suit here 3066 stream.PutCStringAsRawHex8(dst_path.c_str()); 3067 stream.PutChar(','); 3068 stream.PutCStringAsRawHex8(src_path.c_str()); 3069 StringExtractorGDBRemote response; 3070 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 3071 PacketResult::Success) { 3072 if (response.GetChar() == 'F') { 3073 uint32_t result = response.GetU32(UINT32_MAX); 3074 if (result != 0) { 3075 error.SetErrorToGenericError(); 3076 if (response.GetChar() == ',') { 3077 int response_errno = response.GetS32(-1); 3078 if (response_errno > 0) 3079 error.SetError(response_errno, lldb::eErrorTypePOSIX); 3080 } 3081 } 3082 } else { 3083 // Should have returned with 'F<result>[,<errno>]' 3084 error.SetErrorStringWithFormat("symlink failed"); 3085 } 3086 } else { 3087 error.SetErrorString("failed to send vFile:symlink packet"); 3088 } 3089 return error; 3090 } 3091 3092 Status GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) { 3093 std::string path{file_spec.GetPath(false)}; 3094 Status error; 3095 lldb_private::StreamGDBRemote stream; 3096 stream.PutCString("vFile:unlink:"); 3097 // the unix symlink() command reverses its parameters where the dst if first, 3098 // so we follow suit here 3099 stream.PutCStringAsRawHex8(path.c_str()); 3100 StringExtractorGDBRemote response; 3101 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 3102 PacketResult::Success) { 3103 if (response.GetChar() == 'F') { 3104 uint32_t result = response.GetU32(UINT32_MAX); 3105 if (result != 0) { 3106 error.SetErrorToGenericError(); 3107 if (response.GetChar() == ',') { 3108 int response_errno = response.GetS32(-1); 3109 if (response_errno > 0) 3110 error.SetError(response_errno, lldb::eErrorTypePOSIX); 3111 } 3112 } 3113 } else { 3114 // Should have returned with 'F<result>[,<errno>]' 3115 error.SetErrorStringWithFormat("unlink failed"); 3116 } 3117 } else { 3118 error.SetErrorString("failed to send vFile:unlink packet"); 3119 } 3120 return error; 3121 } 3122 3123 // Extension of host I/O packets to get whether a file exists. 3124 bool GDBRemoteCommunicationClient::GetFileExists( 3125 const lldb_private::FileSpec &file_spec) { 3126 std::string path(file_spec.GetPath(false)); 3127 lldb_private::StreamString stream; 3128 stream.PutCString("vFile:exists:"); 3129 stream.PutCStringAsRawHex8(path.c_str()); 3130 StringExtractorGDBRemote response; 3131 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 3132 PacketResult::Success) { 3133 if (response.GetChar() != 'F') 3134 return false; 3135 if (response.GetChar() != ',') 3136 return false; 3137 bool retcode = (response.GetChar() != '0'); 3138 return retcode; 3139 } 3140 return false; 3141 } 3142 3143 bool GDBRemoteCommunicationClient::CalculateMD5( 3144 const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) { 3145 std::string path(file_spec.GetPath(false)); 3146 lldb_private::StreamString stream; 3147 stream.PutCString("vFile:MD5:"); 3148 stream.PutCStringAsRawHex8(path.c_str()); 3149 StringExtractorGDBRemote response; 3150 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 3151 PacketResult::Success) { 3152 if (response.GetChar() != 'F') 3153 return false; 3154 if (response.GetChar() != ',') 3155 return false; 3156 if (response.Peek() && *response.Peek() == 'x') 3157 return false; 3158 low = response.GetHexMaxU64(false, UINT64_MAX); 3159 high = response.GetHexMaxU64(false, UINT64_MAX); 3160 return true; 3161 } 3162 return false; 3163 } 3164 3165 bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) { 3166 // Some targets have issues with g/G packets and we need to avoid using them 3167 if (m_avoid_g_packets == eLazyBoolCalculate) { 3168 if (process) { 3169 m_avoid_g_packets = eLazyBoolNo; 3170 const ArchSpec &arch = process->GetTarget().GetArchitecture(); 3171 if (arch.IsValid() && 3172 arch.GetTriple().getVendor() == llvm::Triple::Apple && 3173 arch.GetTriple().getOS() == llvm::Triple::IOS && 3174 arch.GetTriple().getArch() == llvm::Triple::aarch64) { 3175 m_avoid_g_packets = eLazyBoolYes; 3176 uint32_t gdb_server_version = GetGDBServerProgramVersion(); 3177 if (gdb_server_version != 0) { 3178 const char *gdb_server_name = GetGDBServerProgramName(); 3179 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) { 3180 if (gdb_server_version >= 310) 3181 m_avoid_g_packets = eLazyBoolNo; 3182 } 3183 } 3184 } 3185 } 3186 } 3187 return m_avoid_g_packets == eLazyBoolYes; 3188 } 3189 3190 DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, 3191 uint32_t reg) { 3192 StreamString payload; 3193 payload.Printf("p%x", reg); 3194 StringExtractorGDBRemote response; 3195 if (SendThreadSpecificPacketAndWaitForResponse( 3196 tid, std::move(payload), response, false) != PacketResult::Success || 3197 !response.IsNormalResponse()) 3198 return nullptr; 3199 3200 DataBufferSP buffer_sp( 3201 new DataBufferHeap(response.GetStringRef().size() / 2, 0)); 3202 response.GetHexBytes(buffer_sp->GetData(), '\xcc'); 3203 return buffer_sp; 3204 } 3205 3206 DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) { 3207 StreamString payload; 3208 payload.PutChar('g'); 3209 StringExtractorGDBRemote response; 3210 if (SendThreadSpecificPacketAndWaitForResponse( 3211 tid, std::move(payload), response, false) != PacketResult::Success || 3212 !response.IsNormalResponse()) 3213 return nullptr; 3214 3215 DataBufferSP buffer_sp( 3216 new DataBufferHeap(response.GetStringRef().size() / 2, 0)); 3217 response.GetHexBytes(buffer_sp->GetData(), '\xcc'); 3218 return buffer_sp; 3219 } 3220 3221 bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid, 3222 uint32_t reg_num, 3223 llvm::ArrayRef<uint8_t> data) { 3224 StreamString payload; 3225 payload.Printf("P%x=", reg_num); 3226 payload.PutBytesAsRawHex8(data.data(), data.size(), 3227 endian::InlHostByteOrder(), 3228 endian::InlHostByteOrder()); 3229 StringExtractorGDBRemote response; 3230 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), 3231 response, false) == 3232 PacketResult::Success && 3233 response.IsOKResponse(); 3234 } 3235 3236 bool GDBRemoteCommunicationClient::WriteAllRegisters( 3237 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) { 3238 StreamString payload; 3239 payload.PutChar('G'); 3240 payload.PutBytesAsRawHex8(data.data(), data.size(), 3241 endian::InlHostByteOrder(), 3242 endian::InlHostByteOrder()); 3243 StringExtractorGDBRemote response; 3244 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), 3245 response, false) == 3246 PacketResult::Success && 3247 response.IsOKResponse(); 3248 } 3249 3250 bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid, 3251 uint32_t &save_id) { 3252 save_id = 0; // Set to invalid save ID 3253 if (m_supports_QSaveRegisterState == eLazyBoolNo) 3254 return false; 3255 3256 m_supports_QSaveRegisterState = eLazyBoolYes; 3257 StreamString payload; 3258 payload.PutCString("QSaveRegisterState"); 3259 StringExtractorGDBRemote response; 3260 if (SendThreadSpecificPacketAndWaitForResponse( 3261 tid, std::move(payload), response, false) != PacketResult::Success) 3262 return false; 3263 3264 if (response.IsUnsupportedResponse()) 3265 m_supports_QSaveRegisterState = eLazyBoolNo; 3266 3267 const uint32_t response_save_id = response.GetU32(0); 3268 if (response_save_id == 0) 3269 return false; 3270 3271 save_id = response_save_id; 3272 return true; 3273 } 3274 3275 bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid, 3276 uint32_t save_id) { 3277 // We use the "m_supports_QSaveRegisterState" variable here because the 3278 // QSaveRegisterState and QRestoreRegisterState packets must both be 3279 // supported in order to be useful 3280 if (m_supports_QSaveRegisterState == eLazyBoolNo) 3281 return false; 3282 3283 StreamString payload; 3284 payload.Printf("QRestoreRegisterState:%u", save_id); 3285 StringExtractorGDBRemote response; 3286 if (SendThreadSpecificPacketAndWaitForResponse( 3287 tid, std::move(payload), response, false) != PacketResult::Success) 3288 return false; 3289 3290 if (response.IsOKResponse()) 3291 return true; 3292 3293 if (response.IsUnsupportedResponse()) 3294 m_supports_QSaveRegisterState = eLazyBoolNo; 3295 return false; 3296 } 3297 3298 bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) { 3299 if (!GetSyncThreadStateSupported()) 3300 return false; 3301 3302 StreamString packet; 3303 StringExtractorGDBRemote response; 3304 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid); 3305 return SendPacketAndWaitForResponse(packet.GetString(), response, false) == 3306 GDBRemoteCommunication::PacketResult::Success && 3307 response.IsOKResponse(); 3308 } 3309 3310 lldb::user_id_t 3311 GDBRemoteCommunicationClient::SendStartTracePacket(const TraceOptions &options, 3312 Status &error) { 3313 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3314 lldb::user_id_t ret_uid = LLDB_INVALID_UID; 3315 3316 StreamGDBRemote escaped_packet; 3317 escaped_packet.PutCString("jTraceStart:"); 3318 3319 StructuredData::Dictionary json_packet; 3320 json_packet.AddIntegerItem("type", options.getType()); 3321 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize()); 3322 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize()); 3323 3324 if (options.getThreadID() != LLDB_INVALID_THREAD_ID) 3325 json_packet.AddIntegerItem("threadid", options.getThreadID()); 3326 3327 StructuredData::DictionarySP custom_params = options.getTraceParams(); 3328 if (custom_params) 3329 json_packet.AddItem("params", custom_params); 3330 3331 StreamString json_string; 3332 json_packet.Dump(json_string, false); 3333 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize()); 3334 3335 StringExtractorGDBRemote response; 3336 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response, 3337 true) == 3338 GDBRemoteCommunication::PacketResult::Success) { 3339 if (!response.IsNormalResponse()) { 3340 error = response.GetStatus(); 3341 LLDB_LOG(log, "Target does not support Tracing , error {0}", error); 3342 } else { 3343 ret_uid = response.GetHexMaxU64(false, LLDB_INVALID_UID); 3344 } 3345 } else { 3346 LLDB_LOG(log, "failed to send packet"); 3347 error.SetErrorStringWithFormat("failed to send packet: '%s'", 3348 escaped_packet.GetData()); 3349 } 3350 return ret_uid; 3351 } 3352 3353 Status 3354 GDBRemoteCommunicationClient::SendStopTracePacket(lldb::user_id_t uid, 3355 lldb::tid_t thread_id) { 3356 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3357 StringExtractorGDBRemote response; 3358 Status error; 3359 3360 StructuredData::Dictionary json_packet; 3361 StreamGDBRemote escaped_packet; 3362 StreamString json_string; 3363 escaped_packet.PutCString("jTraceStop:"); 3364 3365 json_packet.AddIntegerItem("traceid", uid); 3366 3367 if (thread_id != LLDB_INVALID_THREAD_ID) 3368 json_packet.AddIntegerItem("threadid", thread_id); 3369 3370 json_packet.Dump(json_string, false); 3371 3372 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize()); 3373 3374 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response, 3375 true) == 3376 GDBRemoteCommunication::PacketResult::Success) { 3377 if (!response.IsOKResponse()) { 3378 error = response.GetStatus(); 3379 LLDB_LOG(log, "stop tracing failed"); 3380 } 3381 } else { 3382 LLDB_LOG(log, "failed to send packet"); 3383 error.SetErrorStringWithFormat( 3384 "failed to send packet: '%s' with error '%d'", escaped_packet.GetData(), 3385 response.GetError()); 3386 } 3387 return error; 3388 } 3389 3390 Status GDBRemoteCommunicationClient::SendGetDataPacket( 3391 lldb::user_id_t uid, lldb::tid_t thread_id, 3392 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) { 3393 3394 StreamGDBRemote escaped_packet; 3395 escaped_packet.PutCString("jTraceBufferRead:"); 3396 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset); 3397 } 3398 3399 Status GDBRemoteCommunicationClient::SendGetMetaDataPacket( 3400 lldb::user_id_t uid, lldb::tid_t thread_id, 3401 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) { 3402 3403 StreamGDBRemote escaped_packet; 3404 escaped_packet.PutCString("jTraceMetaRead:"); 3405 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset); 3406 } 3407 3408 Status 3409 GDBRemoteCommunicationClient::SendGetTraceConfigPacket(lldb::user_id_t uid, 3410 TraceOptions &options) { 3411 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3412 StringExtractorGDBRemote response; 3413 Status error; 3414 3415 StreamString json_string; 3416 StreamGDBRemote escaped_packet; 3417 escaped_packet.PutCString("jTraceConfigRead:"); 3418 3419 StructuredData::Dictionary json_packet; 3420 json_packet.AddIntegerItem("traceid", uid); 3421 3422 if (options.getThreadID() != LLDB_INVALID_THREAD_ID) 3423 json_packet.AddIntegerItem("threadid", options.getThreadID()); 3424 3425 json_packet.Dump(json_string, false); 3426 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize()); 3427 3428 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response, 3429 true) == 3430 GDBRemoteCommunication::PacketResult::Success) { 3431 if (response.IsNormalResponse()) { 3432 uint64_t type = std::numeric_limits<uint64_t>::max(); 3433 uint64_t buffersize = std::numeric_limits<uint64_t>::max(); 3434 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max(); 3435 3436 auto json_object = StructuredData::ParseJSON(response.Peek()); 3437 3438 if (!json_object || 3439 json_object->GetType() != lldb::eStructuredDataTypeDictionary) { 3440 error.SetErrorString("Invalid Configuration obtained"); 3441 return error; 3442 } 3443 3444 auto json_dict = json_object->GetAsDictionary(); 3445 3446 json_dict->GetValueForKeyAsInteger<uint64_t>("metabuffersize", 3447 metabuffersize); 3448 options.setMetaDataBufferSize(metabuffersize); 3449 3450 json_dict->GetValueForKeyAsInteger<uint64_t>("buffersize", buffersize); 3451 options.setTraceBufferSize(buffersize); 3452 3453 json_dict->GetValueForKeyAsInteger<uint64_t>("type", type); 3454 options.setType(static_cast<lldb::TraceType>(type)); 3455 3456 StructuredData::ObjectSP custom_params_sp = 3457 json_dict->GetValueForKey("params"); 3458 if (custom_params_sp) { 3459 if (custom_params_sp->GetType() != 3460 lldb::eStructuredDataTypeDictionary) { 3461 error.SetErrorString("Invalid Configuration obtained"); 3462 return error; 3463 } else 3464 options.setTraceParams( 3465 static_pointer_cast<StructuredData::Dictionary>( 3466 custom_params_sp)); 3467 } 3468 } else { 3469 error = response.GetStatus(); 3470 } 3471 } else { 3472 LLDB_LOG(log, "failed to send packet"); 3473 error.SetErrorStringWithFormat("failed to send packet: '%s'", 3474 escaped_packet.GetData()); 3475 } 3476 return error; 3477 } 3478 3479 Status GDBRemoteCommunicationClient::SendGetTraceDataPacket( 3480 StreamGDBRemote &packet, lldb::user_id_t uid, lldb::tid_t thread_id, 3481 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) { 3482 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3483 Status error; 3484 3485 StructuredData::Dictionary json_packet; 3486 3487 json_packet.AddIntegerItem("traceid", uid); 3488 json_packet.AddIntegerItem("offset", offset); 3489 json_packet.AddIntegerItem("buffersize", buffer.size()); 3490 3491 if (thread_id != LLDB_INVALID_THREAD_ID) 3492 json_packet.AddIntegerItem("threadid", thread_id); 3493 3494 StreamString json_string; 3495 json_packet.Dump(json_string, false); 3496 3497 packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize()); 3498 StringExtractorGDBRemote response; 3499 if (SendPacketAndWaitForResponse(packet.GetString(), response, true) == 3500 GDBRemoteCommunication::PacketResult::Success) { 3501 if (response.IsNormalResponse()) { 3502 size_t filled_size = response.GetHexBytesAvail(buffer); 3503 buffer = llvm::MutableArrayRef<uint8_t>(buffer.data(), filled_size); 3504 } else { 3505 error = response.GetStatus(); 3506 buffer = buffer.slice(buffer.size()); 3507 } 3508 } else { 3509 LLDB_LOG(log, "failed to send packet"); 3510 error.SetErrorStringWithFormat("failed to send packet: '%s'", 3511 packet.GetData()); 3512 buffer = buffer.slice(buffer.size()); 3513 } 3514 return error; 3515 } 3516 3517 bool GDBRemoteCommunicationClient::GetModuleInfo( 3518 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec, 3519 ModuleSpec &module_spec) { 3520 if (!m_supports_qModuleInfo) 3521 return false; 3522 3523 std::string module_path = module_file_spec.GetPath(false); 3524 if (module_path.empty()) 3525 return false; 3526 3527 StreamString packet; 3528 packet.PutCString("qModuleInfo:"); 3529 packet.PutCStringAsRawHex8(module_path.c_str()); 3530 packet.PutCString(";"); 3531 const auto &triple = arch_spec.GetTriple().getTriple(); 3532 packet.PutCStringAsRawHex8(triple.c_str()); 3533 3534 StringExtractorGDBRemote response; 3535 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) != 3536 PacketResult::Success) 3537 return false; 3538 3539 if (response.IsErrorResponse()) 3540 return false; 3541 3542 if (response.IsUnsupportedResponse()) { 3543 m_supports_qModuleInfo = false; 3544 return false; 3545 } 3546 3547 llvm::StringRef name; 3548 llvm::StringRef value; 3549 3550 module_spec.Clear(); 3551 module_spec.GetFileSpec() = module_file_spec; 3552 3553 while (response.GetNameColonValue(name, value)) { 3554 if (name == "uuid" || name == "md5") { 3555 StringExtractor extractor(value); 3556 std::string uuid; 3557 extractor.GetHexByteString(uuid); 3558 module_spec.GetUUID().SetFromCString(uuid.c_str(), uuid.size() / 2); 3559 } else if (name == "triple") { 3560 StringExtractor extractor(value); 3561 std::string triple; 3562 extractor.GetHexByteString(triple); 3563 module_spec.GetArchitecture().SetTriple(triple.c_str()); 3564 } else if (name == "file_offset") { 3565 uint64_t ival = 0; 3566 if (!value.getAsInteger(16, ival)) 3567 module_spec.SetObjectOffset(ival); 3568 } else if (name == "file_size") { 3569 uint64_t ival = 0; 3570 if (!value.getAsInteger(16, ival)) 3571 module_spec.SetObjectSize(ival); 3572 } else if (name == "file_path") { 3573 StringExtractor extractor(value); 3574 std::string path; 3575 extractor.GetHexByteString(path); 3576 module_spec.GetFileSpec() = FileSpec(path, false, arch_spec.GetTriple()); 3577 } 3578 } 3579 3580 return true; 3581 } 3582 3583 static llvm::Optional<ModuleSpec> 3584 ParseModuleSpec(StructuredData::Dictionary *dict) { 3585 ModuleSpec result; 3586 if (!dict) 3587 return llvm::None; 3588 3589 llvm::StringRef string; 3590 uint64_t integer; 3591 3592 if (!dict->GetValueForKeyAsString("uuid", string)) 3593 return llvm::None; 3594 if (result.GetUUID().SetFromStringRef(string, string.size() / 2) != 3595 string.size()) 3596 return llvm::None; 3597 3598 if (!dict->GetValueForKeyAsInteger("file_offset", integer)) 3599 return llvm::None; 3600 result.SetObjectOffset(integer); 3601 3602 if (!dict->GetValueForKeyAsInteger("file_size", integer)) 3603 return llvm::None; 3604 result.SetObjectSize(integer); 3605 3606 if (!dict->GetValueForKeyAsString("triple", string)) 3607 return llvm::None; 3608 result.GetArchitecture().SetTriple(string); 3609 3610 if (!dict->GetValueForKeyAsString("file_path", string)) 3611 return llvm::None; 3612 result.GetFileSpec() = 3613 FileSpec(string, false, result.GetArchitecture().GetTriple()); 3614 3615 return result; 3616 } 3617 3618 llvm::Optional<std::vector<ModuleSpec>> 3619 GDBRemoteCommunicationClient::GetModulesInfo( 3620 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) { 3621 if (!m_supports_jModulesInfo) 3622 return llvm::None; 3623 3624 JSONArray::SP module_array_sp = std::make_shared<JSONArray>(); 3625 for (const FileSpec &module_file_spec : module_file_specs) { 3626 JSONObject::SP module_sp = std::make_shared<JSONObject>(); 3627 module_array_sp->AppendObject(module_sp); 3628 module_sp->SetObject( 3629 "file", std::make_shared<JSONString>(module_file_spec.GetPath(false))); 3630 module_sp->SetObject("triple", 3631 std::make_shared<JSONString>(triple.getTriple())); 3632 } 3633 StreamString unescaped_payload; 3634 unescaped_payload.PutCString("jModulesInfo:"); 3635 module_array_sp->Write(unescaped_payload); 3636 StreamGDBRemote payload; 3637 payload.PutEscapedBytes(unescaped_payload.GetString().data(), 3638 unescaped_payload.GetSize()); 3639 3640 // Increase the timeout for jModulesInfo since this packet can take longer. 3641 ScopedTimeout timeout(*this, std::chrono::seconds(10)); 3642 3643 StringExtractorGDBRemote response; 3644 if (SendPacketAndWaitForResponse(payload.GetString(), response, false) != 3645 PacketResult::Success || 3646 response.IsErrorResponse()) 3647 return llvm::None; 3648 3649 if (response.IsUnsupportedResponse()) { 3650 m_supports_jModulesInfo = false; 3651 return llvm::None; 3652 } 3653 3654 StructuredData::ObjectSP response_object_sp = 3655 StructuredData::ParseJSON(response.GetStringRef()); 3656 if (!response_object_sp) 3657 return llvm::None; 3658 3659 StructuredData::Array *response_array = response_object_sp->GetAsArray(); 3660 if (!response_array) 3661 return llvm::None; 3662 3663 std::vector<ModuleSpec> result; 3664 for (size_t i = 0; i < response_array->GetSize(); ++i) { 3665 if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec( 3666 response_array->GetItemAtIndex(i)->GetAsDictionary())) 3667 result.push_back(*module_spec); 3668 } 3669 3670 return result; 3671 } 3672 3673 // query the target remote for extended information using the qXfer packet 3674 // 3675 // example: object='features', annex='target.xml', out=<xml output> return: 3676 // 'true' on success 3677 // 'false' on failure (err set) 3678 bool GDBRemoteCommunicationClient::ReadExtFeature( 3679 const lldb_private::ConstString object, 3680 const lldb_private::ConstString annex, std::string &out, 3681 lldb_private::Status &err) { 3682 3683 std::stringstream output; 3684 StringExtractorGDBRemote chunk; 3685 3686 uint64_t size = GetRemoteMaxPacketSize(); 3687 if (size == 0) 3688 size = 0x1000; 3689 size = size - 1; // Leave space for the 'm' or 'l' character in the response 3690 int offset = 0; 3691 bool active = true; 3692 3693 // loop until all data has been read 3694 while (active) { 3695 3696 // send query extended feature packet 3697 std::stringstream packet; 3698 packet << "qXfer:" << object.AsCString("") 3699 << ":read:" << annex.AsCString("") << ":" << std::hex << offset 3700 << "," << std::hex << size; 3701 3702 GDBRemoteCommunication::PacketResult res = 3703 SendPacketAndWaitForResponse(packet.str(), chunk, false); 3704 3705 if (res != GDBRemoteCommunication::PacketResult::Success) { 3706 err.SetErrorString("Error sending $qXfer packet"); 3707 return false; 3708 } 3709 3710 const std::string &str = chunk.GetStringRef(); 3711 if (str.length() == 0) { 3712 // should have some data in chunk 3713 err.SetErrorString("Empty response from $qXfer packet"); 3714 return false; 3715 } 3716 3717 // check packet code 3718 switch (str[0]) { 3719 // last chunk 3720 case ('l'): 3721 active = false; 3722 LLVM_FALLTHROUGH; 3723 3724 // more chunks 3725 case ('m'): 3726 if (str.length() > 1) 3727 output << &str[1]; 3728 offset += size; 3729 break; 3730 3731 // unknown chunk 3732 default: 3733 err.SetErrorString("Invalid continuation code from $qXfer packet"); 3734 return false; 3735 } 3736 } 3737 3738 out = output.str(); 3739 err.Success(); 3740 return true; 3741 } 3742 3743 // Notify the target that gdb is prepared to serve symbol lookup requests. 3744 // packet: "qSymbol::" 3745 // reply: 3746 // OK The target does not need to look up any (more) symbols. 3747 // qSymbol:<sym_name> The target requests the value of symbol sym_name (hex 3748 // encoded). 3749 // LLDB may provide the value by sending another qSymbol 3750 // packet 3751 // in the form of"qSymbol:<sym_value>:<sym_name>". 3752 // 3753 // Three examples: 3754 // 3755 // lldb sends: qSymbol:: 3756 // lldb receives: OK 3757 // Remote gdb stub does not need to know the addresses of any symbols, lldb 3758 // does not 3759 // need to ask again in this session. 3760 // 3761 // lldb sends: qSymbol:: 3762 // lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473 3763 // lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473 3764 // lldb receives: OK 3765 // Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does 3766 // not know 3767 // the address at this time. lldb needs to send qSymbol:: again when it has 3768 // more 3769 // solibs loaded. 3770 // 3771 // lldb sends: qSymbol:: 3772 // lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473 3773 // lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473 3774 // lldb receives: OK 3775 // Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says 3776 // that it 3777 // is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it 3778 // does not 3779 // need any more symbols. lldb does not need to ask again in this session. 3780 3781 void GDBRemoteCommunicationClient::ServeSymbolLookups( 3782 lldb_private::Process *process) { 3783 // Set to true once we've resolved a symbol to an address for the remote 3784 // stub. If we get an 'OK' response after this, the remote stub doesn't need 3785 // any more symbols and we can stop asking. 3786 bool symbol_response_provided = false; 3787 3788 // Is this the initial qSymbol:: packet? 3789 bool first_qsymbol_query = true; 3790 3791 if (m_supports_qSymbol && m_qSymbol_requests_done == false) { 3792 Lock lock(*this, false); 3793 if (lock) { 3794 StreamString packet; 3795 packet.PutCString("qSymbol::"); 3796 StringExtractorGDBRemote response; 3797 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) == 3798 PacketResult::Success) { 3799 if (response.IsOKResponse()) { 3800 if (symbol_response_provided || first_qsymbol_query) { 3801 m_qSymbol_requests_done = true; 3802 } 3803 3804 // We are done serving symbols requests 3805 return; 3806 } 3807 first_qsymbol_query = false; 3808 3809 if (response.IsUnsupportedResponse()) { 3810 // qSymbol is not supported by the current GDB server we are 3811 // connected to 3812 m_supports_qSymbol = false; 3813 return; 3814 } else { 3815 llvm::StringRef response_str(response.GetStringRef()); 3816 if (response_str.startswith("qSymbol:")) { 3817 response.SetFilePos(strlen("qSymbol:")); 3818 std::string symbol_name; 3819 if (response.GetHexByteString(symbol_name)) { 3820 if (symbol_name.empty()) 3821 return; 3822 3823 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS; 3824 lldb_private::SymbolContextList sc_list; 3825 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType( 3826 ConstString(symbol_name), eSymbolTypeAny, sc_list)) { 3827 const size_t num_scs = sc_list.GetSize(); 3828 for (size_t sc_idx = 0; 3829 sc_idx < num_scs && 3830 symbol_load_addr == LLDB_INVALID_ADDRESS; 3831 ++sc_idx) { 3832 SymbolContext sc; 3833 if (sc_list.GetContextAtIndex(sc_idx, sc)) { 3834 if (sc.symbol) { 3835 switch (sc.symbol->GetType()) { 3836 case eSymbolTypeInvalid: 3837 case eSymbolTypeAbsolute: 3838 case eSymbolTypeUndefined: 3839 case eSymbolTypeSourceFile: 3840 case eSymbolTypeHeaderFile: 3841 case eSymbolTypeObjectFile: 3842 case eSymbolTypeCommonBlock: 3843 case eSymbolTypeBlock: 3844 case eSymbolTypeLocal: 3845 case eSymbolTypeParam: 3846 case eSymbolTypeVariable: 3847 case eSymbolTypeVariableType: 3848 case eSymbolTypeLineEntry: 3849 case eSymbolTypeLineHeader: 3850 case eSymbolTypeScopeBegin: 3851 case eSymbolTypeScopeEnd: 3852 case eSymbolTypeAdditional: 3853 case eSymbolTypeCompiler: 3854 case eSymbolTypeInstrumentation: 3855 case eSymbolTypeTrampoline: 3856 break; 3857 3858 case eSymbolTypeCode: 3859 case eSymbolTypeResolver: 3860 case eSymbolTypeData: 3861 case eSymbolTypeRuntime: 3862 case eSymbolTypeException: 3863 case eSymbolTypeObjCClass: 3864 case eSymbolTypeObjCMetaClass: 3865 case eSymbolTypeObjCIVar: 3866 case eSymbolTypeReExported: 3867 symbol_load_addr = 3868 sc.symbol->GetLoadAddress(&process->GetTarget()); 3869 break; 3870 } 3871 } 3872 } 3873 } 3874 } 3875 // This is the normal path where our symbol lookup was successful 3876 // and we want to send a packet with the new symbol value and see 3877 // if another lookup needs to be done. 3878 3879 // Change "packet" to contain the requested symbol value and name 3880 packet.Clear(); 3881 packet.PutCString("qSymbol:"); 3882 if (symbol_load_addr != LLDB_INVALID_ADDRESS) { 3883 packet.Printf("%" PRIx64, symbol_load_addr); 3884 symbol_response_provided = true; 3885 } else { 3886 symbol_response_provided = false; 3887 } 3888 packet.PutCString(":"); 3889 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size()); 3890 continue; // go back to the while loop and send "packet" and wait 3891 // for another response 3892 } 3893 } 3894 } 3895 } 3896 // If we make it here, the symbol request packet response wasn't valid or 3897 // our symbol lookup failed so we must abort 3898 return; 3899 3900 } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet( 3901 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) { 3902 log->Printf( 3903 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.", 3904 __FUNCTION__); 3905 } 3906 } 3907 } 3908 3909 StructuredData::Array * 3910 GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() { 3911 if (!m_supported_async_json_packets_is_valid) { 3912 // Query the server for the array of supported asynchronous JSON packets. 3913 m_supported_async_json_packets_is_valid = true; 3914 3915 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3916 3917 // Poll it now. 3918 StringExtractorGDBRemote response; 3919 const bool send_async = false; 3920 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response, 3921 send_async) == PacketResult::Success) { 3922 m_supported_async_json_packets_sp = 3923 StructuredData::ParseJSON(response.GetStringRef()); 3924 if (m_supported_async_json_packets_sp && 3925 !m_supported_async_json_packets_sp->GetAsArray()) { 3926 // We were returned something other than a JSON array. This is 3927 // invalid. Clear it out. 3928 if (log) 3929 log->Printf("GDBRemoteCommunicationClient::%s(): " 3930 "QSupportedAsyncJSONPackets returned invalid " 3931 "result: %s", 3932 __FUNCTION__, response.GetStringRef().c_str()); 3933 m_supported_async_json_packets_sp.reset(); 3934 } 3935 } else { 3936 if (log) 3937 log->Printf("GDBRemoteCommunicationClient::%s(): " 3938 "QSupportedAsyncJSONPackets unsupported", 3939 __FUNCTION__); 3940 } 3941 3942 if (log && m_supported_async_json_packets_sp) { 3943 StreamString stream; 3944 m_supported_async_json_packets_sp->Dump(stream); 3945 log->Printf("GDBRemoteCommunicationClient::%s(): supported async " 3946 "JSON packets: %s", 3947 __FUNCTION__, stream.GetData()); 3948 } 3949 } 3950 3951 return m_supported_async_json_packets_sp 3952 ? m_supported_async_json_packets_sp->GetAsArray() 3953 : nullptr; 3954 } 3955 3956 Status GDBRemoteCommunicationClient::SendSignalsToIgnore( 3957 llvm::ArrayRef<int32_t> signals) { 3958 // Format packet: 3959 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN> 3960 auto range = llvm::make_range(signals.begin(), signals.end()); 3961 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str(); 3962 3963 StringExtractorGDBRemote response; 3964 auto send_status = SendPacketAndWaitForResponse(packet, response, false); 3965 3966 if (send_status != GDBRemoteCommunication::PacketResult::Success) 3967 return Status("Sending QPassSignals packet failed"); 3968 3969 if (response.IsOKResponse()) { 3970 return Status(); 3971 } else { 3972 return Status("Unknown error happened during sending QPassSignals packet."); 3973 } 3974 } 3975 3976 Status GDBRemoteCommunicationClient::ConfigureRemoteStructuredData( 3977 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) { 3978 Status error; 3979 3980 if (type_name.GetLength() == 0) { 3981 error.SetErrorString("invalid type_name argument"); 3982 return error; 3983 } 3984 3985 // Build command: Configure{type_name}: serialized config data. 3986 StreamGDBRemote stream; 3987 stream.PutCString("QConfigure"); 3988 stream.PutCString(type_name.AsCString()); 3989 stream.PutChar(':'); 3990 if (config_sp) { 3991 // Gather the plain-text version of the configuration data. 3992 StreamString unescaped_stream; 3993 config_sp->Dump(unescaped_stream); 3994 unescaped_stream.Flush(); 3995 3996 // Add it to the stream in escaped fashion. 3997 stream.PutEscapedBytes(unescaped_stream.GetString().data(), 3998 unescaped_stream.GetSize()); 3999 } 4000 stream.Flush(); 4001 4002 // Send the packet. 4003 const bool send_async = false; 4004 StringExtractorGDBRemote response; 4005 auto result = 4006 SendPacketAndWaitForResponse(stream.GetString(), response, send_async); 4007 if (result == PacketResult::Success) { 4008 // We failed if the config result comes back other than OK. 4009 if (strcmp(response.GetStringRef().c_str(), "OK") == 0) { 4010 // Okay! 4011 error.Clear(); 4012 } else { 4013 error.SetErrorStringWithFormat("configuring StructuredData feature " 4014 "%s failed with error %s", 4015 type_name.AsCString(), 4016 response.GetStringRef().c_str()); 4017 } 4018 } else { 4019 // Can we get more data here on the failure? 4020 error.SetErrorStringWithFormat("configuring StructuredData feature %s " 4021 "failed when sending packet: " 4022 "PacketResult=%d", 4023 type_name.AsCString(), (int)result); 4024 } 4025 return error; 4026 } 4027 4028 void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) { 4029 GDBRemoteClientBase::OnRunPacketSent(first); 4030 m_curr_tid = LLDB_INVALID_THREAD_ID; 4031 } 4032