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