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