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 if (reg_info->dynamic_size_dwarf_expr_bytes) { 1831 const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len; 1832 response.PutCString("dynamic_size_dwarf_expr_bytes:"); 1833 for (uint32_t i = 0; i < dwarf_opcode_len; ++i) 1834 response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]); 1835 response.PutChar(';'); 1836 } 1837 return SendPacketNoLock(response.GetString()); 1838 } 1839 1840 GDBRemoteCommunication::PacketResult 1841 GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo( 1842 StringExtractorGDBRemote &packet) { 1843 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 1844 1845 // Fail if we don't have a current process. 1846 if (!m_current_process || 1847 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 1848 LLDB_LOG(log, "no process ({0}), returning OK", 1849 m_current_process ? "invalid process id" 1850 : "null m_current_process"); 1851 return SendOKResponse(); 1852 } 1853 1854 StreamGDBRemote response; 1855 response.PutChar('m'); 1856 1857 LLDB_LOG(log, "starting thread iteration"); 1858 NativeThreadProtocol *thread; 1859 uint32_t thread_index; 1860 for (thread_index = 0, 1861 thread = m_current_process->GetThreadAtIndex(thread_index); 1862 thread; ++thread_index, 1863 thread = m_current_process->GetThreadAtIndex(thread_index)) { 1864 LLDB_LOG(log, "iterated thread {0}(tid={2})", thread_index, 1865 thread->GetID()); 1866 if (thread_index > 0) 1867 response.PutChar(','); 1868 response.Printf("%" PRIx64, thread->GetID()); 1869 } 1870 1871 LLDB_LOG(log, "finished thread iteration"); 1872 return SendPacketNoLock(response.GetString()); 1873 } 1874 1875 GDBRemoteCommunication::PacketResult 1876 GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo( 1877 StringExtractorGDBRemote &packet) { 1878 // FIXME for now we return the full thread list in the initial packet and 1879 // always do nothing here. 1880 return SendPacketNoLock("l"); 1881 } 1882 1883 GDBRemoteCommunication::PacketResult 1884 GDBRemoteCommunicationServerLLGS::Handle_g(StringExtractorGDBRemote &packet) { 1885 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 1886 1887 // Move past packet name. 1888 packet.SetFilePos(strlen("g")); 1889 1890 // Get the thread to use. 1891 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 1892 if (!thread) { 1893 LLDB_LOG(log, "failed, no thread available"); 1894 return SendErrorResponse(0x15); 1895 } 1896 1897 // Get the thread's register context. 1898 NativeRegisterContext ®_ctx = thread->GetRegisterContext(); 1899 1900 std::vector<uint8_t> regs_buffer; 1901 for (uint32_t reg_num = 0; reg_num < reg_ctx.GetUserRegisterCount(); 1902 ++reg_num) { 1903 const RegisterInfo *reg_info = reg_ctx.GetRegisterInfoAtIndex(reg_num); 1904 1905 if (reg_info == nullptr) { 1906 LLDB_LOG(log, "failed to get register info for register index {0}", 1907 reg_num); 1908 return SendErrorResponse(0x15); 1909 } 1910 1911 if (reg_info->value_regs != nullptr) 1912 continue; // skip registers that are contained in other registers 1913 1914 RegisterValue reg_value; 1915 Status error = reg_ctx.ReadRegister(reg_info, reg_value); 1916 if (error.Fail()) { 1917 LLDB_LOG(log, "failed to read register at index {0}", reg_num); 1918 return SendErrorResponse(0x15); 1919 } 1920 1921 if (reg_info->byte_offset + reg_info->byte_size >= regs_buffer.size()) 1922 // Resize the buffer to guarantee it can store the register offsetted 1923 // data. 1924 regs_buffer.resize(reg_info->byte_offset + reg_info->byte_size); 1925 1926 // Copy the register offsetted data to the buffer. 1927 memcpy(regs_buffer.data() + reg_info->byte_offset, reg_value.GetBytes(), 1928 reg_info->byte_size); 1929 } 1930 1931 // Write the response. 1932 StreamGDBRemote response; 1933 response.PutBytesAsRawHex8(regs_buffer.data(), regs_buffer.size()); 1934 1935 return SendPacketNoLock(response.GetString()); 1936 } 1937 1938 GDBRemoteCommunication::PacketResult 1939 GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) { 1940 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 1941 1942 // Parse out the register number from the request. 1943 packet.SetFilePos(strlen("p")); 1944 const uint32_t reg_index = 1945 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 1946 if (reg_index == std::numeric_limits<uint32_t>::max()) { 1947 LLDB_LOGF(log, 1948 "GDBRemoteCommunicationServerLLGS::%s failed, could not " 1949 "parse register number from request \"%s\"", 1950 __FUNCTION__, packet.GetStringRef().data()); 1951 return SendErrorResponse(0x15); 1952 } 1953 1954 // Get the thread to use. 1955 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 1956 if (!thread) { 1957 LLDB_LOG(log, "failed, no thread available"); 1958 return SendErrorResponse(0x15); 1959 } 1960 1961 // Get the thread's register context. 1962 NativeRegisterContext ®_context = thread->GetRegisterContext(); 1963 1964 // Return the end of registers response if we've iterated one past the end of 1965 // the register set. 1966 if (reg_index >= reg_context.GetUserRegisterCount()) { 1967 LLDB_LOGF(log, 1968 "GDBRemoteCommunicationServerLLGS::%s failed, requested " 1969 "register %" PRIu32 " beyond register count %" PRIu32, 1970 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount()); 1971 return SendErrorResponse(0x15); 1972 } 1973 1974 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index); 1975 if (!reg_info) { 1976 LLDB_LOGF(log, 1977 "GDBRemoteCommunicationServerLLGS::%s failed, requested " 1978 "register %" PRIu32 " returned NULL", 1979 __FUNCTION__, reg_index); 1980 return SendErrorResponse(0x15); 1981 } 1982 1983 // Build the reginfos response. 1984 StreamGDBRemote response; 1985 1986 // Retrieve the value 1987 RegisterValue reg_value; 1988 Status error = reg_context.ReadRegister(reg_info, reg_value); 1989 if (error.Fail()) { 1990 LLDB_LOGF(log, 1991 "GDBRemoteCommunicationServerLLGS::%s failed, read of " 1992 "requested register %" PRIu32 " (%s) failed: %s", 1993 __FUNCTION__, reg_index, reg_info->name, error.AsCString()); 1994 return SendErrorResponse(0x15); 1995 } 1996 1997 const uint8_t *const data = 1998 static_cast<const uint8_t *>(reg_value.GetBytes()); 1999 if (!data) { 2000 LLDB_LOGF(log, 2001 "GDBRemoteCommunicationServerLLGS::%s failed to get data " 2002 "bytes from requested register %" PRIu32, 2003 __FUNCTION__, reg_index); 2004 return SendErrorResponse(0x15); 2005 } 2006 2007 // FIXME flip as needed to get data in big/little endian format for this host. 2008 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i) 2009 response.PutHex8(data[i]); 2010 2011 return SendPacketNoLock(response.GetString()); 2012 } 2013 2014 GDBRemoteCommunication::PacketResult 2015 GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) { 2016 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 2017 2018 // Ensure there is more content. 2019 if (packet.GetBytesLeft() < 1) 2020 return SendIllFormedResponse(packet, "Empty P packet"); 2021 2022 // Parse out the register number from the request. 2023 packet.SetFilePos(strlen("P")); 2024 const uint32_t reg_index = 2025 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 2026 if (reg_index == std::numeric_limits<uint32_t>::max()) { 2027 LLDB_LOGF(log, 2028 "GDBRemoteCommunicationServerLLGS::%s failed, could not " 2029 "parse register number from request \"%s\"", 2030 __FUNCTION__, packet.GetStringRef().data()); 2031 return SendErrorResponse(0x29); 2032 } 2033 2034 // Note debugserver would send an E30 here. 2035 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '=')) 2036 return SendIllFormedResponse( 2037 packet, "P packet missing '=' char after register number"); 2038 2039 // Parse out the value. 2040 uint8_t reg_bytes[RegisterValue::kMaxRegisterByteSize]; 2041 size_t reg_size = packet.GetHexBytesAvail(reg_bytes); 2042 2043 // Get the thread to use. 2044 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 2045 if (!thread) { 2046 LLDB_LOGF(log, 2047 "GDBRemoteCommunicationServerLLGS::%s failed, no thread " 2048 "available (thread index 0)", 2049 __FUNCTION__); 2050 return SendErrorResponse(0x28); 2051 } 2052 2053 // Get the thread's register context. 2054 NativeRegisterContext ®_context = thread->GetRegisterContext(); 2055 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index); 2056 if (!reg_info) { 2057 LLDB_LOGF(log, 2058 "GDBRemoteCommunicationServerLLGS::%s failed, requested " 2059 "register %" PRIu32 " returned NULL", 2060 __FUNCTION__, reg_index); 2061 return SendErrorResponse(0x48); 2062 } 2063 2064 // Return the end of registers response if we've iterated one past the end of 2065 // the register set. 2066 if (reg_index >= reg_context.GetUserRegisterCount()) { 2067 LLDB_LOGF(log, 2068 "GDBRemoteCommunicationServerLLGS::%s failed, requested " 2069 "register %" PRIu32 " beyond register count %" PRIu32, 2070 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount()); 2071 return SendErrorResponse(0x47); 2072 } 2073 2074 // The dwarf expression are evaluate on host site which may cause register 2075 // size to change Hence the reg_size may not be same as reg_info->bytes_size 2076 if ((reg_size != reg_info->byte_size) && 2077 !(reg_info->dynamic_size_dwarf_expr_bytes)) { 2078 return SendIllFormedResponse(packet, "P packet register size is incorrect"); 2079 } 2080 2081 // Build the reginfos response. 2082 StreamGDBRemote response; 2083 2084 RegisterValue reg_value(makeArrayRef(reg_bytes, reg_size), 2085 m_current_process->GetArchitecture().GetByteOrder()); 2086 Status error = reg_context.WriteRegister(reg_info, reg_value); 2087 if (error.Fail()) { 2088 LLDB_LOGF(log, 2089 "GDBRemoteCommunicationServerLLGS::%s failed, write of " 2090 "requested register %" PRIu32 " (%s) failed: %s", 2091 __FUNCTION__, reg_index, reg_info->name, error.AsCString()); 2092 return SendErrorResponse(0x32); 2093 } 2094 2095 return SendOKResponse(); 2096 } 2097 2098 GDBRemoteCommunication::PacketResult 2099 GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) { 2100 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 2101 2102 // Parse out which variant of $H is requested. 2103 packet.SetFilePos(strlen("H")); 2104 if (packet.GetBytesLeft() < 1) { 2105 LLDB_LOGF(log, 2106 "GDBRemoteCommunicationServerLLGS::%s failed, H command " 2107 "missing {g,c} variant", 2108 __FUNCTION__); 2109 return SendIllFormedResponse(packet, "H command missing {g,c} variant"); 2110 } 2111 2112 const char h_variant = packet.GetChar(); 2113 NativeProcessProtocol *default_process; 2114 switch (h_variant) { 2115 case 'g': 2116 default_process = m_current_process; 2117 break; 2118 2119 case 'c': 2120 default_process = m_continue_process; 2121 break; 2122 2123 default: 2124 LLDB_LOGF( 2125 log, 2126 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c", 2127 __FUNCTION__, h_variant); 2128 return SendIllFormedResponse(packet, 2129 "H variant unsupported, should be c or g"); 2130 } 2131 2132 // Parse out the thread number. 2133 auto pid_tid = packet.GetPidTid(default_process ? default_process->GetID() 2134 : LLDB_INVALID_PROCESS_ID); 2135 if (!pid_tid) 2136 return SendErrorResponse(llvm::make_error<StringError>( 2137 inconvertibleErrorCode(), "Malformed thread-id")); 2138 2139 lldb::pid_t pid = pid_tid->first; 2140 lldb::tid_t tid = pid_tid->second; 2141 2142 if (pid == StringExtractorGDBRemote::AllProcesses) 2143 return SendUnimplementedResponse("Selecting all processes not supported"); 2144 if (pid == LLDB_INVALID_PROCESS_ID) 2145 return SendErrorResponse(llvm::make_error<StringError>( 2146 inconvertibleErrorCode(), "No current process and no PID provided")); 2147 2148 // Check the process ID and find respective process instance. 2149 auto new_process_it = m_debugged_processes.find(pid); 2150 if (new_process_it == m_debugged_processes.end()) 2151 return SendErrorResponse(llvm::make_error<StringError>( 2152 inconvertibleErrorCode(), 2153 llvm::formatv("No process with PID {0} debugged", pid))); 2154 2155 // Ensure we have the given thread when not specifying -1 (all threads) or 0 2156 // (any thread). 2157 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) { 2158 NativeThreadProtocol *thread = new_process_it->second->GetThreadByID(tid); 2159 if (!thread) { 2160 LLDB_LOGF(log, 2161 "GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64 2162 " not found", 2163 __FUNCTION__, tid); 2164 return SendErrorResponse(0x15); 2165 } 2166 } 2167 2168 // Now switch the given process and thread type. 2169 switch (h_variant) { 2170 case 'g': 2171 m_current_process = new_process_it->second.get(); 2172 SetCurrentThreadID(tid); 2173 break; 2174 2175 case 'c': 2176 m_continue_process = new_process_it->second.get(); 2177 SetContinueThreadID(tid); 2178 break; 2179 2180 default: 2181 assert(false && "unsupported $H variant - shouldn't get here"); 2182 return SendIllFormedResponse(packet, 2183 "H variant unsupported, should be c or g"); 2184 } 2185 2186 return SendOKResponse(); 2187 } 2188 2189 GDBRemoteCommunication::PacketResult 2190 GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) { 2191 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 2192 2193 // Fail if we don't have a current process. 2194 if (!m_current_process || 2195 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2196 LLDB_LOGF( 2197 log, 2198 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2199 __FUNCTION__); 2200 return SendErrorResponse(0x15); 2201 } 2202 2203 packet.SetFilePos(::strlen("I")); 2204 uint8_t tmp[4096]; 2205 for (;;) { 2206 size_t read = packet.GetHexBytesAvail(tmp); 2207 if (read == 0) { 2208 break; 2209 } 2210 // write directly to stdin *this might block if stdin buffer is full* 2211 // TODO: enqueue this block in circular buffer and send window size to 2212 // remote host 2213 ConnectionStatus status; 2214 Status error; 2215 m_stdio_communication.Write(tmp, read, status, &error); 2216 if (error.Fail()) { 2217 return SendErrorResponse(0x15); 2218 } 2219 } 2220 2221 return SendOKResponse(); 2222 } 2223 2224 GDBRemoteCommunication::PacketResult 2225 GDBRemoteCommunicationServerLLGS::Handle_interrupt( 2226 StringExtractorGDBRemote &packet) { 2227 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 2228 2229 // Fail if we don't have a current process. 2230 if (!m_current_process || 2231 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2232 LLDB_LOG(log, "failed, no process available"); 2233 return SendErrorResponse(0x15); 2234 } 2235 2236 // Interrupt the process. 2237 Status error = m_current_process->Interrupt(); 2238 if (error.Fail()) { 2239 LLDB_LOG(log, "failed for process {0}: {1}", m_current_process->GetID(), 2240 error); 2241 return SendErrorResponse(GDBRemoteServerError::eErrorResume); 2242 } 2243 2244 LLDB_LOG(log, "stopped process {0}", m_current_process->GetID()); 2245 2246 // No response required from stop all. 2247 return PacketResult::Success; 2248 } 2249 2250 GDBRemoteCommunication::PacketResult 2251 GDBRemoteCommunicationServerLLGS::Handle_memory_read( 2252 StringExtractorGDBRemote &packet) { 2253 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2254 2255 if (!m_current_process || 2256 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2257 LLDB_LOGF( 2258 log, 2259 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2260 __FUNCTION__); 2261 return SendErrorResponse(0x15); 2262 } 2263 2264 // Parse out the memory address. 2265 packet.SetFilePos(strlen("m")); 2266 if (packet.GetBytesLeft() < 1) 2267 return SendIllFormedResponse(packet, "Too short m packet"); 2268 2269 // Read the address. Punting on validation. 2270 // FIXME replace with Hex U64 read with no default value that fails on failed 2271 // read. 2272 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0); 2273 2274 // Validate comma. 2275 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ',')) 2276 return SendIllFormedResponse(packet, "Comma sep missing in m packet"); 2277 2278 // Get # bytes to read. 2279 if (packet.GetBytesLeft() < 1) 2280 return SendIllFormedResponse(packet, "Length missing in m packet"); 2281 2282 const uint64_t byte_count = packet.GetHexMaxU64(false, 0); 2283 if (byte_count == 0) { 2284 LLDB_LOGF(log, 2285 "GDBRemoteCommunicationServerLLGS::%s nothing to read: " 2286 "zero-length packet", 2287 __FUNCTION__); 2288 return SendOKResponse(); 2289 } 2290 2291 // Allocate the response buffer. 2292 std::string buf(byte_count, '\0'); 2293 if (buf.empty()) 2294 return SendErrorResponse(0x78); 2295 2296 // Retrieve the process memory. 2297 size_t bytes_read = 0; 2298 Status error = m_current_process->ReadMemoryWithoutTrap( 2299 read_addr, &buf[0], byte_count, bytes_read); 2300 if (error.Fail()) { 2301 LLDB_LOGF(log, 2302 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 2303 " mem 0x%" PRIx64 ": failed to read. Error: %s", 2304 __FUNCTION__, m_current_process->GetID(), read_addr, 2305 error.AsCString()); 2306 return SendErrorResponse(0x08); 2307 } 2308 2309 if (bytes_read == 0) { 2310 LLDB_LOGF(log, 2311 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 2312 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes", 2313 __FUNCTION__, m_current_process->GetID(), read_addr, byte_count); 2314 return SendErrorResponse(0x08); 2315 } 2316 2317 StreamGDBRemote response; 2318 packet.SetFilePos(0); 2319 char kind = packet.GetChar('?'); 2320 if (kind == 'x') 2321 response.PutEscapedBytes(buf.data(), byte_count); 2322 else { 2323 assert(kind == 'm'); 2324 for (size_t i = 0; i < bytes_read; ++i) 2325 response.PutHex8(buf[i]); 2326 } 2327 2328 return SendPacketNoLock(response.GetString()); 2329 } 2330 2331 GDBRemoteCommunication::PacketResult 2332 GDBRemoteCommunicationServerLLGS::Handle__M(StringExtractorGDBRemote &packet) { 2333 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2334 2335 if (!m_current_process || 2336 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2337 LLDB_LOGF( 2338 log, 2339 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2340 __FUNCTION__); 2341 return SendErrorResponse(0x15); 2342 } 2343 2344 // Parse out the memory address. 2345 packet.SetFilePos(strlen("_M")); 2346 if (packet.GetBytesLeft() < 1) 2347 return SendIllFormedResponse(packet, "Too short _M packet"); 2348 2349 const lldb::addr_t size = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 2350 if (size == LLDB_INVALID_ADDRESS) 2351 return SendIllFormedResponse(packet, "Address not valid"); 2352 if (packet.GetChar() != ',') 2353 return SendIllFormedResponse(packet, "Bad packet"); 2354 Permissions perms = {}; 2355 while (packet.GetBytesLeft() > 0) { 2356 switch (packet.GetChar()) { 2357 case 'r': 2358 perms |= ePermissionsReadable; 2359 break; 2360 case 'w': 2361 perms |= ePermissionsWritable; 2362 break; 2363 case 'x': 2364 perms |= ePermissionsExecutable; 2365 break; 2366 default: 2367 return SendIllFormedResponse(packet, "Bad permissions"); 2368 } 2369 } 2370 2371 llvm::Expected<addr_t> addr = m_current_process->AllocateMemory(size, perms); 2372 if (!addr) 2373 return SendErrorResponse(addr.takeError()); 2374 2375 StreamGDBRemote response; 2376 response.PutHex64(*addr); 2377 return SendPacketNoLock(response.GetString()); 2378 } 2379 2380 GDBRemoteCommunication::PacketResult 2381 GDBRemoteCommunicationServerLLGS::Handle__m(StringExtractorGDBRemote &packet) { 2382 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2383 2384 if (!m_current_process || 2385 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2386 LLDB_LOGF( 2387 log, 2388 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2389 __FUNCTION__); 2390 return SendErrorResponse(0x15); 2391 } 2392 2393 // Parse out the memory address. 2394 packet.SetFilePos(strlen("_m")); 2395 if (packet.GetBytesLeft() < 1) 2396 return SendIllFormedResponse(packet, "Too short m packet"); 2397 2398 const lldb::addr_t addr = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 2399 if (addr == LLDB_INVALID_ADDRESS) 2400 return SendIllFormedResponse(packet, "Address not valid"); 2401 2402 if (llvm::Error Err = m_current_process->DeallocateMemory(addr)) 2403 return SendErrorResponse(std::move(Err)); 2404 2405 return SendOKResponse(); 2406 } 2407 2408 GDBRemoteCommunication::PacketResult 2409 GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) { 2410 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2411 2412 if (!m_current_process || 2413 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2414 LLDB_LOGF( 2415 log, 2416 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2417 __FUNCTION__); 2418 return SendErrorResponse(0x15); 2419 } 2420 2421 // Parse out the memory address. 2422 packet.SetFilePos(strlen("M")); 2423 if (packet.GetBytesLeft() < 1) 2424 return SendIllFormedResponse(packet, "Too short M packet"); 2425 2426 // Read the address. Punting on validation. 2427 // FIXME replace with Hex U64 read with no default value that fails on failed 2428 // read. 2429 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0); 2430 2431 // Validate comma. 2432 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ',')) 2433 return SendIllFormedResponse(packet, "Comma sep missing in M packet"); 2434 2435 // Get # bytes to read. 2436 if (packet.GetBytesLeft() < 1) 2437 return SendIllFormedResponse(packet, "Length missing in M packet"); 2438 2439 const uint64_t byte_count = packet.GetHexMaxU64(false, 0); 2440 if (byte_count == 0) { 2441 LLDB_LOG(log, "nothing to write: zero-length packet"); 2442 return PacketResult::Success; 2443 } 2444 2445 // Validate colon. 2446 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':')) 2447 return SendIllFormedResponse( 2448 packet, "Comma sep missing in M packet after byte length"); 2449 2450 // Allocate the conversion buffer. 2451 std::vector<uint8_t> buf(byte_count, 0); 2452 if (buf.empty()) 2453 return SendErrorResponse(0x78); 2454 2455 // Convert the hex memory write contents to bytes. 2456 StreamGDBRemote response; 2457 const uint64_t convert_count = packet.GetHexBytes(buf, 0); 2458 if (convert_count != byte_count) { 2459 LLDB_LOG(log, 2460 "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} " 2461 "to convert.", 2462 m_current_process->GetID(), write_addr, byte_count, convert_count); 2463 return SendIllFormedResponse(packet, "M content byte length specified did " 2464 "not match hex-encoded content " 2465 "length"); 2466 } 2467 2468 // Write the process memory. 2469 size_t bytes_written = 0; 2470 Status error = m_current_process->WriteMemory(write_addr, &buf[0], byte_count, 2471 bytes_written); 2472 if (error.Fail()) { 2473 LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}", 2474 m_current_process->GetID(), write_addr, error); 2475 return SendErrorResponse(0x09); 2476 } 2477 2478 if (bytes_written == 0) { 2479 LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes", 2480 m_current_process->GetID(), write_addr, byte_count); 2481 return SendErrorResponse(0x09); 2482 } 2483 2484 return SendOKResponse(); 2485 } 2486 2487 GDBRemoteCommunication::PacketResult 2488 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported( 2489 StringExtractorGDBRemote &packet) { 2490 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2491 2492 // Currently only the NativeProcessProtocol knows if it can handle a 2493 // qMemoryRegionInfoSupported request, but we're not guaranteed to be 2494 // attached to a process. For now we'll assume the client only asks this 2495 // when a process is being debugged. 2496 2497 // Ensure we have a process running; otherwise, we can't figure this out 2498 // since we won't have a NativeProcessProtocol. 2499 if (!m_current_process || 2500 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2501 LLDB_LOGF( 2502 log, 2503 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2504 __FUNCTION__); 2505 return SendErrorResponse(0x15); 2506 } 2507 2508 // Test if we can get any region back when asking for the region around NULL. 2509 MemoryRegionInfo region_info; 2510 const Status error = m_current_process->GetMemoryRegionInfo(0, region_info); 2511 if (error.Fail()) { 2512 // We don't support memory region info collection for this 2513 // NativeProcessProtocol. 2514 return SendUnimplementedResponse(""); 2515 } 2516 2517 return SendOKResponse(); 2518 } 2519 2520 GDBRemoteCommunication::PacketResult 2521 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo( 2522 StringExtractorGDBRemote &packet) { 2523 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2524 2525 // Ensure we have a process. 2526 if (!m_current_process || 2527 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2528 LLDB_LOGF( 2529 log, 2530 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2531 __FUNCTION__); 2532 return SendErrorResponse(0x15); 2533 } 2534 2535 // Parse out the memory address. 2536 packet.SetFilePos(strlen("qMemoryRegionInfo:")); 2537 if (packet.GetBytesLeft() < 1) 2538 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet"); 2539 2540 // Read the address. Punting on validation. 2541 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0); 2542 2543 StreamGDBRemote response; 2544 2545 // Get the memory region info for the target address. 2546 MemoryRegionInfo region_info; 2547 const Status error = 2548 m_current_process->GetMemoryRegionInfo(read_addr, region_info); 2549 if (error.Fail()) { 2550 // Return the error message. 2551 2552 response.PutCString("error:"); 2553 response.PutStringAsRawHex8(error.AsCString()); 2554 response.PutChar(';'); 2555 } else { 2556 // Range start and size. 2557 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";", 2558 region_info.GetRange().GetRangeBase(), 2559 region_info.GetRange().GetByteSize()); 2560 2561 // Permissions. 2562 if (region_info.GetReadable() || region_info.GetWritable() || 2563 region_info.GetExecutable()) { 2564 // Write permissions info. 2565 response.PutCString("permissions:"); 2566 2567 if (region_info.GetReadable()) 2568 response.PutChar('r'); 2569 if (region_info.GetWritable()) 2570 response.PutChar('w'); 2571 if (region_info.GetExecutable()) 2572 response.PutChar('x'); 2573 2574 response.PutChar(';'); 2575 } 2576 2577 // Flags 2578 MemoryRegionInfo::OptionalBool memory_tagged = 2579 region_info.GetMemoryTagged(); 2580 if (memory_tagged != MemoryRegionInfo::eDontKnow) { 2581 response.PutCString("flags:"); 2582 if (memory_tagged == MemoryRegionInfo::eYes) { 2583 response.PutCString("mt"); 2584 } 2585 response.PutChar(';'); 2586 } 2587 2588 // Name 2589 ConstString name = region_info.GetName(); 2590 if (name) { 2591 response.PutCString("name:"); 2592 response.PutStringAsRawHex8(name.GetStringRef()); 2593 response.PutChar(';'); 2594 } 2595 } 2596 2597 return SendPacketNoLock(response.GetString()); 2598 } 2599 2600 GDBRemoteCommunication::PacketResult 2601 GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) { 2602 // Ensure we have a process. 2603 if (!m_current_process || 2604 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2605 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2606 LLDB_LOG(log, "failed, no process available"); 2607 return SendErrorResponse(0x15); 2608 } 2609 2610 // Parse out software or hardware breakpoint or watchpoint requested. 2611 packet.SetFilePos(strlen("Z")); 2612 if (packet.GetBytesLeft() < 1) 2613 return SendIllFormedResponse( 2614 packet, "Too short Z packet, missing software/hardware specifier"); 2615 2616 bool want_breakpoint = true; 2617 bool want_hardware = false; 2618 uint32_t watch_flags = 0; 2619 2620 const GDBStoppointType stoppoint_type = 2621 GDBStoppointType(packet.GetS32(eStoppointInvalid)); 2622 switch (stoppoint_type) { 2623 case eBreakpointSoftware: 2624 want_hardware = false; 2625 want_breakpoint = true; 2626 break; 2627 case eBreakpointHardware: 2628 want_hardware = true; 2629 want_breakpoint = true; 2630 break; 2631 case eWatchpointWrite: 2632 watch_flags = 1; 2633 want_hardware = true; 2634 want_breakpoint = false; 2635 break; 2636 case eWatchpointRead: 2637 watch_flags = 2; 2638 want_hardware = true; 2639 want_breakpoint = false; 2640 break; 2641 case eWatchpointReadWrite: 2642 watch_flags = 3; 2643 want_hardware = true; 2644 want_breakpoint = false; 2645 break; 2646 case eStoppointInvalid: 2647 return SendIllFormedResponse( 2648 packet, "Z packet had invalid software/hardware specifier"); 2649 } 2650 2651 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',') 2652 return SendIllFormedResponse( 2653 packet, "Malformed Z packet, expecting comma after stoppoint type"); 2654 2655 // Parse out the stoppoint address. 2656 if (packet.GetBytesLeft() < 1) 2657 return SendIllFormedResponse(packet, "Too short Z packet, missing address"); 2658 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0); 2659 2660 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',') 2661 return SendIllFormedResponse( 2662 packet, "Malformed Z packet, expecting comma after address"); 2663 2664 // Parse out the stoppoint size (i.e. size hint for opcode size). 2665 const uint32_t size = 2666 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 2667 if (size == std::numeric_limits<uint32_t>::max()) 2668 return SendIllFormedResponse( 2669 packet, "Malformed Z packet, failed to parse size argument"); 2670 2671 if (want_breakpoint) { 2672 // Try to set the breakpoint. 2673 const Status error = 2674 m_current_process->SetBreakpoint(addr, size, want_hardware); 2675 if (error.Success()) 2676 return SendOKResponse(); 2677 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); 2678 LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}", 2679 m_current_process->GetID(), error); 2680 return SendErrorResponse(0x09); 2681 } else { 2682 // Try to set the watchpoint. 2683 const Status error = m_current_process->SetWatchpoint( 2684 addr, size, watch_flags, want_hardware); 2685 if (error.Success()) 2686 return SendOKResponse(); 2687 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS)); 2688 LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}", 2689 m_current_process->GetID(), error); 2690 return SendErrorResponse(0x09); 2691 } 2692 } 2693 2694 GDBRemoteCommunication::PacketResult 2695 GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) { 2696 // Ensure we have a process. 2697 if (!m_current_process || 2698 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2699 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2700 LLDB_LOG(log, "failed, no process available"); 2701 return SendErrorResponse(0x15); 2702 } 2703 2704 // Parse out software or hardware breakpoint or watchpoint requested. 2705 packet.SetFilePos(strlen("z")); 2706 if (packet.GetBytesLeft() < 1) 2707 return SendIllFormedResponse( 2708 packet, "Too short z packet, missing software/hardware specifier"); 2709 2710 bool want_breakpoint = true; 2711 bool want_hardware = false; 2712 2713 const GDBStoppointType stoppoint_type = 2714 GDBStoppointType(packet.GetS32(eStoppointInvalid)); 2715 switch (stoppoint_type) { 2716 case eBreakpointHardware: 2717 want_breakpoint = true; 2718 want_hardware = true; 2719 break; 2720 case eBreakpointSoftware: 2721 want_breakpoint = true; 2722 break; 2723 case eWatchpointWrite: 2724 want_breakpoint = false; 2725 break; 2726 case eWatchpointRead: 2727 want_breakpoint = false; 2728 break; 2729 case eWatchpointReadWrite: 2730 want_breakpoint = false; 2731 break; 2732 default: 2733 return SendIllFormedResponse( 2734 packet, "z packet had invalid software/hardware specifier"); 2735 } 2736 2737 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',') 2738 return SendIllFormedResponse( 2739 packet, "Malformed z packet, expecting comma after stoppoint type"); 2740 2741 // Parse out the stoppoint address. 2742 if (packet.GetBytesLeft() < 1) 2743 return SendIllFormedResponse(packet, "Too short z packet, missing address"); 2744 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0); 2745 2746 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',') 2747 return SendIllFormedResponse( 2748 packet, "Malformed z packet, expecting comma after address"); 2749 2750 /* 2751 // Parse out the stoppoint size (i.e. size hint for opcode size). 2752 const uint32_t size = packet.GetHexMaxU32 (false, 2753 std::numeric_limits<uint32_t>::max ()); 2754 if (size == std::numeric_limits<uint32_t>::max ()) 2755 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse 2756 size argument"); 2757 */ 2758 2759 if (want_breakpoint) { 2760 // Try to clear the breakpoint. 2761 const Status error = 2762 m_current_process->RemoveBreakpoint(addr, want_hardware); 2763 if (error.Success()) 2764 return SendOKResponse(); 2765 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); 2766 LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}", 2767 m_current_process->GetID(), error); 2768 return SendErrorResponse(0x09); 2769 } else { 2770 // Try to clear the watchpoint. 2771 const Status error = m_current_process->RemoveWatchpoint(addr); 2772 if (error.Success()) 2773 return SendOKResponse(); 2774 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS)); 2775 LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}", 2776 m_current_process->GetID(), error); 2777 return SendErrorResponse(0x09); 2778 } 2779 } 2780 2781 GDBRemoteCommunication::PacketResult 2782 GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) { 2783 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 2784 2785 // Ensure we have a process. 2786 if (!m_continue_process || 2787 (m_continue_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2788 LLDB_LOGF( 2789 log, 2790 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2791 __FUNCTION__); 2792 return SendErrorResponse(0x32); 2793 } 2794 2795 // We first try to use a continue thread id. If any one or any all set, use 2796 // the current thread. Bail out if we don't have a thread id. 2797 lldb::tid_t tid = GetContinueThreadID(); 2798 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID) 2799 tid = GetCurrentThreadID(); 2800 if (tid == LLDB_INVALID_THREAD_ID) 2801 return SendErrorResponse(0x33); 2802 2803 // Double check that we have such a thread. 2804 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here. 2805 NativeThreadProtocol *thread = m_continue_process->GetThreadByID(tid); 2806 if (!thread) 2807 return SendErrorResponse(0x33); 2808 2809 // Create the step action for the given thread. 2810 ResumeAction action = {tid, eStateStepping, LLDB_INVALID_SIGNAL_NUMBER}; 2811 2812 // Setup the actions list. 2813 ResumeActionList actions; 2814 actions.Append(action); 2815 2816 // All other threads stop while we're single stepping a thread. 2817 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0); 2818 Status error = m_continue_process->Resume(actions); 2819 if (error.Fail()) { 2820 LLDB_LOGF(log, 2821 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 2822 " tid %" PRIu64 " Resume() failed with error: %s", 2823 __FUNCTION__, m_continue_process->GetID(), tid, 2824 error.AsCString()); 2825 return SendErrorResponse(0x49); 2826 } 2827 2828 // No response here - the stop or exit will come from the resulting action. 2829 return PacketResult::Success; 2830 } 2831 2832 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> 2833 GDBRemoteCommunicationServerLLGS::BuildTargetXml() { 2834 // Ensure we have a thread. 2835 NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0); 2836 if (!thread) 2837 return llvm::createStringError(llvm::inconvertibleErrorCode(), 2838 "No thread available"); 2839 2840 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 2841 // Get the register context for the first thread. 2842 NativeRegisterContext ®_context = thread->GetRegisterContext(); 2843 2844 StreamString response; 2845 2846 response.Printf("<?xml version=\"1.0\"?>"); 2847 response.Printf("<target version=\"1.0\">"); 2848 2849 response.Printf("<architecture>%s</architecture>", 2850 m_current_process->GetArchitecture() 2851 .GetTriple() 2852 .getArchName() 2853 .str() 2854 .c_str()); 2855 2856 response.Printf("<feature>"); 2857 2858 const int registers_count = reg_context.GetUserRegisterCount(); 2859 for (int reg_index = 0; reg_index < registers_count; reg_index++) { 2860 const RegisterInfo *reg_info = 2861 reg_context.GetRegisterInfoAtIndex(reg_index); 2862 2863 if (!reg_info) { 2864 LLDB_LOGF(log, 2865 "%s failed to get register info for register index %" PRIu32, 2866 "target.xml", reg_index); 2867 continue; 2868 } 2869 2870 response.Printf("<reg name=\"%s\" bitsize=\"%" PRIu32 "\" regnum=\"%d\" ", 2871 reg_info->name, reg_info->byte_size * 8, reg_index); 2872 2873 if (!reg_context.RegisterOffsetIsDynamic()) 2874 response.Printf("offset=\"%" PRIu32 "\" ", reg_info->byte_offset); 2875 2876 if (reg_info->alt_name && reg_info->alt_name[0]) 2877 response.Printf("altname=\"%s\" ", reg_info->alt_name); 2878 2879 llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info); 2880 if (!encoding.empty()) 2881 response << "encoding=\"" << encoding << "\" "; 2882 2883 llvm::StringRef format = GetFormatNameOrEmpty(*reg_info); 2884 if (!format.empty()) 2885 response << "format=\"" << format << "\" "; 2886 2887 const char *const register_set_name = 2888 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index); 2889 if (register_set_name) 2890 response << "group=\"" << register_set_name << "\" "; 2891 2892 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] != 2893 LLDB_INVALID_REGNUM) 2894 response.Printf("ehframe_regnum=\"%" PRIu32 "\" ", 2895 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]); 2896 2897 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != 2898 LLDB_INVALID_REGNUM) 2899 response.Printf("dwarf_regnum=\"%" PRIu32 "\" ", 2900 reg_info->kinds[RegisterKind::eRegisterKindDWARF]); 2901 2902 llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info); 2903 if (!kind_generic.empty()) 2904 response << "generic=\"" << kind_generic << "\" "; 2905 2906 if (reg_info->value_regs && 2907 reg_info->value_regs[0] != LLDB_INVALID_REGNUM) { 2908 response.PutCString("value_regnums=\""); 2909 CollectRegNums(reg_info->value_regs, response, false); 2910 response.Printf("\" "); 2911 } 2912 2913 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) { 2914 response.PutCString("invalidate_regnums=\""); 2915 CollectRegNums(reg_info->invalidate_regs, response, false); 2916 response.Printf("\" "); 2917 } 2918 2919 if (reg_info->dynamic_size_dwarf_expr_bytes) { 2920 const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len; 2921 response.PutCString("dynamic_size_dwarf_expr_bytes=\""); 2922 for (uint32_t i = 0; i < dwarf_opcode_len; ++i) 2923 response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]); 2924 response.Printf("\" "); 2925 } 2926 2927 response.Printf("/>"); 2928 } 2929 2930 response.Printf("</feature>"); 2931 response.Printf("</target>"); 2932 return MemoryBuffer::getMemBufferCopy(response.GetString(), "target.xml"); 2933 } 2934 2935 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> 2936 GDBRemoteCommunicationServerLLGS::ReadXferObject(llvm::StringRef object, 2937 llvm::StringRef annex) { 2938 // Make sure we have a valid process. 2939 if (!m_current_process || 2940 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2941 return llvm::createStringError(llvm::inconvertibleErrorCode(), 2942 "No process available"); 2943 } 2944 2945 if (object == "auxv") { 2946 // Grab the auxv data. 2947 auto buffer_or_error = m_current_process->GetAuxvData(); 2948 if (!buffer_or_error) 2949 return llvm::errorCodeToError(buffer_or_error.getError()); 2950 return std::move(*buffer_or_error); 2951 } 2952 2953 if (object == "libraries-svr4") { 2954 auto library_list = m_current_process->GetLoadedSVR4Libraries(); 2955 if (!library_list) 2956 return library_list.takeError(); 2957 2958 StreamString response; 2959 response.Printf("<library-list-svr4 version=\"1.0\">"); 2960 for (auto const &library : *library_list) { 2961 response.Printf("<library name=\"%s\" ", 2962 XMLEncodeAttributeValue(library.name.c_str()).c_str()); 2963 response.Printf("lm=\"0x%" PRIx64 "\" ", library.link_map); 2964 response.Printf("l_addr=\"0x%" PRIx64 "\" ", library.base_addr); 2965 response.Printf("l_ld=\"0x%" PRIx64 "\" />", library.ld_addr); 2966 } 2967 response.Printf("</library-list-svr4>"); 2968 return MemoryBuffer::getMemBufferCopy(response.GetString(), __FUNCTION__); 2969 } 2970 2971 if (object == "features" && annex == "target.xml") 2972 return BuildTargetXml(); 2973 2974 return llvm::make_error<UnimplementedError>(); 2975 } 2976 2977 GDBRemoteCommunication::PacketResult 2978 GDBRemoteCommunicationServerLLGS::Handle_qXfer( 2979 StringExtractorGDBRemote &packet) { 2980 SmallVector<StringRef, 5> fields; 2981 // The packet format is "qXfer:<object>:<action>:<annex>:offset,length" 2982 StringRef(packet.GetStringRef()).split(fields, ':', 4); 2983 if (fields.size() != 5) 2984 return SendIllFormedResponse(packet, "malformed qXfer packet"); 2985 StringRef &xfer_object = fields[1]; 2986 StringRef &xfer_action = fields[2]; 2987 StringRef &xfer_annex = fields[3]; 2988 StringExtractor offset_data(fields[4]); 2989 if (xfer_action != "read") 2990 return SendUnimplementedResponse("qXfer action not supported"); 2991 // Parse offset. 2992 const uint64_t xfer_offset = 2993 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max()); 2994 if (xfer_offset == std::numeric_limits<uint64_t>::max()) 2995 return SendIllFormedResponse(packet, "qXfer packet missing offset"); 2996 // Parse out comma. 2997 if (offset_data.GetChar() != ',') 2998 return SendIllFormedResponse(packet, 2999 "qXfer packet missing comma after offset"); 3000 // Parse out the length. 3001 const uint64_t xfer_length = 3002 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max()); 3003 if (xfer_length == std::numeric_limits<uint64_t>::max()) 3004 return SendIllFormedResponse(packet, "qXfer packet missing length"); 3005 3006 // Get a previously constructed buffer if it exists or create it now. 3007 std::string buffer_key = (xfer_object + xfer_action + xfer_annex).str(); 3008 auto buffer_it = m_xfer_buffer_map.find(buffer_key); 3009 if (buffer_it == m_xfer_buffer_map.end()) { 3010 auto buffer_up = ReadXferObject(xfer_object, xfer_annex); 3011 if (!buffer_up) 3012 return SendErrorResponse(buffer_up.takeError()); 3013 buffer_it = m_xfer_buffer_map 3014 .insert(std::make_pair(buffer_key, std::move(*buffer_up))) 3015 .first; 3016 } 3017 3018 // Send back the response 3019 StreamGDBRemote response; 3020 bool done_with_buffer = false; 3021 llvm::StringRef buffer = buffer_it->second->getBuffer(); 3022 if (xfer_offset >= buffer.size()) { 3023 // We have nothing left to send. Mark the buffer as complete. 3024 response.PutChar('l'); 3025 done_with_buffer = true; 3026 } else { 3027 // Figure out how many bytes are available starting at the given offset. 3028 buffer = buffer.drop_front(xfer_offset); 3029 // Mark the response type according to whether we're reading the remainder 3030 // of the data. 3031 if (xfer_length >= buffer.size()) { 3032 // There will be nothing left to read after this 3033 response.PutChar('l'); 3034 done_with_buffer = true; 3035 } else { 3036 // There will still be bytes to read after this request. 3037 response.PutChar('m'); 3038 buffer = buffer.take_front(xfer_length); 3039 } 3040 // Now write the data in encoded binary form. 3041 response.PutEscapedBytes(buffer.data(), buffer.size()); 3042 } 3043 3044 if (done_with_buffer) 3045 m_xfer_buffer_map.erase(buffer_it); 3046 3047 return SendPacketNoLock(response.GetString()); 3048 } 3049 3050 GDBRemoteCommunication::PacketResult 3051 GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState( 3052 StringExtractorGDBRemote &packet) { 3053 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 3054 3055 // Move past packet name. 3056 packet.SetFilePos(strlen("QSaveRegisterState")); 3057 3058 // Get the thread to use. 3059 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 3060 if (!thread) { 3061 if (m_thread_suffix_supported) 3062 return SendIllFormedResponse( 3063 packet, "No thread specified in QSaveRegisterState packet"); 3064 else 3065 return SendIllFormedResponse(packet, 3066 "No thread was is set with the Hg packet"); 3067 } 3068 3069 // Grab the register context for the thread. 3070 NativeRegisterContext& reg_context = thread->GetRegisterContext(); 3071 3072 // Save registers to a buffer. 3073 DataBufferSP register_data_sp; 3074 Status error = reg_context.ReadAllRegisterValues(register_data_sp); 3075 if (error.Fail()) { 3076 LLDB_LOG(log, "pid {0} failed to save all register values: {1}", 3077 m_current_process->GetID(), error); 3078 return SendErrorResponse(0x75); 3079 } 3080 3081 // Allocate a new save id. 3082 const uint32_t save_id = GetNextSavedRegistersID(); 3083 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) && 3084 "GetNextRegisterSaveID() returned an existing register save id"); 3085 3086 // Save the register data buffer under the save id. 3087 { 3088 std::lock_guard<std::mutex> guard(m_saved_registers_mutex); 3089 m_saved_registers_map[save_id] = register_data_sp; 3090 } 3091 3092 // Write the response. 3093 StreamGDBRemote response; 3094 response.Printf("%" PRIu32, save_id); 3095 return SendPacketNoLock(response.GetString()); 3096 } 3097 3098 GDBRemoteCommunication::PacketResult 3099 GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState( 3100 StringExtractorGDBRemote &packet) { 3101 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 3102 3103 // Parse out save id. 3104 packet.SetFilePos(strlen("QRestoreRegisterState:")); 3105 if (packet.GetBytesLeft() < 1) 3106 return SendIllFormedResponse( 3107 packet, "QRestoreRegisterState packet missing register save id"); 3108 3109 const uint32_t save_id = packet.GetU32(0); 3110 if (save_id == 0) { 3111 LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, " 3112 "expecting decimal uint32_t"); 3113 return SendErrorResponse(0x76); 3114 } 3115 3116 // Get the thread to use. 3117 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 3118 if (!thread) { 3119 if (m_thread_suffix_supported) 3120 return SendIllFormedResponse( 3121 packet, "No thread specified in QRestoreRegisterState packet"); 3122 else 3123 return SendIllFormedResponse(packet, 3124 "No thread was is set with the Hg packet"); 3125 } 3126 3127 // Grab the register context for the thread. 3128 NativeRegisterContext ®_context = thread->GetRegisterContext(); 3129 3130 // Retrieve register state buffer, then remove from the list. 3131 DataBufferSP register_data_sp; 3132 { 3133 std::lock_guard<std::mutex> guard(m_saved_registers_mutex); 3134 3135 // Find the register set buffer for the given save id. 3136 auto it = m_saved_registers_map.find(save_id); 3137 if (it == m_saved_registers_map.end()) { 3138 LLDB_LOG(log, 3139 "pid {0} does not have a register set save buffer for id {1}", 3140 m_current_process->GetID(), save_id); 3141 return SendErrorResponse(0x77); 3142 } 3143 register_data_sp = it->second; 3144 3145 // Remove it from the map. 3146 m_saved_registers_map.erase(it); 3147 } 3148 3149 Status error = reg_context.WriteAllRegisterValues(register_data_sp); 3150 if (error.Fail()) { 3151 LLDB_LOG(log, "pid {0} failed to restore all register values: {1}", 3152 m_current_process->GetID(), error); 3153 return SendErrorResponse(0x77); 3154 } 3155 3156 return SendOKResponse(); 3157 } 3158 3159 GDBRemoteCommunication::PacketResult 3160 GDBRemoteCommunicationServerLLGS::Handle_vAttach( 3161 StringExtractorGDBRemote &packet) { 3162 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3163 3164 // Consume the ';' after vAttach. 3165 packet.SetFilePos(strlen("vAttach")); 3166 if (!packet.GetBytesLeft() || packet.GetChar() != ';') 3167 return SendIllFormedResponse(packet, "vAttach missing expected ';'"); 3168 3169 // Grab the PID to which we will attach (assume hex encoding). 3170 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16); 3171 if (pid == LLDB_INVALID_PROCESS_ID) 3172 return SendIllFormedResponse(packet, 3173 "vAttach failed to parse the process id"); 3174 3175 // Attempt to attach. 3176 LLDB_LOGF(log, 3177 "GDBRemoteCommunicationServerLLGS::%s attempting to attach to " 3178 "pid %" PRIu64, 3179 __FUNCTION__, pid); 3180 3181 Status error = AttachToProcess(pid); 3182 3183 if (error.Fail()) { 3184 LLDB_LOGF(log, 3185 "GDBRemoteCommunicationServerLLGS::%s failed to attach to " 3186 "pid %" PRIu64 ": %s\n", 3187 __FUNCTION__, pid, error.AsCString()); 3188 return SendErrorResponse(error); 3189 } 3190 3191 // Notify we attached by sending a stop packet. 3192 return SendStopReasonForState(m_current_process->GetState()); 3193 } 3194 3195 GDBRemoteCommunication::PacketResult 3196 GDBRemoteCommunicationServerLLGS::Handle_vAttachWait( 3197 StringExtractorGDBRemote &packet) { 3198 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3199 3200 // Consume the ';' after the identifier. 3201 packet.SetFilePos(strlen("vAttachWait")); 3202 3203 if (!packet.GetBytesLeft() || packet.GetChar() != ';') 3204 return SendIllFormedResponse(packet, "vAttachWait missing expected ';'"); 3205 3206 // Allocate the buffer for the process name from vAttachWait. 3207 std::string process_name; 3208 if (!packet.GetHexByteString(process_name)) 3209 return SendIllFormedResponse(packet, 3210 "vAttachWait failed to parse process name"); 3211 3212 LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name); 3213 3214 Status error = AttachWaitProcess(process_name, false); 3215 if (error.Fail()) { 3216 LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name, 3217 error); 3218 return SendErrorResponse(error); 3219 } 3220 3221 // Notify we attached by sending a stop packet. 3222 return SendStopReasonForState(m_current_process->GetState()); 3223 } 3224 3225 GDBRemoteCommunication::PacketResult 3226 GDBRemoteCommunicationServerLLGS::Handle_qVAttachOrWaitSupported( 3227 StringExtractorGDBRemote &packet) { 3228 return SendOKResponse(); 3229 } 3230 3231 GDBRemoteCommunication::PacketResult 3232 GDBRemoteCommunicationServerLLGS::Handle_vAttachOrWait( 3233 StringExtractorGDBRemote &packet) { 3234 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3235 3236 // Consume the ';' after the identifier. 3237 packet.SetFilePos(strlen("vAttachOrWait")); 3238 3239 if (!packet.GetBytesLeft() || packet.GetChar() != ';') 3240 return SendIllFormedResponse(packet, "vAttachOrWait missing expected ';'"); 3241 3242 // Allocate the buffer for the process name from vAttachWait. 3243 std::string process_name; 3244 if (!packet.GetHexByteString(process_name)) 3245 return SendIllFormedResponse(packet, 3246 "vAttachOrWait failed to parse process name"); 3247 3248 LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name); 3249 3250 Status error = AttachWaitProcess(process_name, true); 3251 if (error.Fail()) { 3252 LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name, 3253 error); 3254 return SendErrorResponse(error); 3255 } 3256 3257 // Notify we attached by sending a stop packet. 3258 return SendStopReasonForState(m_current_process->GetState()); 3259 } 3260 3261 GDBRemoteCommunication::PacketResult 3262 GDBRemoteCommunicationServerLLGS::Handle_vRun( 3263 StringExtractorGDBRemote &packet) { 3264 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3265 3266 llvm::StringRef s = packet.GetStringRef(); 3267 if (!s.consume_front("vRun;")) 3268 return SendErrorResponse(8); 3269 3270 llvm::SmallVector<llvm::StringRef, 16> argv; 3271 s.split(argv, ';'); 3272 3273 for (llvm::StringRef hex_arg : argv) { 3274 StringExtractor arg_ext{hex_arg}; 3275 std::string arg; 3276 arg_ext.GetHexByteString(arg); 3277 m_process_launch_info.GetArguments().AppendArgument(arg); 3278 LLDB_LOGF(log, "LLGSPacketHandler::%s added arg: \"%s\"", __FUNCTION__, 3279 arg.c_str()); 3280 } 3281 3282 if (!argv.empty()) { 3283 m_process_launch_info.GetExecutableFile().SetFile( 3284 m_process_launch_info.GetArguments()[0].ref(), FileSpec::Style::native); 3285 m_process_launch_error = LaunchProcess(); 3286 if (m_process_launch_error.Success()) 3287 return SendStopReasonForState(m_current_process->GetState()); 3288 LLDB_LOG(log, "failed to launch exe: {0}", m_process_launch_error); 3289 } 3290 return SendErrorResponse(8); 3291 } 3292 3293 GDBRemoteCommunication::PacketResult 3294 GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) { 3295 StopSTDIOForwarding(); 3296 3297 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; 3298 3299 // Consume the ';' after D. 3300 packet.SetFilePos(1); 3301 if (packet.GetBytesLeft()) { 3302 if (packet.GetChar() != ';') 3303 return SendIllFormedResponse(packet, "D missing expected ';'"); 3304 3305 // Grab the PID from which we will detach (assume hex encoding). 3306 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16); 3307 if (pid == LLDB_INVALID_PROCESS_ID) 3308 return SendIllFormedResponse(packet, "D failed to parse the process id"); 3309 } 3310 3311 // Detach forked children if their PID was specified *or* no PID was requested 3312 // (i.e. detach-all packet). 3313 llvm::Error detach_error = llvm::Error::success(); 3314 bool detached = false; 3315 for (auto it = m_debugged_processes.begin(); 3316 it != m_debugged_processes.end();) { 3317 if (pid == LLDB_INVALID_PROCESS_ID || pid == it->first) { 3318 if (llvm::Error e = it->second->Detach().ToError()) 3319 detach_error = llvm::joinErrors(std::move(detach_error), std::move(e)); 3320 else { 3321 if (it->second.get() == m_current_process) 3322 m_current_process = nullptr; 3323 if (it->second.get() == m_continue_process) 3324 m_continue_process = nullptr; 3325 it = m_debugged_processes.erase(it); 3326 detached = true; 3327 continue; 3328 } 3329 } 3330 ++it; 3331 } 3332 3333 if (detach_error) 3334 return SendErrorResponse(std::move(detach_error)); 3335 if (!detached) 3336 return SendErrorResponse(Status("PID %" PRIu64 " not traced", pid)); 3337 return SendOKResponse(); 3338 } 3339 3340 GDBRemoteCommunication::PacketResult 3341 GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo( 3342 StringExtractorGDBRemote &packet) { 3343 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 3344 3345 packet.SetFilePos(strlen("qThreadStopInfo")); 3346 const lldb::tid_t tid = packet.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID); 3347 if (tid == LLDB_INVALID_THREAD_ID) { 3348 LLDB_LOGF(log, 3349 "GDBRemoteCommunicationServerLLGS::%s failed, could not " 3350 "parse thread id from request \"%s\"", 3351 __FUNCTION__, packet.GetStringRef().data()); 3352 return SendErrorResponse(0x15); 3353 } 3354 return SendStopReplyPacketForThread(tid); 3355 } 3356 3357 GDBRemoteCommunication::PacketResult 3358 GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo( 3359 StringExtractorGDBRemote &) { 3360 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 3361 3362 // Ensure we have a debugged process. 3363 if (!m_current_process || 3364 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 3365 return SendErrorResponse(50); 3366 LLDB_LOG(log, "preparing packet for pid {0}", m_current_process->GetID()); 3367 3368 StreamString response; 3369 const bool threads_with_valid_stop_info_only = false; 3370 llvm::Expected<json::Value> threads_info = 3371 GetJSONThreadsInfo(*m_current_process, threads_with_valid_stop_info_only); 3372 if (!threads_info) { 3373 LLDB_LOG_ERROR(log, threads_info.takeError(), 3374 "failed to prepare a packet for pid {1}: {0}", 3375 m_current_process->GetID()); 3376 return SendErrorResponse(52); 3377 } 3378 3379 response.AsRawOstream() << *threads_info; 3380 StreamGDBRemote escaped_response; 3381 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize()); 3382 return SendPacketNoLock(escaped_response.GetString()); 3383 } 3384 3385 GDBRemoteCommunication::PacketResult 3386 GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo( 3387 StringExtractorGDBRemote &packet) { 3388 // Fail if we don't have a current process. 3389 if (!m_current_process || 3390 m_current_process->GetID() == LLDB_INVALID_PROCESS_ID) 3391 return SendErrorResponse(68); 3392 3393 packet.SetFilePos(strlen("qWatchpointSupportInfo")); 3394 if (packet.GetBytesLeft() == 0) 3395 return SendOKResponse(); 3396 if (packet.GetChar() != ':') 3397 return SendErrorResponse(67); 3398 3399 auto hw_debug_cap = m_current_process->GetHardwareDebugSupportInfo(); 3400 3401 StreamGDBRemote response; 3402 if (hw_debug_cap == llvm::None) 3403 response.Printf("num:0;"); 3404 else 3405 response.Printf("num:%d;", hw_debug_cap->second); 3406 3407 return SendPacketNoLock(response.GetString()); 3408 } 3409 3410 GDBRemoteCommunication::PacketResult 3411 GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress( 3412 StringExtractorGDBRemote &packet) { 3413 // Fail if we don't have a current process. 3414 if (!m_current_process || 3415 m_current_process->GetID() == LLDB_INVALID_PROCESS_ID) 3416 return SendErrorResponse(67); 3417 3418 packet.SetFilePos(strlen("qFileLoadAddress:")); 3419 if (packet.GetBytesLeft() == 0) 3420 return SendErrorResponse(68); 3421 3422 std::string file_name; 3423 packet.GetHexByteString(file_name); 3424 3425 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS; 3426 Status error = 3427 m_current_process->GetFileLoadAddress(file_name, file_load_address); 3428 if (error.Fail()) 3429 return SendErrorResponse(69); 3430 3431 if (file_load_address == LLDB_INVALID_ADDRESS) 3432 return SendErrorResponse(1); // File not loaded 3433 3434 StreamGDBRemote response; 3435 response.PutHex64(file_load_address); 3436 return SendPacketNoLock(response.GetString()); 3437 } 3438 3439 GDBRemoteCommunication::PacketResult 3440 GDBRemoteCommunicationServerLLGS::Handle_QPassSignals( 3441 StringExtractorGDBRemote &packet) { 3442 std::vector<int> signals; 3443 packet.SetFilePos(strlen("QPassSignals:")); 3444 3445 // Read sequence of hex signal numbers divided by a semicolon and optionally 3446 // spaces. 3447 while (packet.GetBytesLeft() > 0) { 3448 int signal = packet.GetS32(-1, 16); 3449 if (signal < 0) 3450 return SendIllFormedResponse(packet, "Failed to parse signal number."); 3451 signals.push_back(signal); 3452 3453 packet.SkipSpaces(); 3454 char separator = packet.GetChar(); 3455 if (separator == '\0') 3456 break; // End of string 3457 if (separator != ';') 3458 return SendIllFormedResponse(packet, "Invalid separator," 3459 " expected semicolon."); 3460 } 3461 3462 // Fail if we don't have a current process. 3463 if (!m_current_process) 3464 return SendErrorResponse(68); 3465 3466 Status error = m_current_process->IgnoreSignals(signals); 3467 if (error.Fail()) 3468 return SendErrorResponse(69); 3469 3470 return SendOKResponse(); 3471 } 3472 3473 GDBRemoteCommunication::PacketResult 3474 GDBRemoteCommunicationServerLLGS::Handle_qMemTags( 3475 StringExtractorGDBRemote &packet) { 3476 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3477 3478 // Ensure we have a process. 3479 if (!m_current_process || 3480 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 3481 LLDB_LOGF( 3482 log, 3483 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 3484 __FUNCTION__); 3485 return SendErrorResponse(1); 3486 } 3487 3488 // We are expecting 3489 // qMemTags:<hex address>,<hex length>:<hex type> 3490 3491 // Address 3492 packet.SetFilePos(strlen("qMemTags:")); 3493 const char *current_char = packet.Peek(); 3494 if (!current_char || *current_char == ',') 3495 return SendIllFormedResponse(packet, "Missing address in qMemTags packet"); 3496 const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0); 3497 3498 // Length 3499 char previous_char = packet.GetChar(); 3500 current_char = packet.Peek(); 3501 // If we don't have a separator or the length field is empty 3502 if (previous_char != ',' || (current_char && *current_char == ':')) 3503 return SendIllFormedResponse(packet, 3504 "Invalid addr,length pair in qMemTags packet"); 3505 3506 if (packet.GetBytesLeft() < 1) 3507 return SendIllFormedResponse( 3508 packet, "Too short qMemtags: packet (looking for length)"); 3509 const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0); 3510 3511 // Type 3512 const char *invalid_type_err = "Invalid type field in qMemTags: packet"; 3513 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':') 3514 return SendIllFormedResponse(packet, invalid_type_err); 3515 3516 // Type is a signed integer but packed into the packet as its raw bytes. 3517 // However, our GetU64 uses strtoull which allows +/-. We do not want this. 3518 const char *first_type_char = packet.Peek(); 3519 if (first_type_char && (*first_type_char == '+' || *first_type_char == '-')) 3520 return SendIllFormedResponse(packet, invalid_type_err); 3521 3522 // Extract type as unsigned then cast to signed. 3523 // Using a uint64_t here so that we have some value outside of the 32 bit 3524 // range to use as the invalid return value. 3525 uint64_t raw_type = 3526 packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16); 3527 3528 if ( // Make sure the cast below would be valid 3529 raw_type > std::numeric_limits<uint32_t>::max() || 3530 // To catch inputs like "123aardvark" that will parse but clearly aren't 3531 // valid in this case. 3532 packet.GetBytesLeft()) { 3533 return SendIllFormedResponse(packet, invalid_type_err); 3534 } 3535 3536 // First narrow to 32 bits otherwise the copy into type would take 3537 // the wrong 4 bytes on big endian. 3538 uint32_t raw_type_32 = raw_type; 3539 int32_t type = reinterpret_cast<int32_t &>(raw_type_32); 3540 3541 StreamGDBRemote response; 3542 std::vector<uint8_t> tags; 3543 Status error = m_current_process->ReadMemoryTags(type, addr, length, tags); 3544 if (error.Fail()) 3545 return SendErrorResponse(1); 3546 3547 // This m is here in case we want to support multi part replies in the future. 3548 // In the same manner as qfThreadInfo/qsThreadInfo. 3549 response.PutChar('m'); 3550 response.PutBytesAsRawHex8(tags.data(), tags.size()); 3551 return SendPacketNoLock(response.GetString()); 3552 } 3553 3554 GDBRemoteCommunication::PacketResult 3555 GDBRemoteCommunicationServerLLGS::Handle_QMemTags( 3556 StringExtractorGDBRemote &packet) { 3557 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3558 3559 // Ensure we have a process. 3560 if (!m_current_process || 3561 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 3562 LLDB_LOGF( 3563 log, 3564 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 3565 __FUNCTION__); 3566 return SendErrorResponse(1); 3567 } 3568 3569 // We are expecting 3570 // QMemTags:<hex address>,<hex length>:<hex type>:<tags as hex bytes> 3571 3572 // Address 3573 packet.SetFilePos(strlen("QMemTags:")); 3574 const char *current_char = packet.Peek(); 3575 if (!current_char || *current_char == ',') 3576 return SendIllFormedResponse(packet, "Missing address in QMemTags packet"); 3577 const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0); 3578 3579 // Length 3580 char previous_char = packet.GetChar(); 3581 current_char = packet.Peek(); 3582 // If we don't have a separator or the length field is empty 3583 if (previous_char != ',' || (current_char && *current_char == ':')) 3584 return SendIllFormedResponse(packet, 3585 "Invalid addr,length pair in QMemTags packet"); 3586 3587 if (packet.GetBytesLeft() < 1) 3588 return SendIllFormedResponse( 3589 packet, "Too short QMemtags: packet (looking for length)"); 3590 const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0); 3591 3592 // Type 3593 const char *invalid_type_err = "Invalid type field in QMemTags: packet"; 3594 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':') 3595 return SendIllFormedResponse(packet, invalid_type_err); 3596 3597 // Our GetU64 uses strtoull which allows leading +/-, we don't want that. 3598 const char *first_type_char = packet.Peek(); 3599 if (first_type_char && (*first_type_char == '+' || *first_type_char == '-')) 3600 return SendIllFormedResponse(packet, invalid_type_err); 3601 3602 // The type is a signed integer but is in the packet as its raw bytes. 3603 // So parse first as unsigned then cast to signed later. 3604 // We extract to 64 bit, even though we only expect 32, so that we've 3605 // got some invalid value we can check for. 3606 uint64_t raw_type = 3607 packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16); 3608 if (raw_type > std::numeric_limits<uint32_t>::max()) 3609 return SendIllFormedResponse(packet, invalid_type_err); 3610 3611 // First narrow to 32 bits. Otherwise the copy below would get the wrong 3612 // 4 bytes on big endian. 3613 uint32_t raw_type_32 = raw_type; 3614 int32_t type = reinterpret_cast<int32_t &>(raw_type_32); 3615 3616 // Tag data 3617 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':') 3618 return SendIllFormedResponse(packet, 3619 "Missing tag data in QMemTags: packet"); 3620 3621 // Must be 2 chars per byte 3622 const char *invalid_data_err = "Invalid tag data in QMemTags: packet"; 3623 if (packet.GetBytesLeft() % 2) 3624 return SendIllFormedResponse(packet, invalid_data_err); 3625 3626 // This is bytes here and is unpacked into target specific tags later 3627 // We cannot assume that number of bytes == length here because the server 3628 // can repeat tags to fill a given range. 3629 std::vector<uint8_t> tag_data; 3630 // Zero length writes will not have any tag data 3631 // (but we pass them on because it will still check that tagging is enabled) 3632 if (packet.GetBytesLeft()) { 3633 size_t byte_count = packet.GetBytesLeft() / 2; 3634 tag_data.resize(byte_count); 3635 size_t converted_bytes = packet.GetHexBytes(tag_data, 0); 3636 if (converted_bytes != byte_count) { 3637 return SendIllFormedResponse(packet, invalid_data_err); 3638 } 3639 } 3640 3641 Status status = 3642 m_current_process->WriteMemoryTags(type, addr, length, tag_data); 3643 return status.Success() ? SendOKResponse() : SendErrorResponse(1); 3644 } 3645 3646 GDBRemoteCommunication::PacketResult 3647 GDBRemoteCommunicationServerLLGS::Handle_qSaveCore( 3648 StringExtractorGDBRemote &packet) { 3649 // Fail if we don't have a current process. 3650 if (!m_current_process || 3651 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 3652 return SendErrorResponse(Status("Process not running.")); 3653 3654 std::string path_hint; 3655 3656 StringRef packet_str{packet.GetStringRef()}; 3657 assert(packet_str.startswith("qSaveCore")); 3658 if (packet_str.consume_front("qSaveCore;")) { 3659 llvm::SmallVector<llvm::StringRef, 2> fields; 3660 packet_str.split(fields, ';'); 3661 3662 for (auto x : fields) { 3663 if (x.consume_front("path-hint:")) 3664 StringExtractor(x).GetHexByteString(path_hint); 3665 else 3666 return SendErrorResponse(Status("Unsupported qSaveCore option")); 3667 } 3668 } 3669 3670 llvm::Expected<std::string> ret = m_current_process->SaveCore(path_hint); 3671 if (!ret) 3672 return SendErrorResponse(ret.takeError()); 3673 3674 StreamString response; 3675 response.PutCString("core-path:"); 3676 response.PutStringAsRawHex8(ret.get()); 3677 return SendPacketNoLock(response.GetString()); 3678 } 3679 3680 void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() { 3681 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3682 3683 // Tell the stdio connection to shut down. 3684 if (m_stdio_communication.IsConnected()) { 3685 auto connection = m_stdio_communication.GetConnection(); 3686 if (connection) { 3687 Status error; 3688 connection->Disconnect(&error); 3689 3690 if (error.Success()) { 3691 LLDB_LOGF(log, 3692 "GDBRemoteCommunicationServerLLGS::%s disconnect process " 3693 "terminal stdio - SUCCESS", 3694 __FUNCTION__); 3695 } else { 3696 LLDB_LOGF(log, 3697 "GDBRemoteCommunicationServerLLGS::%s disconnect process " 3698 "terminal stdio - FAIL: %s", 3699 __FUNCTION__, error.AsCString()); 3700 } 3701 } 3702 } 3703 } 3704 3705 NativeThreadProtocol *GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix( 3706 StringExtractorGDBRemote &packet) { 3707 // We have no thread if we don't have a process. 3708 if (!m_current_process || 3709 m_current_process->GetID() == LLDB_INVALID_PROCESS_ID) 3710 return nullptr; 3711 3712 // If the client hasn't asked for thread suffix support, there will not be a 3713 // thread suffix. Use the current thread in that case. 3714 if (!m_thread_suffix_supported) { 3715 const lldb::tid_t current_tid = GetCurrentThreadID(); 3716 if (current_tid == LLDB_INVALID_THREAD_ID) 3717 return nullptr; 3718 else if (current_tid == 0) { 3719 // Pick a thread. 3720 return m_current_process->GetThreadAtIndex(0); 3721 } else 3722 return m_current_process->GetThreadByID(current_tid); 3723 } 3724 3725 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 3726 3727 // Parse out the ';'. 3728 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') { 3729 LLDB_LOGF(log, 3730 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse " 3731 "error: expected ';' prior to start of thread suffix: packet " 3732 "contents = '%s'", 3733 __FUNCTION__, packet.GetStringRef().data()); 3734 return nullptr; 3735 } 3736 3737 if (!packet.GetBytesLeft()) 3738 return nullptr; 3739 3740 // Parse out thread: portion. 3741 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) { 3742 LLDB_LOGF(log, 3743 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse " 3744 "error: expected 'thread:' but not found, packet contents = " 3745 "'%s'", 3746 __FUNCTION__, packet.GetStringRef().data()); 3747 return nullptr; 3748 } 3749 packet.SetFilePos(packet.GetFilePos() + strlen("thread:")); 3750 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0); 3751 if (tid != 0) 3752 return m_current_process->GetThreadByID(tid); 3753 3754 return nullptr; 3755 } 3756 3757 lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const { 3758 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) { 3759 // Use whatever the debug process says is the current thread id since the 3760 // protocol either didn't specify or specified we want any/all threads 3761 // marked as the current thread. 3762 if (!m_current_process) 3763 return LLDB_INVALID_THREAD_ID; 3764 return m_current_process->GetCurrentThreadID(); 3765 } 3766 // Use the specific current thread id set by the gdb remote protocol. 3767 return m_current_tid; 3768 } 3769 3770 uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() { 3771 std::lock_guard<std::mutex> guard(m_saved_registers_mutex); 3772 return m_next_saved_registers_id++; 3773 } 3774 3775 void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() { 3776 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3777 3778 LLDB_LOG(log, "clearing {0} xfer buffers", m_xfer_buffer_map.size()); 3779 m_xfer_buffer_map.clear(); 3780 } 3781 3782 FileSpec 3783 GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path, 3784 const ArchSpec &arch) { 3785 if (m_current_process) { 3786 FileSpec file_spec; 3787 if (m_current_process 3788 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec) 3789 .Success()) { 3790 if (FileSystem::Instance().Exists(file_spec)) 3791 return file_spec; 3792 } 3793 } 3794 3795 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch); 3796 } 3797 3798 std::string GDBRemoteCommunicationServerLLGS::XMLEncodeAttributeValue( 3799 llvm::StringRef value) { 3800 std::string result; 3801 for (const char &c : value) { 3802 switch (c) { 3803 case '\'': 3804 result += "'"; 3805 break; 3806 case '"': 3807 result += """; 3808 break; 3809 case '<': 3810 result += "<"; 3811 break; 3812 case '>': 3813 result += ">"; 3814 break; 3815 default: 3816 result += c; 3817 break; 3818 } 3819 } 3820 return result; 3821 } 3822 3823 llvm::Expected<lldb::tid_t> GDBRemoteCommunicationServerLLGS::ReadTid( 3824 StringExtractorGDBRemote &packet, bool allow_all, lldb::pid_t default_pid) { 3825 assert(m_current_process); 3826 assert(m_current_process->GetID() != LLDB_INVALID_PROCESS_ID); 3827 3828 auto pid_tid = packet.GetPidTid(default_pid); 3829 if (!pid_tid) 3830 return llvm::make_error<StringError>(inconvertibleErrorCode(), 3831 "Malformed thread-id"); 3832 3833 lldb::pid_t pid = pid_tid->first; 3834 lldb::tid_t tid = pid_tid->second; 3835 3836 if (!allow_all && pid == StringExtractorGDBRemote::AllProcesses) 3837 return llvm::make_error<StringError>( 3838 inconvertibleErrorCode(), 3839 llvm::formatv("PID value {0} not allowed", pid == 0 ? 0 : -1)); 3840 3841 if (!allow_all && tid == StringExtractorGDBRemote::AllThreads) 3842 return llvm::make_error<StringError>( 3843 inconvertibleErrorCode(), 3844 llvm::formatv("TID value {0} not allowed", tid == 0 ? 0 : -1)); 3845 3846 if (pid != StringExtractorGDBRemote::AllProcesses) { 3847 if (pid != m_current_process->GetID()) 3848 return llvm::make_error<StringError>( 3849 inconvertibleErrorCode(), llvm::formatv("PID {0} not debugged", pid)); 3850 } 3851 3852 return tid; 3853 } 3854 3855 std::vector<std::string> GDBRemoteCommunicationServerLLGS::HandleFeatures( 3856 const llvm::ArrayRef<llvm::StringRef> client_features) { 3857 std::vector<std::string> ret = 3858 GDBRemoteCommunicationServerCommon::HandleFeatures(client_features); 3859 ret.insert(ret.end(), { 3860 "QThreadSuffixSupported+", 3861 "QListThreadsInStopReply+", 3862 "qXfer:features:read+", 3863 }); 3864 3865 // report server-only features 3866 using Extension = NativeProcessProtocol::Extension; 3867 Extension plugin_features = m_process_factory.GetSupportedExtensions(); 3868 if (bool(plugin_features & Extension::pass_signals)) 3869 ret.push_back("QPassSignals+"); 3870 if (bool(plugin_features & Extension::auxv)) 3871 ret.push_back("qXfer:auxv:read+"); 3872 if (bool(plugin_features & Extension::libraries_svr4)) 3873 ret.push_back("qXfer:libraries-svr4:read+"); 3874 if (bool(plugin_features & Extension::memory_tagging)) 3875 ret.push_back("memory-tagging+"); 3876 if (bool(plugin_features & Extension::savecore)) 3877 ret.push_back("qSaveCore+"); 3878 3879 // check for client features 3880 m_extensions_supported = {}; 3881 for (llvm::StringRef x : client_features) 3882 m_extensions_supported |= 3883 llvm::StringSwitch<Extension>(x) 3884 .Case("multiprocess+", Extension::multiprocess) 3885 .Case("fork-events+", Extension::fork) 3886 .Case("vfork-events+", Extension::vfork) 3887 .Default({}); 3888 3889 m_extensions_supported &= plugin_features; 3890 3891 // fork & vfork require multiprocess 3892 if (!bool(m_extensions_supported & Extension::multiprocess)) 3893 m_extensions_supported &= ~(Extension::fork | Extension::vfork); 3894 3895 // report only if actually supported 3896 if (bool(m_extensions_supported & Extension::multiprocess)) 3897 ret.push_back("multiprocess+"); 3898 if (bool(m_extensions_supported & Extension::fork)) 3899 ret.push_back("fork-events+"); 3900 if (bool(m_extensions_supported & Extension::vfork)) 3901 ret.push_back("vfork-events+"); 3902 3903 for (auto &x : m_debugged_processes) 3904 SetEnabledExtensions(*x.second); 3905 return ret; 3906 } 3907 3908 void GDBRemoteCommunicationServerLLGS::SetEnabledExtensions( 3909 NativeProcessProtocol &process) { 3910 NativeProcessProtocol::Extension flags = m_extensions_supported; 3911 assert(!bool(flags & ~m_process_factory.GetSupportedExtensions())); 3912 process.SetEnabledExtensions(flags); 3913 } 3914