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