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