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