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