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