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