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