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