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 } 1456 else 1457 return SendUnimplementedResponse (packet.GetStringRef ().c_str ()); 1458 1459 if (pid == LLDB_INVALID_PROCESS_ID) 1460 return SendErrorResponse (1); 1461 1462 ProcessInstanceInfo proc_info; 1463 if (!Host::GetProcessInfo (pid, proc_info)) 1464 return SendErrorResponse (1); 1465 1466 StreamString response; 1467 CreateProcessInfoResponse_DebugServerStyle(proc_info, response); 1468 return SendPacketNoLock (response.GetData (), response.GetSize ()); 1469 } 1470 1471 GDBRemoteCommunication::PacketResult 1472 GDBRemoteCommunicationServer::Handle_qProcessInfoPID (StringExtractorGDBRemote &packet) 1473 { 1474 // Packet format: "qProcessInfoPID:%i" where %i is the pid 1475 packet.SetFilePos(::strlen ("qProcessInfoPID:")); 1476 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID); 1477 if (pid != LLDB_INVALID_PROCESS_ID) 1478 { 1479 ProcessInstanceInfo proc_info; 1480 if (Host::GetProcessInfo(pid, proc_info)) 1481 { 1482 StreamString response; 1483 CreateProcessInfoResponse (proc_info, response); 1484 return SendPacketNoLock (response.GetData(), response.GetSize()); 1485 } 1486 } 1487 return SendErrorResponse (1); 1488 } 1489 1490 GDBRemoteCommunication::PacketResult 1491 GDBRemoteCommunicationServer::Handle_qfProcessInfo (StringExtractorGDBRemote &packet) 1492 { 1493 m_proc_infos_index = 0; 1494 m_proc_infos.Clear(); 1495 1496 ProcessInstanceInfoMatch match_info; 1497 packet.SetFilePos(::strlen ("qfProcessInfo")); 1498 if (packet.GetChar() == ':') 1499 { 1500 1501 std::string key; 1502 std::string value; 1503 while (packet.GetNameColonValue(key, value)) 1504 { 1505 bool success = true; 1506 if (key.compare("name") == 0) 1507 { 1508 StringExtractor extractor; 1509 extractor.GetStringRef().swap(value); 1510 extractor.GetHexByteString (value); 1511 match_info.GetProcessInfo().GetExecutableFile().SetFile(value.c_str(), false); 1512 } 1513 else if (key.compare("name_match") == 0) 1514 { 1515 if (value.compare("equals") == 0) 1516 { 1517 match_info.SetNameMatchType (eNameMatchEquals); 1518 } 1519 else if (value.compare("starts_with") == 0) 1520 { 1521 match_info.SetNameMatchType (eNameMatchStartsWith); 1522 } 1523 else if (value.compare("ends_with") == 0) 1524 { 1525 match_info.SetNameMatchType (eNameMatchEndsWith); 1526 } 1527 else if (value.compare("contains") == 0) 1528 { 1529 match_info.SetNameMatchType (eNameMatchContains); 1530 } 1531 else if (value.compare("regex") == 0) 1532 { 1533 match_info.SetNameMatchType (eNameMatchRegularExpression); 1534 } 1535 else 1536 { 1537 success = false; 1538 } 1539 } 1540 else if (key.compare("pid") == 0) 1541 { 1542 match_info.GetProcessInfo().SetProcessID (StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0, &success)); 1543 } 1544 else if (key.compare("parent_pid") == 0) 1545 { 1546 match_info.GetProcessInfo().SetParentProcessID (StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0, &success)); 1547 } 1548 else if (key.compare("uid") == 0) 1549 { 1550 match_info.GetProcessInfo().SetUserID (StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0, &success)); 1551 } 1552 else if (key.compare("gid") == 0) 1553 { 1554 match_info.GetProcessInfo().SetGroupID (StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0, &success)); 1555 } 1556 else if (key.compare("euid") == 0) 1557 { 1558 match_info.GetProcessInfo().SetEffectiveUserID (StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0, &success)); 1559 } 1560 else if (key.compare("egid") == 0) 1561 { 1562 match_info.GetProcessInfo().SetEffectiveGroupID (StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0, &success)); 1563 } 1564 else if (key.compare("all_users") == 0) 1565 { 1566 match_info.SetMatchAllUsers(Args::StringToBoolean(value.c_str(), false, &success)); 1567 } 1568 else if (key.compare("triple") == 0) 1569 { 1570 match_info.GetProcessInfo().GetArchitecture().SetTriple (value.c_str(), NULL); 1571 } 1572 else 1573 { 1574 success = false; 1575 } 1576 1577 if (!success) 1578 return SendErrorResponse (2); 1579 } 1580 } 1581 1582 if (Host::FindProcesses (match_info, m_proc_infos)) 1583 { 1584 // We found something, return the first item by calling the get 1585 // subsequent process info packet handler... 1586 return Handle_qsProcessInfo (packet); 1587 } 1588 return SendErrorResponse (3); 1589 } 1590 1591 GDBRemoteCommunication::PacketResult 1592 GDBRemoteCommunicationServer::Handle_qsProcessInfo (StringExtractorGDBRemote &packet) 1593 { 1594 if (m_proc_infos_index < m_proc_infos.GetSize()) 1595 { 1596 StreamString response; 1597 CreateProcessInfoResponse (m_proc_infos.GetProcessInfoAtIndex(m_proc_infos_index), response); 1598 ++m_proc_infos_index; 1599 return SendPacketNoLock (response.GetData(), response.GetSize()); 1600 } 1601 return SendErrorResponse (4); 1602 } 1603 1604 GDBRemoteCommunication::PacketResult 1605 GDBRemoteCommunicationServer::Handle_qUserName (StringExtractorGDBRemote &packet) 1606 { 1607 #if !defined(LLDB_DISABLE_POSIX) 1608 // Packet format: "qUserName:%i" where %i is the uid 1609 packet.SetFilePos(::strlen ("qUserName:")); 1610 uint32_t uid = packet.GetU32 (UINT32_MAX); 1611 if (uid != UINT32_MAX) 1612 { 1613 std::string name; 1614 if (HostInfo::LookupUserName(uid, name)) 1615 { 1616 StreamString response; 1617 response.PutCStringAsRawHex8 (name.c_str()); 1618 return SendPacketNoLock (response.GetData(), response.GetSize()); 1619 } 1620 } 1621 #endif 1622 return SendErrorResponse (5); 1623 1624 } 1625 1626 GDBRemoteCommunication::PacketResult 1627 GDBRemoteCommunicationServer::Handle_qGroupName (StringExtractorGDBRemote &packet) 1628 { 1629 #if !defined(LLDB_DISABLE_POSIX) 1630 // Packet format: "qGroupName:%i" where %i is the gid 1631 packet.SetFilePos(::strlen ("qGroupName:")); 1632 uint32_t gid = packet.GetU32 (UINT32_MAX); 1633 if (gid != UINT32_MAX) 1634 { 1635 std::string name; 1636 if (HostInfo::LookupGroupName(gid, name)) 1637 { 1638 StreamString response; 1639 response.PutCStringAsRawHex8 (name.c_str()); 1640 return SendPacketNoLock (response.GetData(), response.GetSize()); 1641 } 1642 } 1643 #endif 1644 return SendErrorResponse (6); 1645 } 1646 1647 GDBRemoteCommunication::PacketResult 1648 GDBRemoteCommunicationServer::Handle_qSpeedTest (StringExtractorGDBRemote &packet) 1649 { 1650 packet.SetFilePos(::strlen ("qSpeedTest:")); 1651 1652 std::string key; 1653 std::string value; 1654 bool success = packet.GetNameColonValue(key, value); 1655 if (success && key.compare("response_size") == 0) 1656 { 1657 uint32_t response_size = StringConvert::ToUInt32(value.c_str(), 0, 0, &success); 1658 if (success) 1659 { 1660 if (response_size == 0) 1661 return SendOKResponse(); 1662 StreamString response; 1663 uint32_t bytes_left = response_size; 1664 response.PutCString("data:"); 1665 while (bytes_left > 0) 1666 { 1667 if (bytes_left >= 26) 1668 { 1669 response.PutCString("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); 1670 bytes_left -= 26; 1671 } 1672 else 1673 { 1674 response.Printf ("%*.*s;", bytes_left, bytes_left, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); 1675 bytes_left = 0; 1676 } 1677 } 1678 return SendPacketNoLock (response.GetData(), response.GetSize()); 1679 } 1680 } 1681 return SendErrorResponse (7); 1682 } 1683 1684 // 1685 //static bool 1686 //WaitForProcessToSIGSTOP (const lldb::pid_t pid, const int timeout_in_seconds) 1687 //{ 1688 // const int time_delta_usecs = 100000; 1689 // const int num_retries = timeout_in_seconds/time_delta_usecs; 1690 // for (int i=0; i<num_retries; i++) 1691 // { 1692 // struct proc_bsdinfo bsd_info; 1693 // int error = ::proc_pidinfo (pid, PROC_PIDTBSDINFO, 1694 // (uint64_t) 0, 1695 // &bsd_info, 1696 // PROC_PIDTBSDINFO_SIZE); 1697 // 1698 // switch (error) 1699 // { 1700 // case EINVAL: 1701 // case ENOTSUP: 1702 // case ESRCH: 1703 // case EPERM: 1704 // return false; 1705 // 1706 // default: 1707 // break; 1708 // 1709 // case 0: 1710 // if (bsd_info.pbi_status == SSTOP) 1711 // return true; 1712 // } 1713 // ::usleep (time_delta_usecs); 1714 // } 1715 // return false; 1716 //} 1717 1718 GDBRemoteCommunication::PacketResult 1719 GDBRemoteCommunicationServer::Handle_A (StringExtractorGDBRemote &packet) 1720 { 1721 // The 'A' packet is the most over designed packet ever here with 1722 // redundant argument indexes, redundant argument lengths and needed hex 1723 // encoded argument string values. Really all that is needed is a comma 1724 // separated hex encoded argument value list, but we will stay true to the 1725 // documented version of the 'A' packet here... 1726 1727 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 1728 int actual_arg_index = 0; 1729 1730 packet.SetFilePos(1); // Skip the 'A' 1731 bool success = true; 1732 while (success && packet.GetBytesLeft() > 0) 1733 { 1734 // Decode the decimal argument string length. This length is the 1735 // number of hex nibbles in the argument string value. 1736 const uint32_t arg_len = packet.GetU32(UINT32_MAX); 1737 if (arg_len == UINT32_MAX) 1738 success = false; 1739 else 1740 { 1741 // Make sure the argument hex string length is followed by a comma 1742 if (packet.GetChar() != ',') 1743 success = false; 1744 else 1745 { 1746 // Decode the argument index. We ignore this really because 1747 // who would really send down the arguments in a random order??? 1748 const uint32_t arg_idx = packet.GetU32(UINT32_MAX); 1749 if (arg_idx == UINT32_MAX) 1750 success = false; 1751 else 1752 { 1753 // Make sure the argument index is followed by a comma 1754 if (packet.GetChar() != ',') 1755 success = false; 1756 else 1757 { 1758 // Decode the argument string value from hex bytes 1759 // back into a UTF8 string and make sure the length 1760 // matches the one supplied in the packet 1761 std::string arg; 1762 if (packet.GetHexByteStringFixedLength(arg, arg_len) != (arg_len / 2)) 1763 success = false; 1764 else 1765 { 1766 // If there are any bytes left 1767 if (packet.GetBytesLeft()) 1768 { 1769 if (packet.GetChar() != ',') 1770 success = false; 1771 } 1772 1773 if (success) 1774 { 1775 if (arg_idx == 0) 1776 m_process_launch_info.GetExecutableFile().SetFile(arg.c_str(), false); 1777 m_process_launch_info.GetArguments().AppendArgument(arg.c_str()); 1778 if (log) 1779 log->Printf ("GDBRemoteCommunicationServer::%s added arg %d: \"%s\"", __FUNCTION__, actual_arg_index, arg.c_str ()); 1780 ++actual_arg_index; 1781 } 1782 } 1783 } 1784 } 1785 } 1786 } 1787 } 1788 1789 if (success) 1790 { 1791 m_process_launch_error = LaunchProcess (); 1792 if (m_process_launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) 1793 { 1794 return SendOKResponse (); 1795 } 1796 else 1797 { 1798 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 1799 if (log) 1800 log->Printf("GDBRemoteCommunicationServer::%s failed to launch exe: %s", 1801 __FUNCTION__, 1802 m_process_launch_error.AsCString()); 1803 1804 } 1805 } 1806 return SendErrorResponse (8); 1807 } 1808 1809 GDBRemoteCommunication::PacketResult 1810 GDBRemoteCommunicationServer::Handle_qC (StringExtractorGDBRemote &packet) 1811 { 1812 StreamString response; 1813 1814 if (IsGdbServer ()) 1815 { 1816 // Fail if we don't have a current process. 1817 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 1818 return SendErrorResponse (68); 1819 1820 // Make sure we set the current thread so g and p packets return 1821 // the data the gdb will expect. 1822 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID (); 1823 SetCurrentThreadID (tid); 1824 1825 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread (); 1826 if (!thread_sp) 1827 return SendErrorResponse (69); 1828 1829 response.Printf ("QC%" PRIx64, thread_sp->GetID ()); 1830 } 1831 else 1832 { 1833 // NOTE: lldb should now be using qProcessInfo for process IDs. This path here 1834 // should not be used. It is reporting process id instead of thread id. The 1835 // correct answer doesn't seem to make much sense for lldb-platform. 1836 // CONSIDER: flip to "unsupported". 1837 lldb::pid_t pid = m_process_launch_info.GetProcessID(); 1838 response.Printf("QC%" PRIx64, pid); 1839 1840 // this should always be platform here 1841 assert (m_is_platform && "this code path should only be traversed for lldb-platform"); 1842 1843 if (m_is_platform) 1844 { 1845 // If we launch a process and this GDB server is acting as a platform, 1846 // then we need to clear the process launch state so we can start 1847 // launching another process. In order to launch a process a bunch or 1848 // packets need to be sent: environment packets, working directory, 1849 // disable ASLR, and many more settings. When we launch a process we 1850 // then need to know when to clear this information. Currently we are 1851 // selecting the 'qC' packet as that packet which seems to make the most 1852 // sense. 1853 if (pid != LLDB_INVALID_PROCESS_ID) 1854 { 1855 m_process_launch_info.Clear(); 1856 } 1857 } 1858 } 1859 return SendPacketNoLock (response.GetData(), response.GetSize()); 1860 } 1861 1862 bool 1863 GDBRemoteCommunicationServer::DebugserverProcessReaped (lldb::pid_t pid) 1864 { 1865 Mutex::Locker locker (m_spawned_pids_mutex); 1866 FreePortForProcess(pid); 1867 return m_spawned_pids.erase(pid) > 0; 1868 } 1869 bool 1870 GDBRemoteCommunicationServer::ReapDebugserverProcess (void *callback_baton, 1871 lldb::pid_t pid, 1872 bool exited, 1873 int signal, // Zero for no signal 1874 int status) // Exit value of process if signal is zero 1875 { 1876 GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton; 1877 server->DebugserverProcessReaped (pid); 1878 return true; 1879 } 1880 1881 bool 1882 GDBRemoteCommunicationServer::DebuggedProcessReaped (lldb::pid_t pid) 1883 { 1884 // reap a process that we were debugging (but not debugserver) 1885 Mutex::Locker locker (m_spawned_pids_mutex); 1886 return m_spawned_pids.erase(pid) > 0; 1887 } 1888 1889 bool 1890 GDBRemoteCommunicationServer::ReapDebuggedProcess (void *callback_baton, 1891 lldb::pid_t pid, 1892 bool exited, 1893 int signal, // Zero for no signal 1894 int status) // Exit value of process if signal is zero 1895 { 1896 GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton; 1897 server->DebuggedProcessReaped (pid); 1898 return true; 1899 } 1900 1901 GDBRemoteCommunication::PacketResult 1902 GDBRemoteCommunicationServer::Handle_qLaunchGDBServer (StringExtractorGDBRemote &packet) 1903 { 1904 #ifdef _WIN32 1905 return SendErrorResponse(9); 1906 #else 1907 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM)); 1908 1909 // Spawn a local debugserver as a platform so we can then attach or launch 1910 // a process... 1911 1912 if (m_is_platform) 1913 { 1914 if (log) 1915 log->Printf ("GDBRemoteCommunicationServer::%s() called", __FUNCTION__); 1916 1917 // Sleep and wait a bit for debugserver to start to listen... 1918 ConnectionFileDescriptor file_conn; 1919 std::string hostname; 1920 // TODO: /tmp/ should not be hardcoded. User might want to override /tmp 1921 // with the TMPDIR environment variable 1922 packet.SetFilePos(::strlen ("qLaunchGDBServer;")); 1923 std::string name; 1924 std::string value; 1925 uint16_t port = UINT16_MAX; 1926 while (packet.GetNameColonValue(name, value)) 1927 { 1928 if (name.compare ("host") == 0) 1929 hostname.swap(value); 1930 else if (name.compare ("port") == 0) 1931 port = StringConvert::ToUInt32(value.c_str(), 0, 0); 1932 } 1933 if (port == UINT16_MAX) 1934 port = GetNextAvailablePort(); 1935 1936 // Spawn a new thread to accept the port that gets bound after 1937 // binding to port 0 (zero). 1938 1939 // ignore the hostname send from the remote end, just use the ip address 1940 // that we're currently communicating with as the hostname 1941 1942 // Spawn a debugserver and try to get the port it listens to. 1943 ProcessLaunchInfo debugserver_launch_info; 1944 if (hostname.empty()) 1945 hostname = "127.0.0.1"; 1946 if (log) 1947 log->Printf("Launching debugserver with: %s:%u...\n", hostname.c_str(), port); 1948 1949 // Do not run in a new session so that it can not linger after the 1950 // platform closes. 1951 debugserver_launch_info.SetLaunchInSeparateProcessGroup(false); 1952 debugserver_launch_info.SetMonitorProcessCallback(ReapDebugserverProcess, this, false); 1953 1954 std::string platform_scheme; 1955 std::string platform_ip; 1956 int platform_port; 1957 std::string platform_path; 1958 bool ok = UriParser::Parse(GetConnection()->GetURI().c_str(), platform_scheme, platform_ip, platform_port, platform_path); 1959 assert(ok); 1960 Error error = StartDebugserverProcess ( 1961 platform_ip.c_str(), 1962 port, 1963 debugserver_launch_info, 1964 port); 1965 1966 lldb::pid_t debugserver_pid = debugserver_launch_info.GetProcessID(); 1967 1968 1969 if (debugserver_pid != LLDB_INVALID_PROCESS_ID) 1970 { 1971 Mutex::Locker locker (m_spawned_pids_mutex); 1972 m_spawned_pids.insert(debugserver_pid); 1973 if (port > 0) 1974 AssociatePortWithProcess(port, debugserver_pid); 1975 } 1976 else 1977 { 1978 if (port > 0) 1979 FreePort (port); 1980 } 1981 1982 if (error.Success()) 1983 { 1984 if (log) 1985 log->Printf ("GDBRemoteCommunicationServer::%s() debugserver launched successfully as pid %" PRIu64, __FUNCTION__, debugserver_pid); 1986 1987 char response[256]; 1988 const int response_len = ::snprintf (response, sizeof(response), "pid:%" PRIu64 ";port:%u;", debugserver_pid, port + m_port_offset); 1989 assert (response_len < (int)sizeof(response)); 1990 PacketResult packet_result = SendPacketNoLock (response, response_len); 1991 1992 if (packet_result != PacketResult::Success) 1993 { 1994 if (debugserver_pid != LLDB_INVALID_PROCESS_ID) 1995 ::kill (debugserver_pid, SIGINT); 1996 } 1997 return packet_result; 1998 } 1999 else 2000 { 2001 if (log) 2002 log->Printf ("GDBRemoteCommunicationServer::%s() debugserver launch failed: %s", __FUNCTION__, error.AsCString ()); 2003 } 2004 } 2005 return SendErrorResponse (9); 2006 #endif 2007 } 2008 2009 bool 2010 GDBRemoteCommunicationServer::KillSpawnedProcess (lldb::pid_t pid) 2011 { 2012 // make sure we know about this process 2013 { 2014 Mutex::Locker locker (m_spawned_pids_mutex); 2015 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) 2016 return false; 2017 } 2018 2019 // first try a SIGTERM (standard kill) 2020 Host::Kill (pid, SIGTERM); 2021 2022 // check if that worked 2023 for (size_t i=0; i<10; ++i) 2024 { 2025 { 2026 Mutex::Locker locker (m_spawned_pids_mutex); 2027 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) 2028 { 2029 // it is now killed 2030 return true; 2031 } 2032 } 2033 usleep (10000); 2034 } 2035 2036 // check one more time after the final usleep 2037 { 2038 Mutex::Locker locker (m_spawned_pids_mutex); 2039 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) 2040 return true; 2041 } 2042 2043 // the launched process still lives. Now try killing it again, 2044 // this time with an unblockable signal. 2045 Host::Kill (pid, SIGKILL); 2046 2047 for (size_t i=0; i<10; ++i) 2048 { 2049 { 2050 Mutex::Locker locker (m_spawned_pids_mutex); 2051 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) 2052 { 2053 // it is now killed 2054 return true; 2055 } 2056 } 2057 usleep (10000); 2058 } 2059 2060 // check one more time after the final usleep 2061 // Scope for locker 2062 { 2063 Mutex::Locker locker (m_spawned_pids_mutex); 2064 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) 2065 return true; 2066 } 2067 2068 // no luck - the process still lives 2069 return false; 2070 } 2071 2072 GDBRemoteCommunication::PacketResult 2073 GDBRemoteCommunicationServer::Handle_qKillSpawnedProcess (StringExtractorGDBRemote &packet) 2074 { 2075 packet.SetFilePos(::strlen ("qKillSpawnedProcess:")); 2076 2077 lldb::pid_t pid = packet.GetU64(LLDB_INVALID_PROCESS_ID); 2078 2079 // verify that we know anything about this pid. 2080 // Scope for locker 2081 { 2082 Mutex::Locker locker (m_spawned_pids_mutex); 2083 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) 2084 { 2085 // not a pid we know about 2086 return SendErrorResponse (10); 2087 } 2088 } 2089 2090 // go ahead and attempt to kill the spawned process 2091 if (KillSpawnedProcess (pid)) 2092 return SendOKResponse (); 2093 else 2094 return SendErrorResponse (11); 2095 } 2096 2097 GDBRemoteCommunication::PacketResult 2098 GDBRemoteCommunicationServer::Handle_k (StringExtractorGDBRemote &packet) 2099 { 2100 // ignore for now if we're lldb_platform 2101 if (m_is_platform) 2102 return SendUnimplementedResponse (packet.GetStringRef().c_str()); 2103 2104 // shutdown all spawned processes 2105 std::set<lldb::pid_t> spawned_pids_copy; 2106 2107 // copy pids 2108 { 2109 Mutex::Locker locker (m_spawned_pids_mutex); 2110 spawned_pids_copy.insert (m_spawned_pids.begin (), m_spawned_pids.end ()); 2111 } 2112 2113 // nuke the spawned processes 2114 for (auto it = spawned_pids_copy.begin (); it != spawned_pids_copy.end (); ++it) 2115 { 2116 lldb::pid_t spawned_pid = *it; 2117 if (!KillSpawnedProcess (spawned_pid)) 2118 { 2119 fprintf (stderr, "%s: failed to kill spawned pid %" PRIu64 ", ignoring.\n", __FUNCTION__, spawned_pid); 2120 } 2121 } 2122 2123 FlushInferiorOutput (); 2124 2125 // No OK response for kill packet. 2126 // return SendOKResponse (); 2127 return PacketResult::Success; 2128 } 2129 2130 GDBRemoteCommunication::PacketResult 2131 GDBRemoteCommunicationServer::Handle_qLaunchSuccess (StringExtractorGDBRemote &packet) 2132 { 2133 if (m_process_launch_error.Success()) 2134 return SendOKResponse(); 2135 StreamString response; 2136 response.PutChar('E'); 2137 response.PutCString(m_process_launch_error.AsCString("<unknown error>")); 2138 return SendPacketNoLock (response.GetData(), response.GetSize()); 2139 } 2140 2141 GDBRemoteCommunication::PacketResult 2142 GDBRemoteCommunicationServer::Handle_QEnvironment (StringExtractorGDBRemote &packet) 2143 { 2144 packet.SetFilePos(::strlen ("QEnvironment:")); 2145 const uint32_t bytes_left = packet.GetBytesLeft(); 2146 if (bytes_left > 0) 2147 { 2148 m_process_launch_info.GetEnvironmentEntries ().AppendArgument (packet.Peek()); 2149 return SendOKResponse (); 2150 } 2151 return SendErrorResponse (12); 2152 } 2153 2154 GDBRemoteCommunication::PacketResult 2155 GDBRemoteCommunicationServer::Handle_QLaunchArch (StringExtractorGDBRemote &packet) 2156 { 2157 packet.SetFilePos(::strlen ("QLaunchArch:")); 2158 const uint32_t bytes_left = packet.GetBytesLeft(); 2159 if (bytes_left > 0) 2160 { 2161 const char* arch_triple = packet.Peek(); 2162 ArchSpec arch_spec(arch_triple,NULL); 2163 m_process_launch_info.SetArchitecture(arch_spec); 2164 return SendOKResponse(); 2165 } 2166 return SendErrorResponse(13); 2167 } 2168 2169 GDBRemoteCommunication::PacketResult 2170 GDBRemoteCommunicationServer::Handle_QSetDisableASLR (StringExtractorGDBRemote &packet) 2171 { 2172 packet.SetFilePos(::strlen ("QSetDisableASLR:")); 2173 if (packet.GetU32(0)) 2174 m_process_launch_info.GetFlags().Set (eLaunchFlagDisableASLR); 2175 else 2176 m_process_launch_info.GetFlags().Clear (eLaunchFlagDisableASLR); 2177 return SendOKResponse (); 2178 } 2179 2180 GDBRemoteCommunication::PacketResult 2181 GDBRemoteCommunicationServer::Handle_QSetWorkingDir (StringExtractorGDBRemote &packet) 2182 { 2183 packet.SetFilePos(::strlen ("QSetWorkingDir:")); 2184 std::string path; 2185 packet.GetHexByteString(path); 2186 if (m_is_platform) 2187 { 2188 #ifdef _WIN32 2189 // Not implemented on Windows 2190 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_QSetWorkingDir unimplemented"); 2191 #else 2192 // If this packet is sent to a platform, then change the current working directory 2193 if (::chdir(path.c_str()) != 0) 2194 return SendErrorResponse(errno); 2195 #endif 2196 } 2197 else 2198 { 2199 m_process_launch_info.SwapWorkingDirectory (path); 2200 } 2201 return SendOKResponse (); 2202 } 2203 2204 GDBRemoteCommunication::PacketResult 2205 GDBRemoteCommunicationServer::Handle_qGetWorkingDir (StringExtractorGDBRemote &packet) 2206 { 2207 StreamString response; 2208 2209 if (m_is_platform) 2210 { 2211 // If this packet is sent to a platform, then change the current working directory 2212 char cwd[PATH_MAX]; 2213 if (getcwd(cwd, sizeof(cwd)) == NULL) 2214 { 2215 return SendErrorResponse(errno); 2216 } 2217 else 2218 { 2219 response.PutBytesAsRawHex8(cwd, strlen(cwd)); 2220 return SendPacketNoLock(response.GetData(), response.GetSize()); 2221 } 2222 } 2223 else 2224 { 2225 const char *working_dir = m_process_launch_info.GetWorkingDirectory(); 2226 if (working_dir && working_dir[0]) 2227 { 2228 response.PutBytesAsRawHex8(working_dir, strlen(working_dir)); 2229 return SendPacketNoLock(response.GetData(), response.GetSize()); 2230 } 2231 else 2232 { 2233 return SendErrorResponse(14); 2234 } 2235 } 2236 } 2237 2238 GDBRemoteCommunication::PacketResult 2239 GDBRemoteCommunicationServer::Handle_QSetSTDIN (StringExtractorGDBRemote &packet) 2240 { 2241 packet.SetFilePos(::strlen ("QSetSTDIN:")); 2242 FileAction file_action; 2243 std::string path; 2244 packet.GetHexByteString(path); 2245 const bool read = false; 2246 const bool write = true; 2247 if (file_action.Open(STDIN_FILENO, path.c_str(), read, write)) 2248 { 2249 m_process_launch_info.AppendFileAction(file_action); 2250 return SendOKResponse (); 2251 } 2252 return SendErrorResponse (15); 2253 } 2254 2255 GDBRemoteCommunication::PacketResult 2256 GDBRemoteCommunicationServer::Handle_QSetSTDOUT (StringExtractorGDBRemote &packet) 2257 { 2258 packet.SetFilePos(::strlen ("QSetSTDOUT:")); 2259 FileAction file_action; 2260 std::string path; 2261 packet.GetHexByteString(path); 2262 const bool read = true; 2263 const bool write = false; 2264 if (file_action.Open(STDOUT_FILENO, path.c_str(), read, write)) 2265 { 2266 m_process_launch_info.AppendFileAction(file_action); 2267 return SendOKResponse (); 2268 } 2269 return SendErrorResponse (16); 2270 } 2271 2272 GDBRemoteCommunication::PacketResult 2273 GDBRemoteCommunicationServer::Handle_QSetSTDERR (StringExtractorGDBRemote &packet) 2274 { 2275 packet.SetFilePos(::strlen ("QSetSTDERR:")); 2276 FileAction file_action; 2277 std::string path; 2278 packet.GetHexByteString(path); 2279 const bool read = true; 2280 const bool write = false; 2281 if (file_action.Open(STDERR_FILENO, path.c_str(), read, write)) 2282 { 2283 m_process_launch_info.AppendFileAction(file_action); 2284 return SendOKResponse (); 2285 } 2286 return SendErrorResponse (17); 2287 } 2288 2289 GDBRemoteCommunication::PacketResult 2290 GDBRemoteCommunicationServer::Handle_C (StringExtractorGDBRemote &packet) 2291 { 2292 if (!IsGdbServer ()) 2293 return SendUnimplementedResponse (packet.GetStringRef().c_str()); 2294 2295 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD)); 2296 if (log) 2297 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__); 2298 2299 // Ensure we have a native process. 2300 if (!m_debugged_process_sp) 2301 { 2302 if (log) 2303 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__); 2304 return SendErrorResponse (0x36); 2305 } 2306 2307 // Pull out the signal number. 2308 packet.SetFilePos (::strlen ("C")); 2309 if (packet.GetBytesLeft () < 1) 2310 { 2311 // Shouldn't be using a C without a signal. 2312 return SendIllFormedResponse (packet, "C packet specified without signal."); 2313 } 2314 const uint32_t signo = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ()); 2315 if (signo == std::numeric_limits<uint32_t>::max ()) 2316 return SendIllFormedResponse (packet, "failed to parse signal number"); 2317 2318 // Handle optional continue address. 2319 if (packet.GetBytesLeft () > 0) 2320 { 2321 // FIXME add continue at address support for $C{signo}[;{continue-address}]. 2322 if (*packet.Peek () == ';') 2323 return SendUnimplementedResponse (packet.GetStringRef().c_str()); 2324 else 2325 return SendIllFormedResponse (packet, "unexpected content after $C{signal-number}"); 2326 } 2327 2328 lldb_private::ResumeActionList resume_actions (StateType::eStateRunning, 0); 2329 Error error; 2330 2331 // We have two branches: what to do if a continue thread is specified (in which case we target 2332 // sending the signal to that thread), or when we don't have a continue thread set (in which 2333 // case we send a signal to the process). 2334 2335 // TODO discuss with Greg Clayton, make sure this makes sense. 2336 2337 lldb::tid_t signal_tid = GetContinueThreadID (); 2338 if (signal_tid != LLDB_INVALID_THREAD_ID) 2339 { 2340 // The resume action for the continue thread (or all threads if a continue thread is not set). 2341 lldb_private::ResumeAction action = { GetContinueThreadID (), StateType::eStateRunning, static_cast<int> (signo) }; 2342 2343 // Add the action for the continue thread (or all threads when the continue thread isn't present). 2344 resume_actions.Append (action); 2345 } 2346 else 2347 { 2348 // Send the signal to the process since we weren't targeting a specific continue thread with the signal. 2349 error = m_debugged_process_sp->Signal (signo); 2350 if (error.Fail ()) 2351 { 2352 if (log) 2353 log->Printf ("GDBRemoteCommunicationServer::%s failed to send signal for process %" PRIu64 ": %s", 2354 __FUNCTION__, 2355 m_debugged_process_sp->GetID (), 2356 error.AsCString ()); 2357 2358 return SendErrorResponse (0x52); 2359 } 2360 } 2361 2362 // Resume the threads. 2363 error = m_debugged_process_sp->Resume (resume_actions); 2364 if (error.Fail ()) 2365 { 2366 if (log) 2367 log->Printf ("GDBRemoteCommunicationServer::%s failed to resume threads for process %" PRIu64 ": %s", 2368 __FUNCTION__, 2369 m_debugged_process_sp->GetID (), 2370 error.AsCString ()); 2371 2372 return SendErrorResponse (0x38); 2373 } 2374 2375 // Don't send an "OK" packet; response is the stopped/exited message. 2376 return PacketResult::Success; 2377 } 2378 2379 GDBRemoteCommunication::PacketResult 2380 GDBRemoteCommunicationServer::Handle_c (StringExtractorGDBRemote &packet, bool skip_file_pos_adjustment) 2381 { 2382 if (!IsGdbServer ()) 2383 return SendUnimplementedResponse (packet.GetStringRef().c_str()); 2384 2385 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD)); 2386 if (log) 2387 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__); 2388 2389 // We reuse this method in vCont - don't double adjust the file position. 2390 if (!skip_file_pos_adjustment) 2391 packet.SetFilePos (::strlen ("c")); 2392 2393 // For now just support all continue. 2394 const bool has_continue_address = (packet.GetBytesLeft () > 0); 2395 if (has_continue_address) 2396 { 2397 if (log) 2398 log->Printf ("GDBRemoteCommunicationServer::%s not implemented for c{address} variant [%s remains]", __FUNCTION__, packet.Peek ()); 2399 return SendUnimplementedResponse (packet.GetStringRef().c_str()); 2400 } 2401 2402 // Ensure we have a native process. 2403 if (!m_debugged_process_sp) 2404 { 2405 if (log) 2406 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__); 2407 return SendErrorResponse (0x36); 2408 } 2409 2410 // Build the ResumeActionList 2411 lldb_private::ResumeActionList actions (StateType::eStateRunning, 0); 2412 2413 Error error = m_debugged_process_sp->Resume (actions); 2414 if (error.Fail ()) 2415 { 2416 if (log) 2417 { 2418 log->Printf ("GDBRemoteCommunicationServer::%s c failed for process %" PRIu64 ": %s", 2419 __FUNCTION__, 2420 m_debugged_process_sp->GetID (), 2421 error.AsCString ()); 2422 } 2423 return SendErrorResponse (GDBRemoteServerError::eErrorResume); 2424 } 2425 2426 if (log) 2427 log->Printf ("GDBRemoteCommunicationServer::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ()); 2428 2429 // No response required from continue. 2430 return PacketResult::Success; 2431 } 2432 2433 GDBRemoteCommunication::PacketResult 2434 GDBRemoteCommunicationServer::Handle_vCont_actions (StringExtractorGDBRemote &packet) 2435 { 2436 if (!IsGdbServer ()) 2437 { 2438 // only llgs supports $vCont. 2439 return SendUnimplementedResponse (packet.GetStringRef().c_str()); 2440 } 2441 2442 StreamString response; 2443 response.Printf("vCont;c;C;s;S"); 2444 2445 return SendPacketNoLock(response.GetData(), response.GetSize()); 2446 } 2447 2448 GDBRemoteCommunication::PacketResult 2449 GDBRemoteCommunicationServer::Handle_vCont (StringExtractorGDBRemote &packet) 2450 { 2451 if (!IsGdbServer ()) 2452 { 2453 // only llgs supports $vCont 2454 return SendUnimplementedResponse (packet.GetStringRef().c_str()); 2455 } 2456 2457 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2458 if (log) 2459 log->Printf ("GDBRemoteCommunicationServer::%s handling vCont packet", __FUNCTION__); 2460 2461 packet.SetFilePos (::strlen ("vCont")); 2462 2463 // Check if this is all continue (no options or ";c"). 2464 if (!packet.GetBytesLeft () || (::strcmp (packet.Peek (), ";c") == 0)) 2465 { 2466 // Move the packet past the ";c". 2467 if (packet.GetBytesLeft ()) 2468 packet.SetFilePos (packet.GetFilePos () + ::strlen (";c")); 2469 2470 const bool skip_file_pos_adjustment = true; 2471 return Handle_c (packet, skip_file_pos_adjustment); 2472 } 2473 else if (::strcmp (packet.Peek (), ";s") == 0) 2474 { 2475 // Move past the ';', then do a simple 's'. 2476 packet.SetFilePos (packet.GetFilePos () + 1); 2477 return Handle_s (packet); 2478 } 2479 2480 // Ensure we have a native process. 2481 if (!m_debugged_process_sp) 2482 { 2483 if (log) 2484 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__); 2485 return SendErrorResponse (0x36); 2486 } 2487 2488 ResumeActionList thread_actions; 2489 2490 while (packet.GetBytesLeft () && *packet.Peek () == ';') 2491 { 2492 // Skip the semi-colon. 2493 packet.GetChar (); 2494 2495 // Build up the thread action. 2496 ResumeAction thread_action; 2497 thread_action.tid = LLDB_INVALID_THREAD_ID; 2498 thread_action.state = eStateInvalid; 2499 thread_action.signal = 0; 2500 2501 const char action = packet.GetChar (); 2502 switch (action) 2503 { 2504 case 'C': 2505 thread_action.signal = packet.GetHexMaxU32 (false, 0); 2506 if (thread_action.signal == 0) 2507 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet C action"); 2508 // Fall through to next case... 2509 2510 case 'c': 2511 // Continue 2512 thread_action.state = eStateRunning; 2513 break; 2514 2515 case 'S': 2516 thread_action.signal = packet.GetHexMaxU32 (false, 0); 2517 if (thread_action.signal == 0) 2518 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet S action"); 2519 // Fall through to next case... 2520 2521 case 's': 2522 // Step 2523 thread_action.state = eStateStepping; 2524 break; 2525 2526 default: 2527 return SendIllFormedResponse (packet, "Unsupported vCont action"); 2528 break; 2529 } 2530 2531 // Parse out optional :{thread-id} value. 2532 if (packet.GetBytesLeft () && (*packet.Peek () == ':')) 2533 { 2534 // Consume the separator. 2535 packet.GetChar (); 2536 2537 thread_action.tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID); 2538 if (thread_action.tid == LLDB_INVALID_THREAD_ID) 2539 return SendIllFormedResponse (packet, "Could not parse thread number in vCont packet"); 2540 } 2541 2542 thread_actions.Append (thread_action); 2543 } 2544 2545 Error error = m_debugged_process_sp->Resume (thread_actions); 2546 if (error.Fail ()) 2547 { 2548 if (log) 2549 { 2550 log->Printf ("GDBRemoteCommunicationServer::%s vCont failed for process %" PRIu64 ": %s", 2551 __FUNCTION__, 2552 m_debugged_process_sp->GetID (), 2553 error.AsCString ()); 2554 } 2555 return SendErrorResponse (GDBRemoteServerError::eErrorResume); 2556 } 2557 2558 if (log) 2559 log->Printf ("GDBRemoteCommunicationServer::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ()); 2560 2561 // No response required from vCont. 2562 return PacketResult::Success; 2563 } 2564 2565 GDBRemoteCommunication::PacketResult 2566 GDBRemoteCommunicationServer::Handle_QStartNoAckMode (StringExtractorGDBRemote &packet) 2567 { 2568 // Send response first before changing m_send_acks to we ack this packet 2569 PacketResult packet_result = SendOKResponse (); 2570 m_send_acks = false; 2571 return packet_result; 2572 } 2573 2574 GDBRemoteCommunication::PacketResult 2575 GDBRemoteCommunicationServer::Handle_qPlatform_mkdir (StringExtractorGDBRemote &packet) 2576 { 2577 packet.SetFilePos(::strlen("qPlatform_mkdir:")); 2578 mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX); 2579 if (packet.GetChar() == ',') 2580 { 2581 std::string path; 2582 packet.GetHexByteString(path); 2583 Error error = FileSystem::MakeDirectory(path.c_str(), mode); 2584 if (error.Success()) 2585 return SendPacketNoLock ("OK", 2); 2586 else 2587 return SendErrorResponse(error.GetError()); 2588 } 2589 return SendErrorResponse(20); 2590 } 2591 2592 GDBRemoteCommunication::PacketResult 2593 GDBRemoteCommunicationServer::Handle_qPlatform_chmod (StringExtractorGDBRemote &packet) 2594 { 2595 packet.SetFilePos(::strlen("qPlatform_chmod:")); 2596 2597 mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX); 2598 if (packet.GetChar() == ',') 2599 { 2600 std::string path; 2601 packet.GetHexByteString(path); 2602 Error error = FileSystem::SetFilePermissions(path.c_str(), mode); 2603 if (error.Success()) 2604 return SendPacketNoLock ("OK", 2); 2605 else 2606 return SendErrorResponse(error.GetError()); 2607 } 2608 return SendErrorResponse(19); 2609 } 2610 2611 GDBRemoteCommunication::PacketResult 2612 GDBRemoteCommunicationServer::Handle_vFile_Open (StringExtractorGDBRemote &packet) 2613 { 2614 packet.SetFilePos(::strlen("vFile:open:")); 2615 std::string path; 2616 packet.GetHexByteStringTerminatedBy(path,','); 2617 if (!path.empty()) 2618 { 2619 if (packet.GetChar() == ',') 2620 { 2621 uint32_t flags = packet.GetHexMaxU32(false, 0); 2622 if (packet.GetChar() == ',') 2623 { 2624 mode_t mode = packet.GetHexMaxU32(false, 0600); 2625 Error error; 2626 int fd = ::open (path.c_str(), flags, mode); 2627 const int save_errno = fd == -1 ? errno : 0; 2628 StreamString response; 2629 response.PutChar('F'); 2630 response.Printf("%i", fd); 2631 if (save_errno) 2632 response.Printf(",%i", save_errno); 2633 return SendPacketNoLock(response.GetData(), response.GetSize()); 2634 } 2635 } 2636 } 2637 return SendErrorResponse(18); 2638 } 2639 2640 GDBRemoteCommunication::PacketResult 2641 GDBRemoteCommunicationServer::Handle_vFile_Close (StringExtractorGDBRemote &packet) 2642 { 2643 packet.SetFilePos(::strlen("vFile:close:")); 2644 int fd = packet.GetS32(-1); 2645 Error error; 2646 int err = -1; 2647 int save_errno = 0; 2648 if (fd >= 0) 2649 { 2650 err = close(fd); 2651 save_errno = err == -1 ? errno : 0; 2652 } 2653 else 2654 { 2655 save_errno = EINVAL; 2656 } 2657 StreamString response; 2658 response.PutChar('F'); 2659 response.Printf("%i", err); 2660 if (save_errno) 2661 response.Printf(",%i", save_errno); 2662 return SendPacketNoLock(response.GetData(), response.GetSize()); 2663 } 2664 2665 GDBRemoteCommunication::PacketResult 2666 GDBRemoteCommunicationServer::Handle_vFile_pRead (StringExtractorGDBRemote &packet) 2667 { 2668 #ifdef _WIN32 2669 // Not implemented on Windows 2670 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pRead() unimplemented"); 2671 #else 2672 StreamGDBRemote response; 2673 packet.SetFilePos(::strlen("vFile:pread:")); 2674 int fd = packet.GetS32(-1); 2675 if (packet.GetChar() == ',') 2676 { 2677 uint64_t count = packet.GetU64(UINT64_MAX); 2678 if (packet.GetChar() == ',') 2679 { 2680 uint64_t offset = packet.GetU64(UINT32_MAX); 2681 if (count == UINT64_MAX) 2682 { 2683 response.Printf("F-1:%i", EINVAL); 2684 return SendPacketNoLock(response.GetData(), response.GetSize()); 2685 } 2686 2687 std::string buffer(count, 0); 2688 const ssize_t bytes_read = ::pread (fd, &buffer[0], buffer.size(), offset); 2689 const int save_errno = bytes_read == -1 ? errno : 0; 2690 response.PutChar('F'); 2691 response.Printf("%zi", bytes_read); 2692 if (save_errno) 2693 response.Printf(",%i", save_errno); 2694 else 2695 { 2696 response.PutChar(';'); 2697 response.PutEscapedBytes(&buffer[0], bytes_read); 2698 } 2699 return SendPacketNoLock(response.GetData(), response.GetSize()); 2700 } 2701 } 2702 return SendErrorResponse(21); 2703 2704 #endif 2705 } 2706 2707 GDBRemoteCommunication::PacketResult 2708 GDBRemoteCommunicationServer::Handle_vFile_pWrite (StringExtractorGDBRemote &packet) 2709 { 2710 #ifdef _WIN32 2711 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pWrite() unimplemented"); 2712 #else 2713 packet.SetFilePos(::strlen("vFile:pwrite:")); 2714 2715 StreamGDBRemote response; 2716 response.PutChar('F'); 2717 2718 int fd = packet.GetU32(UINT32_MAX); 2719 if (packet.GetChar() == ',') 2720 { 2721 off_t offset = packet.GetU64(UINT32_MAX); 2722 if (packet.GetChar() == ',') 2723 { 2724 std::string buffer; 2725 if (packet.GetEscapedBinaryData(buffer)) 2726 { 2727 const ssize_t bytes_written = ::pwrite (fd, buffer.data(), buffer.size(), offset); 2728 const int save_errno = bytes_written == -1 ? errno : 0; 2729 response.Printf("%zi", bytes_written); 2730 if (save_errno) 2731 response.Printf(",%i", save_errno); 2732 } 2733 else 2734 { 2735 response.Printf ("-1,%i", EINVAL); 2736 } 2737 return SendPacketNoLock(response.GetData(), response.GetSize()); 2738 } 2739 } 2740 return SendErrorResponse(27); 2741 #endif 2742 } 2743 2744 GDBRemoteCommunication::PacketResult 2745 GDBRemoteCommunicationServer::Handle_vFile_Size (StringExtractorGDBRemote &packet) 2746 { 2747 packet.SetFilePos(::strlen("vFile:size:")); 2748 std::string path; 2749 packet.GetHexByteString(path); 2750 if (!path.empty()) 2751 { 2752 lldb::user_id_t retcode = FileSystem::GetFileSize(FileSpec(path.c_str(), false)); 2753 StreamString response; 2754 response.PutChar('F'); 2755 response.PutHex64(retcode); 2756 if (retcode == UINT64_MAX) 2757 { 2758 response.PutChar(','); 2759 response.PutHex64(retcode); // TODO: replace with Host::GetSyswideErrorCode() 2760 } 2761 return SendPacketNoLock(response.GetData(), response.GetSize()); 2762 } 2763 return SendErrorResponse(22); 2764 } 2765 2766 GDBRemoteCommunication::PacketResult 2767 GDBRemoteCommunicationServer::Handle_vFile_Mode (StringExtractorGDBRemote &packet) 2768 { 2769 packet.SetFilePos(::strlen("vFile:mode:")); 2770 std::string path; 2771 packet.GetHexByteString(path); 2772 if (!path.empty()) 2773 { 2774 Error error; 2775 const uint32_t mode = File::GetPermissions(path.c_str(), error); 2776 StreamString response; 2777 response.Printf("F%u", mode); 2778 if (mode == 0 || error.Fail()) 2779 response.Printf(",%i", (int)error.GetError()); 2780 return SendPacketNoLock(response.GetData(), response.GetSize()); 2781 } 2782 return SendErrorResponse(23); 2783 } 2784 2785 GDBRemoteCommunication::PacketResult 2786 GDBRemoteCommunicationServer::Handle_vFile_Exists (StringExtractorGDBRemote &packet) 2787 { 2788 packet.SetFilePos(::strlen("vFile:exists:")); 2789 std::string path; 2790 packet.GetHexByteString(path); 2791 if (!path.empty()) 2792 { 2793 bool retcode = FileSystem::GetFileExists(FileSpec(path.c_str(), false)); 2794 StreamString response; 2795 response.PutChar('F'); 2796 response.PutChar(','); 2797 if (retcode) 2798 response.PutChar('1'); 2799 else 2800 response.PutChar('0'); 2801 return SendPacketNoLock(response.GetData(), response.GetSize()); 2802 } 2803 return SendErrorResponse(24); 2804 } 2805 2806 GDBRemoteCommunication::PacketResult 2807 GDBRemoteCommunicationServer::Handle_vFile_symlink (StringExtractorGDBRemote &packet) 2808 { 2809 packet.SetFilePos(::strlen("vFile:symlink:")); 2810 std::string dst, src; 2811 packet.GetHexByteStringTerminatedBy(dst, ','); 2812 packet.GetChar(); // Skip ',' char 2813 packet.GetHexByteString(src); 2814 Error error = FileSystem::Symlink(src.c_str(), dst.c_str()); 2815 StreamString response; 2816 response.Printf("F%u,%u", error.GetError(), error.GetError()); 2817 return SendPacketNoLock(response.GetData(), response.GetSize()); 2818 } 2819 2820 GDBRemoteCommunication::PacketResult 2821 GDBRemoteCommunicationServer::Handle_vFile_unlink (StringExtractorGDBRemote &packet) 2822 { 2823 packet.SetFilePos(::strlen("vFile:unlink:")); 2824 std::string path; 2825 packet.GetHexByteString(path); 2826 Error error = FileSystem::Unlink(path.c_str()); 2827 StreamString response; 2828 response.Printf("F%u,%u", error.GetError(), error.GetError()); 2829 return SendPacketNoLock(response.GetData(), response.GetSize()); 2830 } 2831 2832 GDBRemoteCommunication::PacketResult 2833 GDBRemoteCommunicationServer::Handle_qPlatform_shell (StringExtractorGDBRemote &packet) 2834 { 2835 packet.SetFilePos(::strlen("qPlatform_shell:")); 2836 std::string path; 2837 std::string working_dir; 2838 packet.GetHexByteStringTerminatedBy(path,','); 2839 if (!path.empty()) 2840 { 2841 if (packet.GetChar() == ',') 2842 { 2843 // FIXME: add timeout to qPlatform_shell packet 2844 // uint32_t timeout = packet.GetHexMaxU32(false, 32); 2845 uint32_t timeout = 10; 2846 if (packet.GetChar() == ',') 2847 packet.GetHexByteString(working_dir); 2848 int status, signo; 2849 std::string output; 2850 Error err = Host::RunShellCommand(path.c_str(), 2851 working_dir.empty() ? NULL : working_dir.c_str(), 2852 &status, &signo, &output, timeout); 2853 StreamGDBRemote response; 2854 if (err.Fail()) 2855 { 2856 response.PutCString("F,"); 2857 response.PutHex32(UINT32_MAX); 2858 } 2859 else 2860 { 2861 response.PutCString("F,"); 2862 response.PutHex32(status); 2863 response.PutChar(','); 2864 response.PutHex32(signo); 2865 response.PutChar(','); 2866 response.PutEscapedBytes(output.c_str(), output.size()); 2867 } 2868 return SendPacketNoLock(response.GetData(), response.GetSize()); 2869 } 2870 } 2871 return SendErrorResponse(24); 2872 } 2873 2874 void 2875 GDBRemoteCommunicationServer::SetCurrentThreadID (lldb::tid_t tid) 2876 { 2877 assert (IsGdbServer () && "SetCurrentThreadID() called when not GdbServer code"); 2878 2879 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD)); 2880 if (log) 2881 log->Printf ("GDBRemoteCommunicationServer::%s setting current thread id to %" PRIu64, __FUNCTION__, tid); 2882 2883 m_current_tid = tid; 2884 if (m_debugged_process_sp) 2885 m_debugged_process_sp->SetCurrentThreadID (m_current_tid); 2886 } 2887 2888 void 2889 GDBRemoteCommunicationServer::SetContinueThreadID (lldb::tid_t tid) 2890 { 2891 assert (IsGdbServer () && "SetContinueThreadID() called when not GdbServer code"); 2892 2893 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD)); 2894 if (log) 2895 log->Printf ("GDBRemoteCommunicationServer::%s setting continue thread id to %" PRIu64, __FUNCTION__, tid); 2896 2897 m_continue_tid = tid; 2898 } 2899 2900 GDBRemoteCommunication::PacketResult 2901 GDBRemoteCommunicationServer::Handle_stop_reason (StringExtractorGDBRemote &packet) 2902 { 2903 // Handle the $? gdbremote command. 2904 if (!IsGdbServer ()) 2905 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_stop_reason() unimplemented"); 2906 2907 // If no process, indicate error 2908 if (!m_debugged_process_sp) 2909 return SendErrorResponse (02); 2910 2911 return SendStopReasonForState (m_debugged_process_sp->GetState (), true); 2912 } 2913 2914 GDBRemoteCommunication::PacketResult 2915 GDBRemoteCommunicationServer::SendStopReasonForState (lldb::StateType process_state, bool flush_on_exit) 2916 { 2917 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2918 2919 switch (process_state) 2920 { 2921 case eStateAttaching: 2922 case eStateLaunching: 2923 case eStateRunning: 2924 case eStateStepping: 2925 case eStateDetached: 2926 // NOTE: gdb protocol doc looks like it should return $OK 2927 // when everything is running (i.e. no stopped result). 2928 return PacketResult::Success; // Ignore 2929 2930 case eStateSuspended: 2931 case eStateStopped: 2932 case eStateCrashed: 2933 { 2934 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID (); 2935 // Make sure we set the current thread so g and p packets return 2936 // the data the gdb will expect. 2937 SetCurrentThreadID (tid); 2938 return SendStopReplyPacketForThread (tid); 2939 } 2940 2941 case eStateInvalid: 2942 case eStateUnloaded: 2943 case eStateExited: 2944 if (flush_on_exit) 2945 FlushInferiorOutput (); 2946 return SendWResponse(m_debugged_process_sp.get()); 2947 2948 default: 2949 if (log) 2950 { 2951 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", current state reporting not handled: %s", 2952 __FUNCTION__, 2953 m_debugged_process_sp->GetID (), 2954 StateAsCString (process_state)); 2955 } 2956 break; 2957 } 2958 2959 return SendErrorResponse (0); 2960 } 2961 2962 GDBRemoteCommunication::PacketResult 2963 GDBRemoteCommunicationServer::Handle_vFile_Stat (StringExtractorGDBRemote &packet) 2964 { 2965 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_Stat() unimplemented"); 2966 } 2967 2968 GDBRemoteCommunication::PacketResult 2969 GDBRemoteCommunicationServer::Handle_vFile_MD5 (StringExtractorGDBRemote &packet) 2970 { 2971 packet.SetFilePos(::strlen("vFile:MD5:")); 2972 std::string path; 2973 packet.GetHexByteString(path); 2974 if (!path.empty()) 2975 { 2976 uint64_t a,b; 2977 StreamGDBRemote response; 2978 if (FileSystem::CalculateMD5(FileSpec(path.c_str(), false), a, b) == false) 2979 { 2980 response.PutCString("F,"); 2981 response.PutCString("x"); 2982 } 2983 else 2984 { 2985 response.PutCString("F,"); 2986 response.PutHex64(a); 2987 response.PutHex64(b); 2988 } 2989 return SendPacketNoLock(response.GetData(), response.GetSize()); 2990 } 2991 return SendErrorResponse(25); 2992 } 2993 2994 GDBRemoteCommunication::PacketResult 2995 GDBRemoteCommunicationServer::Handle_qRegisterInfo (StringExtractorGDBRemote &packet) 2996 { 2997 // Ensure we're llgs. 2998 if (!IsGdbServer()) 2999 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_qRegisterInfo() unimplemented"); 3000 3001 // Fail if we don't have a current process. 3002 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3003 return SendErrorResponse (68); 3004 3005 // Ensure we have a thread. 3006 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadAtIndex (0)); 3007 if (!thread_sp) 3008 return SendErrorResponse (69); 3009 3010 // Get the register context for the first thread. 3011 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ()); 3012 if (!reg_context_sp) 3013 return SendErrorResponse (69); 3014 3015 // Parse out the register number from the request. 3016 packet.SetFilePos (strlen("qRegisterInfo")); 3017 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ()); 3018 if (reg_index == std::numeric_limits<uint32_t>::max ()) 3019 return SendErrorResponse (69); 3020 3021 // Return the end of registers response if we've iterated one past the end of the register set. 3022 if (reg_index >= reg_context_sp->GetUserRegisterCount ()) 3023 return SendErrorResponse (69); 3024 3025 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index); 3026 if (!reg_info) 3027 return SendErrorResponse (69); 3028 3029 // Build the reginfos response. 3030 StreamGDBRemote response; 3031 3032 response.PutCString ("name:"); 3033 response.PutCString (reg_info->name); 3034 response.PutChar (';'); 3035 3036 if (reg_info->alt_name && reg_info->alt_name[0]) 3037 { 3038 response.PutCString ("alt-name:"); 3039 response.PutCString (reg_info->alt_name); 3040 response.PutChar (';'); 3041 } 3042 3043 response.Printf ("bitsize:%" PRIu32 ";offset:%" PRIu32 ";", reg_info->byte_size * 8, reg_info->byte_offset); 3044 3045 switch (reg_info->encoding) 3046 { 3047 case eEncodingUint: response.PutCString ("encoding:uint;"); break; 3048 case eEncodingSint: response.PutCString ("encoding:sint;"); break; 3049 case eEncodingIEEE754: response.PutCString ("encoding:ieee754;"); break; 3050 case eEncodingVector: response.PutCString ("encoding:vector;"); break; 3051 default: break; 3052 } 3053 3054 switch (reg_info->format) 3055 { 3056 case eFormatBinary: response.PutCString ("format:binary;"); break; 3057 case eFormatDecimal: response.PutCString ("format:decimal;"); break; 3058 case eFormatHex: response.PutCString ("format:hex;"); break; 3059 case eFormatFloat: response.PutCString ("format:float;"); break; 3060 case eFormatVectorOfSInt8: response.PutCString ("format:vector-sint8;"); break; 3061 case eFormatVectorOfUInt8: response.PutCString ("format:vector-uint8;"); break; 3062 case eFormatVectorOfSInt16: response.PutCString ("format:vector-sint16;"); break; 3063 case eFormatVectorOfUInt16: response.PutCString ("format:vector-uint16;"); break; 3064 case eFormatVectorOfSInt32: response.PutCString ("format:vector-sint32;"); break; 3065 case eFormatVectorOfUInt32: response.PutCString ("format:vector-uint32;"); break; 3066 case eFormatVectorOfFloat32: response.PutCString ("format:vector-float32;"); break; 3067 case eFormatVectorOfUInt128: response.PutCString ("format:vector-uint128;"); break; 3068 default: break; 3069 }; 3070 3071 const char *const register_set_name = reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index); 3072 if (register_set_name) 3073 { 3074 response.PutCString ("set:"); 3075 response.PutCString (register_set_name); 3076 response.PutChar (';'); 3077 } 3078 3079 if (reg_info->kinds[RegisterKind::eRegisterKindGCC] != LLDB_INVALID_REGNUM) 3080 response.Printf ("gcc:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindGCC]); 3081 3082 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM) 3083 response.Printf ("dwarf:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindDWARF]); 3084 3085 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric]) 3086 { 3087 case LLDB_REGNUM_GENERIC_PC: response.PutCString("generic:pc;"); break; 3088 case LLDB_REGNUM_GENERIC_SP: response.PutCString("generic:sp;"); break; 3089 case LLDB_REGNUM_GENERIC_FP: response.PutCString("generic:fp;"); break; 3090 case LLDB_REGNUM_GENERIC_RA: response.PutCString("generic:ra;"); break; 3091 case LLDB_REGNUM_GENERIC_FLAGS: response.PutCString("generic:flags;"); break; 3092 case LLDB_REGNUM_GENERIC_ARG1: response.PutCString("generic:arg1;"); break; 3093 case LLDB_REGNUM_GENERIC_ARG2: response.PutCString("generic:arg2;"); break; 3094 case LLDB_REGNUM_GENERIC_ARG3: response.PutCString("generic:arg3;"); break; 3095 case LLDB_REGNUM_GENERIC_ARG4: response.PutCString("generic:arg4;"); break; 3096 case LLDB_REGNUM_GENERIC_ARG5: response.PutCString("generic:arg5;"); break; 3097 case LLDB_REGNUM_GENERIC_ARG6: response.PutCString("generic:arg6;"); break; 3098 case LLDB_REGNUM_GENERIC_ARG7: response.PutCString("generic:arg7;"); break; 3099 case LLDB_REGNUM_GENERIC_ARG8: response.PutCString("generic:arg8;"); break; 3100 default: break; 3101 } 3102 3103 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) 3104 { 3105 response.PutCString ("container-regs:"); 3106 int i = 0; 3107 for (const uint32_t *reg_num = reg_info->value_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) 3108 { 3109 if (i > 0) 3110 response.PutChar (','); 3111 response.Printf ("%" PRIx32, *reg_num); 3112 } 3113 response.PutChar (';'); 3114 } 3115 3116 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) 3117 { 3118 response.PutCString ("invalidate-regs:"); 3119 int i = 0; 3120 for (const uint32_t *reg_num = reg_info->invalidate_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) 3121 { 3122 if (i > 0) 3123 response.PutChar (','); 3124 response.Printf ("%" PRIx32, *reg_num); 3125 } 3126 response.PutChar (';'); 3127 } 3128 3129 return SendPacketNoLock(response.GetData(), response.GetSize()); 3130 } 3131 3132 GDBRemoteCommunication::PacketResult 3133 GDBRemoteCommunicationServer::Handle_qfThreadInfo (StringExtractorGDBRemote &packet) 3134 { 3135 // Ensure we're llgs. 3136 if (!IsGdbServer()) 3137 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_qfThreadInfo() unimplemented"); 3138 3139 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 3140 3141 // Fail if we don't have a current process. 3142 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3143 { 3144 if (log) 3145 log->Printf ("GDBRemoteCommunicationServer::%s() no process (%s), returning OK", __FUNCTION__, m_debugged_process_sp ? "invalid process id" : "null m_debugged_process_sp"); 3146 return SendOKResponse (); 3147 } 3148 3149 StreamGDBRemote response; 3150 response.PutChar ('m'); 3151 3152 if (log) 3153 log->Printf ("GDBRemoteCommunicationServer::%s() starting thread iteration", __FUNCTION__); 3154 3155 NativeThreadProtocolSP thread_sp; 3156 uint32_t thread_index; 3157 for (thread_index = 0, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index); 3158 thread_sp; 3159 ++thread_index, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index)) 3160 { 3161 if (log) 3162 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); 3163 if (thread_index > 0) 3164 response.PutChar(','); 3165 response.Printf ("%" PRIx64, thread_sp->GetID ()); 3166 } 3167 3168 if (log) 3169 log->Printf ("GDBRemoteCommunicationServer::%s() finished thread iteration", __FUNCTION__); 3170 3171 return SendPacketNoLock(response.GetData(), response.GetSize()); 3172 } 3173 3174 GDBRemoteCommunication::PacketResult 3175 GDBRemoteCommunicationServer::Handle_qsThreadInfo (StringExtractorGDBRemote &packet) 3176 { 3177 // Ensure we're llgs. 3178 if (!IsGdbServer()) 3179 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_qsThreadInfo() unimplemented"); 3180 3181 // FIXME for now we return the full thread list in the initial packet and always do nothing here. 3182 return SendPacketNoLock ("l", 1); 3183 } 3184 3185 GDBRemoteCommunication::PacketResult 3186 GDBRemoteCommunicationServer::Handle_p (StringExtractorGDBRemote &packet) 3187 { 3188 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 3189 3190 // Ensure we're llgs. 3191 if (!IsGdbServer()) 3192 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_p() unimplemented"); 3193 3194 // Parse out the register number from the request. 3195 packet.SetFilePos (strlen("p")); 3196 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ()); 3197 if (reg_index == std::numeric_limits<uint32_t>::max ()) 3198 { 3199 if (log) 3200 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ()); 3201 return SendErrorResponse (0x15); 3202 } 3203 3204 // Get the thread to use. 3205 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet); 3206 if (!thread_sp) 3207 { 3208 if (log) 3209 log->Printf ("GDBRemoteCommunicationServer::%s failed, no thread available", __FUNCTION__); 3210 return SendErrorResponse (0x15); 3211 } 3212 3213 // Get the thread's register context. 3214 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ()); 3215 if (!reg_context_sp) 3216 { 3217 if (log) 3218 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 ()); 3219 return SendErrorResponse (0x15); 3220 } 3221 3222 // Return the end of registers response if we've iterated one past the end of the register set. 3223 if (reg_index >= reg_context_sp->GetUserRegisterCount ()) 3224 { 3225 if (log) 3226 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetUserRegisterCount ()); 3227 return SendErrorResponse (0x15); 3228 } 3229 3230 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index); 3231 if (!reg_info) 3232 { 3233 if (log) 3234 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index); 3235 return SendErrorResponse (0x15); 3236 } 3237 3238 // Build the reginfos response. 3239 StreamGDBRemote response; 3240 3241 // Retrieve the value 3242 RegisterValue reg_value; 3243 Error error = reg_context_sp->ReadRegister (reg_info, reg_value); 3244 if (error.Fail ()) 3245 { 3246 if (log) 3247 log->Printf ("GDBRemoteCommunicationServer::%s failed, read of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ()); 3248 return SendErrorResponse (0x15); 3249 } 3250 3251 const uint8_t *const data = reinterpret_cast<const uint8_t*> (reg_value.GetBytes ()); 3252 if (!data) 3253 { 3254 if (log) 3255 log->Printf ("GDBRemoteCommunicationServer::%s failed to get data bytes from requested register %" PRIu32, __FUNCTION__, reg_index); 3256 return SendErrorResponse (0x15); 3257 } 3258 3259 // FIXME flip as needed to get data in big/little endian format for this host. 3260 for (uint32_t i = 0; i < reg_value.GetByteSize (); ++i) 3261 response.PutHex8 (data[i]); 3262 3263 return SendPacketNoLock (response.GetData (), response.GetSize ()); 3264 } 3265 3266 GDBRemoteCommunication::PacketResult 3267 GDBRemoteCommunicationServer::Handle_P (StringExtractorGDBRemote &packet) 3268 { 3269 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 3270 3271 // Ensure we're llgs. 3272 if (!IsGdbServer()) 3273 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_P() unimplemented"); 3274 3275 // Ensure there is more content. 3276 if (packet.GetBytesLeft () < 1) 3277 return SendIllFormedResponse (packet, "Empty P packet"); 3278 3279 // Parse out the register number from the request. 3280 packet.SetFilePos (strlen("P")); 3281 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ()); 3282 if (reg_index == std::numeric_limits<uint32_t>::max ()) 3283 { 3284 if (log) 3285 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ()); 3286 return SendErrorResponse (0x29); 3287 } 3288 3289 // Note debugserver would send an E30 here. 3290 if ((packet.GetBytesLeft () < 1) || (packet.GetChar () != '=')) 3291 return SendIllFormedResponse (packet, "P packet missing '=' char after register number"); 3292 3293 // Get process architecture. 3294 ArchSpec process_arch; 3295 if (!m_debugged_process_sp || !m_debugged_process_sp->GetArchitecture (process_arch)) 3296 { 3297 if (log) 3298 log->Printf ("GDBRemoteCommunicationServer::%s failed to retrieve inferior architecture", __FUNCTION__); 3299 return SendErrorResponse (0x49); 3300 } 3301 3302 // Parse out the value. 3303 uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register 3304 size_t reg_size = packet.GetHexBytesAvail (reg_bytes, sizeof(reg_bytes)); 3305 3306 // Get the thread to use. 3307 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet); 3308 if (!thread_sp) 3309 { 3310 if (log) 3311 log->Printf ("GDBRemoteCommunicationServer::%s failed, no thread available (thread index 0)", __FUNCTION__); 3312 return SendErrorResponse (0x28); 3313 } 3314 3315 // Get the thread's register context. 3316 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ()); 3317 if (!reg_context_sp) 3318 { 3319 if (log) 3320 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 ()); 3321 return SendErrorResponse (0x15); 3322 } 3323 3324 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex (reg_index); 3325 if (!reg_info) 3326 { 3327 if (log) 3328 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index); 3329 return SendErrorResponse (0x48); 3330 } 3331 3332 // Return the end of registers response if we've iterated one past the end of the register set. 3333 if (reg_index >= reg_context_sp->GetUserRegisterCount ()) 3334 { 3335 if (log) 3336 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetUserRegisterCount ()); 3337 return SendErrorResponse (0x47); 3338 } 3339 3340 if (reg_size != reg_info->byte_size) 3341 { 3342 return SendIllFormedResponse (packet, "P packet register size is incorrect"); 3343 } 3344 3345 // Build the reginfos response. 3346 StreamGDBRemote response; 3347 3348 RegisterValue reg_value (reg_bytes, reg_size, process_arch.GetByteOrder ()); 3349 Error error = reg_context_sp->WriteRegister (reg_info, reg_value); 3350 if (error.Fail ()) 3351 { 3352 if (log) 3353 log->Printf ("GDBRemoteCommunicationServer::%s failed, write of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ()); 3354 return SendErrorResponse (0x32); 3355 } 3356 3357 return SendOKResponse(); 3358 } 3359 3360 GDBRemoteCommunicationServer::PacketResult 3361 GDBRemoteCommunicationServer::Handle_H (StringExtractorGDBRemote &packet) 3362 { 3363 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 3364 3365 // Ensure we're llgs. 3366 if (!IsGdbServer()) 3367 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_H() unimplemented"); 3368 3369 // Fail if we don't have a current process. 3370 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3371 { 3372 if (log) 3373 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3374 return SendErrorResponse (0x15); 3375 } 3376 3377 // Parse out which variant of $H is requested. 3378 packet.SetFilePos (strlen("H")); 3379 if (packet.GetBytesLeft () < 1) 3380 { 3381 if (log) 3382 log->Printf ("GDBRemoteCommunicationServer::%s failed, H command missing {g,c} variant", __FUNCTION__); 3383 return SendIllFormedResponse (packet, "H command missing {g,c} variant"); 3384 } 3385 3386 const char h_variant = packet.GetChar (); 3387 switch (h_variant) 3388 { 3389 case 'g': 3390 break; 3391 3392 case 'c': 3393 break; 3394 3395 default: 3396 if (log) 3397 log->Printf ("GDBRemoteCommunicationServer::%s failed, invalid $H variant %c", __FUNCTION__, h_variant); 3398 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g"); 3399 } 3400 3401 // Parse out the thread number. 3402 // FIXME return a parse success/fail value. All values are valid here. 3403 const lldb::tid_t tid = packet.GetHexMaxU64 (false, std::numeric_limits<lldb::tid_t>::max ()); 3404 3405 // Ensure we have the given thread when not specifying -1 (all threads) or 0 (any thread). 3406 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) 3407 { 3408 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid)); 3409 if (!thread_sp) 3410 { 3411 if (log) 3412 log->Printf ("GDBRemoteCommunicationServer::%s failed, tid %" PRIu64 " not found", __FUNCTION__, tid); 3413 return SendErrorResponse (0x15); 3414 } 3415 } 3416 3417 // Now switch the given thread type. 3418 switch (h_variant) 3419 { 3420 case 'g': 3421 SetCurrentThreadID (tid); 3422 break; 3423 3424 case 'c': 3425 SetContinueThreadID (tid); 3426 break; 3427 3428 default: 3429 assert (false && "unsupported $H variant - shouldn't get here"); 3430 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g"); 3431 } 3432 3433 return SendOKResponse(); 3434 } 3435 3436 GDBRemoteCommunicationServer::PacketResult 3437 GDBRemoteCommunicationServer::Handle_I (StringExtractorGDBRemote &packet) 3438 { 3439 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 3440 3441 // Ensure we're llgs. 3442 if (!IsGdbServer()) 3443 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_I() unimplemented"); 3444 3445 // Fail if we don't have a current process. 3446 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3447 { 3448 if (log) 3449 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3450 return SendErrorResponse (0x15); 3451 } 3452 3453 packet.SetFilePos (::strlen("I")); 3454 char tmp[4096]; 3455 for (;;) 3456 { 3457 size_t read = packet.GetHexBytesAvail(tmp, sizeof(tmp)); 3458 if (read == 0) 3459 { 3460 break; 3461 } 3462 // write directly to stdin *this might block if stdin buffer is full* 3463 // TODO: enqueue this block in circular buffer and send window size to remote host 3464 ConnectionStatus status; 3465 Error error; 3466 m_stdio_communication.Write(tmp, read, status, &error); 3467 if (error.Fail()) 3468 { 3469 return SendErrorResponse (0x15); 3470 } 3471 } 3472 3473 return SendOKResponse(); 3474 } 3475 3476 GDBRemoteCommunicationServer::PacketResult 3477 GDBRemoteCommunicationServer::Handle_interrupt (StringExtractorGDBRemote &packet) 3478 { 3479 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 3480 3481 // Ensure we're llgs. 3482 if (!IsGdbServer()) 3483 { 3484 // Only supported on llgs 3485 return SendUnimplementedResponse (""); 3486 } 3487 3488 // Fail if we don't have a current process. 3489 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3490 { 3491 if (log) 3492 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3493 return SendErrorResponse (0x15); 3494 } 3495 3496 // Interrupt the process. 3497 Error error = m_debugged_process_sp->Interrupt (); 3498 if (error.Fail ()) 3499 { 3500 if (log) 3501 { 3502 log->Printf ("GDBRemoteCommunicationServer::%s failed for process %" PRIu64 ": %s", 3503 __FUNCTION__, 3504 m_debugged_process_sp->GetID (), 3505 error.AsCString ()); 3506 } 3507 return SendErrorResponse (GDBRemoteServerError::eErrorResume); 3508 } 3509 3510 if (log) 3511 log->Printf ("GDBRemoteCommunicationServer::%s stopped process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ()); 3512 3513 // No response required from stop all. 3514 return PacketResult::Success; 3515 } 3516 3517 GDBRemoteCommunicationServer::PacketResult 3518 GDBRemoteCommunicationServer::Handle_m (StringExtractorGDBRemote &packet) 3519 { 3520 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3521 3522 // Ensure we're llgs. 3523 if (!IsGdbServer()) 3524 { 3525 // Only supported on llgs 3526 return SendUnimplementedResponse (""); 3527 } 3528 3529 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3530 { 3531 if (log) 3532 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3533 return SendErrorResponse (0x15); 3534 } 3535 3536 // Parse out the memory address. 3537 packet.SetFilePos (strlen("m")); 3538 if (packet.GetBytesLeft() < 1) 3539 return SendIllFormedResponse(packet, "Too short m packet"); 3540 3541 // Read the address. Punting on validation. 3542 // FIXME replace with Hex U64 read with no default value that fails on failed read. 3543 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0); 3544 3545 // Validate comma. 3546 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ',')) 3547 return SendIllFormedResponse(packet, "Comma sep missing in m packet"); 3548 3549 // Get # bytes to read. 3550 if (packet.GetBytesLeft() < 1) 3551 return SendIllFormedResponse(packet, "Length missing in m packet"); 3552 3553 const uint64_t byte_count = packet.GetHexMaxU64(false, 0); 3554 if (byte_count == 0) 3555 { 3556 if (log) 3557 log->Printf ("GDBRemoteCommunicationServer::%s nothing to read: zero-length packet", __FUNCTION__); 3558 return PacketResult::Success; 3559 } 3560 3561 // Allocate the response buffer. 3562 std::string buf(byte_count, '\0'); 3563 if (buf.empty()) 3564 return SendErrorResponse (0x78); 3565 3566 3567 // Retrieve the process memory. 3568 lldb::addr_t bytes_read = 0; 3569 lldb_private::Error error = m_debugged_process_sp->ReadMemory (read_addr, &buf[0], byte_count, bytes_read); 3570 if (error.Fail ()) 3571 { 3572 if (log) 3573 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to read. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, error.AsCString ()); 3574 return SendErrorResponse (0x08); 3575 } 3576 3577 if (bytes_read == 0) 3578 { 3579 if (log) 3580 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); 3581 return SendErrorResponse (0x08); 3582 } 3583 3584 StreamGDBRemote response; 3585 for (lldb::addr_t i = 0; i < bytes_read; ++i) 3586 response.PutHex8(buf[i]); 3587 3588 return SendPacketNoLock(response.GetData(), response.GetSize()); 3589 } 3590 3591 GDBRemoteCommunication::PacketResult 3592 GDBRemoteCommunicationServer::Handle_QSetDetachOnError (StringExtractorGDBRemote &packet) 3593 { 3594 packet.SetFilePos(::strlen ("QSetDetachOnError:")); 3595 if (packet.GetU32(0)) 3596 m_process_launch_info.GetFlags().Set (eLaunchFlagDetachOnError); 3597 else 3598 m_process_launch_info.GetFlags().Clear (eLaunchFlagDetachOnError); 3599 return SendOKResponse (); 3600 } 3601 3602 GDBRemoteCommunicationServer::PacketResult 3603 GDBRemoteCommunicationServer::Handle_M (StringExtractorGDBRemote &packet) 3604 { 3605 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3606 3607 // Ensure we're llgs. 3608 if (!IsGdbServer()) 3609 { 3610 // Only supported on llgs 3611 return SendUnimplementedResponse (""); 3612 } 3613 3614 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3615 { 3616 if (log) 3617 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3618 return SendErrorResponse (0x15); 3619 } 3620 3621 // Parse out the memory address. 3622 packet.SetFilePos (strlen("M")); 3623 if (packet.GetBytesLeft() < 1) 3624 return SendIllFormedResponse(packet, "Too short M packet"); 3625 3626 // Read the address. Punting on validation. 3627 // FIXME replace with Hex U64 read with no default value that fails on failed read. 3628 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0); 3629 3630 // Validate comma. 3631 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ',')) 3632 return SendIllFormedResponse(packet, "Comma sep missing in M packet"); 3633 3634 // Get # bytes to read. 3635 if (packet.GetBytesLeft() < 1) 3636 return SendIllFormedResponse(packet, "Length missing in M packet"); 3637 3638 const uint64_t byte_count = packet.GetHexMaxU64(false, 0); 3639 if (byte_count == 0) 3640 { 3641 if (log) 3642 log->Printf ("GDBRemoteCommunicationServer::%s nothing to write: zero-length packet", __FUNCTION__); 3643 return PacketResult::Success; 3644 } 3645 3646 // Validate colon. 3647 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':')) 3648 return SendIllFormedResponse(packet, "Comma sep missing in M packet after byte length"); 3649 3650 // Allocate the conversion buffer. 3651 std::vector<uint8_t> buf(byte_count, 0); 3652 if (buf.empty()) 3653 return SendErrorResponse (0x78); 3654 3655 // Convert the hex memory write contents to bytes. 3656 StreamGDBRemote response; 3657 const uint64_t convert_count = static_cast<uint64_t> (packet.GetHexBytes (&buf[0], byte_count, 0)); 3658 if (convert_count != byte_count) 3659 { 3660 if (log) 3661 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); 3662 return SendIllFormedResponse (packet, "M content byte length specified did not match hex-encoded content length"); 3663 } 3664 3665 // Write the process memory. 3666 lldb::addr_t bytes_written = 0; 3667 lldb_private::Error error = m_debugged_process_sp->WriteMemory (write_addr, &buf[0], byte_count, bytes_written); 3668 if (error.Fail ()) 3669 { 3670 if (log) 3671 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to write. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, error.AsCString ()); 3672 return SendErrorResponse (0x09); 3673 } 3674 3675 if (bytes_written == 0) 3676 { 3677 if (log) 3678 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); 3679 return SendErrorResponse (0x09); 3680 } 3681 3682 return SendOKResponse (); 3683 } 3684 3685 GDBRemoteCommunicationServer::PacketResult 3686 GDBRemoteCommunicationServer::Handle_qMemoryRegionInfoSupported (StringExtractorGDBRemote &packet) 3687 { 3688 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3689 3690 // We don't support if we're not llgs. 3691 if (!IsGdbServer()) 3692 return SendUnimplementedResponse (""); 3693 3694 // Currently only the NativeProcessProtocol knows if it can handle a qMemoryRegionInfoSupported 3695 // request, but we're not guaranteed to be attached to a process. For now we'll assume the 3696 // client only asks this when a process is being debugged. 3697 3698 // Ensure we have a process running; otherwise, we can't figure this out 3699 // since we won't have a NativeProcessProtocol. 3700 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3701 { 3702 if (log) 3703 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3704 return SendErrorResponse (0x15); 3705 } 3706 3707 // Test if we can get any region back when asking for the region around NULL. 3708 MemoryRegionInfo region_info; 3709 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (0, region_info); 3710 if (error.Fail ()) 3711 { 3712 // We don't support memory region info collection for this NativeProcessProtocol. 3713 return SendUnimplementedResponse (""); 3714 } 3715 3716 return SendOKResponse(); 3717 } 3718 3719 GDBRemoteCommunicationServer::PacketResult 3720 GDBRemoteCommunicationServer::Handle_qMemoryRegionInfo (StringExtractorGDBRemote &packet) 3721 { 3722 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3723 3724 // We don't support if we're not llgs. 3725 if (!IsGdbServer()) 3726 return SendUnimplementedResponse (""); 3727 3728 // Ensure we have a process. 3729 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3730 { 3731 if (log) 3732 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3733 return SendErrorResponse (0x15); 3734 } 3735 3736 // Parse out the memory address. 3737 packet.SetFilePos (strlen("qMemoryRegionInfo:")); 3738 if (packet.GetBytesLeft() < 1) 3739 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet"); 3740 3741 // Read the address. Punting on validation. 3742 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0); 3743 3744 StreamGDBRemote response; 3745 3746 // Get the memory region info for the target address. 3747 MemoryRegionInfo region_info; 3748 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (read_addr, region_info); 3749 if (error.Fail ()) 3750 { 3751 // Return the error message. 3752 3753 response.PutCString ("error:"); 3754 response.PutCStringAsRawHex8 (error.AsCString ()); 3755 response.PutChar (';'); 3756 } 3757 else 3758 { 3759 // Range start and size. 3760 response.Printf ("start:%" PRIx64 ";size:%" PRIx64 ";", region_info.GetRange ().GetRangeBase (), region_info.GetRange ().GetByteSize ()); 3761 3762 // Permissions. 3763 if (region_info.GetReadable () || 3764 region_info.GetWritable () || 3765 region_info.GetExecutable ()) 3766 { 3767 // Write permissions info. 3768 response.PutCString ("permissions:"); 3769 3770 if (region_info.GetReadable ()) 3771 response.PutChar ('r'); 3772 if (region_info.GetWritable ()) 3773 response.PutChar('w'); 3774 if (region_info.GetExecutable()) 3775 response.PutChar ('x'); 3776 3777 response.PutChar (';'); 3778 } 3779 } 3780 3781 return SendPacketNoLock(response.GetData(), response.GetSize()); 3782 } 3783 3784 GDBRemoteCommunicationServer::PacketResult 3785 GDBRemoteCommunicationServer::Handle_Z (StringExtractorGDBRemote &packet) 3786 { 3787 // We don't support if we're not llgs. 3788 if (!IsGdbServer()) 3789 return SendUnimplementedResponse (""); 3790 3791 // Ensure we have a process. 3792 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3793 { 3794 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3795 if (log) 3796 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3797 return SendErrorResponse (0x15); 3798 } 3799 3800 // Parse out software or hardware breakpoint or watchpoint requested. 3801 packet.SetFilePos (strlen("Z")); 3802 if (packet.GetBytesLeft() < 1) 3803 return SendIllFormedResponse(packet, "Too short Z packet, missing software/hardware specifier"); 3804 3805 bool want_breakpoint = true; 3806 bool want_hardware = false; 3807 3808 const GDBStoppointType stoppoint_type = 3809 GDBStoppointType(packet.GetS32 (eStoppointInvalid)); 3810 switch (stoppoint_type) 3811 { 3812 case eBreakpointSoftware: 3813 want_hardware = false; want_breakpoint = true; break; 3814 case eBreakpointHardware: 3815 want_hardware = true; want_breakpoint = true; break; 3816 case eWatchpointWrite: 3817 want_hardware = true; want_breakpoint = false; break; 3818 case eWatchpointRead: 3819 want_hardware = true; want_breakpoint = false; break; 3820 case eWatchpointReadWrite: 3821 want_hardware = true; want_breakpoint = false; break; 3822 case eStoppointInvalid: 3823 return SendIllFormedResponse(packet, "Z packet had invalid software/hardware specifier"); 3824 3825 } 3826 3827 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',') 3828 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after stoppoint type"); 3829 3830 // Parse out the stoppoint address. 3831 if (packet.GetBytesLeft() < 1) 3832 return SendIllFormedResponse(packet, "Too short Z packet, missing address"); 3833 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0); 3834 3835 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',') 3836 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after address"); 3837 3838 // Parse out the stoppoint size (i.e. size hint for opcode size). 3839 const uint32_t size = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ()); 3840 if (size == std::numeric_limits<uint32_t>::max ()) 3841 return SendIllFormedResponse(packet, "Malformed Z packet, failed to parse size argument"); 3842 3843 if (want_breakpoint) 3844 { 3845 // Try to set the breakpoint. 3846 const Error error = m_debugged_process_sp->SetBreakpoint (addr, size, want_hardware); 3847 if (error.Success ()) 3848 return SendOKResponse (); 3849 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); 3850 if (log) 3851 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 3852 " failed to set breakpoint: %s", 3853 __FUNCTION__, 3854 m_debugged_process_sp->GetID (), 3855 error.AsCString ()); 3856 return SendErrorResponse (0x09); 3857 } 3858 else 3859 { 3860 uint32_t watch_flags = 3861 stoppoint_type == eWatchpointWrite 3862 ? watch_flags = 0x1 // Write 3863 : watch_flags = 0x3; // ReadWrite 3864 3865 // Try to set the watchpoint. 3866 const Error error = m_debugged_process_sp->SetWatchpoint ( 3867 addr, size, watch_flags, want_hardware); 3868 if (error.Success ()) 3869 return SendOKResponse (); 3870 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS)); 3871 if (log) 3872 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 3873 " failed to set watchpoint: %s", 3874 __FUNCTION__, 3875 m_debugged_process_sp->GetID (), 3876 error.AsCString ()); 3877 return SendErrorResponse (0x09); 3878 } 3879 } 3880 3881 GDBRemoteCommunicationServer::PacketResult 3882 GDBRemoteCommunicationServer::Handle_z (StringExtractorGDBRemote &packet) 3883 { 3884 // We don't support if we're not llgs. 3885 if (!IsGdbServer()) 3886 return SendUnimplementedResponse (""); 3887 3888 // Ensure we have a process. 3889 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3890 { 3891 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3892 if (log) 3893 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3894 return SendErrorResponse (0x15); 3895 } 3896 3897 // Parse out software or hardware breakpoint or watchpoint requested. 3898 packet.SetFilePos (strlen("z")); 3899 if (packet.GetBytesLeft() < 1) 3900 return SendIllFormedResponse(packet, "Too short z packet, missing software/hardware specifier"); 3901 3902 bool want_breakpoint = true; 3903 3904 const GDBStoppointType stoppoint_type = 3905 GDBStoppointType(packet.GetS32 (eStoppointInvalid)); 3906 switch (stoppoint_type) 3907 { 3908 case eBreakpointHardware: want_breakpoint = true; break; 3909 case eBreakpointSoftware: want_breakpoint = true; break; 3910 case eWatchpointWrite: want_breakpoint = false; break; 3911 case eWatchpointRead: want_breakpoint = false; break; 3912 case eWatchpointReadWrite: want_breakpoint = false; break; 3913 default: 3914 return SendIllFormedResponse(packet, "z packet had invalid software/hardware specifier"); 3915 3916 } 3917 3918 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',') 3919 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after stoppoint type"); 3920 3921 // Parse out the stoppoint address. 3922 if (packet.GetBytesLeft() < 1) 3923 return SendIllFormedResponse(packet, "Too short z packet, missing address"); 3924 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0); 3925 3926 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',') 3927 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after address"); 3928 3929 /* 3930 // Parse out the stoppoint size (i.e. size hint for opcode size). 3931 const uint32_t size = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ()); 3932 if (size == std::numeric_limits<uint32_t>::max ()) 3933 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse size argument"); 3934 */ 3935 3936 if (want_breakpoint) 3937 { 3938 // Try to clear the breakpoint. 3939 const Error error = m_debugged_process_sp->RemoveBreakpoint (addr); 3940 if (error.Success ()) 3941 return SendOKResponse (); 3942 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); 3943 if (log) 3944 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 3945 " failed to remove breakpoint: %s", 3946 __FUNCTION__, 3947 m_debugged_process_sp->GetID (), 3948 error.AsCString ()); 3949 return SendErrorResponse (0x09); 3950 } 3951 else 3952 { 3953 // Try to clear the watchpoint. 3954 const Error error = m_debugged_process_sp->RemoveWatchpoint (addr); 3955 if (error.Success ()) 3956 return SendOKResponse (); 3957 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS)); 3958 if (log) 3959 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 3960 " failed to remove watchpoint: %s", 3961 __FUNCTION__, 3962 m_debugged_process_sp->GetID (), 3963 error.AsCString ()); 3964 return SendErrorResponse (0x09); 3965 } 3966 } 3967 3968 GDBRemoteCommunicationServer::PacketResult 3969 GDBRemoteCommunicationServer::Handle_s (StringExtractorGDBRemote &packet) 3970 { 3971 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD)); 3972 3973 // We don't support if we're not llgs. 3974 if (!IsGdbServer()) 3975 return SendUnimplementedResponse (""); 3976 3977 // Ensure we have a process. 3978 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 3979 { 3980 if (log) 3981 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 3982 return SendErrorResponse (0x32); 3983 } 3984 3985 // We first try to use a continue thread id. If any one or any all set, use the current thread. 3986 // Bail out if we don't have a thread id. 3987 lldb::tid_t tid = GetContinueThreadID (); 3988 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID) 3989 tid = GetCurrentThreadID (); 3990 if (tid == LLDB_INVALID_THREAD_ID) 3991 return SendErrorResponse (0x33); 3992 3993 // Double check that we have such a thread. 3994 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here. 3995 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID (tid); 3996 if (!thread_sp || thread_sp->GetID () != tid) 3997 return SendErrorResponse (0x33); 3998 3999 // Create the step action for the given thread. 4000 lldb_private::ResumeAction action = { tid, eStateStepping, 0 }; 4001 4002 // Setup the actions list. 4003 lldb_private::ResumeActionList actions; 4004 actions.Append (action); 4005 4006 // All other threads stop while we're single stepping a thread. 4007 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0); 4008 Error error = m_debugged_process_sp->Resume (actions); 4009 if (error.Fail ()) 4010 { 4011 if (log) 4012 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " Resume() failed with error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), tid, error.AsCString ()); 4013 return SendErrorResponse(0x49); 4014 } 4015 4016 // No response here - the stop or exit will come from the resulting action. 4017 return PacketResult::Success; 4018 } 4019 4020 GDBRemoteCommunicationServer::PacketResult 4021 GDBRemoteCommunicationServer::Handle_qSupported (StringExtractorGDBRemote &packet) 4022 { 4023 StreamGDBRemote response; 4024 4025 // Features common to lldb-platform and llgs. 4026 uint32_t max_packet_size = 128 * 1024; // 128KBytes is a reasonable max packet size--debugger can always use less 4027 response.Printf ("PacketSize=%x", max_packet_size); 4028 4029 response.PutCString (";QStartNoAckMode+"); 4030 response.PutCString (";QThreadSuffixSupported+"); 4031 response.PutCString (";QListThreadsInStopReply+"); 4032 #if defined(__linux__) 4033 response.PutCString (";qXfer:auxv:read+"); 4034 #endif 4035 4036 return SendPacketNoLock(response.GetData(), response.GetSize()); 4037 } 4038 4039 GDBRemoteCommunicationServer::PacketResult 4040 GDBRemoteCommunicationServer::Handle_QThreadSuffixSupported (StringExtractorGDBRemote &packet) 4041 { 4042 m_thread_suffix_supported = true; 4043 return SendOKResponse(); 4044 } 4045 4046 GDBRemoteCommunicationServer::PacketResult 4047 GDBRemoteCommunicationServer::Handle_QListThreadsInStopReply (StringExtractorGDBRemote &packet) 4048 { 4049 m_list_threads_in_stop_reply = true; 4050 return SendOKResponse(); 4051 } 4052 4053 GDBRemoteCommunicationServer::PacketResult 4054 GDBRemoteCommunicationServer::Handle_qXfer_auxv_read (StringExtractorGDBRemote &packet) 4055 { 4056 // We don't support if we're not llgs. 4057 if (!IsGdbServer()) 4058 return SendUnimplementedResponse ("only supported for lldb-gdbserver"); 4059 4060 // *BSD impls should be able to do this too. 4061 #if defined(__linux__) 4062 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 4063 4064 // Parse out the offset. 4065 packet.SetFilePos (strlen("qXfer:auxv:read::")); 4066 if (packet.GetBytesLeft () < 1) 4067 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset"); 4068 4069 const uint64_t auxv_offset = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ()); 4070 if (auxv_offset == std::numeric_limits<uint64_t>::max ()) 4071 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset"); 4072 4073 // Parse out comma. 4074 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ',') 4075 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing comma after offset"); 4076 4077 // Parse out the length. 4078 const uint64_t auxv_length = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ()); 4079 if (auxv_length == std::numeric_limits<uint64_t>::max ()) 4080 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing length"); 4081 4082 // Grab the auxv data if we need it. 4083 if (!m_active_auxv_buffer_sp) 4084 { 4085 // Make sure we have a valid process. 4086 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 4087 { 4088 if (log) 4089 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 4090 return SendErrorResponse (0x10); 4091 } 4092 4093 // Grab the auxv data. 4094 m_active_auxv_buffer_sp = Host::GetAuxvData (m_debugged_process_sp->GetID ()); 4095 if (!m_active_auxv_buffer_sp || m_active_auxv_buffer_sp->GetByteSize () == 0) 4096 { 4097 // Hmm, no auxv data, call that an error. 4098 if (log) 4099 log->Printf ("GDBRemoteCommunicationServer::%s failed, no auxv data retrieved", __FUNCTION__); 4100 m_active_auxv_buffer_sp.reset (); 4101 return SendErrorResponse (0x11); 4102 } 4103 } 4104 4105 // FIXME find out if/how I lock the stream here. 4106 4107 StreamGDBRemote response; 4108 bool done_with_buffer = false; 4109 4110 if (auxv_offset >= m_active_auxv_buffer_sp->GetByteSize ()) 4111 { 4112 // We have nothing left to send. Mark the buffer as complete. 4113 response.PutChar ('l'); 4114 done_with_buffer = true; 4115 } 4116 else 4117 { 4118 // Figure out how many bytes are available starting at the given offset. 4119 const uint64_t bytes_remaining = m_active_auxv_buffer_sp->GetByteSize () - auxv_offset; 4120 4121 // Figure out how many bytes we're going to read. 4122 const uint64_t bytes_to_read = (auxv_length > bytes_remaining) ? bytes_remaining : auxv_length; 4123 4124 // Mark the response type according to whether we're reading the remainder of the auxv data. 4125 if (bytes_to_read >= bytes_remaining) 4126 { 4127 // There will be nothing left to read after this 4128 response.PutChar ('l'); 4129 done_with_buffer = true; 4130 } 4131 else 4132 { 4133 // There will still be bytes to read after this request. 4134 response.PutChar ('m'); 4135 } 4136 4137 // Now write the data in encoded binary form. 4138 response.PutEscapedBytes (m_active_auxv_buffer_sp->GetBytes () + auxv_offset, bytes_to_read); 4139 } 4140 4141 if (done_with_buffer) 4142 m_active_auxv_buffer_sp.reset (); 4143 4144 return SendPacketNoLock(response.GetData(), response.GetSize()); 4145 #else 4146 return SendUnimplementedResponse ("not implemented on this platform"); 4147 #endif 4148 } 4149 4150 GDBRemoteCommunicationServer::PacketResult 4151 GDBRemoteCommunicationServer::Handle_QSaveRegisterState (StringExtractorGDBRemote &packet) 4152 { 4153 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 4154 4155 // We don't support if we're not llgs. 4156 if (!IsGdbServer()) 4157 return SendUnimplementedResponse ("only supported for lldb-gdbserver"); 4158 4159 // Move past packet name. 4160 packet.SetFilePos (strlen ("QSaveRegisterState")); 4161 4162 // Get the thread to use. 4163 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet); 4164 if (!thread_sp) 4165 { 4166 if (m_thread_suffix_supported) 4167 return SendIllFormedResponse (packet, "No thread specified in QSaveRegisterState packet"); 4168 else 4169 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet"); 4170 } 4171 4172 // Grab the register context for the thread. 4173 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ()); 4174 if (!reg_context_sp) 4175 { 4176 if (log) 4177 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 ()); 4178 return SendErrorResponse (0x15); 4179 } 4180 4181 // Save registers to a buffer. 4182 DataBufferSP register_data_sp; 4183 Error error = reg_context_sp->ReadAllRegisterValues (register_data_sp); 4184 if (error.Fail ()) 4185 { 4186 if (log) 4187 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to save all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ()); 4188 return SendErrorResponse (0x75); 4189 } 4190 4191 // Allocate a new save id. 4192 const uint32_t save_id = GetNextSavedRegistersID (); 4193 assert ((m_saved_registers_map.find (save_id) == m_saved_registers_map.end ()) && "GetNextRegisterSaveID() returned an existing register save id"); 4194 4195 // Save the register data buffer under the save id. 4196 { 4197 Mutex::Locker locker (m_saved_registers_mutex); 4198 m_saved_registers_map[save_id] = register_data_sp; 4199 } 4200 4201 // Write the response. 4202 StreamGDBRemote response; 4203 response.Printf ("%" PRIu32, save_id); 4204 return SendPacketNoLock(response.GetData(), response.GetSize()); 4205 } 4206 4207 GDBRemoteCommunicationServer::PacketResult 4208 GDBRemoteCommunicationServer::Handle_QRestoreRegisterState (StringExtractorGDBRemote &packet) 4209 { 4210 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 4211 4212 // We don't support if we're not llgs. 4213 if (!IsGdbServer()) 4214 return SendUnimplementedResponse ("only supported for lldb-gdbserver"); 4215 4216 // Parse out save id. 4217 packet.SetFilePos (strlen ("QRestoreRegisterState:")); 4218 if (packet.GetBytesLeft () < 1) 4219 return SendIllFormedResponse (packet, "QRestoreRegisterState packet missing register save id"); 4220 4221 const uint32_t save_id = packet.GetU32 (0); 4222 if (save_id == 0) 4223 { 4224 if (log) 4225 log->Printf ("GDBRemoteCommunicationServer::%s QRestoreRegisterState packet has malformed save id, expecting decimal uint32_t", __FUNCTION__); 4226 return SendErrorResponse (0x76); 4227 } 4228 4229 // Get the thread to use. 4230 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet); 4231 if (!thread_sp) 4232 { 4233 if (m_thread_suffix_supported) 4234 return SendIllFormedResponse (packet, "No thread specified in QRestoreRegisterState packet"); 4235 else 4236 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet"); 4237 } 4238 4239 // Grab the register context for the thread. 4240 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ()); 4241 if (!reg_context_sp) 4242 { 4243 if (log) 4244 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 ()); 4245 return SendErrorResponse (0x15); 4246 } 4247 4248 // Retrieve register state buffer, then remove from the list. 4249 DataBufferSP register_data_sp; 4250 { 4251 Mutex::Locker locker (m_saved_registers_mutex); 4252 4253 // Find the register set buffer for the given save id. 4254 auto it = m_saved_registers_map.find (save_id); 4255 if (it == m_saved_registers_map.end ()) 4256 { 4257 if (log) 4258 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); 4259 return SendErrorResponse (0x77); 4260 } 4261 register_data_sp = it->second; 4262 4263 // Remove it from the map. 4264 m_saved_registers_map.erase (it); 4265 } 4266 4267 Error error = reg_context_sp->WriteAllRegisterValues (register_data_sp); 4268 if (error.Fail ()) 4269 { 4270 if (log) 4271 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to restore all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ()); 4272 return SendErrorResponse (0x77); 4273 } 4274 4275 return SendOKResponse(); 4276 } 4277 4278 GDBRemoteCommunicationServer::PacketResult 4279 GDBRemoteCommunicationServer::Handle_vAttach (StringExtractorGDBRemote &packet) 4280 { 4281 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 4282 4283 // We don't support if we're not llgs. 4284 if (!IsGdbServer()) 4285 return SendUnimplementedResponse ("only supported for lldb-gdbserver"); 4286 4287 // Consume the ';' after vAttach. 4288 packet.SetFilePos (strlen ("vAttach")); 4289 if (!packet.GetBytesLeft () || packet.GetChar () != ';') 4290 return SendIllFormedResponse (packet, "vAttach missing expected ';'"); 4291 4292 // Grab the PID to which we will attach (assume hex encoding). 4293 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16); 4294 if (pid == LLDB_INVALID_PROCESS_ID) 4295 return SendIllFormedResponse (packet, "vAttach failed to parse the process id"); 4296 4297 // Attempt to attach. 4298 if (log) 4299 log->Printf ("GDBRemoteCommunicationServer::%s attempting to attach to pid %" PRIu64, __FUNCTION__, pid); 4300 4301 Error error = AttachToProcess (pid); 4302 4303 if (error.Fail ()) 4304 { 4305 if (log) 4306 log->Printf ("GDBRemoteCommunicationServer::%s failed to attach to pid %" PRIu64 ": %s\n", __FUNCTION__, pid, error.AsCString()); 4307 return SendErrorResponse (0x01); 4308 } 4309 4310 // Notify we attached by sending a stop packet. 4311 return SendStopReasonForState (m_debugged_process_sp->GetState (), true); 4312 } 4313 4314 GDBRemoteCommunicationServer::PacketResult 4315 GDBRemoteCommunicationServer::Handle_D (StringExtractorGDBRemote &packet) 4316 { 4317 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS)); 4318 4319 // We don't support if we're not llgs. 4320 if (!IsGdbServer()) 4321 return SendUnimplementedResponse ("only supported for lldb-gdbserver"); 4322 4323 // Scope for mutex locker. 4324 Mutex::Locker locker (m_spawned_pids_mutex); 4325 4326 // Fail if we don't have a current process. 4327 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)) 4328 { 4329 if (log) 4330 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__); 4331 return SendErrorResponse (0x15); 4332 } 4333 4334 if (m_spawned_pids.find(m_debugged_process_sp->GetID ()) == m_spawned_pids.end()) 4335 { 4336 if (log) 4337 log->Printf ("GDBRemoteCommunicationServer::%s failed to find PID %" PRIu64 " in spawned pids list", 4338 __FUNCTION__, m_debugged_process_sp->GetID ()); 4339 return SendErrorResponse (0x1); 4340 } 4341 4342 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; 4343 4344 // Consume the ';' after D. 4345 packet.SetFilePos (1); 4346 if (packet.GetBytesLeft ()) 4347 { 4348 if (packet.GetChar () != ';') 4349 return SendIllFormedResponse (packet, "D missing expected ';'"); 4350 4351 // Grab the PID from which we will detach (assume hex encoding). 4352 pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16); 4353 if (pid == LLDB_INVALID_PROCESS_ID) 4354 return SendIllFormedResponse (packet, "D failed to parse the process id"); 4355 } 4356 4357 if (pid != LLDB_INVALID_PROCESS_ID && 4358 m_debugged_process_sp->GetID () != pid) 4359 { 4360 return SendIllFormedResponse (packet, "Invalid pid"); 4361 } 4362 4363 if (m_stdio_communication.IsConnected ()) 4364 { 4365 m_stdio_communication.StopReadThread (); 4366 } 4367 4368 const Error error = m_debugged_process_sp->Detach (); 4369 if (error.Fail ()) 4370 { 4371 if (log) 4372 log->Printf ("GDBRemoteCommunicationServer::%s failed to detach from pid %" PRIu64 ": %s\n", 4373 __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ()); 4374 return SendErrorResponse (0x01); 4375 } 4376 4377 m_spawned_pids.erase (m_debugged_process_sp->GetID ()); 4378 return SendOKResponse (); 4379 } 4380 4381 GDBRemoteCommunicationServer::PacketResult 4382 GDBRemoteCommunicationServer::Handle_qThreadStopInfo (StringExtractorGDBRemote &packet) 4383 { 4384 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 4385 4386 // We don't support if we're not llgs. 4387 if (!IsGdbServer()) 4388 return SendUnimplementedResponse ("only supported for lldb-gdbserver"); 4389 4390 packet.SetFilePos (strlen("qThreadStopInfo")); 4391 const lldb::tid_t tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID); 4392 if (tid == LLDB_INVALID_THREAD_ID) 4393 { 4394 if (log) 4395 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse thread id from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ()); 4396 return SendErrorResponse (0x15); 4397 } 4398 return SendStopReplyPacketForThread (tid); 4399 } 4400 4401 GDBRemoteCommunicationServer::PacketResult 4402 GDBRemoteCommunicationServer::Handle_qWatchpointSupportInfo (StringExtractorGDBRemote &packet) 4403 { 4404 // Only the gdb server handles this. 4405 if (!IsGdbServer ()) 4406 return SendUnimplementedResponse (packet.GetStringRef ().c_str ()); 4407 4408 // Fail if we don't have a current process. 4409 if (!m_debugged_process_sp || 4410 m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID) 4411 return SendErrorResponse (68); 4412 4413 packet.SetFilePos(strlen("qWatchpointSupportInfo")); 4414 if (packet.GetBytesLeft() == 0) 4415 return SendOKResponse(); 4416 if (packet.GetChar() != ':') 4417 return SendErrorResponse(67); 4418 4419 uint32_t num = m_debugged_process_sp->GetMaxWatchpoints(); 4420 StreamGDBRemote response; 4421 response.Printf ("num:%d;", num); 4422 return SendPacketNoLock(response.GetData(), response.GetSize()); 4423 } 4424 4425 void 4426 GDBRemoteCommunicationServer::FlushInferiorOutput () 4427 { 4428 // If we're not monitoring an inferior's terminal, ignore this. 4429 if (!m_stdio_communication.IsConnected()) 4430 return; 4431 4432 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 4433 if (log) 4434 log->Printf ("GDBRemoteCommunicationServer::%s() called", __FUNCTION__); 4435 4436 // FIXME implement a timeout on the join. 4437 m_stdio_communication.JoinReadThread(); 4438 } 4439 4440 void 4441 GDBRemoteCommunicationServer::MaybeCloseInferiorTerminalConnection () 4442 { 4443 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 4444 4445 // Tell the stdio connection to shut down. 4446 if (m_stdio_communication.IsConnected()) 4447 { 4448 auto connection = m_stdio_communication.GetConnection(); 4449 if (connection) 4450 { 4451 Error error; 4452 connection->Disconnect (&error); 4453 4454 if (error.Success ()) 4455 { 4456 if (log) 4457 log->Printf ("GDBRemoteCommunicationServer::%s disconnect process terminal stdio - SUCCESS", __FUNCTION__); 4458 } 4459 else 4460 { 4461 if (log) 4462 log->Printf ("GDBRemoteCommunicationServer::%s disconnect process terminal stdio - FAIL: %s", __FUNCTION__, error.AsCString ()); 4463 } 4464 } 4465 } 4466 } 4467 4468 4469 lldb_private::NativeThreadProtocolSP 4470 GDBRemoteCommunicationServer::GetThreadFromSuffix (StringExtractorGDBRemote &packet) 4471 { 4472 NativeThreadProtocolSP thread_sp; 4473 4474 // We have no thread if we don't have a process. 4475 if (!m_debugged_process_sp || m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID) 4476 return thread_sp; 4477 4478 // If the client hasn't asked for thread suffix support, there will not be a thread suffix. 4479 // Use the current thread in that case. 4480 if (!m_thread_suffix_supported) 4481 { 4482 const lldb::tid_t current_tid = GetCurrentThreadID (); 4483 if (current_tid == LLDB_INVALID_THREAD_ID) 4484 return thread_sp; 4485 else if (current_tid == 0) 4486 { 4487 // Pick a thread. 4488 return m_debugged_process_sp->GetThreadAtIndex (0); 4489 } 4490 else 4491 return m_debugged_process_sp->GetThreadByID (current_tid); 4492 } 4493 4494 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 4495 4496 // Parse out the ';'. 4497 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ';') 4498 { 4499 if (log) 4500 log->Printf ("GDBRemoteCommunicationServer::%s gdb-remote parse error: expected ';' prior to start of thread suffix: packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ()); 4501 return thread_sp; 4502 } 4503 4504 if (!packet.GetBytesLeft ()) 4505 return thread_sp; 4506 4507 // Parse out thread: portion. 4508 if (strncmp (packet.Peek (), "thread:", strlen("thread:")) != 0) 4509 { 4510 if (log) 4511 log->Printf ("GDBRemoteCommunicationServer::%s gdb-remote parse error: expected 'thread:' but not found, packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ()); 4512 return thread_sp; 4513 } 4514 packet.SetFilePos (packet.GetFilePos () + strlen("thread:")); 4515 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0); 4516 if (tid != 0) 4517 return m_debugged_process_sp->GetThreadByID (tid); 4518 4519 return thread_sp; 4520 } 4521 4522 lldb::tid_t 4523 GDBRemoteCommunicationServer::GetCurrentThreadID () const 4524 { 4525 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) 4526 { 4527 // Use whatever the debug process says is the current thread id 4528 // since the protocol either didn't specify or specified we want 4529 // any/all threads marked as the current thread. 4530 if (!m_debugged_process_sp) 4531 return LLDB_INVALID_THREAD_ID; 4532 return m_debugged_process_sp->GetCurrentThreadID (); 4533 } 4534 // Use the specific current thread id set by the gdb remote protocol. 4535 return m_current_tid; 4536 } 4537 4538 uint32_t 4539 GDBRemoteCommunicationServer::GetNextSavedRegistersID () 4540 { 4541 Mutex::Locker locker (m_saved_registers_mutex); 4542 return m_next_saved_registers_id++; 4543 } 4544 4545 void 4546 GDBRemoteCommunicationServer::ClearProcessSpecificData () 4547 { 4548 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|GDBR_LOG_PROCESS)); 4549 if (log) 4550 log->Printf ("GDBRemoteCommunicationServer::%s()", __FUNCTION__); 4551 4552 // Clear any auxv cached data. 4553 // *BSD impls should be able to do this too. 4554 #if defined(__linux__) 4555 if (log) 4556 log->Printf ("GDBRemoteCommunicationServer::%s clearing auxv buffer (previously %s)", 4557 __FUNCTION__, 4558 m_active_auxv_buffer_sp ? "was set" : "was not set"); 4559 m_active_auxv_buffer_sp.reset (); 4560 #endif 4561 } 4562