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