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