1 //===-- GDBRemoteCommunicationServer.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 "GDBRemoteCommunicationServer.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/ConnectionFileDescriptor.h" 27 #include "lldb/Core/Debugger.h" 28 #include "lldb/Core/Log.h" 29 #include "lldb/Core/State.h" 30 #include "lldb/Core/StreamString.h" 31 #include "lldb/Host/Debug.h" 32 #include "lldb/Host/Endian.h" 33 #include "lldb/Host/File.h" 34 #include "lldb/Host/FileSystem.h" 35 #include "lldb/Host/Host.h" 36 #include "lldb/Host/HostInfo.h" 37 #include "lldb/Host/TimeValue.h" 38 #include "lldb/Target/FileAction.h" 39 #include "lldb/Target/Platform.h" 40 #include "lldb/Target/Process.h" 41 #include "lldb/Target/NativeRegisterContext.h" 42 #include "Host/common/NativeProcessProtocol.h" 43 #include "Host/common/NativeThreadProtocol.h" 44 45 // Project includes 46 #include "Utility/StringExtractorGDBRemote.h" 47 #include "ProcessGDBRemote.h" 48 #include "ProcessGDBRemoteLog.h" 49 50 using namespace lldb; 51 using namespace lldb_private; 52 53 //---------------------------------------------------------------------- 54 // GDBRemote Errors 55 //---------------------------------------------------------------------- 56 57 namespace 58 { 59 enum GDBRemoteServerError 60 { 61 // Set to the first unused error number in literal form below 62 eErrorFirst = 29, 63 eErrorNoProcess = eErrorFirst, 64 eErrorResume, 65 eErrorExitStatus 66 }; 67 } 68 69 //---------------------------------------------------------------------- 70 // GDBRemoteCommunicationServer constructor 71 //---------------------------------------------------------------------- 72 GDBRemoteCommunicationServer::GDBRemoteCommunicationServer(bool is_platform) : 73 GDBRemoteCommunication ("gdb-remote.server", "gdb-remote.server.rx_packet", is_platform), 74 m_platform_sp (Platform::GetDefaultPlatform ()), 75 m_async_thread (LLDB_INVALID_HOST_THREAD), 76 m_process_launch_info (), 77 m_process_launch_error (), 78 m_spawned_pids (), 79 m_spawned_pids_mutex (Mutex::eMutexTypeRecursive), 80 m_proc_infos (), 81 m_proc_infos_index (0), 82 m_port_map (), 83 m_port_offset(0), 84 m_current_tid (LLDB_INVALID_THREAD_ID), 85 m_continue_tid (LLDB_INVALID_THREAD_ID), 86 m_debugged_process_mutex (Mutex::eMutexTypeRecursive), 87 m_debugged_process_sp (), 88 m_debugger_sp (), 89 m_stdio_communication ("process.stdio"), 90 m_exit_now (false), 91 m_inferior_prev_state (StateType::eStateInvalid), 92 m_thread_suffix_supported (false), 93 m_list_threads_in_stop_reply (false), 94 m_active_auxv_buffer_sp (), 95 m_saved_registers_mutex (), 96 m_saved_registers_map (), 97 m_next_saved_registers_id (1) 98 { 99 assert(is_platform && "must be lldb-platform if debugger is not specified"); 100 } 101 102 GDBRemoteCommunicationServer::GDBRemoteCommunicationServer(bool is_platform, 103 const lldb::PlatformSP& platform_sp, 104 lldb::DebuggerSP &debugger_sp) : 105 GDBRemoteCommunication ("gdb-remote.server", "gdb-remote.server.rx_packet", is_platform), 106 m_platform_sp (platform_sp), 107 m_async_thread (LLDB_INVALID_HOST_THREAD), 108 m_process_launch_info (), 109 m_process_launch_error (), 110 m_spawned_pids (), 111 m_spawned_pids_mutex (Mutex::eMutexTypeRecursive), 112 m_proc_infos (), 113 m_proc_infos_index (0), 114 m_port_map (), 115 m_port_offset(0), 116 m_current_tid (LLDB_INVALID_THREAD_ID), 117 m_continue_tid (LLDB_INVALID_THREAD_ID), 118 m_debugged_process_mutex (Mutex::eMutexTypeRecursive), 119 m_debugged_process_sp (), 120 m_debugger_sp (debugger_sp), 121 m_stdio_communication ("process.stdio"), 122 m_exit_now (false), 123 m_inferior_prev_state (StateType::eStateInvalid), 124 m_thread_suffix_supported (false), 125 m_list_threads_in_stop_reply (false), 126 m_active_auxv_buffer_sp (), 127 m_saved_registers_mutex (), 128 m_saved_registers_map (), 129 m_next_saved_registers_id (1) 130 { 131 assert(platform_sp); 132 assert((is_platform || debugger_sp) && "must specify non-NULL debugger_sp when lldb-gdbserver"); 133 } 134 135 //---------------------------------------------------------------------- 136 // Destructor 137 //---------------------------------------------------------------------- 138 GDBRemoteCommunicationServer::~GDBRemoteCommunicationServer() 139 { 140 } 141 142 GDBRemoteCommunication::PacketResult 143 GDBRemoteCommunicationServer::GetPacketAndSendResponse (uint32_t timeout_usec, 144 Error &error, 145 bool &interrupt, 146 bool &quit) 147 { 148 StringExtractorGDBRemote packet; 149 150 PacketResult packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (packet, timeout_usec); 151 if (packet_result == PacketResult::Success) 152 { 153 const StringExtractorGDBRemote::ServerPacketType packet_type = packet.GetServerPacketType (); 154 switch (packet_type) 155 { 156 case StringExtractorGDBRemote::eServerPacketType_nack: 157 case StringExtractorGDBRemote::eServerPacketType_ack: 158 break; 159 160 case StringExtractorGDBRemote::eServerPacketType_invalid: 161 error.SetErrorString("invalid packet"); 162 quit = true; 163 break; 164 165 default: 166 case StringExtractorGDBRemote::eServerPacketType_unimplemented: 167 packet_result = SendUnimplementedResponse (packet.GetStringRef().c_str()); 168 break; 169 170 case StringExtractorGDBRemote::eServerPacketType_A: 171 packet_result = Handle_A (packet); 172 break; 173 174 case StringExtractorGDBRemote::eServerPacketType_qfProcessInfo: 175 packet_result = Handle_qfProcessInfo (packet); 176 break; 177 178 case StringExtractorGDBRemote::eServerPacketType_qsProcessInfo: 179 packet_result = Handle_qsProcessInfo (packet); 180 break; 181 182 case StringExtractorGDBRemote::eServerPacketType_qC: 183 packet_result = Handle_qC (packet); 184 break; 185 186 case StringExtractorGDBRemote::eServerPacketType_qHostInfo: 187 packet_result = Handle_qHostInfo (packet); 188 break; 189 190 case StringExtractorGDBRemote::eServerPacketType_qLaunchGDBServer: 191 packet_result = Handle_qLaunchGDBServer (packet); 192 break; 193 194 case StringExtractorGDBRemote::eServerPacketType_qKillSpawnedProcess: 195 packet_result = Handle_qKillSpawnedProcess (packet); 196 break; 197 198 case StringExtractorGDBRemote::eServerPacketType_k: 199 packet_result = Handle_k (packet); 200 quit = true; 201 break; 202 203 case StringExtractorGDBRemote::eServerPacketType_qLaunchSuccess: 204 packet_result = Handle_qLaunchSuccess (packet); 205 break; 206 207 case StringExtractorGDBRemote::eServerPacketType_qGroupName: 208 packet_result = Handle_qGroupName (packet); 209 break; 210 211 case StringExtractorGDBRemote::eServerPacketType_qProcessInfo: 212 packet_result = Handle_qProcessInfo (packet); 213 break; 214 215 case StringExtractorGDBRemote::eServerPacketType_qProcessInfoPID: 216 packet_result = Handle_qProcessInfoPID (packet); 217 break; 218 219 case StringExtractorGDBRemote::eServerPacketType_qSpeedTest: 220 packet_result = Handle_qSpeedTest (packet); 221 break; 222 223 case StringExtractorGDBRemote::eServerPacketType_qUserName: 224 packet_result = Handle_qUserName (packet); 225 break; 226 227 case StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir: 228 packet_result = Handle_qGetWorkingDir(packet); 229 break; 230 231 case StringExtractorGDBRemote::eServerPacketType_QEnvironment: 232 packet_result = Handle_QEnvironment (packet); 233 break; 234 235 case StringExtractorGDBRemote::eServerPacketType_QLaunchArch: 236 packet_result = Handle_QLaunchArch (packet); 237 break; 238 239 case StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR: 240 packet_result = Handle_QSetDisableASLR (packet); 241 break; 242 243 case StringExtractorGDBRemote::eServerPacketType_QSetDetachOnError: 244 packet_result = Handle_QSetDetachOnError (packet); 245 break; 246 247 case StringExtractorGDBRemote::eServerPacketType_QSetSTDIN: 248 packet_result = Handle_QSetSTDIN (packet); 249 break; 250 251 case StringExtractorGDBRemote::eServerPacketType_QSetSTDOUT: 252 packet_result = Handle_QSetSTDOUT (packet); 253 break; 254 255 case StringExtractorGDBRemote::eServerPacketType_QSetSTDERR: 256 packet_result = Handle_QSetSTDERR (packet); 257 break; 258 259 case StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir: 260 packet_result = Handle_QSetWorkingDir (packet); 261 break; 262 263 case StringExtractorGDBRemote::eServerPacketType_QStartNoAckMode: 264 packet_result = Handle_QStartNoAckMode (packet); 265 break; 266 267 case StringExtractorGDBRemote::eServerPacketType_qPlatform_mkdir: 268 packet_result = Handle_qPlatform_mkdir (packet); 269 break; 270 271 case StringExtractorGDBRemote::eServerPacketType_qPlatform_chmod: 272 packet_result = Handle_qPlatform_chmod (packet); 273 break; 274 275 case StringExtractorGDBRemote::eServerPacketType_qPlatform_shell: 276 packet_result = Handle_qPlatform_shell (packet); 277 break; 278 279 case StringExtractorGDBRemote::eServerPacketType_C: 280 packet_result = Handle_C (packet); 281 break; 282 283 case StringExtractorGDBRemote::eServerPacketType_c: 284 packet_result = Handle_c (packet); 285 break; 286 287 case StringExtractorGDBRemote::eServerPacketType_vCont: 288 packet_result = Handle_vCont (packet); 289 break; 290 291 case StringExtractorGDBRemote::eServerPacketType_vCont_actions: 292 packet_result = Handle_vCont_actions (packet); 293 break; 294 295 case StringExtractorGDBRemote::eServerPacketType_stop_reason: // ? 296 packet_result = Handle_stop_reason (packet); 297 break; 298 299 case StringExtractorGDBRemote::eServerPacketType_vFile_open: 300 packet_result = Handle_vFile_Open (packet); 301 break; 302 303 case StringExtractorGDBRemote::eServerPacketType_vFile_close: 304 packet_result = Handle_vFile_Close (packet); 305 break; 306 307 case StringExtractorGDBRemote::eServerPacketType_vFile_pread: 308 packet_result = Handle_vFile_pRead (packet); 309 break; 310 311 case StringExtractorGDBRemote::eServerPacketType_vFile_pwrite: 312 packet_result = Handle_vFile_pWrite (packet); 313 break; 314 315 case StringExtractorGDBRemote::eServerPacketType_vFile_size: 316 packet_result = Handle_vFile_Size (packet); 317 break; 318 319 case StringExtractorGDBRemote::eServerPacketType_vFile_mode: 320 packet_result = Handle_vFile_Mode (packet); 321 break; 322 323 case StringExtractorGDBRemote::eServerPacketType_vFile_exists: 324 packet_result = Handle_vFile_Exists (packet); 325 break; 326 327 case StringExtractorGDBRemote::eServerPacketType_vFile_stat: 328 packet_result = Handle_vFile_Stat (packet); 329 break; 330 331 case StringExtractorGDBRemote::eServerPacketType_vFile_md5: 332 packet_result = Handle_vFile_MD5 (packet); 333 break; 334 335 case StringExtractorGDBRemote::eServerPacketType_vFile_symlink: 336 packet_result = Handle_vFile_symlink (packet); 337 break; 338 339 case StringExtractorGDBRemote::eServerPacketType_vFile_unlink: 340 packet_result = Handle_vFile_unlink (packet); 341 break; 342 343 case StringExtractorGDBRemote::eServerPacketType_qRegisterInfo: 344 packet_result = Handle_qRegisterInfo (packet); 345 break; 346 347 case StringExtractorGDBRemote::eServerPacketType_qfThreadInfo: 348 packet_result = Handle_qfThreadInfo (packet); 349 break; 350 351 case StringExtractorGDBRemote::eServerPacketType_qsThreadInfo: 352 packet_result = Handle_qsThreadInfo (packet); 353 break; 354 355 case StringExtractorGDBRemote::eServerPacketType_p: 356 packet_result = Handle_p (packet); 357 break; 358 359 case StringExtractorGDBRemote::eServerPacketType_P: 360 packet_result = Handle_P (packet); 361 break; 362 363 case StringExtractorGDBRemote::eServerPacketType_H: 364 packet_result = Handle_H (packet); 365 break; 366 367 case StringExtractorGDBRemote::eServerPacketType_m: 368 packet_result = Handle_m (packet); 369 break; 370 371 case StringExtractorGDBRemote::eServerPacketType_M: 372 packet_result = Handle_M (packet); 373 break; 374 375 case StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported: 376 packet_result = Handle_qMemoryRegionInfoSupported (packet); 377 break; 378 379 case StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo: 380 packet_result = Handle_qMemoryRegionInfo (packet); 381 break; 382 383 case StringExtractorGDBRemote::eServerPacketType_interrupt: 384 if (IsGdbServer ()) 385 packet_result = Handle_interrupt (packet); 386 else 387 { 388 error.SetErrorString("interrupt received"); 389 interrupt = true; 390 } 391 break; 392 393 case StringExtractorGDBRemote::eServerPacketType_Z: 394 packet_result = Handle_Z (packet); 395 break; 396 397 case StringExtractorGDBRemote::eServerPacketType_z: 398 packet_result = Handle_z (packet); 399 break; 400 401 case StringExtractorGDBRemote::eServerPacketType_s: 402 packet_result = Handle_s (packet); 403 break; 404 405 case StringExtractorGDBRemote::eServerPacketType_qSupported: 406 packet_result = Handle_qSupported (packet); 407 break; 408 409 case StringExtractorGDBRemote::eServerPacketType_QThreadSuffixSupported: 410 packet_result = Handle_QThreadSuffixSupported (packet); 411 break; 412 413 case StringExtractorGDBRemote::eServerPacketType_QListThreadsInStopReply: 414 packet_result = Handle_QListThreadsInStopReply (packet); 415 break; 416 417 case StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read: 418 packet_result = Handle_qXfer_auxv_read (packet); 419 break; 420 421 case StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState: 422 packet_result = Handle_QSaveRegisterState (packet); 423 break; 424 425 case StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState: 426 packet_result = Handle_QRestoreRegisterState (packet); 427 break; 428 429 case StringExtractorGDBRemote::eServerPacketType_vAttach: 430 packet_result = Handle_vAttach (packet); 431 break; 432 } 433 } 434 else 435 { 436 if (!IsConnected()) 437 { 438 error.SetErrorString("lost connection"); 439 quit = true; 440 } 441 else 442 { 443 error.SetErrorString("timeout"); 444 } 445 } 446 447 // Check if anything occurred that would force us to want to exit. 448 if (m_exit_now) 449 quit = true; 450 451 return packet_result; 452 } 453 454 lldb_private::Error 455 GDBRemoteCommunicationServer::SetLaunchArguments (const char *const args[], int argc) 456 { 457 if ((argc < 1) || !args || !args[0] || !args[0][0]) 458 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__); 459 460 m_process_launch_info.SetArguments (const_cast<const char**> (args), true); 461 return lldb_private::Error (); 462 } 463 464 lldb_private::Error 465 GDBRemoteCommunicationServer::SetLaunchFlags (unsigned int launch_flags) 466 { 467 m_process_launch_info.GetFlags ().Set (launch_flags); 468 return lldb_private::Error (); 469 } 470 471 lldb_private::Error 472 GDBRemoteCommunicationServer::LaunchProcess () 473 { 474 // FIXME This looks an awful lot like we could override this in 475 // derived classes, one for lldb-platform, the other for lldb-gdbserver. 476 if (IsGdbServer ()) 477 return LaunchDebugServerProcess (); 478 else 479 return LaunchPlatformProcess (); 480 } 481 482 lldb_private::Error 483 GDBRemoteCommunicationServer::LaunchDebugServerProcess () 484 { 485 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 486 487 if (!m_process_launch_info.GetArguments ().GetArgumentCount ()) 488 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__); 489 490 lldb_private::Error error; 491 { 492 Mutex::Locker locker (m_debugged_process_mutex); 493 assert (!m_debugged_process_sp && "lldb-gdbserver creating debugged process but one already exists"); 494 error = m_platform_sp->LaunchNativeProcess ( 495 m_process_launch_info, 496 *this, 497 m_debugged_process_sp); 498 } 499 500 if (!error.Success ()) 501 { 502 fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0)); 503 return error; 504 } 505 506 // Setup stdout/stderr mapping from inferior. 507 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor (); 508 if (terminal_fd >= 0) 509 { 510 if (log) 511 log->Printf ("ProcessGDBRemoteCommunicationServer::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd); 512 error = SetSTDIOFileDescriptor (terminal_fd); 513 if (error.Fail ()) 514 return error; 515 } 516 else 517 { 518 if (log) 519 log->Printf ("ProcessGDBRemoteCommunicationServer::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd); 520 } 521 522 printf ("Launched '%s' as process %" PRIu64 "...\n", m_process_launch_info.GetArguments ().GetArgumentAtIndex (0), m_process_launch_info.GetProcessID ()); 523 524 // Add to list of spawned processes. 525 lldb::pid_t pid; 526 if ((pid = m_process_launch_info.GetProcessID ()) != LLDB_INVALID_PROCESS_ID) 527 { 528 // add to spawned pids 529 { 530 Mutex::Locker locker (m_spawned_pids_mutex); 531 // On an lldb-gdbserver, we would expect there to be only one. 532 assert (m_spawned_pids.empty () && "lldb-gdbserver adding tracked process but one already existed"); 533 m_spawned_pids.insert (pid); 534 } 535 } 536 537 if (error.Success ()) 538 { 539 if (log) 540 log->Printf ("GDBRemoteCommunicationServer::%s beginning check to wait for launched application to hit first stop", __FUNCTION__); 541 542 int iteration = 0; 543 // Wait for the process to hit its first stop state. 544 while (!StateIsStoppedState (m_debugged_process_sp->GetState (), false)) 545 { 546 if (log) 547 log->Printf ("GDBRemoteCommunicationServer::%s waiting for launched process to hit first stop (%d)...", __FUNCTION__, iteration++); 548 549 // FIXME use a finer granularity. 550 std::this_thread::sleep_for(std::chrono::seconds(1)); 551 } 552 553 if (log) 554 log->Printf ("GDBRemoteCommunicationServer::%s launched application has hit first stop", __FUNCTION__); 555 556 } 557 558 return error; 559 } 560 561 lldb_private::Error 562 GDBRemoteCommunicationServer::LaunchPlatformProcess () 563 { 564 if (!m_process_launch_info.GetArguments ().GetArgumentCount ()) 565 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__); 566 567 // specify the process monitor if not already set. This should 568 // generally be what happens since we need to reap started 569 // processes. 570 if (!m_process_launch_info.GetMonitorProcessCallback ()) 571 m_process_launch_info.SetMonitorProcessCallback(ReapDebuggedProcess, this, false); 572 573 lldb_private::Error error = m_platform_sp->LaunchProcess (m_process_launch_info); 574 if (!error.Success ()) 575 { 576 fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0)); 577 return error; 578 } 579 580 printf ("Launched '%s' as process %" PRIu64 "...\n", m_process_launch_info.GetArguments ().GetArgumentAtIndex (0), m_process_launch_info.GetProcessID()); 581 582 // add to list of spawned processes. On an lldb-gdbserver, we 583 // would expect there to be only one. 584 lldb::pid_t pid; 585 if ( (pid = m_process_launch_info.GetProcessID()) != LLDB_INVALID_PROCESS_ID ) 586 { 587 // add to spawned pids 588 { 589 Mutex::Locker locker (m_spawned_pids_mutex); 590 m_spawned_pids.insert(pid); 591 } 592 } 593 594 return error; 595 } 596 597 lldb_private::Error 598 GDBRemoteCommunicationServer::AttachToProcess (lldb::pid_t pid) 599 { 600 Error error; 601 602 if (!IsGdbServer ()) 603 { 604 error.SetErrorString("cannot AttachToProcess () unless process is lldb-gdbserver"); 605 return error; 606 } 607 608 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS)); 609 if (log) 610 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64, __FUNCTION__, pid); 611 612 // Scope for mutex locker. 613 { 614 // Before we try to attach, make sure we aren't already monitoring something else. 615 Mutex::Locker locker (m_spawned_pids_mutex); 616 if (!m_spawned_pids.empty ()) 617 { 618 error.SetErrorStringWithFormat ("cannot attach to a process %" PRIu64 " when another process with pid %" PRIu64 " is being debugged.", pid, *m_spawned_pids.begin()); 619 return error; 620 } 621 622 // Try to attach. 623 error = m_platform_sp->AttachNativeProcess (pid, *this, m_debugged_process_sp); 624 if (!error.Success ()) 625 { 626 fprintf (stderr, "%s: failed to attach to process %" PRIu64 ": %s", __FUNCTION__, pid, error.AsCString ()); 627 return error; 628 } 629 630 // Setup stdout/stderr mapping from inferior. 631 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor (); 632 if (terminal_fd >= 0) 633 { 634 if (log) 635 log->Printf ("ProcessGDBRemoteCommunicationServer::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd); 636 error = SetSTDIOFileDescriptor (terminal_fd); 637 if (error.Fail ()) 638 return error; 639 } 640 else 641 { 642 if (log) 643 log->Printf ("ProcessGDBRemoteCommunicationServer::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd); 644 } 645 646 printf ("Attached to process %" PRIu64 "...\n", pid); 647 648 // Add to list of spawned processes. 649 assert (m_spawned_pids.empty () && "lldb-gdbserver adding tracked process but one already existed"); 650 m_spawned_pids.insert (pid); 651 652 return error; 653 } 654 } 655 656 void 657 GDBRemoteCommunicationServer::InitializeDelegate (lldb_private::NativeProcessProtocol *process) 658 { 659 assert (process && "process cannot be NULL"); 660 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 661 if (log) 662 { 663 log->Printf ("GDBRemoteCommunicationServer::%s called with NativeProcessProtocol pid %" PRIu64 ", current state: %s", 664 __FUNCTION__, 665 process->GetID (), 666 StateAsCString (process->GetState ())); 667 } 668 } 669 670 GDBRemoteCommunication::PacketResult 671 GDBRemoteCommunicationServer::SendWResponse (lldb_private::NativeProcessProtocol *process) 672 { 673 assert (process && "process cannot be NULL"); 674 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 675 676 // send W notification 677 ExitType exit_type = ExitType::eExitTypeInvalid; 678 int return_code = 0; 679 std::string exit_description; 680 681 const bool got_exit_info = process->GetExitStatus (&exit_type, &return_code, exit_description); 682 if (!got_exit_info) 683 { 684 if (log) 685 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", failed to retrieve process exit status", __FUNCTION__, process->GetID ()); 686 687 StreamGDBRemote response; 688 response.PutChar ('E'); 689 response.PutHex8 (GDBRemoteServerError::eErrorExitStatus); 690 return SendPacketNoLock(response.GetData(), response.GetSize()); 691 } 692 else 693 { 694 if (log) 695 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", returning exit type %d, return code %d [%s]", __FUNCTION__, process->GetID (), exit_type, return_code, exit_description.c_str ()); 696 697 StreamGDBRemote response; 698 699 char return_type_code; 700 switch (exit_type) 701 { 702 case ExitType::eExitTypeExit: return_type_code = 'W'; break; 703 case ExitType::eExitTypeSignal: return_type_code = 'X'; break; 704 case ExitType::eExitTypeStop: return_type_code = 'S'; break; 705 706 case ExitType::eExitTypeInvalid: 707 default: return_type_code = 'E'; break; 708 } 709 response.PutChar (return_type_code); 710 711 // POSIX exit status limited to unsigned 8 bits. 712 response.PutHex8 (return_code); 713 714 return SendPacketNoLock(response.GetData(), response.GetSize()); 715 } 716 } 717 718 static void 719 AppendHexValue (StreamString &response, const uint8_t* buf, uint32_t buf_size, bool swap) 720 { 721 int64_t i; 722 if (swap) 723 { 724 for (i = buf_size-1; i >= 0; i--) 725 response.PutHex8 (buf[i]); 726 } 727 else 728 { 729 for (i = 0; i < buf_size; i++) 730 response.PutHex8 (buf[i]); 731 } 732 } 733 734 static void 735 WriteRegisterValueInHexFixedWidth (StreamString &response, 736 NativeRegisterContextSP ®_ctx_sp, 737 const RegisterInfo ®_info, 738 const RegisterValue *reg_value_p) 739 { 740 RegisterValue reg_value; 741 if (!reg_value_p) 742 { 743 Error error = reg_ctx_sp->ReadRegister (®_info, reg_value); 744 if (error.Success ()) 745 reg_value_p = ®_value; 746 // else log. 747 } 748 749 if (reg_value_p) 750 { 751 AppendHexValue (response, (const uint8_t*) reg_value_p->GetBytes (), reg_value_p->GetByteSize (), false); 752 } 753 else 754 { 755 // Zero-out any unreadable values. 756 if (reg_info.byte_size > 0) 757 { 758 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0'); 759 AppendHexValue (response, zeros.data(), zeros.size(), false); 760 } 761 } 762 } 763 764 // WriteGdbRegnumWithFixedWidthHexRegisterValue (response, reg_ctx_sp, *reg_info_p, reg_value); 765 766 767 static void 768 WriteGdbRegnumWithFixedWidthHexRegisterValue (StreamString &response, 769 NativeRegisterContextSP ®_ctx_sp, 770 const RegisterInfo ®_info, 771 const RegisterValue ®_value) 772 { 773 // Output the register number as 'NN:VVVVVVVV;' where NN is a 2 bytes HEX 774 // gdb register number, and VVVVVVVV is the correct number of hex bytes 775 // as ASCII for the register value. 776 if (reg_info.kinds[eRegisterKindGDB] == LLDB_INVALID_REGNUM) 777 return; 778 779 response.Printf ("%.02x:", reg_info.kinds[eRegisterKindGDB]); 780 WriteRegisterValueInHexFixedWidth (response, reg_ctx_sp, reg_info, ®_value); 781 response.PutChar (';'); 782 } 783 784 785 GDBRemoteCommunication::PacketResult 786 GDBRemoteCommunicationServer::SendStopReplyPacketForThread (lldb::tid_t tid) 787 { 788 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 789 790 // Ensure we're llgs. 791 if (!IsGdbServer ()) 792 { 793 // Only supported on llgs 794 return SendUnimplementedResponse (""); 795 } 796 797 // Ensure we have a debugged process. 798 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 799 return SendErrorResponse (50); 800 801 if (log) 802 log->Printf ("GDBRemoteCommunicationServer::%s preparing packet for pid %" PRIu64 " tid %" PRIu64, 803 __FUNCTION__, m_debugged_process_sp->GetID (), tid); 804 805 // Ensure we can get info on the given thread. 806 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid)); 807 if (!thread_sp) 808 return SendErrorResponse (51); 809 810 // Grab the reason this thread stopped. 811 struct ThreadStopInfo tid_stop_info; 812 if (!thread_sp->GetStopReason (tid_stop_info)) 813 return SendErrorResponse (52); 814 815 const bool did_exec = tid_stop_info.reason == eStopReasonExec; 816 // FIXME implement register handling for exec'd inferiors. 817 // if (did_exec) 818 // { 819 // const bool force = true; 820 // InitializeRegisters(force); 821 // } 822 823 StreamString response; 824 // Output the T packet with the thread 825 response.PutChar ('T'); 826 int signum = tid_stop_info.details.signal.signo; 827 if (log) 828 { 829 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " got signal signo = %d, reason = %d, exc_type = %" PRIu64, 830 __FUNCTION__, 831 m_debugged_process_sp->GetID (), 832 tid, 833 signum, 834 tid_stop_info.reason, 835 tid_stop_info.details.exception.type); 836 } 837 838 switch (tid_stop_info.reason) 839 { 840 case eStopReasonSignal: 841 case eStopReasonException: 842 signum = thread_sp->TranslateStopInfoToGdbSignal (tid_stop_info); 843 break; 844 default: 845 signum = 0; 846 if (log) 847 { 848 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " has stop reason %d, using signo = 0 in stop reply response", 849 __FUNCTION__, 850 m_debugged_process_sp->GetID (), 851 tid, 852 tid_stop_info.reason); 853 } 854 break; 855 } 856 857 // Print the signal number. 858 response.PutHex8 (signum & 0xff); 859 860 // Include the tid. 861 response.Printf ("thread:%" PRIx64 ";", tid); 862 863 // Include the thread name if there is one. 864 const char *thread_name = thread_sp->GetName (); 865 if (thread_name && thread_name[0]) 866 { 867 size_t thread_name_len = strlen(thread_name); 868 869 if (::strcspn (thread_name, "$#+-;:") == thread_name_len) 870 { 871 response.PutCString ("name:"); 872 response.PutCString (thread_name); 873 } 874 else 875 { 876 // The thread name contains special chars, send as hex bytes. 877 response.PutCString ("hexname:"); 878 response.PutCStringAsRawHex8 (thread_name); 879 } 880 response.PutChar (';'); 881 } 882 883 // FIXME look for analog 884 // thread_identifier_info_data_t thread_ident_info; 885 // if (DNBThreadGetIdentifierInfo (pid, tid, &thread_ident_info)) 886 // { 887 // if (thread_ident_info.dispatch_qaddr != 0) 888 // ostrm << std::hex << "qaddr:" << thread_ident_info.dispatch_qaddr << ';'; 889 // } 890 891 // If a 'QListThreadsInStopReply' was sent to enable this feature, we 892 // will send all thread IDs back in the "threads" key whose value is 893 // a list of hex thread IDs separated by commas: 894 // "threads:10a,10b,10c;" 895 // This will save the debugger from having to send a pair of qfThreadInfo 896 // and qsThreadInfo packets, but it also might take a lot of room in the 897 // stop reply packet, so it must be enabled only on systems where there 898 // are no limits on packet lengths. 899 if (m_list_threads_in_stop_reply) 900 { 901 response.PutCString ("threads:"); 902 903 uint32_t thread_index = 0; 904 NativeThreadProtocolSP listed_thread_sp; 905 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)) 906 { 907 if (thread_index > 0) 908 response.PutChar (','); 909 response.Printf ("%" PRIx64, listed_thread_sp->GetID ()); 910 } 911 response.PutChar (';'); 912 } 913 914 // 915 // Expedite registers. 916 // 917 918 // Grab the register context. 919 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext (); 920 if (reg_ctx_sp) 921 { 922 // Expedite all registers in the first register set (i.e. should be GPRs) that are not contained in other registers. 923 const RegisterSet *reg_set_p; 924 if (reg_ctx_sp->GetRegisterSetCount () > 0 && ((reg_set_p = reg_ctx_sp->GetRegisterSet (0)) != nullptr)) 925 { 926 if (log) 927 log->Printf ("GDBRemoteCommunicationServer::%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); 928 929 for (const uint32_t *reg_num_p = reg_set_p->registers; *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) 930 { 931 const RegisterInfo *const reg_info_p = reg_ctx_sp->GetRegisterInfoAtIndex (*reg_num_p); 932 if (reg_info_p == nullptr) 933 { 934 if (log) 935 log->Printf ("GDBRemoteCommunicationServer::%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); 936 } 937 else if (reg_info_p->value_regs == nullptr) 938 { 939 // Only expediate registers that are not contained in other registers. 940 RegisterValue reg_value; 941 Error error = reg_ctx_sp->ReadRegister (reg_info_p, reg_value); 942 if (error.Success ()) 943 WriteGdbRegnumWithFixedWidthHexRegisterValue (response, reg_ctx_sp, *reg_info_p, reg_value); 944 else 945 { 946 if (log) 947 log->Printf ("GDBRemoteCommunicationServer::%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 ()); 948 949 } 950 } 951 } 952 } 953 } 954 955 if (did_exec) 956 { 957 response.PutCString ("reason:exec;"); 958 } 959 else if ((tid_stop_info.reason == eStopReasonException) && tid_stop_info.details.exception.type) 960 { 961 response.PutCString ("metype:"); 962 response.PutHex64 (tid_stop_info.details.exception.type); 963 response.PutCString (";mecount:"); 964 response.PutHex32 (tid_stop_info.details.exception.data_count); 965 response.PutChar (';'); 966 967 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) 968 { 969 response.PutCString ("medata:"); 970 response.PutHex64 (tid_stop_info.details.exception.data[i]); 971 response.PutChar (';'); 972 } 973 } 974 975 return SendPacketNoLock (response.GetData(), response.GetSize()); 976 } 977 978 void 979 GDBRemoteCommunicationServer::HandleInferiorState_Exited (lldb_private::NativeProcessProtocol *process) 980 { 981 assert (process && "process cannot be NULL"); 982 983 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 984 if (log) 985 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__); 986 987 // Send the exit result, and don't flush output. 988 // Note: flushing output here would join the inferior stdio reflection thread, which 989 // would gunk up the waitpid monitor thread that is calling this. 990 PacketResult result = SendStopReasonForState (StateType::eStateExited, false); 991 if (result != PacketResult::Success) 992 { 993 if (log) 994 log->Printf ("GDBRemoteCommunicationServer::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ()); 995 } 996 997 // Remove the process from the list of spawned pids. 998 { 999 Mutex::Locker locker (m_spawned_pids_mutex); 1000 if (m_spawned_pids.erase (process->GetID ()) < 1) 1001 { 1002 if (log) 1003 log->Printf ("GDBRemoteCommunicationServer::%s failed to remove PID %" PRIu64 " from the spawned pids list", __FUNCTION__, process->GetID ()); 1004 1005 } 1006 } 1007 1008 // FIXME can't do this yet - since process state propagation is currently 1009 // synchronous, it is running off the NativeProcessProtocol's innards and 1010 // will tear down the NPP while it still has code to execute. 1011 #if 0 1012 // Clear the NativeProcessProtocol pointer. 1013 { 1014 Mutex::Locker locker (m_debugged_process_mutex); 1015 m_debugged_process_sp.reset(); 1016 } 1017 #endif 1018 1019 // Close the pipe to the inferior terminal i/o if we launched it 1020 // and set one up. Otherwise, 'k' and its flush of stdio could 1021 // end up waiting on a thread join that will never end. Consider 1022 // adding a timeout to the connection thread join call so we 1023 // can avoid that scenario altogether. 1024 MaybeCloseInferiorTerminalConnection (); 1025 1026 // We are ready to exit the debug monitor. 1027 m_exit_now = true; 1028 } 1029 1030 void 1031 GDBRemoteCommunicationServer::HandleInferiorState_Stopped (lldb_private::NativeProcessProtocol *process) 1032 { 1033 assert (process && "process cannot be NULL"); 1034 1035 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 1036 if (log) 1037 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__); 1038 1039 // Send the stop reason unless this is the stop after the 1040 // launch or attach. 1041 switch (m_inferior_prev_state) 1042 { 1043 case eStateLaunching: 1044 case eStateAttaching: 1045 // Don't send anything per debugserver behavior. 1046 break; 1047 default: 1048 // In all other cases, send the stop reason. 1049 PacketResult result = SendStopReasonForState (StateType::eStateStopped, false); 1050 if (result != PacketResult::Success) 1051 { 1052 if (log) 1053 log->Printf ("GDBRemoteCommunicationServer::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ()); 1054 } 1055 break; 1056 } 1057 } 1058 1059 void 1060 GDBRemoteCommunicationServer::ProcessStateChanged (lldb_private::NativeProcessProtocol *process, lldb::StateType state) 1061 { 1062 assert (process && "process cannot be NULL"); 1063 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 1064 if (log) 1065 { 1066 log->Printf ("GDBRemoteCommunicationServer::%s called with NativeProcessProtocol pid %" PRIu64 ", state: %s", 1067 __FUNCTION__, 1068 process->GetID (), 1069 StateAsCString (state)); 1070 } 1071 1072 switch (state) 1073 { 1074 case StateType::eStateExited: 1075 HandleInferiorState_Exited (process); 1076 break; 1077 1078 case StateType::eStateStopped: 1079 HandleInferiorState_Stopped (process); 1080 break; 1081 1082 default: 1083 if (log) 1084 { 1085 log->Printf ("GDBRemoteCommunicationServer::%s didn't handle state change for pid %" PRIu64 ", new state: %s", 1086 __FUNCTION__, 1087 process->GetID (), 1088 StateAsCString (state)); 1089 } 1090 break; 1091 } 1092 1093 // Remember the previous state reported to us. 1094 m_inferior_prev_state = state; 1095 } 1096 1097 GDBRemoteCommunication::PacketResult 1098 GDBRemoteCommunicationServer::SendONotification (const char *buffer, uint32_t len) 1099 { 1100 if ((buffer == nullptr) || (len == 0)) 1101 { 1102 // Nothing to send. 1103 return PacketResult::Success; 1104 } 1105 1106 StreamString response; 1107 response.PutChar ('O'); 1108 response.PutBytesAsRawHex8 (buffer, len); 1109 1110 return SendPacketNoLock (response.GetData (), response.GetSize ()); 1111 } 1112 1113 lldb_private::Error 1114 GDBRemoteCommunicationServer::SetSTDIOFileDescriptor (int fd) 1115 { 1116 Error error; 1117 1118 // Set up the Read Thread for reading/handling process I/O 1119 std::unique_ptr<ConnectionFileDescriptor> conn_up (new ConnectionFileDescriptor (fd, true)); 1120 if (!conn_up) 1121 { 1122 error.SetErrorString ("failed to create ConnectionFileDescriptor"); 1123 return error; 1124 } 1125 1126 m_stdio_communication.SetConnection (conn_up.release()); 1127 if (!m_stdio_communication.IsConnected ()) 1128 { 1129 error.SetErrorString ("failed to set connection for inferior I/O communication"); 1130 return error; 1131 } 1132 1133 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this); 1134 m_stdio_communication.StartReadThread(); 1135 1136 return error; 1137 } 1138 1139 void 1140 GDBRemoteCommunicationServer::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len) 1141 { 1142 GDBRemoteCommunicationServer *server = reinterpret_cast<GDBRemoteCommunicationServer*> (baton); 1143 static_cast<void> (server->SendONotification (static_cast<const char *>(src), src_len)); 1144 } 1145 1146 GDBRemoteCommunication::PacketResult 1147 GDBRemoteCommunicationServer::SendUnimplementedResponse (const char *) 1148 { 1149 // TODO: Log the packet we aren't handling... 1150 return SendPacketNoLock ("", 0); 1151 } 1152 1153 1154 GDBRemoteCommunication::PacketResult 1155 GDBRemoteCommunicationServer::SendErrorResponse (uint8_t err) 1156 { 1157 char packet[16]; 1158 int packet_len = ::snprintf (packet, sizeof(packet), "E%2.2x", err); 1159 assert (packet_len < (int)sizeof(packet)); 1160 return SendPacketNoLock (packet, packet_len); 1161 } 1162 1163 GDBRemoteCommunication::PacketResult 1164 GDBRemoteCommunicationServer::SendIllFormedResponse (const StringExtractorGDBRemote &failed_packet, const char *message) 1165 { 1166 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS)); 1167 if (log) 1168 log->Printf ("GDBRemoteCommunicationServer::%s: ILLFORMED: '%s' (%s)", __FUNCTION__, failed_packet.GetStringRef ().c_str (), message ? message : ""); 1169 return SendErrorResponse (0x03); 1170 } 1171 1172 GDBRemoteCommunication::PacketResult 1173 GDBRemoteCommunicationServer::SendOKResponse () 1174 { 1175 return SendPacketNoLock ("OK", 2); 1176 } 1177 1178 bool 1179 GDBRemoteCommunicationServer::HandshakeWithClient(Error *error_ptr) 1180 { 1181 return GetAck() == PacketResult::Success; 1182 } 1183 1184 GDBRemoteCommunication::PacketResult 1185 GDBRemoteCommunicationServer::Handle_qHostInfo (StringExtractorGDBRemote &packet) 1186 { 1187 StreamString response; 1188 1189 // $cputype:16777223;cpusubtype:3;ostype:Darwin;vendor:apple;endian:little;ptrsize:8;#00 1190 1191 ArchSpec host_arch(HostInfo::GetArchitecture()); 1192 const llvm::Triple &host_triple = host_arch.GetTriple(); 1193 response.PutCString("triple:"); 1194 response.PutCString(host_triple.getTriple().c_str()); 1195 response.Printf (";ptrsize:%u;",host_arch.GetAddressByteSize()); 1196 1197 const char* distribution_id = host_arch.GetDistributionId ().AsCString (); 1198 if (distribution_id) 1199 { 1200 response.PutCString("distribution_id:"); 1201 response.PutCStringAsRawHex8(distribution_id); 1202 response.PutCString(";"); 1203 } 1204 1205 // Only send out MachO info when lldb-platform/llgs is running on a MachO host. 1206 #if defined(__APPLE__) 1207 uint32_t cpu = host_arch.GetMachOCPUType(); 1208 uint32_t sub = host_arch.GetMachOCPUSubType(); 1209 if (cpu != LLDB_INVALID_CPUTYPE) 1210 response.Printf ("cputype:%u;", cpu); 1211 if (sub != LLDB_INVALID_CPUTYPE) 1212 response.Printf ("cpusubtype:%u;", sub); 1213 1214 if (cpu == ArchSpec::kCore_arm_any) 1215 response.Printf("watchpoint_exceptions_received:before;"); // On armv7 we use "synchronous" watchpoints which means the exception is delivered before the instruction executes. 1216 else 1217 response.Printf("watchpoint_exceptions_received:after;"); 1218 #else 1219 response.Printf("watchpoint_exceptions_received:after;"); 1220 #endif 1221 1222 switch (lldb::endian::InlHostByteOrder()) 1223 { 1224 case eByteOrderBig: response.PutCString ("endian:big;"); break; 1225 case eByteOrderLittle: response.PutCString ("endian:little;"); break; 1226 case eByteOrderPDP: response.PutCString ("endian:pdp;"); break; 1227 default: response.PutCString ("endian:unknown;"); break; 1228 } 1229 1230 uint32_t major = UINT32_MAX; 1231 uint32_t minor = UINT32_MAX; 1232 uint32_t update = UINT32_MAX; 1233 if (HostInfo::GetOSVersion(major, minor, update)) 1234 { 1235 if (major != UINT32_MAX) 1236 { 1237 response.Printf("os_version:%u", major); 1238 if (minor != UINT32_MAX) 1239 { 1240 response.Printf(".%u", minor); 1241 if (update != UINT32_MAX) 1242 response.Printf(".%u", update); 1243 } 1244 response.PutChar(';'); 1245 } 1246 } 1247 1248 std::string s; 1249 #if !defined(__linux__) 1250 if (HostInfo::GetOSBuildString(s)) 1251 { 1252 response.PutCString ("os_build:"); 1253 response.PutCStringAsRawHex8(s.c_str()); 1254 response.PutChar(';'); 1255 } 1256 if (HostInfo::GetOSKernelDescription(s)) 1257 { 1258 response.PutCString ("os_kernel:"); 1259 response.PutCStringAsRawHex8(s.c_str()); 1260 response.PutChar(';'); 1261 } 1262 #endif 1263 1264 #if defined(__APPLE__) 1265 1266 #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__) 1267 // For iOS devices, we are connected through a USB Mux so we never pretend 1268 // to actually have a hostname as far as the remote lldb that is connecting 1269 // to this lldb-platform is concerned 1270 response.PutCString ("hostname:"); 1271 response.PutCStringAsRawHex8("127.0.0.1"); 1272 response.PutChar(';'); 1273 #else // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__) 1274 if (HostInfo::GetHostname(s)) 1275 { 1276 response.PutCString ("hostname:"); 1277 response.PutCStringAsRawHex8(s.c_str()); 1278 response.PutChar(';'); 1279 } 1280 #endif // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__) 1281 1282 #else // #if defined(__APPLE__) 1283 if (HostInfo::GetHostname(s)) 1284 { 1285 response.PutCString ("hostname:"); 1286 response.PutCStringAsRawHex8(s.c_str()); 1287 response.PutChar(';'); 1288 } 1289 #endif // #if defined(__APPLE__) 1290 1291 return SendPacketNoLock (response.GetData(), response.GetSize()); 1292 } 1293 1294 static void 1295 CreateProcessInfoResponse (const ProcessInstanceInfo &proc_info, StreamString &response) 1296 { 1297 response.Printf ("pid:%" PRIu64 ";ppid:%" PRIu64 ";uid:%i;gid:%i;euid:%i;egid:%i;", 1298 proc_info.GetProcessID(), 1299 proc_info.GetParentProcessID(), 1300 proc_info.GetUserID(), 1301 proc_info.GetGroupID(), 1302 proc_info.GetEffectiveUserID(), 1303 proc_info.GetEffectiveGroupID()); 1304 response.PutCString ("name:"); 1305 response.PutCStringAsRawHex8(proc_info.GetName()); 1306 response.PutChar(';'); 1307 const ArchSpec &proc_arch = proc_info.GetArchitecture(); 1308 if (proc_arch.IsValid()) 1309 { 1310 const llvm::Triple &proc_triple = proc_arch.GetTriple(); 1311 response.PutCString("triple:"); 1312 response.PutCString(proc_triple.getTriple().c_str()); 1313 response.PutChar(';'); 1314 } 1315 } 1316 1317 static void 1318 CreateProcessInfoResponse_DebugServerStyle (const ProcessInstanceInfo &proc_info, StreamString &response) 1319 { 1320 response.Printf ("pid:%" PRIx64 ";parent-pid:%" PRIx64 ";real-uid:%x;real-gid:%x;effective-uid:%x;effective-gid:%x;", 1321 proc_info.GetProcessID(), 1322 proc_info.GetParentProcessID(), 1323 proc_info.GetUserID(), 1324 proc_info.GetGroupID(), 1325 proc_info.GetEffectiveUserID(), 1326 proc_info.GetEffectiveGroupID()); 1327 1328 const ArchSpec &proc_arch = proc_info.GetArchitecture(); 1329 if (proc_arch.IsValid()) 1330 { 1331 const uint32_t cpu_type = proc_arch.GetMachOCPUType(); 1332 if (cpu_type != 0) 1333 response.Printf ("cputype:%" PRIx32 ";", cpu_type); 1334 1335 const uint32_t cpu_subtype = proc_arch.GetMachOCPUSubType(); 1336 if (cpu_subtype != 0) 1337 response.Printf ("cpusubtype:%" PRIx32 ";", cpu_subtype); 1338 1339 const llvm::Triple &proc_triple = proc_arch.GetTriple(); 1340 const std::string vendor = proc_triple.getVendorName (); 1341 if (!vendor.empty ()) 1342 response.Printf ("vendor:%s;", vendor.c_str ()); 1343 1344 std::string ostype = proc_triple.getOSName (); 1345 // Adjust so ostype reports ios for Apple/ARM and Apple/ARM64. 1346 if (proc_triple.getVendor () == llvm::Triple::Apple) 1347 { 1348 switch (proc_triple.getArch ()) 1349 { 1350 case llvm::Triple::arm: 1351 case llvm::Triple::aarch64: 1352 ostype = "ios"; 1353 break; 1354 default: 1355 // No change. 1356 break; 1357 } 1358 } 1359 response.Printf ("ostype:%s;", ostype.c_str ()); 1360 1361 1362 switch (proc_arch.GetByteOrder ()) 1363 { 1364 case lldb::eByteOrderLittle: response.PutCString ("endian:little;"); break; 1365 case lldb::eByteOrderBig: response.PutCString ("endian:big;"); break; 1366 case lldb::eByteOrderPDP: response.PutCString ("endian:pdp;"); break; 1367 default: 1368 // Nothing. 1369 break; 1370 } 1371 1372 if (proc_triple.isArch64Bit ()) 1373 response.PutCString ("ptrsize:8;"); 1374 else if (proc_triple.isArch32Bit ()) 1375 response.PutCString ("ptrsize:4;"); 1376 else if (proc_triple.isArch16Bit ()) 1377 response.PutCString ("ptrsize:2;"); 1378 } 1379 1380 } 1381 1382 1383 GDBRemoteCommunication::PacketResult 1384 GDBRemoteCommunicationServer::Handle_qProcessInfo (StringExtractorGDBRemote &packet) 1385 { 1386 // Only the gdb server handles this. 1387 if (!IsGdbServer ()) 1388 return SendUnimplementedResponse (packet.GetStringRef ().c_str ()); 1389 1390 // Fail if we don't have a current process. 1391 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 1392 return SendErrorResponse (68); 1393 1394 ProcessInstanceInfo proc_info; 1395 if (Host::GetProcessInfo (m_debugged_process_sp->GetID (), proc_info)) 1396 { 1397 StreamString response; 1398 CreateProcessInfoResponse_DebugServerStyle(proc_info, response); 1399 return SendPacketNoLock (response.GetData (), response.GetSize ()); 1400 } 1401 1402 return SendErrorResponse (1); 1403 } 1404 1405 GDBRemoteCommunication::PacketResult 1406 GDBRemoteCommunicationServer::Handle_qProcessInfoPID (StringExtractorGDBRemote &packet) 1407 { 1408 // Packet format: "qProcessInfoPID:%i" where %i is the pid 1409 packet.SetFilePos(::strlen ("qProcessInfoPID:")); 1410 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID); 1411 if (pid != LLDB_INVALID_PROCESS_ID) 1412 { 1413 ProcessInstanceInfo proc_info; 1414 if (Host::GetProcessInfo(pid, proc_info)) 1415 { 1416 StreamString response; 1417 CreateProcessInfoResponse (proc_info, response); 1418 return SendPacketNoLock (response.GetData(), response.GetSize()); 1419 } 1420 } 1421 return SendErrorResponse (1); 1422 } 1423 1424 GDBRemoteCommunication::PacketResult 1425 GDBRemoteCommunicationServer::Handle_qfProcessInfo (StringExtractorGDBRemote &packet) 1426 { 1427 m_proc_infos_index = 0; 1428 m_proc_infos.Clear(); 1429 1430 ProcessInstanceInfoMatch match_info; 1431 packet.SetFilePos(::strlen ("qfProcessInfo")); 1432 if (packet.GetChar() == ':') 1433 { 1434 1435 std::string key; 1436 std::string value; 1437 while (packet.GetNameColonValue(key, value)) 1438 { 1439 bool success = true; 1440 if (key.compare("name") == 0) 1441 { 1442 StringExtractor extractor; 1443 extractor.GetStringRef().swap(value); 1444 extractor.GetHexByteString (value); 1445 match_info.GetProcessInfo().GetExecutableFile().SetFile(value.c_str(), false); 1446 } 1447 else if (key.compare("name_match") == 0) 1448 { 1449 if (value.compare("equals") == 0) 1450 { 1451 match_info.SetNameMatchType (eNameMatchEquals); 1452 } 1453 else if (value.compare("starts_with") == 0) 1454 { 1455 match_info.SetNameMatchType (eNameMatchStartsWith); 1456 } 1457 else if (value.compare("ends_with") == 0) 1458 { 1459 match_info.SetNameMatchType (eNameMatchEndsWith); 1460 } 1461 else if (value.compare("contains") == 0) 1462 { 1463 match_info.SetNameMatchType (eNameMatchContains); 1464 } 1465 else if (value.compare("regex") == 0) 1466 { 1467 match_info.SetNameMatchType (eNameMatchRegularExpression); 1468 } 1469 else 1470 { 1471 success = false; 1472 } 1473 } 1474 else if (key.compare("pid") == 0) 1475 { 1476 match_info.GetProcessInfo().SetProcessID (Args::StringToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0, &success)); 1477 } 1478 else if (key.compare("parent_pid") == 0) 1479 { 1480 match_info.GetProcessInfo().SetParentProcessID (Args::StringToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0, &success)); 1481 } 1482 else if (key.compare("uid") == 0) 1483 { 1484 match_info.GetProcessInfo().SetUserID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success)); 1485 } 1486 else if (key.compare("gid") == 0) 1487 { 1488 match_info.GetProcessInfo().SetGroupID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success)); 1489 } 1490 else if (key.compare("euid") == 0) 1491 { 1492 match_info.GetProcessInfo().SetEffectiveUserID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success)); 1493 } 1494 else if (key.compare("egid") == 0) 1495 { 1496 match_info.GetProcessInfo().SetEffectiveGroupID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success)); 1497 } 1498 else if (key.compare("all_users") == 0) 1499 { 1500 match_info.SetMatchAllUsers(Args::StringToBoolean(value.c_str(), false, &success)); 1501 } 1502 else if (key.compare("triple") == 0) 1503 { 1504 match_info.GetProcessInfo().GetArchitecture().SetTriple (value.c_str(), NULL); 1505 } 1506 else 1507 { 1508 success = false; 1509 } 1510 1511 if (!success) 1512 return SendErrorResponse (2); 1513 } 1514 } 1515 1516 if (Host::FindProcesses (match_info, m_proc_infos)) 1517 { 1518 // We found something, return the first item by calling the get 1519 // subsequent process info packet handler... 1520 return Handle_qsProcessInfo (packet); 1521 } 1522 return SendErrorResponse (3); 1523 } 1524 1525 GDBRemoteCommunication::PacketResult 1526 GDBRemoteCommunicationServer::Handle_qsProcessInfo (StringExtractorGDBRemote &packet) 1527 { 1528 if (m_proc_infos_index < m_proc_infos.GetSize()) 1529 { 1530 StreamString response; 1531 CreateProcessInfoResponse (m_proc_infos.GetProcessInfoAtIndex(m_proc_infos_index), response); 1532 ++m_proc_infos_index; 1533 return SendPacketNoLock (response.GetData(), response.GetSize()); 1534 } 1535 return SendErrorResponse (4); 1536 } 1537 1538 GDBRemoteCommunication::PacketResult 1539 GDBRemoteCommunicationServer::Handle_qUserName (StringExtractorGDBRemote &packet) 1540 { 1541 #if !defined(LLDB_DISABLE_POSIX) 1542 // Packet format: "qUserName:%i" where %i is the uid 1543 packet.SetFilePos(::strlen ("qUserName:")); 1544 uint32_t uid = packet.GetU32 (UINT32_MAX); 1545 if (uid != UINT32_MAX) 1546 { 1547 std::string name; 1548 if (HostInfo::LookupUserName(uid, name)) 1549 { 1550 StreamString response; 1551 response.PutCStringAsRawHex8 (name.c_str()); 1552 return SendPacketNoLock (response.GetData(), response.GetSize()); 1553 } 1554 } 1555 #endif 1556 return SendErrorResponse (5); 1557 1558 } 1559 1560 GDBRemoteCommunication::PacketResult 1561 GDBRemoteCommunicationServer::Handle_qGroupName (StringExtractorGDBRemote &packet) 1562 { 1563 #if !defined(LLDB_DISABLE_POSIX) 1564 // Packet format: "qGroupName:%i" where %i is the gid 1565 packet.SetFilePos(::strlen ("qGroupName:")); 1566 uint32_t gid = packet.GetU32 (UINT32_MAX); 1567 if (gid != UINT32_MAX) 1568 { 1569 std::string name; 1570 if (HostInfo::LookupGroupName(gid, name)) 1571 { 1572 StreamString response; 1573 response.PutCStringAsRawHex8 (name.c_str()); 1574 return SendPacketNoLock (response.GetData(), response.GetSize()); 1575 } 1576 } 1577 #endif 1578 return SendErrorResponse (6); 1579 } 1580 1581 GDBRemoteCommunication::PacketResult 1582 GDBRemoteCommunicationServer::Handle_qSpeedTest (StringExtractorGDBRemote &packet) 1583 { 1584 packet.SetFilePos(::strlen ("qSpeedTest:")); 1585 1586 std::string key; 1587 std::string value; 1588 bool success = packet.GetNameColonValue(key, value); 1589 if (success && key.compare("response_size") == 0) 1590 { 1591 uint32_t response_size = Args::StringToUInt32(value.c_str(), 0, 0, &success); 1592 if (success) 1593 { 1594 if (response_size == 0) 1595 return SendOKResponse(); 1596 StreamString response; 1597 uint32_t bytes_left = response_size; 1598 response.PutCString("data:"); 1599 while (bytes_left > 0) 1600 { 1601 if (bytes_left >= 26) 1602 { 1603 response.PutCString("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); 1604 bytes_left -= 26; 1605 } 1606 else 1607 { 1608 response.Printf ("%*.*s;", bytes_left, bytes_left, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); 1609 bytes_left = 0; 1610 } 1611 } 1612 return SendPacketNoLock (response.GetData(), response.GetSize()); 1613 } 1614 } 1615 return SendErrorResponse (7); 1616 } 1617 1618 // 1619 //static bool 1620 //WaitForProcessToSIGSTOP (const lldb::pid_t pid, const int timeout_in_seconds) 1621 //{ 1622 // const int time_delta_usecs = 100000; 1623 // const int num_retries = timeout_in_seconds/time_delta_usecs; 1624 // for (int i=0; i<num_retries; i++) 1625 // { 1626 // struct proc_bsdinfo bsd_info; 1627 // int error = ::proc_pidinfo (pid, PROC_PIDTBSDINFO, 1628 // (uint64_t) 0, 1629 // &bsd_info, 1630 // PROC_PIDTBSDINFO_SIZE); 1631 // 1632 // switch (error) 1633 // { 1634 // case EINVAL: 1635 // case ENOTSUP: 1636 // case ESRCH: 1637 // case EPERM: 1638 // return false; 1639 // 1640 // default: 1641 // break; 1642 // 1643 // case 0: 1644 // if (bsd_info.pbi_status == SSTOP) 1645 // return true; 1646 // } 1647 // ::usleep (time_delta_usecs); 1648 // } 1649 // return false; 1650 //} 1651 1652 GDBRemoteCommunication::PacketResult 1653 GDBRemoteCommunicationServer::Handle_A (StringExtractorGDBRemote &packet) 1654 { 1655 // The 'A' packet is the most over designed packet ever here with 1656 // redundant argument indexes, redundant argument lengths and needed hex 1657 // encoded argument string values. Really all that is needed is a comma 1658 // separated hex encoded argument value list, but we will stay true to the 1659 // documented version of the 'A' packet here... 1660 1661 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 1662 int actual_arg_index = 0; 1663 1664 packet.SetFilePos(1); // Skip the 'A' 1665 bool success = true; 1666 while (success && packet.GetBytesLeft() > 0) 1667 { 1668 // Decode the decimal argument string length. This length is the 1669 // number of hex nibbles in the argument string value. 1670 const uint32_t arg_len = packet.GetU32(UINT32_MAX); 1671 if (arg_len == UINT32_MAX) 1672 success = false; 1673 else 1674 { 1675 // Make sure the argument hex string length is followed by a comma 1676 if (packet.GetChar() != ',') 1677 success = false; 1678 else 1679 { 1680 // Decode the argument index. We ignore this really because 1681 // who would really send down the arguments in a random order??? 1682 const uint32_t arg_idx = packet.GetU32(UINT32_MAX); 1683 if (arg_idx == UINT32_MAX) 1684 success = false; 1685 else 1686 { 1687 // Make sure the argument index is followed by a comma 1688 if (packet.GetChar() != ',') 1689 success = false; 1690 else 1691 { 1692 // Decode the argument string value from hex bytes 1693 // back into a UTF8 string and make sure the length 1694 // matches the one supplied in the packet 1695 std::string arg; 1696 if (packet.GetHexByteStringFixedLength(arg, arg_len) != (arg_len / 2)) 1697 success = false; 1698 else 1699 { 1700 // If there are any bytes left 1701 if (packet.GetBytesLeft()) 1702 { 1703 if (packet.GetChar() != ',') 1704 success = false; 1705 } 1706 1707 if (success) 1708 { 1709 if (arg_idx == 0) 1710 m_process_launch_info.GetExecutableFile().SetFile(arg.c_str(), false); 1711 m_process_launch_info.GetArguments().AppendArgument(arg.c_str()); 1712 if (log) 1713 log->Printf ("GDBRemoteCommunicationServer::%s added arg %d: \"%s\"", __FUNCTION__, actual_arg_index, arg.c_str ()); 1714 ++actual_arg_index; 1715 } 1716 } 1717 } 1718 } 1719 } 1720 } 1721 } 1722 1723 if (success) 1724 { 1725 m_process_launch_error = LaunchProcess (); 1726 if (m_process_launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) 1727 { 1728 return SendOKResponse (); 1729 } 1730 else 1731 { 1732 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 1733 if (log) 1734 log->Printf("GDBRemoteCommunicationServer::%s failed to launch exe: %s", 1735 __FUNCTION__, 1736 m_process_launch_error.AsCString()); 1737 1738 } 1739 } 1740 return SendErrorResponse (8); 1741 } 1742 1743 GDBRemoteCommunication::PacketResult 1744 GDBRemoteCommunicationServer::Handle_qC (StringExtractorGDBRemote &packet) 1745 { 1746 StreamString response; 1747 1748 if (IsGdbServer ()) 1749 { 1750 // Fail if we don't have a current process. 1751 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 1752 return SendErrorResponse (68); 1753 1754 // Make sure we set the current thread so g and p packets return 1755 // the data the gdb will expect. 1756 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID (); 1757 SetCurrentThreadID (tid); 1758 1759 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread (); 1760 if (!thread_sp) 1761 return SendErrorResponse (69); 1762 1763 response.Printf ("QC%" PRIx64, thread_sp->GetID ()); 1764 } 1765 else 1766 { 1767 // NOTE: lldb should now be using qProcessInfo for process IDs. This path here 1768 // should not be used. It is reporting process id instead of thread id. The 1769 // correct answer doesn't seem to make much sense for lldb-platform. 1770 // CONSIDER: flip to "unsupported". 1771 lldb::pid_t pid = m_process_launch_info.GetProcessID(); 1772 response.Printf("QC%" PRIx64, pid); 1773 1774 // this should always be platform here 1775 assert (m_is_platform && "this code path should only be traversed for lldb-platform"); 1776 1777 if (m_is_platform) 1778 { 1779 // If we launch a process and this GDB server is acting as a platform, 1780 // then we need to clear the process launch state so we can start 1781 // launching another process. In order to launch a process a bunch or 1782 // packets need to be sent: environment packets, working directory, 1783 // disable ASLR, and many more settings. When we launch a process we 1784 // then need to know when to clear this information. Currently we are 1785 // selecting the 'qC' packet as that packet which seems to make the most 1786 // sense. 1787 if (pid != LLDB_INVALID_PROCESS_ID) 1788 { 1789 m_process_launch_info.Clear(); 1790 } 1791 } 1792 } 1793 return SendPacketNoLock (response.GetData(), response.GetSize()); 1794 } 1795 1796 bool 1797 GDBRemoteCommunicationServer::DebugserverProcessReaped (lldb::pid_t pid) 1798 { 1799 Mutex::Locker locker (m_spawned_pids_mutex); 1800 FreePortForProcess(pid); 1801 return m_spawned_pids.erase(pid) > 0; 1802 } 1803 bool 1804 GDBRemoteCommunicationServer::ReapDebugserverProcess (void *callback_baton, 1805 lldb::pid_t pid, 1806 bool exited, 1807 int signal, // Zero for no signal 1808 int status) // Exit value of process if signal is zero 1809 { 1810 GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton; 1811 server->DebugserverProcessReaped (pid); 1812 return true; 1813 } 1814 1815 bool 1816 GDBRemoteCommunicationServer::DebuggedProcessReaped (lldb::pid_t pid) 1817 { 1818 // reap a process that we were debugging (but not debugserver) 1819 Mutex::Locker locker (m_spawned_pids_mutex); 1820 return m_spawned_pids.erase(pid) > 0; 1821 } 1822 1823 bool 1824 GDBRemoteCommunicationServer::ReapDebuggedProcess (void *callback_baton, 1825 lldb::pid_t pid, 1826 bool exited, 1827 int signal, // Zero for no signal 1828 int status) // Exit value of process if signal is zero 1829 { 1830 GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton; 1831 server->DebuggedProcessReaped (pid); 1832 return true; 1833 } 1834 1835 GDBRemoteCommunication::PacketResult 1836 GDBRemoteCommunicationServer::Handle_qLaunchGDBServer (StringExtractorGDBRemote &packet) 1837 { 1838 #ifdef _WIN32 1839 return SendErrorResponse(9); 1840 #else 1841 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM)); 1842 1843 // Spawn a local debugserver as a platform so we can then attach or launch 1844 // a process... 1845 1846 if (m_is_platform) 1847 { 1848 if (log) 1849 log->Printf ("GDBRemoteCommunicationServer::%s() called", __FUNCTION__); 1850 1851 // Sleep and wait a bit for debugserver to start to listen... 1852 ConnectionFileDescriptor file_conn; 1853 std::string hostname; 1854 // TODO: /tmp/ should not be hardcoded. User might want to override /tmp 1855 // with the TMPDIR environment variable 1856 packet.SetFilePos(::strlen ("qLaunchGDBServer;")); 1857 std::string name; 1858 std::string value; 1859 uint16_t port = UINT16_MAX; 1860 while (packet.GetNameColonValue(name, value)) 1861 { 1862 if (name.compare ("host") == 0) 1863 hostname.swap(value); 1864 else if (name.compare ("port") == 0) 1865 port = Args::StringToUInt32(value.c_str(), 0, 0); 1866 } 1867 if (port == UINT16_MAX) 1868 port = GetNextAvailablePort(); 1869 1870 // Spawn a new thread to accept the port that gets bound after 1871 // binding to port 0 (zero). 1872 1873 // Spawn a debugserver and try to get the port it listens to. 1874 ProcessLaunchInfo debugserver_launch_info; 1875 if (hostname.empty()) 1876 hostname = "127.0.0.1"; 1877 if (log) 1878 log->Printf("Launching debugserver with: %s:%u...\n", hostname.c_str(), port); 1879 1880 debugserver_launch_info.SetMonitorProcessCallback(ReapDebugserverProcess, this, false); 1881 1882 Error error = StartDebugserverProcess (hostname.empty() ? NULL : hostname.c_str(), 1883 port, 1884 debugserver_launch_info, 1885 port); 1886 1887 lldb::pid_t debugserver_pid = debugserver_launch_info.GetProcessID(); 1888 1889 1890 if (debugserver_pid != LLDB_INVALID_PROCESS_ID) 1891 { 1892 Mutex::Locker locker (m_spawned_pids_mutex); 1893 m_spawned_pids.insert(debugserver_pid); 1894 if (port > 0) 1895 AssociatePortWithProcess(port, debugserver_pid); 1896 } 1897 else 1898 { 1899 if (port > 0) 1900 FreePort (port); 1901 } 1902 1903 if (error.Success()) 1904 { 1905 if (log) 1906 log->Printf ("GDBRemoteCommunicationServer::%s() debugserver launched successfully as pid %" PRIu64, __FUNCTION__, debugserver_pid); 1907 1908 char response[256]; 1909 const int response_len = ::snprintf (response, sizeof(response), "pid:%" PRIu64 ";port:%u;", debugserver_pid, port + m_port_offset); 1910 assert (response_len < (int)sizeof(response)); 1911 PacketResult packet_result = SendPacketNoLock (response, response_len); 1912 1913 if (packet_result != PacketResult::Success) 1914 { 1915 if (debugserver_pid != LLDB_INVALID_PROCESS_ID) 1916 ::kill (debugserver_pid, SIGINT); 1917 } 1918 return packet_result; 1919 } 1920 else 1921 { 1922 if (log) 1923 log->Printf ("GDBRemoteCommunicationServer::%s() debugserver launch failed: %s", __FUNCTION__, error.AsCString ()); 1924 } 1925 } 1926 return SendErrorResponse (9); 1927 #endif 1928 } 1929 1930 bool 1931 GDBRemoteCommunicationServer::KillSpawnedProcess (lldb::pid_t pid) 1932 { 1933 // make sure we know about this process 1934 { 1935 Mutex::Locker locker (m_spawned_pids_mutex); 1936 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) 1937 return false; 1938 } 1939 1940 // first try a SIGTERM (standard kill) 1941 Host::Kill (pid, SIGTERM); 1942 1943 // check if that worked 1944 for (size_t i=0; i<10; ++i) 1945 { 1946 { 1947 Mutex::Locker locker (m_spawned_pids_mutex); 1948 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) 1949 { 1950 // it is now killed 1951 return true; 1952 } 1953 } 1954 usleep (10000); 1955 } 1956 1957 // check one more time after the final usleep 1958 { 1959 Mutex::Locker locker (m_spawned_pids_mutex); 1960 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) 1961 return true; 1962 } 1963 1964 // the launched process still lives. Now try killing it again, 1965 // this time with an unblockable signal. 1966 Host::Kill (pid, SIGKILL); 1967 1968 for (size_t i=0; i<10; ++i) 1969 { 1970 { 1971 Mutex::Locker locker (m_spawned_pids_mutex); 1972 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) 1973 { 1974 // it is now killed 1975 return true; 1976 } 1977 } 1978 usleep (10000); 1979 } 1980 1981 // check one more time after the final usleep 1982 // Scope for locker 1983 { 1984 Mutex::Locker locker (m_spawned_pids_mutex); 1985 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) 1986 return true; 1987 } 1988 1989 // no luck - the process still lives 1990 return false; 1991 } 1992 1993 GDBRemoteCommunication::PacketResult 1994 GDBRemoteCommunicationServer::Handle_qKillSpawnedProcess (StringExtractorGDBRemote &packet) 1995 { 1996 packet.SetFilePos(::strlen ("qKillSpawnedProcess:")); 1997 1998 lldb::pid_t pid = packet.GetU64(LLDB_INVALID_PROCESS_ID); 1999 2000 // verify that we know anything about this pid. 2001 // Scope for locker 2002 { 2003 Mutex::Locker locker (m_spawned_pids_mutex); 2004 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) 2005 { 2006 // not a pid we know about 2007 return SendErrorResponse (10); 2008 } 2009 } 2010 2011 // go ahead and attempt to kill the spawned process 2012 if (KillSpawnedProcess (pid)) 2013 return SendOKResponse (); 2014 else 2015 return SendErrorResponse (11); 2016 } 2017 2018 GDBRemoteCommunication::PacketResult 2019 GDBRemoteCommunicationServer::Handle_k (StringExtractorGDBRemote &packet) 2020 { 2021 // ignore for now if we're lldb_platform 2022 if (m_is_platform) 2023 return SendUnimplementedResponse (packet.GetStringRef().c_str()); 2024 2025 // shutdown all spawned processes 2026 std::set<lldb::pid_t> spawned_pids_copy; 2027 2028 // copy pids 2029 { 2030 Mutex::Locker locker (m_spawned_pids_mutex); 2031 spawned_pids_copy.insert (m_spawned_pids.begin (), m_spawned_pids.end ()); 2032 } 2033 2034 // nuke the spawned processes 2035 for (auto it = spawned_pids_copy.begin (); it != spawned_pids_copy.end (); ++it) 2036 { 2037 lldb::pid_t spawned_pid = *it; 2038 if (!KillSpawnedProcess (spawned_pid)) 2039 { 2040 fprintf (stderr, "%s: failed to kill spawned pid %" PRIu64 ", ignoring.\n", __FUNCTION__, spawned_pid); 2041 } 2042 } 2043 2044 FlushInferiorOutput (); 2045 2046 // No OK response for kill packet. 2047 // return SendOKResponse (); 2048 return PacketResult::Success; 2049 } 2050 2051 GDBRemoteCommunication::PacketResult 2052 GDBRemoteCommunicationServer::Handle_qLaunchSuccess (StringExtractorGDBRemote &packet) 2053 { 2054 if (m_process_launch_error.Success()) 2055 return SendOKResponse(); 2056 StreamString response; 2057 response.PutChar('E'); 2058 response.PutCString(m_process_launch_error.AsCString("<unknown error>")); 2059 return SendPacketNoLock (response.GetData(), response.GetSize()); 2060 } 2061 2062 GDBRemoteCommunication::PacketResult 2063 GDBRemoteCommunicationServer::Handle_QEnvironment (StringExtractorGDBRemote &packet) 2064 { 2065 packet.SetFilePos(::strlen ("QEnvironment:")); 2066 const uint32_t bytes_left = packet.GetBytesLeft(); 2067 if (bytes_left > 0) 2068 { 2069 m_process_launch_info.GetEnvironmentEntries ().AppendArgument (packet.Peek()); 2070 return SendOKResponse (); 2071 } 2072 return SendErrorResponse (12); 2073 } 2074 2075 GDBRemoteCommunication::PacketResult 2076 GDBRemoteCommunicationServer::Handle_QLaunchArch (StringExtractorGDBRemote &packet) 2077 { 2078 packet.SetFilePos(::strlen ("QLaunchArch:")); 2079 const uint32_t bytes_left = packet.GetBytesLeft(); 2080 if (bytes_left > 0) 2081 { 2082 const char* arch_triple = packet.Peek(); 2083 ArchSpec arch_spec(arch_triple,NULL); 2084 m_process_launch_info.SetArchitecture(arch_spec); 2085 return SendOKResponse(); 2086 } 2087 return SendErrorResponse(13); 2088 } 2089 2090 GDBRemoteCommunication::PacketResult 2091 GDBRemoteCommunicationServer::Handle_QSetDisableASLR (StringExtractorGDBRemote &packet) 2092 { 2093 packet.SetFilePos(::strlen ("QSetDisableASLR:")); 2094 if (packet.GetU32(0)) 2095 m_process_launch_info.GetFlags().Set (eLaunchFlagDisableASLR); 2096 else 2097 m_process_launch_info.GetFlags().Clear (eLaunchFlagDisableASLR); 2098 return SendOKResponse (); 2099 } 2100 2101 GDBRemoteCommunication::PacketResult 2102 GDBRemoteCommunicationServer::Handle_QSetWorkingDir (StringExtractorGDBRemote &packet) 2103 { 2104 packet.SetFilePos(::strlen ("QSetWorkingDir:")); 2105 std::string path; 2106 packet.GetHexByteString(path); 2107 if (m_is_platform) 2108 { 2109 #ifdef _WIN32 2110 // Not implemented on Windows 2111 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_QSetWorkingDir unimplemented"); 2112 #else 2113 // If this packet is sent to a platform, then change the current working directory 2114 if (::chdir(path.c_str()) != 0) 2115 return SendErrorResponse(errno); 2116 #endif 2117 } 2118 else 2119 { 2120 m_process_launch_info.SwapWorkingDirectory (path); 2121 } 2122 return SendOKResponse (); 2123 } 2124 2125 GDBRemoteCommunication::PacketResult 2126 GDBRemoteCommunicationServer::Handle_qGetWorkingDir (StringExtractorGDBRemote &packet) 2127 { 2128 StreamString response; 2129 2130 if (m_is_platform) 2131 { 2132 // If this packet is sent to a platform, then change the current working directory 2133 char cwd[PATH_MAX]; 2134 if (getcwd(cwd, sizeof(cwd)) == NULL) 2135 { 2136 return SendErrorResponse(errno); 2137 } 2138 else 2139 { 2140 response.PutBytesAsRawHex8(cwd, strlen(cwd)); 2141 return SendPacketNoLock(response.GetData(), response.GetSize()); 2142 } 2143 } 2144 else 2145 { 2146 const char *working_dir = m_process_launch_info.GetWorkingDirectory(); 2147 if (working_dir && working_dir[0]) 2148 { 2149 response.PutBytesAsRawHex8(working_dir, strlen(working_dir)); 2150 return SendPacketNoLock(response.GetData(), response.GetSize()); 2151 } 2152 else 2153 { 2154 return SendErrorResponse(14); 2155 } 2156 } 2157 } 2158 2159 GDBRemoteCommunication::PacketResult 2160 GDBRemoteCommunicationServer::Handle_QSetSTDIN (StringExtractorGDBRemote &packet) 2161 { 2162 packet.SetFilePos(::strlen ("QSetSTDIN:")); 2163 FileAction file_action; 2164 std::string path; 2165 packet.GetHexByteString(path); 2166 const bool read = false; 2167 const bool write = true; 2168 if (file_action.Open(STDIN_FILENO, path.c_str(), read, write)) 2169 { 2170 m_process_launch_info.AppendFileAction(file_action); 2171 return SendOKResponse (); 2172 } 2173 return SendErrorResponse (15); 2174 } 2175 2176 GDBRemoteCommunication::PacketResult 2177 GDBRemoteCommunicationServer::Handle_QSetSTDOUT (StringExtractorGDBRemote &packet) 2178 { 2179 packet.SetFilePos(::strlen ("QSetSTDOUT:")); 2180 FileAction file_action; 2181 std::string path; 2182 packet.GetHexByteString(path); 2183 const bool read = true; 2184 const bool write = false; 2185 if (file_action.Open(STDOUT_FILENO, path.c_str(), read, write)) 2186 { 2187 m_process_launch_info.AppendFileAction(file_action); 2188 return SendOKResponse (); 2189 } 2190 return SendErrorResponse (16); 2191 } 2192 2193 GDBRemoteCommunication::PacketResult 2194 GDBRemoteCommunicationServer::Handle_QSetSTDERR (StringExtractorGDBRemote &packet) 2195 { 2196 packet.SetFilePos(::strlen ("QSetSTDERR:")); 2197 FileAction file_action; 2198 std::string path; 2199 packet.GetHexByteString(path); 2200 const bool read = true; 2201 const bool write = false; 2202 if (file_action.Open(STDERR_FILENO, path.c_str(), read, write)) 2203 { 2204 m_process_launch_info.AppendFileAction(file_action); 2205 return SendOKResponse (); 2206 } 2207 return SendErrorResponse (17); 2208 } 2209 2210 GDBRemoteCommunication::PacketResult 2211 GDBRemoteCommunicationServer::Handle_C (StringExtractorGDBRemote &packet) 2212 { 2213 if (!IsGdbServer ()) 2214 return SendUnimplementedResponse (packet.GetStringRef().c_str()); 2215 2216 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD)); 2217 if (log) 2218 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__); 2219 2220 // Ensure we have a native process. 2221 if (!m_debugged_process_sp) 2222 { 2223 if (log) 2224 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__); 2225 return SendErrorResponse (0x36); 2226 } 2227 2228 // Pull out the signal number. 2229 packet.SetFilePos (::strlen ("C")); 2230 if (packet.GetBytesLeft () < 1) 2231 { 2232 // Shouldn't be using a C without a signal. 2233 return SendIllFormedResponse (packet, "C packet specified without signal."); 2234 } 2235 const uint32_t signo = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ()); 2236 if (signo == std::numeric_limits<uint32_t>::max ()) 2237 return SendIllFormedResponse (packet, "failed to parse signal number"); 2238 2239 // Handle optional continue address. 2240 if (packet.GetBytesLeft () > 0) 2241 { 2242 // FIXME add continue at address support for $C{signo}[;{continue-address}]. 2243 if (*packet.Peek () == ';') 2244 return SendUnimplementedResponse (packet.GetStringRef().c_str()); 2245 else 2246 return SendIllFormedResponse (packet, "unexpected content after $C{signal-number}"); 2247 } 2248 2249 lldb_private::ResumeActionList resume_actions (StateType::eStateRunning, 0); 2250 Error error; 2251 2252 // We have two branches: what to do if a continue thread is specified (in which case we target 2253 // sending the signal to that thread), or when we don't have a continue thread set (in which 2254 // case we send a signal to the process). 2255 2256 // TODO discuss with Greg Clayton, make sure this makes sense. 2257 2258 lldb::tid_t signal_tid = GetContinueThreadID (); 2259 if (signal_tid != LLDB_INVALID_THREAD_ID) 2260 { 2261 // The resume action for the continue thread (or all threads if a continue thread is not set). 2262 lldb_private::ResumeAction action = { GetContinueThreadID (), StateType::eStateRunning, static_cast<int> (signo) }; 2263 2264 // Add the action for the continue thread (or all threads when the continue thread isn't present). 2265 resume_actions.Append (action); 2266 } 2267 else 2268 { 2269 // Send the signal to the process since we weren't targeting a specific continue thread with the signal. 2270 error = m_debugged_process_sp->Signal (signo); 2271 if (error.Fail ()) 2272 { 2273 if (log) 2274 log->Printf ("GDBRemoteCommunicationServer::%s failed to send signal for process %" PRIu64 ": %s", 2275 __FUNCTION__, 2276 m_debugged_process_sp->GetID (), 2277 error.AsCString ()); 2278 2279 return SendErrorResponse (0x52); 2280 } 2281 } 2282 2283 // Resume the threads. 2284 error = m_debugged_process_sp->Resume (resume_actions); 2285 if (error.Fail ()) 2286 { 2287 if (log) 2288 log->Printf ("GDBRemoteCommunicationServer::%s failed to resume threads for process %" PRIu64 ": %s", 2289 __FUNCTION__, 2290 m_debugged_process_sp->GetID (), 2291 error.AsCString ()); 2292 2293 return SendErrorResponse (0x38); 2294 } 2295 2296 // Don't send an "OK" packet; response is the stopped/exited message. 2297 return PacketResult::Success; 2298 } 2299 2300 GDBRemoteCommunication::PacketResult 2301 GDBRemoteCommunicationServer::Handle_c (StringExtractorGDBRemote &packet, bool skip_file_pos_adjustment) 2302 { 2303 if (!IsGdbServer ()) 2304 return SendUnimplementedResponse (packet.GetStringRef().c_str()); 2305 2306 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD)); 2307 if (log) 2308 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__); 2309 2310 // We reuse this method in vCont - don't double adjust the file position. 2311 if (!skip_file_pos_adjustment) 2312 packet.SetFilePos (::strlen ("c")); 2313 2314 // For now just support all continue. 2315 const bool has_continue_address = (packet.GetBytesLeft () > 0); 2316 if (has_continue_address) 2317 { 2318 if (log) 2319 log->Printf ("GDBRemoteCommunicationServer::%s not implemented for c{address} variant [%s remains]", __FUNCTION__, packet.Peek ()); 2320 return SendUnimplementedResponse (packet.GetStringRef().c_str()); 2321 } 2322 2323 // Ensure we have a native process. 2324 if (!m_debugged_process_sp) 2325 { 2326 if (log) 2327 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__); 2328 return SendErrorResponse (0x36); 2329 } 2330 2331 // Build the ResumeActionList 2332 lldb_private::ResumeActionList actions (StateType::eStateRunning, 0); 2333 2334 Error error = m_debugged_process_sp->Resume (actions); 2335 if (error.Fail ()) 2336 { 2337 if (log) 2338 { 2339 log->Printf ("GDBRemoteCommunicationServer::%s c failed for process %" PRIu64 ": %s", 2340 __FUNCTION__, 2341 m_debugged_process_sp->GetID (), 2342 error.AsCString ()); 2343 } 2344 return SendErrorResponse (GDBRemoteServerError::eErrorResume); 2345 } 2346 2347 if (log) 2348 log->Printf ("GDBRemoteCommunicationServer::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ()); 2349 2350 // No response required from continue. 2351 return PacketResult::Success; 2352 } 2353 2354 GDBRemoteCommunication::PacketResult 2355 GDBRemoteCommunicationServer::Handle_vCont_actions (StringExtractorGDBRemote &packet) 2356 { 2357 if (!IsGdbServer ()) 2358 { 2359 // only llgs supports $vCont. 2360 return SendUnimplementedResponse (packet.GetStringRef().c_str()); 2361 } 2362 2363 // We handle $vCont messages for c. 2364 // TODO add C, s and S. 2365 StreamString response; 2366 response.Printf("vCont;c;C;s;S"); 2367 2368 return SendPacketNoLock(response.GetData(), response.GetSize()); 2369 } 2370 2371 GDBRemoteCommunication::PacketResult 2372 GDBRemoteCommunicationServer::Handle_vCont (StringExtractorGDBRemote &packet) 2373 { 2374 if (!IsGdbServer ()) 2375 { 2376 // only llgs supports $vCont 2377 return SendUnimplementedResponse (packet.GetStringRef().c_str()); 2378 } 2379 2380 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2381 if (log) 2382 log->Printf ("GDBRemoteCommunicationServer::%s handling vCont packet", __FUNCTION__); 2383 2384 packet.SetFilePos (::strlen ("vCont")); 2385 2386 // Check if this is all continue (no options or ";c"). 2387 if (!packet.GetBytesLeft () || (::strcmp (packet.Peek (), ";c") == 0)) 2388 { 2389 // Move the packet past the ";c". 2390 if (packet.GetBytesLeft ()) 2391 packet.SetFilePos (packet.GetFilePos () + ::strlen (";c")); 2392 2393 const bool skip_file_pos_adjustment = true; 2394 return Handle_c (packet, skip_file_pos_adjustment); 2395 } 2396 else if (::strcmp (packet.Peek (), ";s") == 0) 2397 { 2398 // Move past the ';', then do a simple 's'. 2399 packet.SetFilePos (packet.GetFilePos () + 1); 2400 return Handle_s (packet); 2401 } 2402 2403 // Ensure we have a native process. 2404 if (!m_debugged_process_sp) 2405 { 2406 if (log) 2407 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__); 2408 return SendErrorResponse (0x36); 2409 } 2410 2411 ResumeActionList thread_actions; 2412 2413 while (packet.GetBytesLeft () && *packet.Peek () == ';') 2414 { 2415 // Skip the semi-colon. 2416 packet.GetChar (); 2417 2418 // Build up the thread action. 2419 ResumeAction thread_action; 2420 thread_action.tid = LLDB_INVALID_THREAD_ID; 2421 thread_action.state = eStateInvalid; 2422 thread_action.signal = 0; 2423 2424 const char action = packet.GetChar (); 2425 switch (action) 2426 { 2427 case 'C': 2428 thread_action.signal = packet.GetHexMaxU32 (false, 0); 2429 if (thread_action.signal == 0) 2430 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet C action"); 2431 // Fall through to next case... 2432 2433 case 'c': 2434 // Continue 2435 thread_action.state = eStateRunning; 2436 break; 2437 2438 case 'S': 2439 thread_action.signal = packet.GetHexMaxU32 (false, 0); 2440 if (thread_action.signal == 0) 2441 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet S action"); 2442 // Fall through to next case... 2443 2444 case 's': 2445 // Step 2446 thread_action.state = eStateStepping; 2447 break; 2448 2449 default: 2450 return SendIllFormedResponse (packet, "Unsupported vCont action"); 2451 break; 2452 } 2453 2454 // Parse out optional :{thread-id} value. 2455 if (packet.GetBytesLeft () && (*packet.Peek () == ':')) 2456 { 2457 // Consume the separator. 2458 packet.GetChar (); 2459 2460 thread_action.tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID); 2461 if (thread_action.tid == LLDB_INVALID_THREAD_ID) 2462 return SendIllFormedResponse (packet, "Could not parse thread number in vCont packet"); 2463 } 2464 2465 thread_actions.Append (thread_action); 2466 } 2467 2468 // If a default action for all other threads wasn't mentioned 2469 // then we should stop the threads. 2470 thread_actions.SetDefaultThreadActionIfNeeded (eStateStopped, 0); 2471 2472 Error error = m_debugged_process_sp->Resume (thread_actions); 2473 if (error.Fail ()) 2474 { 2475 if (log) 2476 { 2477 log->Printf ("GDBRemoteCommunicationServer::%s vCont failed for process %" PRIu64 ": %s", 2478 __FUNCTION__, 2479 m_debugged_process_sp->GetID (), 2480 error.AsCString ()); 2481 } 2482 return SendErrorResponse (GDBRemoteServerError::eErrorResume); 2483 } 2484 2485 if (log) 2486 log->Printf ("GDBRemoteCommunicationServer::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ()); 2487 2488 // No response required from vCont. 2489 return PacketResult::Success; 2490 } 2491 2492 GDBRemoteCommunication::PacketResult 2493 GDBRemoteCommunicationServer::Handle_QStartNoAckMode (StringExtractorGDBRemote &packet) 2494 { 2495 // Send response first before changing m_send_acks to we ack this packet 2496 PacketResult packet_result = SendOKResponse (); 2497 m_send_acks = false; 2498 return packet_result; 2499 } 2500 2501 GDBRemoteCommunication::PacketResult 2502 GDBRemoteCommunicationServer::Handle_qPlatform_mkdir (StringExtractorGDBRemote &packet) 2503 { 2504 packet.SetFilePos(::strlen("qPlatform_mkdir:")); 2505 mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX); 2506 if (packet.GetChar() == ',') 2507 { 2508 std::string path; 2509 packet.GetHexByteString(path); 2510 Error error = FileSystem::MakeDirectory(path.c_str(), mode); 2511 if (error.Success()) 2512 return SendPacketNoLock ("OK", 2); 2513 else 2514 return SendErrorResponse(error.GetError()); 2515 } 2516 return SendErrorResponse(20); 2517 } 2518 2519 GDBRemoteCommunication::PacketResult 2520 GDBRemoteCommunicationServer::Handle_qPlatform_chmod (StringExtractorGDBRemote &packet) 2521 { 2522 packet.SetFilePos(::strlen("qPlatform_chmod:")); 2523 2524 mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX); 2525 if (packet.GetChar() == ',') 2526 { 2527 std::string path; 2528 packet.GetHexByteString(path); 2529 Error error = FileSystem::SetFilePermissions(path.c_str(), mode); 2530 if (error.Success()) 2531 return SendPacketNoLock ("OK", 2); 2532 else 2533 return SendErrorResponse(error.GetError()); 2534 } 2535 return SendErrorResponse(19); 2536 } 2537 2538 GDBRemoteCommunication::PacketResult 2539 GDBRemoteCommunicationServer::Handle_vFile_Open (StringExtractorGDBRemote &packet) 2540 { 2541 packet.SetFilePos(::strlen("vFile:open:")); 2542 std::string path; 2543 packet.GetHexByteStringTerminatedBy(path,','); 2544 if (!path.empty()) 2545 { 2546 if (packet.GetChar() == ',') 2547 { 2548 uint32_t flags = packet.GetHexMaxU32(false, 0); 2549 if (packet.GetChar() == ',') 2550 { 2551 mode_t mode = packet.GetHexMaxU32(false, 0600); 2552 Error error; 2553 int fd = ::open (path.c_str(), flags, mode); 2554 const int save_errno = fd == -1 ? errno : 0; 2555 StreamString response; 2556 response.PutChar('F'); 2557 response.Printf("%i", fd); 2558 if (save_errno) 2559 response.Printf(",%i", save_errno); 2560 return SendPacketNoLock(response.GetData(), response.GetSize()); 2561 } 2562 } 2563 } 2564 return SendErrorResponse(18); 2565 } 2566 2567 GDBRemoteCommunication::PacketResult 2568 GDBRemoteCommunicationServer::Handle_vFile_Close (StringExtractorGDBRemote &packet) 2569 { 2570 packet.SetFilePos(::strlen("vFile:close:")); 2571 int fd = packet.GetS32(-1); 2572 Error error; 2573 int err = -1; 2574 int save_errno = 0; 2575 if (fd >= 0) 2576 { 2577 err = close(fd); 2578 save_errno = err == -1 ? errno : 0; 2579 } 2580 else 2581 { 2582 save_errno = EINVAL; 2583 } 2584 StreamString response; 2585 response.PutChar('F'); 2586 response.Printf("%i", err); 2587 if (save_errno) 2588 response.Printf(",%i", save_errno); 2589 return SendPacketNoLock(response.GetData(), response.GetSize()); 2590 } 2591 2592 GDBRemoteCommunication::PacketResult 2593 GDBRemoteCommunicationServer::Handle_vFile_pRead (StringExtractorGDBRemote &packet) 2594 { 2595 #ifdef _WIN32 2596 // Not implemented on Windows 2597 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pRead() unimplemented"); 2598 #else 2599 StreamGDBRemote response; 2600 packet.SetFilePos(::strlen("vFile:pread:")); 2601 int fd = packet.GetS32(-1); 2602 if (packet.GetChar() == ',') 2603 { 2604 uint64_t count = packet.GetU64(UINT64_MAX); 2605 if (packet.GetChar() == ',') 2606 { 2607 uint64_t offset = packet.GetU64(UINT32_MAX); 2608 if (count == UINT64_MAX) 2609 { 2610 response.Printf("F-1:%i", EINVAL); 2611 return SendPacketNoLock(response.GetData(), response.GetSize()); 2612 } 2613 2614 std::string buffer(count, 0); 2615 const ssize_t bytes_read = ::pread (fd, &buffer[0], buffer.size(), offset); 2616 const int save_errno = bytes_read == -1 ? errno : 0; 2617 response.PutChar('F'); 2618 response.Printf("%zi", bytes_read); 2619 if (save_errno) 2620 response.Printf(",%i", save_errno); 2621 else 2622 { 2623 response.PutChar(';'); 2624 response.PutEscapedBytes(&buffer[0], bytes_read); 2625 } 2626 return SendPacketNoLock(response.GetData(), response.GetSize()); 2627 } 2628 } 2629 return SendErrorResponse(21); 2630 2631 #endif 2632 } 2633 2634 GDBRemoteCommunication::PacketResult 2635 GDBRemoteCommunicationServer::Handle_vFile_pWrite (StringExtractorGDBRemote &packet) 2636 { 2637 #ifdef _WIN32 2638 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pWrite() unimplemented"); 2639 #else 2640 packet.SetFilePos(::strlen("vFile:pwrite:")); 2641 2642 StreamGDBRemote response; 2643 response.PutChar('F'); 2644 2645 int fd = packet.GetU32(UINT32_MAX); 2646 if (packet.GetChar() == ',') 2647 { 2648 off_t offset = packet.GetU64(UINT32_MAX); 2649 if (packet.GetChar() == ',') 2650 { 2651 std::string buffer; 2652 if (packet.GetEscapedBinaryData(buffer)) 2653 { 2654 const ssize_t bytes_written = ::pwrite (fd, buffer.data(), buffer.size(), offset); 2655 const int save_errno = bytes_written == -1 ? errno : 0; 2656 response.Printf("%zi", bytes_written); 2657 if (save_errno) 2658 response.Printf(",%i", save_errno); 2659 } 2660 else 2661 { 2662 response.Printf ("-1,%i", EINVAL); 2663 } 2664 return SendPacketNoLock(response.GetData(), response.GetSize()); 2665 } 2666 } 2667 return SendErrorResponse(27); 2668 #endif 2669 } 2670 2671 GDBRemoteCommunication::PacketResult 2672 GDBRemoteCommunicationServer::Handle_vFile_Size (StringExtractorGDBRemote &packet) 2673 { 2674 packet.SetFilePos(::strlen("vFile:size:")); 2675 std::string path; 2676 packet.GetHexByteString(path); 2677 if (!path.empty()) 2678 { 2679 lldb::user_id_t retcode = FileSystem::GetFileSize(FileSpec(path.c_str(), false)); 2680 StreamString response; 2681 response.PutChar('F'); 2682 response.PutHex64(retcode); 2683 if (retcode == UINT64_MAX) 2684 { 2685 response.PutChar(','); 2686 response.PutHex64(retcode); // TODO: replace with Host::GetSyswideErrorCode() 2687 } 2688 return SendPacketNoLock(response.GetData(), response.GetSize()); 2689 } 2690 return SendErrorResponse(22); 2691 } 2692 2693 GDBRemoteCommunication::PacketResult 2694 GDBRemoteCommunicationServer::Handle_vFile_Mode (StringExtractorGDBRemote &packet) 2695 { 2696 packet.SetFilePos(::strlen("vFile:mode:")); 2697 std::string path; 2698 packet.GetHexByteString(path); 2699 if (!path.empty()) 2700 { 2701 Error error; 2702 const uint32_t mode = File::GetPermissions(path.c_str(), error); 2703 StreamString response; 2704 response.Printf("F%u", mode); 2705 if (mode == 0 || error.Fail()) 2706 response.Printf(",%i", (int)error.GetError()); 2707 return SendPacketNoLock(response.GetData(), response.GetSize()); 2708 } 2709 return SendErrorResponse(23); 2710 } 2711 2712 GDBRemoteCommunication::PacketResult 2713 GDBRemoteCommunicationServer::Handle_vFile_Exists (StringExtractorGDBRemote &packet) 2714 { 2715 packet.SetFilePos(::strlen("vFile:exists:")); 2716 std::string path; 2717 packet.GetHexByteString(path); 2718 if (!path.empty()) 2719 { 2720 bool retcode = FileSystem::GetFileExists(FileSpec(path.c_str(), false)); 2721 StreamString response; 2722 response.PutChar('F'); 2723 response.PutChar(','); 2724 if (retcode) 2725 response.PutChar('1'); 2726 else 2727 response.PutChar('0'); 2728 return SendPacketNoLock(response.GetData(), response.GetSize()); 2729 } 2730 return SendErrorResponse(24); 2731 } 2732 2733 GDBRemoteCommunication::PacketResult 2734 GDBRemoteCommunicationServer::Handle_vFile_symlink (StringExtractorGDBRemote &packet) 2735 { 2736 packet.SetFilePos(::strlen("vFile:symlink:")); 2737 std::string dst, src; 2738 packet.GetHexByteStringTerminatedBy(dst, ','); 2739 packet.GetChar(); // Skip ',' char 2740 packet.GetHexByteString(src); 2741 Error error = FileSystem::Symlink(src.c_str(), dst.c_str()); 2742 StreamString response; 2743 response.Printf("F%u,%u", error.GetError(), error.GetError()); 2744 return SendPacketNoLock(response.GetData(), response.GetSize()); 2745 } 2746 2747 GDBRemoteCommunication::PacketResult 2748 GDBRemoteCommunicationServer::Handle_vFile_unlink (StringExtractorGDBRemote &packet) 2749 { 2750 packet.SetFilePos(::strlen("vFile:unlink:")); 2751 std::string path; 2752 packet.GetHexByteString(path); 2753 Error error = FileSystem::Unlink(path.c_str()); 2754 StreamString response; 2755 response.Printf("F%u,%u", error.GetError(), error.GetError()); 2756 return SendPacketNoLock(response.GetData(), response.GetSize()); 2757 } 2758 2759 GDBRemoteCommunication::PacketResult 2760 GDBRemoteCommunicationServer::Handle_qPlatform_shell (StringExtractorGDBRemote &packet) 2761 { 2762 packet.SetFilePos(::strlen("qPlatform_shell:")); 2763 std::string path; 2764 std::string working_dir; 2765 packet.GetHexByteStringTerminatedBy(path,','); 2766 if (!path.empty()) 2767 { 2768 if (packet.GetChar() == ',') 2769 { 2770 // FIXME: add timeout to qPlatform_shell packet 2771 // uint32_t timeout = packet.GetHexMaxU32(false, 32); 2772 uint32_t timeout = 10; 2773 if (packet.GetChar() == ',') 2774 packet.GetHexByteString(working_dir); 2775 int status, signo; 2776 std::string output; 2777 Error err = Host::RunShellCommand(path.c_str(), 2778 working_dir.empty() ? NULL : working_dir.c_str(), 2779 &status, &signo, &output, timeout); 2780 StreamGDBRemote response; 2781 if (err.Fail()) 2782 { 2783 response.PutCString("F,"); 2784 response.PutHex32(UINT32_MAX); 2785 } 2786 else 2787 { 2788 response.PutCString("F,"); 2789 response.PutHex32(status); 2790 response.PutChar(','); 2791 response.PutHex32(signo); 2792 response.PutChar(','); 2793 response.PutEscapedBytes(output.c_str(), output.size()); 2794 } 2795 return SendPacketNoLock(response.GetData(), response.GetSize()); 2796 } 2797 } 2798 return SendErrorResponse(24); 2799 } 2800 2801 void 2802 GDBRemoteCommunicationServer::SetCurrentThreadID (lldb::tid_t tid) 2803 { 2804 assert (IsGdbServer () && "SetCurrentThreadID() called when not GdbServer code"); 2805 2806 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD)); 2807 if (log) 2808 log->Printf ("GDBRemoteCommunicationServer::%s setting current thread id to %" PRIu64, __FUNCTION__, tid); 2809 2810 m_current_tid = tid; 2811 if (m_debugged_process_sp) 2812 m_debugged_process_sp->SetCurrentThreadID (m_current_tid); 2813 } 2814 2815 void 2816 GDBRemoteCommunicationServer::SetContinueThreadID (lldb::tid_t tid) 2817 { 2818 assert (IsGdbServer () && "SetContinueThreadID() called when not GdbServer code"); 2819 2820 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD)); 2821 if (log) 2822 log->Printf ("GDBRemoteCommunicationServer::%s setting continue thread id to %" PRIu64, __FUNCTION__, tid); 2823 2824 m_continue_tid = tid; 2825 } 2826 2827 GDBRemoteCommunication::PacketResult 2828 GDBRemoteCommunicationServer::Handle_stop_reason (StringExtractorGDBRemote &packet) 2829 { 2830 // Handle the $? gdbremote command. 2831 if (!IsGdbServer ()) 2832 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_stop_reason() unimplemented"); 2833 2834 // If no process, indicate error 2835 if (!m_debugged_process_sp) 2836 return SendErrorResponse (02); 2837 2838 return SendStopReasonForState (m_debugged_process_sp->GetState (), true); 2839 } 2840 2841 GDBRemoteCommunication::PacketResult 2842 GDBRemoteCommunicationServer::SendStopReasonForState (lldb::StateType process_state, bool flush_on_exit) 2843 { 2844 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2845 2846 switch (process_state) 2847 { 2848 case eStateAttaching: 2849 case eStateLaunching: 2850 case eStateRunning: 2851 case eStateStepping: 2852 case eStateDetached: 2853 // NOTE: gdb protocol doc looks like it should return $OK 2854 // when everything is running (i.e. no stopped result). 2855 return PacketResult::Success; // Ignore 2856 2857 case eStateSuspended: 2858 case eStateStopped: 2859 case eStateCrashed: 2860 { 2861 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID (); 2862 // Make sure we set the current thread so g and p packets return 2863 // the data the gdb will expect. 2864 SetCurrentThreadID (tid); 2865 return SendStopReplyPacketForThread (tid); 2866 } 2867 2868 case eStateInvalid: 2869 case eStateUnloaded: 2870 case eStateExited: 2871 if (flush_on_exit) 2872 FlushInferiorOutput (); 2873 return SendWResponse(m_debugged_process_sp.get()); 2874 2875 default: 2876 if (log) 2877 { 2878 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", current state reporting not handled: %s", 2879 __FUNCTION__, 2880 m_debugged_process_sp->GetID (), 2881 StateAsCString (process_state)); 2882 } 2883 break; 2884 } 2885 2886 return SendErrorResponse (0); 2887 } 2888 2889 GDBRemoteCommunication::PacketResult 2890 GDBRemoteCommunicationServer::Handle_vFile_Stat (StringExtractorGDBRemote &packet) 2891 { 2892 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_Stat() unimplemented"); 2893 } 2894 2895 GDBRemoteCommunication::PacketResult 2896 GDBRemoteCommunicationServer::Handle_vFile_MD5 (StringExtractorGDBRemote &packet) 2897 { 2898 packet.SetFilePos(::strlen("vFile:MD5:")); 2899 std::string path; 2900 packet.GetHexByteString(path); 2901 if (!path.empty()) 2902 { 2903 uint64_t a,b; 2904 StreamGDBRemote response; 2905 if (FileSystem::CalculateMD5(FileSpec(path.c_str(), false), a, b) == false) 2906 { 2907 response.PutCString("F,"); 2908 response.PutCString("x"); 2909 } 2910 else 2911 { 2912 response.PutCString("F,"); 2913 response.PutHex64(a); 2914 response.PutHex64(b); 2915 } 2916 return SendPacketNoLock(response.GetData(), response.GetSize()); 2917 } 2918 return SendErrorResponse(25); 2919 } 2920 2921 GDBRemoteCommunication::PacketResult 2922 GDBRemoteCommunicationServer::Handle_qRegisterInfo (StringExtractorGDBRemote &packet) 2923 { 2924 // Ensure we're llgs. 2925 if (!IsGdbServer()) 2926 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_qRegisterInfo() unimplemented"); 2927 2928 // Fail if we don't have a current process. 2929 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 2930 return SendErrorResponse (68); 2931 2932 // Ensure we have a thread. 2933 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadAtIndex (0)); 2934 if (!thread_sp) 2935 return SendErrorResponse (69); 2936 2937 // Get the register context for the first thread. 2938 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ()); 2939 if (!reg_context_sp) 2940 return SendErrorResponse (69); 2941 2942 // Parse out the register number from the request. 2943 packet.SetFilePos (strlen("qRegisterInfo")); 2944 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ()); 2945 if (reg_index == std::numeric_limits<uint32_t>::max ()) 2946 return SendErrorResponse (69); 2947 2948 // Return the end of registers response if we've iterated one past the end of the register set. 2949 if (reg_index >= reg_context_sp->GetRegisterCount ()) 2950 return SendErrorResponse (69); 2951 2952 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index); 2953 if (!reg_info) 2954 return SendErrorResponse (69); 2955 2956 // Build the reginfos response. 2957 StreamGDBRemote response; 2958 2959 response.PutCString ("name:"); 2960 response.PutCString (reg_info->name); 2961 response.PutChar (';'); 2962 2963 if (reg_info->alt_name && reg_info->alt_name[0]) 2964 { 2965 response.PutCString ("alt-name:"); 2966 response.PutCString (reg_info->alt_name); 2967 response.PutChar (';'); 2968 } 2969 2970 response.Printf ("bitsize:%" PRIu32 ";offset:%" PRIu32 ";", reg_info->byte_size * 8, reg_info->byte_offset); 2971 2972 switch (reg_info->encoding) 2973 { 2974 case eEncodingUint: response.PutCString ("encoding:uint;"); break; 2975 case eEncodingSint: response.PutCString ("encoding:sint;"); break; 2976 case eEncodingIEEE754: response.PutCString ("encoding:ieee754;"); break; 2977 case eEncodingVector: response.PutCString ("encoding:vector;"); break; 2978 default: break; 2979 } 2980 2981 switch (reg_info->format) 2982 { 2983 case eFormatBinary: response.PutCString ("format:binary;"); break; 2984 case eFormatDecimal: response.PutCString ("format:decimal;"); break; 2985 case eFormatHex: response.PutCString ("format:hex;"); break; 2986 case eFormatFloat: response.PutCString ("format:float;"); break; 2987 case eFormatVectorOfSInt8: response.PutCString ("format:vector-sint8;"); break; 2988 case eFormatVectorOfUInt8: response.PutCString ("format:vector-uint8;"); break; 2989 case eFormatVectorOfSInt16: response.PutCString ("format:vector-sint16;"); break; 2990 case eFormatVectorOfUInt16: response.PutCString ("format:vector-uint16;"); break; 2991 case eFormatVectorOfSInt32: response.PutCString ("format:vector-sint32;"); break; 2992 case eFormatVectorOfUInt32: response.PutCString ("format:vector-uint32;"); break; 2993 case eFormatVectorOfFloat32: response.PutCString ("format:vector-float32;"); break; 2994 case eFormatVectorOfUInt128: response.PutCString ("format:vector-uint128;"); break; 2995 default: break; 2996 }; 2997 2998 const char *const register_set_name = reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index); 2999 if (register_set_name) 3000 { 3001 response.PutCString ("set:"); 3002 response.PutCString (register_set_name); 3003 response.PutChar (';'); 3004 } 3005 3006 if (reg_info->kinds[RegisterKind::eRegisterKindGCC] != LLDB_INVALID_REGNUM) 3007 response.Printf ("gcc:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindGCC]); 3008 3009 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM) 3010 response.Printf ("dwarf:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindDWARF]); 3011 3012 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric]) 3013 { 3014 case LLDB_REGNUM_GENERIC_PC: response.PutCString("generic:pc;"); break; 3015 case LLDB_REGNUM_GENERIC_SP: response.PutCString("generic:sp;"); break; 3016 case LLDB_REGNUM_GENERIC_FP: response.PutCString("generic:fp;"); break; 3017 case LLDB_REGNUM_GENERIC_RA: response.PutCString("generic:ra;"); break; 3018 case LLDB_REGNUM_GENERIC_FLAGS: response.PutCString("generic:flags;"); break; 3019 case LLDB_REGNUM_GENERIC_ARG1: response.PutCString("generic:arg1;"); break; 3020 case LLDB_REGNUM_GENERIC_ARG2: response.PutCString("generic:arg2;"); break; 3021 case LLDB_REGNUM_GENERIC_ARG3: response.PutCString("generic:arg3;"); break; 3022 case LLDB_REGNUM_GENERIC_ARG4: response.PutCString("generic:arg4;"); break; 3023 case LLDB_REGNUM_GENERIC_ARG5: response.PutCString("generic:arg5;"); break; 3024 case LLDB_REGNUM_GENERIC_ARG6: response.PutCString("generic:arg6;"); break; 3025 case LLDB_REGNUM_GENERIC_ARG7: response.PutCString("generic:arg7;"); break; 3026 case LLDB_REGNUM_GENERIC_ARG8: response.PutCString("generic:arg8;"); break; 3027 default: break; 3028 } 3029 3030 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) 3031 { 3032 response.PutCString ("container-regs:"); 3033 int i = 0; 3034 for (const uint32_t *reg_num = reg_info->value_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) 3035 { 3036 if (i > 0) 3037 response.PutChar (','); 3038 response.Printf ("%" PRIx32, *reg_num); 3039 } 3040 response.PutChar (';'); 3041 } 3042 3043 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) 3044 { 3045 response.PutCString ("invalidate-regs:"); 3046 int i = 0; 3047 for (const uint32_t *reg_num = reg_info->invalidate_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) 3048 { 3049 if (i > 0) 3050 response.PutChar (','); 3051 response.Printf ("%" PRIx32, *reg_num); 3052 } 3053 response.PutChar (';'); 3054 } 3055 3056 return SendPacketNoLock(response.GetData(), response.GetSize()); 3057 } 3058 3059 GDBRemoteCommunication::PacketResult 3060 GDBRemoteCommunicationServer::Handle_qfThreadInfo (StringExtractorGDBRemote &packet) 3061 { 3062 // Ensure we're llgs. 3063 if (!IsGdbServer()) 3064 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_qfThreadInfo() unimplemented"); 3065 3066 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 3067 3068 // Fail if we don't have a current process. 3069 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3070 { 3071 if (log) 3072 log->Printf ("GDBRemoteCommunicationServer::%s() no process (%s), returning OK", __FUNCTION__, m_debugged_process_sp ? "invalid process id" : "null m_debugged_process_sp"); 3073 return SendOKResponse (); 3074 } 3075 3076 StreamGDBRemote response; 3077 response.PutChar ('m'); 3078 3079 if (log) 3080 log->Printf ("GDBRemoteCommunicationServer::%s() starting thread iteration", __FUNCTION__); 3081 3082 NativeThreadProtocolSP thread_sp; 3083 uint32_t thread_index; 3084 for (thread_index = 0, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index); 3085 thread_sp; 3086 ++thread_index, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index)) 3087 { 3088 if (log) 3089 log->Printf ("GDBRemoteCommunicationServer::%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); 3090 if (thread_index > 0) 3091 response.PutChar(','); 3092 response.Printf ("%" PRIx64, thread_sp->GetID ()); 3093 } 3094 3095 if (log) 3096 log->Printf ("GDBRemoteCommunicationServer::%s() finished thread iteration", __FUNCTION__); 3097 3098 return SendPacketNoLock(response.GetData(), response.GetSize()); 3099 } 3100 3101 GDBRemoteCommunication::PacketResult 3102 GDBRemoteCommunicationServer::Handle_qsThreadInfo (StringExtractorGDBRemote &packet) 3103 { 3104 // Ensure we're llgs. 3105 if (!IsGdbServer()) 3106 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_qsThreadInfo() unimplemented"); 3107 3108 // FIXME for now we return the full thread list in the initial packet and always do nothing here. 3109 return SendPacketNoLock ("l", 1); 3110 } 3111 3112 GDBRemoteCommunication::PacketResult 3113 GDBRemoteCommunicationServer::Handle_p (StringExtractorGDBRemote &packet) 3114 { 3115 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 3116 3117 // Ensure we're llgs. 3118 if (!IsGdbServer()) 3119 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_p() unimplemented"); 3120 3121 // Parse out the register number from the request. 3122 packet.SetFilePos (strlen("p")); 3123 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ()); 3124 if (reg_index == std::numeric_limits<uint32_t>::max ()) 3125 { 3126 if (log) 3127 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ()); 3128 return SendErrorResponse (0x15); 3129 } 3130 3131 // Get the thread to use. 3132 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet); 3133 if (!thread_sp) 3134 { 3135 if (log) 3136 log->Printf ("GDBRemoteCommunicationServer::%s failed, no thread available", __FUNCTION__); 3137 return SendErrorResponse (0x15); 3138 } 3139 3140 // Get the thread's register context. 3141 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ()); 3142 if (!reg_context_sp) 3143 { 3144 if (log) 3145 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ()); 3146 return SendErrorResponse (0x15); 3147 } 3148 3149 // Return the end of registers response if we've iterated one past the end of the register set. 3150 if (reg_index >= reg_context_sp->GetRegisterCount ()) 3151 { 3152 if (log) 3153 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetRegisterCount ()); 3154 return SendErrorResponse (0x15); 3155 } 3156 3157 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index); 3158 if (!reg_info) 3159 { 3160 if (log) 3161 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index); 3162 return SendErrorResponse (0x15); 3163 } 3164 3165 // Build the reginfos response. 3166 StreamGDBRemote response; 3167 3168 // Retrieve the value 3169 RegisterValue reg_value; 3170 Error error = reg_context_sp->ReadRegister (reg_info, reg_value); 3171 if (error.Fail ()) 3172 { 3173 if (log) 3174 log->Printf ("GDBRemoteCommunicationServer::%s failed, read of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ()); 3175 return SendErrorResponse (0x15); 3176 } 3177 3178 const uint8_t *const data = reinterpret_cast<const uint8_t*> (reg_value.GetBytes ()); 3179 if (!data) 3180 { 3181 if (log) 3182 log->Printf ("GDBRemoteCommunicationServer::%s failed to get data bytes from requested register %" PRIu32, __FUNCTION__, reg_index); 3183 return SendErrorResponse (0x15); 3184 } 3185 3186 // FIXME flip as needed to get data in big/little endian format for this host. 3187 for (uint32_t i = 0; i < reg_value.GetByteSize (); ++i) 3188 response.PutHex8 (data[i]); 3189 3190 return SendPacketNoLock (response.GetData (), response.GetSize ()); 3191 } 3192 3193 GDBRemoteCommunication::PacketResult 3194 GDBRemoteCommunicationServer::Handle_P (StringExtractorGDBRemote &packet) 3195 { 3196 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 3197 3198 // Ensure we're llgs. 3199 if (!IsGdbServer()) 3200 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_P() unimplemented"); 3201 3202 // Ensure there is more content. 3203 if (packet.GetBytesLeft () < 1) 3204 return SendIllFormedResponse (packet, "Empty P packet"); 3205 3206 // Parse out the register number from the request. 3207 packet.SetFilePos (strlen("P")); 3208 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ()); 3209 if (reg_index == std::numeric_limits<uint32_t>::max ()) 3210 { 3211 if (log) 3212 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ()); 3213 return SendErrorResponse (0x29); 3214 } 3215 3216 // Note debugserver would send an E30 here. 3217 if ((packet.GetBytesLeft () < 1) || (packet.GetChar () != '=')) 3218 return SendIllFormedResponse (packet, "P packet missing '=' char after register number"); 3219 3220 // Get process architecture. 3221 ArchSpec process_arch; 3222 if (!m_debugged_process_sp || !m_debugged_process_sp->GetArchitecture (process_arch)) 3223 { 3224 if (log) 3225 log->Printf ("GDBRemoteCommunicationServer::%s failed to retrieve inferior architecture", __FUNCTION__); 3226 return SendErrorResponse (0x49); 3227 } 3228 3229 // Parse out the value. 3230 const uint64_t raw_value = packet.GetHexMaxU64 (process_arch.GetByteOrder () == lldb::eByteOrderLittle, std::numeric_limits<uint64_t>::max ()); 3231 3232 // Get the thread to use. 3233 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet); 3234 if (!thread_sp) 3235 { 3236 if (log) 3237 log->Printf ("GDBRemoteCommunicationServer::%s failed, no thread available (thread index 0)", __FUNCTION__); 3238 return SendErrorResponse (0x28); 3239 } 3240 3241 // Get the thread's register context. 3242 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ()); 3243 if (!reg_context_sp) 3244 { 3245 if (log) 3246 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ()); 3247 return SendErrorResponse (0x15); 3248 } 3249 3250 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index); 3251 if (!reg_info) 3252 { 3253 if (log) 3254 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index); 3255 return SendErrorResponse (0x48); 3256 } 3257 3258 // Return the end of registers response if we've iterated one past the end of the register set. 3259 if (reg_index >= reg_context_sp->GetRegisterCount ()) 3260 { 3261 if (log) 3262 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetRegisterCount ()); 3263 return SendErrorResponse (0x47); 3264 } 3265 3266 3267 // Build the reginfos response. 3268 StreamGDBRemote response; 3269 3270 // FIXME Could be suffixed with a thread: parameter. 3271 // That thread then needs to be fed back into the reg context retrieval above. 3272 Error error = reg_context_sp->WriteRegisterFromUnsigned (reg_info, raw_value); 3273 if (error.Fail ()) 3274 { 3275 if (log) 3276 log->Printf ("GDBRemoteCommunicationServer::%s failed, write of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ()); 3277 return SendErrorResponse (0x32); 3278 } 3279 3280 return SendOKResponse(); 3281 } 3282 3283 GDBRemoteCommunicationServer::PacketResult 3284 GDBRemoteCommunicationServer::Handle_H (StringExtractorGDBRemote &packet) 3285 { 3286 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 3287 3288 // Ensure we're llgs. 3289 if (!IsGdbServer()) 3290 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_H() unimplemented"); 3291 3292 // Fail if we don't have a current process. 3293 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3294 { 3295 if (log) 3296 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3297 return SendErrorResponse (0x15); 3298 } 3299 3300 // Parse out which variant of $H is requested. 3301 packet.SetFilePos (strlen("H")); 3302 if (packet.GetBytesLeft () < 1) 3303 { 3304 if (log) 3305 log->Printf ("GDBRemoteCommunicationServer::%s failed, H command missing {g,c} variant", __FUNCTION__); 3306 return SendIllFormedResponse (packet, "H command missing {g,c} variant"); 3307 } 3308 3309 const char h_variant = packet.GetChar (); 3310 switch (h_variant) 3311 { 3312 case 'g': 3313 break; 3314 3315 case 'c': 3316 break; 3317 3318 default: 3319 if (log) 3320 log->Printf ("GDBRemoteCommunicationServer::%s failed, invalid $H variant %c", __FUNCTION__, h_variant); 3321 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g"); 3322 } 3323 3324 // Parse out the thread number. 3325 // FIXME return a parse success/fail value. All values are valid here. 3326 const lldb::tid_t tid = packet.GetHexMaxU64 (false, std::numeric_limits<lldb::tid_t>::max ()); 3327 3328 // Ensure we have the given thread when not specifying -1 (all threads) or 0 (any thread). 3329 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) 3330 { 3331 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid)); 3332 if (!thread_sp) 3333 { 3334 if (log) 3335 log->Printf ("GDBRemoteCommunicationServer::%s failed, tid %" PRIu64 " not found", __FUNCTION__, tid); 3336 return SendErrorResponse (0x15); 3337 } 3338 } 3339 3340 // Now switch the given thread type. 3341 switch (h_variant) 3342 { 3343 case 'g': 3344 SetCurrentThreadID (tid); 3345 break; 3346 3347 case 'c': 3348 SetContinueThreadID (tid); 3349 break; 3350 3351 default: 3352 assert (false && "unsupported $H variant - shouldn't get here"); 3353 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g"); 3354 } 3355 3356 return SendOKResponse(); 3357 } 3358 3359 GDBRemoteCommunicationServer::PacketResult 3360 GDBRemoteCommunicationServer::Handle_interrupt (StringExtractorGDBRemote &packet) 3361 { 3362 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 3363 3364 // Ensure we're llgs. 3365 if (!IsGdbServer()) 3366 { 3367 // Only supported on llgs 3368 return SendUnimplementedResponse (""); 3369 } 3370 3371 // Fail if we don't have a current process. 3372 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3373 { 3374 if (log) 3375 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3376 return SendErrorResponse (0x15); 3377 } 3378 3379 // Build the ResumeActionList - stop everything. 3380 lldb_private::ResumeActionList actions (StateType::eStateStopped, 0); 3381 3382 Error error = m_debugged_process_sp->Resume (actions); 3383 if (error.Fail ()) 3384 { 3385 if (log) 3386 { 3387 log->Printf ("GDBRemoteCommunicationServer::%s failed for process %" PRIu64 ": %s", 3388 __FUNCTION__, 3389 m_debugged_process_sp->GetID (), 3390 error.AsCString ()); 3391 } 3392 return SendErrorResponse (GDBRemoteServerError::eErrorResume); 3393 } 3394 3395 if (log) 3396 log->Printf ("GDBRemoteCommunicationServer::%s stopped process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ()); 3397 3398 // No response required from stop all. 3399 return PacketResult::Success; 3400 } 3401 3402 GDBRemoteCommunicationServer::PacketResult 3403 GDBRemoteCommunicationServer::Handle_m (StringExtractorGDBRemote &packet) 3404 { 3405 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3406 3407 // Ensure we're llgs. 3408 if (!IsGdbServer()) 3409 { 3410 // Only supported on llgs 3411 return SendUnimplementedResponse (""); 3412 } 3413 3414 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3415 { 3416 if (log) 3417 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3418 return SendErrorResponse (0x15); 3419 } 3420 3421 // Parse out the memory address. 3422 packet.SetFilePos (strlen("m")); 3423 if (packet.GetBytesLeft() < 1) 3424 return SendIllFormedResponse(packet, "Too short m packet"); 3425 3426 // Read the address. Punting on validation. 3427 // FIXME replace with Hex U64 read with no default value that fails on failed read. 3428 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0); 3429 3430 // Validate comma. 3431 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ',')) 3432 return SendIllFormedResponse(packet, "Comma sep missing in m packet"); 3433 3434 // Get # bytes to read. 3435 if (packet.GetBytesLeft() < 1) 3436 return SendIllFormedResponse(packet, "Length missing in m packet"); 3437 3438 const uint64_t byte_count = packet.GetHexMaxU64(false, 0); 3439 if (byte_count == 0) 3440 { 3441 if (log) 3442 log->Printf ("GDBRemoteCommunicationServer::%s nothing to read: zero-length packet", __FUNCTION__); 3443 return PacketResult::Success; 3444 } 3445 3446 // Allocate the response buffer. 3447 std::string buf(byte_count, '\0'); 3448 if (buf.empty()) 3449 return SendErrorResponse (0x78); 3450 3451 3452 // Retrieve the process memory. 3453 lldb::addr_t bytes_read = 0; 3454 lldb_private::Error error = m_debugged_process_sp->ReadMemory (read_addr, &buf[0], byte_count, bytes_read); 3455 if (error.Fail ()) 3456 { 3457 if (log) 3458 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to read. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, error.AsCString ()); 3459 return SendErrorResponse (0x08); 3460 } 3461 3462 if (bytes_read == 0) 3463 { 3464 if (log) 3465 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": read %" PRIu64 " of %" PRIu64 " requested bytes", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, bytes_read, byte_count); 3466 return SendErrorResponse (0x08); 3467 } 3468 3469 StreamGDBRemote response; 3470 for (lldb::addr_t i = 0; i < bytes_read; ++i) 3471 response.PutHex8(buf[i]); 3472 3473 return SendPacketNoLock(response.GetData(), response.GetSize()); 3474 } 3475 3476 GDBRemoteCommunication::PacketResult 3477 GDBRemoteCommunicationServer::Handle_QSetDetachOnError (StringExtractorGDBRemote &packet) 3478 { 3479 packet.SetFilePos(::strlen ("QSetDetachOnError:")); 3480 if (packet.GetU32(0)) 3481 m_process_launch_info.GetFlags().Set (eLaunchFlagDetachOnError); 3482 else 3483 m_process_launch_info.GetFlags().Clear (eLaunchFlagDetachOnError); 3484 return SendOKResponse (); 3485 } 3486 3487 GDBRemoteCommunicationServer::PacketResult 3488 GDBRemoteCommunicationServer::Handle_M (StringExtractorGDBRemote &packet) 3489 { 3490 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3491 3492 // Ensure we're llgs. 3493 if (!IsGdbServer()) 3494 { 3495 // Only supported on llgs 3496 return SendUnimplementedResponse (""); 3497 } 3498 3499 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3500 { 3501 if (log) 3502 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3503 return SendErrorResponse (0x15); 3504 } 3505 3506 // Parse out the memory address. 3507 packet.SetFilePos (strlen("M")); 3508 if (packet.GetBytesLeft() < 1) 3509 return SendIllFormedResponse(packet, "Too short M packet"); 3510 3511 // Read the address. Punting on validation. 3512 // FIXME replace with Hex U64 read with no default value that fails on failed read. 3513 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0); 3514 3515 // Validate comma. 3516 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ',')) 3517 return SendIllFormedResponse(packet, "Comma sep missing in M packet"); 3518 3519 // Get # bytes to read. 3520 if (packet.GetBytesLeft() < 1) 3521 return SendIllFormedResponse(packet, "Length missing in M packet"); 3522 3523 const uint64_t byte_count = packet.GetHexMaxU64(false, 0); 3524 if (byte_count == 0) 3525 { 3526 if (log) 3527 log->Printf ("GDBRemoteCommunicationServer::%s nothing to write: zero-length packet", __FUNCTION__); 3528 return PacketResult::Success; 3529 } 3530 3531 // Validate colon. 3532 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':')) 3533 return SendIllFormedResponse(packet, "Comma sep missing in M packet after byte length"); 3534 3535 // Allocate the conversion buffer. 3536 std::vector<uint8_t> buf(byte_count, 0); 3537 if (buf.empty()) 3538 return SendErrorResponse (0x78); 3539 3540 // Convert the hex memory write contents to bytes. 3541 StreamGDBRemote response; 3542 const uint64_t convert_count = static_cast<uint64_t> (packet.GetHexBytes (&buf[0], byte_count, 0)); 3543 if (convert_count != byte_count) 3544 { 3545 if (log) 3546 log->Printf ("GDBRemoteCommunicationServer::%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); 3547 return SendIllFormedResponse (packet, "M content byte length specified did not match hex-encoded content length"); 3548 } 3549 3550 // Write the process memory. 3551 lldb::addr_t bytes_written = 0; 3552 lldb_private::Error error = m_debugged_process_sp->WriteMemory (write_addr, &buf[0], byte_count, bytes_written); 3553 if (error.Fail ()) 3554 { 3555 if (log) 3556 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to write. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, error.AsCString ()); 3557 return SendErrorResponse (0x09); 3558 } 3559 3560 if (bytes_written == 0) 3561 { 3562 if (log) 3563 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": wrote %" PRIu64 " of %" PRIu64 " requested bytes", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, bytes_written, byte_count); 3564 return SendErrorResponse (0x09); 3565 } 3566 3567 return SendOKResponse (); 3568 } 3569 3570 GDBRemoteCommunicationServer::PacketResult 3571 GDBRemoteCommunicationServer::Handle_qMemoryRegionInfoSupported (StringExtractorGDBRemote &packet) 3572 { 3573 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3574 3575 // We don't support if we're not llgs. 3576 if (!IsGdbServer()) 3577 return SendUnimplementedResponse (""); 3578 3579 // Currently only the NativeProcessProtocol knows if it can handle a qMemoryRegionInfoSupported 3580 // request, but we're not guaranteed to be attached to a process. For now we'll assume the 3581 // client only asks this when a process is being debugged. 3582 3583 // Ensure we have a process running; otherwise, we can't figure this out 3584 // since we won't have a NativeProcessProtocol. 3585 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3586 { 3587 if (log) 3588 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3589 return SendErrorResponse (0x15); 3590 } 3591 3592 // Test if we can get any region back when asking for the region around NULL. 3593 MemoryRegionInfo region_info; 3594 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (0, region_info); 3595 if (error.Fail ()) 3596 { 3597 // We don't support memory region info collection for this NativeProcessProtocol. 3598 return SendUnimplementedResponse (""); 3599 } 3600 3601 return SendOKResponse(); 3602 } 3603 3604 GDBRemoteCommunicationServer::PacketResult 3605 GDBRemoteCommunicationServer::Handle_qMemoryRegionInfo (StringExtractorGDBRemote &packet) 3606 { 3607 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3608 3609 // We don't support if we're not llgs. 3610 if (!IsGdbServer()) 3611 return SendUnimplementedResponse (""); 3612 3613 // Ensure we have a process. 3614 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3615 { 3616 if (log) 3617 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3618 return SendErrorResponse (0x15); 3619 } 3620 3621 // Parse out the memory address. 3622 packet.SetFilePos (strlen("qMemoryRegionInfo:")); 3623 if (packet.GetBytesLeft() < 1) 3624 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet"); 3625 3626 // Read the address. Punting on validation. 3627 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0); 3628 3629 StreamGDBRemote response; 3630 3631 // Get the memory region info for the target address. 3632 MemoryRegionInfo region_info; 3633 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (read_addr, region_info); 3634 if (error.Fail ()) 3635 { 3636 // Return the error message. 3637 3638 response.PutCString ("error:"); 3639 response.PutCStringAsRawHex8 (error.AsCString ()); 3640 response.PutChar (';'); 3641 } 3642 else 3643 { 3644 // Range start and size. 3645 response.Printf ("start:%" PRIx64 ";size:%" PRIx64 ";", region_info.GetRange ().GetRangeBase (), region_info.GetRange ().GetByteSize ()); 3646 3647 // Permissions. 3648 if (region_info.GetReadable () || 3649 region_info.GetWritable () || 3650 region_info.GetExecutable ()) 3651 { 3652 // Write permissions info. 3653 response.PutCString ("permissions:"); 3654 3655 if (region_info.GetReadable ()) 3656 response.PutChar ('r'); 3657 if (region_info.GetWritable ()) 3658 response.PutChar('w'); 3659 if (region_info.GetExecutable()) 3660 response.PutChar ('x'); 3661 3662 response.PutChar (';'); 3663 } 3664 } 3665 3666 return SendPacketNoLock(response.GetData(), response.GetSize()); 3667 } 3668 3669 GDBRemoteCommunicationServer::PacketResult 3670 GDBRemoteCommunicationServer::Handle_Z (StringExtractorGDBRemote &packet) 3671 { 3672 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); 3673 3674 // We don't support if we're not llgs. 3675 if (!IsGdbServer()) 3676 return SendUnimplementedResponse (""); 3677 3678 // Ensure we have a process. 3679 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3680 { 3681 if (log) 3682 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3683 return SendErrorResponse (0x15); 3684 } 3685 3686 // Parse out software or hardware breakpoint requested. 3687 packet.SetFilePos (strlen("Z")); 3688 if (packet.GetBytesLeft() < 1) 3689 return SendIllFormedResponse(packet, "Too short Z packet, missing software/hardware specifier"); 3690 3691 bool want_breakpoint = true; 3692 bool want_hardware = false; 3693 3694 const char breakpoint_type_char = packet.GetChar (); 3695 switch (breakpoint_type_char) 3696 { 3697 case '0': want_hardware = false; want_breakpoint = true; break; 3698 case '1': want_hardware = true; want_breakpoint = true; break; 3699 case '2': want_breakpoint = false; break; 3700 case '3': want_breakpoint = false; break; 3701 default: 3702 return SendIllFormedResponse(packet, "Z packet had invalid software/hardware specifier"); 3703 3704 } 3705 3706 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',') 3707 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after breakpoint type"); 3708 3709 // FIXME implement watchpoint support. 3710 if (!want_breakpoint) 3711 return SendUnimplementedResponse ("watchpoint support not yet implemented"); 3712 3713 // Parse out the breakpoint address. 3714 if (packet.GetBytesLeft() < 1) 3715 return SendIllFormedResponse(packet, "Too short Z packet, missing address"); 3716 const lldb::addr_t breakpoint_addr = packet.GetHexMaxU64(false, 0); 3717 3718 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',') 3719 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after address"); 3720 3721 // Parse out the breakpoint kind (i.e. size hint for opcode size). 3722 const uint32_t kind = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ()); 3723 if (kind == std::numeric_limits<uint32_t>::max ()) 3724 return SendIllFormedResponse(packet, "Malformed Z packet, failed to parse kind argument"); 3725 3726 if (want_breakpoint) 3727 { 3728 // Try to set the breakpoint. 3729 const Error error = m_debugged_process_sp->SetBreakpoint (breakpoint_addr, kind, want_hardware); 3730 if (error.Success ()) 3731 return SendOKResponse (); 3732 else 3733 { 3734 if (log) 3735 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to set breakpoint: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ()); 3736 return SendErrorResponse (0x09); 3737 } 3738 } 3739 3740 // FIXME fix up after watchpoints are handled. 3741 return SendUnimplementedResponse (""); 3742 } 3743 3744 GDBRemoteCommunicationServer::PacketResult 3745 GDBRemoteCommunicationServer::Handle_z (StringExtractorGDBRemote &packet) 3746 { 3747 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); 3748 3749 // We don't support if we're not llgs. 3750 if (!IsGdbServer()) 3751 return SendUnimplementedResponse (""); 3752 3753 // Ensure we have a process. 3754 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3755 { 3756 if (log) 3757 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3758 return SendErrorResponse (0x15); 3759 } 3760 3761 // Parse out software or hardware breakpoint requested. 3762 packet.SetFilePos (strlen("Z")); 3763 if (packet.GetBytesLeft() < 1) 3764 return SendIllFormedResponse(packet, "Too short z packet, missing software/hardware specifier"); 3765 3766 bool want_breakpoint = true; 3767 3768 const char breakpoint_type_char = packet.GetChar (); 3769 switch (breakpoint_type_char) 3770 { 3771 case '0': want_breakpoint = true; break; 3772 case '1': want_breakpoint = true; break; 3773 case '2': want_breakpoint = false; break; 3774 case '3': want_breakpoint = false; break; 3775 default: 3776 return SendIllFormedResponse(packet, "z packet had invalid software/hardware specifier"); 3777 3778 } 3779 3780 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',') 3781 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after breakpoint type"); 3782 3783 // FIXME implement watchpoint support. 3784 if (!want_breakpoint) 3785 return SendUnimplementedResponse ("watchpoint support not yet implemented"); 3786 3787 // Parse out the breakpoint address. 3788 if (packet.GetBytesLeft() < 1) 3789 return SendIllFormedResponse(packet, "Too short z packet, missing address"); 3790 const lldb::addr_t breakpoint_addr = packet.GetHexMaxU64(false, 0); 3791 3792 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',') 3793 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after address"); 3794 3795 // Parse out the breakpoint kind (i.e. size hint for opcode size). 3796 const uint32_t kind = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ()); 3797 if (kind == std::numeric_limits<uint32_t>::max ()) 3798 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse kind argument"); 3799 3800 if (want_breakpoint) 3801 { 3802 // Try to set the breakpoint. 3803 const Error error = m_debugged_process_sp->RemoveBreakpoint (breakpoint_addr); 3804 if (error.Success ()) 3805 return SendOKResponse (); 3806 else 3807 { 3808 if (log) 3809 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to remove breakpoint: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ()); 3810 return SendErrorResponse (0x09); 3811 } 3812 } 3813 3814 // FIXME fix up after watchpoints are handled. 3815 return SendUnimplementedResponse (""); 3816 } 3817 3818 GDBRemoteCommunicationServer::PacketResult 3819 GDBRemoteCommunicationServer::Handle_s (StringExtractorGDBRemote &packet) 3820 { 3821 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD)); 3822 3823 // We don't support if we're not llgs. 3824 if (!IsGdbServer()) 3825 return SendUnimplementedResponse (""); 3826 3827 // Ensure we have a process. 3828 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3829 { 3830 if (log) 3831 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3832 return SendErrorResponse (0x32); 3833 } 3834 3835 // We first try to use a continue thread id. If any one or any all set, use the current thread. 3836 // Bail out if we don't have a thread id. 3837 lldb::tid_t tid = GetContinueThreadID (); 3838 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID) 3839 tid = GetCurrentThreadID (); 3840 if (tid == LLDB_INVALID_THREAD_ID) 3841 return SendErrorResponse (0x33); 3842 3843 // Double check that we have such a thread. 3844 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here. 3845 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID (tid); 3846 if (!thread_sp || thread_sp->GetID () != tid) 3847 return SendErrorResponse (0x33); 3848 3849 // Create the step action for the given thread. 3850 lldb_private::ResumeAction action = { tid, eStateStepping, 0 }; 3851 3852 // Setup the actions list. 3853 lldb_private::ResumeActionList actions; 3854 actions.Append (action); 3855 3856 // All other threads stop while we're single stepping a thread. 3857 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0); 3858 Error error = m_debugged_process_sp->Resume (actions); 3859 if (error.Fail ()) 3860 { 3861 if (log) 3862 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " Resume() failed with error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), tid, error.AsCString ()); 3863 return SendErrorResponse(0x49); 3864 } 3865 3866 // No response here - the stop or exit will come from the resulting action. 3867 return PacketResult::Success; 3868 } 3869 3870 GDBRemoteCommunicationServer::PacketResult 3871 GDBRemoteCommunicationServer::Handle_qSupported (StringExtractorGDBRemote &packet) 3872 { 3873 StreamGDBRemote response; 3874 3875 // Features common to lldb-platform and llgs. 3876 uint32_t max_packet_size = 128 * 1024; // 128KBytes is a reasonable max packet size--debugger can always use less 3877 response.Printf ("PacketSize=%x", max_packet_size); 3878 3879 response.PutCString (";QStartNoAckMode+"); 3880 response.PutCString (";QThreadSuffixSupported+"); 3881 response.PutCString (";QListThreadsInStopReply+"); 3882 #if defined(__linux__) 3883 response.PutCString (";qXfer:auxv:read+"); 3884 #endif 3885 3886 return SendPacketNoLock(response.GetData(), response.GetSize()); 3887 } 3888 3889 GDBRemoteCommunicationServer::PacketResult 3890 GDBRemoteCommunicationServer::Handle_QThreadSuffixSupported (StringExtractorGDBRemote &packet) 3891 { 3892 m_thread_suffix_supported = true; 3893 return SendOKResponse(); 3894 } 3895 3896 GDBRemoteCommunicationServer::PacketResult 3897 GDBRemoteCommunicationServer::Handle_QListThreadsInStopReply (StringExtractorGDBRemote &packet) 3898 { 3899 m_list_threads_in_stop_reply = true; 3900 return SendOKResponse(); 3901 } 3902 3903 GDBRemoteCommunicationServer::PacketResult 3904 GDBRemoteCommunicationServer::Handle_qXfer_auxv_read (StringExtractorGDBRemote &packet) 3905 { 3906 // We don't support if we're not llgs. 3907 if (!IsGdbServer()) 3908 return SendUnimplementedResponse ("only supported for lldb-gdbserver"); 3909 3910 // *BSD impls should be able to do this too. 3911 #if defined(__linux__) 3912 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3913 3914 // Parse out the offset. 3915 packet.SetFilePos (strlen("qXfer:auxv:read::")); 3916 if (packet.GetBytesLeft () < 1) 3917 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset"); 3918 3919 const uint64_t auxv_offset = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ()); 3920 if (auxv_offset == std::numeric_limits<uint64_t>::max ()) 3921 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset"); 3922 3923 // Parse out comma. 3924 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ',') 3925 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing comma after offset"); 3926 3927 // Parse out the length. 3928 const uint64_t auxv_length = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ()); 3929 if (auxv_length == std::numeric_limits<uint64_t>::max ()) 3930 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing length"); 3931 3932 // Grab the auxv data if we need it. 3933 if (!m_active_auxv_buffer_sp) 3934 { 3935 // Make sure we have a valid process. 3936 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3937 { 3938 if (log) 3939 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3940 return SendErrorResponse (0x10); 3941 } 3942 3943 // Grab the auxv data. 3944 m_active_auxv_buffer_sp = Host::GetAuxvData (m_debugged_process_sp->GetID ()); 3945 if (!m_active_auxv_buffer_sp || m_active_auxv_buffer_sp->GetByteSize () == 0) 3946 { 3947 // Hmm, no auxv data, call that an error. 3948 if (log) 3949 log->Printf ("GDBRemoteCommunicationServer::%s failed, no auxv data retrieved", __FUNCTION__); 3950 m_active_auxv_buffer_sp.reset (); 3951 return SendErrorResponse (0x11); 3952 } 3953 } 3954 3955 // FIXME find out if/how I lock the stream here. 3956 3957 StreamGDBRemote response; 3958 bool done_with_buffer = false; 3959 3960 if (auxv_offset >= m_active_auxv_buffer_sp->GetByteSize ()) 3961 { 3962 // We have nothing left to send. Mark the buffer as complete. 3963 response.PutChar ('l'); 3964 done_with_buffer = true; 3965 } 3966 else 3967 { 3968 // Figure out how many bytes are available starting at the given offset. 3969 const uint64_t bytes_remaining = m_active_auxv_buffer_sp->GetByteSize () - auxv_offset; 3970 3971 // Figure out how many bytes we're going to read. 3972 const uint64_t bytes_to_read = (auxv_length > bytes_remaining) ? bytes_remaining : auxv_length; 3973 3974 // Mark the response type according to whether we're reading the remainder of the auxv data. 3975 if (bytes_to_read >= bytes_remaining) 3976 { 3977 // There will be nothing left to read after this 3978 response.PutChar ('l'); 3979 done_with_buffer = true; 3980 } 3981 else 3982 { 3983 // There will still be bytes to read after this request. 3984 response.PutChar ('m'); 3985 } 3986 3987 // Now write the data in encoded binary form. 3988 response.PutEscapedBytes (m_active_auxv_buffer_sp->GetBytes () + auxv_offset, bytes_to_read); 3989 } 3990 3991 if (done_with_buffer) 3992 m_active_auxv_buffer_sp.reset (); 3993 3994 return SendPacketNoLock(response.GetData(), response.GetSize()); 3995 #else 3996 return SendUnimplementedResponse ("not implemented on this platform"); 3997 #endif 3998 } 3999 4000 GDBRemoteCommunicationServer::PacketResult 4001 GDBRemoteCommunicationServer::Handle_QSaveRegisterState (StringExtractorGDBRemote &packet) 4002 { 4003 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 4004 4005 // We don't support if we're not llgs. 4006 if (!IsGdbServer()) 4007 return SendUnimplementedResponse ("only supported for lldb-gdbserver"); 4008 4009 // Move past packet name. 4010 packet.SetFilePos (strlen ("QSaveRegisterState")); 4011 4012 // Get the thread to use. 4013 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet); 4014 if (!thread_sp) 4015 { 4016 if (m_thread_suffix_supported) 4017 return SendIllFormedResponse (packet, "No thread specified in QSaveRegisterState packet"); 4018 else 4019 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet"); 4020 } 4021 4022 // Grab the register context for the thread. 4023 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ()); 4024 if (!reg_context_sp) 4025 { 4026 if (log) 4027 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ()); 4028 return SendErrorResponse (0x15); 4029 } 4030 4031 // Save registers to a buffer. 4032 DataBufferSP register_data_sp; 4033 Error error = reg_context_sp->ReadAllRegisterValues (register_data_sp); 4034 if (error.Fail ()) 4035 { 4036 if (log) 4037 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to save all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ()); 4038 return SendErrorResponse (0x75); 4039 } 4040 4041 // Allocate a new save id. 4042 const uint32_t save_id = GetNextSavedRegistersID (); 4043 assert ((m_saved_registers_map.find (save_id) == m_saved_registers_map.end ()) && "GetNextRegisterSaveID() returned an existing register save id"); 4044 4045 // Save the register data buffer under the save id. 4046 { 4047 Mutex::Locker locker (m_saved_registers_mutex); 4048 m_saved_registers_map[save_id] = register_data_sp; 4049 } 4050 4051 // Write the response. 4052 StreamGDBRemote response; 4053 response.Printf ("%" PRIu32, save_id); 4054 return SendPacketNoLock(response.GetData(), response.GetSize()); 4055 } 4056 4057 GDBRemoteCommunicationServer::PacketResult 4058 GDBRemoteCommunicationServer::Handle_QRestoreRegisterState (StringExtractorGDBRemote &packet) 4059 { 4060 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 4061 4062 // We don't support if we're not llgs. 4063 if (!IsGdbServer()) 4064 return SendUnimplementedResponse ("only supported for lldb-gdbserver"); 4065 4066 // Parse out save id. 4067 packet.SetFilePos (strlen ("QRestoreRegisterState:")); 4068 if (packet.GetBytesLeft () < 1) 4069 return SendIllFormedResponse (packet, "QRestoreRegisterState packet missing register save id"); 4070 4071 const uint32_t save_id = packet.GetU32 (0); 4072 if (save_id == 0) 4073 { 4074 if (log) 4075 log->Printf ("GDBRemoteCommunicationServer::%s QRestoreRegisterState packet has malformed save id, expecting decimal uint32_t", __FUNCTION__); 4076 return SendErrorResponse (0x76); 4077 } 4078 4079 // Get the thread to use. 4080 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet); 4081 if (!thread_sp) 4082 { 4083 if (m_thread_suffix_supported) 4084 return SendIllFormedResponse (packet, "No thread specified in QRestoreRegisterState packet"); 4085 else 4086 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet"); 4087 } 4088 4089 // Grab the register context for the thread. 4090 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ()); 4091 if (!reg_context_sp) 4092 { 4093 if (log) 4094 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ()); 4095 return SendErrorResponse (0x15); 4096 } 4097 4098 // Retrieve register state buffer, then remove from the list. 4099 DataBufferSP register_data_sp; 4100 { 4101 Mutex::Locker locker (m_saved_registers_mutex); 4102 4103 // Find the register set buffer for the given save id. 4104 auto it = m_saved_registers_map.find (save_id); 4105 if (it == m_saved_registers_map.end ()) 4106 { 4107 if (log) 4108 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " does not have a register set save buffer for id %" PRIu32, __FUNCTION__, m_debugged_process_sp->GetID (), save_id); 4109 return SendErrorResponse (0x77); 4110 } 4111 register_data_sp = it->second; 4112 4113 // Remove it from the map. 4114 m_saved_registers_map.erase (it); 4115 } 4116 4117 Error error = reg_context_sp->WriteAllRegisterValues (register_data_sp); 4118 if (error.Fail ()) 4119 { 4120 if (log) 4121 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to restore all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ()); 4122 return SendErrorResponse (0x77); 4123 } 4124 4125 return SendOKResponse(); 4126 } 4127 4128 GDBRemoteCommunicationServer::PacketResult 4129 GDBRemoteCommunicationServer::Handle_vAttach (StringExtractorGDBRemote &packet) 4130 { 4131 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 4132 4133 // We don't support if we're not llgs. 4134 if (!IsGdbServer()) 4135 return SendUnimplementedResponse ("only supported for lldb-gdbserver"); 4136 4137 // Consume the ';' after vAttach. 4138 packet.SetFilePos (strlen ("vAttach")); 4139 if (!packet.GetBytesLeft () || packet.GetChar () != ';') 4140 return SendIllFormedResponse (packet, "vAttach missing expected ';'"); 4141 4142 // Grab the PID to which we will attach (assume hex encoding). 4143 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16); 4144 if (pid == LLDB_INVALID_PROCESS_ID) 4145 return SendIllFormedResponse (packet, "vAttach failed to parse the process id"); 4146 4147 // Attempt to attach. 4148 if (log) 4149 log->Printf ("GDBRemoteCommunicationServer::%s attempting to attach to pid %" PRIu64, __FUNCTION__, pid); 4150 4151 Error error = AttachToProcess (pid); 4152 4153 if (error.Fail ()) 4154 { 4155 if (log) 4156 log->Printf ("GDBRemoteCommunicationServer::%s failed to attach to pid %" PRIu64 ": %s\n", __FUNCTION__, pid, error.AsCString()); 4157 return SendErrorResponse (0x01); 4158 } 4159 4160 // Notify we attached by sending a stop packet. 4161 return SendStopReasonForState (m_debugged_process_sp->GetState (), true); 4162 4163 return PacketResult::Success; 4164 } 4165 4166 void 4167 GDBRemoteCommunicationServer::FlushInferiorOutput () 4168 { 4169 // If we're not monitoring an inferior's terminal, ignore this. 4170 if (!m_stdio_communication.IsConnected()) 4171 return; 4172 4173 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 4174 if (log) 4175 log->Printf ("GDBRemoteCommunicationServer::%s() called", __FUNCTION__); 4176 4177 // FIXME implement a timeout on the join. 4178 m_stdio_communication.JoinReadThread(); 4179 } 4180 4181 void 4182 GDBRemoteCommunicationServer::MaybeCloseInferiorTerminalConnection () 4183 { 4184 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 4185 4186 // Tell the stdio connection to shut down. 4187 if (m_stdio_communication.IsConnected()) 4188 { 4189 auto connection = m_stdio_communication.GetConnection(); 4190 if (connection) 4191 { 4192 Error error; 4193 connection->Disconnect (&error); 4194 4195 if (error.Success ()) 4196 { 4197 if (log) 4198 log->Printf ("GDBRemoteCommunicationServer::%s disconnect process terminal stdio - SUCCESS", __FUNCTION__); 4199 } 4200 else 4201 { 4202 if (log) 4203 log->Printf ("GDBRemoteCommunicationServer::%s disconnect process terminal stdio - FAIL: %s", __FUNCTION__, error.AsCString ()); 4204 } 4205 } 4206 } 4207 } 4208 4209 4210 lldb_private::NativeThreadProtocolSP 4211 GDBRemoteCommunicationServer::GetThreadFromSuffix (StringExtractorGDBRemote &packet) 4212 { 4213 NativeThreadProtocolSP thread_sp; 4214 4215 // We have no thread if we don't have a process. 4216 if (!m_debugged_process_sp || m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID) 4217 return thread_sp; 4218 4219 // If the client hasn't asked for thread suffix support, there will not be a thread suffix. 4220 // Use the current thread in that case. 4221 if (!m_thread_suffix_supported) 4222 { 4223 const lldb::tid_t current_tid = GetCurrentThreadID (); 4224 if (current_tid == LLDB_INVALID_THREAD_ID) 4225 return thread_sp; 4226 else if (current_tid == 0) 4227 { 4228 // Pick a thread. 4229 return m_debugged_process_sp->GetThreadAtIndex (0); 4230 } 4231 else 4232 return m_debugged_process_sp->GetThreadByID (current_tid); 4233 } 4234 4235 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 4236 4237 // Parse out the ';'. 4238 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ';') 4239 { 4240 if (log) 4241 log->Printf ("GDBRemoteCommunicationServer::%s gdb-remote parse error: expected ';' prior to start of thread suffix: packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ()); 4242 return thread_sp; 4243 } 4244 4245 if (!packet.GetBytesLeft ()) 4246 return thread_sp; 4247 4248 // Parse out thread: portion. 4249 if (strncmp (packet.Peek (), "thread:", strlen("thread:")) != 0) 4250 { 4251 if (log) 4252 log->Printf ("GDBRemoteCommunicationServer::%s gdb-remote parse error: expected 'thread:' but not found, packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ()); 4253 return thread_sp; 4254 } 4255 packet.SetFilePos (packet.GetFilePos () + strlen("thread:")); 4256 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0); 4257 if (tid != 0) 4258 return m_debugged_process_sp->GetThreadByID (tid); 4259 4260 return thread_sp; 4261 } 4262 4263 lldb::tid_t 4264 GDBRemoteCommunicationServer::GetCurrentThreadID () const 4265 { 4266 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) 4267 { 4268 // Use whatever the debug process says is the current thread id 4269 // since the protocol either didn't specify or specified we want 4270 // any/all threads marked as the current thread. 4271 if (!m_debugged_process_sp) 4272 return LLDB_INVALID_THREAD_ID; 4273 return m_debugged_process_sp->GetCurrentThreadID (); 4274 } 4275 // Use the specific current thread id set by the gdb remote protocol. 4276 return m_current_tid; 4277 } 4278 4279 uint32_t 4280 GDBRemoteCommunicationServer::GetNextSavedRegistersID () 4281 { 4282 Mutex::Locker locker (m_saved_registers_mutex); 4283 return m_next_saved_registers_id++; 4284 } 4285 4286