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