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