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