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