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