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