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