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