1 //===-- GDBRemoteCommunicationServerLLGS.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 <errno.h> 10 11 #include "lldb/Host/Config.h" 12 13 14 #include <chrono> 15 #include <cstring> 16 #include <thread> 17 18 #include "GDBRemoteCommunicationServerLLGS.h" 19 #include "lldb/Host/ConnectionFileDescriptor.h" 20 #include "lldb/Host/Debug.h" 21 #include "lldb/Host/File.h" 22 #include "lldb/Host/FileAction.h" 23 #include "lldb/Host/FileSystem.h" 24 #include "lldb/Host/Host.h" 25 #include "lldb/Host/HostInfo.h" 26 #include "lldb/Host/PosixApi.h" 27 #include "lldb/Host/common/NativeProcessProtocol.h" 28 #include "lldb/Host/common/NativeRegisterContext.h" 29 #include "lldb/Host/common/NativeThreadProtocol.h" 30 #include "lldb/Target/MemoryRegionInfo.h" 31 #include "lldb/Utility/Args.h" 32 #include "lldb/Utility/DataBuffer.h" 33 #include "lldb/Utility/Endian.h" 34 #include "lldb/Utility/GDBRemote.h" 35 #include "lldb/Utility/LLDBAssert.h" 36 #include "lldb/Utility/Log.h" 37 #include "lldb/Utility/RegisterValue.h" 38 #include "lldb/Utility/State.h" 39 #include "lldb/Utility/StreamString.h" 40 #include "lldb/Utility/UnimplementedError.h" 41 #include "lldb/Utility/UriParser.h" 42 #include "llvm/ADT/Triple.h" 43 #include "llvm/Support/JSON.h" 44 #include "llvm/Support/ScopedPrinter.h" 45 46 #include "ProcessGDBRemote.h" 47 #include "ProcessGDBRemoteLog.h" 48 #include "lldb/Utility/StringExtractorGDBRemote.h" 49 50 using namespace lldb; 51 using namespace lldb_private; 52 using namespace lldb_private::process_gdb_remote; 53 using namespace llvm; 54 55 // GDBRemote Errors 56 57 namespace { 58 enum GDBRemoteServerError { 59 // Set to the first unused error number in literal form below 60 eErrorFirst = 29, 61 eErrorNoProcess = eErrorFirst, 62 eErrorResume, 63 eErrorExitStatus 64 }; 65 } 66 67 // GDBRemoteCommunicationServerLLGS constructor 68 GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS( 69 MainLoop &mainloop, const NativeProcessProtocol::Factory &process_factory) 70 : GDBRemoteCommunicationServerCommon("gdb-remote.server", 71 "gdb-remote.server.rx_packet"), 72 m_mainloop(mainloop), m_process_factory(process_factory), 73 m_stdio_communication("process.stdio") { 74 RegisterPacketHandlers(); 75 } 76 77 void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() { 78 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C, 79 &GDBRemoteCommunicationServerLLGS::Handle_C); 80 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c, 81 &GDBRemoteCommunicationServerLLGS::Handle_c); 82 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D, 83 &GDBRemoteCommunicationServerLLGS::Handle_D); 84 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H, 85 &GDBRemoteCommunicationServerLLGS::Handle_H); 86 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I, 87 &GDBRemoteCommunicationServerLLGS::Handle_I); 88 RegisterMemberFunctionHandler( 89 StringExtractorGDBRemote::eServerPacketType_interrupt, 90 &GDBRemoteCommunicationServerLLGS::Handle_interrupt); 91 RegisterMemberFunctionHandler( 92 StringExtractorGDBRemote::eServerPacketType_m, 93 &GDBRemoteCommunicationServerLLGS::Handle_memory_read); 94 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M, 95 &GDBRemoteCommunicationServerLLGS::Handle_M); 96 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType__M, 97 &GDBRemoteCommunicationServerLLGS::Handle__M); 98 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType__m, 99 &GDBRemoteCommunicationServerLLGS::Handle__m); 100 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p, 101 &GDBRemoteCommunicationServerLLGS::Handle_p); 102 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P, 103 &GDBRemoteCommunicationServerLLGS::Handle_P); 104 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC, 105 &GDBRemoteCommunicationServerLLGS::Handle_qC); 106 RegisterMemberFunctionHandler( 107 StringExtractorGDBRemote::eServerPacketType_qfThreadInfo, 108 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo); 109 RegisterMemberFunctionHandler( 110 StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress, 111 &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress); 112 RegisterMemberFunctionHandler( 113 StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir, 114 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir); 115 RegisterMemberFunctionHandler( 116 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo, 117 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo); 118 RegisterMemberFunctionHandler( 119 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported, 120 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported); 121 RegisterMemberFunctionHandler( 122 StringExtractorGDBRemote::eServerPacketType_qProcessInfo, 123 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo); 124 RegisterMemberFunctionHandler( 125 StringExtractorGDBRemote::eServerPacketType_qRegisterInfo, 126 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo); 127 RegisterMemberFunctionHandler( 128 StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState, 129 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState); 130 RegisterMemberFunctionHandler( 131 StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState, 132 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState); 133 RegisterMemberFunctionHandler( 134 StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR, 135 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR); 136 RegisterMemberFunctionHandler( 137 StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir, 138 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir); 139 RegisterMemberFunctionHandler( 140 StringExtractorGDBRemote::eServerPacketType_qsThreadInfo, 141 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo); 142 RegisterMemberFunctionHandler( 143 StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo, 144 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo); 145 RegisterMemberFunctionHandler( 146 StringExtractorGDBRemote::eServerPacketType_jThreadsInfo, 147 &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo); 148 RegisterMemberFunctionHandler( 149 StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo, 150 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo); 151 RegisterMemberFunctionHandler( 152 StringExtractorGDBRemote::eServerPacketType_qXfer, 153 &GDBRemoteCommunicationServerLLGS::Handle_qXfer); 154 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s, 155 &GDBRemoteCommunicationServerLLGS::Handle_s); 156 RegisterMemberFunctionHandler( 157 StringExtractorGDBRemote::eServerPacketType_stop_reason, 158 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ? 159 RegisterMemberFunctionHandler( 160 StringExtractorGDBRemote::eServerPacketType_vAttach, 161 &GDBRemoteCommunicationServerLLGS::Handle_vAttach); 162 RegisterMemberFunctionHandler( 163 StringExtractorGDBRemote::eServerPacketType_vCont, 164 &GDBRemoteCommunicationServerLLGS::Handle_vCont); 165 RegisterMemberFunctionHandler( 166 StringExtractorGDBRemote::eServerPacketType_vCont_actions, 167 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions); 168 RegisterMemberFunctionHandler( 169 StringExtractorGDBRemote::eServerPacketType_x, 170 &GDBRemoteCommunicationServerLLGS::Handle_memory_read); 171 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z, 172 &GDBRemoteCommunicationServerLLGS::Handle_Z); 173 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z, 174 &GDBRemoteCommunicationServerLLGS::Handle_z); 175 RegisterMemberFunctionHandler( 176 StringExtractorGDBRemote::eServerPacketType_QPassSignals, 177 &GDBRemoteCommunicationServerLLGS::Handle_QPassSignals); 178 179 RegisterMemberFunctionHandler( 180 StringExtractorGDBRemote::eServerPacketType_jTraceStart, 181 &GDBRemoteCommunicationServerLLGS::Handle_jTraceStart); 182 RegisterMemberFunctionHandler( 183 StringExtractorGDBRemote::eServerPacketType_jTraceBufferRead, 184 &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead); 185 RegisterMemberFunctionHandler( 186 StringExtractorGDBRemote::eServerPacketType_jTraceMetaRead, 187 &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead); 188 RegisterMemberFunctionHandler( 189 StringExtractorGDBRemote::eServerPacketType_jTraceStop, 190 &GDBRemoteCommunicationServerLLGS::Handle_jTraceStop); 191 RegisterMemberFunctionHandler( 192 StringExtractorGDBRemote::eServerPacketType_jTraceConfigRead, 193 &GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead); 194 RegisterMemberFunctionHandler( 195 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceSupportedType, 196 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceSupportedType); 197 198 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_g, 199 &GDBRemoteCommunicationServerLLGS::Handle_g); 200 201 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k, 202 [this](StringExtractorGDBRemote packet, Status &error, 203 bool &interrupt, bool &quit) { 204 quit = true; 205 return this->Handle_k(packet); 206 }); 207 } 208 209 void GDBRemoteCommunicationServerLLGS::SetLaunchInfo(const ProcessLaunchInfo &info) { 210 m_process_launch_info = info; 211 } 212 213 Status GDBRemoteCommunicationServerLLGS::LaunchProcess() { 214 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 215 216 if (!m_process_launch_info.GetArguments().GetArgumentCount()) 217 return Status("%s: no process command line specified to launch", 218 __FUNCTION__); 219 220 const bool should_forward_stdio = 221 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr || 222 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr || 223 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr; 224 m_process_launch_info.SetLaunchInSeparateProcessGroup(true); 225 m_process_launch_info.GetFlags().Set(eLaunchFlagDebug); 226 227 if (should_forward_stdio) { 228 // Temporarily relax the following for Windows until we can take advantage 229 // of the recently added pty support. This doesn't really affect the use of 230 // lldb-server on Windows. 231 #if !defined(_WIN32) 232 if (llvm::Error Err = m_process_launch_info.SetUpPtyRedirection()) 233 return Status(std::move(Err)); 234 #endif 235 } 236 237 { 238 std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex); 239 assert(!m_debugged_process_up && "lldb-server creating debugged " 240 "process but one already exists"); 241 auto process_or = 242 m_process_factory.Launch(m_process_launch_info, *this, m_mainloop); 243 if (!process_or) 244 return Status(process_or.takeError()); 245 m_debugged_process_up = std::move(*process_or); 246 } 247 248 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol as 249 // needed. llgs local-process debugging may specify PTY paths, which will 250 // make these file actions non-null process launch -i/e/o will also make 251 // these file actions non-null nullptr means that the traffic is expected to 252 // flow over gdb-remote protocol 253 if (should_forward_stdio) { 254 // nullptr means it's not redirected to file or pty (in case of LLGS local) 255 // at least one of stdio will be transferred pty<->gdb-remote we need to 256 // give the pty master handle to this object to read and/or write 257 LLDB_LOG(log, 258 "pid = {0}: setting up stdout/stderr redirection via $O " 259 "gdb-remote commands", 260 m_debugged_process_up->GetID()); 261 262 // Setup stdout/stderr mapping from inferior to $O 263 auto terminal_fd = m_debugged_process_up->GetTerminalFileDescriptor(); 264 if (terminal_fd >= 0) { 265 LLDB_LOGF(log, 266 "ProcessGDBRemoteCommunicationServerLLGS::%s setting " 267 "inferior STDIO fd to %d", 268 __FUNCTION__, terminal_fd); 269 Status status = SetSTDIOFileDescriptor(terminal_fd); 270 if (status.Fail()) 271 return status; 272 } else { 273 LLDB_LOGF(log, 274 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring " 275 "inferior STDIO since terminal fd reported as %d", 276 __FUNCTION__, terminal_fd); 277 } 278 } else { 279 LLDB_LOG(log, 280 "pid = {0} skipping stdout/stderr redirection via $O: inferior " 281 "will communicate over client-provided file descriptors", 282 m_debugged_process_up->GetID()); 283 } 284 285 printf("Launched '%s' as process %" PRIu64 "...\n", 286 m_process_launch_info.GetArguments().GetArgumentAtIndex(0), 287 m_debugged_process_up->GetID()); 288 289 return Status(); 290 } 291 292 Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) { 293 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 294 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64, 295 __FUNCTION__, pid); 296 297 // Before we try to attach, make sure we aren't already monitoring something 298 // else. 299 if (m_debugged_process_up && 300 m_debugged_process_up->GetID() != LLDB_INVALID_PROCESS_ID) 301 return Status("cannot attach to process %" PRIu64 302 " when another process with pid %" PRIu64 303 " is being debugged.", 304 pid, m_debugged_process_up->GetID()); 305 306 // Try to attach. 307 auto process_or = m_process_factory.Attach(pid, *this, m_mainloop); 308 if (!process_or) { 309 Status status(process_or.takeError()); 310 llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}", pid, 311 status); 312 return status; 313 } 314 m_debugged_process_up = std::move(*process_or); 315 316 // Setup stdout/stderr mapping from inferior. 317 auto terminal_fd = m_debugged_process_up->GetTerminalFileDescriptor(); 318 if (terminal_fd >= 0) { 319 LLDB_LOGF(log, 320 "ProcessGDBRemoteCommunicationServerLLGS::%s setting " 321 "inferior STDIO fd to %d", 322 __FUNCTION__, terminal_fd); 323 Status status = SetSTDIOFileDescriptor(terminal_fd); 324 if (status.Fail()) 325 return status; 326 } else { 327 LLDB_LOGF(log, 328 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring " 329 "inferior STDIO since terminal fd reported as %d", 330 __FUNCTION__, terminal_fd); 331 } 332 333 printf("Attached to process %" PRIu64 "...\n", pid); 334 return Status(); 335 } 336 337 void GDBRemoteCommunicationServerLLGS::InitializeDelegate( 338 NativeProcessProtocol *process) { 339 assert(process && "process cannot be NULL"); 340 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 341 if (log) { 342 LLDB_LOGF(log, 343 "GDBRemoteCommunicationServerLLGS::%s called with " 344 "NativeProcessProtocol pid %" PRIu64 ", current state: %s", 345 __FUNCTION__, process->GetID(), 346 StateAsCString(process->GetState())); 347 } 348 } 349 350 GDBRemoteCommunication::PacketResult 351 GDBRemoteCommunicationServerLLGS::SendWResponse( 352 NativeProcessProtocol *process) { 353 assert(process && "process cannot be NULL"); 354 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 355 356 // send W notification 357 auto wait_status = process->GetExitStatus(); 358 if (!wait_status) { 359 LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status", 360 process->GetID()); 361 362 StreamGDBRemote response; 363 response.PutChar('E'); 364 response.PutHex8(GDBRemoteServerError::eErrorExitStatus); 365 return SendPacketNoLock(response.GetString()); 366 } 367 368 LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(), 369 *wait_status); 370 371 StreamGDBRemote response; 372 response.Format("{0:g}", *wait_status); 373 return SendPacketNoLock(response.GetString()); 374 } 375 376 static void AppendHexValue(StreamString &response, const uint8_t *buf, 377 uint32_t buf_size, bool swap) { 378 int64_t i; 379 if (swap) { 380 for (i = buf_size - 1; i >= 0; i--) 381 response.PutHex8(buf[i]); 382 } else { 383 for (i = 0; i < buf_size; i++) 384 response.PutHex8(buf[i]); 385 } 386 } 387 388 static llvm::StringRef GetEncodingNameOrEmpty(const RegisterInfo ®_info) { 389 switch (reg_info.encoding) { 390 case eEncodingUint: 391 return "uint"; 392 case eEncodingSint: 393 return "sint"; 394 case eEncodingIEEE754: 395 return "ieee754"; 396 case eEncodingVector: 397 return "vector"; 398 default: 399 return ""; 400 } 401 } 402 403 static llvm::StringRef GetFormatNameOrEmpty(const RegisterInfo ®_info) { 404 switch (reg_info.format) { 405 case eFormatBinary: 406 return "binary"; 407 case eFormatDecimal: 408 return "decimal"; 409 case eFormatHex: 410 return "hex"; 411 case eFormatFloat: 412 return "float"; 413 case eFormatVectorOfSInt8: 414 return "vector-sint8"; 415 case eFormatVectorOfUInt8: 416 return "vector-uint8"; 417 case eFormatVectorOfSInt16: 418 return "vector-sint16"; 419 case eFormatVectorOfUInt16: 420 return "vector-uint16"; 421 case eFormatVectorOfSInt32: 422 return "vector-sint32"; 423 case eFormatVectorOfUInt32: 424 return "vector-uint32"; 425 case eFormatVectorOfFloat32: 426 return "vector-float32"; 427 case eFormatVectorOfUInt64: 428 return "vector-uint64"; 429 case eFormatVectorOfUInt128: 430 return "vector-uint128"; 431 default: 432 return ""; 433 }; 434 } 435 436 static llvm::StringRef GetKindGenericOrEmpty(const RegisterInfo ®_info) { 437 switch (reg_info.kinds[RegisterKind::eRegisterKindGeneric]) { 438 case LLDB_REGNUM_GENERIC_PC: 439 return "pc"; 440 case LLDB_REGNUM_GENERIC_SP: 441 return "sp"; 442 case LLDB_REGNUM_GENERIC_FP: 443 return "fp"; 444 case LLDB_REGNUM_GENERIC_RA: 445 return "ra"; 446 case LLDB_REGNUM_GENERIC_FLAGS: 447 return "flags"; 448 case LLDB_REGNUM_GENERIC_ARG1: 449 return "arg1"; 450 case LLDB_REGNUM_GENERIC_ARG2: 451 return "arg2"; 452 case LLDB_REGNUM_GENERIC_ARG3: 453 return "arg3"; 454 case LLDB_REGNUM_GENERIC_ARG4: 455 return "arg4"; 456 case LLDB_REGNUM_GENERIC_ARG5: 457 return "arg5"; 458 case LLDB_REGNUM_GENERIC_ARG6: 459 return "arg6"; 460 case LLDB_REGNUM_GENERIC_ARG7: 461 return "arg7"; 462 case LLDB_REGNUM_GENERIC_ARG8: 463 return "arg8"; 464 default: 465 return ""; 466 } 467 } 468 469 static void CollectRegNums(const uint32_t *reg_num, StreamString &response, 470 bool usehex) { 471 for (int i = 0; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) { 472 if (i > 0) 473 response.PutChar(','); 474 if (usehex) 475 response.Printf("%" PRIx32, *reg_num); 476 else 477 response.Printf("%" PRIu32, *reg_num); 478 } 479 } 480 481 static void WriteRegisterValueInHexFixedWidth( 482 StreamString &response, NativeRegisterContext ®_ctx, 483 const RegisterInfo ®_info, const RegisterValue *reg_value_p, 484 lldb::ByteOrder byte_order) { 485 RegisterValue reg_value; 486 if (!reg_value_p) { 487 Status error = reg_ctx.ReadRegister(®_info, reg_value); 488 if (error.Success()) 489 reg_value_p = ®_value; 490 // else log. 491 } 492 493 if (reg_value_p) { 494 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(), 495 reg_value_p->GetByteSize(), 496 byte_order == lldb::eByteOrderLittle); 497 } else { 498 // Zero-out any unreadable values. 499 if (reg_info.byte_size > 0) { 500 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0'); 501 AppendHexValue(response, zeros.data(), zeros.size(), false); 502 } 503 } 504 } 505 506 static llvm::Optional<json::Object> 507 GetRegistersAsJSON(NativeThreadProtocol &thread) { 508 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 509 510 NativeRegisterContext& reg_ctx = thread.GetRegisterContext(); 511 512 json::Object register_object; 513 514 #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET 515 const auto expedited_regs = 516 reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Full); 517 #else 518 const auto expedited_regs = 519 reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Minimal); 520 #endif 521 if (expedited_regs.empty()) 522 return llvm::None; 523 524 for (auto ®_num : expedited_regs) { 525 const RegisterInfo *const reg_info_p = 526 reg_ctx.GetRegisterInfoAtIndex(reg_num); 527 if (reg_info_p == nullptr) { 528 LLDB_LOGF(log, 529 "%s failed to get register info for register index %" PRIu32, 530 __FUNCTION__, reg_num); 531 continue; 532 } 533 534 if (reg_info_p->value_regs != nullptr) 535 continue; // Only expedite registers that are not contained in other 536 // registers. 537 538 RegisterValue reg_value; 539 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value); 540 if (error.Fail()) { 541 LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s", 542 __FUNCTION__, 543 reg_info_p->name ? reg_info_p->name : "<unnamed-register>", 544 reg_num, error.AsCString()); 545 continue; 546 } 547 548 StreamString stream; 549 WriteRegisterValueInHexFixedWidth(stream, reg_ctx, *reg_info_p, 550 ®_value, lldb::eByteOrderBig); 551 552 register_object.try_emplace(llvm::to_string(reg_num), 553 stream.GetString().str()); 554 } 555 556 return register_object; 557 } 558 559 static const char *GetStopReasonString(StopReason stop_reason) { 560 switch (stop_reason) { 561 case eStopReasonTrace: 562 return "trace"; 563 case eStopReasonBreakpoint: 564 return "breakpoint"; 565 case eStopReasonWatchpoint: 566 return "watchpoint"; 567 case eStopReasonSignal: 568 return "signal"; 569 case eStopReasonException: 570 return "exception"; 571 case eStopReasonExec: 572 return "exec"; 573 case eStopReasonInstrumentation: 574 case eStopReasonInvalid: 575 case eStopReasonPlanComplete: 576 case eStopReasonThreadExiting: 577 case eStopReasonNone: 578 break; // ignored 579 } 580 return nullptr; 581 } 582 583 static llvm::Expected<json::Array> 584 GetJSONThreadsInfo(NativeProcessProtocol &process, bool abridged) { 585 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 586 587 json::Array threads_array; 588 589 // Ensure we can get info on the given thread. 590 uint32_t thread_idx = 0; 591 for (NativeThreadProtocol *thread; 592 (thread = process.GetThreadAtIndex(thread_idx)) != nullptr; 593 ++thread_idx) { 594 595 lldb::tid_t tid = thread->GetID(); 596 597 // Grab the reason this thread stopped. 598 struct ThreadStopInfo tid_stop_info; 599 std::string description; 600 if (!thread->GetStopReason(tid_stop_info, description)) 601 return llvm::make_error<llvm::StringError>( 602 "failed to get stop reason", llvm::inconvertibleErrorCode()); 603 604 const int signum = tid_stop_info.details.signal.signo; 605 if (log) { 606 LLDB_LOGF(log, 607 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 608 " tid %" PRIu64 609 " got signal signo = %d, reason = %d, exc_type = %" PRIu64, 610 __FUNCTION__, process.GetID(), tid, signum, 611 tid_stop_info.reason, tid_stop_info.details.exception.type); 612 } 613 614 json::Object thread_obj; 615 616 if (!abridged) { 617 if (llvm::Optional<json::Object> registers = GetRegistersAsJSON(*thread)) 618 thread_obj.try_emplace("registers", std::move(*registers)); 619 } 620 621 thread_obj.try_emplace("tid", static_cast<int64_t>(tid)); 622 623 if (signum != 0) 624 thread_obj.try_emplace("signal", signum); 625 626 const std::string thread_name = thread->GetName(); 627 if (!thread_name.empty()) 628 thread_obj.try_emplace("name", thread_name); 629 630 const char *stop_reason = GetStopReasonString(tid_stop_info.reason); 631 if (stop_reason) 632 thread_obj.try_emplace("reason", stop_reason); 633 634 if (!description.empty()) 635 thread_obj.try_emplace("description", description); 636 637 if ((tid_stop_info.reason == eStopReasonException) && 638 tid_stop_info.details.exception.type) { 639 thread_obj.try_emplace( 640 "metype", static_cast<int64_t>(tid_stop_info.details.exception.type)); 641 642 json::Array medata_array; 643 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; 644 ++i) { 645 medata_array.push_back( 646 static_cast<int64_t>(tid_stop_info.details.exception.data[i])); 647 } 648 thread_obj.try_emplace("medata", std::move(medata_array)); 649 } 650 threads_array.push_back(std::move(thread_obj)); 651 } 652 return threads_array; 653 } 654 655 GDBRemoteCommunication::PacketResult 656 GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread( 657 lldb::tid_t tid) { 658 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 659 660 // Ensure we have a debugged process. 661 if (!m_debugged_process_up || 662 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) 663 return SendErrorResponse(50); 664 665 LLDB_LOG(log, "preparing packet for pid {0} tid {1}", 666 m_debugged_process_up->GetID(), tid); 667 668 // Ensure we can get info on the given thread. 669 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid); 670 if (!thread) 671 return SendErrorResponse(51); 672 673 // Grab the reason this thread stopped. 674 struct ThreadStopInfo tid_stop_info; 675 std::string description; 676 if (!thread->GetStopReason(tid_stop_info, description)) 677 return SendErrorResponse(52); 678 679 // FIXME implement register handling for exec'd inferiors. 680 // if (tid_stop_info.reason == eStopReasonExec) { 681 // const bool force = true; 682 // InitializeRegisters(force); 683 // } 684 685 StreamString response; 686 // Output the T packet with the thread 687 response.PutChar('T'); 688 int signum = tid_stop_info.details.signal.signo; 689 LLDB_LOG( 690 log, 691 "pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}", 692 m_debugged_process_up->GetID(), tid, signum, int(tid_stop_info.reason), 693 tid_stop_info.details.exception.type); 694 695 // Print the signal number. 696 response.PutHex8(signum & 0xff); 697 698 // Include the tid. 699 response.Printf("thread:%" PRIx64 ";", tid); 700 701 // Include the thread name if there is one. 702 const std::string thread_name = thread->GetName(); 703 if (!thread_name.empty()) { 704 size_t thread_name_len = thread_name.length(); 705 706 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) { 707 response.PutCString("name:"); 708 response.PutCString(thread_name); 709 } else { 710 // The thread name contains special chars, send as hex bytes. 711 response.PutCString("hexname:"); 712 response.PutStringAsRawHex8(thread_name); 713 } 714 response.PutChar(';'); 715 } 716 717 // If a 'QListThreadsInStopReply' was sent to enable this feature, we will 718 // send all thread IDs back in the "threads" key whose value is a list of hex 719 // thread IDs separated by commas: 720 // "threads:10a,10b,10c;" 721 // This will save the debugger from having to send a pair of qfThreadInfo and 722 // qsThreadInfo packets, but it also might take a lot of room in the stop 723 // reply packet, so it must be enabled only on systems where there are no 724 // limits on packet lengths. 725 if (m_list_threads_in_stop_reply) { 726 response.PutCString("threads:"); 727 728 uint32_t thread_index = 0; 729 NativeThreadProtocol *listed_thread; 730 for (listed_thread = m_debugged_process_up->GetThreadAtIndex(thread_index); 731 listed_thread; ++thread_index, 732 listed_thread = m_debugged_process_up->GetThreadAtIndex(thread_index)) { 733 if (thread_index > 0) 734 response.PutChar(','); 735 response.Printf("%" PRIx64, listed_thread->GetID()); 736 } 737 response.PutChar(';'); 738 739 // Include JSON info that describes the stop reason for any threads that 740 // actually have stop reasons. We use the new "jstopinfo" key whose values 741 // is hex ascii JSON that contains the thread IDs thread stop info only for 742 // threads that have stop reasons. Only send this if we have more than one 743 // thread otherwise this packet has all the info it needs. 744 if (thread_index > 1) { 745 const bool threads_with_valid_stop_info_only = true; 746 llvm::Expected<json::Array> threads_info = GetJSONThreadsInfo( 747 *m_debugged_process_up, threads_with_valid_stop_info_only); 748 if (threads_info) { 749 response.PutCString("jstopinfo:"); 750 StreamString unescaped_response; 751 unescaped_response.AsRawOstream() << std::move(*threads_info); 752 response.PutStringAsRawHex8(unescaped_response.GetData()); 753 response.PutChar(';'); 754 } else { 755 LLDB_LOG_ERROR(log, threads_info.takeError(), 756 "failed to prepare a jstopinfo field for pid {1}: {0}", 757 m_debugged_process_up->GetID()); 758 } 759 } 760 761 uint32_t i = 0; 762 response.PutCString("thread-pcs"); 763 char delimiter = ':'; 764 for (NativeThreadProtocol *thread; 765 (thread = m_debugged_process_up->GetThreadAtIndex(i)) != nullptr; 766 ++i) { 767 NativeRegisterContext& reg_ctx = thread->GetRegisterContext(); 768 769 uint32_t reg_to_read = reg_ctx.ConvertRegisterKindToRegisterNumber( 770 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); 771 const RegisterInfo *const reg_info_p = 772 reg_ctx.GetRegisterInfoAtIndex(reg_to_read); 773 774 RegisterValue reg_value; 775 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value); 776 if (error.Fail()) { 777 LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s", 778 __FUNCTION__, 779 reg_info_p->name ? reg_info_p->name : "<unnamed-register>", 780 reg_to_read, error.AsCString()); 781 continue; 782 } 783 784 response.PutChar(delimiter); 785 delimiter = ','; 786 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p, 787 ®_value, endian::InlHostByteOrder()); 788 } 789 790 response.PutChar(';'); 791 } 792 793 // 794 // Expedite registers. 795 // 796 797 // Grab the register context. 798 NativeRegisterContext& reg_ctx = thread->GetRegisterContext(); 799 const auto expedited_regs = 800 reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Full); 801 802 for (auto ®_num : expedited_regs) { 803 const RegisterInfo *const reg_info_p = 804 reg_ctx.GetRegisterInfoAtIndex(reg_num); 805 // Only expediate registers that are not contained in other registers. 806 if (reg_info_p != nullptr && reg_info_p->value_regs == nullptr) { 807 RegisterValue reg_value; 808 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value); 809 if (error.Success()) { 810 response.Printf("%.02x:", reg_num); 811 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p, 812 ®_value, lldb::eByteOrderBig); 813 response.PutChar(';'); 814 } else { 815 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s failed to read " 816 "register '%s' index %" PRIu32 ": %s", 817 __FUNCTION__, 818 reg_info_p->name ? reg_info_p->name : "<unnamed-register>", 819 reg_num, error.AsCString()); 820 } 821 } 822 } 823 824 const char *reason_str = GetStopReasonString(tid_stop_info.reason); 825 if (reason_str != nullptr) { 826 response.Printf("reason:%s;", reason_str); 827 } 828 829 if (!description.empty()) { 830 // Description may contains special chars, send as hex bytes. 831 response.PutCString("description:"); 832 response.PutStringAsRawHex8(description); 833 response.PutChar(';'); 834 } else if ((tid_stop_info.reason == eStopReasonException) && 835 tid_stop_info.details.exception.type) { 836 response.PutCString("metype:"); 837 response.PutHex64(tid_stop_info.details.exception.type); 838 response.PutCString(";mecount:"); 839 response.PutHex32(tid_stop_info.details.exception.data_count); 840 response.PutChar(';'); 841 842 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) { 843 response.PutCString("medata:"); 844 response.PutHex64(tid_stop_info.details.exception.data[i]); 845 response.PutChar(';'); 846 } 847 } 848 849 return SendPacketNoLock(response.GetString()); 850 } 851 852 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited( 853 NativeProcessProtocol *process) { 854 assert(process && "process cannot be NULL"); 855 856 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 857 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__); 858 859 PacketResult result = SendStopReasonForState(StateType::eStateExited); 860 if (result != PacketResult::Success) { 861 LLDB_LOGF(log, 862 "GDBRemoteCommunicationServerLLGS::%s failed to send stop " 863 "notification for PID %" PRIu64 ", state: eStateExited", 864 __FUNCTION__, process->GetID()); 865 } 866 867 // Close the pipe to the inferior terminal i/o if we launched it and set one 868 // up. 869 MaybeCloseInferiorTerminalConnection(); 870 871 // We are ready to exit the debug monitor. 872 m_exit_now = true; 873 m_mainloop.RequestTermination(); 874 } 875 876 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped( 877 NativeProcessProtocol *process) { 878 assert(process && "process cannot be NULL"); 879 880 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 881 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__); 882 883 // Send the stop reason unless this is the stop after the launch or attach. 884 switch (m_inferior_prev_state) { 885 case eStateLaunching: 886 case eStateAttaching: 887 // Don't send anything per debugserver behavior. 888 break; 889 default: 890 // In all other cases, send the stop reason. 891 PacketResult result = SendStopReasonForState(StateType::eStateStopped); 892 if (result != PacketResult::Success) { 893 LLDB_LOGF(log, 894 "GDBRemoteCommunicationServerLLGS::%s failed to send stop " 895 "notification for PID %" PRIu64 ", state: eStateExited", 896 __FUNCTION__, process->GetID()); 897 } 898 break; 899 } 900 } 901 902 void GDBRemoteCommunicationServerLLGS::ProcessStateChanged( 903 NativeProcessProtocol *process, lldb::StateType state) { 904 assert(process && "process cannot be NULL"); 905 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 906 if (log) { 907 LLDB_LOGF(log, 908 "GDBRemoteCommunicationServerLLGS::%s called with " 909 "NativeProcessProtocol pid %" PRIu64 ", state: %s", 910 __FUNCTION__, process->GetID(), StateAsCString(state)); 911 } 912 913 switch (state) { 914 case StateType::eStateRunning: 915 StartSTDIOForwarding(); 916 break; 917 918 case StateType::eStateStopped: 919 // Make sure we get all of the pending stdout/stderr from the inferior and 920 // send it to the lldb host before we send the state change notification 921 SendProcessOutput(); 922 // Then stop the forwarding, so that any late output (see llvm.org/pr25652) 923 // does not interfere with our protocol. 924 StopSTDIOForwarding(); 925 HandleInferiorState_Stopped(process); 926 break; 927 928 case StateType::eStateExited: 929 // Same as above 930 SendProcessOutput(); 931 StopSTDIOForwarding(); 932 HandleInferiorState_Exited(process); 933 break; 934 935 default: 936 if (log) { 937 LLDB_LOGF(log, 938 "GDBRemoteCommunicationServerLLGS::%s didn't handle state " 939 "change for pid %" PRIu64 ", new state: %s", 940 __FUNCTION__, process->GetID(), StateAsCString(state)); 941 } 942 break; 943 } 944 945 // Remember the previous state reported to us. 946 m_inferior_prev_state = state; 947 } 948 949 void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) { 950 ClearProcessSpecificData(); 951 } 952 953 void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() { 954 Log *log(GetLogIfAnyCategoriesSet(GDBR_LOG_COMM)); 955 956 if (!m_handshake_completed) { 957 if (!HandshakeWithClient()) { 958 LLDB_LOGF(log, 959 "GDBRemoteCommunicationServerLLGS::%s handshake with " 960 "client failed, exiting", 961 __FUNCTION__); 962 m_mainloop.RequestTermination(); 963 return; 964 } 965 m_handshake_completed = true; 966 } 967 968 bool interrupt = false; 969 bool done = false; 970 Status error; 971 while (true) { 972 const PacketResult result = GetPacketAndSendResponse( 973 std::chrono::microseconds(0), error, interrupt, done); 974 if (result == PacketResult::ErrorReplyTimeout) 975 break; // No more packets in the queue 976 977 if ((result != PacketResult::Success)) { 978 LLDB_LOGF(log, 979 "GDBRemoteCommunicationServerLLGS::%s processing a packet " 980 "failed: %s", 981 __FUNCTION__, error.AsCString()); 982 m_mainloop.RequestTermination(); 983 break; 984 } 985 } 986 } 987 988 Status GDBRemoteCommunicationServerLLGS::InitializeConnection( 989 std::unique_ptr<Connection> connection) { 990 IOObjectSP read_object_sp = connection->GetReadObject(); 991 GDBRemoteCommunicationServer::SetConnection(std::move(connection)); 992 993 Status error; 994 m_network_handle_up = m_mainloop.RegisterReadObject( 995 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); }, 996 error); 997 return error; 998 } 999 1000 GDBRemoteCommunication::PacketResult 1001 GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer, 1002 uint32_t len) { 1003 if ((buffer == nullptr) || (len == 0)) { 1004 // Nothing to send. 1005 return PacketResult::Success; 1006 } 1007 1008 StreamString response; 1009 response.PutChar('O'); 1010 response.PutBytesAsRawHex8(buffer, len); 1011 1012 return SendPacketNoLock(response.GetString()); 1013 } 1014 1015 Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) { 1016 Status error; 1017 1018 // Set up the reading/handling of process I/O 1019 std::unique_ptr<ConnectionFileDescriptor> conn_up( 1020 new ConnectionFileDescriptor(fd, true)); 1021 if (!conn_up) { 1022 error.SetErrorString("failed to create ConnectionFileDescriptor"); 1023 return error; 1024 } 1025 1026 m_stdio_communication.SetCloseOnEOF(false); 1027 m_stdio_communication.SetConnection(std::move(conn_up)); 1028 if (!m_stdio_communication.IsConnected()) { 1029 error.SetErrorString( 1030 "failed to set connection for inferior I/O communication"); 1031 return error; 1032 } 1033 1034 return Status(); 1035 } 1036 1037 void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() { 1038 // Don't forward if not connected (e.g. when attaching). 1039 if (!m_stdio_communication.IsConnected()) 1040 return; 1041 1042 Status error; 1043 lldbassert(!m_stdio_handle_up); 1044 m_stdio_handle_up = m_mainloop.RegisterReadObject( 1045 m_stdio_communication.GetConnection()->GetReadObject(), 1046 [this](MainLoopBase &) { SendProcessOutput(); }, error); 1047 1048 if (!m_stdio_handle_up) { 1049 // Not much we can do about the failure. Log it and continue without 1050 // forwarding. 1051 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)) 1052 LLDB_LOGF(log, 1053 "GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio " 1054 "forwarding: %s", 1055 __FUNCTION__, error.AsCString()); 1056 } 1057 } 1058 1059 void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() { 1060 m_stdio_handle_up.reset(); 1061 } 1062 1063 void GDBRemoteCommunicationServerLLGS::SendProcessOutput() { 1064 char buffer[1024]; 1065 ConnectionStatus status; 1066 Status error; 1067 while (true) { 1068 size_t bytes_read = m_stdio_communication.Read( 1069 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error); 1070 switch (status) { 1071 case eConnectionStatusSuccess: 1072 SendONotification(buffer, bytes_read); 1073 break; 1074 case eConnectionStatusLostConnection: 1075 case eConnectionStatusEndOfFile: 1076 case eConnectionStatusError: 1077 case eConnectionStatusNoConnection: 1078 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)) 1079 LLDB_LOGF(log, 1080 "GDBRemoteCommunicationServerLLGS::%s Stopping stdio " 1081 "forwarding as communication returned status %d (error: " 1082 "%s)", 1083 __FUNCTION__, status, error.AsCString()); 1084 m_stdio_handle_up.reset(); 1085 return; 1086 1087 case eConnectionStatusInterrupted: 1088 case eConnectionStatusTimedOut: 1089 return; 1090 } 1091 } 1092 } 1093 1094 GDBRemoteCommunication::PacketResult 1095 GDBRemoteCommunicationServerLLGS::Handle_jTraceStart( 1096 StringExtractorGDBRemote &packet) { 1097 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 1098 // Fail if we don't have a current process. 1099 if (!m_debugged_process_up || 1100 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) 1101 return SendErrorResponse(68); 1102 1103 if (!packet.ConsumeFront("jTraceStart:")) 1104 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet "); 1105 1106 TraceOptions options; 1107 uint64_t type = std::numeric_limits<uint64_t>::max(); 1108 uint64_t buffersize = std::numeric_limits<uint64_t>::max(); 1109 lldb::tid_t tid = LLDB_INVALID_THREAD_ID; 1110 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max(); 1111 1112 auto json_object = StructuredData::ParseJSON(packet.Peek()); 1113 1114 if (!json_object || 1115 json_object->GetType() != lldb::eStructuredDataTypeDictionary) 1116 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet "); 1117 1118 auto json_dict = json_object->GetAsDictionary(); 1119 1120 json_dict->GetValueForKeyAsInteger("metabuffersize", metabuffersize); 1121 options.setMetaDataBufferSize(metabuffersize); 1122 1123 json_dict->GetValueForKeyAsInteger("buffersize", buffersize); 1124 options.setTraceBufferSize(buffersize); 1125 1126 json_dict->GetValueForKeyAsInteger("type", type); 1127 options.setType(static_cast<lldb::TraceType>(type)); 1128 1129 json_dict->GetValueForKeyAsInteger("threadid", tid); 1130 options.setThreadID(tid); 1131 1132 StructuredData::ObjectSP custom_params_sp = 1133 json_dict->GetValueForKey("params"); 1134 if (custom_params_sp && 1135 custom_params_sp->GetType() != lldb::eStructuredDataTypeDictionary) 1136 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet "); 1137 1138 options.setTraceParams( 1139 std::static_pointer_cast<StructuredData::Dictionary>(custom_params_sp)); 1140 1141 if (buffersize == std::numeric_limits<uint64_t>::max() || 1142 type != lldb::TraceType::eTraceTypeProcessorTrace) { 1143 LLDB_LOG(log, "Ill formed packet buffersize = {0} type = {1}", buffersize, 1144 type); 1145 return SendIllFormedResponse(packet, "JTrace:start: Ill formed packet "); 1146 } 1147 1148 Status error; 1149 lldb::user_id_t uid = LLDB_INVALID_UID; 1150 uid = m_debugged_process_up->StartTrace(options, error); 1151 LLDB_LOG(log, "uid is {0} , error is {1}", uid, error.GetError()); 1152 if (error.Fail()) 1153 return SendErrorResponse(error); 1154 1155 StreamGDBRemote response; 1156 response.Printf("%" PRIx64, uid); 1157 return SendPacketNoLock(response.GetString()); 1158 } 1159 1160 GDBRemoteCommunication::PacketResult 1161 GDBRemoteCommunicationServerLLGS::Handle_jTraceStop( 1162 StringExtractorGDBRemote &packet) { 1163 // Fail if we don't have a current process. 1164 if (!m_debugged_process_up || 1165 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) 1166 return SendErrorResponse(68); 1167 1168 if (!packet.ConsumeFront("jTraceStop:")) 1169 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet "); 1170 1171 lldb::user_id_t uid = LLDB_INVALID_UID; 1172 lldb::tid_t tid = LLDB_INVALID_THREAD_ID; 1173 1174 auto json_object = StructuredData::ParseJSON(packet.Peek()); 1175 1176 if (!json_object || 1177 json_object->GetType() != lldb::eStructuredDataTypeDictionary) 1178 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet "); 1179 1180 auto json_dict = json_object->GetAsDictionary(); 1181 1182 if (!json_dict->GetValueForKeyAsInteger("traceid", uid)) 1183 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet "); 1184 1185 json_dict->GetValueForKeyAsInteger("threadid", tid); 1186 1187 Status error = m_debugged_process_up->StopTrace(uid, tid); 1188 1189 if (error.Fail()) 1190 return SendErrorResponse(error); 1191 1192 return SendOKResponse(); 1193 } 1194 1195 GDBRemoteCommunication::PacketResult 1196 GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceSupportedType( 1197 StringExtractorGDBRemote &packet) { 1198 1199 // Fail if we don't have a current process. 1200 if (!m_debugged_process_up || 1201 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) 1202 return SendErrorResponse(Status("Process not running.")); 1203 1204 llvm::Expected<TraceTypeInfo> supported_trace_type = 1205 m_debugged_process_up->GetSupportedTraceType(); 1206 if (!supported_trace_type) 1207 return SendErrorResponse(supported_trace_type.takeError()); 1208 1209 StreamGDBRemote escaped_response; 1210 StructuredData::Dictionary json_packet; 1211 1212 json_packet.AddStringItem("name", supported_trace_type->name); 1213 json_packet.AddStringItem("description", supported_trace_type->description); 1214 1215 StreamString json_string; 1216 json_packet.Dump(json_string, false); 1217 escaped_response.PutEscapedBytes(json_string.GetData(), 1218 json_string.GetSize()); 1219 return SendPacketNoLock(escaped_response.GetString()); 1220 } 1221 1222 GDBRemoteCommunication::PacketResult 1223 GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead( 1224 StringExtractorGDBRemote &packet) { 1225 1226 // Fail if we don't have a current process. 1227 if (!m_debugged_process_up || 1228 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) 1229 return SendErrorResponse(68); 1230 1231 if (!packet.ConsumeFront("jTraceConfigRead:")) 1232 return SendIllFormedResponse(packet, 1233 "jTraceConfigRead: Ill formed packet "); 1234 1235 lldb::user_id_t uid = LLDB_INVALID_UID; 1236 lldb::tid_t threadid = LLDB_INVALID_THREAD_ID; 1237 1238 auto json_object = StructuredData::ParseJSON(packet.Peek()); 1239 1240 if (!json_object || 1241 json_object->GetType() != lldb::eStructuredDataTypeDictionary) 1242 return SendIllFormedResponse(packet, 1243 "jTraceConfigRead: Ill formed packet "); 1244 1245 auto json_dict = json_object->GetAsDictionary(); 1246 1247 if (!json_dict->GetValueForKeyAsInteger("traceid", uid)) 1248 return SendIllFormedResponse(packet, 1249 "jTraceConfigRead: Ill formed packet "); 1250 1251 json_dict->GetValueForKeyAsInteger("threadid", threadid); 1252 1253 TraceOptions options; 1254 StreamGDBRemote response; 1255 1256 options.setThreadID(threadid); 1257 Status error = m_debugged_process_up->GetTraceConfig(uid, options); 1258 1259 if (error.Fail()) 1260 return SendErrorResponse(error); 1261 1262 StreamGDBRemote escaped_response; 1263 StructuredData::Dictionary json_packet; 1264 1265 json_packet.AddIntegerItem("type", options.getType()); 1266 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize()); 1267 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize()); 1268 1269 StructuredData::DictionarySP custom_params = options.getTraceParams(); 1270 if (custom_params) 1271 json_packet.AddItem("params", custom_params); 1272 1273 StreamString json_string; 1274 json_packet.Dump(json_string, false); 1275 escaped_response.PutEscapedBytes(json_string.GetData(), 1276 json_string.GetSize()); 1277 return SendPacketNoLock(escaped_response.GetString()); 1278 } 1279 1280 GDBRemoteCommunication::PacketResult 1281 GDBRemoteCommunicationServerLLGS::Handle_jTraceRead( 1282 StringExtractorGDBRemote &packet) { 1283 1284 // Fail if we don't have a current process. 1285 if (!m_debugged_process_up || 1286 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) 1287 return SendErrorResponse(68); 1288 1289 enum PacketType { MetaData, BufferData }; 1290 PacketType tracetype = MetaData; 1291 1292 if (packet.ConsumeFront("jTraceBufferRead:")) 1293 tracetype = BufferData; 1294 else if (packet.ConsumeFront("jTraceMetaRead:")) 1295 tracetype = MetaData; 1296 else { 1297 return SendIllFormedResponse(packet, "jTrace: Ill formed packet "); 1298 } 1299 1300 lldb::user_id_t uid = LLDB_INVALID_UID; 1301 1302 uint64_t byte_count = std::numeric_limits<uint64_t>::max(); 1303 lldb::tid_t tid = LLDB_INVALID_THREAD_ID; 1304 uint64_t offset = std::numeric_limits<uint64_t>::max(); 1305 1306 auto json_object = StructuredData::ParseJSON(packet.Peek()); 1307 1308 if (!json_object || 1309 json_object->GetType() != lldb::eStructuredDataTypeDictionary) 1310 return SendIllFormedResponse(packet, "jTrace: Ill formed packet "); 1311 1312 auto json_dict = json_object->GetAsDictionary(); 1313 1314 if (!json_dict->GetValueForKeyAsInteger("traceid", uid) || 1315 !json_dict->GetValueForKeyAsInteger("offset", offset) || 1316 !json_dict->GetValueForKeyAsInteger("buffersize", byte_count)) 1317 return SendIllFormedResponse(packet, "jTrace: Ill formed packet "); 1318 1319 json_dict->GetValueForKeyAsInteger("threadid", tid); 1320 1321 // Allocate the response buffer. 1322 std::unique_ptr<uint8_t[]> buffer (new (std::nothrow) uint8_t[byte_count]); 1323 if (!buffer) 1324 return SendErrorResponse(0x78); 1325 1326 StreamGDBRemote response; 1327 Status error; 1328 llvm::MutableArrayRef<uint8_t> buf(buffer.get(), byte_count); 1329 1330 if (tracetype == BufferData) 1331 error = m_debugged_process_up->GetData(uid, tid, buf, offset); 1332 else if (tracetype == MetaData) 1333 error = m_debugged_process_up->GetMetaData(uid, tid, buf, offset); 1334 1335 if (error.Fail()) 1336 return SendErrorResponse(error); 1337 1338 for (auto i : buf) 1339 response.PutHex8(i); 1340 1341 StreamGDBRemote escaped_response; 1342 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize()); 1343 return SendPacketNoLock(escaped_response.GetString()); 1344 } 1345 1346 GDBRemoteCommunication::PacketResult 1347 GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo( 1348 StringExtractorGDBRemote &packet) { 1349 // Fail if we don't have a current process. 1350 if (!m_debugged_process_up || 1351 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) 1352 return SendErrorResponse(68); 1353 1354 lldb::pid_t pid = m_debugged_process_up->GetID(); 1355 1356 if (pid == LLDB_INVALID_PROCESS_ID) 1357 return SendErrorResponse(1); 1358 1359 ProcessInstanceInfo proc_info; 1360 if (!Host::GetProcessInfo(pid, proc_info)) 1361 return SendErrorResponse(1); 1362 1363 StreamString response; 1364 CreateProcessInfoResponse_DebugServerStyle(proc_info, response); 1365 return SendPacketNoLock(response.GetString()); 1366 } 1367 1368 GDBRemoteCommunication::PacketResult 1369 GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) { 1370 // Fail if we don't have a current process. 1371 if (!m_debugged_process_up || 1372 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) 1373 return SendErrorResponse(68); 1374 1375 // Make sure we set the current thread so g and p packets return the data the 1376 // gdb will expect. 1377 lldb::tid_t tid = m_debugged_process_up->GetCurrentThreadID(); 1378 SetCurrentThreadID(tid); 1379 1380 NativeThreadProtocol *thread = m_debugged_process_up->GetCurrentThread(); 1381 if (!thread) 1382 return SendErrorResponse(69); 1383 1384 StreamString response; 1385 response.Printf("QC%" PRIx64, thread->GetID()); 1386 1387 return SendPacketNoLock(response.GetString()); 1388 } 1389 1390 GDBRemoteCommunication::PacketResult 1391 GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) { 1392 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 1393 1394 StopSTDIOForwarding(); 1395 1396 if (!m_debugged_process_up) { 1397 LLDB_LOG(log, "No debugged process found."); 1398 return PacketResult::Success; 1399 } 1400 1401 Status error = m_debugged_process_up->Kill(); 1402 if (error.Fail()) 1403 LLDB_LOG(log, "Failed to kill debugged process {0}: {1}", 1404 m_debugged_process_up->GetID(), error); 1405 1406 // No OK response for kill packet. 1407 // return SendOKResponse (); 1408 return PacketResult::Success; 1409 } 1410 1411 GDBRemoteCommunication::PacketResult 1412 GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR( 1413 StringExtractorGDBRemote &packet) { 1414 packet.SetFilePos(::strlen("QSetDisableASLR:")); 1415 if (packet.GetU32(0)) 1416 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR); 1417 else 1418 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR); 1419 return SendOKResponse(); 1420 } 1421 1422 GDBRemoteCommunication::PacketResult 1423 GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir( 1424 StringExtractorGDBRemote &packet) { 1425 packet.SetFilePos(::strlen("QSetWorkingDir:")); 1426 std::string path; 1427 packet.GetHexByteString(path); 1428 m_process_launch_info.SetWorkingDirectory(FileSpec(path)); 1429 return SendOKResponse(); 1430 } 1431 1432 GDBRemoteCommunication::PacketResult 1433 GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir( 1434 StringExtractorGDBRemote &packet) { 1435 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()}; 1436 if (working_dir) { 1437 StreamString response; 1438 response.PutStringAsRawHex8(working_dir.GetCString()); 1439 return SendPacketNoLock(response.GetString()); 1440 } 1441 1442 return SendErrorResponse(14); 1443 } 1444 1445 GDBRemoteCommunication::PacketResult 1446 GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) { 1447 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 1448 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__); 1449 1450 // Ensure we have a native process. 1451 if (!m_debugged_process_up) { 1452 LLDB_LOGF(log, 1453 "GDBRemoteCommunicationServerLLGS::%s no debugged process " 1454 "shared pointer", 1455 __FUNCTION__); 1456 return SendErrorResponse(0x36); 1457 } 1458 1459 // Pull out the signal number. 1460 packet.SetFilePos(::strlen("C")); 1461 if (packet.GetBytesLeft() < 1) { 1462 // Shouldn't be using a C without a signal. 1463 return SendIllFormedResponse(packet, "C packet specified without signal."); 1464 } 1465 const uint32_t signo = 1466 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 1467 if (signo == std::numeric_limits<uint32_t>::max()) 1468 return SendIllFormedResponse(packet, "failed to parse signal number"); 1469 1470 // Handle optional continue address. 1471 if (packet.GetBytesLeft() > 0) { 1472 // FIXME add continue at address support for $C{signo}[;{continue-address}]. 1473 if (*packet.Peek() == ';') 1474 return SendUnimplementedResponse(packet.GetStringRef().data()); 1475 else 1476 return SendIllFormedResponse( 1477 packet, "unexpected content after $C{signal-number}"); 1478 } 1479 1480 ResumeActionList resume_actions(StateType::eStateRunning, 1481 LLDB_INVALID_SIGNAL_NUMBER); 1482 Status error; 1483 1484 // We have two branches: what to do if a continue thread is specified (in 1485 // which case we target sending the signal to that thread), or when we don't 1486 // have a continue thread set (in which case we send a signal to the 1487 // process). 1488 1489 // TODO discuss with Greg Clayton, make sure this makes sense. 1490 1491 lldb::tid_t signal_tid = GetContinueThreadID(); 1492 if (signal_tid != LLDB_INVALID_THREAD_ID) { 1493 // The resume action for the continue thread (or all threads if a continue 1494 // thread is not set). 1495 ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning, 1496 static_cast<int>(signo)}; 1497 1498 // Add the action for the continue thread (or all threads when the continue 1499 // thread isn't present). 1500 resume_actions.Append(action); 1501 } else { 1502 // Send the signal to the process since we weren't targeting a specific 1503 // continue thread with the signal. 1504 error = m_debugged_process_up->Signal(signo); 1505 if (error.Fail()) { 1506 LLDB_LOG(log, "failed to send signal for process {0}: {1}", 1507 m_debugged_process_up->GetID(), error); 1508 1509 return SendErrorResponse(0x52); 1510 } 1511 } 1512 1513 // Resume the threads. 1514 error = m_debugged_process_up->Resume(resume_actions); 1515 if (error.Fail()) { 1516 LLDB_LOG(log, "failed to resume threads for process {0}: {1}", 1517 m_debugged_process_up->GetID(), error); 1518 1519 return SendErrorResponse(0x38); 1520 } 1521 1522 // Don't send an "OK" packet; response is the stopped/exited message. 1523 return PacketResult::Success; 1524 } 1525 1526 GDBRemoteCommunication::PacketResult 1527 GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) { 1528 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 1529 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__); 1530 1531 packet.SetFilePos(packet.GetFilePos() + ::strlen("c")); 1532 1533 // For now just support all continue. 1534 const bool has_continue_address = (packet.GetBytesLeft() > 0); 1535 if (has_continue_address) { 1536 LLDB_LOG(log, "not implemented for c[address] variant [{0} remains]", 1537 packet.Peek()); 1538 return SendUnimplementedResponse(packet.GetStringRef().data()); 1539 } 1540 1541 // Ensure we have a native process. 1542 if (!m_debugged_process_up) { 1543 LLDB_LOGF(log, 1544 "GDBRemoteCommunicationServerLLGS::%s no debugged process " 1545 "shared pointer", 1546 __FUNCTION__); 1547 return SendErrorResponse(0x36); 1548 } 1549 1550 // Build the ResumeActionList 1551 ResumeActionList actions(StateType::eStateRunning, 1552 LLDB_INVALID_SIGNAL_NUMBER); 1553 1554 Status error = m_debugged_process_up->Resume(actions); 1555 if (error.Fail()) { 1556 LLDB_LOG(log, "c failed for process {0}: {1}", 1557 m_debugged_process_up->GetID(), error); 1558 return SendErrorResponse(GDBRemoteServerError::eErrorResume); 1559 } 1560 1561 LLDB_LOG(log, "continued process {0}", m_debugged_process_up->GetID()); 1562 // No response required from continue. 1563 return PacketResult::Success; 1564 } 1565 1566 GDBRemoteCommunication::PacketResult 1567 GDBRemoteCommunicationServerLLGS::Handle_vCont_actions( 1568 StringExtractorGDBRemote &packet) { 1569 StreamString response; 1570 response.Printf("vCont;c;C;s;S"); 1571 1572 return SendPacketNoLock(response.GetString()); 1573 } 1574 1575 GDBRemoteCommunication::PacketResult 1576 GDBRemoteCommunicationServerLLGS::Handle_vCont( 1577 StringExtractorGDBRemote &packet) { 1578 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 1579 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s handling vCont packet", 1580 __FUNCTION__); 1581 1582 packet.SetFilePos(::strlen("vCont")); 1583 1584 if (packet.GetBytesLeft() == 0) { 1585 LLDB_LOGF(log, 1586 "GDBRemoteCommunicationServerLLGS::%s missing action from " 1587 "vCont package", 1588 __FUNCTION__); 1589 return SendIllFormedResponse(packet, "Missing action from vCont package"); 1590 } 1591 1592 // Check if this is all continue (no options or ";c"). 1593 if (::strcmp(packet.Peek(), ";c") == 0) { 1594 // Move past the ';', then do a simple 'c'. 1595 packet.SetFilePos(packet.GetFilePos() + 1); 1596 return Handle_c(packet); 1597 } else if (::strcmp(packet.Peek(), ";s") == 0) { 1598 // Move past the ';', then do a simple 's'. 1599 packet.SetFilePos(packet.GetFilePos() + 1); 1600 return Handle_s(packet); 1601 } 1602 1603 // Ensure we have a native process. 1604 if (!m_debugged_process_up) { 1605 LLDB_LOG(log, "no debugged process"); 1606 return SendErrorResponse(0x36); 1607 } 1608 1609 ResumeActionList thread_actions; 1610 1611 while (packet.GetBytesLeft() && *packet.Peek() == ';') { 1612 // Skip the semi-colon. 1613 packet.GetChar(); 1614 1615 // Build up the thread action. 1616 ResumeAction thread_action; 1617 thread_action.tid = LLDB_INVALID_THREAD_ID; 1618 thread_action.state = eStateInvalid; 1619 thread_action.signal = LLDB_INVALID_SIGNAL_NUMBER; 1620 1621 const char action = packet.GetChar(); 1622 switch (action) { 1623 case 'C': 1624 thread_action.signal = packet.GetHexMaxU32(false, 0); 1625 if (thread_action.signal == 0) 1626 return SendIllFormedResponse( 1627 packet, "Could not parse signal in vCont packet C action"); 1628 LLVM_FALLTHROUGH; 1629 1630 case 'c': 1631 // Continue 1632 thread_action.state = eStateRunning; 1633 break; 1634 1635 case 'S': 1636 thread_action.signal = packet.GetHexMaxU32(false, 0); 1637 if (thread_action.signal == 0) 1638 return SendIllFormedResponse( 1639 packet, "Could not parse signal in vCont packet S action"); 1640 LLVM_FALLTHROUGH; 1641 1642 case 's': 1643 // Step 1644 thread_action.state = eStateStepping; 1645 break; 1646 1647 default: 1648 return SendIllFormedResponse(packet, "Unsupported vCont action"); 1649 break; 1650 } 1651 1652 // Parse out optional :{thread-id} value. 1653 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) { 1654 // Consume the separator. 1655 packet.GetChar(); 1656 1657 thread_action.tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID); 1658 if (thread_action.tid == LLDB_INVALID_THREAD_ID) 1659 return SendIllFormedResponse( 1660 packet, "Could not parse thread number in vCont packet"); 1661 } 1662 1663 thread_actions.Append(thread_action); 1664 } 1665 1666 Status error = m_debugged_process_up->Resume(thread_actions); 1667 if (error.Fail()) { 1668 LLDB_LOG(log, "vCont failed for process {0}: {1}", 1669 m_debugged_process_up->GetID(), error); 1670 return SendErrorResponse(GDBRemoteServerError::eErrorResume); 1671 } 1672 1673 LLDB_LOG(log, "continued process {0}", m_debugged_process_up->GetID()); 1674 // No response required from vCont. 1675 return PacketResult::Success; 1676 } 1677 1678 void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) { 1679 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 1680 LLDB_LOG(log, "setting current thread id to {0}", tid); 1681 1682 m_current_tid = tid; 1683 if (m_debugged_process_up) 1684 m_debugged_process_up->SetCurrentThreadID(m_current_tid); 1685 } 1686 1687 void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) { 1688 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 1689 LLDB_LOG(log, "setting continue thread id to {0}", tid); 1690 1691 m_continue_tid = tid; 1692 } 1693 1694 GDBRemoteCommunication::PacketResult 1695 GDBRemoteCommunicationServerLLGS::Handle_stop_reason( 1696 StringExtractorGDBRemote &packet) { 1697 // Handle the $? gdbremote command. 1698 1699 // If no process, indicate error 1700 if (!m_debugged_process_up) 1701 return SendErrorResponse(02); 1702 1703 return SendStopReasonForState(m_debugged_process_up->GetState()); 1704 } 1705 1706 GDBRemoteCommunication::PacketResult 1707 GDBRemoteCommunicationServerLLGS::SendStopReasonForState( 1708 lldb::StateType process_state) { 1709 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 1710 1711 switch (process_state) { 1712 case eStateAttaching: 1713 case eStateLaunching: 1714 case eStateRunning: 1715 case eStateStepping: 1716 case eStateDetached: 1717 // NOTE: gdb protocol doc looks like it should return $OK 1718 // when everything is running (i.e. no stopped result). 1719 return PacketResult::Success; // Ignore 1720 1721 case eStateSuspended: 1722 case eStateStopped: 1723 case eStateCrashed: { 1724 assert(m_debugged_process_up != nullptr); 1725 lldb::tid_t tid = m_debugged_process_up->GetCurrentThreadID(); 1726 // Make sure we set the current thread so g and p packets return the data 1727 // the gdb will expect. 1728 SetCurrentThreadID(tid); 1729 return SendStopReplyPacketForThread(tid); 1730 } 1731 1732 case eStateInvalid: 1733 case eStateUnloaded: 1734 case eStateExited: 1735 return SendWResponse(m_debugged_process_up.get()); 1736 1737 default: 1738 LLDB_LOG(log, "pid {0}, current state reporting not handled: {1}", 1739 m_debugged_process_up->GetID(), process_state); 1740 break; 1741 } 1742 1743 return SendErrorResponse(0); 1744 } 1745 1746 GDBRemoteCommunication::PacketResult 1747 GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo( 1748 StringExtractorGDBRemote &packet) { 1749 // Fail if we don't have a current process. 1750 if (!m_debugged_process_up || 1751 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) 1752 return SendErrorResponse(68); 1753 1754 // Ensure we have a thread. 1755 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadAtIndex(0); 1756 if (!thread) 1757 return SendErrorResponse(69); 1758 1759 // Get the register context for the first thread. 1760 NativeRegisterContext ®_context = thread->GetRegisterContext(); 1761 1762 // Parse out the register number from the request. 1763 packet.SetFilePos(strlen("qRegisterInfo")); 1764 const uint32_t reg_index = 1765 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 1766 if (reg_index == std::numeric_limits<uint32_t>::max()) 1767 return SendErrorResponse(69); 1768 1769 // Return the end of registers response if we've iterated one past the end of 1770 // the register set. 1771 if (reg_index >= reg_context.GetUserRegisterCount()) 1772 return SendErrorResponse(69); 1773 1774 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index); 1775 if (!reg_info) 1776 return SendErrorResponse(69); 1777 1778 // Build the reginfos response. 1779 StreamGDBRemote response; 1780 1781 response.PutCString("name:"); 1782 response.PutCString(reg_info->name); 1783 response.PutChar(';'); 1784 1785 if (reg_info->alt_name && reg_info->alt_name[0]) { 1786 response.PutCString("alt-name:"); 1787 response.PutCString(reg_info->alt_name); 1788 response.PutChar(';'); 1789 } 1790 1791 response.Printf("bitsize:%" PRIu32 ";offset:%" PRIu32 ";", 1792 reg_info->byte_size * 8, reg_info->byte_offset); 1793 1794 llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info); 1795 if (!encoding.empty()) 1796 response << "encoding:" << encoding << ';'; 1797 1798 llvm::StringRef format = GetFormatNameOrEmpty(*reg_info); 1799 if (!format.empty()) 1800 response << "format:" << format << ';'; 1801 1802 const char *const register_set_name = 1803 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index); 1804 if (register_set_name) 1805 response << "set:" << register_set_name << ';'; 1806 1807 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] != 1808 LLDB_INVALID_REGNUM) 1809 response.Printf("ehframe:%" PRIu32 ";", 1810 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]); 1811 1812 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM) 1813 response.Printf("dwarf:%" PRIu32 ";", 1814 reg_info->kinds[RegisterKind::eRegisterKindDWARF]); 1815 1816 llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info); 1817 if (!kind_generic.empty()) 1818 response << "generic:" << kind_generic << ';'; 1819 1820 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) { 1821 response.PutCString("container-regs:"); 1822 CollectRegNums(reg_info->value_regs, response, true); 1823 response.PutChar(';'); 1824 } 1825 1826 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) { 1827 response.PutCString("invalidate-regs:"); 1828 CollectRegNums(reg_info->invalidate_regs, response, true); 1829 response.PutChar(';'); 1830 } 1831 1832 if (reg_info->dynamic_size_dwarf_expr_bytes) { 1833 const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len; 1834 response.PutCString("dynamic_size_dwarf_expr_bytes:"); 1835 for (uint32_t i = 0; i < dwarf_opcode_len; ++i) 1836 response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]); 1837 response.PutChar(';'); 1838 } 1839 return SendPacketNoLock(response.GetString()); 1840 } 1841 1842 GDBRemoteCommunication::PacketResult 1843 GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo( 1844 StringExtractorGDBRemote &packet) { 1845 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 1846 1847 // Fail if we don't have a current process. 1848 if (!m_debugged_process_up || 1849 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 1850 LLDB_LOG(log, "no process ({0}), returning OK", 1851 m_debugged_process_up ? "invalid process id" 1852 : "null m_debugged_process_up"); 1853 return SendOKResponse(); 1854 } 1855 1856 StreamGDBRemote response; 1857 response.PutChar('m'); 1858 1859 LLDB_LOG(log, "starting thread iteration"); 1860 NativeThreadProtocol *thread; 1861 uint32_t thread_index; 1862 for (thread_index = 0, 1863 thread = m_debugged_process_up->GetThreadAtIndex(thread_index); 1864 thread; ++thread_index, 1865 thread = m_debugged_process_up->GetThreadAtIndex(thread_index)) { 1866 LLDB_LOG(log, "iterated thread {0}(tid={2})", thread_index, 1867 thread->GetID()); 1868 if (thread_index > 0) 1869 response.PutChar(','); 1870 response.Printf("%" PRIx64, thread->GetID()); 1871 } 1872 1873 LLDB_LOG(log, "finished thread iteration"); 1874 return SendPacketNoLock(response.GetString()); 1875 } 1876 1877 GDBRemoteCommunication::PacketResult 1878 GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo( 1879 StringExtractorGDBRemote &packet) { 1880 // FIXME for now we return the full thread list in the initial packet and 1881 // always do nothing here. 1882 return SendPacketNoLock("l"); 1883 } 1884 1885 GDBRemoteCommunication::PacketResult 1886 GDBRemoteCommunicationServerLLGS::Handle_g(StringExtractorGDBRemote &packet) { 1887 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 1888 1889 // Move past packet name. 1890 packet.SetFilePos(strlen("g")); 1891 1892 // Get the thread to use. 1893 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 1894 if (!thread) { 1895 LLDB_LOG(log, "failed, no thread available"); 1896 return SendErrorResponse(0x15); 1897 } 1898 1899 // Get the thread's register context. 1900 NativeRegisterContext ®_ctx = thread->GetRegisterContext(); 1901 1902 std::vector<uint8_t> regs_buffer; 1903 for (uint32_t reg_num = 0; reg_num < reg_ctx.GetUserRegisterCount(); 1904 ++reg_num) { 1905 const RegisterInfo *reg_info = reg_ctx.GetRegisterInfoAtIndex(reg_num); 1906 1907 if (reg_info == nullptr) { 1908 LLDB_LOG(log, "failed to get register info for register index {0}", 1909 reg_num); 1910 return SendErrorResponse(0x15); 1911 } 1912 1913 if (reg_info->value_regs != nullptr) 1914 continue; // skip registers that are contained in other registers 1915 1916 RegisterValue reg_value; 1917 Status error = reg_ctx.ReadRegister(reg_info, reg_value); 1918 if (error.Fail()) { 1919 LLDB_LOG(log, "failed to read register at index {0}", reg_num); 1920 return SendErrorResponse(0x15); 1921 } 1922 1923 if (reg_info->byte_offset + reg_info->byte_size >= regs_buffer.size()) 1924 // Resize the buffer to guarantee it can store the register offsetted 1925 // data. 1926 regs_buffer.resize(reg_info->byte_offset + reg_info->byte_size); 1927 1928 // Copy the register offsetted data to the buffer. 1929 memcpy(regs_buffer.data() + reg_info->byte_offset, reg_value.GetBytes(), 1930 reg_info->byte_size); 1931 } 1932 1933 // Write the response. 1934 StreamGDBRemote response; 1935 response.PutBytesAsRawHex8(regs_buffer.data(), regs_buffer.size()); 1936 1937 return SendPacketNoLock(response.GetString()); 1938 } 1939 1940 GDBRemoteCommunication::PacketResult 1941 GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) { 1942 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 1943 1944 // Parse out the register number from the request. 1945 packet.SetFilePos(strlen("p")); 1946 const uint32_t reg_index = 1947 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 1948 if (reg_index == std::numeric_limits<uint32_t>::max()) { 1949 LLDB_LOGF(log, 1950 "GDBRemoteCommunicationServerLLGS::%s failed, could not " 1951 "parse register number from request \"%s\"", 1952 __FUNCTION__, packet.GetStringRef().data()); 1953 return SendErrorResponse(0x15); 1954 } 1955 1956 // Get the thread to use. 1957 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 1958 if (!thread) { 1959 LLDB_LOG(log, "failed, no thread available"); 1960 return SendErrorResponse(0x15); 1961 } 1962 1963 // Get the thread's register context. 1964 NativeRegisterContext ®_context = thread->GetRegisterContext(); 1965 1966 // Return the end of registers response if we've iterated one past the end of 1967 // the register set. 1968 if (reg_index >= reg_context.GetUserRegisterCount()) { 1969 LLDB_LOGF(log, 1970 "GDBRemoteCommunicationServerLLGS::%s failed, requested " 1971 "register %" PRIu32 " beyond register count %" PRIu32, 1972 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount()); 1973 return SendErrorResponse(0x15); 1974 } 1975 1976 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index); 1977 if (!reg_info) { 1978 LLDB_LOGF(log, 1979 "GDBRemoteCommunicationServerLLGS::%s failed, requested " 1980 "register %" PRIu32 " returned NULL", 1981 __FUNCTION__, reg_index); 1982 return SendErrorResponse(0x15); 1983 } 1984 1985 // Build the reginfos response. 1986 StreamGDBRemote response; 1987 1988 // Retrieve the value 1989 RegisterValue reg_value; 1990 Status error = reg_context.ReadRegister(reg_info, reg_value); 1991 if (error.Fail()) { 1992 LLDB_LOGF(log, 1993 "GDBRemoteCommunicationServerLLGS::%s failed, read of " 1994 "requested register %" PRIu32 " (%s) failed: %s", 1995 __FUNCTION__, reg_index, reg_info->name, error.AsCString()); 1996 return SendErrorResponse(0x15); 1997 } 1998 1999 const uint8_t *const data = 2000 static_cast<const uint8_t *>(reg_value.GetBytes()); 2001 if (!data) { 2002 LLDB_LOGF(log, 2003 "GDBRemoteCommunicationServerLLGS::%s failed to get data " 2004 "bytes from requested register %" PRIu32, 2005 __FUNCTION__, reg_index); 2006 return SendErrorResponse(0x15); 2007 } 2008 2009 // FIXME flip as needed to get data in big/little endian format for this host. 2010 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i) 2011 response.PutHex8(data[i]); 2012 2013 return SendPacketNoLock(response.GetString()); 2014 } 2015 2016 GDBRemoteCommunication::PacketResult 2017 GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) { 2018 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 2019 2020 // Ensure there is more content. 2021 if (packet.GetBytesLeft() < 1) 2022 return SendIllFormedResponse(packet, "Empty P packet"); 2023 2024 // Parse out the register number from the request. 2025 packet.SetFilePos(strlen("P")); 2026 const uint32_t reg_index = 2027 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 2028 if (reg_index == std::numeric_limits<uint32_t>::max()) { 2029 LLDB_LOGF(log, 2030 "GDBRemoteCommunicationServerLLGS::%s failed, could not " 2031 "parse register number from request \"%s\"", 2032 __FUNCTION__, packet.GetStringRef().data()); 2033 return SendErrorResponse(0x29); 2034 } 2035 2036 // Note debugserver would send an E30 here. 2037 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '=')) 2038 return SendIllFormedResponse( 2039 packet, "P packet missing '=' char after register number"); 2040 2041 // Parse out the value. 2042 uint8_t reg_bytes[RegisterValue::kMaxRegisterByteSize]; 2043 size_t reg_size = packet.GetHexBytesAvail(reg_bytes); 2044 2045 // Get the thread to use. 2046 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 2047 if (!thread) { 2048 LLDB_LOGF(log, 2049 "GDBRemoteCommunicationServerLLGS::%s failed, no thread " 2050 "available (thread index 0)", 2051 __FUNCTION__); 2052 return SendErrorResponse(0x28); 2053 } 2054 2055 // Get the thread's register context. 2056 NativeRegisterContext ®_context = thread->GetRegisterContext(); 2057 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index); 2058 if (!reg_info) { 2059 LLDB_LOGF(log, 2060 "GDBRemoteCommunicationServerLLGS::%s failed, requested " 2061 "register %" PRIu32 " returned NULL", 2062 __FUNCTION__, reg_index); 2063 return SendErrorResponse(0x48); 2064 } 2065 2066 // Return the end of registers response if we've iterated one past the end of 2067 // the register set. 2068 if (reg_index >= reg_context.GetUserRegisterCount()) { 2069 LLDB_LOGF(log, 2070 "GDBRemoteCommunicationServerLLGS::%s failed, requested " 2071 "register %" PRIu32 " beyond register count %" PRIu32, 2072 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount()); 2073 return SendErrorResponse(0x47); 2074 } 2075 2076 // The dwarf expression are evaluate on host site which may cause register 2077 // size to change Hence the reg_size may not be same as reg_info->bytes_size 2078 if ((reg_size != reg_info->byte_size) && 2079 !(reg_info->dynamic_size_dwarf_expr_bytes)) { 2080 return SendIllFormedResponse(packet, "P packet register size is incorrect"); 2081 } 2082 2083 // Build the reginfos response. 2084 StreamGDBRemote response; 2085 2086 RegisterValue reg_value( 2087 makeArrayRef(reg_bytes, reg_size), 2088 m_debugged_process_up->GetArchitecture().GetByteOrder()); 2089 Status error = reg_context.WriteRegister(reg_info, reg_value); 2090 if (error.Fail()) { 2091 LLDB_LOGF(log, 2092 "GDBRemoteCommunicationServerLLGS::%s failed, write of " 2093 "requested register %" PRIu32 " (%s) failed: %s", 2094 __FUNCTION__, reg_index, reg_info->name, error.AsCString()); 2095 return SendErrorResponse(0x32); 2096 } 2097 2098 return SendOKResponse(); 2099 } 2100 2101 GDBRemoteCommunication::PacketResult 2102 GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) { 2103 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 2104 2105 // Fail if we don't have a current process. 2106 if (!m_debugged_process_up || 2107 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2108 LLDB_LOGF( 2109 log, 2110 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2111 __FUNCTION__); 2112 return SendErrorResponse(0x15); 2113 } 2114 2115 // Parse out which variant of $H is requested. 2116 packet.SetFilePos(strlen("H")); 2117 if (packet.GetBytesLeft() < 1) { 2118 LLDB_LOGF(log, 2119 "GDBRemoteCommunicationServerLLGS::%s failed, H command " 2120 "missing {g,c} variant", 2121 __FUNCTION__); 2122 return SendIllFormedResponse(packet, "H command missing {g,c} variant"); 2123 } 2124 2125 const char h_variant = packet.GetChar(); 2126 switch (h_variant) { 2127 case 'g': 2128 break; 2129 2130 case 'c': 2131 break; 2132 2133 default: 2134 LLDB_LOGF( 2135 log, 2136 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c", 2137 __FUNCTION__, h_variant); 2138 return SendIllFormedResponse(packet, 2139 "H variant unsupported, should be c or g"); 2140 } 2141 2142 // Parse out the thread number. 2143 // FIXME return a parse success/fail value. All values are valid here. 2144 const lldb::tid_t tid = 2145 packet.GetHexMaxU64(false, std::numeric_limits<lldb::tid_t>::max()); 2146 2147 // Ensure we have the given thread when not specifying -1 (all threads) or 0 2148 // (any thread). 2149 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) { 2150 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid); 2151 if (!thread) { 2152 LLDB_LOGF(log, 2153 "GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64 2154 " not found", 2155 __FUNCTION__, tid); 2156 return SendErrorResponse(0x15); 2157 } 2158 } 2159 2160 // Now switch the given thread type. 2161 switch (h_variant) { 2162 case 'g': 2163 SetCurrentThreadID(tid); 2164 break; 2165 2166 case 'c': 2167 SetContinueThreadID(tid); 2168 break; 2169 2170 default: 2171 assert(false && "unsupported $H variant - shouldn't get here"); 2172 return SendIllFormedResponse(packet, 2173 "H variant unsupported, should be c or g"); 2174 } 2175 2176 return SendOKResponse(); 2177 } 2178 2179 GDBRemoteCommunication::PacketResult 2180 GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) { 2181 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 2182 2183 // Fail if we don't have a current process. 2184 if (!m_debugged_process_up || 2185 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2186 LLDB_LOGF( 2187 log, 2188 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2189 __FUNCTION__); 2190 return SendErrorResponse(0x15); 2191 } 2192 2193 packet.SetFilePos(::strlen("I")); 2194 uint8_t tmp[4096]; 2195 for (;;) { 2196 size_t read = packet.GetHexBytesAvail(tmp); 2197 if (read == 0) { 2198 break; 2199 } 2200 // write directly to stdin *this might block if stdin buffer is full* 2201 // TODO: enqueue this block in circular buffer and send window size to 2202 // remote host 2203 ConnectionStatus status; 2204 Status error; 2205 m_stdio_communication.Write(tmp, read, status, &error); 2206 if (error.Fail()) { 2207 return SendErrorResponse(0x15); 2208 } 2209 } 2210 2211 return SendOKResponse(); 2212 } 2213 2214 GDBRemoteCommunication::PacketResult 2215 GDBRemoteCommunicationServerLLGS::Handle_interrupt( 2216 StringExtractorGDBRemote &packet) { 2217 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 2218 2219 // Fail if we don't have a current process. 2220 if (!m_debugged_process_up || 2221 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2222 LLDB_LOG(log, "failed, no process available"); 2223 return SendErrorResponse(0x15); 2224 } 2225 2226 // Interrupt the process. 2227 Status error = m_debugged_process_up->Interrupt(); 2228 if (error.Fail()) { 2229 LLDB_LOG(log, "failed for process {0}: {1}", m_debugged_process_up->GetID(), 2230 error); 2231 return SendErrorResponse(GDBRemoteServerError::eErrorResume); 2232 } 2233 2234 LLDB_LOG(log, "stopped process {0}", m_debugged_process_up->GetID()); 2235 2236 // No response required from stop all. 2237 return PacketResult::Success; 2238 } 2239 2240 GDBRemoteCommunication::PacketResult 2241 GDBRemoteCommunicationServerLLGS::Handle_memory_read( 2242 StringExtractorGDBRemote &packet) { 2243 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2244 2245 if (!m_debugged_process_up || 2246 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2247 LLDB_LOGF( 2248 log, 2249 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2250 __FUNCTION__); 2251 return SendErrorResponse(0x15); 2252 } 2253 2254 // Parse out the memory address. 2255 packet.SetFilePos(strlen("m")); 2256 if (packet.GetBytesLeft() < 1) 2257 return SendIllFormedResponse(packet, "Too short m packet"); 2258 2259 // Read the address. Punting on validation. 2260 // FIXME replace with Hex U64 read with no default value that fails on failed 2261 // read. 2262 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0); 2263 2264 // Validate comma. 2265 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ',')) 2266 return SendIllFormedResponse(packet, "Comma sep missing in m packet"); 2267 2268 // Get # bytes to read. 2269 if (packet.GetBytesLeft() < 1) 2270 return SendIllFormedResponse(packet, "Length missing in m packet"); 2271 2272 const uint64_t byte_count = packet.GetHexMaxU64(false, 0); 2273 if (byte_count == 0) { 2274 LLDB_LOGF(log, 2275 "GDBRemoteCommunicationServerLLGS::%s nothing to read: " 2276 "zero-length packet", 2277 __FUNCTION__); 2278 return SendOKResponse(); 2279 } 2280 2281 // Allocate the response buffer. 2282 std::string buf(byte_count, '\0'); 2283 if (buf.empty()) 2284 return SendErrorResponse(0x78); 2285 2286 // Retrieve the process memory. 2287 size_t bytes_read = 0; 2288 Status error = m_debugged_process_up->ReadMemoryWithoutTrap( 2289 read_addr, &buf[0], byte_count, bytes_read); 2290 if (error.Fail()) { 2291 LLDB_LOGF(log, 2292 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 2293 " mem 0x%" PRIx64 ": failed to read. Error: %s", 2294 __FUNCTION__, m_debugged_process_up->GetID(), read_addr, 2295 error.AsCString()); 2296 return SendErrorResponse(0x08); 2297 } 2298 2299 if (bytes_read == 0) { 2300 LLDB_LOGF(log, 2301 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 2302 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes", 2303 __FUNCTION__, m_debugged_process_up->GetID(), read_addr, 2304 byte_count); 2305 return SendErrorResponse(0x08); 2306 } 2307 2308 StreamGDBRemote response; 2309 packet.SetFilePos(0); 2310 char kind = packet.GetChar('?'); 2311 if (kind == 'x') 2312 response.PutEscapedBytes(buf.data(), byte_count); 2313 else { 2314 assert(kind == 'm'); 2315 for (size_t i = 0; i < bytes_read; ++i) 2316 response.PutHex8(buf[i]); 2317 } 2318 2319 return SendPacketNoLock(response.GetString()); 2320 } 2321 2322 GDBRemoteCommunication::PacketResult 2323 GDBRemoteCommunicationServerLLGS::Handle__M(StringExtractorGDBRemote &packet) { 2324 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2325 2326 if (!m_debugged_process_up || 2327 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2328 LLDB_LOGF( 2329 log, 2330 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2331 __FUNCTION__); 2332 return SendErrorResponse(0x15); 2333 } 2334 2335 // Parse out the memory address. 2336 packet.SetFilePos(strlen("_M")); 2337 if (packet.GetBytesLeft() < 1) 2338 return SendIllFormedResponse(packet, "Too short _M packet"); 2339 2340 const lldb::addr_t size = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 2341 if (size == LLDB_INVALID_ADDRESS) 2342 return SendIllFormedResponse(packet, "Address not valid"); 2343 if (packet.GetChar() != ',') 2344 return SendIllFormedResponse(packet, "Bad packet"); 2345 Permissions perms = {}; 2346 while (packet.GetBytesLeft() > 0) { 2347 switch (packet.GetChar()) { 2348 case 'r': 2349 perms |= ePermissionsReadable; 2350 break; 2351 case 'w': 2352 perms |= ePermissionsWritable; 2353 break; 2354 case 'x': 2355 perms |= ePermissionsExecutable; 2356 break; 2357 default: 2358 return SendIllFormedResponse(packet, "Bad permissions"); 2359 } 2360 } 2361 2362 llvm::Expected<addr_t> addr = 2363 m_debugged_process_up->AllocateMemory(size, perms); 2364 if (!addr) 2365 return SendErrorResponse(addr.takeError()); 2366 2367 StreamGDBRemote response; 2368 response.PutHex64(*addr); 2369 return SendPacketNoLock(response.GetString()); 2370 } 2371 2372 GDBRemoteCommunication::PacketResult 2373 GDBRemoteCommunicationServerLLGS::Handle__m(StringExtractorGDBRemote &packet) { 2374 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2375 2376 if (!m_debugged_process_up || 2377 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2378 LLDB_LOGF( 2379 log, 2380 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2381 __FUNCTION__); 2382 return SendErrorResponse(0x15); 2383 } 2384 2385 // Parse out the memory address. 2386 packet.SetFilePos(strlen("_m")); 2387 if (packet.GetBytesLeft() < 1) 2388 return SendIllFormedResponse(packet, "Too short m packet"); 2389 2390 const lldb::addr_t addr = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 2391 if (addr == LLDB_INVALID_ADDRESS) 2392 return SendIllFormedResponse(packet, "Address not valid"); 2393 2394 if (llvm::Error Err = m_debugged_process_up->DeallocateMemory(addr)) 2395 return SendErrorResponse(std::move(Err)); 2396 2397 return SendOKResponse(); 2398 } 2399 2400 GDBRemoteCommunication::PacketResult 2401 GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) { 2402 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2403 2404 if (!m_debugged_process_up || 2405 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2406 LLDB_LOGF( 2407 log, 2408 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2409 __FUNCTION__); 2410 return SendErrorResponse(0x15); 2411 } 2412 2413 // Parse out the memory address. 2414 packet.SetFilePos(strlen("M")); 2415 if (packet.GetBytesLeft() < 1) 2416 return SendIllFormedResponse(packet, "Too short M packet"); 2417 2418 // Read the address. Punting on validation. 2419 // FIXME replace with Hex U64 read with no default value that fails on failed 2420 // read. 2421 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0); 2422 2423 // Validate comma. 2424 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ',')) 2425 return SendIllFormedResponse(packet, "Comma sep missing in M packet"); 2426 2427 // Get # bytes to read. 2428 if (packet.GetBytesLeft() < 1) 2429 return SendIllFormedResponse(packet, "Length missing in M packet"); 2430 2431 const uint64_t byte_count = packet.GetHexMaxU64(false, 0); 2432 if (byte_count == 0) { 2433 LLDB_LOG(log, "nothing to write: zero-length packet"); 2434 return PacketResult::Success; 2435 } 2436 2437 // Validate colon. 2438 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':')) 2439 return SendIllFormedResponse( 2440 packet, "Comma sep missing in M packet after byte length"); 2441 2442 // Allocate the conversion buffer. 2443 std::vector<uint8_t> buf(byte_count, 0); 2444 if (buf.empty()) 2445 return SendErrorResponse(0x78); 2446 2447 // Convert the hex memory write contents to bytes. 2448 StreamGDBRemote response; 2449 const uint64_t convert_count = packet.GetHexBytes(buf, 0); 2450 if (convert_count != byte_count) { 2451 LLDB_LOG(log, 2452 "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} " 2453 "to convert.", 2454 m_debugged_process_up->GetID(), write_addr, byte_count, 2455 convert_count); 2456 return SendIllFormedResponse(packet, "M content byte length specified did " 2457 "not match hex-encoded content " 2458 "length"); 2459 } 2460 2461 // Write the process memory. 2462 size_t bytes_written = 0; 2463 Status error = m_debugged_process_up->WriteMemory(write_addr, &buf[0], 2464 byte_count, bytes_written); 2465 if (error.Fail()) { 2466 LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}", 2467 m_debugged_process_up->GetID(), write_addr, error); 2468 return SendErrorResponse(0x09); 2469 } 2470 2471 if (bytes_written == 0) { 2472 LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes", 2473 m_debugged_process_up->GetID(), write_addr, byte_count); 2474 return SendErrorResponse(0x09); 2475 } 2476 2477 return SendOKResponse(); 2478 } 2479 2480 GDBRemoteCommunication::PacketResult 2481 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported( 2482 StringExtractorGDBRemote &packet) { 2483 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2484 2485 // Currently only the NativeProcessProtocol knows if it can handle a 2486 // qMemoryRegionInfoSupported request, but we're not guaranteed to be 2487 // attached to a process. For now we'll assume the client only asks this 2488 // when a process is being debugged. 2489 2490 // Ensure we have a process running; otherwise, we can't figure this out 2491 // since we won't have a NativeProcessProtocol. 2492 if (!m_debugged_process_up || 2493 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2494 LLDB_LOGF( 2495 log, 2496 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2497 __FUNCTION__); 2498 return SendErrorResponse(0x15); 2499 } 2500 2501 // Test if we can get any region back when asking for the region around NULL. 2502 MemoryRegionInfo region_info; 2503 const Status error = 2504 m_debugged_process_up->GetMemoryRegionInfo(0, region_info); 2505 if (error.Fail()) { 2506 // We don't support memory region info collection for this 2507 // NativeProcessProtocol. 2508 return SendUnimplementedResponse(""); 2509 } 2510 2511 return SendOKResponse(); 2512 } 2513 2514 GDBRemoteCommunication::PacketResult 2515 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo( 2516 StringExtractorGDBRemote &packet) { 2517 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2518 2519 // Ensure we have a process. 2520 if (!m_debugged_process_up || 2521 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2522 LLDB_LOGF( 2523 log, 2524 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2525 __FUNCTION__); 2526 return SendErrorResponse(0x15); 2527 } 2528 2529 // Parse out the memory address. 2530 packet.SetFilePos(strlen("qMemoryRegionInfo:")); 2531 if (packet.GetBytesLeft() < 1) 2532 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet"); 2533 2534 // Read the address. Punting on validation. 2535 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0); 2536 2537 StreamGDBRemote response; 2538 2539 // Get the memory region info for the target address. 2540 MemoryRegionInfo region_info; 2541 const Status error = 2542 m_debugged_process_up->GetMemoryRegionInfo(read_addr, region_info); 2543 if (error.Fail()) { 2544 // Return the error message. 2545 2546 response.PutCString("error:"); 2547 response.PutStringAsRawHex8(error.AsCString()); 2548 response.PutChar(';'); 2549 } else { 2550 // Range start and size. 2551 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";", 2552 region_info.GetRange().GetRangeBase(), 2553 region_info.GetRange().GetByteSize()); 2554 2555 // Permissions. 2556 if (region_info.GetReadable() || region_info.GetWritable() || 2557 region_info.GetExecutable()) { 2558 // Write permissions info. 2559 response.PutCString("permissions:"); 2560 2561 if (region_info.GetReadable()) 2562 response.PutChar('r'); 2563 if (region_info.GetWritable()) 2564 response.PutChar('w'); 2565 if (region_info.GetExecutable()) 2566 response.PutChar('x'); 2567 2568 response.PutChar(';'); 2569 } 2570 2571 // Flags 2572 MemoryRegionInfo::OptionalBool memory_tagged = 2573 region_info.GetMemoryTagged(); 2574 if (memory_tagged != MemoryRegionInfo::eDontKnow) { 2575 response.PutCString("flags:"); 2576 if (memory_tagged == MemoryRegionInfo::eYes) { 2577 response.PutCString("mt"); 2578 } 2579 response.PutChar(';'); 2580 } 2581 2582 // Name 2583 ConstString name = region_info.GetName(); 2584 if (name) { 2585 response.PutCString("name:"); 2586 response.PutStringAsRawHex8(name.GetStringRef()); 2587 response.PutChar(';'); 2588 } 2589 } 2590 2591 return SendPacketNoLock(response.GetString()); 2592 } 2593 2594 GDBRemoteCommunication::PacketResult 2595 GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) { 2596 // Ensure we have a process. 2597 if (!m_debugged_process_up || 2598 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2599 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2600 LLDB_LOG(log, "failed, no process available"); 2601 return SendErrorResponse(0x15); 2602 } 2603 2604 // Parse out software or hardware breakpoint or watchpoint requested. 2605 packet.SetFilePos(strlen("Z")); 2606 if (packet.GetBytesLeft() < 1) 2607 return SendIllFormedResponse( 2608 packet, "Too short Z packet, missing software/hardware specifier"); 2609 2610 bool want_breakpoint = true; 2611 bool want_hardware = false; 2612 uint32_t watch_flags = 0; 2613 2614 const GDBStoppointType stoppoint_type = 2615 GDBStoppointType(packet.GetS32(eStoppointInvalid)); 2616 switch (stoppoint_type) { 2617 case eBreakpointSoftware: 2618 want_hardware = false; 2619 want_breakpoint = true; 2620 break; 2621 case eBreakpointHardware: 2622 want_hardware = true; 2623 want_breakpoint = true; 2624 break; 2625 case eWatchpointWrite: 2626 watch_flags = 1; 2627 want_hardware = true; 2628 want_breakpoint = false; 2629 break; 2630 case eWatchpointRead: 2631 watch_flags = 2; 2632 want_hardware = true; 2633 want_breakpoint = false; 2634 break; 2635 case eWatchpointReadWrite: 2636 watch_flags = 3; 2637 want_hardware = true; 2638 want_breakpoint = false; 2639 break; 2640 case eStoppointInvalid: 2641 return SendIllFormedResponse( 2642 packet, "Z packet had invalid software/hardware specifier"); 2643 } 2644 2645 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',') 2646 return SendIllFormedResponse( 2647 packet, "Malformed Z packet, expecting comma after stoppoint type"); 2648 2649 // Parse out the stoppoint address. 2650 if (packet.GetBytesLeft() < 1) 2651 return SendIllFormedResponse(packet, "Too short Z packet, missing address"); 2652 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0); 2653 2654 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',') 2655 return SendIllFormedResponse( 2656 packet, "Malformed Z packet, expecting comma after address"); 2657 2658 // Parse out the stoppoint size (i.e. size hint for opcode size). 2659 const uint32_t size = 2660 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 2661 if (size == std::numeric_limits<uint32_t>::max()) 2662 return SendIllFormedResponse( 2663 packet, "Malformed Z packet, failed to parse size argument"); 2664 2665 if (want_breakpoint) { 2666 // Try to set the breakpoint. 2667 const Status error = 2668 m_debugged_process_up->SetBreakpoint(addr, size, want_hardware); 2669 if (error.Success()) 2670 return SendOKResponse(); 2671 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); 2672 LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}", 2673 m_debugged_process_up->GetID(), error); 2674 return SendErrorResponse(0x09); 2675 } else { 2676 // Try to set the watchpoint. 2677 const Status error = m_debugged_process_up->SetWatchpoint( 2678 addr, size, watch_flags, want_hardware); 2679 if (error.Success()) 2680 return SendOKResponse(); 2681 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS)); 2682 LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}", 2683 m_debugged_process_up->GetID(), error); 2684 return SendErrorResponse(0x09); 2685 } 2686 } 2687 2688 GDBRemoteCommunication::PacketResult 2689 GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) { 2690 // Ensure we have a process. 2691 if (!m_debugged_process_up || 2692 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2693 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2694 LLDB_LOG(log, "failed, no process available"); 2695 return SendErrorResponse(0x15); 2696 } 2697 2698 // Parse out software or hardware breakpoint or watchpoint requested. 2699 packet.SetFilePos(strlen("z")); 2700 if (packet.GetBytesLeft() < 1) 2701 return SendIllFormedResponse( 2702 packet, "Too short z packet, missing software/hardware specifier"); 2703 2704 bool want_breakpoint = true; 2705 bool want_hardware = false; 2706 2707 const GDBStoppointType stoppoint_type = 2708 GDBStoppointType(packet.GetS32(eStoppointInvalid)); 2709 switch (stoppoint_type) { 2710 case eBreakpointHardware: 2711 want_breakpoint = true; 2712 want_hardware = true; 2713 break; 2714 case eBreakpointSoftware: 2715 want_breakpoint = true; 2716 break; 2717 case eWatchpointWrite: 2718 want_breakpoint = false; 2719 break; 2720 case eWatchpointRead: 2721 want_breakpoint = false; 2722 break; 2723 case eWatchpointReadWrite: 2724 want_breakpoint = false; 2725 break; 2726 default: 2727 return SendIllFormedResponse( 2728 packet, "z packet had invalid software/hardware specifier"); 2729 } 2730 2731 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',') 2732 return SendIllFormedResponse( 2733 packet, "Malformed z packet, expecting comma after stoppoint type"); 2734 2735 // Parse out the stoppoint address. 2736 if (packet.GetBytesLeft() < 1) 2737 return SendIllFormedResponse(packet, "Too short z packet, missing address"); 2738 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0); 2739 2740 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',') 2741 return SendIllFormedResponse( 2742 packet, "Malformed z packet, expecting comma after address"); 2743 2744 /* 2745 // Parse out the stoppoint size (i.e. size hint for opcode size). 2746 const uint32_t size = packet.GetHexMaxU32 (false, 2747 std::numeric_limits<uint32_t>::max ()); 2748 if (size == std::numeric_limits<uint32_t>::max ()) 2749 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse 2750 size argument"); 2751 */ 2752 2753 if (want_breakpoint) { 2754 // Try to clear the breakpoint. 2755 const Status error = 2756 m_debugged_process_up->RemoveBreakpoint(addr, want_hardware); 2757 if (error.Success()) 2758 return SendOKResponse(); 2759 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); 2760 LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}", 2761 m_debugged_process_up->GetID(), error); 2762 return SendErrorResponse(0x09); 2763 } else { 2764 // Try to clear the watchpoint. 2765 const Status error = m_debugged_process_up->RemoveWatchpoint(addr); 2766 if (error.Success()) 2767 return SendOKResponse(); 2768 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS)); 2769 LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}", 2770 m_debugged_process_up->GetID(), error); 2771 return SendErrorResponse(0x09); 2772 } 2773 } 2774 2775 GDBRemoteCommunication::PacketResult 2776 GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) { 2777 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 2778 2779 // Ensure we have a process. 2780 if (!m_debugged_process_up || 2781 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2782 LLDB_LOGF( 2783 log, 2784 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2785 __FUNCTION__); 2786 return SendErrorResponse(0x32); 2787 } 2788 2789 // We first try to use a continue thread id. If any one or any all set, use 2790 // the current thread. Bail out if we don't have a thread id. 2791 lldb::tid_t tid = GetContinueThreadID(); 2792 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID) 2793 tid = GetCurrentThreadID(); 2794 if (tid == LLDB_INVALID_THREAD_ID) 2795 return SendErrorResponse(0x33); 2796 2797 // Double check that we have such a thread. 2798 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here. 2799 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid); 2800 if (!thread) 2801 return SendErrorResponse(0x33); 2802 2803 // Create the step action for the given thread. 2804 ResumeAction action = {tid, eStateStepping, LLDB_INVALID_SIGNAL_NUMBER}; 2805 2806 // Setup the actions list. 2807 ResumeActionList actions; 2808 actions.Append(action); 2809 2810 // All other threads stop while we're single stepping a thread. 2811 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0); 2812 Status error = m_debugged_process_up->Resume(actions); 2813 if (error.Fail()) { 2814 LLDB_LOGF(log, 2815 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 2816 " tid %" PRIu64 " Resume() failed with error: %s", 2817 __FUNCTION__, m_debugged_process_up->GetID(), tid, 2818 error.AsCString()); 2819 return SendErrorResponse(0x49); 2820 } 2821 2822 // No response here - the stop or exit will come from the resulting action. 2823 return PacketResult::Success; 2824 } 2825 2826 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> 2827 GDBRemoteCommunicationServerLLGS::BuildTargetXml() { 2828 // Ensure we have a thread. 2829 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadAtIndex(0); 2830 if (!thread) 2831 return llvm::createStringError(llvm::inconvertibleErrorCode(), 2832 "No thread available"); 2833 2834 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 2835 // Get the register context for the first thread. 2836 NativeRegisterContext ®_context = thread->GetRegisterContext(); 2837 2838 StreamString response; 2839 2840 response.Printf("<?xml version=\"1.0\"?>"); 2841 response.Printf("<target version=\"1.0\">"); 2842 2843 response.Printf("<architecture>%s</architecture>", 2844 m_debugged_process_up->GetArchitecture() 2845 .GetTriple() 2846 .getArchName() 2847 .str() 2848 .c_str()); 2849 2850 response.Printf("<feature>"); 2851 2852 const int registers_count = reg_context.GetUserRegisterCount(); 2853 for (int reg_index = 0; reg_index < registers_count; reg_index++) { 2854 const RegisterInfo *reg_info = 2855 reg_context.GetRegisterInfoAtIndex(reg_index); 2856 2857 if (!reg_info) { 2858 LLDB_LOGF(log, 2859 "%s failed to get register info for register index %" PRIu32, 2860 "target.xml", reg_index); 2861 continue; 2862 } 2863 2864 response.Printf("<reg name=\"%s\" bitsize=\"%" PRIu32 "\" offset=\"%" PRIu32 2865 "\" regnum=\"%d\" ", 2866 reg_info->name, reg_info->byte_size * 8, 2867 reg_info->byte_offset, reg_index); 2868 2869 if (reg_info->alt_name && reg_info->alt_name[0]) 2870 response.Printf("altname=\"%s\" ", reg_info->alt_name); 2871 2872 llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info); 2873 if (!encoding.empty()) 2874 response << "encoding=\"" << encoding << "\" "; 2875 2876 llvm::StringRef format = GetFormatNameOrEmpty(*reg_info); 2877 if (!format.empty()) 2878 response << "format=\"" << format << "\" "; 2879 2880 const char *const register_set_name = 2881 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index); 2882 if (register_set_name) 2883 response << "group=\"" << register_set_name << "\" "; 2884 2885 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] != 2886 LLDB_INVALID_REGNUM) 2887 response.Printf("ehframe_regnum=\"%" PRIu32 "\" ", 2888 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]); 2889 2890 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != 2891 LLDB_INVALID_REGNUM) 2892 response.Printf("dwarf_regnum=\"%" PRIu32 "\" ", 2893 reg_info->kinds[RegisterKind::eRegisterKindDWARF]); 2894 2895 llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info); 2896 if (!kind_generic.empty()) 2897 response << "generic=\"" << kind_generic << "\" "; 2898 2899 if (reg_info->value_regs && 2900 reg_info->value_regs[0] != LLDB_INVALID_REGNUM) { 2901 response.PutCString("value_regnums=\""); 2902 CollectRegNums(reg_info->value_regs, response, false); 2903 response.Printf("\" "); 2904 } 2905 2906 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) { 2907 response.PutCString("invalidate_regnums=\""); 2908 CollectRegNums(reg_info->invalidate_regs, response, false); 2909 response.Printf("\" "); 2910 } 2911 2912 if (reg_info->dynamic_size_dwarf_expr_bytes) { 2913 const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len; 2914 response.PutCString("dynamic_size_dwarf_expr_bytes=\""); 2915 for (uint32_t i = 0; i < dwarf_opcode_len; ++i) 2916 response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]); 2917 response.Printf("\" "); 2918 } 2919 2920 response.Printf("/>"); 2921 } 2922 2923 response.Printf("</feature>"); 2924 response.Printf("</target>"); 2925 return MemoryBuffer::getMemBufferCopy(response.GetString(), "target.xml"); 2926 } 2927 2928 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> 2929 GDBRemoteCommunicationServerLLGS::ReadXferObject(llvm::StringRef object, 2930 llvm::StringRef annex) { 2931 // Make sure we have a valid process. 2932 if (!m_debugged_process_up || 2933 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2934 return llvm::createStringError(llvm::inconvertibleErrorCode(), 2935 "No process available"); 2936 } 2937 2938 if (object == "auxv") { 2939 // Grab the auxv data. 2940 auto buffer_or_error = m_debugged_process_up->GetAuxvData(); 2941 if (!buffer_or_error) 2942 return llvm::errorCodeToError(buffer_or_error.getError()); 2943 return std::move(*buffer_or_error); 2944 } 2945 2946 if (object == "libraries-svr4") { 2947 auto library_list = m_debugged_process_up->GetLoadedSVR4Libraries(); 2948 if (!library_list) 2949 return library_list.takeError(); 2950 2951 StreamString response; 2952 response.Printf("<library-list-svr4 version=\"1.0\">"); 2953 for (auto const &library : *library_list) { 2954 response.Printf("<library name=\"%s\" ", 2955 XMLEncodeAttributeValue(library.name.c_str()).c_str()); 2956 response.Printf("lm=\"0x%" PRIx64 "\" ", library.link_map); 2957 response.Printf("l_addr=\"0x%" PRIx64 "\" ", library.base_addr); 2958 response.Printf("l_ld=\"0x%" PRIx64 "\" />", library.ld_addr); 2959 } 2960 response.Printf("</library-list-svr4>"); 2961 return MemoryBuffer::getMemBufferCopy(response.GetString(), __FUNCTION__); 2962 } 2963 2964 if (object == "features" && annex == "target.xml") 2965 return BuildTargetXml(); 2966 2967 return llvm::make_error<UnimplementedError>(); 2968 } 2969 2970 GDBRemoteCommunication::PacketResult 2971 GDBRemoteCommunicationServerLLGS::Handle_qXfer( 2972 StringExtractorGDBRemote &packet) { 2973 SmallVector<StringRef, 5> fields; 2974 // The packet format is "qXfer:<object>:<action>:<annex>:offset,length" 2975 StringRef(packet.GetStringRef()).split(fields, ':', 4); 2976 if (fields.size() != 5) 2977 return SendIllFormedResponse(packet, "malformed qXfer packet"); 2978 StringRef &xfer_object = fields[1]; 2979 StringRef &xfer_action = fields[2]; 2980 StringRef &xfer_annex = fields[3]; 2981 StringExtractor offset_data(fields[4]); 2982 if (xfer_action != "read") 2983 return SendUnimplementedResponse("qXfer action not supported"); 2984 // Parse offset. 2985 const uint64_t xfer_offset = 2986 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max()); 2987 if (xfer_offset == std::numeric_limits<uint64_t>::max()) 2988 return SendIllFormedResponse(packet, "qXfer packet missing offset"); 2989 // Parse out comma. 2990 if (offset_data.GetChar() != ',') 2991 return SendIllFormedResponse(packet, 2992 "qXfer packet missing comma after offset"); 2993 // Parse out the length. 2994 const uint64_t xfer_length = 2995 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max()); 2996 if (xfer_length == std::numeric_limits<uint64_t>::max()) 2997 return SendIllFormedResponse(packet, "qXfer packet missing length"); 2998 2999 // Get a previously constructed buffer if it exists or create it now. 3000 std::string buffer_key = (xfer_object + xfer_action + xfer_annex).str(); 3001 auto buffer_it = m_xfer_buffer_map.find(buffer_key); 3002 if (buffer_it == m_xfer_buffer_map.end()) { 3003 auto buffer_up = ReadXferObject(xfer_object, xfer_annex); 3004 if (!buffer_up) 3005 return SendErrorResponse(buffer_up.takeError()); 3006 buffer_it = m_xfer_buffer_map 3007 .insert(std::make_pair(buffer_key, std::move(*buffer_up))) 3008 .first; 3009 } 3010 3011 // Send back the response 3012 StreamGDBRemote response; 3013 bool done_with_buffer = false; 3014 llvm::StringRef buffer = buffer_it->second->getBuffer(); 3015 if (xfer_offset >= buffer.size()) { 3016 // We have nothing left to send. Mark the buffer as complete. 3017 response.PutChar('l'); 3018 done_with_buffer = true; 3019 } else { 3020 // Figure out how many bytes are available starting at the given offset. 3021 buffer = buffer.drop_front(xfer_offset); 3022 // Mark the response type according to whether we're reading the remainder 3023 // of the data. 3024 if (xfer_length >= buffer.size()) { 3025 // There will be nothing left to read after this 3026 response.PutChar('l'); 3027 done_with_buffer = true; 3028 } else { 3029 // There will still be bytes to read after this request. 3030 response.PutChar('m'); 3031 buffer = buffer.take_front(xfer_length); 3032 } 3033 // Now write the data in encoded binary form. 3034 response.PutEscapedBytes(buffer.data(), buffer.size()); 3035 } 3036 3037 if (done_with_buffer) 3038 m_xfer_buffer_map.erase(buffer_it); 3039 3040 return SendPacketNoLock(response.GetString()); 3041 } 3042 3043 GDBRemoteCommunication::PacketResult 3044 GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState( 3045 StringExtractorGDBRemote &packet) { 3046 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 3047 3048 // Move past packet name. 3049 packet.SetFilePos(strlen("QSaveRegisterState")); 3050 3051 // Get the thread to use. 3052 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 3053 if (!thread) { 3054 if (m_thread_suffix_supported) 3055 return SendIllFormedResponse( 3056 packet, "No thread specified in QSaveRegisterState packet"); 3057 else 3058 return SendIllFormedResponse(packet, 3059 "No thread was is set with the Hg packet"); 3060 } 3061 3062 // Grab the register context for the thread. 3063 NativeRegisterContext& reg_context = thread->GetRegisterContext(); 3064 3065 // Save registers to a buffer. 3066 DataBufferSP register_data_sp; 3067 Status error = reg_context.ReadAllRegisterValues(register_data_sp); 3068 if (error.Fail()) { 3069 LLDB_LOG(log, "pid {0} failed to save all register values: {1}", 3070 m_debugged_process_up->GetID(), error); 3071 return SendErrorResponse(0x75); 3072 } 3073 3074 // Allocate a new save id. 3075 const uint32_t save_id = GetNextSavedRegistersID(); 3076 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) && 3077 "GetNextRegisterSaveID() returned an existing register save id"); 3078 3079 // Save the register data buffer under the save id. 3080 { 3081 std::lock_guard<std::mutex> guard(m_saved_registers_mutex); 3082 m_saved_registers_map[save_id] = register_data_sp; 3083 } 3084 3085 // Write the response. 3086 StreamGDBRemote response; 3087 response.Printf("%" PRIu32, save_id); 3088 return SendPacketNoLock(response.GetString()); 3089 } 3090 3091 GDBRemoteCommunication::PacketResult 3092 GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState( 3093 StringExtractorGDBRemote &packet) { 3094 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 3095 3096 // Parse out save id. 3097 packet.SetFilePos(strlen("QRestoreRegisterState:")); 3098 if (packet.GetBytesLeft() < 1) 3099 return SendIllFormedResponse( 3100 packet, "QRestoreRegisterState packet missing register save id"); 3101 3102 const uint32_t save_id = packet.GetU32(0); 3103 if (save_id == 0) { 3104 LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, " 3105 "expecting decimal uint32_t"); 3106 return SendErrorResponse(0x76); 3107 } 3108 3109 // Get the thread to use. 3110 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 3111 if (!thread) { 3112 if (m_thread_suffix_supported) 3113 return SendIllFormedResponse( 3114 packet, "No thread specified in QRestoreRegisterState packet"); 3115 else 3116 return SendIllFormedResponse(packet, 3117 "No thread was is set with the Hg packet"); 3118 } 3119 3120 // Grab the register context for the thread. 3121 NativeRegisterContext ®_context = thread->GetRegisterContext(); 3122 3123 // Retrieve register state buffer, then remove from the list. 3124 DataBufferSP register_data_sp; 3125 { 3126 std::lock_guard<std::mutex> guard(m_saved_registers_mutex); 3127 3128 // Find the register set buffer for the given save id. 3129 auto it = m_saved_registers_map.find(save_id); 3130 if (it == m_saved_registers_map.end()) { 3131 LLDB_LOG(log, 3132 "pid {0} does not have a register set save buffer for id {1}", 3133 m_debugged_process_up->GetID(), save_id); 3134 return SendErrorResponse(0x77); 3135 } 3136 register_data_sp = it->second; 3137 3138 // Remove it from the map. 3139 m_saved_registers_map.erase(it); 3140 } 3141 3142 Status error = reg_context.WriteAllRegisterValues(register_data_sp); 3143 if (error.Fail()) { 3144 LLDB_LOG(log, "pid {0} failed to restore all register values: {1}", 3145 m_debugged_process_up->GetID(), error); 3146 return SendErrorResponse(0x77); 3147 } 3148 3149 return SendOKResponse(); 3150 } 3151 3152 GDBRemoteCommunication::PacketResult 3153 GDBRemoteCommunicationServerLLGS::Handle_vAttach( 3154 StringExtractorGDBRemote &packet) { 3155 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3156 3157 // Consume the ';' after vAttach. 3158 packet.SetFilePos(strlen("vAttach")); 3159 if (!packet.GetBytesLeft() || packet.GetChar() != ';') 3160 return SendIllFormedResponse(packet, "vAttach missing expected ';'"); 3161 3162 // Grab the PID to which we will attach (assume hex encoding). 3163 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16); 3164 if (pid == LLDB_INVALID_PROCESS_ID) 3165 return SendIllFormedResponse(packet, 3166 "vAttach failed to parse the process id"); 3167 3168 // Attempt to attach. 3169 LLDB_LOGF(log, 3170 "GDBRemoteCommunicationServerLLGS::%s attempting to attach to " 3171 "pid %" PRIu64, 3172 __FUNCTION__, pid); 3173 3174 Status error = AttachToProcess(pid); 3175 3176 if (error.Fail()) { 3177 LLDB_LOGF(log, 3178 "GDBRemoteCommunicationServerLLGS::%s failed to attach to " 3179 "pid %" PRIu64 ": %s\n", 3180 __FUNCTION__, pid, error.AsCString()); 3181 return SendErrorResponse(error); 3182 } 3183 3184 // Notify we attached by sending a stop packet. 3185 return SendStopReasonForState(m_debugged_process_up->GetState()); 3186 } 3187 3188 GDBRemoteCommunication::PacketResult 3189 GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) { 3190 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3191 3192 StopSTDIOForwarding(); 3193 3194 // Fail if we don't have a current process. 3195 if (!m_debugged_process_up || 3196 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 3197 LLDB_LOGF( 3198 log, 3199 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 3200 __FUNCTION__); 3201 return SendErrorResponse(0x15); 3202 } 3203 3204 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; 3205 3206 // Consume the ';' after D. 3207 packet.SetFilePos(1); 3208 if (packet.GetBytesLeft()) { 3209 if (packet.GetChar() != ';') 3210 return SendIllFormedResponse(packet, "D missing expected ';'"); 3211 3212 // Grab the PID from which we will detach (assume hex encoding). 3213 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16); 3214 if (pid == LLDB_INVALID_PROCESS_ID) 3215 return SendIllFormedResponse(packet, "D failed to parse the process id"); 3216 } 3217 3218 if (pid != LLDB_INVALID_PROCESS_ID && m_debugged_process_up->GetID() != pid) { 3219 return SendIllFormedResponse(packet, "Invalid pid"); 3220 } 3221 3222 const Status error = m_debugged_process_up->Detach(); 3223 if (error.Fail()) { 3224 LLDB_LOGF(log, 3225 "GDBRemoteCommunicationServerLLGS::%s failed to detach from " 3226 "pid %" PRIu64 ": %s\n", 3227 __FUNCTION__, m_debugged_process_up->GetID(), error.AsCString()); 3228 return SendErrorResponse(0x01); 3229 } 3230 3231 return SendOKResponse(); 3232 } 3233 3234 GDBRemoteCommunication::PacketResult 3235 GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo( 3236 StringExtractorGDBRemote &packet) { 3237 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 3238 3239 packet.SetFilePos(strlen("qThreadStopInfo")); 3240 const lldb::tid_t tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID); 3241 if (tid == LLDB_INVALID_THREAD_ID) { 3242 LLDB_LOGF(log, 3243 "GDBRemoteCommunicationServerLLGS::%s failed, could not " 3244 "parse thread id from request \"%s\"", 3245 __FUNCTION__, packet.GetStringRef().data()); 3246 return SendErrorResponse(0x15); 3247 } 3248 return SendStopReplyPacketForThread(tid); 3249 } 3250 3251 GDBRemoteCommunication::PacketResult 3252 GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo( 3253 StringExtractorGDBRemote &) { 3254 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 3255 3256 // Ensure we have a debugged process. 3257 if (!m_debugged_process_up || 3258 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) 3259 return SendErrorResponse(50); 3260 LLDB_LOG(log, "preparing packet for pid {0}", m_debugged_process_up->GetID()); 3261 3262 StreamString response; 3263 const bool threads_with_valid_stop_info_only = false; 3264 llvm::Expected<json::Value> threads_info = GetJSONThreadsInfo( 3265 *m_debugged_process_up, threads_with_valid_stop_info_only); 3266 if (!threads_info) { 3267 LLDB_LOG_ERROR(log, threads_info.takeError(), 3268 "failed to prepare a packet for pid {1}: {0}", 3269 m_debugged_process_up->GetID()); 3270 return SendErrorResponse(52); 3271 } 3272 3273 response.AsRawOstream() << *threads_info; 3274 StreamGDBRemote escaped_response; 3275 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize()); 3276 return SendPacketNoLock(escaped_response.GetString()); 3277 } 3278 3279 GDBRemoteCommunication::PacketResult 3280 GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo( 3281 StringExtractorGDBRemote &packet) { 3282 // Fail if we don't have a current process. 3283 if (!m_debugged_process_up || 3284 m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID) 3285 return SendErrorResponse(68); 3286 3287 packet.SetFilePos(strlen("qWatchpointSupportInfo")); 3288 if (packet.GetBytesLeft() == 0) 3289 return SendOKResponse(); 3290 if (packet.GetChar() != ':') 3291 return SendErrorResponse(67); 3292 3293 auto hw_debug_cap = m_debugged_process_up->GetHardwareDebugSupportInfo(); 3294 3295 StreamGDBRemote response; 3296 if (hw_debug_cap == llvm::None) 3297 response.Printf("num:0;"); 3298 else 3299 response.Printf("num:%d;", hw_debug_cap->second); 3300 3301 return SendPacketNoLock(response.GetString()); 3302 } 3303 3304 GDBRemoteCommunication::PacketResult 3305 GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress( 3306 StringExtractorGDBRemote &packet) { 3307 // Fail if we don't have a current process. 3308 if (!m_debugged_process_up || 3309 m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID) 3310 return SendErrorResponse(67); 3311 3312 packet.SetFilePos(strlen("qFileLoadAddress:")); 3313 if (packet.GetBytesLeft() == 0) 3314 return SendErrorResponse(68); 3315 3316 std::string file_name; 3317 packet.GetHexByteString(file_name); 3318 3319 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS; 3320 Status error = 3321 m_debugged_process_up->GetFileLoadAddress(file_name, file_load_address); 3322 if (error.Fail()) 3323 return SendErrorResponse(69); 3324 3325 if (file_load_address == LLDB_INVALID_ADDRESS) 3326 return SendErrorResponse(1); // File not loaded 3327 3328 StreamGDBRemote response; 3329 response.PutHex64(file_load_address); 3330 return SendPacketNoLock(response.GetString()); 3331 } 3332 3333 GDBRemoteCommunication::PacketResult 3334 GDBRemoteCommunicationServerLLGS::Handle_QPassSignals( 3335 StringExtractorGDBRemote &packet) { 3336 std::vector<int> signals; 3337 packet.SetFilePos(strlen("QPassSignals:")); 3338 3339 // Read sequence of hex signal numbers divided by a semicolon and optionally 3340 // spaces. 3341 while (packet.GetBytesLeft() > 0) { 3342 int signal = packet.GetS32(-1, 16); 3343 if (signal < 0) 3344 return SendIllFormedResponse(packet, "Failed to parse signal number."); 3345 signals.push_back(signal); 3346 3347 packet.SkipSpaces(); 3348 char separator = packet.GetChar(); 3349 if (separator == '\0') 3350 break; // End of string 3351 if (separator != ';') 3352 return SendIllFormedResponse(packet, "Invalid separator," 3353 " expected semicolon."); 3354 } 3355 3356 // Fail if we don't have a current process. 3357 if (!m_debugged_process_up) 3358 return SendErrorResponse(68); 3359 3360 Status error = m_debugged_process_up->IgnoreSignals(signals); 3361 if (error.Fail()) 3362 return SendErrorResponse(69); 3363 3364 return SendOKResponse(); 3365 } 3366 3367 void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() { 3368 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3369 3370 // Tell the stdio connection to shut down. 3371 if (m_stdio_communication.IsConnected()) { 3372 auto connection = m_stdio_communication.GetConnection(); 3373 if (connection) { 3374 Status error; 3375 connection->Disconnect(&error); 3376 3377 if (error.Success()) { 3378 LLDB_LOGF(log, 3379 "GDBRemoteCommunicationServerLLGS::%s disconnect process " 3380 "terminal stdio - SUCCESS", 3381 __FUNCTION__); 3382 } else { 3383 LLDB_LOGF(log, 3384 "GDBRemoteCommunicationServerLLGS::%s disconnect process " 3385 "terminal stdio - FAIL: %s", 3386 __FUNCTION__, error.AsCString()); 3387 } 3388 } 3389 } 3390 } 3391 3392 NativeThreadProtocol *GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix( 3393 StringExtractorGDBRemote &packet) { 3394 // We have no thread if we don't have a process. 3395 if (!m_debugged_process_up || 3396 m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID) 3397 return nullptr; 3398 3399 // If the client hasn't asked for thread suffix support, there will not be a 3400 // thread suffix. Use the current thread in that case. 3401 if (!m_thread_suffix_supported) { 3402 const lldb::tid_t current_tid = GetCurrentThreadID(); 3403 if (current_tid == LLDB_INVALID_THREAD_ID) 3404 return nullptr; 3405 else if (current_tid == 0) { 3406 // Pick a thread. 3407 return m_debugged_process_up->GetThreadAtIndex(0); 3408 } else 3409 return m_debugged_process_up->GetThreadByID(current_tid); 3410 } 3411 3412 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 3413 3414 // Parse out the ';'. 3415 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') { 3416 LLDB_LOGF(log, 3417 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse " 3418 "error: expected ';' prior to start of thread suffix: packet " 3419 "contents = '%s'", 3420 __FUNCTION__, packet.GetStringRef().data()); 3421 return nullptr; 3422 } 3423 3424 if (!packet.GetBytesLeft()) 3425 return nullptr; 3426 3427 // Parse out thread: portion. 3428 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) { 3429 LLDB_LOGF(log, 3430 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse " 3431 "error: expected 'thread:' but not found, packet contents = " 3432 "'%s'", 3433 __FUNCTION__, packet.GetStringRef().data()); 3434 return nullptr; 3435 } 3436 packet.SetFilePos(packet.GetFilePos() + strlen("thread:")); 3437 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0); 3438 if (tid != 0) 3439 return m_debugged_process_up->GetThreadByID(tid); 3440 3441 return nullptr; 3442 } 3443 3444 lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const { 3445 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) { 3446 // Use whatever the debug process says is the current thread id since the 3447 // protocol either didn't specify or specified we want any/all threads 3448 // marked as the current thread. 3449 if (!m_debugged_process_up) 3450 return LLDB_INVALID_THREAD_ID; 3451 return m_debugged_process_up->GetCurrentThreadID(); 3452 } 3453 // Use the specific current thread id set by the gdb remote protocol. 3454 return m_current_tid; 3455 } 3456 3457 uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() { 3458 std::lock_guard<std::mutex> guard(m_saved_registers_mutex); 3459 return m_next_saved_registers_id++; 3460 } 3461 3462 void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() { 3463 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3464 3465 LLDB_LOG(log, "clearing {0} xfer buffers", m_xfer_buffer_map.size()); 3466 m_xfer_buffer_map.clear(); 3467 } 3468 3469 FileSpec 3470 GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path, 3471 const ArchSpec &arch) { 3472 if (m_debugged_process_up) { 3473 FileSpec file_spec; 3474 if (m_debugged_process_up 3475 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec) 3476 .Success()) { 3477 if (FileSystem::Instance().Exists(file_spec)) 3478 return file_spec; 3479 } 3480 } 3481 3482 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch); 3483 } 3484 3485 std::string GDBRemoteCommunicationServerLLGS::XMLEncodeAttributeValue( 3486 llvm::StringRef value) { 3487 std::string result; 3488 for (const char &c : value) { 3489 switch (c) { 3490 case '\'': 3491 result += "'"; 3492 break; 3493 case '"': 3494 result += """; 3495 break; 3496 case '<': 3497 result += "<"; 3498 break; 3499 case '>': 3500 result += ">"; 3501 break; 3502 default: 3503 result += c; 3504 break; 3505 } 3506 } 3507 return result; 3508 } 3509