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