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