1 //===-- GDBRemoteCommunicationServerLLGS.cpp ------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include <cerrno> 10 11 #include "lldb/Host/Config.h" 12 13 14 #include <chrono> 15 #include <cstring> 16 #include <limits> 17 #include <thread> 18 19 #include "GDBRemoteCommunicationServerLLGS.h" 20 #include "lldb/Host/ConnectionFileDescriptor.h" 21 #include "lldb/Host/Debug.h" 22 #include "lldb/Host/File.h" 23 #include "lldb/Host/FileAction.h" 24 #include "lldb/Host/FileSystem.h" 25 #include "lldb/Host/Host.h" 26 #include "lldb/Host/HostInfo.h" 27 #include "lldb/Host/PosixApi.h" 28 #include "lldb/Host/Socket.h" 29 #include "lldb/Host/common/NativeProcessProtocol.h" 30 #include "lldb/Host/common/NativeRegisterContext.h" 31 #include "lldb/Host/common/NativeThreadProtocol.h" 32 #include "lldb/Target/MemoryRegionInfo.h" 33 #include "lldb/Utility/Args.h" 34 #include "lldb/Utility/DataBuffer.h" 35 #include "lldb/Utility/Endian.h" 36 #include "lldb/Utility/GDBRemote.h" 37 #include "lldb/Utility/LLDBAssert.h" 38 #include "lldb/Utility/LLDBLog.h" 39 #include "lldb/Utility/Log.h" 40 #include "lldb/Utility/RegisterValue.h" 41 #include "lldb/Utility/State.h" 42 #include "lldb/Utility/StreamString.h" 43 #include "lldb/Utility/UnimplementedError.h" 44 #include "lldb/Utility/UriParser.h" 45 #include "llvm/ADT/Triple.h" 46 #include "llvm/Support/JSON.h" 47 #include "llvm/Support/ScopedPrinter.h" 48 49 #include "ProcessGDBRemote.h" 50 #include "ProcessGDBRemoteLog.h" 51 #include "lldb/Utility/StringExtractorGDBRemote.h" 52 53 using namespace lldb; 54 using namespace lldb_private; 55 using namespace lldb_private::process_gdb_remote; 56 using namespace llvm; 57 58 // GDBRemote Errors 59 60 namespace { 61 enum GDBRemoteServerError { 62 // Set to the first unused error number in literal form below 63 eErrorFirst = 29, 64 eErrorNoProcess = eErrorFirst, 65 eErrorResume, 66 eErrorExitStatus 67 }; 68 } 69 70 // GDBRemoteCommunicationServerLLGS constructor 71 GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS( 72 MainLoop &mainloop, const NativeProcessProtocol::Factory &process_factory) 73 : GDBRemoteCommunicationServerCommon("gdb-remote.server", 74 "gdb-remote.server.rx_packet"), 75 m_mainloop(mainloop), m_process_factory(process_factory), 76 m_current_process(nullptr), m_continue_process(nullptr), 77 m_stdio_communication("process.stdio") { 78 RegisterPacketHandlers(); 79 } 80 81 void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() { 82 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C, 83 &GDBRemoteCommunicationServerLLGS::Handle_C); 84 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c, 85 &GDBRemoteCommunicationServerLLGS::Handle_c); 86 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D, 87 &GDBRemoteCommunicationServerLLGS::Handle_D); 88 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H, 89 &GDBRemoteCommunicationServerLLGS::Handle_H); 90 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I, 91 &GDBRemoteCommunicationServerLLGS::Handle_I); 92 RegisterMemberFunctionHandler( 93 StringExtractorGDBRemote::eServerPacketType_interrupt, 94 &GDBRemoteCommunicationServerLLGS::Handle_interrupt); 95 RegisterMemberFunctionHandler( 96 StringExtractorGDBRemote::eServerPacketType_m, 97 &GDBRemoteCommunicationServerLLGS::Handle_memory_read); 98 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M, 99 &GDBRemoteCommunicationServerLLGS::Handle_M); 100 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType__M, 101 &GDBRemoteCommunicationServerLLGS::Handle__M); 102 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType__m, 103 &GDBRemoteCommunicationServerLLGS::Handle__m); 104 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p, 105 &GDBRemoteCommunicationServerLLGS::Handle_p); 106 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P, 107 &GDBRemoteCommunicationServerLLGS::Handle_P); 108 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC, 109 &GDBRemoteCommunicationServerLLGS::Handle_qC); 110 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_T, 111 &GDBRemoteCommunicationServerLLGS::Handle_T); 112 RegisterMemberFunctionHandler( 113 StringExtractorGDBRemote::eServerPacketType_qfThreadInfo, 114 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo); 115 RegisterMemberFunctionHandler( 116 StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress, 117 &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress); 118 RegisterMemberFunctionHandler( 119 StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir, 120 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir); 121 RegisterMemberFunctionHandler( 122 StringExtractorGDBRemote::eServerPacketType_QThreadSuffixSupported, 123 &GDBRemoteCommunicationServerLLGS::Handle_QThreadSuffixSupported); 124 RegisterMemberFunctionHandler( 125 StringExtractorGDBRemote::eServerPacketType_QListThreadsInStopReply, 126 &GDBRemoteCommunicationServerLLGS::Handle_QListThreadsInStopReply); 127 RegisterMemberFunctionHandler( 128 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo, 129 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo); 130 RegisterMemberFunctionHandler( 131 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported, 132 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported); 133 RegisterMemberFunctionHandler( 134 StringExtractorGDBRemote::eServerPacketType_qProcessInfo, 135 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo); 136 RegisterMemberFunctionHandler( 137 StringExtractorGDBRemote::eServerPacketType_qRegisterInfo, 138 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo); 139 RegisterMemberFunctionHandler( 140 StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState, 141 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState); 142 RegisterMemberFunctionHandler( 143 StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState, 144 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState); 145 RegisterMemberFunctionHandler( 146 StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR, 147 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR); 148 RegisterMemberFunctionHandler( 149 StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir, 150 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir); 151 RegisterMemberFunctionHandler( 152 StringExtractorGDBRemote::eServerPacketType_qsThreadInfo, 153 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo); 154 RegisterMemberFunctionHandler( 155 StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo, 156 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo); 157 RegisterMemberFunctionHandler( 158 StringExtractorGDBRemote::eServerPacketType_jThreadsInfo, 159 &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo); 160 RegisterMemberFunctionHandler( 161 StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo, 162 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo); 163 RegisterMemberFunctionHandler( 164 StringExtractorGDBRemote::eServerPacketType_qXfer, 165 &GDBRemoteCommunicationServerLLGS::Handle_qXfer); 166 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s, 167 &GDBRemoteCommunicationServerLLGS::Handle_s); 168 RegisterMemberFunctionHandler( 169 StringExtractorGDBRemote::eServerPacketType_stop_reason, 170 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ? 171 RegisterMemberFunctionHandler( 172 StringExtractorGDBRemote::eServerPacketType_vAttach, 173 &GDBRemoteCommunicationServerLLGS::Handle_vAttach); 174 RegisterMemberFunctionHandler( 175 StringExtractorGDBRemote::eServerPacketType_vAttachWait, 176 &GDBRemoteCommunicationServerLLGS::Handle_vAttachWait); 177 RegisterMemberFunctionHandler( 178 StringExtractorGDBRemote::eServerPacketType_qVAttachOrWaitSupported, 179 &GDBRemoteCommunicationServerLLGS::Handle_qVAttachOrWaitSupported); 180 RegisterMemberFunctionHandler( 181 StringExtractorGDBRemote::eServerPacketType_vAttachOrWait, 182 &GDBRemoteCommunicationServerLLGS::Handle_vAttachOrWait); 183 RegisterMemberFunctionHandler( 184 StringExtractorGDBRemote::eServerPacketType_vCont, 185 &GDBRemoteCommunicationServerLLGS::Handle_vCont); 186 RegisterMemberFunctionHandler( 187 StringExtractorGDBRemote::eServerPacketType_vCont_actions, 188 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions); 189 RegisterMemberFunctionHandler( 190 StringExtractorGDBRemote::eServerPacketType_vRun, 191 &GDBRemoteCommunicationServerLLGS::Handle_vRun); 192 RegisterMemberFunctionHandler( 193 StringExtractorGDBRemote::eServerPacketType_x, 194 &GDBRemoteCommunicationServerLLGS::Handle_memory_read); 195 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z, 196 &GDBRemoteCommunicationServerLLGS::Handle_Z); 197 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z, 198 &GDBRemoteCommunicationServerLLGS::Handle_z); 199 RegisterMemberFunctionHandler( 200 StringExtractorGDBRemote::eServerPacketType_QPassSignals, 201 &GDBRemoteCommunicationServerLLGS::Handle_QPassSignals); 202 203 RegisterMemberFunctionHandler( 204 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceSupported, 205 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceSupported); 206 RegisterMemberFunctionHandler( 207 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceStart, 208 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStart); 209 RegisterMemberFunctionHandler( 210 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceStop, 211 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStop); 212 RegisterMemberFunctionHandler( 213 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceGetState, 214 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetState); 215 RegisterMemberFunctionHandler( 216 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceGetBinaryData, 217 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetBinaryData); 218 219 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_g, 220 &GDBRemoteCommunicationServerLLGS::Handle_g); 221 222 RegisterMemberFunctionHandler( 223 StringExtractorGDBRemote::eServerPacketType_qMemTags, 224 &GDBRemoteCommunicationServerLLGS::Handle_qMemTags); 225 226 RegisterMemberFunctionHandler( 227 StringExtractorGDBRemote::eServerPacketType_QMemTags, 228 &GDBRemoteCommunicationServerLLGS::Handle_QMemTags); 229 230 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k, 231 [this](StringExtractorGDBRemote packet, Status &error, 232 bool &interrupt, bool &quit) { 233 quit = true; 234 return this->Handle_k(packet); 235 }); 236 237 RegisterMemberFunctionHandler( 238 StringExtractorGDBRemote::eServerPacketType_vKill, 239 &GDBRemoteCommunicationServerLLGS::Handle_vKill); 240 241 RegisterMemberFunctionHandler( 242 StringExtractorGDBRemote::eServerPacketType_qLLDBSaveCore, 243 &GDBRemoteCommunicationServerLLGS::Handle_qSaveCore); 244 245 RegisterMemberFunctionHandler( 246 StringExtractorGDBRemote::eServerPacketType_QNonStop, 247 &GDBRemoteCommunicationServerLLGS::Handle_QNonStop); 248 RegisterMemberFunctionHandler( 249 StringExtractorGDBRemote::eServerPacketType_vStopped, 250 &GDBRemoteCommunicationServerLLGS::Handle_vStopped); 251 RegisterMemberFunctionHandler( 252 StringExtractorGDBRemote::eServerPacketType_vCtrlC, 253 &GDBRemoteCommunicationServerLLGS::Handle_vCtrlC); 254 } 255 256 void GDBRemoteCommunicationServerLLGS::SetLaunchInfo(const ProcessLaunchInfo &info) { 257 m_process_launch_info = info; 258 } 259 260 Status GDBRemoteCommunicationServerLLGS::LaunchProcess() { 261 Log *log = GetLog(LLDBLog::Process); 262 263 if (!m_process_launch_info.GetArguments().GetArgumentCount()) 264 return Status("%s: no process command line specified to launch", 265 __FUNCTION__); 266 267 const bool should_forward_stdio = 268 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr || 269 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr || 270 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr; 271 m_process_launch_info.SetLaunchInSeparateProcessGroup(true); 272 m_process_launch_info.GetFlags().Set(eLaunchFlagDebug); 273 274 if (should_forward_stdio) { 275 // Temporarily relax the following for Windows until we can take advantage 276 // of the recently added pty support. This doesn't really affect the use of 277 // lldb-server on Windows. 278 #if !defined(_WIN32) 279 if (llvm::Error Err = m_process_launch_info.SetUpPtyRedirection()) 280 return Status(std::move(Err)); 281 #endif 282 } 283 284 { 285 std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex); 286 assert(m_debugged_processes.empty() && "lldb-server creating debugged " 287 "process but one already exists"); 288 auto process_or = 289 m_process_factory.Launch(m_process_launch_info, *this, m_mainloop); 290 if (!process_or) 291 return Status(process_or.takeError()); 292 m_continue_process = m_current_process = process_or->get(); 293 m_debugged_processes.emplace( 294 m_current_process->GetID(), 295 DebuggedProcess{std::move(*process_or), DebuggedProcess::Flag{}}); 296 } 297 298 SetEnabledExtensions(*m_current_process); 299 300 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol as 301 // needed. llgs local-process debugging may specify PTY paths, which will 302 // make these file actions non-null process launch -i/e/o will also make 303 // these file actions non-null nullptr means that the traffic is expected to 304 // flow over gdb-remote protocol 305 if (should_forward_stdio) { 306 // nullptr means it's not redirected to file or pty (in case of LLGS local) 307 // at least one of stdio will be transferred pty<->gdb-remote we need to 308 // give the pty primary handle to this object to read and/or write 309 LLDB_LOG(log, 310 "pid = {0}: setting up stdout/stderr redirection via $O " 311 "gdb-remote commands", 312 m_current_process->GetID()); 313 314 // Setup stdout/stderr mapping from inferior to $O 315 auto terminal_fd = m_current_process->GetTerminalFileDescriptor(); 316 if (terminal_fd >= 0) { 317 LLDB_LOGF(log, 318 "ProcessGDBRemoteCommunicationServerLLGS::%s setting " 319 "inferior STDIO fd to %d", 320 __FUNCTION__, terminal_fd); 321 Status status = SetSTDIOFileDescriptor(terminal_fd); 322 if (status.Fail()) 323 return status; 324 } else { 325 LLDB_LOGF(log, 326 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring " 327 "inferior STDIO since terminal fd reported as %d", 328 __FUNCTION__, terminal_fd); 329 } 330 } else { 331 LLDB_LOG(log, 332 "pid = {0} skipping stdout/stderr redirection via $O: inferior " 333 "will communicate over client-provided file descriptors", 334 m_current_process->GetID()); 335 } 336 337 printf("Launched '%s' as process %" PRIu64 "...\n", 338 m_process_launch_info.GetArguments().GetArgumentAtIndex(0), 339 m_current_process->GetID()); 340 341 return Status(); 342 } 343 344 Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) { 345 Log *log = GetLog(LLDBLog::Process); 346 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64, 347 __FUNCTION__, pid); 348 349 // Before we try to attach, make sure we aren't already monitoring something 350 // else. 351 if (!m_debugged_processes.empty()) 352 return Status("cannot attach to process %" PRIu64 353 " when another process with pid %" PRIu64 354 " is being debugged.", 355 pid, m_current_process->GetID()); 356 357 // Try to attach. 358 auto process_or = m_process_factory.Attach(pid, *this, m_mainloop); 359 if (!process_or) { 360 Status status(process_or.takeError()); 361 llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}\n", pid, 362 status); 363 return status; 364 } 365 m_continue_process = m_current_process = process_or->get(); 366 m_debugged_processes.emplace( 367 m_current_process->GetID(), 368 DebuggedProcess{std::move(*process_or), DebuggedProcess::Flag{}}); 369 SetEnabledExtensions(*m_current_process); 370 371 // Setup stdout/stderr mapping from inferior. 372 auto terminal_fd = m_current_process->GetTerminalFileDescriptor(); 373 if (terminal_fd >= 0) { 374 LLDB_LOGF(log, 375 "ProcessGDBRemoteCommunicationServerLLGS::%s setting " 376 "inferior STDIO fd to %d", 377 __FUNCTION__, terminal_fd); 378 Status status = SetSTDIOFileDescriptor(terminal_fd); 379 if (status.Fail()) 380 return status; 381 } else { 382 LLDB_LOGF(log, 383 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring " 384 "inferior STDIO since terminal fd reported as %d", 385 __FUNCTION__, terminal_fd); 386 } 387 388 printf("Attached to process %" PRIu64 "...\n", pid); 389 return Status(); 390 } 391 392 Status GDBRemoteCommunicationServerLLGS::AttachWaitProcess( 393 llvm::StringRef process_name, bool include_existing) { 394 Log *log = GetLog(LLDBLog::Process); 395 396 std::chrono::milliseconds polling_interval = std::chrono::milliseconds(1); 397 398 // Create the matcher used to search the process list. 399 ProcessInstanceInfoList exclusion_list; 400 ProcessInstanceInfoMatch match_info; 401 match_info.GetProcessInfo().GetExecutableFile().SetFile( 402 process_name, llvm::sys::path::Style::native); 403 match_info.SetNameMatchType(NameMatch::Equals); 404 405 if (include_existing) { 406 LLDB_LOG(log, "including existing processes in search"); 407 } else { 408 // Create the excluded process list before polling begins. 409 Host::FindProcesses(match_info, exclusion_list); 410 LLDB_LOG(log, "placed '{0}' processes in the exclusion list.", 411 exclusion_list.size()); 412 } 413 414 LLDB_LOG(log, "waiting for '{0}' to appear", process_name); 415 416 auto is_in_exclusion_list = 417 [&exclusion_list](const ProcessInstanceInfo &info) { 418 for (auto &excluded : exclusion_list) { 419 if (excluded.GetProcessID() == info.GetProcessID()) 420 return true; 421 } 422 return false; 423 }; 424 425 ProcessInstanceInfoList loop_process_list; 426 while (true) { 427 loop_process_list.clear(); 428 if (Host::FindProcesses(match_info, loop_process_list)) { 429 // Remove all the elements that are in the exclusion list. 430 llvm::erase_if(loop_process_list, is_in_exclusion_list); 431 432 // One match! We found the desired process. 433 if (loop_process_list.size() == 1) { 434 auto matching_process_pid = loop_process_list[0].GetProcessID(); 435 LLDB_LOG(log, "found pid {0}", matching_process_pid); 436 return AttachToProcess(matching_process_pid); 437 } 438 439 // Multiple matches! Return an error reporting the PIDs we found. 440 if (loop_process_list.size() > 1) { 441 StreamString error_stream; 442 error_stream.Format( 443 "Multiple executables with name: '{0}' found. Pids: ", 444 process_name); 445 for (size_t i = 0; i < loop_process_list.size() - 1; ++i) { 446 error_stream.Format("{0}, ", loop_process_list[i].GetProcessID()); 447 } 448 error_stream.Format("{0}.", loop_process_list.back().GetProcessID()); 449 450 Status error; 451 error.SetErrorString(error_stream.GetString()); 452 return error; 453 } 454 } 455 // No matches, we have not found the process. Sleep until next poll. 456 LLDB_LOG(log, "sleep {0} seconds", polling_interval); 457 std::this_thread::sleep_for(polling_interval); 458 } 459 } 460 461 void GDBRemoteCommunicationServerLLGS::InitializeDelegate( 462 NativeProcessProtocol *process) { 463 assert(process && "process cannot be NULL"); 464 Log *log = GetLog(LLDBLog::Process); 465 if (log) { 466 LLDB_LOGF(log, 467 "GDBRemoteCommunicationServerLLGS::%s called with " 468 "NativeProcessProtocol pid %" PRIu64 ", current state: %s", 469 __FUNCTION__, process->GetID(), 470 StateAsCString(process->GetState())); 471 } 472 } 473 474 GDBRemoteCommunication::PacketResult 475 GDBRemoteCommunicationServerLLGS::SendWResponse( 476 NativeProcessProtocol *process) { 477 assert(process && "process cannot be NULL"); 478 Log *log = GetLog(LLDBLog::Process); 479 480 // send W notification 481 auto wait_status = process->GetExitStatus(); 482 if (!wait_status) { 483 LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status", 484 process->GetID()); 485 486 StreamGDBRemote response; 487 response.PutChar('E'); 488 response.PutHex8(GDBRemoteServerError::eErrorExitStatus); 489 return SendPacketNoLock(response.GetString()); 490 } 491 492 LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(), 493 *wait_status); 494 495 // If the process was killed through vKill, return "OK". 496 if (bool(m_debugged_processes.at(process->GetID()).flags & 497 DebuggedProcess::Flag::vkilled)) 498 return SendOKResponse(); 499 500 StreamGDBRemote response; 501 response.Format("{0:g}", *wait_status); 502 if (bool(m_extensions_supported & 503 NativeProcessProtocol::Extension::multiprocess)) 504 response.Format(";process:{0:x-}", process->GetID()); 505 if (m_non_stop) 506 return SendNotificationPacketNoLock("Stop", m_stop_notification_queue, 507 response.GetString()); 508 return SendPacketNoLock(response.GetString()); 509 } 510 511 static void AppendHexValue(StreamString &response, const uint8_t *buf, 512 uint32_t buf_size, bool swap) { 513 int64_t i; 514 if (swap) { 515 for (i = buf_size - 1; i >= 0; i--) 516 response.PutHex8(buf[i]); 517 } else { 518 for (i = 0; i < buf_size; i++) 519 response.PutHex8(buf[i]); 520 } 521 } 522 523 static llvm::StringRef GetEncodingNameOrEmpty(const RegisterInfo ®_info) { 524 switch (reg_info.encoding) { 525 case eEncodingUint: 526 return "uint"; 527 case eEncodingSint: 528 return "sint"; 529 case eEncodingIEEE754: 530 return "ieee754"; 531 case eEncodingVector: 532 return "vector"; 533 default: 534 return ""; 535 } 536 } 537 538 static llvm::StringRef GetFormatNameOrEmpty(const RegisterInfo ®_info) { 539 switch (reg_info.format) { 540 case eFormatBinary: 541 return "binary"; 542 case eFormatDecimal: 543 return "decimal"; 544 case eFormatHex: 545 return "hex"; 546 case eFormatFloat: 547 return "float"; 548 case eFormatVectorOfSInt8: 549 return "vector-sint8"; 550 case eFormatVectorOfUInt8: 551 return "vector-uint8"; 552 case eFormatVectorOfSInt16: 553 return "vector-sint16"; 554 case eFormatVectorOfUInt16: 555 return "vector-uint16"; 556 case eFormatVectorOfSInt32: 557 return "vector-sint32"; 558 case eFormatVectorOfUInt32: 559 return "vector-uint32"; 560 case eFormatVectorOfFloat32: 561 return "vector-float32"; 562 case eFormatVectorOfUInt64: 563 return "vector-uint64"; 564 case eFormatVectorOfUInt128: 565 return "vector-uint128"; 566 default: 567 return ""; 568 }; 569 } 570 571 static llvm::StringRef GetKindGenericOrEmpty(const RegisterInfo ®_info) { 572 switch (reg_info.kinds[RegisterKind::eRegisterKindGeneric]) { 573 case LLDB_REGNUM_GENERIC_PC: 574 return "pc"; 575 case LLDB_REGNUM_GENERIC_SP: 576 return "sp"; 577 case LLDB_REGNUM_GENERIC_FP: 578 return "fp"; 579 case LLDB_REGNUM_GENERIC_RA: 580 return "ra"; 581 case LLDB_REGNUM_GENERIC_FLAGS: 582 return "flags"; 583 case LLDB_REGNUM_GENERIC_ARG1: 584 return "arg1"; 585 case LLDB_REGNUM_GENERIC_ARG2: 586 return "arg2"; 587 case LLDB_REGNUM_GENERIC_ARG3: 588 return "arg3"; 589 case LLDB_REGNUM_GENERIC_ARG4: 590 return "arg4"; 591 case LLDB_REGNUM_GENERIC_ARG5: 592 return "arg5"; 593 case LLDB_REGNUM_GENERIC_ARG6: 594 return "arg6"; 595 case LLDB_REGNUM_GENERIC_ARG7: 596 return "arg7"; 597 case LLDB_REGNUM_GENERIC_ARG8: 598 return "arg8"; 599 default: 600 return ""; 601 } 602 } 603 604 static void CollectRegNums(const uint32_t *reg_num, StreamString &response, 605 bool usehex) { 606 for (int i = 0; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) { 607 if (i > 0) 608 response.PutChar(','); 609 if (usehex) 610 response.Printf("%" PRIx32, *reg_num); 611 else 612 response.Printf("%" PRIu32, *reg_num); 613 } 614 } 615 616 static void WriteRegisterValueInHexFixedWidth( 617 StreamString &response, NativeRegisterContext ®_ctx, 618 const RegisterInfo ®_info, const RegisterValue *reg_value_p, 619 lldb::ByteOrder byte_order) { 620 RegisterValue reg_value; 621 if (!reg_value_p) { 622 Status error = reg_ctx.ReadRegister(®_info, reg_value); 623 if (error.Success()) 624 reg_value_p = ®_value; 625 // else log. 626 } 627 628 if (reg_value_p) { 629 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(), 630 reg_value_p->GetByteSize(), 631 byte_order == lldb::eByteOrderLittle); 632 } else { 633 // Zero-out any unreadable values. 634 if (reg_info.byte_size > 0) { 635 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0'); 636 AppendHexValue(response, zeros.data(), zeros.size(), false); 637 } 638 } 639 } 640 641 static llvm::Optional<json::Object> 642 GetRegistersAsJSON(NativeThreadProtocol &thread) { 643 Log *log = GetLog(LLDBLog::Thread); 644 645 NativeRegisterContext& reg_ctx = thread.GetRegisterContext(); 646 647 json::Object register_object; 648 649 #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET 650 const auto expedited_regs = 651 reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Full); 652 #else 653 const auto expedited_regs = 654 reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Minimal); 655 #endif 656 if (expedited_regs.empty()) 657 return llvm::None; 658 659 for (auto ®_num : expedited_regs) { 660 const RegisterInfo *const reg_info_p = 661 reg_ctx.GetRegisterInfoAtIndex(reg_num); 662 if (reg_info_p == nullptr) { 663 LLDB_LOGF(log, 664 "%s failed to get register info for register index %" PRIu32, 665 __FUNCTION__, reg_num); 666 continue; 667 } 668 669 if (reg_info_p->value_regs != nullptr) 670 continue; // Only expedite registers that are not contained in other 671 // registers. 672 673 RegisterValue reg_value; 674 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value); 675 if (error.Fail()) { 676 LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s", 677 __FUNCTION__, 678 reg_info_p->name ? reg_info_p->name : "<unnamed-register>", 679 reg_num, error.AsCString()); 680 continue; 681 } 682 683 StreamString stream; 684 WriteRegisterValueInHexFixedWidth(stream, reg_ctx, *reg_info_p, 685 ®_value, lldb::eByteOrderBig); 686 687 register_object.try_emplace(llvm::to_string(reg_num), 688 stream.GetString().str()); 689 } 690 691 return register_object; 692 } 693 694 static const char *GetStopReasonString(StopReason stop_reason) { 695 switch (stop_reason) { 696 case eStopReasonTrace: 697 return "trace"; 698 case eStopReasonBreakpoint: 699 return "breakpoint"; 700 case eStopReasonWatchpoint: 701 return "watchpoint"; 702 case eStopReasonSignal: 703 return "signal"; 704 case eStopReasonException: 705 return "exception"; 706 case eStopReasonExec: 707 return "exec"; 708 case eStopReasonProcessorTrace: 709 return "processor trace"; 710 case eStopReasonFork: 711 return "fork"; 712 case eStopReasonVFork: 713 return "vfork"; 714 case eStopReasonVForkDone: 715 return "vforkdone"; 716 case eStopReasonInstrumentation: 717 case eStopReasonInvalid: 718 case eStopReasonPlanComplete: 719 case eStopReasonThreadExiting: 720 case eStopReasonNone: 721 break; // ignored 722 } 723 return nullptr; 724 } 725 726 static llvm::Expected<json::Array> 727 GetJSONThreadsInfo(NativeProcessProtocol &process, bool abridged) { 728 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread); 729 730 json::Array threads_array; 731 732 // Ensure we can get info on the given thread. 733 for (NativeThreadProtocol &thread : process.Threads()) { 734 lldb::tid_t tid = thread.GetID(); 735 // Grab the reason this thread stopped. 736 struct ThreadStopInfo tid_stop_info; 737 std::string description; 738 if (!thread.GetStopReason(tid_stop_info, description)) 739 return llvm::make_error<llvm::StringError>( 740 "failed to get stop reason", llvm::inconvertibleErrorCode()); 741 742 const int signum = tid_stop_info.signo; 743 if (log) { 744 LLDB_LOGF(log, 745 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 746 " tid %" PRIu64 747 " got signal signo = %d, reason = %d, exc_type = %" PRIu64, 748 __FUNCTION__, process.GetID(), tid, signum, 749 tid_stop_info.reason, tid_stop_info.details.exception.type); 750 } 751 752 json::Object thread_obj; 753 754 if (!abridged) { 755 if (llvm::Optional<json::Object> registers = GetRegistersAsJSON(thread)) 756 thread_obj.try_emplace("registers", std::move(*registers)); 757 } 758 759 thread_obj.try_emplace("tid", static_cast<int64_t>(tid)); 760 761 if (signum != 0) 762 thread_obj.try_emplace("signal", signum); 763 764 const std::string thread_name = thread.GetName(); 765 if (!thread_name.empty()) 766 thread_obj.try_emplace("name", thread_name); 767 768 const char *stop_reason = GetStopReasonString(tid_stop_info.reason); 769 if (stop_reason) 770 thread_obj.try_emplace("reason", stop_reason); 771 772 if (!description.empty()) 773 thread_obj.try_emplace("description", description); 774 775 if ((tid_stop_info.reason == eStopReasonException) && 776 tid_stop_info.details.exception.type) { 777 thread_obj.try_emplace( 778 "metype", static_cast<int64_t>(tid_stop_info.details.exception.type)); 779 780 json::Array medata_array; 781 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; 782 ++i) { 783 medata_array.push_back( 784 static_cast<int64_t>(tid_stop_info.details.exception.data[i])); 785 } 786 thread_obj.try_emplace("medata", std::move(medata_array)); 787 } 788 threads_array.push_back(std::move(thread_obj)); 789 } 790 return threads_array; 791 } 792 793 StreamString 794 GDBRemoteCommunicationServerLLGS::PrepareStopReplyPacketForThread( 795 NativeThreadProtocol &thread) { 796 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread); 797 798 NativeProcessProtocol &process = thread.GetProcess(); 799 800 LLDB_LOG(log, "preparing packet for pid {0} tid {1}", process.GetID(), 801 thread.GetID()); 802 803 // Grab the reason this thread stopped. 804 StreamString response; 805 struct ThreadStopInfo tid_stop_info; 806 std::string description; 807 if (!thread.GetStopReason(tid_stop_info, description)) 808 return response; 809 810 // FIXME implement register handling for exec'd inferiors. 811 // if (tid_stop_info.reason == eStopReasonExec) { 812 // const bool force = true; 813 // InitializeRegisters(force); 814 // } 815 816 // Output the T packet with the thread 817 response.PutChar('T'); 818 int signum = tid_stop_info.signo; 819 LLDB_LOG( 820 log, 821 "pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}", 822 process.GetID(), thread.GetID(), signum, int(tid_stop_info.reason), 823 tid_stop_info.details.exception.type); 824 825 // Print the signal number. 826 response.PutHex8(signum & 0xff); 827 828 // Include the (pid and) tid. 829 response.PutCString("thread:"); 830 AppendThreadIDToResponse(response, process.GetID(), thread.GetID()); 831 response.PutChar(';'); 832 833 // Include the thread name if there is one. 834 const std::string thread_name = thread.GetName(); 835 if (!thread_name.empty()) { 836 size_t thread_name_len = thread_name.length(); 837 838 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) { 839 response.PutCString("name:"); 840 response.PutCString(thread_name); 841 } else { 842 // The thread name contains special chars, send as hex bytes. 843 response.PutCString("hexname:"); 844 response.PutStringAsRawHex8(thread_name); 845 } 846 response.PutChar(';'); 847 } 848 849 // If a 'QListThreadsInStopReply' was sent to enable this feature, we will 850 // send all thread IDs back in the "threads" key whose value is a list of hex 851 // thread IDs separated by commas: 852 // "threads:10a,10b,10c;" 853 // This will save the debugger from having to send a pair of qfThreadInfo and 854 // qsThreadInfo packets, but it also might take a lot of room in the stop 855 // reply packet, so it must be enabled only on systems where there are no 856 // limits on packet lengths. 857 if (m_list_threads_in_stop_reply) { 858 response.PutCString("threads:"); 859 860 uint32_t thread_num = 0; 861 for (NativeThreadProtocol &listed_thread : process.Threads()) { 862 if (thread_num > 0) 863 response.PutChar(','); 864 response.Printf("%" PRIx64, listed_thread.GetID()); 865 ++thread_num; 866 } 867 response.PutChar(';'); 868 869 // Include JSON info that describes the stop reason for any threads that 870 // actually have stop reasons. We use the new "jstopinfo" key whose values 871 // is hex ascii JSON that contains the thread IDs thread stop info only for 872 // threads that have stop reasons. Only send this if we have more than one 873 // thread otherwise this packet has all the info it needs. 874 if (thread_num > 1) { 875 const bool threads_with_valid_stop_info_only = true; 876 llvm::Expected<json::Array> threads_info = GetJSONThreadsInfo( 877 *m_current_process, threads_with_valid_stop_info_only); 878 if (threads_info) { 879 response.PutCString("jstopinfo:"); 880 StreamString unescaped_response; 881 unescaped_response.AsRawOstream() << std::move(*threads_info); 882 response.PutStringAsRawHex8(unescaped_response.GetData()); 883 response.PutChar(';'); 884 } else { 885 LLDB_LOG_ERROR(log, threads_info.takeError(), 886 "failed to prepare a jstopinfo field for pid {1}: {0}", 887 process.GetID()); 888 } 889 } 890 891 response.PutCString("thread-pcs"); 892 char delimiter = ':'; 893 for (NativeThreadProtocol &thread : process.Threads()) { 894 NativeRegisterContext ®_ctx = thread.GetRegisterContext(); 895 896 uint32_t reg_to_read = reg_ctx.ConvertRegisterKindToRegisterNumber( 897 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); 898 const RegisterInfo *const reg_info_p = 899 reg_ctx.GetRegisterInfoAtIndex(reg_to_read); 900 901 RegisterValue reg_value; 902 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value); 903 if (error.Fail()) { 904 LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s", 905 __FUNCTION__, 906 reg_info_p->name ? reg_info_p->name : "<unnamed-register>", 907 reg_to_read, error.AsCString()); 908 continue; 909 } 910 911 response.PutChar(delimiter); 912 delimiter = ','; 913 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p, 914 ®_value, endian::InlHostByteOrder()); 915 } 916 917 response.PutChar(';'); 918 } 919 920 // 921 // Expedite registers. 922 // 923 924 // Grab the register context. 925 NativeRegisterContext ®_ctx = thread.GetRegisterContext(); 926 const auto expedited_regs = 927 reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Full); 928 929 for (auto ®_num : expedited_regs) { 930 const RegisterInfo *const reg_info_p = 931 reg_ctx.GetRegisterInfoAtIndex(reg_num); 932 // Only expediate registers that are not contained in other registers. 933 if (reg_info_p != nullptr && reg_info_p->value_regs == nullptr) { 934 RegisterValue reg_value; 935 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value); 936 if (error.Success()) { 937 response.Printf("%.02x:", reg_num); 938 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p, 939 ®_value, lldb::eByteOrderBig); 940 response.PutChar(';'); 941 } else { 942 LLDB_LOGF(log, 943 "GDBRemoteCommunicationServerLLGS::%s failed to read " 944 "register '%s' index %" PRIu32 ": %s", 945 __FUNCTION__, 946 reg_info_p->name ? reg_info_p->name : "<unnamed-register>", 947 reg_num, error.AsCString()); 948 } 949 } 950 } 951 952 const char *reason_str = GetStopReasonString(tid_stop_info.reason); 953 if (reason_str != nullptr) { 954 response.Printf("reason:%s;", reason_str); 955 } 956 957 if (!description.empty()) { 958 // Description may contains special chars, send as hex bytes. 959 response.PutCString("description:"); 960 response.PutStringAsRawHex8(description); 961 response.PutChar(';'); 962 } else if ((tid_stop_info.reason == eStopReasonException) && 963 tid_stop_info.details.exception.type) { 964 response.PutCString("metype:"); 965 response.PutHex64(tid_stop_info.details.exception.type); 966 response.PutCString(";mecount:"); 967 response.PutHex32(tid_stop_info.details.exception.data_count); 968 response.PutChar(';'); 969 970 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) { 971 response.PutCString("medata:"); 972 response.PutHex64(tid_stop_info.details.exception.data[i]); 973 response.PutChar(';'); 974 } 975 } 976 977 // Include child process PID/TID for forks. 978 if (tid_stop_info.reason == eStopReasonFork || 979 tid_stop_info.reason == eStopReasonVFork) { 980 assert(bool(m_extensions_supported & 981 NativeProcessProtocol::Extension::multiprocess)); 982 if (tid_stop_info.reason == eStopReasonFork) 983 assert(bool(m_extensions_supported & 984 NativeProcessProtocol::Extension::fork)); 985 if (tid_stop_info.reason == eStopReasonVFork) 986 assert(bool(m_extensions_supported & 987 NativeProcessProtocol::Extension::vfork)); 988 response.Printf("%s:p%" PRIx64 ".%" PRIx64 ";", reason_str, 989 tid_stop_info.details.fork.child_pid, 990 tid_stop_info.details.fork.child_tid); 991 } 992 993 return response; 994 } 995 996 GDBRemoteCommunication::PacketResult 997 GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread( 998 NativeProcessProtocol &process, lldb::tid_t tid, bool force_synchronous) { 999 // Ensure we can get info on the given thread. 1000 NativeThreadProtocol *thread = process.GetThreadByID(tid); 1001 if (!thread) 1002 return SendErrorResponse(51); 1003 1004 StreamString response = PrepareStopReplyPacketForThread(*thread); 1005 if (response.Empty()) 1006 return SendErrorResponse(42); 1007 1008 if (m_non_stop && !force_synchronous) { 1009 PacketResult ret = SendNotificationPacketNoLock( 1010 "Stop", m_stop_notification_queue, response.GetString()); 1011 // Queue notification events for the remaining threads. 1012 EnqueueStopReplyPackets(tid); 1013 return ret; 1014 } 1015 1016 return SendPacketNoLock(response.GetString()); 1017 } 1018 1019 void GDBRemoteCommunicationServerLLGS::EnqueueStopReplyPackets( 1020 lldb::tid_t thread_to_skip) { 1021 if (!m_non_stop) 1022 return; 1023 1024 for (NativeThreadProtocol &listed_thread : m_current_process->Threads()) { 1025 if (listed_thread.GetID() != thread_to_skip) 1026 m_stop_notification_queue.push_back( 1027 PrepareStopReplyPacketForThread(listed_thread).GetString().str()); 1028 } 1029 } 1030 1031 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited( 1032 NativeProcessProtocol *process) { 1033 assert(process && "process cannot be NULL"); 1034 1035 Log *log = GetLog(LLDBLog::Process); 1036 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__); 1037 1038 PacketResult result = SendStopReasonForState( 1039 *process, StateType::eStateExited, /*force_synchronous=*/false); 1040 if (result != PacketResult::Success) { 1041 LLDB_LOGF(log, 1042 "GDBRemoteCommunicationServerLLGS::%s failed to send stop " 1043 "notification for PID %" PRIu64 ", state: eStateExited", 1044 __FUNCTION__, process->GetID()); 1045 } 1046 1047 if (m_current_process == process) 1048 m_current_process = nullptr; 1049 if (m_continue_process == process) 1050 m_continue_process = nullptr; 1051 1052 lldb::pid_t pid = process->GetID(); 1053 m_mainloop.AddPendingCallback([this, pid](MainLoopBase &loop) { 1054 auto find_it = m_debugged_processes.find(pid); 1055 assert(find_it != m_debugged_processes.end()); 1056 bool vkilled = bool(find_it->second.flags & DebuggedProcess::Flag::vkilled); 1057 m_debugged_processes.erase(find_it); 1058 // Terminate the main loop only if vKill has not been used. 1059 // When running in non-stop mode, wait for the vStopped to clear 1060 // the notification queue. 1061 if (m_debugged_processes.empty() && !m_non_stop && !vkilled) { 1062 // Close the pipe to the inferior terminal i/o if we launched it and set 1063 // one up. 1064 MaybeCloseInferiorTerminalConnection(); 1065 1066 // We are ready to exit the debug monitor. 1067 m_exit_now = true; 1068 loop.RequestTermination(); 1069 } 1070 }); 1071 } 1072 1073 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped( 1074 NativeProcessProtocol *process) { 1075 assert(process && "process cannot be NULL"); 1076 1077 Log *log = GetLog(LLDBLog::Process); 1078 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__); 1079 1080 PacketResult result = SendStopReasonForState( 1081 *process, StateType::eStateStopped, /*force_synchronous=*/false); 1082 if (result != PacketResult::Success) { 1083 LLDB_LOGF(log, 1084 "GDBRemoteCommunicationServerLLGS::%s failed to send stop " 1085 "notification for PID %" PRIu64 ", state: eStateExited", 1086 __FUNCTION__, process->GetID()); 1087 } 1088 } 1089 1090 void GDBRemoteCommunicationServerLLGS::ProcessStateChanged( 1091 NativeProcessProtocol *process, lldb::StateType state) { 1092 assert(process && "process cannot be NULL"); 1093 Log *log = GetLog(LLDBLog::Process); 1094 if (log) { 1095 LLDB_LOGF(log, 1096 "GDBRemoteCommunicationServerLLGS::%s called with " 1097 "NativeProcessProtocol pid %" PRIu64 ", state: %s", 1098 __FUNCTION__, process->GetID(), StateAsCString(state)); 1099 } 1100 1101 switch (state) { 1102 case StateType::eStateRunning: 1103 break; 1104 1105 case StateType::eStateStopped: 1106 // Make sure we get all of the pending stdout/stderr from the inferior and 1107 // send it to the lldb host before we send the state change notification 1108 SendProcessOutput(); 1109 // Then stop the forwarding, so that any late output (see llvm.org/pr25652) 1110 // does not interfere with our protocol. 1111 StopSTDIOForwarding(); 1112 HandleInferiorState_Stopped(process); 1113 break; 1114 1115 case StateType::eStateExited: 1116 // Same as above 1117 SendProcessOutput(); 1118 StopSTDIOForwarding(); 1119 HandleInferiorState_Exited(process); 1120 break; 1121 1122 default: 1123 if (log) { 1124 LLDB_LOGF(log, 1125 "GDBRemoteCommunicationServerLLGS::%s didn't handle state " 1126 "change for pid %" PRIu64 ", new state: %s", 1127 __FUNCTION__, process->GetID(), StateAsCString(state)); 1128 } 1129 break; 1130 } 1131 } 1132 1133 void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) { 1134 ClearProcessSpecificData(); 1135 } 1136 1137 void GDBRemoteCommunicationServerLLGS::NewSubprocess( 1138 NativeProcessProtocol *parent_process, 1139 std::unique_ptr<NativeProcessProtocol> child_process) { 1140 lldb::pid_t child_pid = child_process->GetID(); 1141 assert(child_pid != LLDB_INVALID_PROCESS_ID); 1142 assert(m_debugged_processes.find(child_pid) == m_debugged_processes.end()); 1143 m_debugged_processes.emplace( 1144 child_pid, 1145 DebuggedProcess{std::move(child_process), DebuggedProcess::Flag{}}); 1146 } 1147 1148 void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() { 1149 Log *log = GetLog(GDBRLog::Comm); 1150 1151 bool interrupt = false; 1152 bool done = false; 1153 Status error; 1154 while (true) { 1155 const PacketResult result = GetPacketAndSendResponse( 1156 std::chrono::microseconds(0), error, interrupt, done); 1157 if (result == PacketResult::ErrorReplyTimeout) 1158 break; // No more packets in the queue 1159 1160 if ((result != PacketResult::Success)) { 1161 LLDB_LOGF(log, 1162 "GDBRemoteCommunicationServerLLGS::%s processing a packet " 1163 "failed: %s", 1164 __FUNCTION__, error.AsCString()); 1165 m_mainloop.RequestTermination(); 1166 break; 1167 } 1168 } 1169 } 1170 1171 Status GDBRemoteCommunicationServerLLGS::InitializeConnection( 1172 std::unique_ptr<Connection> connection) { 1173 IOObjectSP read_object_sp = connection->GetReadObject(); 1174 GDBRemoteCommunicationServer::SetConnection(std::move(connection)); 1175 1176 Status error; 1177 m_network_handle_up = m_mainloop.RegisterReadObject( 1178 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); }, 1179 error); 1180 return error; 1181 } 1182 1183 GDBRemoteCommunication::PacketResult 1184 GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer, 1185 uint32_t len) { 1186 if ((buffer == nullptr) || (len == 0)) { 1187 // Nothing to send. 1188 return PacketResult::Success; 1189 } 1190 1191 StreamString response; 1192 response.PutChar('O'); 1193 response.PutBytesAsRawHex8(buffer, len); 1194 1195 return SendPacketNoLock(response.GetString()); 1196 } 1197 1198 Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) { 1199 Status error; 1200 1201 // Set up the reading/handling of process I/O 1202 std::unique_ptr<ConnectionFileDescriptor> conn_up( 1203 new ConnectionFileDescriptor(fd, true)); 1204 if (!conn_up) { 1205 error.SetErrorString("failed to create ConnectionFileDescriptor"); 1206 return error; 1207 } 1208 1209 m_stdio_communication.SetCloseOnEOF(false); 1210 m_stdio_communication.SetConnection(std::move(conn_up)); 1211 if (!m_stdio_communication.IsConnected()) { 1212 error.SetErrorString( 1213 "failed to set connection for inferior I/O communication"); 1214 return error; 1215 } 1216 1217 return Status(); 1218 } 1219 1220 void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() { 1221 // Don't forward if not connected (e.g. when attaching). 1222 if (!m_stdio_communication.IsConnected()) 1223 return; 1224 1225 Status error; 1226 assert(!m_stdio_handle_up); 1227 m_stdio_handle_up = m_mainloop.RegisterReadObject( 1228 m_stdio_communication.GetConnection()->GetReadObject(), 1229 [this](MainLoopBase &) { SendProcessOutput(); }, error); 1230 1231 if (!m_stdio_handle_up) { 1232 // Not much we can do about the failure. Log it and continue without 1233 // forwarding. 1234 if (Log *log = GetLog(LLDBLog::Process)) 1235 LLDB_LOG(log, "Failed to set up stdio forwarding: {0}", error); 1236 } 1237 } 1238 1239 void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() { 1240 m_stdio_handle_up.reset(); 1241 } 1242 1243 void GDBRemoteCommunicationServerLLGS::SendProcessOutput() { 1244 char buffer[1024]; 1245 ConnectionStatus status; 1246 Status error; 1247 while (true) { 1248 size_t bytes_read = m_stdio_communication.Read( 1249 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error); 1250 switch (status) { 1251 case eConnectionStatusSuccess: 1252 SendONotification(buffer, bytes_read); 1253 break; 1254 case eConnectionStatusLostConnection: 1255 case eConnectionStatusEndOfFile: 1256 case eConnectionStatusError: 1257 case eConnectionStatusNoConnection: 1258 if (Log *log = GetLog(LLDBLog::Process)) 1259 LLDB_LOGF(log, 1260 "GDBRemoteCommunicationServerLLGS::%s Stopping stdio " 1261 "forwarding as communication returned status %d (error: " 1262 "%s)", 1263 __FUNCTION__, status, error.AsCString()); 1264 m_stdio_handle_up.reset(); 1265 return; 1266 1267 case eConnectionStatusInterrupted: 1268 case eConnectionStatusTimedOut: 1269 return; 1270 } 1271 } 1272 } 1273 1274 GDBRemoteCommunication::PacketResult 1275 GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceSupported( 1276 StringExtractorGDBRemote &packet) { 1277 1278 // Fail if we don't have a current process. 1279 if (!m_current_process || 1280 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 1281 return SendErrorResponse(Status("Process not running.")); 1282 1283 return SendJSONResponse(m_current_process->TraceSupported()); 1284 } 1285 1286 GDBRemoteCommunication::PacketResult 1287 GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStop( 1288 StringExtractorGDBRemote &packet) { 1289 // Fail if we don't have a current process. 1290 if (!m_current_process || 1291 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 1292 return SendErrorResponse(Status("Process not running.")); 1293 1294 packet.ConsumeFront("jLLDBTraceStop:"); 1295 Expected<TraceStopRequest> stop_request = 1296 json::parse<TraceStopRequest>(packet.Peek(), "TraceStopRequest"); 1297 if (!stop_request) 1298 return SendErrorResponse(stop_request.takeError()); 1299 1300 if (Error err = m_current_process->TraceStop(*stop_request)) 1301 return SendErrorResponse(std::move(err)); 1302 1303 return SendOKResponse(); 1304 } 1305 1306 GDBRemoteCommunication::PacketResult 1307 GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStart( 1308 StringExtractorGDBRemote &packet) { 1309 1310 // Fail if we don't have a current process. 1311 if (!m_current_process || 1312 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 1313 return SendErrorResponse(Status("Process not running.")); 1314 1315 packet.ConsumeFront("jLLDBTraceStart:"); 1316 Expected<TraceStartRequest> request = 1317 json::parse<TraceStartRequest>(packet.Peek(), "TraceStartRequest"); 1318 if (!request) 1319 return SendErrorResponse(request.takeError()); 1320 1321 if (Error err = m_current_process->TraceStart(packet.Peek(), request->type)) 1322 return SendErrorResponse(std::move(err)); 1323 1324 return SendOKResponse(); 1325 } 1326 1327 GDBRemoteCommunication::PacketResult 1328 GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetState( 1329 StringExtractorGDBRemote &packet) { 1330 1331 // Fail if we don't have a current process. 1332 if (!m_current_process || 1333 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 1334 return SendErrorResponse(Status("Process not running.")); 1335 1336 packet.ConsumeFront("jLLDBTraceGetState:"); 1337 Expected<TraceGetStateRequest> request = 1338 json::parse<TraceGetStateRequest>(packet.Peek(), "TraceGetStateRequest"); 1339 if (!request) 1340 return SendErrorResponse(request.takeError()); 1341 1342 return SendJSONResponse(m_current_process->TraceGetState(request->type)); 1343 } 1344 1345 GDBRemoteCommunication::PacketResult 1346 GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetBinaryData( 1347 StringExtractorGDBRemote &packet) { 1348 1349 // Fail if we don't have a current process. 1350 if (!m_current_process || 1351 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 1352 return SendErrorResponse(Status("Process not running.")); 1353 1354 packet.ConsumeFront("jLLDBTraceGetBinaryData:"); 1355 llvm::Expected<TraceGetBinaryDataRequest> request = 1356 llvm::json::parse<TraceGetBinaryDataRequest>(packet.Peek(), 1357 "TraceGetBinaryDataRequest"); 1358 if (!request) 1359 return SendErrorResponse(Status(request.takeError())); 1360 1361 if (Expected<std::vector<uint8_t>> bytes = 1362 m_current_process->TraceGetBinaryData(*request)) { 1363 StreamGDBRemote response; 1364 response.PutEscapedBytes(bytes->data(), bytes->size()); 1365 return SendPacketNoLock(response.GetString()); 1366 } else 1367 return SendErrorResponse(bytes.takeError()); 1368 } 1369 1370 GDBRemoteCommunication::PacketResult 1371 GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo( 1372 StringExtractorGDBRemote &packet) { 1373 // Fail if we don't have a current process. 1374 if (!m_current_process || 1375 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 1376 return SendErrorResponse(68); 1377 1378 lldb::pid_t pid = m_current_process->GetID(); 1379 1380 if (pid == LLDB_INVALID_PROCESS_ID) 1381 return SendErrorResponse(1); 1382 1383 ProcessInstanceInfo proc_info; 1384 if (!Host::GetProcessInfo(pid, proc_info)) 1385 return SendErrorResponse(1); 1386 1387 StreamString response; 1388 CreateProcessInfoResponse_DebugServerStyle(proc_info, response); 1389 return SendPacketNoLock(response.GetString()); 1390 } 1391 1392 GDBRemoteCommunication::PacketResult 1393 GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) { 1394 // Fail if we don't have a current process. 1395 if (!m_current_process || 1396 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 1397 return SendErrorResponse(68); 1398 1399 // Make sure we set the current thread so g and p packets return the data the 1400 // gdb will expect. 1401 lldb::tid_t tid = m_current_process->GetCurrentThreadID(); 1402 SetCurrentThreadID(tid); 1403 1404 NativeThreadProtocol *thread = m_current_process->GetCurrentThread(); 1405 if (!thread) 1406 return SendErrorResponse(69); 1407 1408 StreamString response; 1409 response.PutCString("QC"); 1410 AppendThreadIDToResponse(response, m_current_process->GetID(), 1411 thread->GetID()); 1412 1413 return SendPacketNoLock(response.GetString()); 1414 } 1415 1416 GDBRemoteCommunication::PacketResult 1417 GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) { 1418 Log *log = GetLog(LLDBLog::Process); 1419 1420 StopSTDIOForwarding(); 1421 1422 if (m_debugged_processes.empty()) { 1423 LLDB_LOG(log, "No debugged process found."); 1424 return PacketResult::Success; 1425 } 1426 1427 for (auto it = m_debugged_processes.begin(); it != m_debugged_processes.end(); 1428 ++it) { 1429 LLDB_LOG(log, "Killing process {0}", it->first); 1430 Status error = it->second.process_up->Kill(); 1431 if (error.Fail()) 1432 LLDB_LOG(log, "Failed to kill debugged process {0}: {1}", it->first, 1433 error); 1434 } 1435 1436 // The response to kill packet is undefined per the spec. LLDB 1437 // follows the same rules as for continue packets, i.e. no response 1438 // in all-stop mode, and "OK" in non-stop mode; in both cases this 1439 // is followed by the actual stop reason. 1440 return SendContinueSuccessResponse(); 1441 } 1442 1443 GDBRemoteCommunication::PacketResult 1444 GDBRemoteCommunicationServerLLGS::Handle_vKill( 1445 StringExtractorGDBRemote &packet) { 1446 StopSTDIOForwarding(); 1447 1448 packet.SetFilePos(6); // vKill; 1449 uint32_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16); 1450 if (pid == LLDB_INVALID_PROCESS_ID) 1451 return SendIllFormedResponse(packet, 1452 "vKill failed to parse the process id"); 1453 1454 auto it = m_debugged_processes.find(pid); 1455 if (it == m_debugged_processes.end()) 1456 return SendErrorResponse(42); 1457 1458 Status error = it->second.process_up->Kill(); 1459 if (error.Fail()) 1460 return SendErrorResponse(error.ToError()); 1461 1462 // OK response is sent when the process dies. 1463 it->second.flags |= DebuggedProcess::Flag::vkilled; 1464 return PacketResult::Success; 1465 } 1466 1467 GDBRemoteCommunication::PacketResult 1468 GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR( 1469 StringExtractorGDBRemote &packet) { 1470 packet.SetFilePos(::strlen("QSetDisableASLR:")); 1471 if (packet.GetU32(0)) 1472 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR); 1473 else 1474 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR); 1475 return SendOKResponse(); 1476 } 1477 1478 GDBRemoteCommunication::PacketResult 1479 GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir( 1480 StringExtractorGDBRemote &packet) { 1481 packet.SetFilePos(::strlen("QSetWorkingDir:")); 1482 std::string path; 1483 packet.GetHexByteString(path); 1484 m_process_launch_info.SetWorkingDirectory(FileSpec(path)); 1485 return SendOKResponse(); 1486 } 1487 1488 GDBRemoteCommunication::PacketResult 1489 GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir( 1490 StringExtractorGDBRemote &packet) { 1491 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()}; 1492 if (working_dir) { 1493 StreamString response; 1494 response.PutStringAsRawHex8(working_dir.GetCString()); 1495 return SendPacketNoLock(response.GetString()); 1496 } 1497 1498 return SendErrorResponse(14); 1499 } 1500 1501 GDBRemoteCommunication::PacketResult 1502 GDBRemoteCommunicationServerLLGS::Handle_QThreadSuffixSupported( 1503 StringExtractorGDBRemote &packet) { 1504 m_thread_suffix_supported = true; 1505 return SendOKResponse(); 1506 } 1507 1508 GDBRemoteCommunication::PacketResult 1509 GDBRemoteCommunicationServerLLGS::Handle_QListThreadsInStopReply( 1510 StringExtractorGDBRemote &packet) { 1511 m_list_threads_in_stop_reply = true; 1512 return SendOKResponse(); 1513 } 1514 1515 GDBRemoteCommunication::PacketResult 1516 GDBRemoteCommunicationServerLLGS::ResumeProcess( 1517 NativeProcessProtocol &process, const ResumeActionList &actions) { 1518 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread); 1519 1520 // In non-stop protocol mode, the process could be running already. 1521 // We do not support resuming threads independently, so just error out. 1522 if (!process.CanResume()) { 1523 LLDB_LOG(log, "process {0} cannot be resumed (state={1})", process.GetID(), 1524 process.GetState()); 1525 return SendErrorResponse(0x37); 1526 } 1527 1528 Status error = process.Resume(actions); 1529 if (error.Fail()) { 1530 LLDB_LOG(log, "process {0} failed to resume: {1}", process.GetID(), error); 1531 return SendErrorResponse(GDBRemoteServerError::eErrorResume); 1532 } 1533 1534 LLDB_LOG(log, "process {0} resumed", process.GetID()); 1535 1536 return PacketResult::Success; 1537 } 1538 1539 GDBRemoteCommunication::PacketResult 1540 GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) { 1541 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread); 1542 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__); 1543 1544 // Ensure we have a native process. 1545 if (!m_continue_process) { 1546 LLDB_LOGF(log, 1547 "GDBRemoteCommunicationServerLLGS::%s no debugged process " 1548 "shared pointer", 1549 __FUNCTION__); 1550 return SendErrorResponse(0x36); 1551 } 1552 1553 // Pull out the signal number. 1554 packet.SetFilePos(::strlen("C")); 1555 if (packet.GetBytesLeft() < 1) { 1556 // Shouldn't be using a C without a signal. 1557 return SendIllFormedResponse(packet, "C packet specified without signal."); 1558 } 1559 const uint32_t signo = 1560 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 1561 if (signo == std::numeric_limits<uint32_t>::max()) 1562 return SendIllFormedResponse(packet, "failed to parse signal number"); 1563 1564 // Handle optional continue address. 1565 if (packet.GetBytesLeft() > 0) { 1566 // FIXME add continue at address support for $C{signo}[;{continue-address}]. 1567 if (*packet.Peek() == ';') 1568 return SendUnimplementedResponse(packet.GetStringRef().data()); 1569 else 1570 return SendIllFormedResponse( 1571 packet, "unexpected content after $C{signal-number}"); 1572 } 1573 1574 // In non-stop protocol mode, the process could be running already. 1575 // We do not support resuming threads independently, so just error out. 1576 if (!m_continue_process->CanResume()) { 1577 LLDB_LOG(log, "process cannot be resumed (state={0})", 1578 m_continue_process->GetState()); 1579 return SendErrorResponse(0x37); 1580 } 1581 1582 ResumeActionList resume_actions(StateType::eStateRunning, 1583 LLDB_INVALID_SIGNAL_NUMBER); 1584 Status error; 1585 1586 // We have two branches: what to do if a continue thread is specified (in 1587 // which case we target sending the signal to that thread), or when we don't 1588 // have a continue thread set (in which case we send a signal to the 1589 // process). 1590 1591 // TODO discuss with Greg Clayton, make sure this makes sense. 1592 1593 lldb::tid_t signal_tid = GetContinueThreadID(); 1594 if (signal_tid != LLDB_INVALID_THREAD_ID) { 1595 // The resume action for the continue thread (or all threads if a continue 1596 // thread is not set). 1597 ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning, 1598 static_cast<int>(signo)}; 1599 1600 // Add the action for the continue thread (or all threads when the continue 1601 // thread isn't present). 1602 resume_actions.Append(action); 1603 } else { 1604 // Send the signal to the process since we weren't targeting a specific 1605 // continue thread with the signal. 1606 error = m_continue_process->Signal(signo); 1607 if (error.Fail()) { 1608 LLDB_LOG(log, "failed to send signal for process {0}: {1}", 1609 m_continue_process->GetID(), error); 1610 1611 return SendErrorResponse(0x52); 1612 } 1613 } 1614 1615 // NB: this checks CanResume() twice but using a single code path for 1616 // resuming still seems worth it. 1617 PacketResult resume_res = ResumeProcess(*m_continue_process, resume_actions); 1618 if (resume_res != PacketResult::Success) 1619 return resume_res; 1620 1621 // Don't send an "OK" packet, except in non-stop mode; 1622 // otherwise, the response is the stopped/exited message. 1623 return SendContinueSuccessResponse(); 1624 } 1625 1626 GDBRemoteCommunication::PacketResult 1627 GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) { 1628 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread); 1629 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__); 1630 1631 packet.SetFilePos(packet.GetFilePos() + ::strlen("c")); 1632 1633 // For now just support all continue. 1634 const bool has_continue_address = (packet.GetBytesLeft() > 0); 1635 if (has_continue_address) { 1636 LLDB_LOG(log, "not implemented for c[address] variant [{0} remains]", 1637 packet.Peek()); 1638 return SendUnimplementedResponse(packet.GetStringRef().data()); 1639 } 1640 1641 // Ensure we have a native process. 1642 if (!m_continue_process) { 1643 LLDB_LOGF(log, 1644 "GDBRemoteCommunicationServerLLGS::%s no debugged process " 1645 "shared pointer", 1646 __FUNCTION__); 1647 return SendErrorResponse(0x36); 1648 } 1649 1650 // Build the ResumeActionList 1651 ResumeActionList actions(StateType::eStateRunning, 1652 LLDB_INVALID_SIGNAL_NUMBER); 1653 1654 PacketResult resume_res = ResumeProcess(*m_continue_process, actions); 1655 if (resume_res != PacketResult::Success) 1656 return resume_res; 1657 1658 return SendContinueSuccessResponse(); 1659 } 1660 1661 GDBRemoteCommunication::PacketResult 1662 GDBRemoteCommunicationServerLLGS::Handle_vCont_actions( 1663 StringExtractorGDBRemote &packet) { 1664 StreamString response; 1665 response.Printf("vCont;c;C;s;S;t"); 1666 1667 return SendPacketNoLock(response.GetString()); 1668 } 1669 1670 static bool ResumeActionListStopsAllThreads(ResumeActionList &actions) { 1671 // We're doing a stop-all if and only if our only action is a "t" for all 1672 // threads. 1673 if (const ResumeAction *default_action = 1674 actions.GetActionForThread(LLDB_INVALID_THREAD_ID, false)) { 1675 if (default_action->state == eStateSuspended && actions.GetSize() == 1) 1676 return true; 1677 } 1678 1679 return false; 1680 } 1681 1682 GDBRemoteCommunication::PacketResult 1683 GDBRemoteCommunicationServerLLGS::Handle_vCont( 1684 StringExtractorGDBRemote &packet) { 1685 Log *log = GetLog(LLDBLog::Process); 1686 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s handling vCont packet", 1687 __FUNCTION__); 1688 1689 packet.SetFilePos(::strlen("vCont")); 1690 1691 if (packet.GetBytesLeft() == 0) { 1692 LLDB_LOGF(log, 1693 "GDBRemoteCommunicationServerLLGS::%s missing action from " 1694 "vCont package", 1695 __FUNCTION__); 1696 return SendIllFormedResponse(packet, "Missing action from vCont package"); 1697 } 1698 1699 if (::strcmp(packet.Peek(), ";s") == 0) { 1700 // Move past the ';', then do a simple 's'. 1701 packet.SetFilePos(packet.GetFilePos() + 1); 1702 return Handle_s(packet); 1703 } 1704 1705 std::unordered_map<lldb::pid_t, ResumeActionList> thread_actions; 1706 1707 while (packet.GetBytesLeft() && *packet.Peek() == ';') { 1708 // Skip the semi-colon. 1709 packet.GetChar(); 1710 1711 // Build up the thread action. 1712 ResumeAction thread_action; 1713 thread_action.tid = LLDB_INVALID_THREAD_ID; 1714 thread_action.state = eStateInvalid; 1715 thread_action.signal = LLDB_INVALID_SIGNAL_NUMBER; 1716 1717 const char action = packet.GetChar(); 1718 switch (action) { 1719 case 'C': 1720 thread_action.signal = packet.GetHexMaxU32(false, 0); 1721 if (thread_action.signal == 0) 1722 return SendIllFormedResponse( 1723 packet, "Could not parse signal in vCont packet C action"); 1724 LLVM_FALLTHROUGH; 1725 1726 case 'c': 1727 // Continue 1728 thread_action.state = eStateRunning; 1729 break; 1730 1731 case 'S': 1732 thread_action.signal = packet.GetHexMaxU32(false, 0); 1733 if (thread_action.signal == 0) 1734 return SendIllFormedResponse( 1735 packet, "Could not parse signal in vCont packet S action"); 1736 LLVM_FALLTHROUGH; 1737 1738 case 's': 1739 // Step 1740 thread_action.state = eStateStepping; 1741 break; 1742 1743 case 't': 1744 // Stop 1745 thread_action.state = eStateSuspended; 1746 break; 1747 1748 default: 1749 return SendIllFormedResponse(packet, "Unsupported vCont action"); 1750 break; 1751 } 1752 1753 lldb::pid_t pid = StringExtractorGDBRemote::AllProcesses; 1754 lldb::tid_t tid = StringExtractorGDBRemote::AllThreads; 1755 1756 // Parse out optional :{thread-id} value. 1757 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) { 1758 // Consume the separator. 1759 packet.GetChar(); 1760 1761 auto pid_tid = packet.GetPidTid(StringExtractorGDBRemote::AllProcesses); 1762 if (!pid_tid) 1763 return SendIllFormedResponse(packet, "Malformed thread-id"); 1764 1765 pid = pid_tid->first; 1766 tid = pid_tid->second; 1767 } 1768 1769 if (thread_action.state == eStateSuspended && 1770 tid != StringExtractorGDBRemote::AllThreads) { 1771 return SendIllFormedResponse( 1772 packet, "'t' action not supported for individual threads"); 1773 } 1774 1775 if (pid == StringExtractorGDBRemote::AllProcesses) { 1776 if (m_debugged_processes.size() > 1) 1777 return SendIllFormedResponse( 1778 packet, "Resuming multiple processes not supported yet"); 1779 if (!m_continue_process) { 1780 LLDB_LOG(log, "no debugged process"); 1781 return SendErrorResponse(0x36); 1782 } 1783 pid = m_continue_process->GetID(); 1784 } 1785 1786 if (tid == StringExtractorGDBRemote::AllThreads) 1787 tid = LLDB_INVALID_THREAD_ID; 1788 1789 thread_action.tid = tid; 1790 1791 thread_actions[pid].Append(thread_action); 1792 } 1793 1794 assert(thread_actions.size() >= 1); 1795 if (thread_actions.size() > 1) 1796 return SendIllFormedResponse( 1797 packet, "Resuming multiple processes not supported yet"); 1798 1799 for (std::pair<lldb::pid_t, ResumeActionList> x : thread_actions) { 1800 auto process_it = m_debugged_processes.find(x.first); 1801 if (process_it == m_debugged_processes.end()) { 1802 LLDB_LOG(log, "vCont failed for process {0}: process not debugged", 1803 x.first); 1804 return SendErrorResponse(GDBRemoteServerError::eErrorResume); 1805 } 1806 1807 // There are four possible scenarios here. These are: 1808 // 1. vCont on a stopped process that resumes at least one thread. 1809 // In this case, we call Resume(). 1810 // 2. vCont on a stopped process that leaves all threads suspended. 1811 // A no-op. 1812 // 3. vCont on a running process that requests suspending all 1813 // running threads. In this case, we call Interrupt(). 1814 // 4. vCont on a running process that requests suspending a subset 1815 // of running threads or resuming a subset of suspended threads. 1816 // Since we do not support full nonstop mode, this is unsupported 1817 // and we return an error. 1818 1819 assert(process_it->second.process_up); 1820 if (ResumeActionListStopsAllThreads(x.second)) { 1821 if (process_it->second.process_up->IsRunning()) { 1822 assert(m_non_stop); 1823 1824 Status error = process_it->second.process_up->Interrupt(); 1825 if (error.Fail()) { 1826 LLDB_LOG(log, "vCont failed to halt process {0}: {1}", x.first, 1827 error); 1828 return SendErrorResponse(GDBRemoteServerError::eErrorResume); 1829 } 1830 1831 LLDB_LOG(log, "halted process {0}", x.first); 1832 1833 // hack to avoid enabling stdio forwarding after stop 1834 // TODO: remove this when we improve stdio forwarding for nonstop 1835 assert(thread_actions.size() == 1); 1836 return SendOKResponse(); 1837 } 1838 } else { 1839 PacketResult resume_res = 1840 ResumeProcess(*process_it->second.process_up, x.second); 1841 if (resume_res != PacketResult::Success) 1842 return resume_res; 1843 } 1844 } 1845 1846 return SendContinueSuccessResponse(); 1847 } 1848 1849 void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) { 1850 Log *log = GetLog(LLDBLog::Thread); 1851 LLDB_LOG(log, "setting current thread id to {0}", tid); 1852 1853 m_current_tid = tid; 1854 if (m_current_process) 1855 m_current_process->SetCurrentThreadID(m_current_tid); 1856 } 1857 1858 void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) { 1859 Log *log = GetLog(LLDBLog::Thread); 1860 LLDB_LOG(log, "setting continue thread id to {0}", tid); 1861 1862 m_continue_tid = tid; 1863 } 1864 1865 GDBRemoteCommunication::PacketResult 1866 GDBRemoteCommunicationServerLLGS::Handle_stop_reason( 1867 StringExtractorGDBRemote &packet) { 1868 // Handle the $? gdbremote command. 1869 1870 if (m_non_stop) { 1871 // Clear the notification queue first, except for pending exit 1872 // notifications. 1873 llvm::erase_if(m_stop_notification_queue, [](const std::string &x) { 1874 return x.front() != 'W' && x.front() != 'X'; 1875 }); 1876 1877 if (m_current_process) { 1878 // Queue stop reply packets for all active threads. Start with 1879 // the current thread (for clients that don't actually support multiple 1880 // stop reasons). 1881 NativeThreadProtocol *thread = m_current_process->GetCurrentThread(); 1882 if (thread) 1883 m_stop_notification_queue.push_back( 1884 PrepareStopReplyPacketForThread(*thread).GetString().str()); 1885 EnqueueStopReplyPackets(thread ? thread->GetID() 1886 : LLDB_INVALID_THREAD_ID); 1887 } 1888 1889 // If the notification queue is empty (i.e. everything is running), send OK. 1890 if (m_stop_notification_queue.empty()) 1891 return SendOKResponse(); 1892 1893 // Send the first item from the new notification queue synchronously. 1894 return SendPacketNoLock(m_stop_notification_queue.front()); 1895 } 1896 1897 // If no process, indicate error 1898 if (!m_current_process) 1899 return SendErrorResponse(02); 1900 1901 return SendStopReasonForState(*m_current_process, 1902 m_current_process->GetState(), 1903 /*force_synchronous=*/true); 1904 } 1905 1906 GDBRemoteCommunication::PacketResult 1907 GDBRemoteCommunicationServerLLGS::SendStopReasonForState( 1908 NativeProcessProtocol &process, lldb::StateType process_state, 1909 bool force_synchronous) { 1910 Log *log = GetLog(LLDBLog::Process); 1911 1912 switch (process_state) { 1913 case eStateAttaching: 1914 case eStateLaunching: 1915 case eStateRunning: 1916 case eStateStepping: 1917 case eStateDetached: 1918 // NOTE: gdb protocol doc looks like it should return $OK 1919 // when everything is running (i.e. no stopped result). 1920 return PacketResult::Success; // Ignore 1921 1922 case eStateSuspended: 1923 case eStateStopped: 1924 case eStateCrashed: { 1925 lldb::tid_t tid = process.GetCurrentThreadID(); 1926 // Make sure we set the current thread so g and p packets return the data 1927 // the gdb will expect. 1928 SetCurrentThreadID(tid); 1929 return SendStopReplyPacketForThread(process, tid, force_synchronous); 1930 } 1931 1932 case eStateInvalid: 1933 case eStateUnloaded: 1934 case eStateExited: 1935 return SendWResponse(&process); 1936 1937 default: 1938 LLDB_LOG(log, "pid {0}, current state reporting not handled: {1}", 1939 process.GetID(), process_state); 1940 break; 1941 } 1942 1943 return SendErrorResponse(0); 1944 } 1945 1946 GDBRemoteCommunication::PacketResult 1947 GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo( 1948 StringExtractorGDBRemote &packet) { 1949 // Fail if we don't have a current process. 1950 if (!m_current_process || 1951 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 1952 return SendErrorResponse(68); 1953 1954 // Ensure we have a thread. 1955 NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0); 1956 if (!thread) 1957 return SendErrorResponse(69); 1958 1959 // Get the register context for the first thread. 1960 NativeRegisterContext ®_context = thread->GetRegisterContext(); 1961 1962 // Parse out the register number from the request. 1963 packet.SetFilePos(strlen("qRegisterInfo")); 1964 const uint32_t reg_index = 1965 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 1966 if (reg_index == std::numeric_limits<uint32_t>::max()) 1967 return SendErrorResponse(69); 1968 1969 // Return the end of registers response if we've iterated one past the end of 1970 // the register set. 1971 if (reg_index >= reg_context.GetUserRegisterCount()) 1972 return SendErrorResponse(69); 1973 1974 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index); 1975 if (!reg_info) 1976 return SendErrorResponse(69); 1977 1978 // Build the reginfos response. 1979 StreamGDBRemote response; 1980 1981 response.PutCString("name:"); 1982 response.PutCString(reg_info->name); 1983 response.PutChar(';'); 1984 1985 if (reg_info->alt_name && reg_info->alt_name[0]) { 1986 response.PutCString("alt-name:"); 1987 response.PutCString(reg_info->alt_name); 1988 response.PutChar(';'); 1989 } 1990 1991 response.Printf("bitsize:%" PRIu32 ";", reg_info->byte_size * 8); 1992 1993 if (!reg_context.RegisterOffsetIsDynamic()) 1994 response.Printf("offset:%" PRIu32 ";", reg_info->byte_offset); 1995 1996 llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info); 1997 if (!encoding.empty()) 1998 response << "encoding:" << encoding << ';'; 1999 2000 llvm::StringRef format = GetFormatNameOrEmpty(*reg_info); 2001 if (!format.empty()) 2002 response << "format:" << format << ';'; 2003 2004 const char *const register_set_name = 2005 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index); 2006 if (register_set_name) 2007 response << "set:" << register_set_name << ';'; 2008 2009 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] != 2010 LLDB_INVALID_REGNUM) 2011 response.Printf("ehframe:%" PRIu32 ";", 2012 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]); 2013 2014 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM) 2015 response.Printf("dwarf:%" PRIu32 ";", 2016 reg_info->kinds[RegisterKind::eRegisterKindDWARF]); 2017 2018 llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info); 2019 if (!kind_generic.empty()) 2020 response << "generic:" << kind_generic << ';'; 2021 2022 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) { 2023 response.PutCString("container-regs:"); 2024 CollectRegNums(reg_info->value_regs, response, true); 2025 response.PutChar(';'); 2026 } 2027 2028 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) { 2029 response.PutCString("invalidate-regs:"); 2030 CollectRegNums(reg_info->invalidate_regs, response, true); 2031 response.PutChar(';'); 2032 } 2033 2034 return SendPacketNoLock(response.GetString()); 2035 } 2036 2037 void GDBRemoteCommunicationServerLLGS::AddProcessThreads( 2038 StreamGDBRemote &response, NativeProcessProtocol &process, bool &had_any) { 2039 Log *log = GetLog(LLDBLog::Thread); 2040 2041 lldb::pid_t pid = process.GetID(); 2042 if (pid == LLDB_INVALID_PROCESS_ID) 2043 return; 2044 2045 LLDB_LOG(log, "iterating over threads of process {0}", process.GetID()); 2046 for (NativeThreadProtocol &thread : process.Threads()) { 2047 LLDB_LOG(log, "iterated thread tid={0}", thread.GetID()); 2048 response.PutChar(had_any ? ',' : 'm'); 2049 AppendThreadIDToResponse(response, pid, thread.GetID()); 2050 had_any = true; 2051 } 2052 } 2053 2054 GDBRemoteCommunication::PacketResult 2055 GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo( 2056 StringExtractorGDBRemote &packet) { 2057 assert(m_debugged_processes.size() == 1 || 2058 bool(m_extensions_supported & 2059 NativeProcessProtocol::Extension::multiprocess)); 2060 2061 bool had_any = false; 2062 StreamGDBRemote response; 2063 2064 for (auto &pid_ptr : m_debugged_processes) 2065 AddProcessThreads(response, *pid_ptr.second.process_up, had_any); 2066 2067 if (!had_any) 2068 return SendOKResponse(); 2069 return SendPacketNoLock(response.GetString()); 2070 } 2071 2072 GDBRemoteCommunication::PacketResult 2073 GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo( 2074 StringExtractorGDBRemote &packet) { 2075 // FIXME for now we return the full thread list in the initial packet and 2076 // always do nothing here. 2077 return SendPacketNoLock("l"); 2078 } 2079 2080 GDBRemoteCommunication::PacketResult 2081 GDBRemoteCommunicationServerLLGS::Handle_g(StringExtractorGDBRemote &packet) { 2082 Log *log = GetLog(LLDBLog::Thread); 2083 2084 // Move past packet name. 2085 packet.SetFilePos(strlen("g")); 2086 2087 // Get the thread to use. 2088 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 2089 if (!thread) { 2090 LLDB_LOG(log, "failed, no thread available"); 2091 return SendErrorResponse(0x15); 2092 } 2093 2094 // Get the thread's register context. 2095 NativeRegisterContext ®_ctx = thread->GetRegisterContext(); 2096 2097 std::vector<uint8_t> regs_buffer; 2098 for (uint32_t reg_num = 0; reg_num < reg_ctx.GetUserRegisterCount(); 2099 ++reg_num) { 2100 const RegisterInfo *reg_info = reg_ctx.GetRegisterInfoAtIndex(reg_num); 2101 2102 if (reg_info == nullptr) { 2103 LLDB_LOG(log, "failed to get register info for register index {0}", 2104 reg_num); 2105 return SendErrorResponse(0x15); 2106 } 2107 2108 if (reg_info->value_regs != nullptr) 2109 continue; // skip registers that are contained in other registers 2110 2111 RegisterValue reg_value; 2112 Status error = reg_ctx.ReadRegister(reg_info, reg_value); 2113 if (error.Fail()) { 2114 LLDB_LOG(log, "failed to read register at index {0}", reg_num); 2115 return SendErrorResponse(0x15); 2116 } 2117 2118 if (reg_info->byte_offset + reg_info->byte_size >= regs_buffer.size()) 2119 // Resize the buffer to guarantee it can store the register offsetted 2120 // data. 2121 regs_buffer.resize(reg_info->byte_offset + reg_info->byte_size); 2122 2123 // Copy the register offsetted data to the buffer. 2124 memcpy(regs_buffer.data() + reg_info->byte_offset, reg_value.GetBytes(), 2125 reg_info->byte_size); 2126 } 2127 2128 // Write the response. 2129 StreamGDBRemote response; 2130 response.PutBytesAsRawHex8(regs_buffer.data(), regs_buffer.size()); 2131 2132 return SendPacketNoLock(response.GetString()); 2133 } 2134 2135 GDBRemoteCommunication::PacketResult 2136 GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) { 2137 Log *log = GetLog(LLDBLog::Thread); 2138 2139 // Parse out the register number from the request. 2140 packet.SetFilePos(strlen("p")); 2141 const uint32_t reg_index = 2142 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 2143 if (reg_index == std::numeric_limits<uint32_t>::max()) { 2144 LLDB_LOGF(log, 2145 "GDBRemoteCommunicationServerLLGS::%s failed, could not " 2146 "parse register number from request \"%s\"", 2147 __FUNCTION__, packet.GetStringRef().data()); 2148 return SendErrorResponse(0x15); 2149 } 2150 2151 // Get the thread to use. 2152 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 2153 if (!thread) { 2154 LLDB_LOG(log, "failed, no thread available"); 2155 return SendErrorResponse(0x15); 2156 } 2157 2158 // Get the thread's register context. 2159 NativeRegisterContext ®_context = thread->GetRegisterContext(); 2160 2161 // Return the end of registers response if we've iterated one past the end of 2162 // the register set. 2163 if (reg_index >= reg_context.GetUserRegisterCount()) { 2164 LLDB_LOGF(log, 2165 "GDBRemoteCommunicationServerLLGS::%s failed, requested " 2166 "register %" PRIu32 " beyond register count %" PRIu32, 2167 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount()); 2168 return SendErrorResponse(0x15); 2169 } 2170 2171 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index); 2172 if (!reg_info) { 2173 LLDB_LOGF(log, 2174 "GDBRemoteCommunicationServerLLGS::%s failed, requested " 2175 "register %" PRIu32 " returned NULL", 2176 __FUNCTION__, reg_index); 2177 return SendErrorResponse(0x15); 2178 } 2179 2180 // Build the reginfos response. 2181 StreamGDBRemote response; 2182 2183 // Retrieve the value 2184 RegisterValue reg_value; 2185 Status error = reg_context.ReadRegister(reg_info, reg_value); 2186 if (error.Fail()) { 2187 LLDB_LOGF(log, 2188 "GDBRemoteCommunicationServerLLGS::%s failed, read of " 2189 "requested register %" PRIu32 " (%s) failed: %s", 2190 __FUNCTION__, reg_index, reg_info->name, error.AsCString()); 2191 return SendErrorResponse(0x15); 2192 } 2193 2194 const uint8_t *const data = 2195 static_cast<const uint8_t *>(reg_value.GetBytes()); 2196 if (!data) { 2197 LLDB_LOGF(log, 2198 "GDBRemoteCommunicationServerLLGS::%s failed to get data " 2199 "bytes from requested register %" PRIu32, 2200 __FUNCTION__, reg_index); 2201 return SendErrorResponse(0x15); 2202 } 2203 2204 // FIXME flip as needed to get data in big/little endian format for this host. 2205 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i) 2206 response.PutHex8(data[i]); 2207 2208 return SendPacketNoLock(response.GetString()); 2209 } 2210 2211 GDBRemoteCommunication::PacketResult 2212 GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) { 2213 Log *log = GetLog(LLDBLog::Thread); 2214 2215 // Ensure there is more content. 2216 if (packet.GetBytesLeft() < 1) 2217 return SendIllFormedResponse(packet, "Empty P packet"); 2218 2219 // Parse out the register number from the request. 2220 packet.SetFilePos(strlen("P")); 2221 const uint32_t reg_index = 2222 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 2223 if (reg_index == std::numeric_limits<uint32_t>::max()) { 2224 LLDB_LOGF(log, 2225 "GDBRemoteCommunicationServerLLGS::%s failed, could not " 2226 "parse register number from request \"%s\"", 2227 __FUNCTION__, packet.GetStringRef().data()); 2228 return SendErrorResponse(0x29); 2229 } 2230 2231 // Note debugserver would send an E30 here. 2232 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '=')) 2233 return SendIllFormedResponse( 2234 packet, "P packet missing '=' char after register number"); 2235 2236 // Parse out the value. 2237 uint8_t reg_bytes[RegisterValue::kMaxRegisterByteSize]; 2238 size_t reg_size = packet.GetHexBytesAvail(reg_bytes); 2239 2240 // Get the thread to use. 2241 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 2242 if (!thread) { 2243 LLDB_LOGF(log, 2244 "GDBRemoteCommunicationServerLLGS::%s failed, no thread " 2245 "available (thread index 0)", 2246 __FUNCTION__); 2247 return SendErrorResponse(0x28); 2248 } 2249 2250 // Get the thread's register context. 2251 NativeRegisterContext ®_context = thread->GetRegisterContext(); 2252 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index); 2253 if (!reg_info) { 2254 LLDB_LOGF(log, 2255 "GDBRemoteCommunicationServerLLGS::%s failed, requested " 2256 "register %" PRIu32 " returned NULL", 2257 __FUNCTION__, reg_index); 2258 return SendErrorResponse(0x48); 2259 } 2260 2261 // Return the end of registers response if we've iterated one past the end of 2262 // the register set. 2263 if (reg_index >= reg_context.GetUserRegisterCount()) { 2264 LLDB_LOGF(log, 2265 "GDBRemoteCommunicationServerLLGS::%s failed, requested " 2266 "register %" PRIu32 " beyond register count %" PRIu32, 2267 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount()); 2268 return SendErrorResponse(0x47); 2269 } 2270 2271 if (reg_size != reg_info->byte_size) 2272 return SendIllFormedResponse(packet, "P packet register size is incorrect"); 2273 2274 // Build the reginfos response. 2275 StreamGDBRemote response; 2276 2277 RegisterValue reg_value(makeArrayRef(reg_bytes, reg_size), 2278 m_current_process->GetArchitecture().GetByteOrder()); 2279 Status error = reg_context.WriteRegister(reg_info, reg_value); 2280 if (error.Fail()) { 2281 LLDB_LOGF(log, 2282 "GDBRemoteCommunicationServerLLGS::%s failed, write of " 2283 "requested register %" PRIu32 " (%s) failed: %s", 2284 __FUNCTION__, reg_index, reg_info->name, error.AsCString()); 2285 return SendErrorResponse(0x32); 2286 } 2287 2288 return SendOKResponse(); 2289 } 2290 2291 GDBRemoteCommunication::PacketResult 2292 GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) { 2293 Log *log = GetLog(LLDBLog::Thread); 2294 2295 // Parse out which variant of $H is requested. 2296 packet.SetFilePos(strlen("H")); 2297 if (packet.GetBytesLeft() < 1) { 2298 LLDB_LOGF(log, 2299 "GDBRemoteCommunicationServerLLGS::%s failed, H command " 2300 "missing {g,c} variant", 2301 __FUNCTION__); 2302 return SendIllFormedResponse(packet, "H command missing {g,c} variant"); 2303 } 2304 2305 const char h_variant = packet.GetChar(); 2306 NativeProcessProtocol *default_process; 2307 switch (h_variant) { 2308 case 'g': 2309 default_process = m_current_process; 2310 break; 2311 2312 case 'c': 2313 default_process = m_continue_process; 2314 break; 2315 2316 default: 2317 LLDB_LOGF( 2318 log, 2319 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c", 2320 __FUNCTION__, h_variant); 2321 return SendIllFormedResponse(packet, 2322 "H variant unsupported, should be c or g"); 2323 } 2324 2325 // Parse out the thread number. 2326 auto pid_tid = packet.GetPidTid(default_process ? default_process->GetID() 2327 : LLDB_INVALID_PROCESS_ID); 2328 if (!pid_tid) 2329 return SendErrorResponse(llvm::make_error<StringError>( 2330 inconvertibleErrorCode(), "Malformed thread-id")); 2331 2332 lldb::pid_t pid = pid_tid->first; 2333 lldb::tid_t tid = pid_tid->second; 2334 2335 if (pid == StringExtractorGDBRemote::AllProcesses) 2336 return SendUnimplementedResponse("Selecting all processes not supported"); 2337 if (pid == LLDB_INVALID_PROCESS_ID) 2338 return SendErrorResponse(llvm::make_error<StringError>( 2339 inconvertibleErrorCode(), "No current process and no PID provided")); 2340 2341 // Check the process ID and find respective process instance. 2342 auto new_process_it = m_debugged_processes.find(pid); 2343 if (new_process_it == m_debugged_processes.end()) 2344 return SendErrorResponse(llvm::make_error<StringError>( 2345 inconvertibleErrorCode(), 2346 llvm::formatv("No process with PID {0} debugged", pid))); 2347 2348 // Ensure we have the given thread when not specifying -1 (all threads) or 0 2349 // (any thread). 2350 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) { 2351 NativeThreadProtocol *thread = 2352 new_process_it->second.process_up->GetThreadByID(tid); 2353 if (!thread) { 2354 LLDB_LOGF(log, 2355 "GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64 2356 " not found", 2357 __FUNCTION__, tid); 2358 return SendErrorResponse(0x15); 2359 } 2360 } 2361 2362 // Now switch the given process and thread type. 2363 switch (h_variant) { 2364 case 'g': 2365 m_current_process = new_process_it->second.process_up.get(); 2366 SetCurrentThreadID(tid); 2367 break; 2368 2369 case 'c': 2370 m_continue_process = new_process_it->second.process_up.get(); 2371 SetContinueThreadID(tid); 2372 break; 2373 2374 default: 2375 assert(false && "unsupported $H variant - shouldn't get here"); 2376 return SendIllFormedResponse(packet, 2377 "H variant unsupported, should be c or g"); 2378 } 2379 2380 return SendOKResponse(); 2381 } 2382 2383 GDBRemoteCommunication::PacketResult 2384 GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) { 2385 Log *log = GetLog(LLDBLog::Thread); 2386 2387 // Fail if we don't have a current process. 2388 if (!m_current_process || 2389 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2390 LLDB_LOGF( 2391 log, 2392 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2393 __FUNCTION__); 2394 return SendErrorResponse(0x15); 2395 } 2396 2397 packet.SetFilePos(::strlen("I")); 2398 uint8_t tmp[4096]; 2399 for (;;) { 2400 size_t read = packet.GetHexBytesAvail(tmp); 2401 if (read == 0) { 2402 break; 2403 } 2404 // write directly to stdin *this might block if stdin buffer is full* 2405 // TODO: enqueue this block in circular buffer and send window size to 2406 // remote host 2407 ConnectionStatus status; 2408 Status error; 2409 m_stdio_communication.Write(tmp, read, status, &error); 2410 if (error.Fail()) { 2411 return SendErrorResponse(0x15); 2412 } 2413 } 2414 2415 return SendOKResponse(); 2416 } 2417 2418 GDBRemoteCommunication::PacketResult 2419 GDBRemoteCommunicationServerLLGS::Handle_interrupt( 2420 StringExtractorGDBRemote &packet) { 2421 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread); 2422 2423 // Fail if we don't have a current process. 2424 if (!m_current_process || 2425 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2426 LLDB_LOG(log, "failed, no process available"); 2427 return SendErrorResponse(0x15); 2428 } 2429 2430 // Interrupt the process. 2431 Status error = m_current_process->Interrupt(); 2432 if (error.Fail()) { 2433 LLDB_LOG(log, "failed for process {0}: {1}", m_current_process->GetID(), 2434 error); 2435 return SendErrorResponse(GDBRemoteServerError::eErrorResume); 2436 } 2437 2438 LLDB_LOG(log, "stopped process {0}", m_current_process->GetID()); 2439 2440 // No response required from stop all. 2441 return PacketResult::Success; 2442 } 2443 2444 GDBRemoteCommunication::PacketResult 2445 GDBRemoteCommunicationServerLLGS::Handle_memory_read( 2446 StringExtractorGDBRemote &packet) { 2447 Log *log = GetLog(LLDBLog::Process); 2448 2449 if (!m_current_process || 2450 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2451 LLDB_LOGF( 2452 log, 2453 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2454 __FUNCTION__); 2455 return SendErrorResponse(0x15); 2456 } 2457 2458 // Parse out the memory address. 2459 packet.SetFilePos(strlen("m")); 2460 if (packet.GetBytesLeft() < 1) 2461 return SendIllFormedResponse(packet, "Too short m packet"); 2462 2463 // Read the address. Punting on validation. 2464 // FIXME replace with Hex U64 read with no default value that fails on failed 2465 // read. 2466 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0); 2467 2468 // Validate comma. 2469 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ',')) 2470 return SendIllFormedResponse(packet, "Comma sep missing in m packet"); 2471 2472 // Get # bytes to read. 2473 if (packet.GetBytesLeft() < 1) 2474 return SendIllFormedResponse(packet, "Length missing in m packet"); 2475 2476 const uint64_t byte_count = packet.GetHexMaxU64(false, 0); 2477 if (byte_count == 0) { 2478 LLDB_LOGF(log, 2479 "GDBRemoteCommunicationServerLLGS::%s nothing to read: " 2480 "zero-length packet", 2481 __FUNCTION__); 2482 return SendOKResponse(); 2483 } 2484 2485 // Allocate the response buffer. 2486 std::string buf(byte_count, '\0'); 2487 if (buf.empty()) 2488 return SendErrorResponse(0x78); 2489 2490 // Retrieve the process memory. 2491 size_t bytes_read = 0; 2492 Status error = m_current_process->ReadMemoryWithoutTrap( 2493 read_addr, &buf[0], byte_count, bytes_read); 2494 if (error.Fail()) { 2495 LLDB_LOGF(log, 2496 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 2497 " mem 0x%" PRIx64 ": failed to read. Error: %s", 2498 __FUNCTION__, m_current_process->GetID(), read_addr, 2499 error.AsCString()); 2500 return SendErrorResponse(0x08); 2501 } 2502 2503 if (bytes_read == 0) { 2504 LLDB_LOGF(log, 2505 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 2506 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes", 2507 __FUNCTION__, m_current_process->GetID(), read_addr, byte_count); 2508 return SendErrorResponse(0x08); 2509 } 2510 2511 StreamGDBRemote response; 2512 packet.SetFilePos(0); 2513 char kind = packet.GetChar('?'); 2514 if (kind == 'x') 2515 response.PutEscapedBytes(buf.data(), byte_count); 2516 else { 2517 assert(kind == 'm'); 2518 for (size_t i = 0; i < bytes_read; ++i) 2519 response.PutHex8(buf[i]); 2520 } 2521 2522 return SendPacketNoLock(response.GetString()); 2523 } 2524 2525 GDBRemoteCommunication::PacketResult 2526 GDBRemoteCommunicationServerLLGS::Handle__M(StringExtractorGDBRemote &packet) { 2527 Log *log = GetLog(LLDBLog::Process); 2528 2529 if (!m_current_process || 2530 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2531 LLDB_LOGF( 2532 log, 2533 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2534 __FUNCTION__); 2535 return SendErrorResponse(0x15); 2536 } 2537 2538 // Parse out the memory address. 2539 packet.SetFilePos(strlen("_M")); 2540 if (packet.GetBytesLeft() < 1) 2541 return SendIllFormedResponse(packet, "Too short _M packet"); 2542 2543 const lldb::addr_t size = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 2544 if (size == LLDB_INVALID_ADDRESS) 2545 return SendIllFormedResponse(packet, "Address not valid"); 2546 if (packet.GetChar() != ',') 2547 return SendIllFormedResponse(packet, "Bad packet"); 2548 Permissions perms = {}; 2549 while (packet.GetBytesLeft() > 0) { 2550 switch (packet.GetChar()) { 2551 case 'r': 2552 perms |= ePermissionsReadable; 2553 break; 2554 case 'w': 2555 perms |= ePermissionsWritable; 2556 break; 2557 case 'x': 2558 perms |= ePermissionsExecutable; 2559 break; 2560 default: 2561 return SendIllFormedResponse(packet, "Bad permissions"); 2562 } 2563 } 2564 2565 llvm::Expected<addr_t> addr = m_current_process->AllocateMemory(size, perms); 2566 if (!addr) 2567 return SendErrorResponse(addr.takeError()); 2568 2569 StreamGDBRemote response; 2570 response.PutHex64(*addr); 2571 return SendPacketNoLock(response.GetString()); 2572 } 2573 2574 GDBRemoteCommunication::PacketResult 2575 GDBRemoteCommunicationServerLLGS::Handle__m(StringExtractorGDBRemote &packet) { 2576 Log *log = GetLog(LLDBLog::Process); 2577 2578 if (!m_current_process || 2579 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2580 LLDB_LOGF( 2581 log, 2582 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2583 __FUNCTION__); 2584 return SendErrorResponse(0x15); 2585 } 2586 2587 // Parse out the memory address. 2588 packet.SetFilePos(strlen("_m")); 2589 if (packet.GetBytesLeft() < 1) 2590 return SendIllFormedResponse(packet, "Too short m packet"); 2591 2592 const lldb::addr_t addr = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 2593 if (addr == LLDB_INVALID_ADDRESS) 2594 return SendIllFormedResponse(packet, "Address not valid"); 2595 2596 if (llvm::Error Err = m_current_process->DeallocateMemory(addr)) 2597 return SendErrorResponse(std::move(Err)); 2598 2599 return SendOKResponse(); 2600 } 2601 2602 GDBRemoteCommunication::PacketResult 2603 GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) { 2604 Log *log = GetLog(LLDBLog::Process); 2605 2606 if (!m_current_process || 2607 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2608 LLDB_LOGF( 2609 log, 2610 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2611 __FUNCTION__); 2612 return SendErrorResponse(0x15); 2613 } 2614 2615 // Parse out the memory address. 2616 packet.SetFilePos(strlen("M")); 2617 if (packet.GetBytesLeft() < 1) 2618 return SendIllFormedResponse(packet, "Too short M packet"); 2619 2620 // Read the address. Punting on validation. 2621 // FIXME replace with Hex U64 read with no default value that fails on failed 2622 // read. 2623 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0); 2624 2625 // Validate comma. 2626 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ',')) 2627 return SendIllFormedResponse(packet, "Comma sep missing in M packet"); 2628 2629 // Get # bytes to read. 2630 if (packet.GetBytesLeft() < 1) 2631 return SendIllFormedResponse(packet, "Length missing in M packet"); 2632 2633 const uint64_t byte_count = packet.GetHexMaxU64(false, 0); 2634 if (byte_count == 0) { 2635 LLDB_LOG(log, "nothing to write: zero-length packet"); 2636 return PacketResult::Success; 2637 } 2638 2639 // Validate colon. 2640 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':')) 2641 return SendIllFormedResponse( 2642 packet, "Comma sep missing in M packet after byte length"); 2643 2644 // Allocate the conversion buffer. 2645 std::vector<uint8_t> buf(byte_count, 0); 2646 if (buf.empty()) 2647 return SendErrorResponse(0x78); 2648 2649 // Convert the hex memory write contents to bytes. 2650 StreamGDBRemote response; 2651 const uint64_t convert_count = packet.GetHexBytes(buf, 0); 2652 if (convert_count != byte_count) { 2653 LLDB_LOG(log, 2654 "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} " 2655 "to convert.", 2656 m_current_process->GetID(), write_addr, byte_count, convert_count); 2657 return SendIllFormedResponse(packet, "M content byte length specified did " 2658 "not match hex-encoded content " 2659 "length"); 2660 } 2661 2662 // Write the process memory. 2663 size_t bytes_written = 0; 2664 Status error = m_current_process->WriteMemory(write_addr, &buf[0], byte_count, 2665 bytes_written); 2666 if (error.Fail()) { 2667 LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}", 2668 m_current_process->GetID(), write_addr, error); 2669 return SendErrorResponse(0x09); 2670 } 2671 2672 if (bytes_written == 0) { 2673 LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes", 2674 m_current_process->GetID(), write_addr, byte_count); 2675 return SendErrorResponse(0x09); 2676 } 2677 2678 return SendOKResponse(); 2679 } 2680 2681 GDBRemoteCommunication::PacketResult 2682 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported( 2683 StringExtractorGDBRemote &packet) { 2684 Log *log = GetLog(LLDBLog::Process); 2685 2686 // Currently only the NativeProcessProtocol knows if it can handle a 2687 // qMemoryRegionInfoSupported request, but we're not guaranteed to be 2688 // attached to a process. For now we'll assume the client only asks this 2689 // when a process is being debugged. 2690 2691 // Ensure we have a process running; otherwise, we can't figure this out 2692 // since we won't have a NativeProcessProtocol. 2693 if (!m_current_process || 2694 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2695 LLDB_LOGF( 2696 log, 2697 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2698 __FUNCTION__); 2699 return SendErrorResponse(0x15); 2700 } 2701 2702 // Test if we can get any region back when asking for the region around NULL. 2703 MemoryRegionInfo region_info; 2704 const Status error = m_current_process->GetMemoryRegionInfo(0, region_info); 2705 if (error.Fail()) { 2706 // We don't support memory region info collection for this 2707 // NativeProcessProtocol. 2708 return SendUnimplementedResponse(""); 2709 } 2710 2711 return SendOKResponse(); 2712 } 2713 2714 GDBRemoteCommunication::PacketResult 2715 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo( 2716 StringExtractorGDBRemote &packet) { 2717 Log *log = GetLog(LLDBLog::Process); 2718 2719 // Ensure we have a process. 2720 if (!m_current_process || 2721 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2722 LLDB_LOGF( 2723 log, 2724 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2725 __FUNCTION__); 2726 return SendErrorResponse(0x15); 2727 } 2728 2729 // Parse out the memory address. 2730 packet.SetFilePos(strlen("qMemoryRegionInfo:")); 2731 if (packet.GetBytesLeft() < 1) 2732 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet"); 2733 2734 // Read the address. Punting on validation. 2735 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0); 2736 2737 StreamGDBRemote response; 2738 2739 // Get the memory region info for the target address. 2740 MemoryRegionInfo region_info; 2741 const Status error = 2742 m_current_process->GetMemoryRegionInfo(read_addr, region_info); 2743 if (error.Fail()) { 2744 // Return the error message. 2745 2746 response.PutCString("error:"); 2747 response.PutStringAsRawHex8(error.AsCString()); 2748 response.PutChar(';'); 2749 } else { 2750 // Range start and size. 2751 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";", 2752 region_info.GetRange().GetRangeBase(), 2753 region_info.GetRange().GetByteSize()); 2754 2755 // Permissions. 2756 if (region_info.GetReadable() || region_info.GetWritable() || 2757 region_info.GetExecutable()) { 2758 // Write permissions info. 2759 response.PutCString("permissions:"); 2760 2761 if (region_info.GetReadable()) 2762 response.PutChar('r'); 2763 if (region_info.GetWritable()) 2764 response.PutChar('w'); 2765 if (region_info.GetExecutable()) 2766 response.PutChar('x'); 2767 2768 response.PutChar(';'); 2769 } 2770 2771 // Flags 2772 MemoryRegionInfo::OptionalBool memory_tagged = 2773 region_info.GetMemoryTagged(); 2774 if (memory_tagged != MemoryRegionInfo::eDontKnow) { 2775 response.PutCString("flags:"); 2776 if (memory_tagged == MemoryRegionInfo::eYes) { 2777 response.PutCString("mt"); 2778 } 2779 response.PutChar(';'); 2780 } 2781 2782 // Name 2783 ConstString name = region_info.GetName(); 2784 if (name) { 2785 response.PutCString("name:"); 2786 response.PutStringAsRawHex8(name.GetStringRef()); 2787 response.PutChar(';'); 2788 } 2789 } 2790 2791 return SendPacketNoLock(response.GetString()); 2792 } 2793 2794 GDBRemoteCommunication::PacketResult 2795 GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) { 2796 // Ensure we have a process. 2797 if (!m_current_process || 2798 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2799 Log *log = GetLog(LLDBLog::Process); 2800 LLDB_LOG(log, "failed, no process available"); 2801 return SendErrorResponse(0x15); 2802 } 2803 2804 // Parse out software or hardware breakpoint or watchpoint requested. 2805 packet.SetFilePos(strlen("Z")); 2806 if (packet.GetBytesLeft() < 1) 2807 return SendIllFormedResponse( 2808 packet, "Too short Z packet, missing software/hardware specifier"); 2809 2810 bool want_breakpoint = true; 2811 bool want_hardware = false; 2812 uint32_t watch_flags = 0; 2813 2814 const GDBStoppointType stoppoint_type = 2815 GDBStoppointType(packet.GetS32(eStoppointInvalid)); 2816 switch (stoppoint_type) { 2817 case eBreakpointSoftware: 2818 want_hardware = false; 2819 want_breakpoint = true; 2820 break; 2821 case eBreakpointHardware: 2822 want_hardware = true; 2823 want_breakpoint = true; 2824 break; 2825 case eWatchpointWrite: 2826 watch_flags = 1; 2827 want_hardware = true; 2828 want_breakpoint = false; 2829 break; 2830 case eWatchpointRead: 2831 watch_flags = 2; 2832 want_hardware = true; 2833 want_breakpoint = false; 2834 break; 2835 case eWatchpointReadWrite: 2836 watch_flags = 3; 2837 want_hardware = true; 2838 want_breakpoint = false; 2839 break; 2840 case eStoppointInvalid: 2841 return SendIllFormedResponse( 2842 packet, "Z packet had invalid software/hardware specifier"); 2843 } 2844 2845 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',') 2846 return SendIllFormedResponse( 2847 packet, "Malformed Z packet, expecting comma after stoppoint type"); 2848 2849 // Parse out the stoppoint address. 2850 if (packet.GetBytesLeft() < 1) 2851 return SendIllFormedResponse(packet, "Too short Z packet, missing address"); 2852 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0); 2853 2854 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',') 2855 return SendIllFormedResponse( 2856 packet, "Malformed Z packet, expecting comma after address"); 2857 2858 // Parse out the stoppoint size (i.e. size hint for opcode size). 2859 const uint32_t size = 2860 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 2861 if (size == std::numeric_limits<uint32_t>::max()) 2862 return SendIllFormedResponse( 2863 packet, "Malformed Z packet, failed to parse size argument"); 2864 2865 if (want_breakpoint) { 2866 // Try to set the breakpoint. 2867 const Status error = 2868 m_current_process->SetBreakpoint(addr, size, want_hardware); 2869 if (error.Success()) 2870 return SendOKResponse(); 2871 Log *log = GetLog(LLDBLog::Breakpoints); 2872 LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}", 2873 m_current_process->GetID(), error); 2874 return SendErrorResponse(0x09); 2875 } else { 2876 // Try to set the watchpoint. 2877 const Status error = m_current_process->SetWatchpoint( 2878 addr, size, watch_flags, want_hardware); 2879 if (error.Success()) 2880 return SendOKResponse(); 2881 Log *log = GetLog(LLDBLog::Watchpoints); 2882 LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}", 2883 m_current_process->GetID(), error); 2884 return SendErrorResponse(0x09); 2885 } 2886 } 2887 2888 GDBRemoteCommunication::PacketResult 2889 GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) { 2890 // Ensure we have a process. 2891 if (!m_current_process || 2892 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2893 Log *log = GetLog(LLDBLog::Process); 2894 LLDB_LOG(log, "failed, no process available"); 2895 return SendErrorResponse(0x15); 2896 } 2897 2898 // Parse out software or hardware breakpoint or watchpoint requested. 2899 packet.SetFilePos(strlen("z")); 2900 if (packet.GetBytesLeft() < 1) 2901 return SendIllFormedResponse( 2902 packet, "Too short z packet, missing software/hardware specifier"); 2903 2904 bool want_breakpoint = true; 2905 bool want_hardware = false; 2906 2907 const GDBStoppointType stoppoint_type = 2908 GDBStoppointType(packet.GetS32(eStoppointInvalid)); 2909 switch (stoppoint_type) { 2910 case eBreakpointHardware: 2911 want_breakpoint = true; 2912 want_hardware = true; 2913 break; 2914 case eBreakpointSoftware: 2915 want_breakpoint = true; 2916 break; 2917 case eWatchpointWrite: 2918 want_breakpoint = false; 2919 break; 2920 case eWatchpointRead: 2921 want_breakpoint = false; 2922 break; 2923 case eWatchpointReadWrite: 2924 want_breakpoint = false; 2925 break; 2926 default: 2927 return SendIllFormedResponse( 2928 packet, "z packet had invalid software/hardware specifier"); 2929 } 2930 2931 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',') 2932 return SendIllFormedResponse( 2933 packet, "Malformed z packet, expecting comma after stoppoint type"); 2934 2935 // Parse out the stoppoint address. 2936 if (packet.GetBytesLeft() < 1) 2937 return SendIllFormedResponse(packet, "Too short z packet, missing address"); 2938 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0); 2939 2940 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',') 2941 return SendIllFormedResponse( 2942 packet, "Malformed z packet, expecting comma after address"); 2943 2944 /* 2945 // Parse out the stoppoint size (i.e. size hint for opcode size). 2946 const uint32_t size = packet.GetHexMaxU32 (false, 2947 std::numeric_limits<uint32_t>::max ()); 2948 if (size == std::numeric_limits<uint32_t>::max ()) 2949 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse 2950 size argument"); 2951 */ 2952 2953 if (want_breakpoint) { 2954 // Try to clear the breakpoint. 2955 const Status error = 2956 m_current_process->RemoveBreakpoint(addr, want_hardware); 2957 if (error.Success()) 2958 return SendOKResponse(); 2959 Log *log = GetLog(LLDBLog::Breakpoints); 2960 LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}", 2961 m_current_process->GetID(), error); 2962 return SendErrorResponse(0x09); 2963 } else { 2964 // Try to clear the watchpoint. 2965 const Status error = m_current_process->RemoveWatchpoint(addr); 2966 if (error.Success()) 2967 return SendOKResponse(); 2968 Log *log = GetLog(LLDBLog::Watchpoints); 2969 LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}", 2970 m_current_process->GetID(), error); 2971 return SendErrorResponse(0x09); 2972 } 2973 } 2974 2975 GDBRemoteCommunication::PacketResult 2976 GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) { 2977 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread); 2978 2979 // Ensure we have a process. 2980 if (!m_continue_process || 2981 (m_continue_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2982 LLDB_LOGF( 2983 log, 2984 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2985 __FUNCTION__); 2986 return SendErrorResponse(0x32); 2987 } 2988 2989 // We first try to use a continue thread id. If any one or any all set, use 2990 // the current thread. Bail out if we don't have a thread id. 2991 lldb::tid_t tid = GetContinueThreadID(); 2992 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID) 2993 tid = GetCurrentThreadID(); 2994 if (tid == LLDB_INVALID_THREAD_ID) 2995 return SendErrorResponse(0x33); 2996 2997 // Double check that we have such a thread. 2998 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here. 2999 NativeThreadProtocol *thread = m_continue_process->GetThreadByID(tid); 3000 if (!thread) 3001 return SendErrorResponse(0x33); 3002 3003 // Create the step action for the given thread. 3004 ResumeAction action = {tid, eStateStepping, LLDB_INVALID_SIGNAL_NUMBER}; 3005 3006 // Setup the actions list. 3007 ResumeActionList actions; 3008 actions.Append(action); 3009 3010 // All other threads stop while we're single stepping a thread. 3011 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0); 3012 3013 PacketResult resume_res = ResumeProcess(*m_continue_process, actions); 3014 if (resume_res != PacketResult::Success) 3015 return resume_res; 3016 3017 // No response here, unless in non-stop mode. 3018 // Otherwise, the stop or exit will come from the resulting action. 3019 return SendContinueSuccessResponse(); 3020 } 3021 3022 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> 3023 GDBRemoteCommunicationServerLLGS::BuildTargetXml() { 3024 // Ensure we have a thread. 3025 NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0); 3026 if (!thread) 3027 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3028 "No thread available"); 3029 3030 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread); 3031 // Get the register context for the first thread. 3032 NativeRegisterContext ®_context = thread->GetRegisterContext(); 3033 3034 StreamString response; 3035 3036 response.Printf("<?xml version=\"1.0\"?>"); 3037 response.Printf("<target version=\"1.0\">"); 3038 3039 response.Printf("<architecture>%s</architecture>", 3040 m_current_process->GetArchitecture() 3041 .GetTriple() 3042 .getArchName() 3043 .str() 3044 .c_str()); 3045 3046 response.Printf("<feature>"); 3047 3048 const int registers_count = reg_context.GetUserRegisterCount(); 3049 for (int reg_index = 0; reg_index < registers_count; reg_index++) { 3050 const RegisterInfo *reg_info = 3051 reg_context.GetRegisterInfoAtIndex(reg_index); 3052 3053 if (!reg_info) { 3054 LLDB_LOGF(log, 3055 "%s failed to get register info for register index %" PRIu32, 3056 "target.xml", reg_index); 3057 continue; 3058 } 3059 3060 response.Printf("<reg name=\"%s\" bitsize=\"%" PRIu32 "\" regnum=\"%d\" ", 3061 reg_info->name, reg_info->byte_size * 8, reg_index); 3062 3063 if (!reg_context.RegisterOffsetIsDynamic()) 3064 response.Printf("offset=\"%" PRIu32 "\" ", reg_info->byte_offset); 3065 3066 if (reg_info->alt_name && reg_info->alt_name[0]) 3067 response.Printf("altname=\"%s\" ", reg_info->alt_name); 3068 3069 llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info); 3070 if (!encoding.empty()) 3071 response << "encoding=\"" << encoding << "\" "; 3072 3073 llvm::StringRef format = GetFormatNameOrEmpty(*reg_info); 3074 if (!format.empty()) 3075 response << "format=\"" << format << "\" "; 3076 3077 const char *const register_set_name = 3078 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index); 3079 if (register_set_name) 3080 response << "group=\"" << register_set_name << "\" "; 3081 3082 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] != 3083 LLDB_INVALID_REGNUM) 3084 response.Printf("ehframe_regnum=\"%" PRIu32 "\" ", 3085 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]); 3086 3087 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != 3088 LLDB_INVALID_REGNUM) 3089 response.Printf("dwarf_regnum=\"%" PRIu32 "\" ", 3090 reg_info->kinds[RegisterKind::eRegisterKindDWARF]); 3091 3092 llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info); 3093 if (!kind_generic.empty()) 3094 response << "generic=\"" << kind_generic << "\" "; 3095 3096 if (reg_info->value_regs && 3097 reg_info->value_regs[0] != LLDB_INVALID_REGNUM) { 3098 response.PutCString("value_regnums=\""); 3099 CollectRegNums(reg_info->value_regs, response, false); 3100 response.Printf("\" "); 3101 } 3102 3103 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) { 3104 response.PutCString("invalidate_regnums=\""); 3105 CollectRegNums(reg_info->invalidate_regs, response, false); 3106 response.Printf("\" "); 3107 } 3108 3109 response.Printf("/>"); 3110 } 3111 3112 response.Printf("</feature>"); 3113 response.Printf("</target>"); 3114 return MemoryBuffer::getMemBufferCopy(response.GetString(), "target.xml"); 3115 } 3116 3117 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> 3118 GDBRemoteCommunicationServerLLGS::ReadXferObject(llvm::StringRef object, 3119 llvm::StringRef annex) { 3120 // Make sure we have a valid process. 3121 if (!m_current_process || 3122 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 3123 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3124 "No process available"); 3125 } 3126 3127 if (object == "auxv") { 3128 // Grab the auxv data. 3129 auto buffer_or_error = m_current_process->GetAuxvData(); 3130 if (!buffer_or_error) 3131 return llvm::errorCodeToError(buffer_or_error.getError()); 3132 return std::move(*buffer_or_error); 3133 } 3134 3135 if (object == "siginfo") { 3136 NativeThreadProtocol *thread = m_current_process->GetCurrentThread(); 3137 if (!thread) 3138 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3139 "no current thread"); 3140 3141 auto buffer_or_error = thread->GetSiginfo(); 3142 if (!buffer_or_error) 3143 return buffer_or_error.takeError(); 3144 return std::move(*buffer_or_error); 3145 } 3146 3147 if (object == "libraries-svr4") { 3148 auto library_list = m_current_process->GetLoadedSVR4Libraries(); 3149 if (!library_list) 3150 return library_list.takeError(); 3151 3152 StreamString response; 3153 response.Printf("<library-list-svr4 version=\"1.0\">"); 3154 for (auto const &library : *library_list) { 3155 response.Printf("<library name=\"%s\" ", 3156 XMLEncodeAttributeValue(library.name.c_str()).c_str()); 3157 response.Printf("lm=\"0x%" PRIx64 "\" ", library.link_map); 3158 response.Printf("l_addr=\"0x%" PRIx64 "\" ", library.base_addr); 3159 response.Printf("l_ld=\"0x%" PRIx64 "\" />", library.ld_addr); 3160 } 3161 response.Printf("</library-list-svr4>"); 3162 return MemoryBuffer::getMemBufferCopy(response.GetString(), __FUNCTION__); 3163 } 3164 3165 if (object == "features" && annex == "target.xml") 3166 return BuildTargetXml(); 3167 3168 return llvm::make_error<UnimplementedError>(); 3169 } 3170 3171 GDBRemoteCommunication::PacketResult 3172 GDBRemoteCommunicationServerLLGS::Handle_qXfer( 3173 StringExtractorGDBRemote &packet) { 3174 SmallVector<StringRef, 5> fields; 3175 // The packet format is "qXfer:<object>:<action>:<annex>:offset,length" 3176 StringRef(packet.GetStringRef()).split(fields, ':', 4); 3177 if (fields.size() != 5) 3178 return SendIllFormedResponse(packet, "malformed qXfer packet"); 3179 StringRef &xfer_object = fields[1]; 3180 StringRef &xfer_action = fields[2]; 3181 StringRef &xfer_annex = fields[3]; 3182 StringExtractor offset_data(fields[4]); 3183 if (xfer_action != "read") 3184 return SendUnimplementedResponse("qXfer action not supported"); 3185 // Parse offset. 3186 const uint64_t xfer_offset = 3187 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max()); 3188 if (xfer_offset == std::numeric_limits<uint64_t>::max()) 3189 return SendIllFormedResponse(packet, "qXfer packet missing offset"); 3190 // Parse out comma. 3191 if (offset_data.GetChar() != ',') 3192 return SendIllFormedResponse(packet, 3193 "qXfer packet missing comma after offset"); 3194 // Parse out the length. 3195 const uint64_t xfer_length = 3196 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max()); 3197 if (xfer_length == std::numeric_limits<uint64_t>::max()) 3198 return SendIllFormedResponse(packet, "qXfer packet missing length"); 3199 3200 // Get a previously constructed buffer if it exists or create it now. 3201 std::string buffer_key = (xfer_object + xfer_action + xfer_annex).str(); 3202 auto buffer_it = m_xfer_buffer_map.find(buffer_key); 3203 if (buffer_it == m_xfer_buffer_map.end()) { 3204 auto buffer_up = ReadXferObject(xfer_object, xfer_annex); 3205 if (!buffer_up) 3206 return SendErrorResponse(buffer_up.takeError()); 3207 buffer_it = m_xfer_buffer_map 3208 .insert(std::make_pair(buffer_key, std::move(*buffer_up))) 3209 .first; 3210 } 3211 3212 // Send back the response 3213 StreamGDBRemote response; 3214 bool done_with_buffer = false; 3215 llvm::StringRef buffer = buffer_it->second->getBuffer(); 3216 if (xfer_offset >= buffer.size()) { 3217 // We have nothing left to send. Mark the buffer as complete. 3218 response.PutChar('l'); 3219 done_with_buffer = true; 3220 } else { 3221 // Figure out how many bytes are available starting at the given offset. 3222 buffer = buffer.drop_front(xfer_offset); 3223 // Mark the response type according to whether we're reading the remainder 3224 // of the data. 3225 if (xfer_length >= buffer.size()) { 3226 // There will be nothing left to read after this 3227 response.PutChar('l'); 3228 done_with_buffer = true; 3229 } else { 3230 // There will still be bytes to read after this request. 3231 response.PutChar('m'); 3232 buffer = buffer.take_front(xfer_length); 3233 } 3234 // Now write the data in encoded binary form. 3235 response.PutEscapedBytes(buffer.data(), buffer.size()); 3236 } 3237 3238 if (done_with_buffer) 3239 m_xfer_buffer_map.erase(buffer_it); 3240 3241 return SendPacketNoLock(response.GetString()); 3242 } 3243 3244 GDBRemoteCommunication::PacketResult 3245 GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState( 3246 StringExtractorGDBRemote &packet) { 3247 Log *log = GetLog(LLDBLog::Thread); 3248 3249 // Move past packet name. 3250 packet.SetFilePos(strlen("QSaveRegisterState")); 3251 3252 // Get the thread to use. 3253 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 3254 if (!thread) { 3255 if (m_thread_suffix_supported) 3256 return SendIllFormedResponse( 3257 packet, "No thread specified in QSaveRegisterState packet"); 3258 else 3259 return SendIllFormedResponse(packet, 3260 "No thread was is set with the Hg packet"); 3261 } 3262 3263 // Grab the register context for the thread. 3264 NativeRegisterContext& reg_context = thread->GetRegisterContext(); 3265 3266 // Save registers to a buffer. 3267 WritableDataBufferSP register_data_sp; 3268 Status error = reg_context.ReadAllRegisterValues(register_data_sp); 3269 if (error.Fail()) { 3270 LLDB_LOG(log, "pid {0} failed to save all register values: {1}", 3271 m_current_process->GetID(), error); 3272 return SendErrorResponse(0x75); 3273 } 3274 3275 // Allocate a new save id. 3276 const uint32_t save_id = GetNextSavedRegistersID(); 3277 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) && 3278 "GetNextRegisterSaveID() returned an existing register save id"); 3279 3280 // Save the register data buffer under the save id. 3281 { 3282 std::lock_guard<std::mutex> guard(m_saved_registers_mutex); 3283 m_saved_registers_map[save_id] = register_data_sp; 3284 } 3285 3286 // Write the response. 3287 StreamGDBRemote response; 3288 response.Printf("%" PRIu32, save_id); 3289 return SendPacketNoLock(response.GetString()); 3290 } 3291 3292 GDBRemoteCommunication::PacketResult 3293 GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState( 3294 StringExtractorGDBRemote &packet) { 3295 Log *log = GetLog(LLDBLog::Thread); 3296 3297 // Parse out save id. 3298 packet.SetFilePos(strlen("QRestoreRegisterState:")); 3299 if (packet.GetBytesLeft() < 1) 3300 return SendIllFormedResponse( 3301 packet, "QRestoreRegisterState packet missing register save id"); 3302 3303 const uint32_t save_id = packet.GetU32(0); 3304 if (save_id == 0) { 3305 LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, " 3306 "expecting decimal uint32_t"); 3307 return SendErrorResponse(0x76); 3308 } 3309 3310 // Get the thread to use. 3311 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 3312 if (!thread) { 3313 if (m_thread_suffix_supported) 3314 return SendIllFormedResponse( 3315 packet, "No thread specified in QRestoreRegisterState packet"); 3316 else 3317 return SendIllFormedResponse(packet, 3318 "No thread was is set with the Hg packet"); 3319 } 3320 3321 // Grab the register context for the thread. 3322 NativeRegisterContext ®_context = thread->GetRegisterContext(); 3323 3324 // Retrieve register state buffer, then remove from the list. 3325 DataBufferSP register_data_sp; 3326 { 3327 std::lock_guard<std::mutex> guard(m_saved_registers_mutex); 3328 3329 // Find the register set buffer for the given save id. 3330 auto it = m_saved_registers_map.find(save_id); 3331 if (it == m_saved_registers_map.end()) { 3332 LLDB_LOG(log, 3333 "pid {0} does not have a register set save buffer for id {1}", 3334 m_current_process->GetID(), save_id); 3335 return SendErrorResponse(0x77); 3336 } 3337 register_data_sp = it->second; 3338 3339 // Remove it from the map. 3340 m_saved_registers_map.erase(it); 3341 } 3342 3343 Status error = reg_context.WriteAllRegisterValues(register_data_sp); 3344 if (error.Fail()) { 3345 LLDB_LOG(log, "pid {0} failed to restore all register values: {1}", 3346 m_current_process->GetID(), error); 3347 return SendErrorResponse(0x77); 3348 } 3349 3350 return SendOKResponse(); 3351 } 3352 3353 GDBRemoteCommunication::PacketResult 3354 GDBRemoteCommunicationServerLLGS::Handle_vAttach( 3355 StringExtractorGDBRemote &packet) { 3356 Log *log = GetLog(LLDBLog::Process); 3357 3358 // Consume the ';' after vAttach. 3359 packet.SetFilePos(strlen("vAttach")); 3360 if (!packet.GetBytesLeft() || packet.GetChar() != ';') 3361 return SendIllFormedResponse(packet, "vAttach missing expected ';'"); 3362 3363 // Grab the PID to which we will attach (assume hex encoding). 3364 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16); 3365 if (pid == LLDB_INVALID_PROCESS_ID) 3366 return SendIllFormedResponse(packet, 3367 "vAttach failed to parse the process id"); 3368 3369 // Attempt to attach. 3370 LLDB_LOGF(log, 3371 "GDBRemoteCommunicationServerLLGS::%s attempting to attach to " 3372 "pid %" PRIu64, 3373 __FUNCTION__, pid); 3374 3375 Status error = AttachToProcess(pid); 3376 3377 if (error.Fail()) { 3378 LLDB_LOGF(log, 3379 "GDBRemoteCommunicationServerLLGS::%s failed to attach to " 3380 "pid %" PRIu64 ": %s\n", 3381 __FUNCTION__, pid, error.AsCString()); 3382 return SendErrorResponse(error); 3383 } 3384 3385 // Notify we attached by sending a stop packet. 3386 assert(m_current_process); 3387 return SendStopReasonForState(*m_current_process, 3388 m_current_process->GetState(), 3389 /*force_synchronous=*/false); 3390 } 3391 3392 GDBRemoteCommunication::PacketResult 3393 GDBRemoteCommunicationServerLLGS::Handle_vAttachWait( 3394 StringExtractorGDBRemote &packet) { 3395 Log *log = GetLog(LLDBLog::Process); 3396 3397 // Consume the ';' after the identifier. 3398 packet.SetFilePos(strlen("vAttachWait")); 3399 3400 if (!packet.GetBytesLeft() || packet.GetChar() != ';') 3401 return SendIllFormedResponse(packet, "vAttachWait missing expected ';'"); 3402 3403 // Allocate the buffer for the process name from vAttachWait. 3404 std::string process_name; 3405 if (!packet.GetHexByteString(process_name)) 3406 return SendIllFormedResponse(packet, 3407 "vAttachWait failed to parse process name"); 3408 3409 LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name); 3410 3411 Status error = AttachWaitProcess(process_name, false); 3412 if (error.Fail()) { 3413 LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name, 3414 error); 3415 return SendErrorResponse(error); 3416 } 3417 3418 // Notify we attached by sending a stop packet. 3419 assert(m_current_process); 3420 return SendStopReasonForState(*m_current_process, 3421 m_current_process->GetState(), 3422 /*force_synchronous=*/false); 3423 } 3424 3425 GDBRemoteCommunication::PacketResult 3426 GDBRemoteCommunicationServerLLGS::Handle_qVAttachOrWaitSupported( 3427 StringExtractorGDBRemote &packet) { 3428 return SendOKResponse(); 3429 } 3430 3431 GDBRemoteCommunication::PacketResult 3432 GDBRemoteCommunicationServerLLGS::Handle_vAttachOrWait( 3433 StringExtractorGDBRemote &packet) { 3434 Log *log = GetLog(LLDBLog::Process); 3435 3436 // Consume the ';' after the identifier. 3437 packet.SetFilePos(strlen("vAttachOrWait")); 3438 3439 if (!packet.GetBytesLeft() || packet.GetChar() != ';') 3440 return SendIllFormedResponse(packet, "vAttachOrWait missing expected ';'"); 3441 3442 // Allocate the buffer for the process name from vAttachWait. 3443 std::string process_name; 3444 if (!packet.GetHexByteString(process_name)) 3445 return SendIllFormedResponse(packet, 3446 "vAttachOrWait failed to parse process name"); 3447 3448 LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name); 3449 3450 Status error = AttachWaitProcess(process_name, true); 3451 if (error.Fail()) { 3452 LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name, 3453 error); 3454 return SendErrorResponse(error); 3455 } 3456 3457 // Notify we attached by sending a stop packet. 3458 assert(m_current_process); 3459 return SendStopReasonForState(*m_current_process, 3460 m_current_process->GetState(), 3461 /*force_synchronous=*/false); 3462 } 3463 3464 GDBRemoteCommunication::PacketResult 3465 GDBRemoteCommunicationServerLLGS::Handle_vRun( 3466 StringExtractorGDBRemote &packet) { 3467 Log *log = GetLog(LLDBLog::Process); 3468 3469 llvm::StringRef s = packet.GetStringRef(); 3470 if (!s.consume_front("vRun;")) 3471 return SendErrorResponse(8); 3472 3473 llvm::SmallVector<llvm::StringRef, 16> argv; 3474 s.split(argv, ';'); 3475 3476 for (llvm::StringRef hex_arg : argv) { 3477 StringExtractor arg_ext{hex_arg}; 3478 std::string arg; 3479 arg_ext.GetHexByteString(arg); 3480 m_process_launch_info.GetArguments().AppendArgument(arg); 3481 LLDB_LOGF(log, "LLGSPacketHandler::%s added arg: \"%s\"", __FUNCTION__, 3482 arg.c_str()); 3483 } 3484 3485 if (!argv.empty()) { 3486 m_process_launch_info.GetExecutableFile().SetFile( 3487 m_process_launch_info.GetArguments()[0].ref(), FileSpec::Style::native); 3488 m_process_launch_error = LaunchProcess(); 3489 if (m_process_launch_error.Success()) { 3490 assert(m_current_process); 3491 return SendStopReasonForState(*m_current_process, 3492 m_current_process->GetState(), 3493 /*force_synchronous=*/true); 3494 } 3495 LLDB_LOG(log, "failed to launch exe: {0}", m_process_launch_error); 3496 } 3497 return SendErrorResponse(8); 3498 } 3499 3500 GDBRemoteCommunication::PacketResult 3501 GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) { 3502 Log *log = GetLog(LLDBLog::Process); 3503 StopSTDIOForwarding(); 3504 3505 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; 3506 3507 // Consume the ';' after D. 3508 packet.SetFilePos(1); 3509 if (packet.GetBytesLeft()) { 3510 if (packet.GetChar() != ';') 3511 return SendIllFormedResponse(packet, "D missing expected ';'"); 3512 3513 // Grab the PID from which we will detach (assume hex encoding). 3514 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16); 3515 if (pid == LLDB_INVALID_PROCESS_ID) 3516 return SendIllFormedResponse(packet, "D failed to parse the process id"); 3517 } 3518 3519 // Detach forked children if their PID was specified *or* no PID was requested 3520 // (i.e. detach-all packet). 3521 llvm::Error detach_error = llvm::Error::success(); 3522 bool detached = false; 3523 for (auto it = m_debugged_processes.begin(); 3524 it != m_debugged_processes.end();) { 3525 if (pid == LLDB_INVALID_PROCESS_ID || pid == it->first) { 3526 LLDB_LOGF(log, 3527 "GDBRemoteCommunicationServerLLGS::%s detaching %" PRId64, 3528 __FUNCTION__, it->first); 3529 if (llvm::Error e = it->second.process_up->Detach().ToError()) 3530 detach_error = llvm::joinErrors(std::move(detach_error), std::move(e)); 3531 else { 3532 if (it->second.process_up.get() == m_current_process) 3533 m_current_process = nullptr; 3534 if (it->second.process_up.get() == m_continue_process) 3535 m_continue_process = nullptr; 3536 it = m_debugged_processes.erase(it); 3537 detached = true; 3538 continue; 3539 } 3540 } 3541 ++it; 3542 } 3543 3544 if (detach_error) 3545 return SendErrorResponse(std::move(detach_error)); 3546 if (!detached) 3547 return SendErrorResponse(Status("PID %" PRIu64 " not traced", pid)); 3548 return SendOKResponse(); 3549 } 3550 3551 GDBRemoteCommunication::PacketResult 3552 GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo( 3553 StringExtractorGDBRemote &packet) { 3554 Log *log = GetLog(LLDBLog::Thread); 3555 3556 if (!m_current_process || 3557 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 3558 return SendErrorResponse(50); 3559 3560 packet.SetFilePos(strlen("qThreadStopInfo")); 3561 const lldb::tid_t tid = packet.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID); 3562 if (tid == LLDB_INVALID_THREAD_ID) { 3563 LLDB_LOGF(log, 3564 "GDBRemoteCommunicationServerLLGS::%s failed, could not " 3565 "parse thread id from request \"%s\"", 3566 __FUNCTION__, packet.GetStringRef().data()); 3567 return SendErrorResponse(0x15); 3568 } 3569 return SendStopReplyPacketForThread(*m_current_process, tid, 3570 /*force_synchronous=*/true); 3571 } 3572 3573 GDBRemoteCommunication::PacketResult 3574 GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo( 3575 StringExtractorGDBRemote &) { 3576 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread); 3577 3578 // Ensure we have a debugged process. 3579 if (!m_current_process || 3580 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 3581 return SendErrorResponse(50); 3582 LLDB_LOG(log, "preparing packet for pid {0}", m_current_process->GetID()); 3583 3584 StreamString response; 3585 const bool threads_with_valid_stop_info_only = false; 3586 llvm::Expected<json::Value> threads_info = 3587 GetJSONThreadsInfo(*m_current_process, threads_with_valid_stop_info_only); 3588 if (!threads_info) { 3589 LLDB_LOG_ERROR(log, threads_info.takeError(), 3590 "failed to prepare a packet for pid {1}: {0}", 3591 m_current_process->GetID()); 3592 return SendErrorResponse(52); 3593 } 3594 3595 response.AsRawOstream() << *threads_info; 3596 StreamGDBRemote escaped_response; 3597 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize()); 3598 return SendPacketNoLock(escaped_response.GetString()); 3599 } 3600 3601 GDBRemoteCommunication::PacketResult 3602 GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo( 3603 StringExtractorGDBRemote &packet) { 3604 // Fail if we don't have a current process. 3605 if (!m_current_process || 3606 m_current_process->GetID() == LLDB_INVALID_PROCESS_ID) 3607 return SendErrorResponse(68); 3608 3609 packet.SetFilePos(strlen("qWatchpointSupportInfo")); 3610 if (packet.GetBytesLeft() == 0) 3611 return SendOKResponse(); 3612 if (packet.GetChar() != ':') 3613 return SendErrorResponse(67); 3614 3615 auto hw_debug_cap = m_current_process->GetHardwareDebugSupportInfo(); 3616 3617 StreamGDBRemote response; 3618 if (hw_debug_cap == llvm::None) 3619 response.Printf("num:0;"); 3620 else 3621 response.Printf("num:%d;", hw_debug_cap->second); 3622 3623 return SendPacketNoLock(response.GetString()); 3624 } 3625 3626 GDBRemoteCommunication::PacketResult 3627 GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress( 3628 StringExtractorGDBRemote &packet) { 3629 // Fail if we don't have a current process. 3630 if (!m_current_process || 3631 m_current_process->GetID() == LLDB_INVALID_PROCESS_ID) 3632 return SendErrorResponse(67); 3633 3634 packet.SetFilePos(strlen("qFileLoadAddress:")); 3635 if (packet.GetBytesLeft() == 0) 3636 return SendErrorResponse(68); 3637 3638 std::string file_name; 3639 packet.GetHexByteString(file_name); 3640 3641 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS; 3642 Status error = 3643 m_current_process->GetFileLoadAddress(file_name, file_load_address); 3644 if (error.Fail()) 3645 return SendErrorResponse(69); 3646 3647 if (file_load_address == LLDB_INVALID_ADDRESS) 3648 return SendErrorResponse(1); // File not loaded 3649 3650 StreamGDBRemote response; 3651 response.PutHex64(file_load_address); 3652 return SendPacketNoLock(response.GetString()); 3653 } 3654 3655 GDBRemoteCommunication::PacketResult 3656 GDBRemoteCommunicationServerLLGS::Handle_QPassSignals( 3657 StringExtractorGDBRemote &packet) { 3658 std::vector<int> signals; 3659 packet.SetFilePos(strlen("QPassSignals:")); 3660 3661 // Read sequence of hex signal numbers divided by a semicolon and optionally 3662 // spaces. 3663 while (packet.GetBytesLeft() > 0) { 3664 int signal = packet.GetS32(-1, 16); 3665 if (signal < 0) 3666 return SendIllFormedResponse(packet, "Failed to parse signal number."); 3667 signals.push_back(signal); 3668 3669 packet.SkipSpaces(); 3670 char separator = packet.GetChar(); 3671 if (separator == '\0') 3672 break; // End of string 3673 if (separator != ';') 3674 return SendIllFormedResponse(packet, "Invalid separator," 3675 " expected semicolon."); 3676 } 3677 3678 // Fail if we don't have a current process. 3679 if (!m_current_process) 3680 return SendErrorResponse(68); 3681 3682 Status error = m_current_process->IgnoreSignals(signals); 3683 if (error.Fail()) 3684 return SendErrorResponse(69); 3685 3686 return SendOKResponse(); 3687 } 3688 3689 GDBRemoteCommunication::PacketResult 3690 GDBRemoteCommunicationServerLLGS::Handle_qMemTags( 3691 StringExtractorGDBRemote &packet) { 3692 Log *log = GetLog(LLDBLog::Process); 3693 3694 // Ensure we have a process. 3695 if (!m_current_process || 3696 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 3697 LLDB_LOGF( 3698 log, 3699 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 3700 __FUNCTION__); 3701 return SendErrorResponse(1); 3702 } 3703 3704 // We are expecting 3705 // qMemTags:<hex address>,<hex length>:<hex type> 3706 3707 // Address 3708 packet.SetFilePos(strlen("qMemTags:")); 3709 const char *current_char = packet.Peek(); 3710 if (!current_char || *current_char == ',') 3711 return SendIllFormedResponse(packet, "Missing address in qMemTags packet"); 3712 const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0); 3713 3714 // Length 3715 char previous_char = packet.GetChar(); 3716 current_char = packet.Peek(); 3717 // If we don't have a separator or the length field is empty 3718 if (previous_char != ',' || (current_char && *current_char == ':')) 3719 return SendIllFormedResponse(packet, 3720 "Invalid addr,length pair in qMemTags packet"); 3721 3722 if (packet.GetBytesLeft() < 1) 3723 return SendIllFormedResponse( 3724 packet, "Too short qMemtags: packet (looking for length)"); 3725 const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0); 3726 3727 // Type 3728 const char *invalid_type_err = "Invalid type field in qMemTags: packet"; 3729 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':') 3730 return SendIllFormedResponse(packet, invalid_type_err); 3731 3732 // Type is a signed integer but packed into the packet as its raw bytes. 3733 // However, our GetU64 uses strtoull which allows +/-. We do not want this. 3734 const char *first_type_char = packet.Peek(); 3735 if (first_type_char && (*first_type_char == '+' || *first_type_char == '-')) 3736 return SendIllFormedResponse(packet, invalid_type_err); 3737 3738 // Extract type as unsigned then cast to signed. 3739 // Using a uint64_t here so that we have some value outside of the 32 bit 3740 // range to use as the invalid return value. 3741 uint64_t raw_type = 3742 packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16); 3743 3744 if ( // Make sure the cast below would be valid 3745 raw_type > std::numeric_limits<uint32_t>::max() || 3746 // To catch inputs like "123aardvark" that will parse but clearly aren't 3747 // valid in this case. 3748 packet.GetBytesLeft()) { 3749 return SendIllFormedResponse(packet, invalid_type_err); 3750 } 3751 3752 // First narrow to 32 bits otherwise the copy into type would take 3753 // the wrong 4 bytes on big endian. 3754 uint32_t raw_type_32 = raw_type; 3755 int32_t type = reinterpret_cast<int32_t &>(raw_type_32); 3756 3757 StreamGDBRemote response; 3758 std::vector<uint8_t> tags; 3759 Status error = m_current_process->ReadMemoryTags(type, addr, length, tags); 3760 if (error.Fail()) 3761 return SendErrorResponse(1); 3762 3763 // This m is here in case we want to support multi part replies in the future. 3764 // In the same manner as qfThreadInfo/qsThreadInfo. 3765 response.PutChar('m'); 3766 response.PutBytesAsRawHex8(tags.data(), tags.size()); 3767 return SendPacketNoLock(response.GetString()); 3768 } 3769 3770 GDBRemoteCommunication::PacketResult 3771 GDBRemoteCommunicationServerLLGS::Handle_QMemTags( 3772 StringExtractorGDBRemote &packet) { 3773 Log *log = GetLog(LLDBLog::Process); 3774 3775 // Ensure we have a process. 3776 if (!m_current_process || 3777 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 3778 LLDB_LOGF( 3779 log, 3780 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 3781 __FUNCTION__); 3782 return SendErrorResponse(1); 3783 } 3784 3785 // We are expecting 3786 // QMemTags:<hex address>,<hex length>:<hex type>:<tags as hex bytes> 3787 3788 // Address 3789 packet.SetFilePos(strlen("QMemTags:")); 3790 const char *current_char = packet.Peek(); 3791 if (!current_char || *current_char == ',') 3792 return SendIllFormedResponse(packet, "Missing address in QMemTags packet"); 3793 const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0); 3794 3795 // Length 3796 char previous_char = packet.GetChar(); 3797 current_char = packet.Peek(); 3798 // If we don't have a separator or the length field is empty 3799 if (previous_char != ',' || (current_char && *current_char == ':')) 3800 return SendIllFormedResponse(packet, 3801 "Invalid addr,length pair in QMemTags packet"); 3802 3803 if (packet.GetBytesLeft() < 1) 3804 return SendIllFormedResponse( 3805 packet, "Too short QMemtags: packet (looking for length)"); 3806 const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0); 3807 3808 // Type 3809 const char *invalid_type_err = "Invalid type field in QMemTags: packet"; 3810 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':') 3811 return SendIllFormedResponse(packet, invalid_type_err); 3812 3813 // Our GetU64 uses strtoull which allows leading +/-, we don't want that. 3814 const char *first_type_char = packet.Peek(); 3815 if (first_type_char && (*first_type_char == '+' || *first_type_char == '-')) 3816 return SendIllFormedResponse(packet, invalid_type_err); 3817 3818 // The type is a signed integer but is in the packet as its raw bytes. 3819 // So parse first as unsigned then cast to signed later. 3820 // We extract to 64 bit, even though we only expect 32, so that we've 3821 // got some invalid value we can check for. 3822 uint64_t raw_type = 3823 packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16); 3824 if (raw_type > std::numeric_limits<uint32_t>::max()) 3825 return SendIllFormedResponse(packet, invalid_type_err); 3826 3827 // First narrow to 32 bits. Otherwise the copy below would get the wrong 3828 // 4 bytes on big endian. 3829 uint32_t raw_type_32 = raw_type; 3830 int32_t type = reinterpret_cast<int32_t &>(raw_type_32); 3831 3832 // Tag data 3833 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':') 3834 return SendIllFormedResponse(packet, 3835 "Missing tag data in QMemTags: packet"); 3836 3837 // Must be 2 chars per byte 3838 const char *invalid_data_err = "Invalid tag data in QMemTags: packet"; 3839 if (packet.GetBytesLeft() % 2) 3840 return SendIllFormedResponse(packet, invalid_data_err); 3841 3842 // This is bytes here and is unpacked into target specific tags later 3843 // We cannot assume that number of bytes == length here because the server 3844 // can repeat tags to fill a given range. 3845 std::vector<uint8_t> tag_data; 3846 // Zero length writes will not have any tag data 3847 // (but we pass them on because it will still check that tagging is enabled) 3848 if (packet.GetBytesLeft()) { 3849 size_t byte_count = packet.GetBytesLeft() / 2; 3850 tag_data.resize(byte_count); 3851 size_t converted_bytes = packet.GetHexBytes(tag_data, 0); 3852 if (converted_bytes != byte_count) { 3853 return SendIllFormedResponse(packet, invalid_data_err); 3854 } 3855 } 3856 3857 Status status = 3858 m_current_process->WriteMemoryTags(type, addr, length, tag_data); 3859 return status.Success() ? SendOKResponse() : SendErrorResponse(1); 3860 } 3861 3862 GDBRemoteCommunication::PacketResult 3863 GDBRemoteCommunicationServerLLGS::Handle_qSaveCore( 3864 StringExtractorGDBRemote &packet) { 3865 // Fail if we don't have a current process. 3866 if (!m_current_process || 3867 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 3868 return SendErrorResponse(Status("Process not running.")); 3869 3870 std::string path_hint; 3871 3872 StringRef packet_str{packet.GetStringRef()}; 3873 assert(packet_str.startswith("qSaveCore")); 3874 if (packet_str.consume_front("qSaveCore;")) { 3875 for (auto x : llvm::split(packet_str, ';')) { 3876 if (x.consume_front("path-hint:")) 3877 StringExtractor(x).GetHexByteString(path_hint); 3878 else 3879 return SendErrorResponse(Status("Unsupported qSaveCore option")); 3880 } 3881 } 3882 3883 llvm::Expected<std::string> ret = m_current_process->SaveCore(path_hint); 3884 if (!ret) 3885 return SendErrorResponse(ret.takeError()); 3886 3887 StreamString response; 3888 response.PutCString("core-path:"); 3889 response.PutStringAsRawHex8(ret.get()); 3890 return SendPacketNoLock(response.GetString()); 3891 } 3892 3893 GDBRemoteCommunication::PacketResult 3894 GDBRemoteCommunicationServerLLGS::Handle_QNonStop( 3895 StringExtractorGDBRemote &packet) { 3896 StringRef packet_str{packet.GetStringRef()}; 3897 assert(packet_str.startswith("QNonStop:")); 3898 packet_str.consume_front("QNonStop:"); 3899 if (packet_str == "0") { 3900 m_non_stop = false; 3901 // TODO: stop all threads 3902 } else if (packet_str == "1") { 3903 m_non_stop = true; 3904 } else 3905 return SendErrorResponse(Status("Invalid QNonStop packet")); 3906 return SendOKResponse(); 3907 } 3908 3909 GDBRemoteCommunication::PacketResult 3910 GDBRemoteCommunicationServerLLGS::Handle_vStopped( 3911 StringExtractorGDBRemote &packet) { 3912 // Per the protocol, the first message put into the queue is sent 3913 // immediately. However, it remains the queue until the client ACKs 3914 // it via vStopped -- then we pop it and send the next message. 3915 // The process repeats until the last message in the queue is ACK-ed, 3916 // in which case the vStopped packet sends an OK response. 3917 3918 if (m_stop_notification_queue.empty()) 3919 return SendErrorResponse(Status("No pending notification to ack")); 3920 m_stop_notification_queue.pop_front(); 3921 if (!m_stop_notification_queue.empty()) 3922 return SendPacketNoLock(m_stop_notification_queue.front()); 3923 // If this was the last notification and all the processes exited, 3924 // terminate the server. 3925 if (m_debugged_processes.empty()) { 3926 m_exit_now = true; 3927 m_mainloop.RequestTermination(); 3928 } 3929 return SendOKResponse(); 3930 } 3931 3932 GDBRemoteCommunication::PacketResult 3933 GDBRemoteCommunicationServerLLGS::Handle_vCtrlC( 3934 StringExtractorGDBRemote &packet) { 3935 if (!m_non_stop) 3936 return SendErrorResponse(Status("vCtrl is only valid in non-stop mode")); 3937 3938 PacketResult interrupt_res = Handle_interrupt(packet); 3939 // If interrupting the process failed, pass the result through. 3940 if (interrupt_res != PacketResult::Success) 3941 return interrupt_res; 3942 // Otherwise, vCtrlC should issue an OK response (normal interrupts do not). 3943 return SendOKResponse(); 3944 } 3945 3946 GDBRemoteCommunication::PacketResult 3947 GDBRemoteCommunicationServerLLGS::Handle_T(StringExtractorGDBRemote &packet) { 3948 packet.SetFilePos(strlen("T")); 3949 auto pid_tid = packet.GetPidTid(m_current_process ? m_current_process->GetID() 3950 : LLDB_INVALID_PROCESS_ID); 3951 if (!pid_tid) 3952 return SendErrorResponse(llvm::make_error<StringError>( 3953 inconvertibleErrorCode(), "Malformed thread-id")); 3954 3955 lldb::pid_t pid = pid_tid->first; 3956 lldb::tid_t tid = pid_tid->second; 3957 3958 // Technically, this would also be caught by the PID check but let's be more 3959 // explicit about the error. 3960 if (pid == LLDB_INVALID_PROCESS_ID) 3961 return SendErrorResponse(llvm::make_error<StringError>( 3962 inconvertibleErrorCode(), "No current process and no PID provided")); 3963 3964 // Check the process ID and find respective process instance. 3965 auto new_process_it = m_debugged_processes.find(pid); 3966 if (new_process_it == m_debugged_processes.end()) 3967 return SendErrorResponse(1); 3968 3969 // Check the thread ID 3970 if (!new_process_it->second.process_up->GetThreadByID(tid)) 3971 return SendErrorResponse(2); 3972 3973 return SendOKResponse(); 3974 } 3975 3976 void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() { 3977 Log *log = GetLog(LLDBLog::Process); 3978 3979 // Tell the stdio connection to shut down. 3980 if (m_stdio_communication.IsConnected()) { 3981 auto connection = m_stdio_communication.GetConnection(); 3982 if (connection) { 3983 Status error; 3984 connection->Disconnect(&error); 3985 3986 if (error.Success()) { 3987 LLDB_LOGF(log, 3988 "GDBRemoteCommunicationServerLLGS::%s disconnect process " 3989 "terminal stdio - SUCCESS", 3990 __FUNCTION__); 3991 } else { 3992 LLDB_LOGF(log, 3993 "GDBRemoteCommunicationServerLLGS::%s disconnect process " 3994 "terminal stdio - FAIL: %s", 3995 __FUNCTION__, error.AsCString()); 3996 } 3997 } 3998 } 3999 } 4000 4001 NativeThreadProtocol *GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix( 4002 StringExtractorGDBRemote &packet) { 4003 // We have no thread if we don't have a process. 4004 if (!m_current_process || 4005 m_current_process->GetID() == LLDB_INVALID_PROCESS_ID) 4006 return nullptr; 4007 4008 // If the client hasn't asked for thread suffix support, there will not be a 4009 // thread suffix. Use the current thread in that case. 4010 if (!m_thread_suffix_supported) { 4011 const lldb::tid_t current_tid = GetCurrentThreadID(); 4012 if (current_tid == LLDB_INVALID_THREAD_ID) 4013 return nullptr; 4014 else if (current_tid == 0) { 4015 // Pick a thread. 4016 return m_current_process->GetThreadAtIndex(0); 4017 } else 4018 return m_current_process->GetThreadByID(current_tid); 4019 } 4020 4021 Log *log = GetLog(LLDBLog::Thread); 4022 4023 // Parse out the ';'. 4024 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') { 4025 LLDB_LOGF(log, 4026 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse " 4027 "error: expected ';' prior to start of thread suffix: packet " 4028 "contents = '%s'", 4029 __FUNCTION__, packet.GetStringRef().data()); 4030 return nullptr; 4031 } 4032 4033 if (!packet.GetBytesLeft()) 4034 return nullptr; 4035 4036 // Parse out thread: portion. 4037 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) { 4038 LLDB_LOGF(log, 4039 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse " 4040 "error: expected 'thread:' but not found, packet contents = " 4041 "'%s'", 4042 __FUNCTION__, packet.GetStringRef().data()); 4043 return nullptr; 4044 } 4045 packet.SetFilePos(packet.GetFilePos() + strlen("thread:")); 4046 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0); 4047 if (tid != 0) 4048 return m_current_process->GetThreadByID(tid); 4049 4050 return nullptr; 4051 } 4052 4053 lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const { 4054 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) { 4055 // Use whatever the debug process says is the current thread id since the 4056 // protocol either didn't specify or specified we want any/all threads 4057 // marked as the current thread. 4058 if (!m_current_process) 4059 return LLDB_INVALID_THREAD_ID; 4060 return m_current_process->GetCurrentThreadID(); 4061 } 4062 // Use the specific current thread id set by the gdb remote protocol. 4063 return m_current_tid; 4064 } 4065 4066 uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() { 4067 std::lock_guard<std::mutex> guard(m_saved_registers_mutex); 4068 return m_next_saved_registers_id++; 4069 } 4070 4071 void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() { 4072 Log *log = GetLog(LLDBLog::Process); 4073 4074 LLDB_LOG(log, "clearing {0} xfer buffers", m_xfer_buffer_map.size()); 4075 m_xfer_buffer_map.clear(); 4076 } 4077 4078 FileSpec 4079 GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path, 4080 const ArchSpec &arch) { 4081 if (m_current_process) { 4082 FileSpec file_spec; 4083 if (m_current_process 4084 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec) 4085 .Success()) { 4086 if (FileSystem::Instance().Exists(file_spec)) 4087 return file_spec; 4088 } 4089 } 4090 4091 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch); 4092 } 4093 4094 std::string GDBRemoteCommunicationServerLLGS::XMLEncodeAttributeValue( 4095 llvm::StringRef value) { 4096 std::string result; 4097 for (const char &c : value) { 4098 switch (c) { 4099 case '\'': 4100 result += "'"; 4101 break; 4102 case '"': 4103 result += """; 4104 break; 4105 case '<': 4106 result += "<"; 4107 break; 4108 case '>': 4109 result += ">"; 4110 break; 4111 default: 4112 result += c; 4113 break; 4114 } 4115 } 4116 return result; 4117 } 4118 4119 std::vector<std::string> GDBRemoteCommunicationServerLLGS::HandleFeatures( 4120 const llvm::ArrayRef<llvm::StringRef> client_features) { 4121 std::vector<std::string> ret = 4122 GDBRemoteCommunicationServerCommon::HandleFeatures(client_features); 4123 ret.insert(ret.end(), { 4124 "QThreadSuffixSupported+", 4125 "QListThreadsInStopReply+", 4126 "qXfer:features:read+", 4127 "QNonStop+", 4128 }); 4129 4130 // report server-only features 4131 using Extension = NativeProcessProtocol::Extension; 4132 Extension plugin_features = m_process_factory.GetSupportedExtensions(); 4133 if (bool(plugin_features & Extension::pass_signals)) 4134 ret.push_back("QPassSignals+"); 4135 if (bool(plugin_features & Extension::auxv)) 4136 ret.push_back("qXfer:auxv:read+"); 4137 if (bool(plugin_features & Extension::libraries_svr4)) 4138 ret.push_back("qXfer:libraries-svr4:read+"); 4139 if (bool(plugin_features & Extension::siginfo_read)) 4140 ret.push_back("qXfer:siginfo:read+"); 4141 if (bool(plugin_features & Extension::memory_tagging)) 4142 ret.push_back("memory-tagging+"); 4143 if (bool(plugin_features & Extension::savecore)) 4144 ret.push_back("qSaveCore+"); 4145 4146 // check for client features 4147 m_extensions_supported = {}; 4148 for (llvm::StringRef x : client_features) 4149 m_extensions_supported |= 4150 llvm::StringSwitch<Extension>(x) 4151 .Case("multiprocess+", Extension::multiprocess) 4152 .Case("fork-events+", Extension::fork) 4153 .Case("vfork-events+", Extension::vfork) 4154 .Default({}); 4155 4156 m_extensions_supported &= plugin_features; 4157 4158 // fork & vfork require multiprocess 4159 if (!bool(m_extensions_supported & Extension::multiprocess)) 4160 m_extensions_supported &= ~(Extension::fork | Extension::vfork); 4161 4162 // report only if actually supported 4163 if (bool(m_extensions_supported & Extension::multiprocess)) 4164 ret.push_back("multiprocess+"); 4165 if (bool(m_extensions_supported & Extension::fork)) 4166 ret.push_back("fork-events+"); 4167 if (bool(m_extensions_supported & Extension::vfork)) 4168 ret.push_back("vfork-events+"); 4169 4170 for (auto &x : m_debugged_processes) 4171 SetEnabledExtensions(*x.second.process_up); 4172 return ret; 4173 } 4174 4175 void GDBRemoteCommunicationServerLLGS::SetEnabledExtensions( 4176 NativeProcessProtocol &process) { 4177 NativeProcessProtocol::Extension flags = m_extensions_supported; 4178 assert(!bool(flags & ~m_process_factory.GetSupportedExtensions())); 4179 process.SetEnabledExtensions(flags); 4180 } 4181 4182 GDBRemoteCommunication::PacketResult 4183 GDBRemoteCommunicationServerLLGS::SendContinueSuccessResponse() { 4184 // TODO: how to handle forwarding in non-stop mode? 4185 StartSTDIOForwarding(); 4186 return m_non_stop ? SendOKResponse() : PacketResult::Success; 4187 } 4188 4189 void GDBRemoteCommunicationServerLLGS::AppendThreadIDToResponse( 4190 Stream &response, lldb::pid_t pid, lldb::tid_t tid) { 4191 if (bool(m_extensions_supported & 4192 NativeProcessProtocol::Extension::multiprocess)) 4193 response.Format("p{0:x-}.", pid); 4194 response.Format("{0:x-}", tid); 4195 } 4196 4197 std::string 4198 lldb_private::process_gdb_remote::LLGSArgToURL(llvm::StringRef url_arg, 4199 bool reverse_connect) { 4200 // Try parsing the argument as URL. 4201 if (llvm::Optional<URI> url = URI::Parse(url_arg)) { 4202 if (reverse_connect) 4203 return url_arg.str(); 4204 4205 // Translate the scheme from LLGS notation to ConnectionFileDescriptor. 4206 // If the scheme doesn't match any, pass it through to support using CFD 4207 // schemes directly. 4208 std::string new_url = llvm::StringSwitch<std::string>(url->scheme) 4209 .Case("tcp", "listen") 4210 .Case("unix", "unix-accept") 4211 .Case("unix-abstract", "unix-abstract-accept") 4212 .Default(url->scheme.str()); 4213 llvm::append_range(new_url, url_arg.substr(url->scheme.size())); 4214 return new_url; 4215 } 4216 4217 std::string host_port = url_arg.str(); 4218 // If host_and_port starts with ':', default the host to be "localhost" and 4219 // expect the remainder to be the port. 4220 if (url_arg.startswith(":")) 4221 host_port.insert(0, "localhost"); 4222 4223 // Try parsing the (preprocessed) argument as host:port pair. 4224 if (!llvm::errorToBool(Socket::DecodeHostAndPort(host_port).takeError())) 4225 return (reverse_connect ? "connect://" : "listen://") + host_port; 4226 4227 // If none of the above applied, interpret the argument as UNIX socket path. 4228 return (reverse_connect ? "unix-connect://" : "unix-accept://") + 4229 url_arg.str(); 4230 } 4231