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