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 // Packet format: "qUserName:%i" where %i is the uid 1542 packet.SetFilePos(::strlen ("qUserName:")); 1543 uint32_t uid = packet.GetU32 (UINT32_MAX); 1544 if (uid != UINT32_MAX) 1545 { 1546 std::string name; 1547 if (Host::GetUserName (uid, name)) 1548 { 1549 StreamString response; 1550 response.PutCStringAsRawHex8 (name.c_str()); 1551 return SendPacketNoLock (response.GetData(), response.GetSize()); 1552 } 1553 } 1554 return SendErrorResponse (5); 1555 1556 } 1557 1558 GDBRemoteCommunication::PacketResult 1559 GDBRemoteCommunicationServer::Handle_qGroupName (StringExtractorGDBRemote &packet) 1560 { 1561 // Packet format: "qGroupName:%i" where %i is the gid 1562 packet.SetFilePos(::strlen ("qGroupName:")); 1563 uint32_t gid = packet.GetU32 (UINT32_MAX); 1564 if (gid != UINT32_MAX) 1565 { 1566 std::string name; 1567 if (Host::GetGroupName (gid, name)) 1568 { 1569 StreamString response; 1570 response.PutCStringAsRawHex8 (name.c_str()); 1571 return SendPacketNoLock (response.GetData(), response.GetSize()); 1572 } 1573 } 1574 return SendErrorResponse (6); 1575 } 1576 1577 GDBRemoteCommunication::PacketResult 1578 GDBRemoteCommunicationServer::Handle_qSpeedTest (StringExtractorGDBRemote &packet) 1579 { 1580 packet.SetFilePos(::strlen ("qSpeedTest:")); 1581 1582 std::string key; 1583 std::string value; 1584 bool success = packet.GetNameColonValue(key, value); 1585 if (success && key.compare("response_size") == 0) 1586 { 1587 uint32_t response_size = Args::StringToUInt32(value.c_str(), 0, 0, &success); 1588 if (success) 1589 { 1590 if (response_size == 0) 1591 return SendOKResponse(); 1592 StreamString response; 1593 uint32_t bytes_left = response_size; 1594 response.PutCString("data:"); 1595 while (bytes_left > 0) 1596 { 1597 if (bytes_left >= 26) 1598 { 1599 response.PutCString("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); 1600 bytes_left -= 26; 1601 } 1602 else 1603 { 1604 response.Printf ("%*.*s;", bytes_left, bytes_left, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); 1605 bytes_left = 0; 1606 } 1607 } 1608 return SendPacketNoLock (response.GetData(), response.GetSize()); 1609 } 1610 } 1611 return SendErrorResponse (7); 1612 } 1613 1614 // 1615 //static bool 1616 //WaitForProcessToSIGSTOP (const lldb::pid_t pid, const int timeout_in_seconds) 1617 //{ 1618 // const int time_delta_usecs = 100000; 1619 // const int num_retries = timeout_in_seconds/time_delta_usecs; 1620 // for (int i=0; i<num_retries; i++) 1621 // { 1622 // struct proc_bsdinfo bsd_info; 1623 // int error = ::proc_pidinfo (pid, PROC_PIDTBSDINFO, 1624 // (uint64_t) 0, 1625 // &bsd_info, 1626 // PROC_PIDTBSDINFO_SIZE); 1627 // 1628 // switch (error) 1629 // { 1630 // case EINVAL: 1631 // case ENOTSUP: 1632 // case ESRCH: 1633 // case EPERM: 1634 // return false; 1635 // 1636 // default: 1637 // break; 1638 // 1639 // case 0: 1640 // if (bsd_info.pbi_status == SSTOP) 1641 // return true; 1642 // } 1643 // ::usleep (time_delta_usecs); 1644 // } 1645 // return false; 1646 //} 1647 1648 GDBRemoteCommunication::PacketResult 1649 GDBRemoteCommunicationServer::Handle_A (StringExtractorGDBRemote &packet) 1650 { 1651 // The 'A' packet is the most over designed packet ever here with 1652 // redundant argument indexes, redundant argument lengths and needed hex 1653 // encoded argument string values. Really all that is needed is a comma 1654 // separated hex encoded argument value list, but we will stay true to the 1655 // documented version of the 'A' packet here... 1656 1657 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 1658 int actual_arg_index = 0; 1659 1660 packet.SetFilePos(1); // Skip the 'A' 1661 bool success = true; 1662 while (success && packet.GetBytesLeft() > 0) 1663 { 1664 // Decode the decimal argument string length. This length is the 1665 // number of hex nibbles in the argument string value. 1666 const uint32_t arg_len = packet.GetU32(UINT32_MAX); 1667 if (arg_len == UINT32_MAX) 1668 success = false; 1669 else 1670 { 1671 // Make sure the argument hex string length is followed by a comma 1672 if (packet.GetChar() != ',') 1673 success = false; 1674 else 1675 { 1676 // Decode the argument index. We ignore this really because 1677 // who would really send down the arguments in a random order??? 1678 const uint32_t arg_idx = packet.GetU32(UINT32_MAX); 1679 if (arg_idx == UINT32_MAX) 1680 success = false; 1681 else 1682 { 1683 // Make sure the argument index is followed by a comma 1684 if (packet.GetChar() != ',') 1685 success = false; 1686 else 1687 { 1688 // Decode the argument string value from hex bytes 1689 // back into a UTF8 string and make sure the length 1690 // matches the one supplied in the packet 1691 std::string arg; 1692 if (packet.GetHexByteStringFixedLength(arg, arg_len) != (arg_len / 2)) 1693 success = false; 1694 else 1695 { 1696 // If there are any bytes left 1697 if (packet.GetBytesLeft()) 1698 { 1699 if (packet.GetChar() != ',') 1700 success = false; 1701 } 1702 1703 if (success) 1704 { 1705 if (arg_idx == 0) 1706 m_process_launch_info.GetExecutableFile().SetFile(arg.c_str(), false); 1707 m_process_launch_info.GetArguments().AppendArgument(arg.c_str()); 1708 if (log) 1709 log->Printf ("GDBRemoteCommunicationServer::%s added arg %d: \"%s\"", __FUNCTION__, actual_arg_index, arg.c_str ()); 1710 ++actual_arg_index; 1711 } 1712 } 1713 } 1714 } 1715 } 1716 } 1717 } 1718 1719 if (success) 1720 { 1721 m_process_launch_error = LaunchProcess (); 1722 if (m_process_launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) 1723 { 1724 return SendOKResponse (); 1725 } 1726 else 1727 { 1728 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 1729 if (log) 1730 log->Printf("GDBRemoteCommunicationServer::%s failed to launch exe: %s", 1731 __FUNCTION__, 1732 m_process_launch_error.AsCString()); 1733 1734 } 1735 } 1736 return SendErrorResponse (8); 1737 } 1738 1739 GDBRemoteCommunication::PacketResult 1740 GDBRemoteCommunicationServer::Handle_qC (StringExtractorGDBRemote &packet) 1741 { 1742 StreamString response; 1743 1744 if (IsGdbServer ()) 1745 { 1746 // Fail if we don't have a current process. 1747 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 1748 return SendErrorResponse (68); 1749 1750 // Make sure we set the current thread so g and p packets return 1751 // the data the gdb will expect. 1752 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID (); 1753 SetCurrentThreadID (tid); 1754 1755 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread (); 1756 if (!thread_sp) 1757 return SendErrorResponse (69); 1758 1759 response.Printf ("QC%" PRIx64, thread_sp->GetID ()); 1760 } 1761 else 1762 { 1763 // NOTE: lldb should now be using qProcessInfo for process IDs. This path here 1764 // should not be used. It is reporting process id instead of thread id. The 1765 // correct answer doesn't seem to make much sense for lldb-platform. 1766 // CONSIDER: flip to "unsupported". 1767 lldb::pid_t pid = m_process_launch_info.GetProcessID(); 1768 response.Printf("QC%" PRIx64, pid); 1769 1770 // this should always be platform here 1771 assert (m_is_platform && "this code path should only be traversed for lldb-platform"); 1772 1773 if (m_is_platform) 1774 { 1775 // If we launch a process and this GDB server is acting as a platform, 1776 // then we need to clear the process launch state so we can start 1777 // launching another process. In order to launch a process a bunch or 1778 // packets need to be sent: environment packets, working directory, 1779 // disable ASLR, and many more settings. When we launch a process we 1780 // then need to know when to clear this information. Currently we are 1781 // selecting the 'qC' packet as that packet which seems to make the most 1782 // sense. 1783 if (pid != LLDB_INVALID_PROCESS_ID) 1784 { 1785 m_process_launch_info.Clear(); 1786 } 1787 } 1788 } 1789 return SendPacketNoLock (response.GetData(), response.GetSize()); 1790 } 1791 1792 bool 1793 GDBRemoteCommunicationServer::DebugserverProcessReaped (lldb::pid_t pid) 1794 { 1795 Mutex::Locker locker (m_spawned_pids_mutex); 1796 FreePortForProcess(pid); 1797 return m_spawned_pids.erase(pid) > 0; 1798 } 1799 bool 1800 GDBRemoteCommunicationServer::ReapDebugserverProcess (void *callback_baton, 1801 lldb::pid_t pid, 1802 bool exited, 1803 int signal, // Zero for no signal 1804 int status) // Exit value of process if signal is zero 1805 { 1806 GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton; 1807 server->DebugserverProcessReaped (pid); 1808 return true; 1809 } 1810 1811 bool 1812 GDBRemoteCommunicationServer::DebuggedProcessReaped (lldb::pid_t pid) 1813 { 1814 // reap a process that we were debugging (but not debugserver) 1815 Mutex::Locker locker (m_spawned_pids_mutex); 1816 return m_spawned_pids.erase(pid) > 0; 1817 } 1818 1819 bool 1820 GDBRemoteCommunicationServer::ReapDebuggedProcess (void *callback_baton, 1821 lldb::pid_t pid, 1822 bool exited, 1823 int signal, // Zero for no signal 1824 int status) // Exit value of process if signal is zero 1825 { 1826 GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton; 1827 server->DebuggedProcessReaped (pid); 1828 return true; 1829 } 1830 1831 GDBRemoteCommunication::PacketResult 1832 GDBRemoteCommunicationServer::Handle_qLaunchGDBServer (StringExtractorGDBRemote &packet) 1833 { 1834 #ifdef _WIN32 1835 return SendErrorResponse(9); 1836 #else 1837 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM)); 1838 1839 // Spawn a local debugserver as a platform so we can then attach or launch 1840 // a process... 1841 1842 if (m_is_platform) 1843 { 1844 if (log) 1845 log->Printf ("GDBRemoteCommunicationServer::%s() called", __FUNCTION__); 1846 1847 // Sleep and wait a bit for debugserver to start to listen... 1848 ConnectionFileDescriptor file_conn; 1849 std::string hostname; 1850 // TODO: /tmp/ should not be hardcoded. User might want to override /tmp 1851 // with the TMPDIR environment variable 1852 packet.SetFilePos(::strlen ("qLaunchGDBServer;")); 1853 std::string name; 1854 std::string value; 1855 uint16_t port = UINT16_MAX; 1856 while (packet.GetNameColonValue(name, value)) 1857 { 1858 if (name.compare ("host") == 0) 1859 hostname.swap(value); 1860 else if (name.compare ("port") == 0) 1861 port = Args::StringToUInt32(value.c_str(), 0, 0); 1862 } 1863 if (port == UINT16_MAX) 1864 port = GetNextAvailablePort(); 1865 1866 // Spawn a new thread to accept the port that gets bound after 1867 // binding to port 0 (zero). 1868 1869 // Spawn a debugserver and try to get the port it listens to. 1870 ProcessLaunchInfo debugserver_launch_info; 1871 if (hostname.empty()) 1872 hostname = "127.0.0.1"; 1873 if (log) 1874 log->Printf("Launching debugserver with: %s:%u...\n", hostname.c_str(), port); 1875 1876 debugserver_launch_info.SetMonitorProcessCallback(ReapDebugserverProcess, this, false); 1877 1878 Error error = StartDebugserverProcess (hostname.empty() ? NULL : hostname.c_str(), 1879 port, 1880 debugserver_launch_info, 1881 port); 1882 1883 lldb::pid_t debugserver_pid = debugserver_launch_info.GetProcessID(); 1884 1885 1886 if (debugserver_pid != LLDB_INVALID_PROCESS_ID) 1887 { 1888 Mutex::Locker locker (m_spawned_pids_mutex); 1889 m_spawned_pids.insert(debugserver_pid); 1890 if (port > 0) 1891 AssociatePortWithProcess(port, debugserver_pid); 1892 } 1893 else 1894 { 1895 if (port > 0) 1896 FreePort (port); 1897 } 1898 1899 if (error.Success()) 1900 { 1901 if (log) 1902 log->Printf ("GDBRemoteCommunicationServer::%s() debugserver launched successfully as pid %" PRIu64, __FUNCTION__, debugserver_pid); 1903 1904 char response[256]; 1905 const int response_len = ::snprintf (response, sizeof(response), "pid:%" PRIu64 ";port:%u;", debugserver_pid, port + m_port_offset); 1906 assert (response_len < (int)sizeof(response)); 1907 PacketResult packet_result = SendPacketNoLock (response, response_len); 1908 1909 if (packet_result != PacketResult::Success) 1910 { 1911 if (debugserver_pid != LLDB_INVALID_PROCESS_ID) 1912 ::kill (debugserver_pid, SIGINT); 1913 } 1914 return packet_result; 1915 } 1916 else 1917 { 1918 if (log) 1919 log->Printf ("GDBRemoteCommunicationServer::%s() debugserver launch failed: %s", __FUNCTION__, error.AsCString ()); 1920 } 1921 } 1922 return SendErrorResponse (9); 1923 #endif 1924 } 1925 1926 bool 1927 GDBRemoteCommunicationServer::KillSpawnedProcess (lldb::pid_t pid) 1928 { 1929 // make sure we know about this process 1930 { 1931 Mutex::Locker locker (m_spawned_pids_mutex); 1932 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) 1933 return false; 1934 } 1935 1936 // first try a SIGTERM (standard kill) 1937 Host::Kill (pid, SIGTERM); 1938 1939 // check if that worked 1940 for (size_t i=0; i<10; ++i) 1941 { 1942 { 1943 Mutex::Locker locker (m_spawned_pids_mutex); 1944 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) 1945 { 1946 // it is now killed 1947 return true; 1948 } 1949 } 1950 usleep (10000); 1951 } 1952 1953 // check one more time after the final usleep 1954 { 1955 Mutex::Locker locker (m_spawned_pids_mutex); 1956 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) 1957 return true; 1958 } 1959 1960 // the launched process still lives. Now try killing it again, 1961 // this time with an unblockable signal. 1962 Host::Kill (pid, SIGKILL); 1963 1964 for (size_t i=0; i<10; ++i) 1965 { 1966 { 1967 Mutex::Locker locker (m_spawned_pids_mutex); 1968 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) 1969 { 1970 // it is now killed 1971 return true; 1972 } 1973 } 1974 usleep (10000); 1975 } 1976 1977 // check one more time after the final usleep 1978 // Scope for locker 1979 { 1980 Mutex::Locker locker (m_spawned_pids_mutex); 1981 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) 1982 return true; 1983 } 1984 1985 // no luck - the process still lives 1986 return false; 1987 } 1988 1989 GDBRemoteCommunication::PacketResult 1990 GDBRemoteCommunicationServer::Handle_qKillSpawnedProcess (StringExtractorGDBRemote &packet) 1991 { 1992 packet.SetFilePos(::strlen ("qKillSpawnedProcess:")); 1993 1994 lldb::pid_t pid = packet.GetU64(LLDB_INVALID_PROCESS_ID); 1995 1996 // verify that we know anything about this pid. 1997 // Scope for locker 1998 { 1999 Mutex::Locker locker (m_spawned_pids_mutex); 2000 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) 2001 { 2002 // not a pid we know about 2003 return SendErrorResponse (10); 2004 } 2005 } 2006 2007 // go ahead and attempt to kill the spawned process 2008 if (KillSpawnedProcess (pid)) 2009 return SendOKResponse (); 2010 else 2011 return SendErrorResponse (11); 2012 } 2013 2014 GDBRemoteCommunication::PacketResult 2015 GDBRemoteCommunicationServer::Handle_k (StringExtractorGDBRemote &packet) 2016 { 2017 // ignore for now if we're lldb_platform 2018 if (m_is_platform) 2019 return SendUnimplementedResponse (packet.GetStringRef().c_str()); 2020 2021 // shutdown all spawned processes 2022 std::set<lldb::pid_t> spawned_pids_copy; 2023 2024 // copy pids 2025 { 2026 Mutex::Locker locker (m_spawned_pids_mutex); 2027 spawned_pids_copy.insert (m_spawned_pids.begin (), m_spawned_pids.end ()); 2028 } 2029 2030 // nuke the spawned processes 2031 for (auto it = spawned_pids_copy.begin (); it != spawned_pids_copy.end (); ++it) 2032 { 2033 lldb::pid_t spawned_pid = *it; 2034 if (!KillSpawnedProcess (spawned_pid)) 2035 { 2036 fprintf (stderr, "%s: failed to kill spawned pid %" PRIu64 ", ignoring.\n", __FUNCTION__, spawned_pid); 2037 } 2038 } 2039 2040 FlushInferiorOutput (); 2041 2042 // No OK response for kill packet. 2043 // return SendOKResponse (); 2044 return PacketResult::Success; 2045 } 2046 2047 GDBRemoteCommunication::PacketResult 2048 GDBRemoteCommunicationServer::Handle_qLaunchSuccess (StringExtractorGDBRemote &packet) 2049 { 2050 if (m_process_launch_error.Success()) 2051 return SendOKResponse(); 2052 StreamString response; 2053 response.PutChar('E'); 2054 response.PutCString(m_process_launch_error.AsCString("<unknown error>")); 2055 return SendPacketNoLock (response.GetData(), response.GetSize()); 2056 } 2057 2058 GDBRemoteCommunication::PacketResult 2059 GDBRemoteCommunicationServer::Handle_QEnvironment (StringExtractorGDBRemote &packet) 2060 { 2061 packet.SetFilePos(::strlen ("QEnvironment:")); 2062 const uint32_t bytes_left = packet.GetBytesLeft(); 2063 if (bytes_left > 0) 2064 { 2065 m_process_launch_info.GetEnvironmentEntries ().AppendArgument (packet.Peek()); 2066 return SendOKResponse (); 2067 } 2068 return SendErrorResponse (12); 2069 } 2070 2071 GDBRemoteCommunication::PacketResult 2072 GDBRemoteCommunicationServer::Handle_QLaunchArch (StringExtractorGDBRemote &packet) 2073 { 2074 packet.SetFilePos(::strlen ("QLaunchArch:")); 2075 const uint32_t bytes_left = packet.GetBytesLeft(); 2076 if (bytes_left > 0) 2077 { 2078 const char* arch_triple = packet.Peek(); 2079 ArchSpec arch_spec(arch_triple,NULL); 2080 m_process_launch_info.SetArchitecture(arch_spec); 2081 return SendOKResponse(); 2082 } 2083 return SendErrorResponse(13); 2084 } 2085 2086 GDBRemoteCommunication::PacketResult 2087 GDBRemoteCommunicationServer::Handle_QSetDisableASLR (StringExtractorGDBRemote &packet) 2088 { 2089 packet.SetFilePos(::strlen ("QSetDisableASLR:")); 2090 if (packet.GetU32(0)) 2091 m_process_launch_info.GetFlags().Set (eLaunchFlagDisableASLR); 2092 else 2093 m_process_launch_info.GetFlags().Clear (eLaunchFlagDisableASLR); 2094 return SendOKResponse (); 2095 } 2096 2097 GDBRemoteCommunication::PacketResult 2098 GDBRemoteCommunicationServer::Handle_QSetWorkingDir (StringExtractorGDBRemote &packet) 2099 { 2100 packet.SetFilePos(::strlen ("QSetWorkingDir:")); 2101 std::string path; 2102 packet.GetHexByteString(path); 2103 if (m_is_platform) 2104 { 2105 #ifdef _WIN32 2106 // Not implemented on Windows 2107 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_QSetWorkingDir unimplemented"); 2108 #else 2109 // If this packet is sent to a platform, then change the current working directory 2110 if (::chdir(path.c_str()) != 0) 2111 return SendErrorResponse(errno); 2112 #endif 2113 } 2114 else 2115 { 2116 m_process_launch_info.SwapWorkingDirectory (path); 2117 } 2118 return SendOKResponse (); 2119 } 2120 2121 GDBRemoteCommunication::PacketResult 2122 GDBRemoteCommunicationServer::Handle_qGetWorkingDir (StringExtractorGDBRemote &packet) 2123 { 2124 StreamString response; 2125 2126 if (m_is_platform) 2127 { 2128 // If this packet is sent to a platform, then change the current working directory 2129 char cwd[PATH_MAX]; 2130 if (getcwd(cwd, sizeof(cwd)) == NULL) 2131 { 2132 return SendErrorResponse(errno); 2133 } 2134 else 2135 { 2136 response.PutBytesAsRawHex8(cwd, strlen(cwd)); 2137 return SendPacketNoLock(response.GetData(), response.GetSize()); 2138 } 2139 } 2140 else 2141 { 2142 const char *working_dir = m_process_launch_info.GetWorkingDirectory(); 2143 if (working_dir && working_dir[0]) 2144 { 2145 response.PutBytesAsRawHex8(working_dir, strlen(working_dir)); 2146 return SendPacketNoLock(response.GetData(), response.GetSize()); 2147 } 2148 else 2149 { 2150 return SendErrorResponse(14); 2151 } 2152 } 2153 } 2154 2155 GDBRemoteCommunication::PacketResult 2156 GDBRemoteCommunicationServer::Handle_QSetSTDIN (StringExtractorGDBRemote &packet) 2157 { 2158 packet.SetFilePos(::strlen ("QSetSTDIN:")); 2159 FileAction file_action; 2160 std::string path; 2161 packet.GetHexByteString(path); 2162 const bool read = false; 2163 const bool write = true; 2164 if (file_action.Open(STDIN_FILENO, path.c_str(), read, write)) 2165 { 2166 m_process_launch_info.AppendFileAction(file_action); 2167 return SendOKResponse (); 2168 } 2169 return SendErrorResponse (15); 2170 } 2171 2172 GDBRemoteCommunication::PacketResult 2173 GDBRemoteCommunicationServer::Handle_QSetSTDOUT (StringExtractorGDBRemote &packet) 2174 { 2175 packet.SetFilePos(::strlen ("QSetSTDOUT:")); 2176 FileAction file_action; 2177 std::string path; 2178 packet.GetHexByteString(path); 2179 const bool read = true; 2180 const bool write = false; 2181 if (file_action.Open(STDOUT_FILENO, path.c_str(), read, write)) 2182 { 2183 m_process_launch_info.AppendFileAction(file_action); 2184 return SendOKResponse (); 2185 } 2186 return SendErrorResponse (16); 2187 } 2188 2189 GDBRemoteCommunication::PacketResult 2190 GDBRemoteCommunicationServer::Handle_QSetSTDERR (StringExtractorGDBRemote &packet) 2191 { 2192 packet.SetFilePos(::strlen ("QSetSTDERR:")); 2193 FileAction file_action; 2194 std::string path; 2195 packet.GetHexByteString(path); 2196 const bool read = true; 2197 const bool write = false; 2198 if (file_action.Open(STDERR_FILENO, path.c_str(), read, write)) 2199 { 2200 m_process_launch_info.AppendFileAction(file_action); 2201 return SendOKResponse (); 2202 } 2203 return SendErrorResponse (17); 2204 } 2205 2206 GDBRemoteCommunication::PacketResult 2207 GDBRemoteCommunicationServer::Handle_C (StringExtractorGDBRemote &packet) 2208 { 2209 if (!IsGdbServer ()) 2210 return SendUnimplementedResponse (packet.GetStringRef().c_str()); 2211 2212 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD)); 2213 if (log) 2214 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__); 2215 2216 // Ensure we have a native process. 2217 if (!m_debugged_process_sp) 2218 { 2219 if (log) 2220 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__); 2221 return SendErrorResponse (0x36); 2222 } 2223 2224 // Pull out the signal number. 2225 packet.SetFilePos (::strlen ("C")); 2226 if (packet.GetBytesLeft () < 1) 2227 { 2228 // Shouldn't be using a C without a signal. 2229 return SendIllFormedResponse (packet, "C packet specified without signal."); 2230 } 2231 const uint32_t signo = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ()); 2232 if (signo == std::numeric_limits<uint32_t>::max ()) 2233 return SendIllFormedResponse (packet, "failed to parse signal number"); 2234 2235 // Handle optional continue address. 2236 if (packet.GetBytesLeft () > 0) 2237 { 2238 // FIXME add continue at address support for $C{signo}[;{continue-address}]. 2239 if (*packet.Peek () == ';') 2240 return SendUnimplementedResponse (packet.GetStringRef().c_str()); 2241 else 2242 return SendIllFormedResponse (packet, "unexpected content after $C{signal-number}"); 2243 } 2244 2245 lldb_private::ResumeActionList resume_actions (StateType::eStateRunning, 0); 2246 Error error; 2247 2248 // We have two branches: what to do if a continue thread is specified (in which case we target 2249 // sending the signal to that thread), or when we don't have a continue thread set (in which 2250 // case we send a signal to the process). 2251 2252 // TODO discuss with Greg Clayton, make sure this makes sense. 2253 2254 lldb::tid_t signal_tid = GetContinueThreadID (); 2255 if (signal_tid != LLDB_INVALID_THREAD_ID) 2256 { 2257 // The resume action for the continue thread (or all threads if a continue thread is not set). 2258 lldb_private::ResumeAction action = { GetContinueThreadID (), StateType::eStateRunning, static_cast<int> (signo) }; 2259 2260 // Add the action for the continue thread (or all threads when the continue thread isn't present). 2261 resume_actions.Append (action); 2262 } 2263 else 2264 { 2265 // Send the signal to the process since we weren't targeting a specific continue thread with the signal. 2266 error = m_debugged_process_sp->Signal (signo); 2267 if (error.Fail ()) 2268 { 2269 if (log) 2270 log->Printf ("GDBRemoteCommunicationServer::%s failed to send signal for process %" PRIu64 ": %s", 2271 __FUNCTION__, 2272 m_debugged_process_sp->GetID (), 2273 error.AsCString ()); 2274 2275 return SendErrorResponse (0x52); 2276 } 2277 } 2278 2279 // Resume the threads. 2280 error = m_debugged_process_sp->Resume (resume_actions); 2281 if (error.Fail ()) 2282 { 2283 if (log) 2284 log->Printf ("GDBRemoteCommunicationServer::%s failed to resume threads for process %" PRIu64 ": %s", 2285 __FUNCTION__, 2286 m_debugged_process_sp->GetID (), 2287 error.AsCString ()); 2288 2289 return SendErrorResponse (0x38); 2290 } 2291 2292 // Don't send an "OK" packet; response is the stopped/exited message. 2293 return PacketResult::Success; 2294 } 2295 2296 GDBRemoteCommunication::PacketResult 2297 GDBRemoteCommunicationServer::Handle_c (StringExtractorGDBRemote &packet, bool skip_file_pos_adjustment) 2298 { 2299 if (!IsGdbServer ()) 2300 return SendUnimplementedResponse (packet.GetStringRef().c_str()); 2301 2302 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD)); 2303 if (log) 2304 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__); 2305 2306 // We reuse this method in vCont - don't double adjust the file position. 2307 if (!skip_file_pos_adjustment) 2308 packet.SetFilePos (::strlen ("c")); 2309 2310 // For now just support all continue. 2311 const bool has_continue_address = (packet.GetBytesLeft () > 0); 2312 if (has_continue_address) 2313 { 2314 if (log) 2315 log->Printf ("GDBRemoteCommunicationServer::%s not implemented for c{address} variant [%s remains]", __FUNCTION__, packet.Peek ()); 2316 return SendUnimplementedResponse (packet.GetStringRef().c_str()); 2317 } 2318 2319 // Ensure we have a native process. 2320 if (!m_debugged_process_sp) 2321 { 2322 if (log) 2323 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__); 2324 return SendErrorResponse (0x36); 2325 } 2326 2327 // Build the ResumeActionList 2328 lldb_private::ResumeActionList actions (StateType::eStateRunning, 0); 2329 2330 Error error = m_debugged_process_sp->Resume (actions); 2331 if (error.Fail ()) 2332 { 2333 if (log) 2334 { 2335 log->Printf ("GDBRemoteCommunicationServer::%s c failed for process %" PRIu64 ": %s", 2336 __FUNCTION__, 2337 m_debugged_process_sp->GetID (), 2338 error.AsCString ()); 2339 } 2340 return SendErrorResponse (GDBRemoteServerError::eErrorResume); 2341 } 2342 2343 if (log) 2344 log->Printf ("GDBRemoteCommunicationServer::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ()); 2345 2346 // No response required from continue. 2347 return PacketResult::Success; 2348 } 2349 2350 GDBRemoteCommunication::PacketResult 2351 GDBRemoteCommunicationServer::Handle_vCont_actions (StringExtractorGDBRemote &packet) 2352 { 2353 if (!IsGdbServer ()) 2354 { 2355 // only llgs supports $vCont. 2356 return SendUnimplementedResponse (packet.GetStringRef().c_str()); 2357 } 2358 2359 // We handle $vCont messages for c. 2360 // TODO add C, s and S. 2361 StreamString response; 2362 response.Printf("vCont;c;C;s;S"); 2363 2364 return SendPacketNoLock(response.GetData(), response.GetSize()); 2365 } 2366 2367 GDBRemoteCommunication::PacketResult 2368 GDBRemoteCommunicationServer::Handle_vCont (StringExtractorGDBRemote &packet) 2369 { 2370 if (!IsGdbServer ()) 2371 { 2372 // only llgs supports $vCont 2373 return SendUnimplementedResponse (packet.GetStringRef().c_str()); 2374 } 2375 2376 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2377 if (log) 2378 log->Printf ("GDBRemoteCommunicationServer::%s handling vCont packet", __FUNCTION__); 2379 2380 packet.SetFilePos (::strlen ("vCont")); 2381 2382 // Check if this is all continue (no options or ";c"). 2383 if (!packet.GetBytesLeft () || (::strcmp (packet.Peek (), ";c") == 0)) 2384 { 2385 // Move the packet past the ";c". 2386 if (packet.GetBytesLeft ()) 2387 packet.SetFilePos (packet.GetFilePos () + ::strlen (";c")); 2388 2389 const bool skip_file_pos_adjustment = true; 2390 return Handle_c (packet, skip_file_pos_adjustment); 2391 } 2392 else if (::strcmp (packet.Peek (), ";s") == 0) 2393 { 2394 // Move past the ';', then do a simple 's'. 2395 packet.SetFilePos (packet.GetFilePos () + 1); 2396 return Handle_s (packet); 2397 } 2398 2399 // Ensure we have a native process. 2400 if (!m_debugged_process_sp) 2401 { 2402 if (log) 2403 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__); 2404 return SendErrorResponse (0x36); 2405 } 2406 2407 ResumeActionList thread_actions; 2408 2409 while (packet.GetBytesLeft () && *packet.Peek () == ';') 2410 { 2411 // Skip the semi-colon. 2412 packet.GetChar (); 2413 2414 // Build up the thread action. 2415 ResumeAction thread_action; 2416 thread_action.tid = LLDB_INVALID_THREAD_ID; 2417 thread_action.state = eStateInvalid; 2418 thread_action.signal = 0; 2419 2420 const char action = packet.GetChar (); 2421 switch (action) 2422 { 2423 case 'C': 2424 thread_action.signal = packet.GetHexMaxU32 (false, 0); 2425 if (thread_action.signal == 0) 2426 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet C action"); 2427 // Fall through to next case... 2428 2429 case 'c': 2430 // Continue 2431 thread_action.state = eStateRunning; 2432 break; 2433 2434 case 'S': 2435 thread_action.signal = packet.GetHexMaxU32 (false, 0); 2436 if (thread_action.signal == 0) 2437 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet S action"); 2438 // Fall through to next case... 2439 2440 case 's': 2441 // Step 2442 thread_action.state = eStateStepping; 2443 break; 2444 2445 default: 2446 return SendIllFormedResponse (packet, "Unsupported vCont action"); 2447 break; 2448 } 2449 2450 // Parse out optional :{thread-id} value. 2451 if (packet.GetBytesLeft () && (*packet.Peek () == ':')) 2452 { 2453 // Consume the separator. 2454 packet.GetChar (); 2455 2456 thread_action.tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID); 2457 if (thread_action.tid == LLDB_INVALID_THREAD_ID) 2458 return SendIllFormedResponse (packet, "Could not parse thread number in vCont packet"); 2459 } 2460 2461 thread_actions.Append (thread_action); 2462 } 2463 2464 // If a default action for all other threads wasn't mentioned 2465 // then we should stop the threads. 2466 thread_actions.SetDefaultThreadActionIfNeeded (eStateStopped, 0); 2467 2468 Error error = m_debugged_process_sp->Resume (thread_actions); 2469 if (error.Fail ()) 2470 { 2471 if (log) 2472 { 2473 log->Printf ("GDBRemoteCommunicationServer::%s vCont failed for process %" PRIu64 ": %s", 2474 __FUNCTION__, 2475 m_debugged_process_sp->GetID (), 2476 error.AsCString ()); 2477 } 2478 return SendErrorResponse (GDBRemoteServerError::eErrorResume); 2479 } 2480 2481 if (log) 2482 log->Printf ("GDBRemoteCommunicationServer::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ()); 2483 2484 // No response required from vCont. 2485 return PacketResult::Success; 2486 } 2487 2488 GDBRemoteCommunication::PacketResult 2489 GDBRemoteCommunicationServer::Handle_QStartNoAckMode (StringExtractorGDBRemote &packet) 2490 { 2491 // Send response first before changing m_send_acks to we ack this packet 2492 PacketResult packet_result = SendOKResponse (); 2493 m_send_acks = false; 2494 return packet_result; 2495 } 2496 2497 GDBRemoteCommunication::PacketResult 2498 GDBRemoteCommunicationServer::Handle_qPlatform_mkdir (StringExtractorGDBRemote &packet) 2499 { 2500 packet.SetFilePos(::strlen("qPlatform_mkdir:")); 2501 mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX); 2502 if (packet.GetChar() == ',') 2503 { 2504 std::string path; 2505 packet.GetHexByteString(path); 2506 Error error = FileSystem::MakeDirectory(path.c_str(), mode); 2507 if (error.Success()) 2508 return SendPacketNoLock ("OK", 2); 2509 else 2510 return SendErrorResponse(error.GetError()); 2511 } 2512 return SendErrorResponse(20); 2513 } 2514 2515 GDBRemoteCommunication::PacketResult 2516 GDBRemoteCommunicationServer::Handle_qPlatform_chmod (StringExtractorGDBRemote &packet) 2517 { 2518 packet.SetFilePos(::strlen("qPlatform_chmod:")); 2519 2520 mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX); 2521 if (packet.GetChar() == ',') 2522 { 2523 std::string path; 2524 packet.GetHexByteString(path); 2525 Error error = FileSystem::SetFilePermissions(path.c_str(), mode); 2526 if (error.Success()) 2527 return SendPacketNoLock ("OK", 2); 2528 else 2529 return SendErrorResponse(error.GetError()); 2530 } 2531 return SendErrorResponse(19); 2532 } 2533 2534 GDBRemoteCommunication::PacketResult 2535 GDBRemoteCommunicationServer::Handle_vFile_Open (StringExtractorGDBRemote &packet) 2536 { 2537 packet.SetFilePos(::strlen("vFile:open:")); 2538 std::string path; 2539 packet.GetHexByteStringTerminatedBy(path,','); 2540 if (!path.empty()) 2541 { 2542 if (packet.GetChar() == ',') 2543 { 2544 uint32_t flags = packet.GetHexMaxU32(false, 0); 2545 if (packet.GetChar() == ',') 2546 { 2547 mode_t mode = packet.GetHexMaxU32(false, 0600); 2548 Error error; 2549 int fd = ::open (path.c_str(), flags, mode); 2550 const int save_errno = fd == -1 ? errno : 0; 2551 StreamString response; 2552 response.PutChar('F'); 2553 response.Printf("%i", fd); 2554 if (save_errno) 2555 response.Printf(",%i", save_errno); 2556 return SendPacketNoLock(response.GetData(), response.GetSize()); 2557 } 2558 } 2559 } 2560 return SendErrorResponse(18); 2561 } 2562 2563 GDBRemoteCommunication::PacketResult 2564 GDBRemoteCommunicationServer::Handle_vFile_Close (StringExtractorGDBRemote &packet) 2565 { 2566 packet.SetFilePos(::strlen("vFile:close:")); 2567 int fd = packet.GetS32(-1); 2568 Error error; 2569 int err = -1; 2570 int save_errno = 0; 2571 if (fd >= 0) 2572 { 2573 err = close(fd); 2574 save_errno = err == -1 ? errno : 0; 2575 } 2576 else 2577 { 2578 save_errno = EINVAL; 2579 } 2580 StreamString response; 2581 response.PutChar('F'); 2582 response.Printf("%i", err); 2583 if (save_errno) 2584 response.Printf(",%i", save_errno); 2585 return SendPacketNoLock(response.GetData(), response.GetSize()); 2586 } 2587 2588 GDBRemoteCommunication::PacketResult 2589 GDBRemoteCommunicationServer::Handle_vFile_pRead (StringExtractorGDBRemote &packet) 2590 { 2591 #ifdef _WIN32 2592 // Not implemented on Windows 2593 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pRead() unimplemented"); 2594 #else 2595 StreamGDBRemote response; 2596 packet.SetFilePos(::strlen("vFile:pread:")); 2597 int fd = packet.GetS32(-1); 2598 if (packet.GetChar() == ',') 2599 { 2600 uint64_t count = packet.GetU64(UINT64_MAX); 2601 if (packet.GetChar() == ',') 2602 { 2603 uint64_t offset = packet.GetU64(UINT32_MAX); 2604 if (count == UINT64_MAX) 2605 { 2606 response.Printf("F-1:%i", EINVAL); 2607 return SendPacketNoLock(response.GetData(), response.GetSize()); 2608 } 2609 2610 std::string buffer(count, 0); 2611 const ssize_t bytes_read = ::pread (fd, &buffer[0], buffer.size(), offset); 2612 const int save_errno = bytes_read == -1 ? errno : 0; 2613 response.PutChar('F'); 2614 response.Printf("%zi", bytes_read); 2615 if (save_errno) 2616 response.Printf(",%i", save_errno); 2617 else 2618 { 2619 response.PutChar(';'); 2620 response.PutEscapedBytes(&buffer[0], bytes_read); 2621 } 2622 return SendPacketNoLock(response.GetData(), response.GetSize()); 2623 } 2624 } 2625 return SendErrorResponse(21); 2626 2627 #endif 2628 } 2629 2630 GDBRemoteCommunication::PacketResult 2631 GDBRemoteCommunicationServer::Handle_vFile_pWrite (StringExtractorGDBRemote &packet) 2632 { 2633 #ifdef _WIN32 2634 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pWrite() unimplemented"); 2635 #else 2636 packet.SetFilePos(::strlen("vFile:pwrite:")); 2637 2638 StreamGDBRemote response; 2639 response.PutChar('F'); 2640 2641 int fd = packet.GetU32(UINT32_MAX); 2642 if (packet.GetChar() == ',') 2643 { 2644 off_t offset = packet.GetU64(UINT32_MAX); 2645 if (packet.GetChar() == ',') 2646 { 2647 std::string buffer; 2648 if (packet.GetEscapedBinaryData(buffer)) 2649 { 2650 const ssize_t bytes_written = ::pwrite (fd, buffer.data(), buffer.size(), offset); 2651 const int save_errno = bytes_written == -1 ? errno : 0; 2652 response.Printf("%zi", bytes_written); 2653 if (save_errno) 2654 response.Printf(",%i", save_errno); 2655 } 2656 else 2657 { 2658 response.Printf ("-1,%i", EINVAL); 2659 } 2660 return SendPacketNoLock(response.GetData(), response.GetSize()); 2661 } 2662 } 2663 return SendErrorResponse(27); 2664 #endif 2665 } 2666 2667 GDBRemoteCommunication::PacketResult 2668 GDBRemoteCommunicationServer::Handle_vFile_Size (StringExtractorGDBRemote &packet) 2669 { 2670 packet.SetFilePos(::strlen("vFile:size:")); 2671 std::string path; 2672 packet.GetHexByteString(path); 2673 if (!path.empty()) 2674 { 2675 lldb::user_id_t retcode = FileSystem::GetFileSize(FileSpec(path.c_str(), false)); 2676 StreamString response; 2677 response.PutChar('F'); 2678 response.PutHex64(retcode); 2679 if (retcode == UINT64_MAX) 2680 { 2681 response.PutChar(','); 2682 response.PutHex64(retcode); // TODO: replace with Host::GetSyswideErrorCode() 2683 } 2684 return SendPacketNoLock(response.GetData(), response.GetSize()); 2685 } 2686 return SendErrorResponse(22); 2687 } 2688 2689 GDBRemoteCommunication::PacketResult 2690 GDBRemoteCommunicationServer::Handle_vFile_Mode (StringExtractorGDBRemote &packet) 2691 { 2692 packet.SetFilePos(::strlen("vFile:mode:")); 2693 std::string path; 2694 packet.GetHexByteString(path); 2695 if (!path.empty()) 2696 { 2697 Error error; 2698 const uint32_t mode = File::GetPermissions(path.c_str(), error); 2699 StreamString response; 2700 response.Printf("F%u", mode); 2701 if (mode == 0 || error.Fail()) 2702 response.Printf(",%i", (int)error.GetError()); 2703 return SendPacketNoLock(response.GetData(), response.GetSize()); 2704 } 2705 return SendErrorResponse(23); 2706 } 2707 2708 GDBRemoteCommunication::PacketResult 2709 GDBRemoteCommunicationServer::Handle_vFile_Exists (StringExtractorGDBRemote &packet) 2710 { 2711 packet.SetFilePos(::strlen("vFile:exists:")); 2712 std::string path; 2713 packet.GetHexByteString(path); 2714 if (!path.empty()) 2715 { 2716 bool retcode = FileSystem::GetFileExists(FileSpec(path.c_str(), false)); 2717 StreamString response; 2718 response.PutChar('F'); 2719 response.PutChar(','); 2720 if (retcode) 2721 response.PutChar('1'); 2722 else 2723 response.PutChar('0'); 2724 return SendPacketNoLock(response.GetData(), response.GetSize()); 2725 } 2726 return SendErrorResponse(24); 2727 } 2728 2729 GDBRemoteCommunication::PacketResult 2730 GDBRemoteCommunicationServer::Handle_vFile_symlink (StringExtractorGDBRemote &packet) 2731 { 2732 packet.SetFilePos(::strlen("vFile:symlink:")); 2733 std::string dst, src; 2734 packet.GetHexByteStringTerminatedBy(dst, ','); 2735 packet.GetChar(); // Skip ',' char 2736 packet.GetHexByteString(src); 2737 Error error = FileSystem::Symlink(src.c_str(), dst.c_str()); 2738 StreamString response; 2739 response.Printf("F%u,%u", error.GetError(), error.GetError()); 2740 return SendPacketNoLock(response.GetData(), response.GetSize()); 2741 } 2742 2743 GDBRemoteCommunication::PacketResult 2744 GDBRemoteCommunicationServer::Handle_vFile_unlink (StringExtractorGDBRemote &packet) 2745 { 2746 packet.SetFilePos(::strlen("vFile:unlink:")); 2747 std::string path; 2748 packet.GetHexByteString(path); 2749 Error error = FileSystem::Unlink(path.c_str()); 2750 StreamString response; 2751 response.Printf("F%u,%u", error.GetError(), error.GetError()); 2752 return SendPacketNoLock(response.GetData(), response.GetSize()); 2753 } 2754 2755 GDBRemoteCommunication::PacketResult 2756 GDBRemoteCommunicationServer::Handle_qPlatform_shell (StringExtractorGDBRemote &packet) 2757 { 2758 packet.SetFilePos(::strlen("qPlatform_shell:")); 2759 std::string path; 2760 std::string working_dir; 2761 packet.GetHexByteStringTerminatedBy(path,','); 2762 if (!path.empty()) 2763 { 2764 if (packet.GetChar() == ',') 2765 { 2766 // FIXME: add timeout to qPlatform_shell packet 2767 // uint32_t timeout = packet.GetHexMaxU32(false, 32); 2768 uint32_t timeout = 10; 2769 if (packet.GetChar() == ',') 2770 packet.GetHexByteString(working_dir); 2771 int status, signo; 2772 std::string output; 2773 Error err = Host::RunShellCommand(path.c_str(), 2774 working_dir.empty() ? NULL : working_dir.c_str(), 2775 &status, &signo, &output, timeout); 2776 StreamGDBRemote response; 2777 if (err.Fail()) 2778 { 2779 response.PutCString("F,"); 2780 response.PutHex32(UINT32_MAX); 2781 } 2782 else 2783 { 2784 response.PutCString("F,"); 2785 response.PutHex32(status); 2786 response.PutChar(','); 2787 response.PutHex32(signo); 2788 response.PutChar(','); 2789 response.PutEscapedBytes(output.c_str(), output.size()); 2790 } 2791 return SendPacketNoLock(response.GetData(), response.GetSize()); 2792 } 2793 } 2794 return SendErrorResponse(24); 2795 } 2796 2797 void 2798 GDBRemoteCommunicationServer::SetCurrentThreadID (lldb::tid_t tid) 2799 { 2800 assert (IsGdbServer () && "SetCurrentThreadID() called when not GdbServer code"); 2801 2802 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD)); 2803 if (log) 2804 log->Printf ("GDBRemoteCommunicationServer::%s setting current thread id to %" PRIu64, __FUNCTION__, tid); 2805 2806 m_current_tid = tid; 2807 if (m_debugged_process_sp) 2808 m_debugged_process_sp->SetCurrentThreadID (m_current_tid); 2809 } 2810 2811 void 2812 GDBRemoteCommunicationServer::SetContinueThreadID (lldb::tid_t tid) 2813 { 2814 assert (IsGdbServer () && "SetContinueThreadID() called when not GdbServer code"); 2815 2816 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD)); 2817 if (log) 2818 log->Printf ("GDBRemoteCommunicationServer::%s setting continue thread id to %" PRIu64, __FUNCTION__, tid); 2819 2820 m_continue_tid = tid; 2821 } 2822 2823 GDBRemoteCommunication::PacketResult 2824 GDBRemoteCommunicationServer::Handle_stop_reason (StringExtractorGDBRemote &packet) 2825 { 2826 // Handle the $? gdbremote command. 2827 if (!IsGdbServer ()) 2828 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_stop_reason() unimplemented"); 2829 2830 // If no process, indicate error 2831 if (!m_debugged_process_sp) 2832 return SendErrorResponse (02); 2833 2834 return SendStopReasonForState (m_debugged_process_sp->GetState (), true); 2835 } 2836 2837 GDBRemoteCommunication::PacketResult 2838 GDBRemoteCommunicationServer::SendStopReasonForState (lldb::StateType process_state, bool flush_on_exit) 2839 { 2840 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2841 2842 switch (process_state) 2843 { 2844 case eStateAttaching: 2845 case eStateLaunching: 2846 case eStateRunning: 2847 case eStateStepping: 2848 case eStateDetached: 2849 // NOTE: gdb protocol doc looks like it should return $OK 2850 // when everything is running (i.e. no stopped result). 2851 return PacketResult::Success; // Ignore 2852 2853 case eStateSuspended: 2854 case eStateStopped: 2855 case eStateCrashed: 2856 { 2857 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID (); 2858 // Make sure we set the current thread so g and p packets return 2859 // the data the gdb will expect. 2860 SetCurrentThreadID (tid); 2861 return SendStopReplyPacketForThread (tid); 2862 } 2863 2864 case eStateInvalid: 2865 case eStateUnloaded: 2866 case eStateExited: 2867 if (flush_on_exit) 2868 FlushInferiorOutput (); 2869 return SendWResponse(m_debugged_process_sp.get()); 2870 2871 default: 2872 if (log) 2873 { 2874 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", current state reporting not handled: %s", 2875 __FUNCTION__, 2876 m_debugged_process_sp->GetID (), 2877 StateAsCString (process_state)); 2878 } 2879 break; 2880 } 2881 2882 return SendErrorResponse (0); 2883 } 2884 2885 GDBRemoteCommunication::PacketResult 2886 GDBRemoteCommunicationServer::Handle_vFile_Stat (StringExtractorGDBRemote &packet) 2887 { 2888 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_Stat() unimplemented"); 2889 } 2890 2891 GDBRemoteCommunication::PacketResult 2892 GDBRemoteCommunicationServer::Handle_vFile_MD5 (StringExtractorGDBRemote &packet) 2893 { 2894 packet.SetFilePos(::strlen("vFile:MD5:")); 2895 std::string path; 2896 packet.GetHexByteString(path); 2897 if (!path.empty()) 2898 { 2899 uint64_t a,b; 2900 StreamGDBRemote response; 2901 if (FileSystem::CalculateMD5(FileSpec(path.c_str(), false), a, b) == false) 2902 { 2903 response.PutCString("F,"); 2904 response.PutCString("x"); 2905 } 2906 else 2907 { 2908 response.PutCString("F,"); 2909 response.PutHex64(a); 2910 response.PutHex64(b); 2911 } 2912 return SendPacketNoLock(response.GetData(), response.GetSize()); 2913 } 2914 return SendErrorResponse(25); 2915 } 2916 2917 GDBRemoteCommunication::PacketResult 2918 GDBRemoteCommunicationServer::Handle_qRegisterInfo (StringExtractorGDBRemote &packet) 2919 { 2920 // Ensure we're llgs. 2921 if (!IsGdbServer()) 2922 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_qRegisterInfo() unimplemented"); 2923 2924 // Fail if we don't have a current process. 2925 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 2926 return SendErrorResponse (68); 2927 2928 // Ensure we have a thread. 2929 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadAtIndex (0)); 2930 if (!thread_sp) 2931 return SendErrorResponse (69); 2932 2933 // Get the register context for the first thread. 2934 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ()); 2935 if (!reg_context_sp) 2936 return SendErrorResponse (69); 2937 2938 // Parse out the register number from the request. 2939 packet.SetFilePos (strlen("qRegisterInfo")); 2940 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ()); 2941 if (reg_index == std::numeric_limits<uint32_t>::max ()) 2942 return SendErrorResponse (69); 2943 2944 // Return the end of registers response if we've iterated one past the end of the register set. 2945 if (reg_index >= reg_context_sp->GetRegisterCount ()) 2946 return SendErrorResponse (69); 2947 2948 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index); 2949 if (!reg_info) 2950 return SendErrorResponse (69); 2951 2952 // Build the reginfos response. 2953 StreamGDBRemote response; 2954 2955 response.PutCString ("name:"); 2956 response.PutCString (reg_info->name); 2957 response.PutChar (';'); 2958 2959 if (reg_info->alt_name && reg_info->alt_name[0]) 2960 { 2961 response.PutCString ("alt-name:"); 2962 response.PutCString (reg_info->alt_name); 2963 response.PutChar (';'); 2964 } 2965 2966 response.Printf ("bitsize:%" PRIu32 ";offset:%" PRIu32 ";", reg_info->byte_size * 8, reg_info->byte_offset); 2967 2968 switch (reg_info->encoding) 2969 { 2970 case eEncodingUint: response.PutCString ("encoding:uint;"); break; 2971 case eEncodingSint: response.PutCString ("encoding:sint;"); break; 2972 case eEncodingIEEE754: response.PutCString ("encoding:ieee754;"); break; 2973 case eEncodingVector: response.PutCString ("encoding:vector;"); break; 2974 default: break; 2975 } 2976 2977 switch (reg_info->format) 2978 { 2979 case eFormatBinary: response.PutCString ("format:binary;"); break; 2980 case eFormatDecimal: response.PutCString ("format:decimal;"); break; 2981 case eFormatHex: response.PutCString ("format:hex;"); break; 2982 case eFormatFloat: response.PutCString ("format:float;"); break; 2983 case eFormatVectorOfSInt8: response.PutCString ("format:vector-sint8;"); break; 2984 case eFormatVectorOfUInt8: response.PutCString ("format:vector-uint8;"); break; 2985 case eFormatVectorOfSInt16: response.PutCString ("format:vector-sint16;"); break; 2986 case eFormatVectorOfUInt16: response.PutCString ("format:vector-uint16;"); break; 2987 case eFormatVectorOfSInt32: response.PutCString ("format:vector-sint32;"); break; 2988 case eFormatVectorOfUInt32: response.PutCString ("format:vector-uint32;"); break; 2989 case eFormatVectorOfFloat32: response.PutCString ("format:vector-float32;"); break; 2990 case eFormatVectorOfUInt128: response.PutCString ("format:vector-uint128;"); break; 2991 default: break; 2992 }; 2993 2994 const char *const register_set_name = reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index); 2995 if (register_set_name) 2996 { 2997 response.PutCString ("set:"); 2998 response.PutCString (register_set_name); 2999 response.PutChar (';'); 3000 } 3001 3002 if (reg_info->kinds[RegisterKind::eRegisterKindGCC] != LLDB_INVALID_REGNUM) 3003 response.Printf ("gcc:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindGCC]); 3004 3005 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM) 3006 response.Printf ("dwarf:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindDWARF]); 3007 3008 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric]) 3009 { 3010 case LLDB_REGNUM_GENERIC_PC: response.PutCString("generic:pc;"); break; 3011 case LLDB_REGNUM_GENERIC_SP: response.PutCString("generic:sp;"); break; 3012 case LLDB_REGNUM_GENERIC_FP: response.PutCString("generic:fp;"); break; 3013 case LLDB_REGNUM_GENERIC_RA: response.PutCString("generic:ra;"); break; 3014 case LLDB_REGNUM_GENERIC_FLAGS: response.PutCString("generic:flags;"); break; 3015 case LLDB_REGNUM_GENERIC_ARG1: response.PutCString("generic:arg1;"); break; 3016 case LLDB_REGNUM_GENERIC_ARG2: response.PutCString("generic:arg2;"); break; 3017 case LLDB_REGNUM_GENERIC_ARG3: response.PutCString("generic:arg3;"); break; 3018 case LLDB_REGNUM_GENERIC_ARG4: response.PutCString("generic:arg4;"); break; 3019 case LLDB_REGNUM_GENERIC_ARG5: response.PutCString("generic:arg5;"); break; 3020 case LLDB_REGNUM_GENERIC_ARG6: response.PutCString("generic:arg6;"); break; 3021 case LLDB_REGNUM_GENERIC_ARG7: response.PutCString("generic:arg7;"); break; 3022 case LLDB_REGNUM_GENERIC_ARG8: response.PutCString("generic:arg8;"); break; 3023 default: break; 3024 } 3025 3026 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) 3027 { 3028 response.PutCString ("container-regs:"); 3029 int i = 0; 3030 for (const uint32_t *reg_num = reg_info->value_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) 3031 { 3032 if (i > 0) 3033 response.PutChar (','); 3034 response.Printf ("%" PRIx32, *reg_num); 3035 } 3036 response.PutChar (';'); 3037 } 3038 3039 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) 3040 { 3041 response.PutCString ("invalidate-regs:"); 3042 int i = 0; 3043 for (const uint32_t *reg_num = reg_info->invalidate_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) 3044 { 3045 if (i > 0) 3046 response.PutChar (','); 3047 response.Printf ("%" PRIx32, *reg_num); 3048 } 3049 response.PutChar (';'); 3050 } 3051 3052 return SendPacketNoLock(response.GetData(), response.GetSize()); 3053 } 3054 3055 GDBRemoteCommunication::PacketResult 3056 GDBRemoteCommunicationServer::Handle_qfThreadInfo (StringExtractorGDBRemote &packet) 3057 { 3058 // Ensure we're llgs. 3059 if (!IsGdbServer()) 3060 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_qfThreadInfo() unimplemented"); 3061 3062 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 3063 3064 // Fail if we don't have a current process. 3065 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3066 { 3067 if (log) 3068 log->Printf ("GDBRemoteCommunicationServer::%s() no process (%s), returning OK", __FUNCTION__, m_debugged_process_sp ? "invalid process id" : "null m_debugged_process_sp"); 3069 return SendOKResponse (); 3070 } 3071 3072 StreamGDBRemote response; 3073 response.PutChar ('m'); 3074 3075 if (log) 3076 log->Printf ("GDBRemoteCommunicationServer::%s() starting thread iteration", __FUNCTION__); 3077 3078 NativeThreadProtocolSP thread_sp; 3079 uint32_t thread_index; 3080 for (thread_index = 0, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index); 3081 thread_sp; 3082 ++thread_index, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index)) 3083 { 3084 if (log) 3085 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); 3086 if (thread_index > 0) 3087 response.PutChar(','); 3088 response.Printf ("%" PRIx64, thread_sp->GetID ()); 3089 } 3090 3091 if (log) 3092 log->Printf ("GDBRemoteCommunicationServer::%s() finished thread iteration", __FUNCTION__); 3093 3094 return SendPacketNoLock(response.GetData(), response.GetSize()); 3095 } 3096 3097 GDBRemoteCommunication::PacketResult 3098 GDBRemoteCommunicationServer::Handle_qsThreadInfo (StringExtractorGDBRemote &packet) 3099 { 3100 // Ensure we're llgs. 3101 if (!IsGdbServer()) 3102 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_qsThreadInfo() unimplemented"); 3103 3104 // FIXME for now we return the full thread list in the initial packet and always do nothing here. 3105 return SendPacketNoLock ("l", 1); 3106 } 3107 3108 GDBRemoteCommunication::PacketResult 3109 GDBRemoteCommunicationServer::Handle_p (StringExtractorGDBRemote &packet) 3110 { 3111 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 3112 3113 // Ensure we're llgs. 3114 if (!IsGdbServer()) 3115 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_p() unimplemented"); 3116 3117 // Parse out the register number from the request. 3118 packet.SetFilePos (strlen("p")); 3119 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ()); 3120 if (reg_index == std::numeric_limits<uint32_t>::max ()) 3121 { 3122 if (log) 3123 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ()); 3124 return SendErrorResponse (0x15); 3125 } 3126 3127 // Get the thread to use. 3128 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet); 3129 if (!thread_sp) 3130 { 3131 if (log) 3132 log->Printf ("GDBRemoteCommunicationServer::%s failed, no thread available", __FUNCTION__); 3133 return SendErrorResponse (0x15); 3134 } 3135 3136 // Get the thread's register context. 3137 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ()); 3138 if (!reg_context_sp) 3139 { 3140 if (log) 3141 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 ()); 3142 return SendErrorResponse (0x15); 3143 } 3144 3145 // Return the end of registers response if we've iterated one past the end of the register set. 3146 if (reg_index >= reg_context_sp->GetRegisterCount ()) 3147 { 3148 if (log) 3149 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetRegisterCount ()); 3150 return SendErrorResponse (0x15); 3151 } 3152 3153 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index); 3154 if (!reg_info) 3155 { 3156 if (log) 3157 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index); 3158 return SendErrorResponse (0x15); 3159 } 3160 3161 // Build the reginfos response. 3162 StreamGDBRemote response; 3163 3164 // Retrieve the value 3165 RegisterValue reg_value; 3166 Error error = reg_context_sp->ReadRegister (reg_info, reg_value); 3167 if (error.Fail ()) 3168 { 3169 if (log) 3170 log->Printf ("GDBRemoteCommunicationServer::%s failed, read of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ()); 3171 return SendErrorResponse (0x15); 3172 } 3173 3174 const uint8_t *const data = reinterpret_cast<const uint8_t*> (reg_value.GetBytes ()); 3175 if (!data) 3176 { 3177 if (log) 3178 log->Printf ("GDBRemoteCommunicationServer::%s failed to get data bytes from requested register %" PRIu32, __FUNCTION__, reg_index); 3179 return SendErrorResponse (0x15); 3180 } 3181 3182 // FIXME flip as needed to get data in big/little endian format for this host. 3183 for (uint32_t i = 0; i < reg_value.GetByteSize (); ++i) 3184 response.PutHex8 (data[i]); 3185 3186 return SendPacketNoLock (response.GetData (), response.GetSize ()); 3187 } 3188 3189 GDBRemoteCommunication::PacketResult 3190 GDBRemoteCommunicationServer::Handle_P (StringExtractorGDBRemote &packet) 3191 { 3192 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 3193 3194 // Ensure we're llgs. 3195 if (!IsGdbServer()) 3196 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_P() unimplemented"); 3197 3198 // Ensure there is more content. 3199 if (packet.GetBytesLeft () < 1) 3200 return SendIllFormedResponse (packet, "Empty P packet"); 3201 3202 // Parse out the register number from the request. 3203 packet.SetFilePos (strlen("P")); 3204 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ()); 3205 if (reg_index == std::numeric_limits<uint32_t>::max ()) 3206 { 3207 if (log) 3208 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ()); 3209 return SendErrorResponse (0x29); 3210 } 3211 3212 // Note debugserver would send an E30 here. 3213 if ((packet.GetBytesLeft () < 1) || (packet.GetChar () != '=')) 3214 return SendIllFormedResponse (packet, "P packet missing '=' char after register number"); 3215 3216 // Get process architecture. 3217 ArchSpec process_arch; 3218 if (!m_debugged_process_sp || !m_debugged_process_sp->GetArchitecture (process_arch)) 3219 { 3220 if (log) 3221 log->Printf ("GDBRemoteCommunicationServer::%s failed to retrieve inferior architecture", __FUNCTION__); 3222 return SendErrorResponse (0x49); 3223 } 3224 3225 // Parse out the value. 3226 const uint64_t raw_value = packet.GetHexMaxU64 (process_arch.GetByteOrder () == lldb::eByteOrderLittle, std::numeric_limits<uint64_t>::max ()); 3227 3228 // Get the thread to use. 3229 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet); 3230 if (!thread_sp) 3231 { 3232 if (log) 3233 log->Printf ("GDBRemoteCommunicationServer::%s failed, no thread available (thread index 0)", __FUNCTION__); 3234 return SendErrorResponse (0x28); 3235 } 3236 3237 // Get the thread's register context. 3238 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ()); 3239 if (!reg_context_sp) 3240 { 3241 if (log) 3242 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 ()); 3243 return SendErrorResponse (0x15); 3244 } 3245 3246 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index); 3247 if (!reg_info) 3248 { 3249 if (log) 3250 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index); 3251 return SendErrorResponse (0x48); 3252 } 3253 3254 // Return the end of registers response if we've iterated one past the end of the register set. 3255 if (reg_index >= reg_context_sp->GetRegisterCount ()) 3256 { 3257 if (log) 3258 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetRegisterCount ()); 3259 return SendErrorResponse (0x47); 3260 } 3261 3262 3263 // Build the reginfos response. 3264 StreamGDBRemote response; 3265 3266 // FIXME Could be suffixed with a thread: parameter. 3267 // That thread then needs to be fed back into the reg context retrieval above. 3268 Error error = reg_context_sp->WriteRegisterFromUnsigned (reg_info, raw_value); 3269 if (error.Fail ()) 3270 { 3271 if (log) 3272 log->Printf ("GDBRemoteCommunicationServer::%s failed, write of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ()); 3273 return SendErrorResponse (0x32); 3274 } 3275 3276 return SendOKResponse(); 3277 } 3278 3279 GDBRemoteCommunicationServer::PacketResult 3280 GDBRemoteCommunicationServer::Handle_H (StringExtractorGDBRemote &packet) 3281 { 3282 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 3283 3284 // Ensure we're llgs. 3285 if (!IsGdbServer()) 3286 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_H() unimplemented"); 3287 3288 // Fail if we don't have a current process. 3289 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3290 { 3291 if (log) 3292 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3293 return SendErrorResponse (0x15); 3294 } 3295 3296 // Parse out which variant of $H is requested. 3297 packet.SetFilePos (strlen("H")); 3298 if (packet.GetBytesLeft () < 1) 3299 { 3300 if (log) 3301 log->Printf ("GDBRemoteCommunicationServer::%s failed, H command missing {g,c} variant", __FUNCTION__); 3302 return SendIllFormedResponse (packet, "H command missing {g,c} variant"); 3303 } 3304 3305 const char h_variant = packet.GetChar (); 3306 switch (h_variant) 3307 { 3308 case 'g': 3309 break; 3310 3311 case 'c': 3312 break; 3313 3314 default: 3315 if (log) 3316 log->Printf ("GDBRemoteCommunicationServer::%s failed, invalid $H variant %c", __FUNCTION__, h_variant); 3317 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g"); 3318 } 3319 3320 // Parse out the thread number. 3321 // FIXME return a parse success/fail value. All values are valid here. 3322 const lldb::tid_t tid = packet.GetHexMaxU64 (false, std::numeric_limits<lldb::tid_t>::max ()); 3323 3324 // Ensure we have the given thread when not specifying -1 (all threads) or 0 (any thread). 3325 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) 3326 { 3327 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid)); 3328 if (!thread_sp) 3329 { 3330 if (log) 3331 log->Printf ("GDBRemoteCommunicationServer::%s failed, tid %" PRIu64 " not found", __FUNCTION__, tid); 3332 return SendErrorResponse (0x15); 3333 } 3334 } 3335 3336 // Now switch the given thread type. 3337 switch (h_variant) 3338 { 3339 case 'g': 3340 SetCurrentThreadID (tid); 3341 break; 3342 3343 case 'c': 3344 SetContinueThreadID (tid); 3345 break; 3346 3347 default: 3348 assert (false && "unsupported $H variant - shouldn't get here"); 3349 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g"); 3350 } 3351 3352 return SendOKResponse(); 3353 } 3354 3355 GDBRemoteCommunicationServer::PacketResult 3356 GDBRemoteCommunicationServer::Handle_interrupt (StringExtractorGDBRemote &packet) 3357 { 3358 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 3359 3360 // Ensure we're llgs. 3361 if (!IsGdbServer()) 3362 { 3363 // Only supported on llgs 3364 return SendUnimplementedResponse (""); 3365 } 3366 3367 // Fail if we don't have a current process. 3368 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3369 { 3370 if (log) 3371 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3372 return SendErrorResponse (0x15); 3373 } 3374 3375 // Build the ResumeActionList - stop everything. 3376 lldb_private::ResumeActionList actions (StateType::eStateStopped, 0); 3377 3378 Error error = m_debugged_process_sp->Resume (actions); 3379 if (error.Fail ()) 3380 { 3381 if (log) 3382 { 3383 log->Printf ("GDBRemoteCommunicationServer::%s failed for process %" PRIu64 ": %s", 3384 __FUNCTION__, 3385 m_debugged_process_sp->GetID (), 3386 error.AsCString ()); 3387 } 3388 return SendErrorResponse (GDBRemoteServerError::eErrorResume); 3389 } 3390 3391 if (log) 3392 log->Printf ("GDBRemoteCommunicationServer::%s stopped process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ()); 3393 3394 // No response required from stop all. 3395 return PacketResult::Success; 3396 } 3397 3398 GDBRemoteCommunicationServer::PacketResult 3399 GDBRemoteCommunicationServer::Handle_m (StringExtractorGDBRemote &packet) 3400 { 3401 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3402 3403 // Ensure we're llgs. 3404 if (!IsGdbServer()) 3405 { 3406 // Only supported on llgs 3407 return SendUnimplementedResponse (""); 3408 } 3409 3410 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3411 { 3412 if (log) 3413 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3414 return SendErrorResponse (0x15); 3415 } 3416 3417 // Parse out the memory address. 3418 packet.SetFilePos (strlen("m")); 3419 if (packet.GetBytesLeft() < 1) 3420 return SendIllFormedResponse(packet, "Too short m packet"); 3421 3422 // Read the address. Punting on validation. 3423 // FIXME replace with Hex U64 read with no default value that fails on failed read. 3424 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0); 3425 3426 // Validate comma. 3427 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ',')) 3428 return SendIllFormedResponse(packet, "Comma sep missing in m packet"); 3429 3430 // Get # bytes to read. 3431 if (packet.GetBytesLeft() < 1) 3432 return SendIllFormedResponse(packet, "Length missing in m packet"); 3433 3434 const uint64_t byte_count = packet.GetHexMaxU64(false, 0); 3435 if (byte_count == 0) 3436 { 3437 if (log) 3438 log->Printf ("GDBRemoteCommunicationServer::%s nothing to read: zero-length packet", __FUNCTION__); 3439 return PacketResult::Success; 3440 } 3441 3442 // Allocate the response buffer. 3443 std::string buf(byte_count, '\0'); 3444 if (buf.empty()) 3445 return SendErrorResponse (0x78); 3446 3447 3448 // Retrieve the process memory. 3449 lldb::addr_t bytes_read = 0; 3450 lldb_private::Error error = m_debugged_process_sp->ReadMemory (read_addr, &buf[0], byte_count, bytes_read); 3451 if (error.Fail ()) 3452 { 3453 if (log) 3454 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to read. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, error.AsCString ()); 3455 return SendErrorResponse (0x08); 3456 } 3457 3458 if (bytes_read == 0) 3459 { 3460 if (log) 3461 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); 3462 return SendErrorResponse (0x08); 3463 } 3464 3465 StreamGDBRemote response; 3466 for (lldb::addr_t i = 0; i < bytes_read; ++i) 3467 response.PutHex8(buf[i]); 3468 3469 return SendPacketNoLock(response.GetData(), response.GetSize()); 3470 } 3471 3472 GDBRemoteCommunication::PacketResult 3473 GDBRemoteCommunicationServer::Handle_QSetDetachOnError (StringExtractorGDBRemote &packet) 3474 { 3475 packet.SetFilePos(::strlen ("QSetDetachOnError:")); 3476 if (packet.GetU32(0)) 3477 m_process_launch_info.GetFlags().Set (eLaunchFlagDetachOnError); 3478 else 3479 m_process_launch_info.GetFlags().Clear (eLaunchFlagDetachOnError); 3480 return SendOKResponse (); 3481 } 3482 3483 GDBRemoteCommunicationServer::PacketResult 3484 GDBRemoteCommunicationServer::Handle_M (StringExtractorGDBRemote &packet) 3485 { 3486 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3487 3488 // Ensure we're llgs. 3489 if (!IsGdbServer()) 3490 { 3491 // Only supported on llgs 3492 return SendUnimplementedResponse (""); 3493 } 3494 3495 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3496 { 3497 if (log) 3498 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3499 return SendErrorResponse (0x15); 3500 } 3501 3502 // Parse out the memory address. 3503 packet.SetFilePos (strlen("M")); 3504 if (packet.GetBytesLeft() < 1) 3505 return SendIllFormedResponse(packet, "Too short M packet"); 3506 3507 // Read the address. Punting on validation. 3508 // FIXME replace with Hex U64 read with no default value that fails on failed read. 3509 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0); 3510 3511 // Validate comma. 3512 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ',')) 3513 return SendIllFormedResponse(packet, "Comma sep missing in M packet"); 3514 3515 // Get # bytes to read. 3516 if (packet.GetBytesLeft() < 1) 3517 return SendIllFormedResponse(packet, "Length missing in M packet"); 3518 3519 const uint64_t byte_count = packet.GetHexMaxU64(false, 0); 3520 if (byte_count == 0) 3521 { 3522 if (log) 3523 log->Printf ("GDBRemoteCommunicationServer::%s nothing to write: zero-length packet", __FUNCTION__); 3524 return PacketResult::Success; 3525 } 3526 3527 // Validate colon. 3528 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':')) 3529 return SendIllFormedResponse(packet, "Comma sep missing in M packet after byte length"); 3530 3531 // Allocate the conversion buffer. 3532 std::vector<uint8_t> buf(byte_count, 0); 3533 if (buf.empty()) 3534 return SendErrorResponse (0x78); 3535 3536 // Convert the hex memory write contents to bytes. 3537 StreamGDBRemote response; 3538 const uint64_t convert_count = static_cast<uint64_t> (packet.GetHexBytes (&buf[0], byte_count, 0)); 3539 if (convert_count != byte_count) 3540 { 3541 if (log) 3542 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); 3543 return SendIllFormedResponse (packet, "M content byte length specified did not match hex-encoded content length"); 3544 } 3545 3546 // Write the process memory. 3547 lldb::addr_t bytes_written = 0; 3548 lldb_private::Error error = m_debugged_process_sp->WriteMemory (write_addr, &buf[0], byte_count, bytes_written); 3549 if (error.Fail ()) 3550 { 3551 if (log) 3552 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to write. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, error.AsCString ()); 3553 return SendErrorResponse (0x09); 3554 } 3555 3556 if (bytes_written == 0) 3557 { 3558 if (log) 3559 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); 3560 return SendErrorResponse (0x09); 3561 } 3562 3563 return SendOKResponse (); 3564 } 3565 3566 GDBRemoteCommunicationServer::PacketResult 3567 GDBRemoteCommunicationServer::Handle_qMemoryRegionInfoSupported (StringExtractorGDBRemote &packet) 3568 { 3569 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3570 3571 // We don't support if we're not llgs. 3572 if (!IsGdbServer()) 3573 return SendUnimplementedResponse (""); 3574 3575 // Currently only the NativeProcessProtocol knows if it can handle a qMemoryRegionInfoSupported 3576 // request, but we're not guaranteed to be attached to a process. For now we'll assume the 3577 // client only asks this when a process is being debugged. 3578 3579 // Ensure we have a process running; otherwise, we can't figure this out 3580 // since we won't have a NativeProcessProtocol. 3581 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3582 { 3583 if (log) 3584 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3585 return SendErrorResponse (0x15); 3586 } 3587 3588 // Test if we can get any region back when asking for the region around NULL. 3589 MemoryRegionInfo region_info; 3590 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (0, region_info); 3591 if (error.Fail ()) 3592 { 3593 // We don't support memory region info collection for this NativeProcessProtocol. 3594 return SendUnimplementedResponse (""); 3595 } 3596 3597 return SendOKResponse(); 3598 } 3599 3600 GDBRemoteCommunicationServer::PacketResult 3601 GDBRemoteCommunicationServer::Handle_qMemoryRegionInfo (StringExtractorGDBRemote &packet) 3602 { 3603 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3604 3605 // We don't support if we're not llgs. 3606 if (!IsGdbServer()) 3607 return SendUnimplementedResponse (""); 3608 3609 // Ensure we have a process. 3610 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3611 { 3612 if (log) 3613 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3614 return SendErrorResponse (0x15); 3615 } 3616 3617 // Parse out the memory address. 3618 packet.SetFilePos (strlen("qMemoryRegionInfo:")); 3619 if (packet.GetBytesLeft() < 1) 3620 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet"); 3621 3622 // Read the address. Punting on validation. 3623 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0); 3624 3625 StreamGDBRemote response; 3626 3627 // Get the memory region info for the target address. 3628 MemoryRegionInfo region_info; 3629 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (read_addr, region_info); 3630 if (error.Fail ()) 3631 { 3632 // Return the error message. 3633 3634 response.PutCString ("error:"); 3635 response.PutCStringAsRawHex8 (error.AsCString ()); 3636 response.PutChar (';'); 3637 } 3638 else 3639 { 3640 // Range start and size. 3641 response.Printf ("start:%" PRIx64 ";size:%" PRIx64 ";", region_info.GetRange ().GetRangeBase (), region_info.GetRange ().GetByteSize ()); 3642 3643 // Permissions. 3644 if (region_info.GetReadable () || 3645 region_info.GetWritable () || 3646 region_info.GetExecutable ()) 3647 { 3648 // Write permissions info. 3649 response.PutCString ("permissions:"); 3650 3651 if (region_info.GetReadable ()) 3652 response.PutChar ('r'); 3653 if (region_info.GetWritable ()) 3654 response.PutChar('w'); 3655 if (region_info.GetExecutable()) 3656 response.PutChar ('x'); 3657 3658 response.PutChar (';'); 3659 } 3660 } 3661 3662 return SendPacketNoLock(response.GetData(), response.GetSize()); 3663 } 3664 3665 GDBRemoteCommunicationServer::PacketResult 3666 GDBRemoteCommunicationServer::Handle_Z (StringExtractorGDBRemote &packet) 3667 { 3668 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); 3669 3670 // We don't support if we're not llgs. 3671 if (!IsGdbServer()) 3672 return SendUnimplementedResponse (""); 3673 3674 // Ensure we have a process. 3675 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3676 { 3677 if (log) 3678 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3679 return SendErrorResponse (0x15); 3680 } 3681 3682 // Parse out software or hardware breakpoint requested. 3683 packet.SetFilePos (strlen("Z")); 3684 if (packet.GetBytesLeft() < 1) 3685 return SendIllFormedResponse(packet, "Too short Z packet, missing software/hardware specifier"); 3686 3687 bool want_breakpoint = true; 3688 bool want_hardware = false; 3689 3690 const char breakpoint_type_char = packet.GetChar (); 3691 switch (breakpoint_type_char) 3692 { 3693 case '0': want_hardware = false; want_breakpoint = true; break; 3694 case '1': want_hardware = true; want_breakpoint = true; break; 3695 case '2': want_breakpoint = false; break; 3696 case '3': want_breakpoint = false; break; 3697 default: 3698 return SendIllFormedResponse(packet, "Z packet had invalid software/hardware specifier"); 3699 3700 } 3701 3702 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',') 3703 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after breakpoint type"); 3704 3705 // FIXME implement watchpoint support. 3706 if (!want_breakpoint) 3707 return SendUnimplementedResponse ("watchpoint support not yet implemented"); 3708 3709 // Parse out the breakpoint address. 3710 if (packet.GetBytesLeft() < 1) 3711 return SendIllFormedResponse(packet, "Too short Z packet, missing address"); 3712 const lldb::addr_t breakpoint_addr = packet.GetHexMaxU64(false, 0); 3713 3714 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',') 3715 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after address"); 3716 3717 // Parse out the breakpoint kind (i.e. size hint for opcode size). 3718 const uint32_t kind = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ()); 3719 if (kind == std::numeric_limits<uint32_t>::max ()) 3720 return SendIllFormedResponse(packet, "Malformed Z packet, failed to parse kind argument"); 3721 3722 if (want_breakpoint) 3723 { 3724 // Try to set the breakpoint. 3725 const Error error = m_debugged_process_sp->SetBreakpoint (breakpoint_addr, kind, want_hardware); 3726 if (error.Success ()) 3727 return SendOKResponse (); 3728 else 3729 { 3730 if (log) 3731 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to set breakpoint: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ()); 3732 return SendErrorResponse (0x09); 3733 } 3734 } 3735 3736 // FIXME fix up after watchpoints are handled. 3737 return SendUnimplementedResponse (""); 3738 } 3739 3740 GDBRemoteCommunicationServer::PacketResult 3741 GDBRemoteCommunicationServer::Handle_z (StringExtractorGDBRemote &packet) 3742 { 3743 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); 3744 3745 // We don't support if we're not llgs. 3746 if (!IsGdbServer()) 3747 return SendUnimplementedResponse (""); 3748 3749 // Ensure we have a process. 3750 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3751 { 3752 if (log) 3753 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3754 return SendErrorResponse (0x15); 3755 } 3756 3757 // Parse out software or hardware breakpoint requested. 3758 packet.SetFilePos (strlen("Z")); 3759 if (packet.GetBytesLeft() < 1) 3760 return SendIllFormedResponse(packet, "Too short z packet, missing software/hardware specifier"); 3761 3762 bool want_breakpoint = true; 3763 3764 const char breakpoint_type_char = packet.GetChar (); 3765 switch (breakpoint_type_char) 3766 { 3767 case '0': want_breakpoint = true; break; 3768 case '1': want_breakpoint = true; break; 3769 case '2': want_breakpoint = false; break; 3770 case '3': want_breakpoint = false; break; 3771 default: 3772 return SendIllFormedResponse(packet, "z packet had invalid software/hardware specifier"); 3773 3774 } 3775 3776 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',') 3777 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after breakpoint type"); 3778 3779 // FIXME implement watchpoint support. 3780 if (!want_breakpoint) 3781 return SendUnimplementedResponse ("watchpoint support not yet implemented"); 3782 3783 // Parse out the breakpoint address. 3784 if (packet.GetBytesLeft() < 1) 3785 return SendIllFormedResponse(packet, "Too short z packet, missing address"); 3786 const lldb::addr_t breakpoint_addr = packet.GetHexMaxU64(false, 0); 3787 3788 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',') 3789 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after address"); 3790 3791 // Parse out the breakpoint kind (i.e. size hint for opcode size). 3792 const uint32_t kind = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ()); 3793 if (kind == std::numeric_limits<uint32_t>::max ()) 3794 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse kind argument"); 3795 3796 if (want_breakpoint) 3797 { 3798 // Try to set the breakpoint. 3799 const Error error = m_debugged_process_sp->RemoveBreakpoint (breakpoint_addr); 3800 if (error.Success ()) 3801 return SendOKResponse (); 3802 else 3803 { 3804 if (log) 3805 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to remove breakpoint: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ()); 3806 return SendErrorResponse (0x09); 3807 } 3808 } 3809 3810 // FIXME fix up after watchpoints are handled. 3811 return SendUnimplementedResponse (""); 3812 } 3813 3814 GDBRemoteCommunicationServer::PacketResult 3815 GDBRemoteCommunicationServer::Handle_s (StringExtractorGDBRemote &packet) 3816 { 3817 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD)); 3818 3819 // We don't support if we're not llgs. 3820 if (!IsGdbServer()) 3821 return SendUnimplementedResponse (""); 3822 3823 // Ensure we have a process. 3824 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3825 { 3826 if (log) 3827 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3828 return SendErrorResponse (0x32); 3829 } 3830 3831 // We first try to use a continue thread id. If any one or any all set, use the current thread. 3832 // Bail out if we don't have a thread id. 3833 lldb::tid_t tid = GetContinueThreadID (); 3834 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID) 3835 tid = GetCurrentThreadID (); 3836 if (tid == LLDB_INVALID_THREAD_ID) 3837 return SendErrorResponse (0x33); 3838 3839 // Double check that we have such a thread. 3840 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here. 3841 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID (tid); 3842 if (!thread_sp || thread_sp->GetID () != tid) 3843 return SendErrorResponse (0x33); 3844 3845 // Create the step action for the given thread. 3846 lldb_private::ResumeAction action = { tid, eStateStepping, 0 }; 3847 3848 // Setup the actions list. 3849 lldb_private::ResumeActionList actions; 3850 actions.Append (action); 3851 3852 // All other threads stop while we're single stepping a thread. 3853 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0); 3854 Error error = m_debugged_process_sp->Resume (actions); 3855 if (error.Fail ()) 3856 { 3857 if (log) 3858 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " Resume() failed with error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), tid, error.AsCString ()); 3859 return SendErrorResponse(0x49); 3860 } 3861 3862 // No response here - the stop or exit will come from the resulting action. 3863 return PacketResult::Success; 3864 } 3865 3866 GDBRemoteCommunicationServer::PacketResult 3867 GDBRemoteCommunicationServer::Handle_qSupported (StringExtractorGDBRemote &packet) 3868 { 3869 StreamGDBRemote response; 3870 3871 // Features common to lldb-platform and llgs. 3872 uint32_t max_packet_size = 128 * 1024; // 128KBytes is a reasonable max packet size--debugger can always use less 3873 response.Printf ("PacketSize=%x", max_packet_size); 3874 3875 response.PutCString (";QStartNoAckMode+"); 3876 response.PutCString (";QThreadSuffixSupported+"); 3877 response.PutCString (";QListThreadsInStopReply+"); 3878 #if defined(__linux__) 3879 response.PutCString (";qXfer:auxv:read+"); 3880 #endif 3881 3882 return SendPacketNoLock(response.GetData(), response.GetSize()); 3883 } 3884 3885 GDBRemoteCommunicationServer::PacketResult 3886 GDBRemoteCommunicationServer::Handle_QThreadSuffixSupported (StringExtractorGDBRemote &packet) 3887 { 3888 m_thread_suffix_supported = true; 3889 return SendOKResponse(); 3890 } 3891 3892 GDBRemoteCommunicationServer::PacketResult 3893 GDBRemoteCommunicationServer::Handle_QListThreadsInStopReply (StringExtractorGDBRemote &packet) 3894 { 3895 m_list_threads_in_stop_reply = true; 3896 return SendOKResponse(); 3897 } 3898 3899 GDBRemoteCommunicationServer::PacketResult 3900 GDBRemoteCommunicationServer::Handle_qXfer_auxv_read (StringExtractorGDBRemote &packet) 3901 { 3902 // We don't support if we're not llgs. 3903 if (!IsGdbServer()) 3904 return SendUnimplementedResponse ("only supported for lldb-gdbserver"); 3905 3906 // *BSD impls should be able to do this too. 3907 #if defined(__linux__) 3908 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3909 3910 // Parse out the offset. 3911 packet.SetFilePos (strlen("qXfer:auxv:read::")); 3912 if (packet.GetBytesLeft () < 1) 3913 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset"); 3914 3915 const uint64_t auxv_offset = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ()); 3916 if (auxv_offset == std::numeric_limits<uint64_t>::max ()) 3917 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset"); 3918 3919 // Parse out comma. 3920 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ',') 3921 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing comma after offset"); 3922 3923 // Parse out the length. 3924 const uint64_t auxv_length = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ()); 3925 if (auxv_length == std::numeric_limits<uint64_t>::max ()) 3926 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing length"); 3927 3928 // Grab the auxv data if we need it. 3929 if (!m_active_auxv_buffer_sp) 3930 { 3931 // Make sure we have a valid process. 3932 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3933 { 3934 if (log) 3935 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3936 return SendErrorResponse (0x10); 3937 } 3938 3939 // Grab the auxv data. 3940 m_active_auxv_buffer_sp = Host::GetAuxvData (m_debugged_process_sp->GetID ()); 3941 if (!m_active_auxv_buffer_sp || m_active_auxv_buffer_sp->GetByteSize () == 0) 3942 { 3943 // Hmm, no auxv data, call that an error. 3944 if (log) 3945 log->Printf ("GDBRemoteCommunicationServer::%s failed, no auxv data retrieved", __FUNCTION__); 3946 m_active_auxv_buffer_sp.reset (); 3947 return SendErrorResponse (0x11); 3948 } 3949 } 3950 3951 // FIXME find out if/how I lock the stream here. 3952 3953 StreamGDBRemote response; 3954 bool done_with_buffer = false; 3955 3956 if (auxv_offset >= m_active_auxv_buffer_sp->GetByteSize ()) 3957 { 3958 // We have nothing left to send. Mark the buffer as complete. 3959 response.PutChar ('l'); 3960 done_with_buffer = true; 3961 } 3962 else 3963 { 3964 // Figure out how many bytes are available starting at the given offset. 3965 const uint64_t bytes_remaining = m_active_auxv_buffer_sp->GetByteSize () - auxv_offset; 3966 3967 // Figure out how many bytes we're going to read. 3968 const uint64_t bytes_to_read = (auxv_length > bytes_remaining) ? bytes_remaining : auxv_length; 3969 3970 // Mark the response type according to whether we're reading the remainder of the auxv data. 3971 if (bytes_to_read >= bytes_remaining) 3972 { 3973 // There will be nothing left to read after this 3974 response.PutChar ('l'); 3975 done_with_buffer = true; 3976 } 3977 else 3978 { 3979 // There will still be bytes to read after this request. 3980 response.PutChar ('m'); 3981 } 3982 3983 // Now write the data in encoded binary form. 3984 response.PutEscapedBytes (m_active_auxv_buffer_sp->GetBytes () + auxv_offset, bytes_to_read); 3985 } 3986 3987 if (done_with_buffer) 3988 m_active_auxv_buffer_sp.reset (); 3989 3990 return SendPacketNoLock(response.GetData(), response.GetSize()); 3991 #else 3992 return SendUnimplementedResponse ("not implemented on this platform"); 3993 #endif 3994 } 3995 3996 GDBRemoteCommunicationServer::PacketResult 3997 GDBRemoteCommunicationServer::Handle_QSaveRegisterState (StringExtractorGDBRemote &packet) 3998 { 3999 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 4000 4001 // We don't support if we're not llgs. 4002 if (!IsGdbServer()) 4003 return SendUnimplementedResponse ("only supported for lldb-gdbserver"); 4004 4005 // Move past packet name. 4006 packet.SetFilePos (strlen ("QSaveRegisterState")); 4007 4008 // Get the thread to use. 4009 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet); 4010 if (!thread_sp) 4011 { 4012 if (m_thread_suffix_supported) 4013 return SendIllFormedResponse (packet, "No thread specified in QSaveRegisterState packet"); 4014 else 4015 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet"); 4016 } 4017 4018 // Grab the register context for the thread. 4019 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ()); 4020 if (!reg_context_sp) 4021 { 4022 if (log) 4023 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 ()); 4024 return SendErrorResponse (0x15); 4025 } 4026 4027 // Save registers to a buffer. 4028 DataBufferSP register_data_sp; 4029 Error error = reg_context_sp->ReadAllRegisterValues (register_data_sp); 4030 if (error.Fail ()) 4031 { 4032 if (log) 4033 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to save all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ()); 4034 return SendErrorResponse (0x75); 4035 } 4036 4037 // Allocate a new save id. 4038 const uint32_t save_id = GetNextSavedRegistersID (); 4039 assert ((m_saved_registers_map.find (save_id) == m_saved_registers_map.end ()) && "GetNextRegisterSaveID() returned an existing register save id"); 4040 4041 // Save the register data buffer under the save id. 4042 { 4043 Mutex::Locker locker (m_saved_registers_mutex); 4044 m_saved_registers_map[save_id] = register_data_sp; 4045 } 4046 4047 // Write the response. 4048 StreamGDBRemote response; 4049 response.Printf ("%" PRIu32, save_id); 4050 return SendPacketNoLock(response.GetData(), response.GetSize()); 4051 } 4052 4053 GDBRemoteCommunicationServer::PacketResult 4054 GDBRemoteCommunicationServer::Handle_QRestoreRegisterState (StringExtractorGDBRemote &packet) 4055 { 4056 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 4057 4058 // We don't support if we're not llgs. 4059 if (!IsGdbServer()) 4060 return SendUnimplementedResponse ("only supported for lldb-gdbserver"); 4061 4062 // Parse out save id. 4063 packet.SetFilePos (strlen ("QRestoreRegisterState:")); 4064 if (packet.GetBytesLeft () < 1) 4065 return SendIllFormedResponse (packet, "QRestoreRegisterState packet missing register save id"); 4066 4067 const uint32_t save_id = packet.GetU32 (0); 4068 if (save_id == 0) 4069 { 4070 if (log) 4071 log->Printf ("GDBRemoteCommunicationServer::%s QRestoreRegisterState packet has malformed save id, expecting decimal uint32_t", __FUNCTION__); 4072 return SendErrorResponse (0x76); 4073 } 4074 4075 // Get the thread to use. 4076 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet); 4077 if (!thread_sp) 4078 { 4079 if (m_thread_suffix_supported) 4080 return SendIllFormedResponse (packet, "No thread specified in QRestoreRegisterState packet"); 4081 else 4082 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet"); 4083 } 4084 4085 // Grab the register context for the thread. 4086 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ()); 4087 if (!reg_context_sp) 4088 { 4089 if (log) 4090 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 ()); 4091 return SendErrorResponse (0x15); 4092 } 4093 4094 // Retrieve register state buffer, then remove from the list. 4095 DataBufferSP register_data_sp; 4096 { 4097 Mutex::Locker locker (m_saved_registers_mutex); 4098 4099 // Find the register set buffer for the given save id. 4100 auto it = m_saved_registers_map.find (save_id); 4101 if (it == m_saved_registers_map.end ()) 4102 { 4103 if (log) 4104 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); 4105 return SendErrorResponse (0x77); 4106 } 4107 register_data_sp = it->second; 4108 4109 // Remove it from the map. 4110 m_saved_registers_map.erase (it); 4111 } 4112 4113 Error error = reg_context_sp->WriteAllRegisterValues (register_data_sp); 4114 if (error.Fail ()) 4115 { 4116 if (log) 4117 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to restore all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ()); 4118 return SendErrorResponse (0x77); 4119 } 4120 4121 return SendOKResponse(); 4122 } 4123 4124 GDBRemoteCommunicationServer::PacketResult 4125 GDBRemoteCommunicationServer::Handle_vAttach (StringExtractorGDBRemote &packet) 4126 { 4127 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 4128 4129 // We don't support if we're not llgs. 4130 if (!IsGdbServer()) 4131 return SendUnimplementedResponse ("only supported for lldb-gdbserver"); 4132 4133 // Consume the ';' after vAttach. 4134 packet.SetFilePos (strlen ("vAttach")); 4135 if (!packet.GetBytesLeft () || packet.GetChar () != ';') 4136 return SendIllFormedResponse (packet, "vAttach missing expected ';'"); 4137 4138 // Grab the PID to which we will attach (assume hex encoding). 4139 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16); 4140 if (pid == LLDB_INVALID_PROCESS_ID) 4141 return SendIllFormedResponse (packet, "vAttach failed to parse the process id"); 4142 4143 // Attempt to attach. 4144 if (log) 4145 log->Printf ("GDBRemoteCommunicationServer::%s attempting to attach to pid %" PRIu64, __FUNCTION__, pid); 4146 4147 Error error = AttachToProcess (pid); 4148 4149 if (error.Fail ()) 4150 { 4151 if (log) 4152 log->Printf ("GDBRemoteCommunicationServer::%s failed to attach to pid %" PRIu64 ": %s\n", __FUNCTION__, pid, error.AsCString()); 4153 return SendErrorResponse (0x01); 4154 } 4155 4156 // Notify we attached by sending a stop packet. 4157 return SendStopReasonForState (m_debugged_process_sp->GetState (), true); 4158 4159 return PacketResult::Success; 4160 } 4161 4162 void 4163 GDBRemoteCommunicationServer::FlushInferiorOutput () 4164 { 4165 // If we're not monitoring an inferior's terminal, ignore this. 4166 if (!m_stdio_communication.IsConnected()) 4167 return; 4168 4169 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 4170 if (log) 4171 log->Printf ("GDBRemoteCommunicationServer::%s() called", __FUNCTION__); 4172 4173 // FIXME implement a timeout on the join. 4174 m_stdio_communication.JoinReadThread(); 4175 } 4176 4177 void 4178 GDBRemoteCommunicationServer::MaybeCloseInferiorTerminalConnection () 4179 { 4180 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 4181 4182 // Tell the stdio connection to shut down. 4183 if (m_stdio_communication.IsConnected()) 4184 { 4185 auto connection = m_stdio_communication.GetConnection(); 4186 if (connection) 4187 { 4188 Error error; 4189 connection->Disconnect (&error); 4190 4191 if (error.Success ()) 4192 { 4193 if (log) 4194 log->Printf ("GDBRemoteCommunicationServer::%s disconnect process terminal stdio - SUCCESS", __FUNCTION__); 4195 } 4196 else 4197 { 4198 if (log) 4199 log->Printf ("GDBRemoteCommunicationServer::%s disconnect process terminal stdio - FAIL: %s", __FUNCTION__, error.AsCString ()); 4200 } 4201 } 4202 } 4203 } 4204 4205 4206 lldb_private::NativeThreadProtocolSP 4207 GDBRemoteCommunicationServer::GetThreadFromSuffix (StringExtractorGDBRemote &packet) 4208 { 4209 NativeThreadProtocolSP thread_sp; 4210 4211 // We have no thread if we don't have a process. 4212 if (!m_debugged_process_sp || m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID) 4213 return thread_sp; 4214 4215 // If the client hasn't asked for thread suffix support, there will not be a thread suffix. 4216 // Use the current thread in that case. 4217 if (!m_thread_suffix_supported) 4218 { 4219 const lldb::tid_t current_tid = GetCurrentThreadID (); 4220 if (current_tid == LLDB_INVALID_THREAD_ID) 4221 return thread_sp; 4222 else if (current_tid == 0) 4223 { 4224 // Pick a thread. 4225 return m_debugged_process_sp->GetThreadAtIndex (0); 4226 } 4227 else 4228 return m_debugged_process_sp->GetThreadByID (current_tid); 4229 } 4230 4231 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 4232 4233 // Parse out the ';'. 4234 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ';') 4235 { 4236 if (log) 4237 log->Printf ("GDBRemoteCommunicationServer::%s gdb-remote parse error: expected ';' prior to start of thread suffix: packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ()); 4238 return thread_sp; 4239 } 4240 4241 if (!packet.GetBytesLeft ()) 4242 return thread_sp; 4243 4244 // Parse out thread: portion. 4245 if (strncmp (packet.Peek (), "thread:", strlen("thread:")) != 0) 4246 { 4247 if (log) 4248 log->Printf ("GDBRemoteCommunicationServer::%s gdb-remote parse error: expected 'thread:' but not found, packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ()); 4249 return thread_sp; 4250 } 4251 packet.SetFilePos (packet.GetFilePos () + strlen("thread:")); 4252 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0); 4253 if (tid != 0) 4254 return m_debugged_process_sp->GetThreadByID (tid); 4255 4256 return thread_sp; 4257 } 4258 4259 lldb::tid_t 4260 GDBRemoteCommunicationServer::GetCurrentThreadID () const 4261 { 4262 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) 4263 { 4264 // Use whatever the debug process says is the current thread id 4265 // since the protocol either didn't specify or specified we want 4266 // any/all threads marked as the current thread. 4267 if (!m_debugged_process_sp) 4268 return LLDB_INVALID_THREAD_ID; 4269 return m_debugged_process_sp->GetCurrentThreadID (); 4270 } 4271 // Use the specific current thread id set by the gdb remote protocol. 4272 return m_current_tid; 4273 } 4274 4275 uint32_t 4276 GDBRemoteCommunicationServer::GetNextSavedRegistersID () 4277 { 4278 Mutex::Locker locker (m_saved_registers_mutex); 4279 return m_next_saved_registers_id++; 4280 } 4281 4282