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 } else if (name.equals("cputype")) { 1944 value.getAsInteger(0, cpu); 1945 } else if (name.equals("cpusubtype")) { 1946 value.getAsInteger(0, sub); 1947 } else if (name.equals("vendor")) { 1948 vendor = value; 1949 } else if (name.equals("ostype")) { 1950 os_type = value; 1951 } 1952 } 1953 1954 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) { 1955 if (vendor == "apple") { 1956 process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu, 1957 sub); 1958 process_info.GetArchitecture().GetTriple().setVendorName( 1959 llvm::StringRef(vendor)); 1960 process_info.GetArchitecture().GetTriple().setOSName( 1961 llvm::StringRef(os_type)); 1962 } 1963 } 1964 1965 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) 1966 return true; 1967 } 1968 return false; 1969 } 1970 1971 bool GDBRemoteCommunicationClient::GetProcessInfo( 1972 lldb::pid_t pid, ProcessInstanceInfo &process_info) { 1973 process_info.Clear(); 1974 1975 if (m_supports_qProcessInfoPID) { 1976 char packet[32]; 1977 const int packet_len = 1978 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid); 1979 assert(packet_len < (int)sizeof(packet)); 1980 UNUSED_IF_ASSERT_DISABLED(packet_len); 1981 StringExtractorGDBRemote response; 1982 if (SendPacketAndWaitForResponse(packet, response, false) == 1983 PacketResult::Success) { 1984 return DecodeProcessInfoResponse(response, process_info); 1985 } else { 1986 m_supports_qProcessInfoPID = false; 1987 return false; 1988 } 1989 } 1990 return false; 1991 } 1992 1993 bool GDBRemoteCommunicationClient::GetCurrentProcessInfo(bool allow_lazy) { 1994 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS | 1995 GDBR_LOG_PACKETS)); 1996 1997 if (allow_lazy) { 1998 if (m_qProcessInfo_is_valid == eLazyBoolYes) 1999 return true; 2000 if (m_qProcessInfo_is_valid == eLazyBoolNo) 2001 return false; 2002 } 2003 2004 GetHostInfo(); 2005 2006 StringExtractorGDBRemote response; 2007 if (SendPacketAndWaitForResponse("qProcessInfo", response, false) == 2008 PacketResult::Success) { 2009 if (response.IsNormalResponse()) { 2010 llvm::StringRef name; 2011 llvm::StringRef value; 2012 uint32_t cpu = LLDB_INVALID_CPUTYPE; 2013 uint32_t sub = 0; 2014 std::string arch_name; 2015 std::string os_name; 2016 std::string vendor_name; 2017 std::string triple; 2018 std::string elf_abi; 2019 uint32_t pointer_byte_size = 0; 2020 StringExtractor extractor; 2021 ByteOrder byte_order = eByteOrderInvalid; 2022 uint32_t num_keys_decoded = 0; 2023 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; 2024 while (response.GetNameColonValue(name, value)) { 2025 if (name.equals("cputype")) { 2026 if (!value.getAsInteger(16, cpu)) 2027 ++num_keys_decoded; 2028 } else if (name.equals("cpusubtype")) { 2029 if (!value.getAsInteger(16, sub)) 2030 ++num_keys_decoded; 2031 } else if (name.equals("triple")) { 2032 StringExtractor extractor(value); 2033 extractor.GetHexByteString(triple); 2034 ++num_keys_decoded; 2035 } else if (name.equals("ostype")) { 2036 os_name = value; 2037 ++num_keys_decoded; 2038 } else if (name.equals("vendor")) { 2039 vendor_name = value; 2040 ++num_keys_decoded; 2041 } else if (name.equals("endian")) { 2042 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value) 2043 .Case("little", eByteOrderLittle) 2044 .Case("big", eByteOrderBig) 2045 .Case("pdp", eByteOrderPDP) 2046 .Default(eByteOrderInvalid); 2047 if (byte_order != eByteOrderInvalid) 2048 ++num_keys_decoded; 2049 } else if (name.equals("ptrsize")) { 2050 if (!value.getAsInteger(16, pointer_byte_size)) 2051 ++num_keys_decoded; 2052 } else if (name.equals("pid")) { 2053 if (!value.getAsInteger(16, pid)) 2054 ++num_keys_decoded; 2055 } else if (name.equals("elf_abi")) { 2056 elf_abi = value; 2057 ++num_keys_decoded; 2058 } 2059 } 2060 if (num_keys_decoded > 0) 2061 m_qProcessInfo_is_valid = eLazyBoolYes; 2062 if (pid != LLDB_INVALID_PROCESS_ID) { 2063 m_curr_pid_is_valid = eLazyBoolYes; 2064 m_curr_pid = pid; 2065 } 2066 2067 // Set the ArchSpec from the triple if we have it. 2068 if (!triple.empty()) { 2069 m_process_arch.SetTriple(triple.c_str()); 2070 m_process_arch.SetFlags(elf_abi); 2071 if (pointer_byte_size) { 2072 assert(pointer_byte_size == m_process_arch.GetAddressByteSize()); 2073 } 2074 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && 2075 !vendor_name.empty()) { 2076 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name); 2077 2078 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat); 2079 assert(triple.getObjectFormat() != llvm::Triple::Wasm); 2080 switch (triple.getObjectFormat()) { 2081 case llvm::Triple::MachO: 2082 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub); 2083 break; 2084 case llvm::Triple::ELF: 2085 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub); 2086 break; 2087 case llvm::Triple::COFF: 2088 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub); 2089 break; 2090 case llvm::Triple::Wasm: 2091 if (log) 2092 log->Printf("error: not supported target architecture"); 2093 return false; 2094 case llvm::Triple::UnknownObjectFormat: 2095 if (log) 2096 log->Printf("error: failed to determine target architecture"); 2097 return false; 2098 } 2099 2100 if (pointer_byte_size) { 2101 assert(pointer_byte_size == m_process_arch.GetAddressByteSize()); 2102 } 2103 if (byte_order != eByteOrderInvalid) { 2104 assert(byte_order == m_process_arch.GetByteOrder()); 2105 } 2106 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name)); 2107 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name)); 2108 m_host_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name)); 2109 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name)); 2110 } 2111 return true; 2112 } 2113 } else { 2114 m_qProcessInfo_is_valid = eLazyBoolNo; 2115 } 2116 2117 return false; 2118 } 2119 2120 uint32_t GDBRemoteCommunicationClient::FindProcesses( 2121 const ProcessInstanceInfoMatch &match_info, 2122 ProcessInstanceInfoList &process_infos) { 2123 process_infos.Clear(); 2124 2125 if (m_supports_qfProcessInfo) { 2126 StreamString packet; 2127 packet.PutCString("qfProcessInfo"); 2128 if (!match_info.MatchAllProcesses()) { 2129 packet.PutChar(':'); 2130 const char *name = match_info.GetProcessInfo().GetName(); 2131 bool has_name_match = false; 2132 if (name && name[0]) { 2133 has_name_match = true; 2134 NameMatch name_match_type = match_info.GetNameMatchType(); 2135 switch (name_match_type) { 2136 case NameMatch::Ignore: 2137 has_name_match = false; 2138 break; 2139 2140 case NameMatch::Equals: 2141 packet.PutCString("name_match:equals;"); 2142 break; 2143 2144 case NameMatch::Contains: 2145 packet.PutCString("name_match:contains;"); 2146 break; 2147 2148 case NameMatch::StartsWith: 2149 packet.PutCString("name_match:starts_with;"); 2150 break; 2151 2152 case NameMatch::EndsWith: 2153 packet.PutCString("name_match:ends_with;"); 2154 break; 2155 2156 case NameMatch::RegularExpression: 2157 packet.PutCString("name_match:regex;"); 2158 break; 2159 } 2160 if (has_name_match) { 2161 packet.PutCString("name:"); 2162 packet.PutBytesAsRawHex8(name, ::strlen(name)); 2163 packet.PutChar(';'); 2164 } 2165 } 2166 2167 if (match_info.GetProcessInfo().ProcessIDIsValid()) 2168 packet.Printf("pid:%" PRIu64 ";", 2169 match_info.GetProcessInfo().GetProcessID()); 2170 if (match_info.GetProcessInfo().ParentProcessIDIsValid()) 2171 packet.Printf("parent_pid:%" PRIu64 ";", 2172 match_info.GetProcessInfo().GetParentProcessID()); 2173 if (match_info.GetProcessInfo().UserIDIsValid()) 2174 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID()); 2175 if (match_info.GetProcessInfo().GroupIDIsValid()) 2176 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID()); 2177 if (match_info.GetProcessInfo().EffectiveUserIDIsValid()) 2178 packet.Printf("euid:%u;", 2179 match_info.GetProcessInfo().GetEffectiveUserID()); 2180 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid()) 2181 packet.Printf("egid:%u;", 2182 match_info.GetProcessInfo().GetEffectiveGroupID()); 2183 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid()) 2184 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0); 2185 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) { 2186 const ArchSpec &match_arch = 2187 match_info.GetProcessInfo().GetArchitecture(); 2188 const llvm::Triple &triple = match_arch.GetTriple(); 2189 packet.PutCString("triple:"); 2190 packet.PutCString(triple.getTriple()); 2191 packet.PutChar(';'); 2192 } 2193 } 2194 StringExtractorGDBRemote response; 2195 // Increase timeout as the first qfProcessInfo packet takes a long time on 2196 // Android. The value of 1min was arrived at empirically. 2197 ScopedTimeout timeout(*this, minutes(1)); 2198 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) == 2199 PacketResult::Success) { 2200 do { 2201 ProcessInstanceInfo process_info; 2202 if (!DecodeProcessInfoResponse(response, process_info)) 2203 break; 2204 process_infos.Append(process_info); 2205 response.GetStringRef().clear(); 2206 response.SetFilePos(0); 2207 } while (SendPacketAndWaitForResponse("qsProcessInfo", response, false) == 2208 PacketResult::Success); 2209 } else { 2210 m_supports_qfProcessInfo = false; 2211 return 0; 2212 } 2213 } 2214 return process_infos.GetSize(); 2215 } 2216 2217 bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid, 2218 std::string &name) { 2219 if (m_supports_qUserName) { 2220 char packet[32]; 2221 const int packet_len = 2222 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid); 2223 assert(packet_len < (int)sizeof(packet)); 2224 UNUSED_IF_ASSERT_DISABLED(packet_len); 2225 StringExtractorGDBRemote response; 2226 if (SendPacketAndWaitForResponse(packet, response, false) == 2227 PacketResult::Success) { 2228 if (response.IsNormalResponse()) { 2229 // Make sure we parsed the right number of characters. The response is 2230 // the hex encoded user name and should make up the entire packet. If 2231 // there are any non-hex ASCII bytes, the length won't match below.. 2232 if (response.GetHexByteString(name) * 2 == 2233 response.GetStringRef().size()) 2234 return true; 2235 } 2236 } else { 2237 m_supports_qUserName = false; 2238 return false; 2239 } 2240 } 2241 return false; 2242 } 2243 2244 bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid, 2245 std::string &name) { 2246 if (m_supports_qGroupName) { 2247 char packet[32]; 2248 const int packet_len = 2249 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid); 2250 assert(packet_len < (int)sizeof(packet)); 2251 UNUSED_IF_ASSERT_DISABLED(packet_len); 2252 StringExtractorGDBRemote response; 2253 if (SendPacketAndWaitForResponse(packet, response, false) == 2254 PacketResult::Success) { 2255 if (response.IsNormalResponse()) { 2256 // Make sure we parsed the right number of characters. The response is 2257 // the hex encoded group name and should make up the entire packet. If 2258 // there are any non-hex ASCII bytes, the length won't match below.. 2259 if (response.GetHexByteString(name) * 2 == 2260 response.GetStringRef().size()) 2261 return true; 2262 } 2263 } else { 2264 m_supports_qGroupName = false; 2265 return false; 2266 } 2267 } 2268 return false; 2269 } 2270 2271 bool GDBRemoteCommunicationClient::SetNonStopMode(const bool enable) { 2272 // Form non-stop packet request 2273 char packet[32]; 2274 const int packet_len = 2275 ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable); 2276 assert(packet_len < (int)sizeof(packet)); 2277 UNUSED_IF_ASSERT_DISABLED(packet_len); 2278 2279 StringExtractorGDBRemote response; 2280 // Send to target 2281 if (SendPacketAndWaitForResponse(packet, response, false) == 2282 PacketResult::Success) 2283 if (response.IsOKResponse()) 2284 return true; 2285 2286 // Failed or not supported 2287 return false; 2288 } 2289 2290 static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size, 2291 uint32_t recv_size) { 2292 packet.Clear(); 2293 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size); 2294 uint32_t bytes_left = send_size; 2295 while (bytes_left > 0) { 2296 if (bytes_left >= 26) { 2297 packet.PutCString("abcdefghijklmnopqrstuvwxyz"); 2298 bytes_left -= 26; 2299 } else { 2300 packet.Printf("%*.*s;", bytes_left, bytes_left, 2301 "abcdefghijklmnopqrstuvwxyz"); 2302 bytes_left = 0; 2303 } 2304 } 2305 } 2306 2307 duration<float> 2308 calculate_standard_deviation(const std::vector<duration<float>> &v) { 2309 using Dur = duration<float>; 2310 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur()); 2311 Dur mean = sum / v.size(); 2312 float accum = 0; 2313 for (auto d : v) { 2314 float delta = (d - mean).count(); 2315 accum += delta * delta; 2316 }; 2317 2318 return Dur(sqrtf(accum / (v.size() - 1))); 2319 } 2320 2321 void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets, 2322 uint32_t max_send, 2323 uint32_t max_recv, 2324 uint64_t recv_amount, 2325 bool json, Stream &strm) { 2326 uint32_t i; 2327 if (SendSpeedTestPacket(0, 0)) { 2328 StreamString packet; 2329 if (json) 2330 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n " 2331 "\"results\" : [", 2332 num_packets); 2333 else 2334 strm.Printf("Testing sending %u packets of various sizes:\n", 2335 num_packets); 2336 strm.Flush(); 2337 2338 uint32_t result_idx = 0; 2339 uint32_t send_size; 2340 std::vector<duration<float>> packet_times; 2341 2342 for (send_size = 0; send_size <= max_send; 2343 send_size ? send_size *= 2 : send_size = 4) { 2344 for (uint32_t recv_size = 0; recv_size <= max_recv; 2345 recv_size ? recv_size *= 2 : recv_size = 4) { 2346 MakeSpeedTestPacket(packet, send_size, recv_size); 2347 2348 packet_times.clear(); 2349 // Test how long it takes to send 'num_packets' packets 2350 const auto start_time = steady_clock::now(); 2351 for (i = 0; i < num_packets; ++i) { 2352 const auto packet_start_time = steady_clock::now(); 2353 StringExtractorGDBRemote response; 2354 SendPacketAndWaitForResponse(packet.GetString(), response, false); 2355 const auto packet_end_time = steady_clock::now(); 2356 packet_times.push_back(packet_end_time - packet_start_time); 2357 } 2358 const auto end_time = steady_clock::now(); 2359 const auto total_time = end_time - start_time; 2360 2361 float packets_per_second = 2362 ((float)num_packets) / duration<float>(total_time).count(); 2363 auto average_per_packet = total_time / num_packets; 2364 const duration<float> standard_deviation = 2365 calculate_standard_deviation(packet_times); 2366 if (json) { 2367 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : " 2368 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, " 2369 "\"standard_deviation_nsec\" : {4,9:ns-f0}}", 2370 result_idx > 0 ? "," : "", send_size, recv_size, 2371 total_time, standard_deviation); 2372 ++result_idx; 2373 } else { 2374 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for " 2375 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with " 2376 "standard deviation of {5,10:ms+f6}\n", 2377 send_size, recv_size, duration<float>(total_time), 2378 packets_per_second, duration<float>(average_per_packet), 2379 standard_deviation); 2380 } 2381 strm.Flush(); 2382 } 2383 } 2384 2385 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f); 2386 if (json) 2387 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" " 2388 ": %" PRIu64 ",\n \"results\" : [", 2389 recv_amount); 2390 else 2391 strm.Printf("Testing receiving %2.1fMB of data using varying receive " 2392 "packet sizes:\n", 2393 k_recv_amount_mb); 2394 strm.Flush(); 2395 send_size = 0; 2396 result_idx = 0; 2397 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) { 2398 MakeSpeedTestPacket(packet, send_size, recv_size); 2399 2400 // If we have a receive size, test how long it takes to receive 4MB of 2401 // data 2402 if (recv_size > 0) { 2403 const auto start_time = steady_clock::now(); 2404 uint32_t bytes_read = 0; 2405 uint32_t packet_count = 0; 2406 while (bytes_read < recv_amount) { 2407 StringExtractorGDBRemote response; 2408 SendPacketAndWaitForResponse(packet.GetString(), response, false); 2409 bytes_read += recv_size; 2410 ++packet_count; 2411 } 2412 const auto end_time = steady_clock::now(); 2413 const auto total_time = end_time - start_time; 2414 float mb_second = ((float)recv_amount) / 2415 duration<float>(total_time).count() / 2416 (1024.0 * 1024.0); 2417 float packets_per_second = 2418 ((float)packet_count) / duration<float>(total_time).count(); 2419 const auto average_per_packet = total_time / packet_count; 2420 2421 if (json) { 2422 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : " 2423 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}", 2424 result_idx > 0 ? "," : "", send_size, recv_size, 2425 total_time); 2426 ++result_idx; 2427 } else { 2428 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed " 2429 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for " 2430 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n", 2431 send_size, recv_size, packet_count, k_recv_amount_mb, 2432 duration<float>(total_time), mb_second, 2433 packets_per_second, duration<float>(average_per_packet)); 2434 } 2435 strm.Flush(); 2436 } 2437 } 2438 if (json) 2439 strm.Printf("\n ]\n }\n}\n"); 2440 else 2441 strm.EOL(); 2442 } 2443 } 2444 2445 bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size, 2446 uint32_t recv_size) { 2447 StreamString packet; 2448 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size); 2449 uint32_t bytes_left = send_size; 2450 while (bytes_left > 0) { 2451 if (bytes_left >= 26) { 2452 packet.PutCString("abcdefghijklmnopqrstuvwxyz"); 2453 bytes_left -= 26; 2454 } else { 2455 packet.Printf("%*.*s;", bytes_left, bytes_left, 2456 "abcdefghijklmnopqrstuvwxyz"); 2457 bytes_left = 0; 2458 } 2459 } 2460 2461 StringExtractorGDBRemote response; 2462 return SendPacketAndWaitForResponse(packet.GetString(), response, false) == 2463 PacketResult::Success; 2464 } 2465 2466 bool GDBRemoteCommunicationClient::LaunchGDBServer( 2467 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port, 2468 std::string &socket_name) { 2469 pid = LLDB_INVALID_PROCESS_ID; 2470 port = 0; 2471 socket_name.clear(); 2472 2473 StringExtractorGDBRemote response; 2474 StreamString stream; 2475 stream.PutCString("qLaunchGDBServer;"); 2476 std::string hostname; 2477 if (remote_accept_hostname && remote_accept_hostname[0]) 2478 hostname = remote_accept_hostname; 2479 else { 2480 if (HostInfo::GetHostname(hostname)) { 2481 // Make the GDB server we launch only accept connections from this host 2482 stream.Printf("host:%s;", hostname.c_str()); 2483 } else { 2484 // Make the GDB server we launch accept connections from any host since 2485 // we can't figure out the hostname 2486 stream.Printf("host:*;"); 2487 } 2488 } 2489 // give the process a few seconds to startup 2490 ScopedTimeout timeout(*this, seconds(10)); 2491 2492 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2493 PacketResult::Success) { 2494 llvm::StringRef name; 2495 llvm::StringRef value; 2496 while (response.GetNameColonValue(name, value)) { 2497 if (name.equals("port")) 2498 value.getAsInteger(0, port); 2499 else if (name.equals("pid")) 2500 value.getAsInteger(0, pid); 2501 else if (name.compare("socket_name") == 0) { 2502 StringExtractor extractor(value); 2503 extractor.GetHexByteString(socket_name); 2504 } 2505 } 2506 return true; 2507 } 2508 return false; 2509 } 2510 2511 size_t GDBRemoteCommunicationClient::QueryGDBServer( 2512 std::vector<std::pair<uint16_t, std::string>> &connection_urls) { 2513 connection_urls.clear(); 2514 2515 StringExtractorGDBRemote response; 2516 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) != 2517 PacketResult::Success) 2518 return 0; 2519 2520 StructuredData::ObjectSP data = 2521 StructuredData::ParseJSON(response.GetStringRef()); 2522 if (!data) 2523 return 0; 2524 2525 StructuredData::Array *array = data->GetAsArray(); 2526 if (!array) 2527 return 0; 2528 2529 for (size_t i = 0, count = array->GetSize(); i < count; ++i) { 2530 StructuredData::Dictionary *element = nullptr; 2531 if (!array->GetItemAtIndexAsDictionary(i, element)) 2532 continue; 2533 2534 uint16_t port = 0; 2535 if (StructuredData::ObjectSP port_osp = 2536 element->GetValueForKey(llvm::StringRef("port"))) 2537 port = port_osp->GetIntegerValue(0); 2538 2539 std::string socket_name; 2540 if (StructuredData::ObjectSP socket_name_osp = 2541 element->GetValueForKey(llvm::StringRef("socket_name"))) 2542 socket_name = socket_name_osp->GetStringValue(); 2543 2544 if (port != 0 || !socket_name.empty()) 2545 connection_urls.emplace_back(port, socket_name); 2546 } 2547 return connection_urls.size(); 2548 } 2549 2550 bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) { 2551 StreamString stream; 2552 stream.Printf("qKillSpawnedProcess:%" PRId64, pid); 2553 2554 StringExtractorGDBRemote response; 2555 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2556 PacketResult::Success) { 2557 if (response.IsOKResponse()) 2558 return true; 2559 } 2560 return false; 2561 } 2562 2563 bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid) { 2564 if (m_curr_tid == tid) 2565 return true; 2566 2567 char packet[32]; 2568 int packet_len; 2569 if (tid == UINT64_MAX) 2570 packet_len = ::snprintf(packet, sizeof(packet), "Hg-1"); 2571 else 2572 packet_len = ::snprintf(packet, sizeof(packet), "Hg%" PRIx64, tid); 2573 assert(packet_len + 1 < (int)sizeof(packet)); 2574 UNUSED_IF_ASSERT_DISABLED(packet_len); 2575 StringExtractorGDBRemote response; 2576 if (SendPacketAndWaitForResponse(packet, response, false) == 2577 PacketResult::Success) { 2578 if (response.IsOKResponse()) { 2579 m_curr_tid = tid; 2580 return true; 2581 } 2582 2583 /* 2584 * Connected bare-iron target (like YAMON gdb-stub) may not have support for 2585 * Hg packet. 2586 * The reply from '?' packet could be as simple as 'S05'. There is no packet 2587 * which can 2588 * give us pid and/or tid. Assume pid=tid=1 in such cases. 2589 */ 2590 if (response.IsUnsupportedResponse() && IsConnected()) { 2591 m_curr_tid = 1; 2592 return true; 2593 } 2594 } 2595 return false; 2596 } 2597 2598 bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid) { 2599 if (m_curr_tid_run == tid) 2600 return true; 2601 2602 char packet[32]; 2603 int packet_len; 2604 if (tid == UINT64_MAX) 2605 packet_len = ::snprintf(packet, sizeof(packet), "Hc-1"); 2606 else 2607 packet_len = ::snprintf(packet, sizeof(packet), "Hc%" PRIx64, tid); 2608 2609 assert(packet_len + 1 < (int)sizeof(packet)); 2610 UNUSED_IF_ASSERT_DISABLED(packet_len); 2611 StringExtractorGDBRemote response; 2612 if (SendPacketAndWaitForResponse(packet, response, false) == 2613 PacketResult::Success) { 2614 if (response.IsOKResponse()) { 2615 m_curr_tid_run = tid; 2616 return true; 2617 } 2618 2619 /* 2620 * Connected bare-iron target (like YAMON gdb-stub) may not have support for 2621 * Hc packet. 2622 * The reply from '?' packet could be as simple as 'S05'. There is no packet 2623 * which can 2624 * give us pid and/or tid. Assume pid=tid=1 in such cases. 2625 */ 2626 if (response.IsUnsupportedResponse() && IsConnected()) { 2627 m_curr_tid_run = 1; 2628 return true; 2629 } 2630 } 2631 return false; 2632 } 2633 2634 bool GDBRemoteCommunicationClient::GetStopReply( 2635 StringExtractorGDBRemote &response) { 2636 if (SendPacketAndWaitForResponse("?", response, false) == 2637 PacketResult::Success) 2638 return response.IsNormalResponse(); 2639 return false; 2640 } 2641 2642 bool GDBRemoteCommunicationClient::GetThreadStopInfo( 2643 lldb::tid_t tid, StringExtractorGDBRemote &response) { 2644 if (m_supports_qThreadStopInfo) { 2645 char packet[256]; 2646 int packet_len = 2647 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid); 2648 assert(packet_len < (int)sizeof(packet)); 2649 UNUSED_IF_ASSERT_DISABLED(packet_len); 2650 if (SendPacketAndWaitForResponse(packet, response, false) == 2651 PacketResult::Success) { 2652 if (response.IsUnsupportedResponse()) 2653 m_supports_qThreadStopInfo = false; 2654 else if (response.IsNormalResponse()) 2655 return true; 2656 else 2657 return false; 2658 } else { 2659 m_supports_qThreadStopInfo = false; 2660 } 2661 } 2662 return false; 2663 } 2664 2665 uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket( 2666 GDBStoppointType type, bool insert, addr_t addr, uint32_t length) { 2667 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); 2668 if (log) 2669 log->Printf("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64, 2670 __FUNCTION__, insert ? "add" : "remove", addr); 2671 2672 // Check if the stub is known not to support this breakpoint type 2673 if (!SupportsGDBStoppointPacket(type)) 2674 return UINT8_MAX; 2675 // Construct the breakpoint packet 2676 char packet[64]; 2677 const int packet_len = 2678 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x", 2679 insert ? 'Z' : 'z', type, addr, length); 2680 // Check we haven't overwritten the end of the packet buffer 2681 assert(packet_len + 1 < (int)sizeof(packet)); 2682 UNUSED_IF_ASSERT_DISABLED(packet_len); 2683 StringExtractorGDBRemote response; 2684 // Make sure the response is either "OK", "EXX" where XX are two hex digits, 2685 // or "" (unsupported) 2686 response.SetResponseValidatorToOKErrorNotSupported(); 2687 // Try to send the breakpoint packet, and check that it was correctly sent 2688 if (SendPacketAndWaitForResponse(packet, response, true) == 2689 PacketResult::Success) { 2690 // Receive and OK packet when the breakpoint successfully placed 2691 if (response.IsOKResponse()) 2692 return 0; 2693 2694 // Status while setting breakpoint, send back specific error 2695 if (response.IsErrorResponse()) 2696 return response.GetError(); 2697 2698 // Empty packet informs us that breakpoint is not supported 2699 if (response.IsUnsupportedResponse()) { 2700 // Disable this breakpoint type since it is unsupported 2701 switch (type) { 2702 case eBreakpointSoftware: 2703 m_supports_z0 = false; 2704 break; 2705 case eBreakpointHardware: 2706 m_supports_z1 = false; 2707 break; 2708 case eWatchpointWrite: 2709 m_supports_z2 = false; 2710 break; 2711 case eWatchpointRead: 2712 m_supports_z3 = false; 2713 break; 2714 case eWatchpointReadWrite: 2715 m_supports_z4 = false; 2716 break; 2717 case eStoppointInvalid: 2718 return UINT8_MAX; 2719 } 2720 } 2721 } 2722 // Signal generic failure 2723 return UINT8_MAX; 2724 } 2725 2726 size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs( 2727 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) { 2728 thread_ids.clear(); 2729 2730 Lock lock(*this, false); 2731 if (lock) { 2732 sequence_mutex_unavailable = false; 2733 StringExtractorGDBRemote response; 2734 2735 PacketResult packet_result; 2736 for (packet_result = 2737 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response); 2738 packet_result == PacketResult::Success && response.IsNormalResponse(); 2739 packet_result = 2740 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) { 2741 char ch = response.GetChar(); 2742 if (ch == 'l') 2743 break; 2744 if (ch == 'm') { 2745 do { 2746 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID); 2747 2748 if (tid != LLDB_INVALID_THREAD_ID) { 2749 thread_ids.push_back(tid); 2750 } 2751 ch = response.GetChar(); // Skip the command separator 2752 } while (ch == ','); // Make sure we got a comma separator 2753 } 2754 } 2755 2756 /* 2757 * Connected bare-iron target (like YAMON gdb-stub) may not have support for 2758 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet 2759 * could 2760 * be as simple as 'S05'. There is no packet which can give us pid and/or 2761 * tid. 2762 * Assume pid=tid=1 in such cases. 2763 */ 2764 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) && 2765 thread_ids.size() == 0 && IsConnected()) { 2766 thread_ids.push_back(1); 2767 } 2768 } else { 2769 #if !defined(LLDB_CONFIGURATION_DEBUG) 2770 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS | 2771 GDBR_LOG_PACKETS)); 2772 if (log) 2773 log->Printf("error: failed to get packet sequence mutex, not sending " 2774 "packet 'qfThreadInfo'"); 2775 #endif 2776 sequence_mutex_unavailable = true; 2777 } 2778 return thread_ids.size(); 2779 } 2780 2781 lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() { 2782 StringExtractorGDBRemote response; 2783 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) != 2784 PacketResult::Success || 2785 !response.IsNormalResponse()) 2786 return LLDB_INVALID_ADDRESS; 2787 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 2788 } 2789 2790 lldb_private::Status GDBRemoteCommunicationClient::RunShellCommand( 2791 const char *command, // Shouldn't be NULL 2792 const FileSpec & 2793 working_dir, // Pass empty FileSpec to use the current working directory 2794 int *status_ptr, // Pass NULL if you don't want the process exit status 2795 int *signo_ptr, // Pass NULL if you don't want the signal that caused the 2796 // process to exit 2797 std::string 2798 *command_output, // Pass NULL if you don't want the command output 2799 const Timeout<std::micro> &timeout) { 2800 lldb_private::StreamString stream; 2801 stream.PutCString("qPlatform_shell:"); 2802 stream.PutBytesAsRawHex8(command, strlen(command)); 2803 stream.PutChar(','); 2804 uint32_t timeout_sec = UINT32_MAX; 2805 if (timeout) { 2806 // TODO: Use chrono version of std::ceil once c++17 is available. 2807 timeout_sec = std::ceil(std::chrono::duration<double>(*timeout).count()); 2808 } 2809 stream.PutHex32(timeout_sec); 2810 if (working_dir) { 2811 std::string path{working_dir.GetPath(false)}; 2812 stream.PutChar(','); 2813 stream.PutCStringAsRawHex8(path.c_str()); 2814 } 2815 StringExtractorGDBRemote response; 2816 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2817 PacketResult::Success) { 2818 if (response.GetChar() != 'F') 2819 return Status("malformed reply"); 2820 if (response.GetChar() != ',') 2821 return Status("malformed reply"); 2822 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX); 2823 if (exitcode == UINT32_MAX) 2824 return Status("unable to run remote process"); 2825 else if (status_ptr) 2826 *status_ptr = exitcode; 2827 if (response.GetChar() != ',') 2828 return Status("malformed reply"); 2829 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX); 2830 if (signo_ptr) 2831 *signo_ptr = signo; 2832 if (response.GetChar() != ',') 2833 return Status("malformed reply"); 2834 std::string output; 2835 response.GetEscapedBinaryData(output); 2836 if (command_output) 2837 command_output->assign(output); 2838 return Status(); 2839 } 2840 return Status("unable to send packet"); 2841 } 2842 2843 Status GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec, 2844 uint32_t file_permissions) { 2845 std::string path{file_spec.GetPath(false)}; 2846 lldb_private::StreamString stream; 2847 stream.PutCString("qPlatform_mkdir:"); 2848 stream.PutHex32(file_permissions); 2849 stream.PutChar(','); 2850 stream.PutCStringAsRawHex8(path.c_str()); 2851 llvm::StringRef packet = stream.GetString(); 2852 StringExtractorGDBRemote response; 2853 2854 if (SendPacketAndWaitForResponse(packet, response, false) != 2855 PacketResult::Success) 2856 return Status("failed to send '%s' packet", packet.str().c_str()); 2857 2858 if (response.GetChar() != 'F') 2859 return Status("invalid response to '%s' packet", packet.str().c_str()); 2860 2861 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX); 2862 } 2863 2864 Status 2865 GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec, 2866 uint32_t file_permissions) { 2867 std::string path{file_spec.GetPath(false)}; 2868 lldb_private::StreamString stream; 2869 stream.PutCString("qPlatform_chmod:"); 2870 stream.PutHex32(file_permissions); 2871 stream.PutChar(','); 2872 stream.PutCStringAsRawHex8(path.c_str()); 2873 llvm::StringRef packet = stream.GetString(); 2874 StringExtractorGDBRemote response; 2875 2876 if (SendPacketAndWaitForResponse(packet, response, false) != 2877 PacketResult::Success) 2878 return Status("failed to send '%s' packet", stream.GetData()); 2879 2880 if (response.GetChar() != 'F') 2881 return Status("invalid response to '%s' packet", stream.GetData()); 2882 2883 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX); 2884 } 2885 2886 static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response, 2887 uint64_t fail_result, Status &error) { 2888 response.SetFilePos(0); 2889 if (response.GetChar() != 'F') 2890 return fail_result; 2891 int32_t result = response.GetS32(-2); 2892 if (result == -2) 2893 return fail_result; 2894 if (response.GetChar() == ',') { 2895 int result_errno = response.GetS32(-2); 2896 if (result_errno != -2) 2897 error.SetError(result_errno, eErrorTypePOSIX); 2898 else 2899 error.SetError(-1, eErrorTypeGeneric); 2900 } else 2901 error.Clear(); 2902 return result; 2903 } 2904 lldb::user_id_t 2905 GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec, 2906 uint32_t flags, mode_t mode, 2907 Status &error) { 2908 std::string path(file_spec.GetPath(false)); 2909 lldb_private::StreamString stream; 2910 stream.PutCString("vFile:open:"); 2911 if (path.empty()) 2912 return UINT64_MAX; 2913 stream.PutCStringAsRawHex8(path.c_str()); 2914 stream.PutChar(','); 2915 stream.PutHex32(flags); 2916 stream.PutChar(','); 2917 stream.PutHex32(mode); 2918 StringExtractorGDBRemote response; 2919 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2920 PacketResult::Success) { 2921 return ParseHostIOPacketResponse(response, UINT64_MAX, error); 2922 } 2923 return UINT64_MAX; 2924 } 2925 2926 bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd, 2927 Status &error) { 2928 lldb_private::StreamString stream; 2929 stream.Printf("vFile:close:%i", (int)fd); 2930 StringExtractorGDBRemote response; 2931 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2932 PacketResult::Success) { 2933 return ParseHostIOPacketResponse(response, -1, error) == 0; 2934 } 2935 return false; 2936 } 2937 2938 // Extension of host I/O packets to get the file size. 2939 lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize( 2940 const lldb_private::FileSpec &file_spec) { 2941 std::string path(file_spec.GetPath(false)); 2942 lldb_private::StreamString stream; 2943 stream.PutCString("vFile:size:"); 2944 stream.PutCStringAsRawHex8(path.c_str()); 2945 StringExtractorGDBRemote response; 2946 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2947 PacketResult::Success) { 2948 if (response.GetChar() != 'F') 2949 return UINT64_MAX; 2950 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX); 2951 return retcode; 2952 } 2953 return UINT64_MAX; 2954 } 2955 2956 Status 2957 GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec, 2958 uint32_t &file_permissions) { 2959 std::string path{file_spec.GetPath(false)}; 2960 Status error; 2961 lldb_private::StreamString stream; 2962 stream.PutCString("vFile:mode:"); 2963 stream.PutCStringAsRawHex8(path.c_str()); 2964 StringExtractorGDBRemote response; 2965 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2966 PacketResult::Success) { 2967 if (response.GetChar() != 'F') { 2968 error.SetErrorStringWithFormat("invalid response to '%s' packet", 2969 stream.GetData()); 2970 } else { 2971 const uint32_t mode = response.GetS32(-1); 2972 if (static_cast<int32_t>(mode) == -1) { 2973 if (response.GetChar() == ',') { 2974 int response_errno = response.GetS32(-1); 2975 if (response_errno > 0) 2976 error.SetError(response_errno, lldb::eErrorTypePOSIX); 2977 else 2978 error.SetErrorToGenericError(); 2979 } else 2980 error.SetErrorToGenericError(); 2981 } else { 2982 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO); 2983 } 2984 } 2985 } else { 2986 error.SetErrorStringWithFormat("failed to send '%s' packet", 2987 stream.GetData()); 2988 } 2989 return error; 2990 } 2991 2992 uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd, 2993 uint64_t offset, void *dst, 2994 uint64_t dst_len, 2995 Status &error) { 2996 lldb_private::StreamString stream; 2997 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, 2998 offset); 2999 StringExtractorGDBRemote response; 3000 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 3001 PacketResult::Success) { 3002 if (response.GetChar() != 'F') 3003 return 0; 3004 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX); 3005 if (retcode == UINT32_MAX) 3006 return retcode; 3007 const char next = (response.Peek() ? *response.Peek() : 0); 3008 if (next == ',') 3009 return 0; 3010 if (next == ';') { 3011 response.GetChar(); // skip the semicolon 3012 std::string buffer; 3013 if (response.GetEscapedBinaryData(buffer)) { 3014 const uint64_t data_to_write = 3015 std::min<uint64_t>(dst_len, buffer.size()); 3016 if (data_to_write > 0) 3017 memcpy(dst, &buffer[0], data_to_write); 3018 return data_to_write; 3019 } 3020 } 3021 } 3022 return 0; 3023 } 3024 3025 uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd, 3026 uint64_t offset, 3027 const void *src, 3028 uint64_t src_len, 3029 Status &error) { 3030 lldb_private::StreamGDBRemote stream; 3031 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset); 3032 stream.PutEscapedBytes(src, src_len); 3033 StringExtractorGDBRemote response; 3034 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 3035 PacketResult::Success) { 3036 if (response.GetChar() != 'F') { 3037 error.SetErrorStringWithFormat("write file failed"); 3038 return 0; 3039 } 3040 uint64_t bytes_written = response.GetU64(UINT64_MAX); 3041 if (bytes_written == UINT64_MAX) { 3042 error.SetErrorToGenericError(); 3043 if (response.GetChar() == ',') { 3044 int response_errno = response.GetS32(-1); 3045 if (response_errno > 0) 3046 error.SetError(response_errno, lldb::eErrorTypePOSIX); 3047 } 3048 return 0; 3049 } 3050 return bytes_written; 3051 } else { 3052 error.SetErrorString("failed to send vFile:pwrite packet"); 3053 } 3054 return 0; 3055 } 3056 3057 Status GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, 3058 const FileSpec &dst) { 3059 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)}; 3060 Status error; 3061 lldb_private::StreamGDBRemote stream; 3062 stream.PutCString("vFile:symlink:"); 3063 // the unix symlink() command reverses its parameters where the dst if first, 3064 // so we follow suit here 3065 stream.PutCStringAsRawHex8(dst_path.c_str()); 3066 stream.PutChar(','); 3067 stream.PutCStringAsRawHex8(src_path.c_str()); 3068 StringExtractorGDBRemote response; 3069 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 3070 PacketResult::Success) { 3071 if (response.GetChar() == 'F') { 3072 uint32_t result = response.GetU32(UINT32_MAX); 3073 if (result != 0) { 3074 error.SetErrorToGenericError(); 3075 if (response.GetChar() == ',') { 3076 int response_errno = response.GetS32(-1); 3077 if (response_errno > 0) 3078 error.SetError(response_errno, lldb::eErrorTypePOSIX); 3079 } 3080 } 3081 } else { 3082 // Should have returned with 'F<result>[,<errno>]' 3083 error.SetErrorStringWithFormat("symlink failed"); 3084 } 3085 } else { 3086 error.SetErrorString("failed to send vFile:symlink packet"); 3087 } 3088 return error; 3089 } 3090 3091 Status GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) { 3092 std::string path{file_spec.GetPath(false)}; 3093 Status error; 3094 lldb_private::StreamGDBRemote stream; 3095 stream.PutCString("vFile:unlink:"); 3096 // the unix symlink() command reverses its parameters where the dst if first, 3097 // so we follow suit here 3098 stream.PutCStringAsRawHex8(path.c_str()); 3099 StringExtractorGDBRemote response; 3100 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 3101 PacketResult::Success) { 3102 if (response.GetChar() == 'F') { 3103 uint32_t result = response.GetU32(UINT32_MAX); 3104 if (result != 0) { 3105 error.SetErrorToGenericError(); 3106 if (response.GetChar() == ',') { 3107 int response_errno = response.GetS32(-1); 3108 if (response_errno > 0) 3109 error.SetError(response_errno, lldb::eErrorTypePOSIX); 3110 } 3111 } 3112 } else { 3113 // Should have returned with 'F<result>[,<errno>]' 3114 error.SetErrorStringWithFormat("unlink failed"); 3115 } 3116 } else { 3117 error.SetErrorString("failed to send vFile:unlink packet"); 3118 } 3119 return error; 3120 } 3121 3122 // Extension of host I/O packets to get whether a file exists. 3123 bool GDBRemoteCommunicationClient::GetFileExists( 3124 const lldb_private::FileSpec &file_spec) { 3125 std::string path(file_spec.GetPath(false)); 3126 lldb_private::StreamString stream; 3127 stream.PutCString("vFile:exists:"); 3128 stream.PutCStringAsRawHex8(path.c_str()); 3129 StringExtractorGDBRemote response; 3130 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 3131 PacketResult::Success) { 3132 if (response.GetChar() != 'F') 3133 return false; 3134 if (response.GetChar() != ',') 3135 return false; 3136 bool retcode = (response.GetChar() != '0'); 3137 return retcode; 3138 } 3139 return false; 3140 } 3141 3142 bool GDBRemoteCommunicationClient::CalculateMD5( 3143 const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) { 3144 std::string path(file_spec.GetPath(false)); 3145 lldb_private::StreamString stream; 3146 stream.PutCString("vFile:MD5:"); 3147 stream.PutCStringAsRawHex8(path.c_str()); 3148 StringExtractorGDBRemote response; 3149 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 3150 PacketResult::Success) { 3151 if (response.GetChar() != 'F') 3152 return false; 3153 if (response.GetChar() != ',') 3154 return false; 3155 if (response.Peek() && *response.Peek() == 'x') 3156 return false; 3157 low = response.GetHexMaxU64(false, UINT64_MAX); 3158 high = response.GetHexMaxU64(false, UINT64_MAX); 3159 return true; 3160 } 3161 return false; 3162 } 3163 3164 bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) { 3165 // Some targets have issues with g/G packets and we need to avoid using them 3166 if (m_avoid_g_packets == eLazyBoolCalculate) { 3167 if (process) { 3168 m_avoid_g_packets = eLazyBoolNo; 3169 const ArchSpec &arch = process->GetTarget().GetArchitecture(); 3170 if (arch.IsValid() && 3171 arch.GetTriple().getVendor() == llvm::Triple::Apple && 3172 arch.GetTriple().getOS() == llvm::Triple::IOS && 3173 arch.GetTriple().getArch() == llvm::Triple::aarch64) { 3174 m_avoid_g_packets = eLazyBoolYes; 3175 uint32_t gdb_server_version = GetGDBServerProgramVersion(); 3176 if (gdb_server_version != 0) { 3177 const char *gdb_server_name = GetGDBServerProgramName(); 3178 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) { 3179 if (gdb_server_version >= 310) 3180 m_avoid_g_packets = eLazyBoolNo; 3181 } 3182 } 3183 } 3184 } 3185 } 3186 return m_avoid_g_packets == eLazyBoolYes; 3187 } 3188 3189 DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, 3190 uint32_t reg) { 3191 StreamString payload; 3192 payload.Printf("p%x", reg); 3193 StringExtractorGDBRemote response; 3194 if (SendThreadSpecificPacketAndWaitForResponse( 3195 tid, std::move(payload), response, false) != PacketResult::Success || 3196 !response.IsNormalResponse()) 3197 return nullptr; 3198 3199 DataBufferSP buffer_sp( 3200 new DataBufferHeap(response.GetStringRef().size() / 2, 0)); 3201 response.GetHexBytes(buffer_sp->GetData(), '\xcc'); 3202 return buffer_sp; 3203 } 3204 3205 DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) { 3206 StreamString payload; 3207 payload.PutChar('g'); 3208 StringExtractorGDBRemote response; 3209 if (SendThreadSpecificPacketAndWaitForResponse( 3210 tid, std::move(payload), response, false) != PacketResult::Success || 3211 !response.IsNormalResponse()) 3212 return nullptr; 3213 3214 DataBufferSP buffer_sp( 3215 new DataBufferHeap(response.GetStringRef().size() / 2, 0)); 3216 response.GetHexBytes(buffer_sp->GetData(), '\xcc'); 3217 return buffer_sp; 3218 } 3219 3220 bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid, 3221 uint32_t reg_num, 3222 llvm::ArrayRef<uint8_t> data) { 3223 StreamString payload; 3224 payload.Printf("P%x=", reg_num); 3225 payload.PutBytesAsRawHex8(data.data(), data.size(), 3226 endian::InlHostByteOrder(), 3227 endian::InlHostByteOrder()); 3228 StringExtractorGDBRemote response; 3229 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), 3230 response, false) == 3231 PacketResult::Success && 3232 response.IsOKResponse(); 3233 } 3234 3235 bool GDBRemoteCommunicationClient::WriteAllRegisters( 3236 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) { 3237 StreamString payload; 3238 payload.PutChar('G'); 3239 payload.PutBytesAsRawHex8(data.data(), data.size(), 3240 endian::InlHostByteOrder(), 3241 endian::InlHostByteOrder()); 3242 StringExtractorGDBRemote response; 3243 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), 3244 response, false) == 3245 PacketResult::Success && 3246 response.IsOKResponse(); 3247 } 3248 3249 bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid, 3250 uint32_t &save_id) { 3251 save_id = 0; // Set to invalid save ID 3252 if (m_supports_QSaveRegisterState == eLazyBoolNo) 3253 return false; 3254 3255 m_supports_QSaveRegisterState = eLazyBoolYes; 3256 StreamString payload; 3257 payload.PutCString("QSaveRegisterState"); 3258 StringExtractorGDBRemote response; 3259 if (SendThreadSpecificPacketAndWaitForResponse( 3260 tid, std::move(payload), response, false) != PacketResult::Success) 3261 return false; 3262 3263 if (response.IsUnsupportedResponse()) 3264 m_supports_QSaveRegisterState = eLazyBoolNo; 3265 3266 const uint32_t response_save_id = response.GetU32(0); 3267 if (response_save_id == 0) 3268 return false; 3269 3270 save_id = response_save_id; 3271 return true; 3272 } 3273 3274 bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid, 3275 uint32_t save_id) { 3276 // We use the "m_supports_QSaveRegisterState" variable here because the 3277 // QSaveRegisterState and QRestoreRegisterState packets must both be 3278 // supported in order to be useful 3279 if (m_supports_QSaveRegisterState == eLazyBoolNo) 3280 return false; 3281 3282 StreamString payload; 3283 payload.Printf("QRestoreRegisterState:%u", save_id); 3284 StringExtractorGDBRemote response; 3285 if (SendThreadSpecificPacketAndWaitForResponse( 3286 tid, std::move(payload), response, false) != PacketResult::Success) 3287 return false; 3288 3289 if (response.IsOKResponse()) 3290 return true; 3291 3292 if (response.IsUnsupportedResponse()) 3293 m_supports_QSaveRegisterState = eLazyBoolNo; 3294 return false; 3295 } 3296 3297 bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) { 3298 if (!GetSyncThreadStateSupported()) 3299 return false; 3300 3301 StreamString packet; 3302 StringExtractorGDBRemote response; 3303 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid); 3304 return SendPacketAndWaitForResponse(packet.GetString(), response, false) == 3305 GDBRemoteCommunication::PacketResult::Success && 3306 response.IsOKResponse(); 3307 } 3308 3309 lldb::user_id_t 3310 GDBRemoteCommunicationClient::SendStartTracePacket(const TraceOptions &options, 3311 Status &error) { 3312 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3313 lldb::user_id_t ret_uid = LLDB_INVALID_UID; 3314 3315 StreamGDBRemote escaped_packet; 3316 escaped_packet.PutCString("jTraceStart:"); 3317 3318 StructuredData::Dictionary json_packet; 3319 json_packet.AddIntegerItem("type", options.getType()); 3320 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize()); 3321 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize()); 3322 3323 if (options.getThreadID() != LLDB_INVALID_THREAD_ID) 3324 json_packet.AddIntegerItem("threadid", options.getThreadID()); 3325 3326 StructuredData::DictionarySP custom_params = options.getTraceParams(); 3327 if (custom_params) 3328 json_packet.AddItem("params", custom_params); 3329 3330 StreamString json_string; 3331 json_packet.Dump(json_string, false); 3332 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize()); 3333 3334 StringExtractorGDBRemote response; 3335 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response, 3336 true) == 3337 GDBRemoteCommunication::PacketResult::Success) { 3338 if (!response.IsNormalResponse()) { 3339 error = response.GetStatus(); 3340 LLDB_LOG(log, "Target does not support Tracing , error {0}", error); 3341 } else { 3342 ret_uid = response.GetHexMaxU64(false, LLDB_INVALID_UID); 3343 } 3344 } else { 3345 LLDB_LOG(log, "failed to send packet"); 3346 error.SetErrorStringWithFormat("failed to send packet: '%s'", 3347 escaped_packet.GetData()); 3348 } 3349 return ret_uid; 3350 } 3351 3352 Status 3353 GDBRemoteCommunicationClient::SendStopTracePacket(lldb::user_id_t uid, 3354 lldb::tid_t thread_id) { 3355 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3356 StringExtractorGDBRemote response; 3357 Status error; 3358 3359 StructuredData::Dictionary json_packet; 3360 StreamGDBRemote escaped_packet; 3361 StreamString json_string; 3362 escaped_packet.PutCString("jTraceStop:"); 3363 3364 json_packet.AddIntegerItem("traceid", uid); 3365 3366 if (thread_id != LLDB_INVALID_THREAD_ID) 3367 json_packet.AddIntegerItem("threadid", thread_id); 3368 3369 json_packet.Dump(json_string, false); 3370 3371 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize()); 3372 3373 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response, 3374 true) == 3375 GDBRemoteCommunication::PacketResult::Success) { 3376 if (!response.IsOKResponse()) { 3377 error = response.GetStatus(); 3378 LLDB_LOG(log, "stop tracing failed"); 3379 } 3380 } else { 3381 LLDB_LOG(log, "failed to send packet"); 3382 error.SetErrorStringWithFormat( 3383 "failed to send packet: '%s' with error '%d'", escaped_packet.GetData(), 3384 response.GetError()); 3385 } 3386 return error; 3387 } 3388 3389 Status GDBRemoteCommunicationClient::SendGetDataPacket( 3390 lldb::user_id_t uid, lldb::tid_t thread_id, 3391 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) { 3392 3393 StreamGDBRemote escaped_packet; 3394 escaped_packet.PutCString("jTraceBufferRead:"); 3395 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset); 3396 } 3397 3398 Status GDBRemoteCommunicationClient::SendGetMetaDataPacket( 3399 lldb::user_id_t uid, lldb::tid_t thread_id, 3400 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) { 3401 3402 StreamGDBRemote escaped_packet; 3403 escaped_packet.PutCString("jTraceMetaRead:"); 3404 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset); 3405 } 3406 3407 Status 3408 GDBRemoteCommunicationClient::SendGetTraceConfigPacket(lldb::user_id_t uid, 3409 TraceOptions &options) { 3410 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3411 StringExtractorGDBRemote response; 3412 Status error; 3413 3414 StreamString json_string; 3415 StreamGDBRemote escaped_packet; 3416 escaped_packet.PutCString("jTraceConfigRead:"); 3417 3418 StructuredData::Dictionary json_packet; 3419 json_packet.AddIntegerItem("traceid", uid); 3420 3421 if (options.getThreadID() != LLDB_INVALID_THREAD_ID) 3422 json_packet.AddIntegerItem("threadid", options.getThreadID()); 3423 3424 json_packet.Dump(json_string, false); 3425 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize()); 3426 3427 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response, 3428 true) == 3429 GDBRemoteCommunication::PacketResult::Success) { 3430 if (response.IsNormalResponse()) { 3431 uint64_t type = std::numeric_limits<uint64_t>::max(); 3432 uint64_t buffersize = std::numeric_limits<uint64_t>::max(); 3433 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max(); 3434 3435 auto json_object = StructuredData::ParseJSON(response.Peek()); 3436 3437 if (!json_object || 3438 json_object->GetType() != lldb::eStructuredDataTypeDictionary) { 3439 error.SetErrorString("Invalid Configuration obtained"); 3440 return error; 3441 } 3442 3443 auto json_dict = json_object->GetAsDictionary(); 3444 3445 json_dict->GetValueForKeyAsInteger<uint64_t>("metabuffersize", 3446 metabuffersize); 3447 options.setMetaDataBufferSize(metabuffersize); 3448 3449 json_dict->GetValueForKeyAsInteger<uint64_t>("buffersize", buffersize); 3450 options.setTraceBufferSize(buffersize); 3451 3452 json_dict->GetValueForKeyAsInteger<uint64_t>("type", type); 3453 options.setType(static_cast<lldb::TraceType>(type)); 3454 3455 StructuredData::ObjectSP custom_params_sp = 3456 json_dict->GetValueForKey("params"); 3457 if (custom_params_sp) { 3458 if (custom_params_sp->GetType() != 3459 lldb::eStructuredDataTypeDictionary) { 3460 error.SetErrorString("Invalid Configuration obtained"); 3461 return error; 3462 } else 3463 options.setTraceParams( 3464 static_pointer_cast<StructuredData::Dictionary>( 3465 custom_params_sp)); 3466 } 3467 } else { 3468 error = response.GetStatus(); 3469 } 3470 } else { 3471 LLDB_LOG(log, "failed to send packet"); 3472 error.SetErrorStringWithFormat("failed to send packet: '%s'", 3473 escaped_packet.GetData()); 3474 } 3475 return error; 3476 } 3477 3478 Status GDBRemoteCommunicationClient::SendGetTraceDataPacket( 3479 StreamGDBRemote &packet, lldb::user_id_t uid, lldb::tid_t thread_id, 3480 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) { 3481 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3482 Status error; 3483 3484 StructuredData::Dictionary json_packet; 3485 3486 json_packet.AddIntegerItem("traceid", uid); 3487 json_packet.AddIntegerItem("offset", offset); 3488 json_packet.AddIntegerItem("buffersize", buffer.size()); 3489 3490 if (thread_id != LLDB_INVALID_THREAD_ID) 3491 json_packet.AddIntegerItem("threadid", thread_id); 3492 3493 StreamString json_string; 3494 json_packet.Dump(json_string, false); 3495 3496 packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize()); 3497 StringExtractorGDBRemote response; 3498 if (SendPacketAndWaitForResponse(packet.GetString(), response, true) == 3499 GDBRemoteCommunication::PacketResult::Success) { 3500 if (response.IsNormalResponse()) { 3501 size_t filled_size = response.GetHexBytesAvail(buffer); 3502 buffer = llvm::MutableArrayRef<uint8_t>(buffer.data(), filled_size); 3503 } else { 3504 error = response.GetStatus(); 3505 buffer = buffer.slice(buffer.size()); 3506 } 3507 } else { 3508 LLDB_LOG(log, "failed to send packet"); 3509 error.SetErrorStringWithFormat("failed to send packet: '%s'", 3510 packet.GetData()); 3511 buffer = buffer.slice(buffer.size()); 3512 } 3513 return error; 3514 } 3515 3516 bool GDBRemoteCommunicationClient::GetModuleInfo( 3517 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec, 3518 ModuleSpec &module_spec) { 3519 if (!m_supports_qModuleInfo) 3520 return false; 3521 3522 std::string module_path = module_file_spec.GetPath(false); 3523 if (module_path.empty()) 3524 return false; 3525 3526 StreamString packet; 3527 packet.PutCString("qModuleInfo:"); 3528 packet.PutCStringAsRawHex8(module_path.c_str()); 3529 packet.PutCString(";"); 3530 const auto &triple = arch_spec.GetTriple().getTriple(); 3531 packet.PutCStringAsRawHex8(triple.c_str()); 3532 3533 StringExtractorGDBRemote response; 3534 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) != 3535 PacketResult::Success) 3536 return false; 3537 3538 if (response.IsErrorResponse()) 3539 return false; 3540 3541 if (response.IsUnsupportedResponse()) { 3542 m_supports_qModuleInfo = false; 3543 return false; 3544 } 3545 3546 llvm::StringRef name; 3547 llvm::StringRef value; 3548 3549 module_spec.Clear(); 3550 module_spec.GetFileSpec() = module_file_spec; 3551 3552 while (response.GetNameColonValue(name, value)) { 3553 if (name == "uuid" || name == "md5") { 3554 StringExtractor extractor(value); 3555 std::string uuid; 3556 extractor.GetHexByteString(uuid); 3557 module_spec.GetUUID().SetFromCString(uuid.c_str(), uuid.size() / 2); 3558 } else if (name == "triple") { 3559 StringExtractor extractor(value); 3560 std::string triple; 3561 extractor.GetHexByteString(triple); 3562 module_spec.GetArchitecture().SetTriple(triple.c_str()); 3563 } else if (name == "file_offset") { 3564 uint64_t ival = 0; 3565 if (!value.getAsInteger(16, ival)) 3566 module_spec.SetObjectOffset(ival); 3567 } else if (name == "file_size") { 3568 uint64_t ival = 0; 3569 if (!value.getAsInteger(16, ival)) 3570 module_spec.SetObjectSize(ival); 3571 } else if (name == "file_path") { 3572 StringExtractor extractor(value); 3573 std::string path; 3574 extractor.GetHexByteString(path); 3575 module_spec.GetFileSpec() = FileSpec(path, false, arch_spec.GetTriple()); 3576 } 3577 } 3578 3579 return true; 3580 } 3581 3582 static llvm::Optional<ModuleSpec> 3583 ParseModuleSpec(StructuredData::Dictionary *dict) { 3584 ModuleSpec result; 3585 if (!dict) 3586 return llvm::None; 3587 3588 llvm::StringRef string; 3589 uint64_t integer; 3590 3591 if (!dict->GetValueForKeyAsString("uuid", string)) 3592 return llvm::None; 3593 if (result.GetUUID().SetFromStringRef(string, string.size() / 2) != 3594 string.size()) 3595 return llvm::None; 3596 3597 if (!dict->GetValueForKeyAsInteger("file_offset", integer)) 3598 return llvm::None; 3599 result.SetObjectOffset(integer); 3600 3601 if (!dict->GetValueForKeyAsInteger("file_size", integer)) 3602 return llvm::None; 3603 result.SetObjectSize(integer); 3604 3605 if (!dict->GetValueForKeyAsString("triple", string)) 3606 return llvm::None; 3607 result.GetArchitecture().SetTriple(string); 3608 3609 if (!dict->GetValueForKeyAsString("file_path", string)) 3610 return llvm::None; 3611 result.GetFileSpec() = 3612 FileSpec(string, false, result.GetArchitecture().GetTriple()); 3613 3614 return result; 3615 } 3616 3617 llvm::Optional<std::vector<ModuleSpec>> 3618 GDBRemoteCommunicationClient::GetModulesInfo( 3619 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) { 3620 if (!m_supports_jModulesInfo) 3621 return llvm::None; 3622 3623 JSONArray::SP module_array_sp = std::make_shared<JSONArray>(); 3624 for (const FileSpec &module_file_spec : module_file_specs) { 3625 JSONObject::SP module_sp = std::make_shared<JSONObject>(); 3626 module_array_sp->AppendObject(module_sp); 3627 module_sp->SetObject( 3628 "file", std::make_shared<JSONString>(module_file_spec.GetPath(false))); 3629 module_sp->SetObject("triple", 3630 std::make_shared<JSONString>(triple.getTriple())); 3631 } 3632 StreamString unescaped_payload; 3633 unescaped_payload.PutCString("jModulesInfo:"); 3634 module_array_sp->Write(unescaped_payload); 3635 StreamGDBRemote payload; 3636 payload.PutEscapedBytes(unescaped_payload.GetString().data(), 3637 unescaped_payload.GetSize()); 3638 3639 // Increase the timeout for jModulesInfo since this packet can take longer. 3640 ScopedTimeout timeout(*this, std::chrono::seconds(10)); 3641 3642 StringExtractorGDBRemote response; 3643 if (SendPacketAndWaitForResponse(payload.GetString(), response, false) != 3644 PacketResult::Success || 3645 response.IsErrorResponse()) 3646 return llvm::None; 3647 3648 if (response.IsUnsupportedResponse()) { 3649 m_supports_jModulesInfo = false; 3650 return llvm::None; 3651 } 3652 3653 StructuredData::ObjectSP response_object_sp = 3654 StructuredData::ParseJSON(response.GetStringRef()); 3655 if (!response_object_sp) 3656 return llvm::None; 3657 3658 StructuredData::Array *response_array = response_object_sp->GetAsArray(); 3659 if (!response_array) 3660 return llvm::None; 3661 3662 std::vector<ModuleSpec> result; 3663 for (size_t i = 0; i < response_array->GetSize(); ++i) { 3664 if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec( 3665 response_array->GetItemAtIndex(i)->GetAsDictionary())) 3666 result.push_back(*module_spec); 3667 } 3668 3669 return result; 3670 } 3671 3672 // query the target remote for extended information using the qXfer packet 3673 // 3674 // example: object='features', annex='target.xml', out=<xml output> return: 3675 // 'true' on success 3676 // 'false' on failure (err set) 3677 bool GDBRemoteCommunicationClient::ReadExtFeature( 3678 const lldb_private::ConstString object, 3679 const lldb_private::ConstString annex, std::string &out, 3680 lldb_private::Status &err) { 3681 3682 std::stringstream output; 3683 StringExtractorGDBRemote chunk; 3684 3685 uint64_t size = GetRemoteMaxPacketSize(); 3686 if (size == 0) 3687 size = 0x1000; 3688 size = size - 1; // Leave space for the 'm' or 'l' character in the response 3689 int offset = 0; 3690 bool active = true; 3691 3692 // loop until all data has been read 3693 while (active) { 3694 3695 // send query extended feature packet 3696 std::stringstream packet; 3697 packet << "qXfer:" << object.AsCString("") 3698 << ":read:" << annex.AsCString("") << ":" << std::hex << offset 3699 << "," << std::hex << size; 3700 3701 GDBRemoteCommunication::PacketResult res = 3702 SendPacketAndWaitForResponse(packet.str(), chunk, false); 3703 3704 if (res != GDBRemoteCommunication::PacketResult::Success) { 3705 err.SetErrorString("Error sending $qXfer packet"); 3706 return false; 3707 } 3708 3709 const std::string &str = chunk.GetStringRef(); 3710 if (str.length() == 0) { 3711 // should have some data in chunk 3712 err.SetErrorString("Empty response from $qXfer packet"); 3713 return false; 3714 } 3715 3716 // check packet code 3717 switch (str[0]) { 3718 // last chunk 3719 case ('l'): 3720 active = false; 3721 LLVM_FALLTHROUGH; 3722 3723 // more chunks 3724 case ('m'): 3725 if (str.length() > 1) 3726 output << &str[1]; 3727 offset += size; 3728 break; 3729 3730 // unknown chunk 3731 default: 3732 err.SetErrorString("Invalid continuation code from $qXfer packet"); 3733 return false; 3734 } 3735 } 3736 3737 out = output.str(); 3738 err.Success(); 3739 return true; 3740 } 3741 3742 // Notify the target that gdb is prepared to serve symbol lookup requests. 3743 // packet: "qSymbol::" 3744 // reply: 3745 // OK The target does not need to look up any (more) symbols. 3746 // qSymbol:<sym_name> The target requests the value of symbol sym_name (hex 3747 // encoded). 3748 // LLDB may provide the value by sending another qSymbol 3749 // packet 3750 // in the form of"qSymbol:<sym_value>:<sym_name>". 3751 // 3752 // Three examples: 3753 // 3754 // lldb sends: qSymbol:: 3755 // lldb receives: OK 3756 // Remote gdb stub does not need to know the addresses of any symbols, lldb 3757 // does not 3758 // need to ask again in this session. 3759 // 3760 // lldb sends: qSymbol:: 3761 // lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473 3762 // lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473 3763 // lldb receives: OK 3764 // Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does 3765 // not know 3766 // the address at this time. lldb needs to send qSymbol:: again when it has 3767 // more 3768 // solibs loaded. 3769 // 3770 // lldb sends: qSymbol:: 3771 // lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473 3772 // lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473 3773 // lldb receives: OK 3774 // Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says 3775 // that it 3776 // is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it 3777 // does not 3778 // need any more symbols. lldb does not need to ask again in this session. 3779 3780 void GDBRemoteCommunicationClient::ServeSymbolLookups( 3781 lldb_private::Process *process) { 3782 // Set to true once we've resolved a symbol to an address for the remote 3783 // stub. If we get an 'OK' response after this, the remote stub doesn't need 3784 // any more symbols and we can stop asking. 3785 bool symbol_response_provided = false; 3786 3787 // Is this the initial qSymbol:: packet? 3788 bool first_qsymbol_query = true; 3789 3790 if (m_supports_qSymbol && m_qSymbol_requests_done == false) { 3791 Lock lock(*this, false); 3792 if (lock) { 3793 StreamString packet; 3794 packet.PutCString("qSymbol::"); 3795 StringExtractorGDBRemote response; 3796 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) == 3797 PacketResult::Success) { 3798 if (response.IsOKResponse()) { 3799 if (symbol_response_provided || first_qsymbol_query) { 3800 m_qSymbol_requests_done = true; 3801 } 3802 3803 // We are done serving symbols requests 3804 return; 3805 } 3806 first_qsymbol_query = false; 3807 3808 if (response.IsUnsupportedResponse()) { 3809 // qSymbol is not supported by the current GDB server we are 3810 // connected to 3811 m_supports_qSymbol = false; 3812 return; 3813 } else { 3814 llvm::StringRef response_str(response.GetStringRef()); 3815 if (response_str.startswith("qSymbol:")) { 3816 response.SetFilePos(strlen("qSymbol:")); 3817 std::string symbol_name; 3818 if (response.GetHexByteString(symbol_name)) { 3819 if (symbol_name.empty()) 3820 return; 3821 3822 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS; 3823 lldb_private::SymbolContextList sc_list; 3824 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType( 3825 ConstString(symbol_name), eSymbolTypeAny, sc_list)) { 3826 const size_t num_scs = sc_list.GetSize(); 3827 for (size_t sc_idx = 0; 3828 sc_idx < num_scs && 3829 symbol_load_addr == LLDB_INVALID_ADDRESS; 3830 ++sc_idx) { 3831 SymbolContext sc; 3832 if (sc_list.GetContextAtIndex(sc_idx, sc)) { 3833 if (sc.symbol) { 3834 switch (sc.symbol->GetType()) { 3835 case eSymbolTypeInvalid: 3836 case eSymbolTypeAbsolute: 3837 case eSymbolTypeUndefined: 3838 case eSymbolTypeSourceFile: 3839 case eSymbolTypeHeaderFile: 3840 case eSymbolTypeObjectFile: 3841 case eSymbolTypeCommonBlock: 3842 case eSymbolTypeBlock: 3843 case eSymbolTypeLocal: 3844 case eSymbolTypeParam: 3845 case eSymbolTypeVariable: 3846 case eSymbolTypeVariableType: 3847 case eSymbolTypeLineEntry: 3848 case eSymbolTypeLineHeader: 3849 case eSymbolTypeScopeBegin: 3850 case eSymbolTypeScopeEnd: 3851 case eSymbolTypeAdditional: 3852 case eSymbolTypeCompiler: 3853 case eSymbolTypeInstrumentation: 3854 case eSymbolTypeTrampoline: 3855 break; 3856 3857 case eSymbolTypeCode: 3858 case eSymbolTypeResolver: 3859 case eSymbolTypeData: 3860 case eSymbolTypeRuntime: 3861 case eSymbolTypeException: 3862 case eSymbolTypeObjCClass: 3863 case eSymbolTypeObjCMetaClass: 3864 case eSymbolTypeObjCIVar: 3865 case eSymbolTypeReExported: 3866 symbol_load_addr = 3867 sc.symbol->GetLoadAddress(&process->GetTarget()); 3868 break; 3869 } 3870 } 3871 } 3872 } 3873 } 3874 // This is the normal path where our symbol lookup was successful 3875 // and we want to send a packet with the new symbol value and see 3876 // if another lookup needs to be done. 3877 3878 // Change "packet" to contain the requested symbol value and name 3879 packet.Clear(); 3880 packet.PutCString("qSymbol:"); 3881 if (symbol_load_addr != LLDB_INVALID_ADDRESS) { 3882 packet.Printf("%" PRIx64, symbol_load_addr); 3883 symbol_response_provided = true; 3884 } else { 3885 symbol_response_provided = false; 3886 } 3887 packet.PutCString(":"); 3888 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size()); 3889 continue; // go back to the while loop and send "packet" and wait 3890 // for another response 3891 } 3892 } 3893 } 3894 } 3895 // If we make it here, the symbol request packet response wasn't valid or 3896 // our symbol lookup failed so we must abort 3897 return; 3898 3899 } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet( 3900 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) { 3901 log->Printf( 3902 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.", 3903 __FUNCTION__); 3904 } 3905 } 3906 } 3907 3908 StructuredData::Array * 3909 GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() { 3910 if (!m_supported_async_json_packets_is_valid) { 3911 // Query the server for the array of supported asynchronous JSON packets. 3912 m_supported_async_json_packets_is_valid = true; 3913 3914 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3915 3916 // Poll it now. 3917 StringExtractorGDBRemote response; 3918 const bool send_async = false; 3919 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response, 3920 send_async) == PacketResult::Success) { 3921 m_supported_async_json_packets_sp = 3922 StructuredData::ParseJSON(response.GetStringRef()); 3923 if (m_supported_async_json_packets_sp && 3924 !m_supported_async_json_packets_sp->GetAsArray()) { 3925 // We were returned something other than a JSON array. This is 3926 // invalid. Clear it out. 3927 if (log) 3928 log->Printf("GDBRemoteCommunicationClient::%s(): " 3929 "QSupportedAsyncJSONPackets returned invalid " 3930 "result: %s", 3931 __FUNCTION__, response.GetStringRef().c_str()); 3932 m_supported_async_json_packets_sp.reset(); 3933 } 3934 } else { 3935 if (log) 3936 log->Printf("GDBRemoteCommunicationClient::%s(): " 3937 "QSupportedAsyncJSONPackets unsupported", 3938 __FUNCTION__); 3939 } 3940 3941 if (log && m_supported_async_json_packets_sp) { 3942 StreamString stream; 3943 m_supported_async_json_packets_sp->Dump(stream); 3944 log->Printf("GDBRemoteCommunicationClient::%s(): supported async " 3945 "JSON packets: %s", 3946 __FUNCTION__, stream.GetData()); 3947 } 3948 } 3949 3950 return m_supported_async_json_packets_sp 3951 ? m_supported_async_json_packets_sp->GetAsArray() 3952 : nullptr; 3953 } 3954 3955 Status GDBRemoteCommunicationClient::SendSignalsToIgnore( 3956 llvm::ArrayRef<int32_t> signals) { 3957 // Format packet: 3958 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN> 3959 auto range = llvm::make_range(signals.begin(), signals.end()); 3960 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str(); 3961 3962 StringExtractorGDBRemote response; 3963 auto send_status = SendPacketAndWaitForResponse(packet, response, false); 3964 3965 if (send_status != GDBRemoteCommunication::PacketResult::Success) 3966 return Status("Sending QPassSignals packet failed"); 3967 3968 if (response.IsOKResponse()) { 3969 return Status(); 3970 } else { 3971 return Status("Unknown error happened during sending QPassSignals packet."); 3972 } 3973 } 3974 3975 Status GDBRemoteCommunicationClient::ConfigureRemoteStructuredData( 3976 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) { 3977 Status error; 3978 3979 if (type_name.GetLength() == 0) { 3980 error.SetErrorString("invalid type_name argument"); 3981 return error; 3982 } 3983 3984 // Build command: Configure{type_name}: serialized config data. 3985 StreamGDBRemote stream; 3986 stream.PutCString("QConfigure"); 3987 stream.PutCString(type_name.AsCString()); 3988 stream.PutChar(':'); 3989 if (config_sp) { 3990 // Gather the plain-text version of the configuration data. 3991 StreamString unescaped_stream; 3992 config_sp->Dump(unescaped_stream); 3993 unescaped_stream.Flush(); 3994 3995 // Add it to the stream in escaped fashion. 3996 stream.PutEscapedBytes(unescaped_stream.GetString().data(), 3997 unescaped_stream.GetSize()); 3998 } 3999 stream.Flush(); 4000 4001 // Send the packet. 4002 const bool send_async = false; 4003 StringExtractorGDBRemote response; 4004 auto result = 4005 SendPacketAndWaitForResponse(stream.GetString(), response, send_async); 4006 if (result == PacketResult::Success) { 4007 // We failed if the config result comes back other than OK. 4008 if (strcmp(response.GetStringRef().c_str(), "OK") == 0) { 4009 // Okay! 4010 error.Clear(); 4011 } else { 4012 error.SetErrorStringWithFormat("configuring StructuredData feature " 4013 "%s failed with error %s", 4014 type_name.AsCString(), 4015 response.GetStringRef().c_str()); 4016 } 4017 } else { 4018 // Can we get more data here on the failure? 4019 error.SetErrorStringWithFormat("configuring StructuredData feature %s " 4020 "failed when sending packet: " 4021 "PacketResult=%d", 4022 type_name.AsCString(), (int)result); 4023 } 4024 return error; 4025 } 4026 4027 void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) { 4028 GDBRemoteClientBase::OnRunPacketSent(first); 4029 m_curr_tid = LLDB_INVALID_THREAD_ID; 4030 } 4031