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