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