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