1 //===-- GDBRemoteCommunicationServerLLGS.cpp --------------------*- C++ -*-===// 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 <errno.h> 10 11 #include "lldb/Host/Config.h" 12 13 #include "GDBRemoteCommunicationServerLLGS.h" 14 #include "lldb/Utility/StreamGDBRemote.h" 15 16 #include <chrono> 17 #include <cstring> 18 #include <thread> 19 20 #include "lldb/Host/ConnectionFileDescriptor.h" 21 #include "lldb/Host/Debug.h" 22 #include "lldb/Host/File.h" 23 #include "lldb/Host/FileAction.h" 24 #include "lldb/Host/FileSystem.h" 25 #include "lldb/Host/Host.h" 26 #include "lldb/Host/HostInfo.h" 27 #include "lldb/Host/PosixApi.h" 28 #include "lldb/Host/common/NativeProcessProtocol.h" 29 #include "lldb/Host/common/NativeRegisterContext.h" 30 #include "lldb/Host/common/NativeThreadProtocol.h" 31 #include "lldb/Target/MemoryRegionInfo.h" 32 #include "lldb/Utility/Args.h" 33 #include "lldb/Utility/DataBuffer.h" 34 #include "lldb/Utility/Endian.h" 35 #include "lldb/Utility/JSON.h" 36 #include "lldb/Utility/LLDBAssert.h" 37 #include "lldb/Utility/Log.h" 38 #include "lldb/Utility/RegisterValue.h" 39 #include "lldb/Utility/State.h" 40 #include "lldb/Utility/StreamString.h" 41 #include "lldb/Utility/UriParser.h" 42 #include "llvm/ADT/Triple.h" 43 #include "llvm/Support/ScopedPrinter.h" 44 45 #include "ProcessGDBRemote.h" 46 #include "ProcessGDBRemoteLog.h" 47 #include "lldb/Utility/StringExtractorGDBRemote.h" 48 49 using namespace lldb; 50 using namespace lldb_private; 51 using namespace lldb_private::process_gdb_remote; 52 using namespace llvm; 53 54 // GDBRemote Errors 55 56 namespace { 57 enum GDBRemoteServerError { 58 // Set to the first unused error number in literal form below 59 eErrorFirst = 29, 60 eErrorNoProcess = eErrorFirst, 61 eErrorResume, 62 eErrorExitStatus 63 }; 64 } 65 66 // GDBRemoteCommunicationServerLLGS constructor 67 GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS( 68 MainLoop &mainloop, const NativeProcessProtocol::Factory &process_factory) 69 : GDBRemoteCommunicationServerCommon("gdb-remote.server", 70 "gdb-remote.server.rx_packet"), 71 m_mainloop(mainloop), m_process_factory(process_factory), 72 m_stdio_communication("process.stdio") { 73 RegisterPacketHandlers(); 74 } 75 76 void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() { 77 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C, 78 &GDBRemoteCommunicationServerLLGS::Handle_C); 79 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c, 80 &GDBRemoteCommunicationServerLLGS::Handle_c); 81 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D, 82 &GDBRemoteCommunicationServerLLGS::Handle_D); 83 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H, 84 &GDBRemoteCommunicationServerLLGS::Handle_H); 85 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I, 86 &GDBRemoteCommunicationServerLLGS::Handle_I); 87 RegisterMemberFunctionHandler( 88 StringExtractorGDBRemote::eServerPacketType_interrupt, 89 &GDBRemoteCommunicationServerLLGS::Handle_interrupt); 90 RegisterMemberFunctionHandler( 91 StringExtractorGDBRemote::eServerPacketType_m, 92 &GDBRemoteCommunicationServerLLGS::Handle_memory_read); 93 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M, 94 &GDBRemoteCommunicationServerLLGS::Handle_M); 95 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p, 96 &GDBRemoteCommunicationServerLLGS::Handle_p); 97 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P, 98 &GDBRemoteCommunicationServerLLGS::Handle_P); 99 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC, 100 &GDBRemoteCommunicationServerLLGS::Handle_qC); 101 RegisterMemberFunctionHandler( 102 StringExtractorGDBRemote::eServerPacketType_qfThreadInfo, 103 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo); 104 RegisterMemberFunctionHandler( 105 StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress, 106 &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress); 107 RegisterMemberFunctionHandler( 108 StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir, 109 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir); 110 RegisterMemberFunctionHandler( 111 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo, 112 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo); 113 RegisterMemberFunctionHandler( 114 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported, 115 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported); 116 RegisterMemberFunctionHandler( 117 StringExtractorGDBRemote::eServerPacketType_qProcessInfo, 118 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo); 119 RegisterMemberFunctionHandler( 120 StringExtractorGDBRemote::eServerPacketType_qRegisterInfo, 121 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo); 122 RegisterMemberFunctionHandler( 123 StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState, 124 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState); 125 RegisterMemberFunctionHandler( 126 StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState, 127 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState); 128 RegisterMemberFunctionHandler( 129 StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR, 130 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR); 131 RegisterMemberFunctionHandler( 132 StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir, 133 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir); 134 RegisterMemberFunctionHandler( 135 StringExtractorGDBRemote::eServerPacketType_qsThreadInfo, 136 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo); 137 RegisterMemberFunctionHandler( 138 StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo, 139 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo); 140 RegisterMemberFunctionHandler( 141 StringExtractorGDBRemote::eServerPacketType_jThreadsInfo, 142 &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo); 143 RegisterMemberFunctionHandler( 144 StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo, 145 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo); 146 RegisterMemberFunctionHandler( 147 StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read, 148 &GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read); 149 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s, 150 &GDBRemoteCommunicationServerLLGS::Handle_s); 151 RegisterMemberFunctionHandler( 152 StringExtractorGDBRemote::eServerPacketType_stop_reason, 153 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ? 154 RegisterMemberFunctionHandler( 155 StringExtractorGDBRemote::eServerPacketType_vAttach, 156 &GDBRemoteCommunicationServerLLGS::Handle_vAttach); 157 RegisterMemberFunctionHandler( 158 StringExtractorGDBRemote::eServerPacketType_vCont, 159 &GDBRemoteCommunicationServerLLGS::Handle_vCont); 160 RegisterMemberFunctionHandler( 161 StringExtractorGDBRemote::eServerPacketType_vCont_actions, 162 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions); 163 RegisterMemberFunctionHandler( 164 StringExtractorGDBRemote::eServerPacketType_x, 165 &GDBRemoteCommunicationServerLLGS::Handle_memory_read); 166 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z, 167 &GDBRemoteCommunicationServerLLGS::Handle_Z); 168 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z, 169 &GDBRemoteCommunicationServerLLGS::Handle_z); 170 RegisterMemberFunctionHandler( 171 StringExtractorGDBRemote::eServerPacketType_QPassSignals, 172 &GDBRemoteCommunicationServerLLGS::Handle_QPassSignals); 173 174 RegisterMemberFunctionHandler( 175 StringExtractorGDBRemote::eServerPacketType_jTraceStart, 176 &GDBRemoteCommunicationServerLLGS::Handle_jTraceStart); 177 RegisterMemberFunctionHandler( 178 StringExtractorGDBRemote::eServerPacketType_jTraceBufferRead, 179 &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead); 180 RegisterMemberFunctionHandler( 181 StringExtractorGDBRemote::eServerPacketType_jTraceMetaRead, 182 &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead); 183 RegisterMemberFunctionHandler( 184 StringExtractorGDBRemote::eServerPacketType_jTraceStop, 185 &GDBRemoteCommunicationServerLLGS::Handle_jTraceStop); 186 RegisterMemberFunctionHandler( 187 StringExtractorGDBRemote::eServerPacketType_jTraceConfigRead, 188 &GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead); 189 190 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k, 191 [this](StringExtractorGDBRemote packet, Status &error, 192 bool &interrupt, bool &quit) { 193 quit = true; 194 return this->Handle_k(packet); 195 }); 196 } 197 198 void GDBRemoteCommunicationServerLLGS::SetLaunchInfo(const ProcessLaunchInfo &info) { 199 m_process_launch_info = info; 200 } 201 202 Status GDBRemoteCommunicationServerLLGS::LaunchProcess() { 203 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 204 205 if (!m_process_launch_info.GetArguments().GetArgumentCount()) 206 return Status("%s: no process command line specified to launch", 207 __FUNCTION__); 208 209 const bool should_forward_stdio = 210 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr || 211 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr || 212 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr; 213 m_process_launch_info.SetLaunchInSeparateProcessGroup(true); 214 m_process_launch_info.GetFlags().Set(eLaunchFlagDebug); 215 216 if (should_forward_stdio) { 217 if (llvm::Error Err = m_process_launch_info.SetUpPtyRedirection()) 218 return Status(std::move(Err)); 219 } 220 221 { 222 std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex); 223 assert(!m_debugged_process_up && "lldb-server creating debugged " 224 "process but one already exists"); 225 auto process_or = 226 m_process_factory.Launch(m_process_launch_info, *this, m_mainloop); 227 if (!process_or) 228 return Status(process_or.takeError()); 229 m_debugged_process_up = std::move(*process_or); 230 } 231 232 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol as 233 // needed. llgs local-process debugging may specify PTY paths, which will 234 // make these file actions non-null process launch -i/e/o will also make 235 // these file actions non-null nullptr means that the traffic is expected to 236 // flow over gdb-remote protocol 237 if (should_forward_stdio) { 238 // nullptr means it's not redirected to file or pty (in case of LLGS local) 239 // at least one of stdio will be transferred pty<->gdb-remote we need to 240 // give the pty master handle to this object to read and/or write 241 LLDB_LOG(log, 242 "pid = {0}: setting up stdout/stderr redirection via $O " 243 "gdb-remote commands", 244 m_debugged_process_up->GetID()); 245 246 // Setup stdout/stderr mapping from inferior to $O 247 auto terminal_fd = m_debugged_process_up->GetTerminalFileDescriptor(); 248 if (terminal_fd >= 0) { 249 if (log) 250 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting " 251 "inferior STDIO fd to %d", 252 __FUNCTION__, terminal_fd); 253 Status status = SetSTDIOFileDescriptor(terminal_fd); 254 if (status.Fail()) 255 return status; 256 } else { 257 if (log) 258 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring " 259 "inferior STDIO since terminal fd reported as %d", 260 __FUNCTION__, terminal_fd); 261 } 262 } else { 263 LLDB_LOG(log, 264 "pid = {0} skipping stdout/stderr redirection via $O: inferior " 265 "will communicate over client-provided file descriptors", 266 m_debugged_process_up->GetID()); 267 } 268 269 printf("Launched '%s' as process %" PRIu64 "...\n", 270 m_process_launch_info.GetArguments().GetArgumentAtIndex(0), 271 m_debugged_process_up->GetID()); 272 273 return Status(); 274 } 275 276 Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) { 277 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 278 if (log) 279 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64, 280 __FUNCTION__, pid); 281 282 // Before we try to attach, make sure we aren't already monitoring something 283 // else. 284 if (m_debugged_process_up && 285 m_debugged_process_up->GetID() != LLDB_INVALID_PROCESS_ID) 286 return Status("cannot attach to process %" PRIu64 287 " when another process with pid %" PRIu64 288 " is being debugged.", 289 pid, m_debugged_process_up->GetID()); 290 291 // Try to attach. 292 auto process_or = m_process_factory.Attach(pid, *this, m_mainloop); 293 if (!process_or) { 294 Status status(process_or.takeError()); 295 llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}", pid, 296 status); 297 return status; 298 } 299 m_debugged_process_up = std::move(*process_or); 300 301 // Setup stdout/stderr mapping from inferior. 302 auto terminal_fd = m_debugged_process_up->GetTerminalFileDescriptor(); 303 if (terminal_fd >= 0) { 304 if (log) 305 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting " 306 "inferior STDIO fd to %d", 307 __FUNCTION__, terminal_fd); 308 Status status = SetSTDIOFileDescriptor(terminal_fd); 309 if (status.Fail()) 310 return status; 311 } else { 312 if (log) 313 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring " 314 "inferior STDIO since terminal fd reported as %d", 315 __FUNCTION__, terminal_fd); 316 } 317 318 printf("Attached to process %" PRIu64 "...\n", pid); 319 return Status(); 320 } 321 322 void GDBRemoteCommunicationServerLLGS::InitializeDelegate( 323 NativeProcessProtocol *process) { 324 assert(process && "process cannot be NULL"); 325 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 326 if (log) { 327 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with " 328 "NativeProcessProtocol pid %" PRIu64 ", current state: %s", 329 __FUNCTION__, process->GetID(), 330 StateAsCString(process->GetState())); 331 } 332 } 333 334 GDBRemoteCommunication::PacketResult 335 GDBRemoteCommunicationServerLLGS::SendWResponse( 336 NativeProcessProtocol *process) { 337 assert(process && "process cannot be NULL"); 338 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 339 340 // send W notification 341 auto wait_status = process->GetExitStatus(); 342 if (!wait_status) { 343 LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status", 344 process->GetID()); 345 346 StreamGDBRemote response; 347 response.PutChar('E'); 348 response.PutHex8(GDBRemoteServerError::eErrorExitStatus); 349 return SendPacketNoLock(response.GetString()); 350 } 351 352 LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(), 353 *wait_status); 354 355 StreamGDBRemote response; 356 response.Format("{0:g}", *wait_status); 357 return SendPacketNoLock(response.GetString()); 358 } 359 360 static void AppendHexValue(StreamString &response, const uint8_t *buf, 361 uint32_t buf_size, bool swap) { 362 int64_t i; 363 if (swap) { 364 for (i = buf_size - 1; i >= 0; i--) 365 response.PutHex8(buf[i]); 366 } else { 367 for (i = 0; i < buf_size; i++) 368 response.PutHex8(buf[i]); 369 } 370 } 371 372 static void WriteRegisterValueInHexFixedWidth( 373 StreamString &response, NativeRegisterContext ®_ctx, 374 const RegisterInfo ®_info, const RegisterValue *reg_value_p, 375 lldb::ByteOrder byte_order) { 376 RegisterValue reg_value; 377 if (!reg_value_p) { 378 Status error = reg_ctx.ReadRegister(®_info, reg_value); 379 if (error.Success()) 380 reg_value_p = ®_value; 381 // else log. 382 } 383 384 if (reg_value_p) { 385 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(), 386 reg_value_p->GetByteSize(), 387 byte_order == lldb::eByteOrderLittle); 388 } else { 389 // Zero-out any unreadable values. 390 if (reg_info.byte_size > 0) { 391 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0'); 392 AppendHexValue(response, zeros.data(), zeros.size(), false); 393 } 394 } 395 } 396 397 static JSONObject::SP GetRegistersAsJSON(NativeThreadProtocol &thread) { 398 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 399 400 NativeRegisterContext& reg_ctx = thread.GetRegisterContext(); 401 402 JSONObject::SP register_object_sp = std::make_shared<JSONObject>(); 403 404 #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET 405 // Expedite all registers in the first register set (i.e. should be GPRs) 406 // that are not contained in other registers. 407 const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0); 408 if (!reg_set_p) 409 return nullptr; 410 for (const uint32_t *reg_num_p = reg_set_p->registers; 411 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) { 412 uint32_t reg_num = *reg_num_p; 413 #else 414 // Expedite only a couple of registers until we figure out why sending 415 // registers is expensive. 416 static const uint32_t k_expedited_registers[] = { 417 LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP, 418 LLDB_REGNUM_GENERIC_RA, LLDB_INVALID_REGNUM}; 419 420 for (const uint32_t *generic_reg_p = k_expedited_registers; 421 *generic_reg_p != LLDB_INVALID_REGNUM; ++generic_reg_p) { 422 uint32_t reg_num = reg_ctx.ConvertRegisterKindToRegisterNumber( 423 eRegisterKindGeneric, *generic_reg_p); 424 if (reg_num == LLDB_INVALID_REGNUM) 425 continue; // Target does not support the given register. 426 #endif 427 428 const RegisterInfo *const reg_info_p = 429 reg_ctx.GetRegisterInfoAtIndex(reg_num); 430 if (reg_info_p == nullptr) { 431 if (log) 432 log->Printf( 433 "%s failed to get register info for register index %" PRIu32, 434 __FUNCTION__, reg_num); 435 continue; 436 } 437 438 if (reg_info_p->value_regs != nullptr) 439 continue; // Only expedite registers that are not contained in other 440 // registers. 441 442 RegisterValue reg_value; 443 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value); 444 if (error.Fail()) { 445 if (log) 446 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s", 447 __FUNCTION__, 448 reg_info_p->name ? reg_info_p->name : "<unnamed-register>", 449 reg_num, error.AsCString()); 450 continue; 451 } 452 453 StreamString stream; 454 WriteRegisterValueInHexFixedWidth(stream, reg_ctx, *reg_info_p, 455 ®_value, lldb::eByteOrderBig); 456 457 register_object_sp->SetObject( 458 llvm::to_string(reg_num), 459 std::make_shared<JSONString>(stream.GetString())); 460 } 461 462 return register_object_sp; 463 } 464 465 static const char *GetStopReasonString(StopReason stop_reason) { 466 switch (stop_reason) { 467 case eStopReasonTrace: 468 return "trace"; 469 case eStopReasonBreakpoint: 470 return "breakpoint"; 471 case eStopReasonWatchpoint: 472 return "watchpoint"; 473 case eStopReasonSignal: 474 return "signal"; 475 case eStopReasonException: 476 return "exception"; 477 case eStopReasonExec: 478 return "exec"; 479 case eStopReasonInstrumentation: 480 case eStopReasonInvalid: 481 case eStopReasonPlanComplete: 482 case eStopReasonThreadExiting: 483 case eStopReasonNone: 484 break; // ignored 485 } 486 return nullptr; 487 } 488 489 static JSONArray::SP GetJSONThreadsInfo(NativeProcessProtocol &process, 490 bool abridged) { 491 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 492 493 JSONArray::SP threads_array_sp = std::make_shared<JSONArray>(); 494 495 // Ensure we can get info on the given thread. 496 uint32_t thread_idx = 0; 497 for (NativeThreadProtocol *thread; 498 (thread = process.GetThreadAtIndex(thread_idx)) != nullptr; 499 ++thread_idx) { 500 501 lldb::tid_t tid = thread->GetID(); 502 503 // Grab the reason this thread stopped. 504 struct ThreadStopInfo tid_stop_info; 505 std::string description; 506 if (!thread->GetStopReason(tid_stop_info, description)) 507 return nullptr; 508 509 const int signum = tid_stop_info.details.signal.signo; 510 if (log) { 511 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 512 " tid %" PRIu64 513 " got signal signo = %d, reason = %d, exc_type = %" PRIu64, 514 __FUNCTION__, process.GetID(), tid, signum, 515 tid_stop_info.reason, tid_stop_info.details.exception.type); 516 } 517 518 JSONObject::SP thread_obj_sp = std::make_shared<JSONObject>(); 519 threads_array_sp->AppendObject(thread_obj_sp); 520 521 if (!abridged) { 522 if (JSONObject::SP registers_sp = GetRegistersAsJSON(*thread)) 523 thread_obj_sp->SetObject("registers", registers_sp); 524 } 525 526 thread_obj_sp->SetObject("tid", std::make_shared<JSONNumber>(tid)); 527 if (signum != 0) 528 thread_obj_sp->SetObject("signal", std::make_shared<JSONNumber>(signum)); 529 530 const std::string thread_name = thread->GetName(); 531 if (!thread_name.empty()) 532 thread_obj_sp->SetObject("name", 533 std::make_shared<JSONString>(thread_name)); 534 535 if (const char *stop_reason_str = GetStopReasonString(tid_stop_info.reason)) 536 thread_obj_sp->SetObject("reason", 537 std::make_shared<JSONString>(stop_reason_str)); 538 539 if (!description.empty()) 540 thread_obj_sp->SetObject("description", 541 std::make_shared<JSONString>(description)); 542 543 if ((tid_stop_info.reason == eStopReasonException) && 544 tid_stop_info.details.exception.type) { 545 thread_obj_sp->SetObject( 546 "metype", 547 std::make_shared<JSONNumber>(tid_stop_info.details.exception.type)); 548 549 JSONArray::SP medata_array_sp = std::make_shared<JSONArray>(); 550 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; 551 ++i) { 552 medata_array_sp->AppendObject(std::make_shared<JSONNumber>( 553 tid_stop_info.details.exception.data[i])); 554 } 555 thread_obj_sp->SetObject("medata", medata_array_sp); 556 } 557 558 // TODO: Expedite interesting regions of inferior memory 559 } 560 561 return threads_array_sp; 562 } 563 564 GDBRemoteCommunication::PacketResult 565 GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread( 566 lldb::tid_t tid) { 567 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 568 569 // Ensure we have a debugged process. 570 if (!m_debugged_process_up || 571 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) 572 return SendErrorResponse(50); 573 574 LLDB_LOG(log, "preparing packet for pid {0} tid {1}", 575 m_debugged_process_up->GetID(), tid); 576 577 // Ensure we can get info on the given thread. 578 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid); 579 if (!thread) 580 return SendErrorResponse(51); 581 582 // Grab the reason this thread stopped. 583 struct ThreadStopInfo tid_stop_info; 584 std::string description; 585 if (!thread->GetStopReason(tid_stop_info, description)) 586 return SendErrorResponse(52); 587 588 // FIXME implement register handling for exec'd inferiors. 589 // if (tid_stop_info.reason == eStopReasonExec) { 590 // const bool force = true; 591 // InitializeRegisters(force); 592 // } 593 594 StreamString response; 595 // Output the T packet with the thread 596 response.PutChar('T'); 597 int signum = tid_stop_info.details.signal.signo; 598 LLDB_LOG( 599 log, 600 "pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}", 601 m_debugged_process_up->GetID(), tid, signum, int(tid_stop_info.reason), 602 tid_stop_info.details.exception.type); 603 604 // Print the signal number. 605 response.PutHex8(signum & 0xff); 606 607 // Include the tid. 608 response.Printf("thread:%" PRIx64 ";", tid); 609 610 // Include the thread name if there is one. 611 const std::string thread_name = thread->GetName(); 612 if (!thread_name.empty()) { 613 size_t thread_name_len = thread_name.length(); 614 615 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) { 616 response.PutCString("name:"); 617 response.PutCString(thread_name); 618 } else { 619 // The thread name contains special chars, send as hex bytes. 620 response.PutCString("hexname:"); 621 response.PutStringAsRawHex8(thread_name); 622 } 623 response.PutChar(';'); 624 } 625 626 // If a 'QListThreadsInStopReply' was sent to enable this feature, we will 627 // send all thread IDs back in the "threads" key whose value is a list of hex 628 // thread IDs separated by commas: 629 // "threads:10a,10b,10c;" 630 // This will save the debugger from having to send a pair of qfThreadInfo and 631 // qsThreadInfo packets, but it also might take a lot of room in the stop 632 // reply packet, so it must be enabled only on systems where there are no 633 // limits on packet lengths. 634 if (m_list_threads_in_stop_reply) { 635 response.PutCString("threads:"); 636 637 uint32_t thread_index = 0; 638 NativeThreadProtocol *listed_thread; 639 for (listed_thread = m_debugged_process_up->GetThreadAtIndex(thread_index); 640 listed_thread; ++thread_index, 641 listed_thread = m_debugged_process_up->GetThreadAtIndex(thread_index)) { 642 if (thread_index > 0) 643 response.PutChar(','); 644 response.Printf("%" PRIx64, listed_thread->GetID()); 645 } 646 response.PutChar(';'); 647 648 // Include JSON info that describes the stop reason for any threads that 649 // actually have stop reasons. We use the new "jstopinfo" key whose values 650 // is hex ascii JSON that contains the thread IDs thread stop info only for 651 // threads that have stop reasons. Only send this if we have more than one 652 // thread otherwise this packet has all the info it needs. 653 if (thread_index > 0) { 654 const bool threads_with_valid_stop_info_only = true; 655 JSONArray::SP threads_info_sp = GetJSONThreadsInfo( 656 *m_debugged_process_up, threads_with_valid_stop_info_only); 657 if (threads_info_sp) { 658 response.PutCString("jstopinfo:"); 659 StreamString unescaped_response; 660 threads_info_sp->Write(unescaped_response); 661 response.PutStringAsRawHex8(unescaped_response.GetData()); 662 response.PutChar(';'); 663 } else 664 LLDB_LOG(log, "failed to prepare a jstopinfo field for pid {0}", 665 m_debugged_process_up->GetID()); 666 } 667 668 uint32_t i = 0; 669 response.PutCString("thread-pcs"); 670 char delimiter = ':'; 671 for (NativeThreadProtocol *thread; 672 (thread = m_debugged_process_up->GetThreadAtIndex(i)) != nullptr; 673 ++i) { 674 NativeRegisterContext& reg_ctx = thread->GetRegisterContext(); 675 676 uint32_t reg_to_read = reg_ctx.ConvertRegisterKindToRegisterNumber( 677 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); 678 const RegisterInfo *const reg_info_p = 679 reg_ctx.GetRegisterInfoAtIndex(reg_to_read); 680 681 RegisterValue reg_value; 682 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value); 683 if (error.Fail()) { 684 if (log) 685 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s", 686 __FUNCTION__, 687 reg_info_p->name ? reg_info_p->name 688 : "<unnamed-register>", 689 reg_to_read, error.AsCString()); 690 continue; 691 } 692 693 response.PutChar(delimiter); 694 delimiter = ','; 695 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p, 696 ®_value, endian::InlHostByteOrder()); 697 } 698 699 response.PutChar(';'); 700 } 701 702 // 703 // Expedite registers. 704 // 705 706 // Grab the register context. 707 NativeRegisterContext& reg_ctx = thread->GetRegisterContext(); 708 // Expedite all registers in the first register set (i.e. should be GPRs) 709 // that are not contained in other registers. 710 const RegisterSet *reg_set_p; 711 if (reg_ctx.GetRegisterSetCount() > 0 && 712 ((reg_set_p = reg_ctx.GetRegisterSet(0)) != nullptr)) { 713 if (log) 714 log->Printf("GDBRemoteCommunicationServerLLGS::%s expediting registers " 715 "from set '%s' (registers set count: %zu)", 716 __FUNCTION__, 717 reg_set_p->name ? reg_set_p->name : "<unnamed-set>", 718 reg_set_p->num_registers); 719 720 for (const uint32_t *reg_num_p = reg_set_p->registers; 721 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) { 722 const RegisterInfo *const reg_info_p = 723 reg_ctx.GetRegisterInfoAtIndex(*reg_num_p); 724 if (reg_info_p == nullptr) { 725 if (log) 726 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get " 727 "register info for register set '%s', register index " 728 "%" PRIu32, 729 __FUNCTION__, 730 reg_set_p->name ? reg_set_p->name : "<unnamed-set>", 731 *reg_num_p); 732 } else if (reg_info_p->value_regs == nullptr) { 733 // Only expediate registers that are not contained in other registers. 734 RegisterValue reg_value; 735 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value); 736 if (error.Success()) { 737 response.Printf("%.02x:", *reg_num_p); 738 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p, 739 ®_value, lldb::eByteOrderBig); 740 response.PutChar(';'); 741 } else { 742 if (log) 743 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to read " 744 "register '%s' index %" PRIu32 ": %s", 745 __FUNCTION__, 746 reg_info_p->name ? reg_info_p->name 747 : "<unnamed-register>", 748 *reg_num_p, error.AsCString()); 749 } 750 } 751 } 752 } 753 754 const char *reason_str = GetStopReasonString(tid_stop_info.reason); 755 if (reason_str != nullptr) { 756 response.Printf("reason:%s;", reason_str); 757 } 758 759 if (!description.empty()) { 760 // Description may contains special chars, send as hex bytes. 761 response.PutCString("description:"); 762 response.PutStringAsRawHex8(description); 763 response.PutChar(';'); 764 } else if ((tid_stop_info.reason == eStopReasonException) && 765 tid_stop_info.details.exception.type) { 766 response.PutCString("metype:"); 767 response.PutHex64(tid_stop_info.details.exception.type); 768 response.PutCString(";mecount:"); 769 response.PutHex32(tid_stop_info.details.exception.data_count); 770 response.PutChar(';'); 771 772 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) { 773 response.PutCString("medata:"); 774 response.PutHex64(tid_stop_info.details.exception.data[i]); 775 response.PutChar(';'); 776 } 777 } 778 779 return SendPacketNoLock(response.GetString()); 780 } 781 782 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited( 783 NativeProcessProtocol *process) { 784 assert(process && "process cannot be NULL"); 785 786 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 787 if (log) 788 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__); 789 790 PacketResult result = SendStopReasonForState(StateType::eStateExited); 791 if (result != PacketResult::Success) { 792 if (log) 793 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop " 794 "notification for PID %" PRIu64 ", state: eStateExited", 795 __FUNCTION__, process->GetID()); 796 } 797 798 // Close the pipe to the inferior terminal i/o if we launched it and set one 799 // up. 800 MaybeCloseInferiorTerminalConnection(); 801 802 // We are ready to exit the debug monitor. 803 m_exit_now = true; 804 m_mainloop.RequestTermination(); 805 } 806 807 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped( 808 NativeProcessProtocol *process) { 809 assert(process && "process cannot be NULL"); 810 811 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 812 if (log) 813 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__); 814 815 // Send the stop reason unless this is the stop after the launch or attach. 816 switch (m_inferior_prev_state) { 817 case eStateLaunching: 818 case eStateAttaching: 819 // Don't send anything per debugserver behavior. 820 break; 821 default: 822 // In all other cases, send the stop reason. 823 PacketResult result = SendStopReasonForState(StateType::eStateStopped); 824 if (result != PacketResult::Success) { 825 if (log) 826 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop " 827 "notification for PID %" PRIu64 ", state: eStateExited", 828 __FUNCTION__, process->GetID()); 829 } 830 break; 831 } 832 } 833 834 void GDBRemoteCommunicationServerLLGS::ProcessStateChanged( 835 NativeProcessProtocol *process, lldb::StateType state) { 836 assert(process && "process cannot be NULL"); 837 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 838 if (log) { 839 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with " 840 "NativeProcessProtocol pid %" PRIu64 ", state: %s", 841 __FUNCTION__, process->GetID(), StateAsCString(state)); 842 } 843 844 switch (state) { 845 case StateType::eStateRunning: 846 StartSTDIOForwarding(); 847 break; 848 849 case StateType::eStateStopped: 850 // Make sure we get all of the pending stdout/stderr from the inferior and 851 // send it to the lldb host before we send the state change notification 852 SendProcessOutput(); 853 // Then stop the forwarding, so that any late output (see llvm.org/pr25652) 854 // does not interfere with our protocol. 855 StopSTDIOForwarding(); 856 HandleInferiorState_Stopped(process); 857 break; 858 859 case StateType::eStateExited: 860 // Same as above 861 SendProcessOutput(); 862 StopSTDIOForwarding(); 863 HandleInferiorState_Exited(process); 864 break; 865 866 default: 867 if (log) { 868 log->Printf("GDBRemoteCommunicationServerLLGS::%s didn't handle state " 869 "change for pid %" PRIu64 ", new state: %s", 870 __FUNCTION__, process->GetID(), StateAsCString(state)); 871 } 872 break; 873 } 874 875 // Remember the previous state reported to us. 876 m_inferior_prev_state = state; 877 } 878 879 void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) { 880 ClearProcessSpecificData(); 881 } 882 883 void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() { 884 Log *log(GetLogIfAnyCategoriesSet(GDBR_LOG_COMM)); 885 886 if (!m_handshake_completed) { 887 if (!HandshakeWithClient()) { 888 if (log) 889 log->Printf("GDBRemoteCommunicationServerLLGS::%s handshake with " 890 "client failed, exiting", 891 __FUNCTION__); 892 m_mainloop.RequestTermination(); 893 return; 894 } 895 m_handshake_completed = true; 896 } 897 898 bool interrupt = false; 899 bool done = false; 900 Status error; 901 while (true) { 902 const PacketResult result = GetPacketAndSendResponse( 903 std::chrono::microseconds(0), error, interrupt, done); 904 if (result == PacketResult::ErrorReplyTimeout) 905 break; // No more packets in the queue 906 907 if ((result != PacketResult::Success)) { 908 if (log) 909 log->Printf("GDBRemoteCommunicationServerLLGS::%s processing a packet " 910 "failed: %s", 911 __FUNCTION__, error.AsCString()); 912 m_mainloop.RequestTermination(); 913 break; 914 } 915 } 916 } 917 918 Status GDBRemoteCommunicationServerLLGS::InitializeConnection( 919 std::unique_ptr<Connection> &&connection) { 920 IOObjectSP read_object_sp = connection->GetReadObject(); 921 GDBRemoteCommunicationServer::SetConnection(connection.release()); 922 923 Status error; 924 m_network_handle_up = m_mainloop.RegisterReadObject( 925 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); }, 926 error); 927 return error; 928 } 929 930 GDBRemoteCommunication::PacketResult 931 GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer, 932 uint32_t len) { 933 if ((buffer == nullptr) || (len == 0)) { 934 // Nothing to send. 935 return PacketResult::Success; 936 } 937 938 StreamString response; 939 response.PutChar('O'); 940 response.PutBytesAsRawHex8(buffer, len); 941 942 return SendPacketNoLock(response.GetString()); 943 } 944 945 Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) { 946 Status error; 947 948 // Set up the reading/handling of process I/O 949 std::unique_ptr<ConnectionFileDescriptor> conn_up( 950 new ConnectionFileDescriptor(fd, true)); 951 if (!conn_up) { 952 error.SetErrorString("failed to create ConnectionFileDescriptor"); 953 return error; 954 } 955 956 m_stdio_communication.SetCloseOnEOF(false); 957 m_stdio_communication.SetConnection(conn_up.release()); 958 if (!m_stdio_communication.IsConnected()) { 959 error.SetErrorString( 960 "failed to set connection for inferior I/O communication"); 961 return error; 962 } 963 964 return Status(); 965 } 966 967 void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() { 968 // Don't forward if not connected (e.g. when attaching). 969 if (!m_stdio_communication.IsConnected()) 970 return; 971 972 Status error; 973 lldbassert(!m_stdio_handle_up); 974 m_stdio_handle_up = m_mainloop.RegisterReadObject( 975 m_stdio_communication.GetConnection()->GetReadObject(), 976 [this](MainLoopBase &) { SendProcessOutput(); }, error); 977 978 if (!m_stdio_handle_up) { 979 // Not much we can do about the failure. Log it and continue without 980 // forwarding. 981 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)) 982 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio " 983 "forwarding: %s", 984 __FUNCTION__, error.AsCString()); 985 } 986 } 987 988 void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() { 989 m_stdio_handle_up.reset(); 990 } 991 992 void GDBRemoteCommunicationServerLLGS::SendProcessOutput() { 993 char buffer[1024]; 994 ConnectionStatus status; 995 Status error; 996 while (true) { 997 size_t bytes_read = m_stdio_communication.Read( 998 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error); 999 switch (status) { 1000 case eConnectionStatusSuccess: 1001 SendONotification(buffer, bytes_read); 1002 break; 1003 case eConnectionStatusLostConnection: 1004 case eConnectionStatusEndOfFile: 1005 case eConnectionStatusError: 1006 case eConnectionStatusNoConnection: 1007 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)) 1008 log->Printf("GDBRemoteCommunicationServerLLGS::%s Stopping stdio " 1009 "forwarding as communication returned status %d (error: " 1010 "%s)", 1011 __FUNCTION__, status, error.AsCString()); 1012 m_stdio_handle_up.reset(); 1013 return; 1014 1015 case eConnectionStatusInterrupted: 1016 case eConnectionStatusTimedOut: 1017 return; 1018 } 1019 } 1020 } 1021 1022 GDBRemoteCommunication::PacketResult 1023 GDBRemoteCommunicationServerLLGS::Handle_jTraceStart( 1024 StringExtractorGDBRemote &packet) { 1025 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 1026 // Fail if we don't have a current process. 1027 if (!m_debugged_process_up || 1028 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) 1029 return SendErrorResponse(68); 1030 1031 if (!packet.ConsumeFront("jTraceStart:")) 1032 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet "); 1033 1034 TraceOptions options; 1035 uint64_t type = std::numeric_limits<uint64_t>::max(); 1036 uint64_t buffersize = std::numeric_limits<uint64_t>::max(); 1037 lldb::tid_t tid = LLDB_INVALID_THREAD_ID; 1038 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max(); 1039 1040 auto json_object = StructuredData::ParseJSON(packet.Peek()); 1041 1042 if (!json_object || 1043 json_object->GetType() != lldb::eStructuredDataTypeDictionary) 1044 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet "); 1045 1046 auto json_dict = json_object->GetAsDictionary(); 1047 1048 json_dict->GetValueForKeyAsInteger("metabuffersize", metabuffersize); 1049 options.setMetaDataBufferSize(metabuffersize); 1050 1051 json_dict->GetValueForKeyAsInteger("buffersize", buffersize); 1052 options.setTraceBufferSize(buffersize); 1053 1054 json_dict->GetValueForKeyAsInteger("type", type); 1055 options.setType(static_cast<lldb::TraceType>(type)); 1056 1057 json_dict->GetValueForKeyAsInteger("threadid", tid); 1058 options.setThreadID(tid); 1059 1060 StructuredData::ObjectSP custom_params_sp = 1061 json_dict->GetValueForKey("params"); 1062 if (custom_params_sp && 1063 custom_params_sp->GetType() != lldb::eStructuredDataTypeDictionary) 1064 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet "); 1065 1066 options.setTraceParams( 1067 static_pointer_cast<StructuredData::Dictionary>(custom_params_sp)); 1068 1069 if (buffersize == std::numeric_limits<uint64_t>::max() || 1070 type != lldb::TraceType::eTraceTypeProcessorTrace) { 1071 LLDB_LOG(log, "Ill formed packet buffersize = {0} type = {1}", buffersize, 1072 type); 1073 return SendIllFormedResponse(packet, "JTrace:start: Ill formed packet "); 1074 } 1075 1076 Status error; 1077 lldb::user_id_t uid = LLDB_INVALID_UID; 1078 uid = m_debugged_process_up->StartTrace(options, error); 1079 LLDB_LOG(log, "uid is {0} , error is {1}", uid, error.GetError()); 1080 if (error.Fail()) 1081 return SendErrorResponse(error); 1082 1083 StreamGDBRemote response; 1084 response.Printf("%" PRIx64, uid); 1085 return SendPacketNoLock(response.GetString()); 1086 } 1087 1088 GDBRemoteCommunication::PacketResult 1089 GDBRemoteCommunicationServerLLGS::Handle_jTraceStop( 1090 StringExtractorGDBRemote &packet) { 1091 // Fail if we don't have a current process. 1092 if (!m_debugged_process_up || 1093 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) 1094 return SendErrorResponse(68); 1095 1096 if (!packet.ConsumeFront("jTraceStop:")) 1097 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet "); 1098 1099 lldb::user_id_t uid = LLDB_INVALID_UID; 1100 lldb::tid_t tid = LLDB_INVALID_THREAD_ID; 1101 1102 auto json_object = StructuredData::ParseJSON(packet.Peek()); 1103 1104 if (!json_object || 1105 json_object->GetType() != lldb::eStructuredDataTypeDictionary) 1106 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet "); 1107 1108 auto json_dict = json_object->GetAsDictionary(); 1109 1110 if (!json_dict->GetValueForKeyAsInteger("traceid", uid)) 1111 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet "); 1112 1113 json_dict->GetValueForKeyAsInteger("threadid", tid); 1114 1115 Status error = m_debugged_process_up->StopTrace(uid, tid); 1116 1117 if (error.Fail()) 1118 return SendErrorResponse(error); 1119 1120 return SendOKResponse(); 1121 } 1122 1123 GDBRemoteCommunication::PacketResult 1124 GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead( 1125 StringExtractorGDBRemote &packet) { 1126 1127 // Fail if we don't have a current process. 1128 if (!m_debugged_process_up || 1129 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) 1130 return SendErrorResponse(68); 1131 1132 if (!packet.ConsumeFront("jTraceConfigRead:")) 1133 return SendIllFormedResponse(packet, 1134 "jTraceConfigRead: Ill formed packet "); 1135 1136 lldb::user_id_t uid = LLDB_INVALID_UID; 1137 lldb::tid_t threadid = LLDB_INVALID_THREAD_ID; 1138 1139 auto json_object = StructuredData::ParseJSON(packet.Peek()); 1140 1141 if (!json_object || 1142 json_object->GetType() != lldb::eStructuredDataTypeDictionary) 1143 return SendIllFormedResponse(packet, 1144 "jTraceConfigRead: Ill formed packet "); 1145 1146 auto json_dict = json_object->GetAsDictionary(); 1147 1148 if (!json_dict->GetValueForKeyAsInteger("traceid", uid)) 1149 return SendIllFormedResponse(packet, 1150 "jTraceConfigRead: Ill formed packet "); 1151 1152 json_dict->GetValueForKeyAsInteger("threadid", threadid); 1153 1154 TraceOptions options; 1155 StreamGDBRemote response; 1156 1157 options.setThreadID(threadid); 1158 Status error = m_debugged_process_up->GetTraceConfig(uid, options); 1159 1160 if (error.Fail()) 1161 return SendErrorResponse(error); 1162 1163 StreamGDBRemote escaped_response; 1164 StructuredData::Dictionary json_packet; 1165 1166 json_packet.AddIntegerItem("type", options.getType()); 1167 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize()); 1168 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize()); 1169 1170 StructuredData::DictionarySP custom_params = options.getTraceParams(); 1171 if (custom_params) 1172 json_packet.AddItem("params", custom_params); 1173 1174 StreamString json_string; 1175 json_packet.Dump(json_string, false); 1176 escaped_response.PutEscapedBytes(json_string.GetData(), 1177 json_string.GetSize()); 1178 return SendPacketNoLock(escaped_response.GetString()); 1179 } 1180 1181 GDBRemoteCommunication::PacketResult 1182 GDBRemoteCommunicationServerLLGS::Handle_jTraceRead( 1183 StringExtractorGDBRemote &packet) { 1184 1185 // Fail if we don't have a current process. 1186 if (!m_debugged_process_up || 1187 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) 1188 return SendErrorResponse(68); 1189 1190 enum PacketType { MetaData, BufferData }; 1191 PacketType tracetype = MetaData; 1192 1193 if (packet.ConsumeFront("jTraceBufferRead:")) 1194 tracetype = BufferData; 1195 else if (packet.ConsumeFront("jTraceMetaRead:")) 1196 tracetype = MetaData; 1197 else { 1198 return SendIllFormedResponse(packet, "jTrace: Ill formed packet "); 1199 } 1200 1201 lldb::user_id_t uid = LLDB_INVALID_UID; 1202 1203 uint64_t byte_count = std::numeric_limits<uint64_t>::max(); 1204 lldb::tid_t tid = LLDB_INVALID_THREAD_ID; 1205 uint64_t offset = std::numeric_limits<uint64_t>::max(); 1206 1207 auto json_object = StructuredData::ParseJSON(packet.Peek()); 1208 1209 if (!json_object || 1210 json_object->GetType() != lldb::eStructuredDataTypeDictionary) 1211 return SendIllFormedResponse(packet, "jTrace: Ill formed packet "); 1212 1213 auto json_dict = json_object->GetAsDictionary(); 1214 1215 if (!json_dict->GetValueForKeyAsInteger("traceid", uid) || 1216 !json_dict->GetValueForKeyAsInteger("offset", offset) || 1217 !json_dict->GetValueForKeyAsInteger("buffersize", byte_count)) 1218 return SendIllFormedResponse(packet, "jTrace: Ill formed packet "); 1219 1220 json_dict->GetValueForKeyAsInteger("threadid", tid); 1221 1222 // Allocate the response buffer. 1223 std::unique_ptr<uint8_t[]> buffer (new (std::nothrow) uint8_t[byte_count]); 1224 if (!buffer) 1225 return SendErrorResponse(0x78); 1226 1227 StreamGDBRemote response; 1228 Status error; 1229 llvm::MutableArrayRef<uint8_t> buf(buffer.get(), byte_count); 1230 1231 if (tracetype == BufferData) 1232 error = m_debugged_process_up->GetData(uid, tid, buf, offset); 1233 else if (tracetype == MetaData) 1234 error = m_debugged_process_up->GetMetaData(uid, tid, buf, offset); 1235 1236 if (error.Fail()) 1237 return SendErrorResponse(error); 1238 1239 for (auto i : buf) 1240 response.PutHex8(i); 1241 1242 StreamGDBRemote escaped_response; 1243 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize()); 1244 return SendPacketNoLock(escaped_response.GetString()); 1245 } 1246 1247 GDBRemoteCommunication::PacketResult 1248 GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo( 1249 StringExtractorGDBRemote &packet) { 1250 // Fail if we don't have a current process. 1251 if (!m_debugged_process_up || 1252 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) 1253 return SendErrorResponse(68); 1254 1255 lldb::pid_t pid = m_debugged_process_up->GetID(); 1256 1257 if (pid == LLDB_INVALID_PROCESS_ID) 1258 return SendErrorResponse(1); 1259 1260 ProcessInstanceInfo proc_info; 1261 if (!Host::GetProcessInfo(pid, proc_info)) 1262 return SendErrorResponse(1); 1263 1264 StreamString response; 1265 CreateProcessInfoResponse_DebugServerStyle(proc_info, response); 1266 return SendPacketNoLock(response.GetString()); 1267 } 1268 1269 GDBRemoteCommunication::PacketResult 1270 GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) { 1271 // Fail if we don't have a current process. 1272 if (!m_debugged_process_up || 1273 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) 1274 return SendErrorResponse(68); 1275 1276 // Make sure we set the current thread so g and p packets return the data the 1277 // gdb will expect. 1278 lldb::tid_t tid = m_debugged_process_up->GetCurrentThreadID(); 1279 SetCurrentThreadID(tid); 1280 1281 NativeThreadProtocol *thread = m_debugged_process_up->GetCurrentThread(); 1282 if (!thread) 1283 return SendErrorResponse(69); 1284 1285 StreamString response; 1286 response.Printf("QC%" PRIx64, thread->GetID()); 1287 1288 return SendPacketNoLock(response.GetString()); 1289 } 1290 1291 GDBRemoteCommunication::PacketResult 1292 GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) { 1293 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 1294 1295 StopSTDIOForwarding(); 1296 1297 if (!m_debugged_process_up) { 1298 LLDB_LOG(log, "No debugged process found."); 1299 return PacketResult::Success; 1300 } 1301 1302 Status error = m_debugged_process_up->Kill(); 1303 if (error.Fail()) 1304 LLDB_LOG(log, "Failed to kill debugged process {0}: {1}", 1305 m_debugged_process_up->GetID(), error); 1306 1307 // No OK response for kill packet. 1308 // return SendOKResponse (); 1309 return PacketResult::Success; 1310 } 1311 1312 GDBRemoteCommunication::PacketResult 1313 GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR( 1314 StringExtractorGDBRemote &packet) { 1315 packet.SetFilePos(::strlen("QSetDisableASLR:")); 1316 if (packet.GetU32(0)) 1317 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR); 1318 else 1319 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR); 1320 return SendOKResponse(); 1321 } 1322 1323 GDBRemoteCommunication::PacketResult 1324 GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir( 1325 StringExtractorGDBRemote &packet) { 1326 packet.SetFilePos(::strlen("QSetWorkingDir:")); 1327 std::string path; 1328 packet.GetHexByteString(path); 1329 m_process_launch_info.SetWorkingDirectory(FileSpec(path)); 1330 return SendOKResponse(); 1331 } 1332 1333 GDBRemoteCommunication::PacketResult 1334 GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir( 1335 StringExtractorGDBRemote &packet) { 1336 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()}; 1337 if (working_dir) { 1338 StreamString response; 1339 response.PutStringAsRawHex8(working_dir.GetCString()); 1340 return SendPacketNoLock(response.GetString()); 1341 } 1342 1343 return SendErrorResponse(14); 1344 } 1345 1346 GDBRemoteCommunication::PacketResult 1347 GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) { 1348 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 1349 if (log) 1350 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__); 1351 1352 // Ensure we have a native process. 1353 if (!m_debugged_process_up) { 1354 if (log) 1355 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process " 1356 "shared pointer", 1357 __FUNCTION__); 1358 return SendErrorResponse(0x36); 1359 } 1360 1361 // Pull out the signal number. 1362 packet.SetFilePos(::strlen("C")); 1363 if (packet.GetBytesLeft() < 1) { 1364 // Shouldn't be using a C without a signal. 1365 return SendIllFormedResponse(packet, "C packet specified without signal."); 1366 } 1367 const uint32_t signo = 1368 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 1369 if (signo == std::numeric_limits<uint32_t>::max()) 1370 return SendIllFormedResponse(packet, "failed to parse signal number"); 1371 1372 // Handle optional continue address. 1373 if (packet.GetBytesLeft() > 0) { 1374 // FIXME add continue at address support for $C{signo}[;{continue-address}]. 1375 if (*packet.Peek() == ';') 1376 return SendUnimplementedResponse(packet.GetStringRef().c_str()); 1377 else 1378 return SendIllFormedResponse( 1379 packet, "unexpected content after $C{signal-number}"); 1380 } 1381 1382 ResumeActionList resume_actions(StateType::eStateRunning, 0); 1383 Status error; 1384 1385 // We have two branches: what to do if a continue thread is specified (in 1386 // which case we target sending the signal to that thread), or when we don't 1387 // have a continue thread set (in which case we send a signal to the 1388 // process). 1389 1390 // TODO discuss with Greg Clayton, make sure this makes sense. 1391 1392 lldb::tid_t signal_tid = GetContinueThreadID(); 1393 if (signal_tid != LLDB_INVALID_THREAD_ID) { 1394 // The resume action for the continue thread (or all threads if a continue 1395 // thread is not set). 1396 ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning, 1397 static_cast<int>(signo)}; 1398 1399 // Add the action for the continue thread (or all threads when the continue 1400 // thread isn't present). 1401 resume_actions.Append(action); 1402 } else { 1403 // Send the signal to the process since we weren't targeting a specific 1404 // continue thread with the signal. 1405 error = m_debugged_process_up->Signal(signo); 1406 if (error.Fail()) { 1407 LLDB_LOG(log, "failed to send signal for process {0}: {1}", 1408 m_debugged_process_up->GetID(), error); 1409 1410 return SendErrorResponse(0x52); 1411 } 1412 } 1413 1414 // Resume the threads. 1415 error = m_debugged_process_up->Resume(resume_actions); 1416 if (error.Fail()) { 1417 LLDB_LOG(log, "failed to resume threads for process {0}: {1}", 1418 m_debugged_process_up->GetID(), error); 1419 1420 return SendErrorResponse(0x38); 1421 } 1422 1423 // Don't send an "OK" packet; response is the stopped/exited message. 1424 return PacketResult::Success; 1425 } 1426 1427 GDBRemoteCommunication::PacketResult 1428 GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) { 1429 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 1430 if (log) 1431 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__); 1432 1433 packet.SetFilePos(packet.GetFilePos() + ::strlen("c")); 1434 1435 // For now just support all continue. 1436 const bool has_continue_address = (packet.GetBytesLeft() > 0); 1437 if (has_continue_address) { 1438 LLDB_LOG(log, "not implemented for c[address] variant [{0} remains]", 1439 packet.Peek()); 1440 return SendUnimplementedResponse(packet.GetStringRef().c_str()); 1441 } 1442 1443 // Ensure we have a native process. 1444 if (!m_debugged_process_up) { 1445 if (log) 1446 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process " 1447 "shared pointer", 1448 __FUNCTION__); 1449 return SendErrorResponse(0x36); 1450 } 1451 1452 // Build the ResumeActionList 1453 ResumeActionList actions(StateType::eStateRunning, 0); 1454 1455 Status error = m_debugged_process_up->Resume(actions); 1456 if (error.Fail()) { 1457 LLDB_LOG(log, "c failed for process {0}: {1}", 1458 m_debugged_process_up->GetID(), error); 1459 return SendErrorResponse(GDBRemoteServerError::eErrorResume); 1460 } 1461 1462 LLDB_LOG(log, "continued process {0}", m_debugged_process_up->GetID()); 1463 // No response required from continue. 1464 return PacketResult::Success; 1465 } 1466 1467 GDBRemoteCommunication::PacketResult 1468 GDBRemoteCommunicationServerLLGS::Handle_vCont_actions( 1469 StringExtractorGDBRemote &packet) { 1470 StreamString response; 1471 response.Printf("vCont;c;C;s;S"); 1472 1473 return SendPacketNoLock(response.GetString()); 1474 } 1475 1476 GDBRemoteCommunication::PacketResult 1477 GDBRemoteCommunicationServerLLGS::Handle_vCont( 1478 StringExtractorGDBRemote &packet) { 1479 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 1480 if (log) 1481 log->Printf("GDBRemoteCommunicationServerLLGS::%s handling vCont packet", 1482 __FUNCTION__); 1483 1484 packet.SetFilePos(::strlen("vCont")); 1485 1486 if (packet.GetBytesLeft() == 0) { 1487 if (log) 1488 log->Printf("GDBRemoteCommunicationServerLLGS::%s missing action from " 1489 "vCont package", 1490 __FUNCTION__); 1491 return SendIllFormedResponse(packet, "Missing action from vCont package"); 1492 } 1493 1494 // Check if this is all continue (no options or ";c"). 1495 if (::strcmp(packet.Peek(), ";c") == 0) { 1496 // Move past the ';', then do a simple 'c'. 1497 packet.SetFilePos(packet.GetFilePos() + 1); 1498 return Handle_c(packet); 1499 } else if (::strcmp(packet.Peek(), ";s") == 0) { 1500 // Move past the ';', then do a simple 's'. 1501 packet.SetFilePos(packet.GetFilePos() + 1); 1502 return Handle_s(packet); 1503 } 1504 1505 // Ensure we have a native process. 1506 if (!m_debugged_process_up) { 1507 LLDB_LOG(log, "no debugged process"); 1508 return SendErrorResponse(0x36); 1509 } 1510 1511 ResumeActionList thread_actions; 1512 1513 while (packet.GetBytesLeft() && *packet.Peek() == ';') { 1514 // Skip the semi-colon. 1515 packet.GetChar(); 1516 1517 // Build up the thread action. 1518 ResumeAction thread_action; 1519 thread_action.tid = LLDB_INVALID_THREAD_ID; 1520 thread_action.state = eStateInvalid; 1521 thread_action.signal = 0; 1522 1523 const char action = packet.GetChar(); 1524 switch (action) { 1525 case 'C': 1526 thread_action.signal = packet.GetHexMaxU32(false, 0); 1527 if (thread_action.signal == 0) 1528 return SendIllFormedResponse( 1529 packet, "Could not parse signal in vCont packet C action"); 1530 LLVM_FALLTHROUGH; 1531 1532 case 'c': 1533 // Continue 1534 thread_action.state = eStateRunning; 1535 break; 1536 1537 case 'S': 1538 thread_action.signal = packet.GetHexMaxU32(false, 0); 1539 if (thread_action.signal == 0) 1540 return SendIllFormedResponse( 1541 packet, "Could not parse signal in vCont packet S action"); 1542 LLVM_FALLTHROUGH; 1543 1544 case 's': 1545 // Step 1546 thread_action.state = eStateStepping; 1547 break; 1548 1549 default: 1550 return SendIllFormedResponse(packet, "Unsupported vCont action"); 1551 break; 1552 } 1553 1554 // Parse out optional :{thread-id} value. 1555 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) { 1556 // Consume the separator. 1557 packet.GetChar(); 1558 1559 thread_action.tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID); 1560 if (thread_action.tid == LLDB_INVALID_THREAD_ID) 1561 return SendIllFormedResponse( 1562 packet, "Could not parse thread number in vCont packet"); 1563 } 1564 1565 thread_actions.Append(thread_action); 1566 } 1567 1568 Status error = m_debugged_process_up->Resume(thread_actions); 1569 if (error.Fail()) { 1570 LLDB_LOG(log, "vCont failed for process {0}: {1}", 1571 m_debugged_process_up->GetID(), error); 1572 return SendErrorResponse(GDBRemoteServerError::eErrorResume); 1573 } 1574 1575 LLDB_LOG(log, "continued process {0}", m_debugged_process_up->GetID()); 1576 // No response required from vCont. 1577 return PacketResult::Success; 1578 } 1579 1580 void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) { 1581 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 1582 LLDB_LOG(log, "setting current thread id to {0}", tid); 1583 1584 m_current_tid = tid; 1585 if (m_debugged_process_up) 1586 m_debugged_process_up->SetCurrentThreadID(m_current_tid); 1587 } 1588 1589 void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) { 1590 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 1591 LLDB_LOG(log, "setting continue thread id to {0}", tid); 1592 1593 m_continue_tid = tid; 1594 } 1595 1596 GDBRemoteCommunication::PacketResult 1597 GDBRemoteCommunicationServerLLGS::Handle_stop_reason( 1598 StringExtractorGDBRemote &packet) { 1599 // Handle the $? gdbremote command. 1600 1601 // If no process, indicate error 1602 if (!m_debugged_process_up) 1603 return SendErrorResponse(02); 1604 1605 return SendStopReasonForState(m_debugged_process_up->GetState()); 1606 } 1607 1608 GDBRemoteCommunication::PacketResult 1609 GDBRemoteCommunicationServerLLGS::SendStopReasonForState( 1610 lldb::StateType process_state) { 1611 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 1612 1613 switch (process_state) { 1614 case eStateAttaching: 1615 case eStateLaunching: 1616 case eStateRunning: 1617 case eStateStepping: 1618 case eStateDetached: 1619 // NOTE: gdb protocol doc looks like it should return $OK 1620 // when everything is running (i.e. no stopped result). 1621 return PacketResult::Success; // Ignore 1622 1623 case eStateSuspended: 1624 case eStateStopped: 1625 case eStateCrashed: { 1626 lldb::tid_t tid = m_debugged_process_up->GetCurrentThreadID(); 1627 // Make sure we set the current thread so g and p packets return the data 1628 // the gdb will expect. 1629 SetCurrentThreadID(tid); 1630 return SendStopReplyPacketForThread(tid); 1631 } 1632 1633 case eStateInvalid: 1634 case eStateUnloaded: 1635 case eStateExited: 1636 return SendWResponse(m_debugged_process_up.get()); 1637 1638 default: 1639 LLDB_LOG(log, "pid {0}, current state reporting not handled: {1}", 1640 m_debugged_process_up->GetID(), process_state); 1641 break; 1642 } 1643 1644 return SendErrorResponse(0); 1645 } 1646 1647 GDBRemoteCommunication::PacketResult 1648 GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo( 1649 StringExtractorGDBRemote &packet) { 1650 // Fail if we don't have a current process. 1651 if (!m_debugged_process_up || 1652 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) 1653 return SendErrorResponse(68); 1654 1655 // Ensure we have a thread. 1656 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadAtIndex(0); 1657 if (!thread) 1658 return SendErrorResponse(69); 1659 1660 // Get the register context for the first thread. 1661 NativeRegisterContext ®_context = thread->GetRegisterContext(); 1662 1663 // Parse out the register number from the request. 1664 packet.SetFilePos(strlen("qRegisterInfo")); 1665 const uint32_t reg_index = 1666 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 1667 if (reg_index == std::numeric_limits<uint32_t>::max()) 1668 return SendErrorResponse(69); 1669 1670 // Return the end of registers response if we've iterated one past the end of 1671 // the register set. 1672 if (reg_index >= reg_context.GetUserRegisterCount()) 1673 return SendErrorResponse(69); 1674 1675 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index); 1676 if (!reg_info) 1677 return SendErrorResponse(69); 1678 1679 // Build the reginfos response. 1680 StreamGDBRemote response; 1681 1682 response.PutCString("name:"); 1683 response.PutCString(reg_info->name); 1684 response.PutChar(';'); 1685 1686 if (reg_info->alt_name && reg_info->alt_name[0]) { 1687 response.PutCString("alt-name:"); 1688 response.PutCString(reg_info->alt_name); 1689 response.PutChar(';'); 1690 } 1691 1692 response.Printf("bitsize:%" PRIu32 ";offset:%" PRIu32 ";", 1693 reg_info->byte_size * 8, reg_info->byte_offset); 1694 1695 switch (reg_info->encoding) { 1696 case eEncodingUint: 1697 response.PutCString("encoding:uint;"); 1698 break; 1699 case eEncodingSint: 1700 response.PutCString("encoding:sint;"); 1701 break; 1702 case eEncodingIEEE754: 1703 response.PutCString("encoding:ieee754;"); 1704 break; 1705 case eEncodingVector: 1706 response.PutCString("encoding:vector;"); 1707 break; 1708 default: 1709 break; 1710 } 1711 1712 switch (reg_info->format) { 1713 case eFormatBinary: 1714 response.PutCString("format:binary;"); 1715 break; 1716 case eFormatDecimal: 1717 response.PutCString("format:decimal;"); 1718 break; 1719 case eFormatHex: 1720 response.PutCString("format:hex;"); 1721 break; 1722 case eFormatFloat: 1723 response.PutCString("format:float;"); 1724 break; 1725 case eFormatVectorOfSInt8: 1726 response.PutCString("format:vector-sint8;"); 1727 break; 1728 case eFormatVectorOfUInt8: 1729 response.PutCString("format:vector-uint8;"); 1730 break; 1731 case eFormatVectorOfSInt16: 1732 response.PutCString("format:vector-sint16;"); 1733 break; 1734 case eFormatVectorOfUInt16: 1735 response.PutCString("format:vector-uint16;"); 1736 break; 1737 case eFormatVectorOfSInt32: 1738 response.PutCString("format:vector-sint32;"); 1739 break; 1740 case eFormatVectorOfUInt32: 1741 response.PutCString("format:vector-uint32;"); 1742 break; 1743 case eFormatVectorOfFloat32: 1744 response.PutCString("format:vector-float32;"); 1745 break; 1746 case eFormatVectorOfUInt64: 1747 response.PutCString("format:vector-uint64;"); 1748 break; 1749 case eFormatVectorOfUInt128: 1750 response.PutCString("format:vector-uint128;"); 1751 break; 1752 default: 1753 break; 1754 }; 1755 1756 const char *const register_set_name = 1757 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index); 1758 if (register_set_name) { 1759 response.PutCString("set:"); 1760 response.PutCString(register_set_name); 1761 response.PutChar(';'); 1762 } 1763 1764 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] != 1765 LLDB_INVALID_REGNUM) 1766 response.Printf("ehframe:%" PRIu32 ";", 1767 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]); 1768 1769 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM) 1770 response.Printf("dwarf:%" PRIu32 ";", 1771 reg_info->kinds[RegisterKind::eRegisterKindDWARF]); 1772 1773 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric]) { 1774 case LLDB_REGNUM_GENERIC_PC: 1775 response.PutCString("generic:pc;"); 1776 break; 1777 case LLDB_REGNUM_GENERIC_SP: 1778 response.PutCString("generic:sp;"); 1779 break; 1780 case LLDB_REGNUM_GENERIC_FP: 1781 response.PutCString("generic:fp;"); 1782 break; 1783 case LLDB_REGNUM_GENERIC_RA: 1784 response.PutCString("generic:ra;"); 1785 break; 1786 case LLDB_REGNUM_GENERIC_FLAGS: 1787 response.PutCString("generic:flags;"); 1788 break; 1789 case LLDB_REGNUM_GENERIC_ARG1: 1790 response.PutCString("generic:arg1;"); 1791 break; 1792 case LLDB_REGNUM_GENERIC_ARG2: 1793 response.PutCString("generic:arg2;"); 1794 break; 1795 case LLDB_REGNUM_GENERIC_ARG3: 1796 response.PutCString("generic:arg3;"); 1797 break; 1798 case LLDB_REGNUM_GENERIC_ARG4: 1799 response.PutCString("generic:arg4;"); 1800 break; 1801 case LLDB_REGNUM_GENERIC_ARG5: 1802 response.PutCString("generic:arg5;"); 1803 break; 1804 case LLDB_REGNUM_GENERIC_ARG6: 1805 response.PutCString("generic:arg6;"); 1806 break; 1807 case LLDB_REGNUM_GENERIC_ARG7: 1808 response.PutCString("generic:arg7;"); 1809 break; 1810 case LLDB_REGNUM_GENERIC_ARG8: 1811 response.PutCString("generic:arg8;"); 1812 break; 1813 default: 1814 break; 1815 } 1816 1817 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) { 1818 response.PutCString("container-regs:"); 1819 int i = 0; 1820 for (const uint32_t *reg_num = reg_info->value_regs; 1821 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) { 1822 if (i > 0) 1823 response.PutChar(','); 1824 response.Printf("%" PRIx32, *reg_num); 1825 } 1826 response.PutChar(';'); 1827 } 1828 1829 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) { 1830 response.PutCString("invalidate-regs:"); 1831 int i = 0; 1832 for (const uint32_t *reg_num = reg_info->invalidate_regs; 1833 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) { 1834 if (i > 0) 1835 response.PutChar(','); 1836 response.Printf("%" PRIx32, *reg_num); 1837 } 1838 response.PutChar(';'); 1839 } 1840 1841 if (reg_info->dynamic_size_dwarf_expr_bytes) { 1842 const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len; 1843 response.PutCString("dynamic_size_dwarf_expr_bytes:"); 1844 for (uint32_t i = 0; i < dwarf_opcode_len; ++i) 1845 response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]); 1846 response.PutChar(';'); 1847 } 1848 return SendPacketNoLock(response.GetString()); 1849 } 1850 1851 GDBRemoteCommunication::PacketResult 1852 GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo( 1853 StringExtractorGDBRemote &packet) { 1854 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 1855 1856 // Fail if we don't have a current process. 1857 if (!m_debugged_process_up || 1858 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 1859 LLDB_LOG(log, "no process ({0}), returning OK", 1860 m_debugged_process_up ? "invalid process id" 1861 : "null m_debugged_process_up"); 1862 return SendOKResponse(); 1863 } 1864 1865 StreamGDBRemote response; 1866 response.PutChar('m'); 1867 1868 LLDB_LOG(log, "starting thread iteration"); 1869 NativeThreadProtocol *thread; 1870 uint32_t thread_index; 1871 for (thread_index = 0, 1872 thread = m_debugged_process_up->GetThreadAtIndex(thread_index); 1873 thread; ++thread_index, 1874 thread = m_debugged_process_up->GetThreadAtIndex(thread_index)) { 1875 LLDB_LOG(log, "iterated thread {0}(tid={2})", thread_index, 1876 thread->GetID()); 1877 if (thread_index > 0) 1878 response.PutChar(','); 1879 response.Printf("%" PRIx64, thread->GetID()); 1880 } 1881 1882 LLDB_LOG(log, "finished thread iteration"); 1883 return SendPacketNoLock(response.GetString()); 1884 } 1885 1886 GDBRemoteCommunication::PacketResult 1887 GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo( 1888 StringExtractorGDBRemote &packet) { 1889 // FIXME for now we return the full thread list in the initial packet and 1890 // always do nothing here. 1891 return SendPacketNoLock("l"); 1892 } 1893 1894 GDBRemoteCommunication::PacketResult 1895 GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) { 1896 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 1897 1898 // Parse out the register number from the request. 1899 packet.SetFilePos(strlen("p")); 1900 const uint32_t reg_index = 1901 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 1902 if (reg_index == std::numeric_limits<uint32_t>::max()) { 1903 if (log) 1904 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not " 1905 "parse register number from request \"%s\"", 1906 __FUNCTION__, packet.GetStringRef().c_str()); 1907 return SendErrorResponse(0x15); 1908 } 1909 1910 // Get the thread to use. 1911 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 1912 if (!thread) { 1913 LLDB_LOG(log, "failed, no thread available"); 1914 return SendErrorResponse(0x15); 1915 } 1916 1917 // Get the thread's register context. 1918 NativeRegisterContext ®_context = thread->GetRegisterContext(); 1919 1920 // Return the end of registers response if we've iterated one past the end of 1921 // the register set. 1922 if (reg_index >= reg_context.GetUserRegisterCount()) { 1923 if (log) 1924 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested " 1925 "register %" PRIu32 " beyond register count %" PRIu32, 1926 __FUNCTION__, reg_index, 1927 reg_context.GetUserRegisterCount()); 1928 return SendErrorResponse(0x15); 1929 } 1930 1931 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index); 1932 if (!reg_info) { 1933 if (log) 1934 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested " 1935 "register %" PRIu32 " returned NULL", 1936 __FUNCTION__, reg_index); 1937 return SendErrorResponse(0x15); 1938 } 1939 1940 // Build the reginfos response. 1941 StreamGDBRemote response; 1942 1943 // Retrieve the value 1944 RegisterValue reg_value; 1945 Status error = reg_context.ReadRegister(reg_info, reg_value); 1946 if (error.Fail()) { 1947 if (log) 1948 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, read of " 1949 "requested register %" PRIu32 " (%s) failed: %s", 1950 __FUNCTION__, reg_index, reg_info->name, error.AsCString()); 1951 return SendErrorResponse(0x15); 1952 } 1953 1954 const uint8_t *const data = 1955 reinterpret_cast<const uint8_t *>(reg_value.GetBytes()); 1956 if (!data) { 1957 if (log) 1958 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get data " 1959 "bytes from requested register %" PRIu32, 1960 __FUNCTION__, reg_index); 1961 return SendErrorResponse(0x15); 1962 } 1963 1964 // FIXME flip as needed to get data in big/little endian format for this host. 1965 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i) 1966 response.PutHex8(data[i]); 1967 1968 return SendPacketNoLock(response.GetString()); 1969 } 1970 1971 GDBRemoteCommunication::PacketResult 1972 GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) { 1973 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 1974 1975 // Ensure there is more content. 1976 if (packet.GetBytesLeft() < 1) 1977 return SendIllFormedResponse(packet, "Empty P packet"); 1978 1979 // Parse out the register number from the request. 1980 packet.SetFilePos(strlen("P")); 1981 const uint32_t reg_index = 1982 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 1983 if (reg_index == std::numeric_limits<uint32_t>::max()) { 1984 if (log) 1985 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not " 1986 "parse register number from request \"%s\"", 1987 __FUNCTION__, packet.GetStringRef().c_str()); 1988 return SendErrorResponse(0x29); 1989 } 1990 1991 // Note debugserver would send an E30 here. 1992 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '=')) 1993 return SendIllFormedResponse( 1994 packet, "P packet missing '=' char after register number"); 1995 1996 // Parse out the value. 1997 uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register 1998 size_t reg_size = packet.GetHexBytesAvail(reg_bytes); 1999 2000 // Get the thread to use. 2001 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 2002 if (!thread) { 2003 if (log) 2004 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, no thread " 2005 "available (thread index 0)", 2006 __FUNCTION__); 2007 return SendErrorResponse(0x28); 2008 } 2009 2010 // Get the thread's register context. 2011 NativeRegisterContext ®_context = thread->GetRegisterContext(); 2012 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index); 2013 if (!reg_info) { 2014 if (log) 2015 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested " 2016 "register %" PRIu32 " returned NULL", 2017 __FUNCTION__, reg_index); 2018 return SendErrorResponse(0x48); 2019 } 2020 2021 // Return the end of registers response if we've iterated one past the end of 2022 // the register set. 2023 if (reg_index >= reg_context.GetUserRegisterCount()) { 2024 if (log) 2025 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested " 2026 "register %" PRIu32 " beyond register count %" PRIu32, 2027 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount()); 2028 return SendErrorResponse(0x47); 2029 } 2030 2031 // The dwarf expression are evaluate on host site which may cause register 2032 // size to change Hence the reg_size may not be same as reg_info->bytes_size 2033 if ((reg_size != reg_info->byte_size) && 2034 !(reg_info->dynamic_size_dwarf_expr_bytes)) { 2035 return SendIllFormedResponse(packet, "P packet register size is incorrect"); 2036 } 2037 2038 // Build the reginfos response. 2039 StreamGDBRemote response; 2040 2041 RegisterValue reg_value( 2042 reg_bytes, reg_size, 2043 m_debugged_process_up->GetArchitecture().GetByteOrder()); 2044 Status error = reg_context.WriteRegister(reg_info, reg_value); 2045 if (error.Fail()) { 2046 if (log) 2047 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, write of " 2048 "requested register %" PRIu32 " (%s) failed: %s", 2049 __FUNCTION__, reg_index, reg_info->name, error.AsCString()); 2050 return SendErrorResponse(0x32); 2051 } 2052 2053 return SendOKResponse(); 2054 } 2055 2056 GDBRemoteCommunication::PacketResult 2057 GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) { 2058 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 2059 2060 // Fail if we don't have a current process. 2061 if (!m_debugged_process_up || 2062 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2063 if (log) 2064 log->Printf( 2065 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2066 __FUNCTION__); 2067 return SendErrorResponse(0x15); 2068 } 2069 2070 // Parse out which variant of $H is requested. 2071 packet.SetFilePos(strlen("H")); 2072 if (packet.GetBytesLeft() < 1) { 2073 if (log) 2074 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, H command " 2075 "missing {g,c} variant", 2076 __FUNCTION__); 2077 return SendIllFormedResponse(packet, "H command missing {g,c} variant"); 2078 } 2079 2080 const char h_variant = packet.GetChar(); 2081 switch (h_variant) { 2082 case 'g': 2083 break; 2084 2085 case 'c': 2086 break; 2087 2088 default: 2089 if (log) 2090 log->Printf( 2091 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c", 2092 __FUNCTION__, h_variant); 2093 return SendIllFormedResponse(packet, 2094 "H variant unsupported, should be c or g"); 2095 } 2096 2097 // Parse out the thread number. 2098 // FIXME return a parse success/fail value. All values are valid here. 2099 const lldb::tid_t tid = 2100 packet.GetHexMaxU64(false, std::numeric_limits<lldb::tid_t>::max()); 2101 2102 // Ensure we have the given thread when not specifying -1 (all threads) or 0 2103 // (any thread). 2104 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) { 2105 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid); 2106 if (!thread) { 2107 if (log) 2108 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64 2109 " not found", 2110 __FUNCTION__, tid); 2111 return SendErrorResponse(0x15); 2112 } 2113 } 2114 2115 // Now switch the given thread type. 2116 switch (h_variant) { 2117 case 'g': 2118 SetCurrentThreadID(tid); 2119 break; 2120 2121 case 'c': 2122 SetContinueThreadID(tid); 2123 break; 2124 2125 default: 2126 assert(false && "unsupported $H variant - shouldn't get here"); 2127 return SendIllFormedResponse(packet, 2128 "H variant unsupported, should be c or g"); 2129 } 2130 2131 return SendOKResponse(); 2132 } 2133 2134 GDBRemoteCommunication::PacketResult 2135 GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) { 2136 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 2137 2138 // Fail if we don't have a current process. 2139 if (!m_debugged_process_up || 2140 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2141 if (log) 2142 log->Printf( 2143 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2144 __FUNCTION__); 2145 return SendErrorResponse(0x15); 2146 } 2147 2148 packet.SetFilePos(::strlen("I")); 2149 uint8_t tmp[4096]; 2150 for (;;) { 2151 size_t read = packet.GetHexBytesAvail(tmp); 2152 if (read == 0) { 2153 break; 2154 } 2155 // write directly to stdin *this might block if stdin buffer is full* 2156 // TODO: enqueue this block in circular buffer and send window size to 2157 // remote host 2158 ConnectionStatus status; 2159 Status error; 2160 m_stdio_communication.Write(tmp, read, status, &error); 2161 if (error.Fail()) { 2162 return SendErrorResponse(0x15); 2163 } 2164 } 2165 2166 return SendOKResponse(); 2167 } 2168 2169 GDBRemoteCommunication::PacketResult 2170 GDBRemoteCommunicationServerLLGS::Handle_interrupt( 2171 StringExtractorGDBRemote &packet) { 2172 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 2173 2174 // Fail if we don't have a current process. 2175 if (!m_debugged_process_up || 2176 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2177 LLDB_LOG(log, "failed, no process available"); 2178 return SendErrorResponse(0x15); 2179 } 2180 2181 // Interrupt the process. 2182 Status error = m_debugged_process_up->Interrupt(); 2183 if (error.Fail()) { 2184 LLDB_LOG(log, "failed for process {0}: {1}", m_debugged_process_up->GetID(), 2185 error); 2186 return SendErrorResponse(GDBRemoteServerError::eErrorResume); 2187 } 2188 2189 LLDB_LOG(log, "stopped process {0}", m_debugged_process_up->GetID()); 2190 2191 // No response required from stop all. 2192 return PacketResult::Success; 2193 } 2194 2195 GDBRemoteCommunication::PacketResult 2196 GDBRemoteCommunicationServerLLGS::Handle_memory_read( 2197 StringExtractorGDBRemote &packet) { 2198 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2199 2200 if (!m_debugged_process_up || 2201 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2202 if (log) 2203 log->Printf( 2204 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2205 __FUNCTION__); 2206 return SendErrorResponse(0x15); 2207 } 2208 2209 // Parse out the memory address. 2210 packet.SetFilePos(strlen("m")); 2211 if (packet.GetBytesLeft() < 1) 2212 return SendIllFormedResponse(packet, "Too short m packet"); 2213 2214 // Read the address. Punting on validation. 2215 // FIXME replace with Hex U64 read with no default value that fails on failed 2216 // read. 2217 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0); 2218 2219 // Validate comma. 2220 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ',')) 2221 return SendIllFormedResponse(packet, "Comma sep missing in m packet"); 2222 2223 // Get # bytes to read. 2224 if (packet.GetBytesLeft() < 1) 2225 return SendIllFormedResponse(packet, "Length missing in m packet"); 2226 2227 const uint64_t byte_count = packet.GetHexMaxU64(false, 0); 2228 if (byte_count == 0) { 2229 if (log) 2230 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to read: " 2231 "zero-length packet", 2232 __FUNCTION__); 2233 return SendOKResponse(); 2234 } 2235 2236 // Allocate the response buffer. 2237 std::string buf(byte_count, '\0'); 2238 if (buf.empty()) 2239 return SendErrorResponse(0x78); 2240 2241 // Retrieve the process memory. 2242 size_t bytes_read = 0; 2243 Status error = m_debugged_process_up->ReadMemoryWithoutTrap( 2244 read_addr, &buf[0], byte_count, bytes_read); 2245 if (error.Fail()) { 2246 if (log) 2247 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 2248 " mem 0x%" PRIx64 ": failed to read. Error: %s", 2249 __FUNCTION__, m_debugged_process_up->GetID(), read_addr, 2250 error.AsCString()); 2251 return SendErrorResponse(0x08); 2252 } 2253 2254 if (bytes_read == 0) { 2255 if (log) 2256 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 2257 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes", 2258 __FUNCTION__, m_debugged_process_up->GetID(), read_addr, 2259 byte_count); 2260 return SendErrorResponse(0x08); 2261 } 2262 2263 StreamGDBRemote response; 2264 packet.SetFilePos(0); 2265 char kind = packet.GetChar('?'); 2266 if (kind == 'x') 2267 response.PutEscapedBytes(buf.data(), byte_count); 2268 else { 2269 assert(kind == 'm'); 2270 for (size_t i = 0; i < bytes_read; ++i) 2271 response.PutHex8(buf[i]); 2272 } 2273 2274 return SendPacketNoLock(response.GetString()); 2275 } 2276 2277 GDBRemoteCommunication::PacketResult 2278 GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) { 2279 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2280 2281 if (!m_debugged_process_up || 2282 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2283 if (log) 2284 log->Printf( 2285 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2286 __FUNCTION__); 2287 return SendErrorResponse(0x15); 2288 } 2289 2290 // Parse out the memory address. 2291 packet.SetFilePos(strlen("M")); 2292 if (packet.GetBytesLeft() < 1) 2293 return SendIllFormedResponse(packet, "Too short M packet"); 2294 2295 // Read the address. Punting on validation. 2296 // FIXME replace with Hex U64 read with no default value that fails on failed 2297 // read. 2298 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0); 2299 2300 // Validate comma. 2301 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ',')) 2302 return SendIllFormedResponse(packet, "Comma sep missing in M packet"); 2303 2304 // Get # bytes to read. 2305 if (packet.GetBytesLeft() < 1) 2306 return SendIllFormedResponse(packet, "Length missing in M packet"); 2307 2308 const uint64_t byte_count = packet.GetHexMaxU64(false, 0); 2309 if (byte_count == 0) { 2310 LLDB_LOG(log, "nothing to write: zero-length packet"); 2311 return PacketResult::Success; 2312 } 2313 2314 // Validate colon. 2315 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':')) 2316 return SendIllFormedResponse( 2317 packet, "Comma sep missing in M packet after byte length"); 2318 2319 // Allocate the conversion buffer. 2320 std::vector<uint8_t> buf(byte_count, 0); 2321 if (buf.empty()) 2322 return SendErrorResponse(0x78); 2323 2324 // Convert the hex memory write contents to bytes. 2325 StreamGDBRemote response; 2326 const uint64_t convert_count = packet.GetHexBytes(buf, 0); 2327 if (convert_count != byte_count) { 2328 LLDB_LOG(log, 2329 "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} " 2330 "to convert.", 2331 m_debugged_process_up->GetID(), write_addr, byte_count, 2332 convert_count); 2333 return SendIllFormedResponse(packet, "M content byte length specified did " 2334 "not match hex-encoded content " 2335 "length"); 2336 } 2337 2338 // Write the process memory. 2339 size_t bytes_written = 0; 2340 Status error = m_debugged_process_up->WriteMemory(write_addr, &buf[0], 2341 byte_count, bytes_written); 2342 if (error.Fail()) { 2343 LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}", 2344 m_debugged_process_up->GetID(), write_addr, error); 2345 return SendErrorResponse(0x09); 2346 } 2347 2348 if (bytes_written == 0) { 2349 LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes", 2350 m_debugged_process_up->GetID(), write_addr, byte_count); 2351 return SendErrorResponse(0x09); 2352 } 2353 2354 return SendOKResponse(); 2355 } 2356 2357 GDBRemoteCommunication::PacketResult 2358 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported( 2359 StringExtractorGDBRemote &packet) { 2360 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2361 2362 // Currently only the NativeProcessProtocol knows if it can handle a 2363 // qMemoryRegionInfoSupported request, but we're not guaranteed to be 2364 // attached to a process. For now we'll assume the client only asks this 2365 // when a process is being debugged. 2366 2367 // Ensure we have a process running; otherwise, we can't figure this out 2368 // since we won't have a NativeProcessProtocol. 2369 if (!m_debugged_process_up || 2370 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2371 if (log) 2372 log->Printf( 2373 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2374 __FUNCTION__); 2375 return SendErrorResponse(0x15); 2376 } 2377 2378 // Test if we can get any region back when asking for the region around NULL. 2379 MemoryRegionInfo region_info; 2380 const Status error = 2381 m_debugged_process_up->GetMemoryRegionInfo(0, region_info); 2382 if (error.Fail()) { 2383 // We don't support memory region info collection for this 2384 // NativeProcessProtocol. 2385 return SendUnimplementedResponse(""); 2386 } 2387 2388 return SendOKResponse(); 2389 } 2390 2391 GDBRemoteCommunication::PacketResult 2392 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo( 2393 StringExtractorGDBRemote &packet) { 2394 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2395 2396 // Ensure we have a process. 2397 if (!m_debugged_process_up || 2398 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2399 if (log) 2400 log->Printf( 2401 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2402 __FUNCTION__); 2403 return SendErrorResponse(0x15); 2404 } 2405 2406 // Parse out the memory address. 2407 packet.SetFilePos(strlen("qMemoryRegionInfo:")); 2408 if (packet.GetBytesLeft() < 1) 2409 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet"); 2410 2411 // Read the address. Punting on validation. 2412 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0); 2413 2414 StreamGDBRemote response; 2415 2416 // Get the memory region info for the target address. 2417 MemoryRegionInfo region_info; 2418 const Status error = 2419 m_debugged_process_up->GetMemoryRegionInfo(read_addr, region_info); 2420 if (error.Fail()) { 2421 // Return the error message. 2422 2423 response.PutCString("error:"); 2424 response.PutStringAsRawHex8(error.AsCString()); 2425 response.PutChar(';'); 2426 } else { 2427 // Range start and size. 2428 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";", 2429 region_info.GetRange().GetRangeBase(), 2430 region_info.GetRange().GetByteSize()); 2431 2432 // Permissions. 2433 if (region_info.GetReadable() || region_info.GetWritable() || 2434 region_info.GetExecutable()) { 2435 // Write permissions info. 2436 response.PutCString("permissions:"); 2437 2438 if (region_info.GetReadable()) 2439 response.PutChar('r'); 2440 if (region_info.GetWritable()) 2441 response.PutChar('w'); 2442 if (region_info.GetExecutable()) 2443 response.PutChar('x'); 2444 2445 response.PutChar(';'); 2446 } 2447 2448 // Name 2449 ConstString name = region_info.GetName(); 2450 if (name) { 2451 response.PutCString("name:"); 2452 response.PutStringAsRawHex8(name.AsCString()); 2453 response.PutChar(';'); 2454 } 2455 } 2456 2457 return SendPacketNoLock(response.GetString()); 2458 } 2459 2460 GDBRemoteCommunication::PacketResult 2461 GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) { 2462 // Ensure we have a process. 2463 if (!m_debugged_process_up || 2464 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2465 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2466 LLDB_LOG(log, "failed, no process available"); 2467 return SendErrorResponse(0x15); 2468 } 2469 2470 // Parse out software or hardware breakpoint or watchpoint requested. 2471 packet.SetFilePos(strlen("Z")); 2472 if (packet.GetBytesLeft() < 1) 2473 return SendIllFormedResponse( 2474 packet, "Too short Z packet, missing software/hardware specifier"); 2475 2476 bool want_breakpoint = true; 2477 bool want_hardware = false; 2478 uint32_t watch_flags = 0; 2479 2480 const GDBStoppointType stoppoint_type = 2481 GDBStoppointType(packet.GetS32(eStoppointInvalid)); 2482 switch (stoppoint_type) { 2483 case eBreakpointSoftware: 2484 want_hardware = false; 2485 want_breakpoint = true; 2486 break; 2487 case eBreakpointHardware: 2488 want_hardware = true; 2489 want_breakpoint = true; 2490 break; 2491 case eWatchpointWrite: 2492 watch_flags = 1; 2493 want_hardware = true; 2494 want_breakpoint = false; 2495 break; 2496 case eWatchpointRead: 2497 watch_flags = 2; 2498 want_hardware = true; 2499 want_breakpoint = false; 2500 break; 2501 case eWatchpointReadWrite: 2502 watch_flags = 3; 2503 want_hardware = true; 2504 want_breakpoint = false; 2505 break; 2506 case eStoppointInvalid: 2507 return SendIllFormedResponse( 2508 packet, "Z packet had invalid software/hardware specifier"); 2509 } 2510 2511 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',') 2512 return SendIllFormedResponse( 2513 packet, "Malformed Z packet, expecting comma after stoppoint type"); 2514 2515 // Parse out the stoppoint address. 2516 if (packet.GetBytesLeft() < 1) 2517 return SendIllFormedResponse(packet, "Too short Z packet, missing address"); 2518 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0); 2519 2520 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',') 2521 return SendIllFormedResponse( 2522 packet, "Malformed Z packet, expecting comma after address"); 2523 2524 // Parse out the stoppoint size (i.e. size hint for opcode size). 2525 const uint32_t size = 2526 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 2527 if (size == std::numeric_limits<uint32_t>::max()) 2528 return SendIllFormedResponse( 2529 packet, "Malformed Z packet, failed to parse size argument"); 2530 2531 if (want_breakpoint) { 2532 // Try to set the breakpoint. 2533 const Status error = 2534 m_debugged_process_up->SetBreakpoint(addr, size, want_hardware); 2535 if (error.Success()) 2536 return SendOKResponse(); 2537 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); 2538 LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}", 2539 m_debugged_process_up->GetID(), error); 2540 return SendErrorResponse(0x09); 2541 } else { 2542 // Try to set the watchpoint. 2543 const Status error = m_debugged_process_up->SetWatchpoint( 2544 addr, size, watch_flags, want_hardware); 2545 if (error.Success()) 2546 return SendOKResponse(); 2547 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS)); 2548 LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}", 2549 m_debugged_process_up->GetID(), error); 2550 return SendErrorResponse(0x09); 2551 } 2552 } 2553 2554 GDBRemoteCommunication::PacketResult 2555 GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) { 2556 // Ensure we have a process. 2557 if (!m_debugged_process_up || 2558 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2559 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2560 LLDB_LOG(log, "failed, no process available"); 2561 return SendErrorResponse(0x15); 2562 } 2563 2564 // Parse out software or hardware breakpoint or watchpoint requested. 2565 packet.SetFilePos(strlen("z")); 2566 if (packet.GetBytesLeft() < 1) 2567 return SendIllFormedResponse( 2568 packet, "Too short z packet, missing software/hardware specifier"); 2569 2570 bool want_breakpoint = true; 2571 bool want_hardware = false; 2572 2573 const GDBStoppointType stoppoint_type = 2574 GDBStoppointType(packet.GetS32(eStoppointInvalid)); 2575 switch (stoppoint_type) { 2576 case eBreakpointHardware: 2577 want_breakpoint = true; 2578 want_hardware = true; 2579 break; 2580 case eBreakpointSoftware: 2581 want_breakpoint = true; 2582 break; 2583 case eWatchpointWrite: 2584 want_breakpoint = false; 2585 break; 2586 case eWatchpointRead: 2587 want_breakpoint = false; 2588 break; 2589 case eWatchpointReadWrite: 2590 want_breakpoint = false; 2591 break; 2592 default: 2593 return SendIllFormedResponse( 2594 packet, "z packet had invalid software/hardware specifier"); 2595 } 2596 2597 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',') 2598 return SendIllFormedResponse( 2599 packet, "Malformed z packet, expecting comma after stoppoint type"); 2600 2601 // Parse out the stoppoint address. 2602 if (packet.GetBytesLeft() < 1) 2603 return SendIllFormedResponse(packet, "Too short z packet, missing address"); 2604 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0); 2605 2606 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',') 2607 return SendIllFormedResponse( 2608 packet, "Malformed z packet, expecting comma after address"); 2609 2610 /* 2611 // Parse out the stoppoint size (i.e. size hint for opcode size). 2612 const uint32_t size = packet.GetHexMaxU32 (false, 2613 std::numeric_limits<uint32_t>::max ()); 2614 if (size == std::numeric_limits<uint32_t>::max ()) 2615 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse 2616 size argument"); 2617 */ 2618 2619 if (want_breakpoint) { 2620 // Try to clear the breakpoint. 2621 const Status error = 2622 m_debugged_process_up->RemoveBreakpoint(addr, want_hardware); 2623 if (error.Success()) 2624 return SendOKResponse(); 2625 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); 2626 LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}", 2627 m_debugged_process_up->GetID(), error); 2628 return SendErrorResponse(0x09); 2629 } else { 2630 // Try to clear the watchpoint. 2631 const Status error = m_debugged_process_up->RemoveWatchpoint(addr); 2632 if (error.Success()) 2633 return SendOKResponse(); 2634 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS)); 2635 LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}", 2636 m_debugged_process_up->GetID(), error); 2637 return SendErrorResponse(0x09); 2638 } 2639 } 2640 2641 GDBRemoteCommunication::PacketResult 2642 GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) { 2643 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 2644 2645 // Ensure we have a process. 2646 if (!m_debugged_process_up || 2647 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2648 if (log) 2649 log->Printf( 2650 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2651 __FUNCTION__); 2652 return SendErrorResponse(0x32); 2653 } 2654 2655 // We first try to use a continue thread id. If any one or any all set, use 2656 // the current thread. Bail out if we don't have a thread id. 2657 lldb::tid_t tid = GetContinueThreadID(); 2658 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID) 2659 tid = GetCurrentThreadID(); 2660 if (tid == LLDB_INVALID_THREAD_ID) 2661 return SendErrorResponse(0x33); 2662 2663 // Double check that we have such a thread. 2664 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here. 2665 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid); 2666 if (!thread) 2667 return SendErrorResponse(0x33); 2668 2669 // Create the step action for the given thread. 2670 ResumeAction action = {tid, eStateStepping, 0}; 2671 2672 // Setup the actions list. 2673 ResumeActionList actions; 2674 actions.Append(action); 2675 2676 // All other threads stop while we're single stepping a thread. 2677 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0); 2678 Status error = m_debugged_process_up->Resume(actions); 2679 if (error.Fail()) { 2680 if (log) 2681 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 2682 " tid %" PRIu64 " Resume() failed with error: %s", 2683 __FUNCTION__, m_debugged_process_up->GetID(), tid, 2684 error.AsCString()); 2685 return SendErrorResponse(0x49); 2686 } 2687 2688 // No response here - the stop or exit will come from the resulting action. 2689 return PacketResult::Success; 2690 } 2691 2692 GDBRemoteCommunication::PacketResult 2693 GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read( 2694 StringExtractorGDBRemote &packet) { 2695 // *BSD impls should be able to do this too. 2696 #if defined(__linux__) || defined(__NetBSD__) 2697 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2698 2699 // Parse out the offset. 2700 packet.SetFilePos(strlen("qXfer:auxv:read::")); 2701 if (packet.GetBytesLeft() < 1) 2702 return SendIllFormedResponse(packet, 2703 "qXfer:auxv:read:: packet missing offset"); 2704 2705 const uint64_t auxv_offset = 2706 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max()); 2707 if (auxv_offset == std::numeric_limits<uint64_t>::max()) 2708 return SendIllFormedResponse(packet, 2709 "qXfer:auxv:read:: packet missing offset"); 2710 2711 // Parse out comma. 2712 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ',') 2713 return SendIllFormedResponse( 2714 packet, "qXfer:auxv:read:: packet missing comma after offset"); 2715 2716 // Parse out the length. 2717 const uint64_t auxv_length = 2718 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max()); 2719 if (auxv_length == std::numeric_limits<uint64_t>::max()) 2720 return SendIllFormedResponse(packet, 2721 "qXfer:auxv:read:: packet missing length"); 2722 2723 // Grab the auxv data if we need it. 2724 if (!m_active_auxv_buffer_up) { 2725 // Make sure we have a valid process. 2726 if (!m_debugged_process_up || 2727 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2728 if (log) 2729 log->Printf( 2730 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2731 __FUNCTION__); 2732 return SendErrorResponse(0x10); 2733 } 2734 2735 // Grab the auxv data. 2736 auto buffer_or_error = m_debugged_process_up->GetAuxvData(); 2737 if (!buffer_or_error) { 2738 std::error_code ec = buffer_or_error.getError(); 2739 LLDB_LOG(log, "no auxv data retrieved: {0}", ec.message()); 2740 return SendErrorResponse(ec.value()); 2741 } 2742 m_active_auxv_buffer_up = std::move(*buffer_or_error); 2743 } 2744 2745 StreamGDBRemote response; 2746 bool done_with_buffer = false; 2747 2748 llvm::StringRef buffer = m_active_auxv_buffer_up->getBuffer(); 2749 if (auxv_offset >= buffer.size()) { 2750 // We have nothing left to send. Mark the buffer as complete. 2751 response.PutChar('l'); 2752 done_with_buffer = true; 2753 } else { 2754 // Figure out how many bytes are available starting at the given offset. 2755 buffer = buffer.drop_front(auxv_offset); 2756 2757 // Mark the response type according to whether we're reading the remainder 2758 // of the auxv data. 2759 if (auxv_length >= buffer.size()) { 2760 // There will be nothing left to read after this 2761 response.PutChar('l'); 2762 done_with_buffer = true; 2763 } else { 2764 // There will still be bytes to read after this request. 2765 response.PutChar('m'); 2766 buffer = buffer.take_front(auxv_length); 2767 } 2768 2769 // Now write the data in encoded binary form. 2770 response.PutEscapedBytes(buffer.data(), buffer.size()); 2771 } 2772 2773 if (done_with_buffer) 2774 m_active_auxv_buffer_up.reset(); 2775 2776 return SendPacketNoLock(response.GetString()); 2777 #else 2778 return SendUnimplementedResponse("not implemented on this platform"); 2779 #endif 2780 } 2781 2782 GDBRemoteCommunication::PacketResult 2783 GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState( 2784 StringExtractorGDBRemote &packet) { 2785 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 2786 2787 // Move past packet name. 2788 packet.SetFilePos(strlen("QSaveRegisterState")); 2789 2790 // Get the thread to use. 2791 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 2792 if (!thread) { 2793 if (m_thread_suffix_supported) 2794 return SendIllFormedResponse( 2795 packet, "No thread specified in QSaveRegisterState packet"); 2796 else 2797 return SendIllFormedResponse(packet, 2798 "No thread was is set with the Hg packet"); 2799 } 2800 2801 // Grab the register context for the thread. 2802 NativeRegisterContext& reg_context = thread->GetRegisterContext(); 2803 2804 // Save registers to a buffer. 2805 DataBufferSP register_data_sp; 2806 Status error = reg_context.ReadAllRegisterValues(register_data_sp); 2807 if (error.Fail()) { 2808 LLDB_LOG(log, "pid {0} failed to save all register values: {1}", 2809 m_debugged_process_up->GetID(), error); 2810 return SendErrorResponse(0x75); 2811 } 2812 2813 // Allocate a new save id. 2814 const uint32_t save_id = GetNextSavedRegistersID(); 2815 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) && 2816 "GetNextRegisterSaveID() returned an existing register save id"); 2817 2818 // Save the register data buffer under the save id. 2819 { 2820 std::lock_guard<std::mutex> guard(m_saved_registers_mutex); 2821 m_saved_registers_map[save_id] = register_data_sp; 2822 } 2823 2824 // Write the response. 2825 StreamGDBRemote response; 2826 response.Printf("%" PRIu32, save_id); 2827 return SendPacketNoLock(response.GetString()); 2828 } 2829 2830 GDBRemoteCommunication::PacketResult 2831 GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState( 2832 StringExtractorGDBRemote &packet) { 2833 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 2834 2835 // Parse out save id. 2836 packet.SetFilePos(strlen("QRestoreRegisterState:")); 2837 if (packet.GetBytesLeft() < 1) 2838 return SendIllFormedResponse( 2839 packet, "QRestoreRegisterState packet missing register save id"); 2840 2841 const uint32_t save_id = packet.GetU32(0); 2842 if (save_id == 0) { 2843 LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, " 2844 "expecting decimal uint32_t"); 2845 return SendErrorResponse(0x76); 2846 } 2847 2848 // Get the thread to use. 2849 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 2850 if (!thread) { 2851 if (m_thread_suffix_supported) 2852 return SendIllFormedResponse( 2853 packet, "No thread specified in QRestoreRegisterState packet"); 2854 else 2855 return SendIllFormedResponse(packet, 2856 "No thread was is set with the Hg packet"); 2857 } 2858 2859 // Grab the register context for the thread. 2860 NativeRegisterContext ®_context = thread->GetRegisterContext(); 2861 2862 // Retrieve register state buffer, then remove from the list. 2863 DataBufferSP register_data_sp; 2864 { 2865 std::lock_guard<std::mutex> guard(m_saved_registers_mutex); 2866 2867 // Find the register set buffer for the given save id. 2868 auto it = m_saved_registers_map.find(save_id); 2869 if (it == m_saved_registers_map.end()) { 2870 LLDB_LOG(log, 2871 "pid {0} does not have a register set save buffer for id {1}", 2872 m_debugged_process_up->GetID(), save_id); 2873 return SendErrorResponse(0x77); 2874 } 2875 register_data_sp = it->second; 2876 2877 // Remove it from the map. 2878 m_saved_registers_map.erase(it); 2879 } 2880 2881 Status error = reg_context.WriteAllRegisterValues(register_data_sp); 2882 if (error.Fail()) { 2883 LLDB_LOG(log, "pid {0} failed to restore all register values: {1}", 2884 m_debugged_process_up->GetID(), error); 2885 return SendErrorResponse(0x77); 2886 } 2887 2888 return SendOKResponse(); 2889 } 2890 2891 GDBRemoteCommunication::PacketResult 2892 GDBRemoteCommunicationServerLLGS::Handle_vAttach( 2893 StringExtractorGDBRemote &packet) { 2894 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2895 2896 // Consume the ';' after vAttach. 2897 packet.SetFilePos(strlen("vAttach")); 2898 if (!packet.GetBytesLeft() || packet.GetChar() != ';') 2899 return SendIllFormedResponse(packet, "vAttach missing expected ';'"); 2900 2901 // Grab the PID to which we will attach (assume hex encoding). 2902 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16); 2903 if (pid == LLDB_INVALID_PROCESS_ID) 2904 return SendIllFormedResponse(packet, 2905 "vAttach failed to parse the process id"); 2906 2907 // Attempt to attach. 2908 if (log) 2909 log->Printf("GDBRemoteCommunicationServerLLGS::%s attempting to attach to " 2910 "pid %" PRIu64, 2911 __FUNCTION__, pid); 2912 2913 Status error = AttachToProcess(pid); 2914 2915 if (error.Fail()) { 2916 if (log) 2917 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to attach to " 2918 "pid %" PRIu64 ": %s\n", 2919 __FUNCTION__, pid, error.AsCString()); 2920 return SendErrorResponse(error); 2921 } 2922 2923 // Notify we attached by sending a stop packet. 2924 return SendStopReasonForState(m_debugged_process_up->GetState()); 2925 } 2926 2927 GDBRemoteCommunication::PacketResult 2928 GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) { 2929 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 2930 2931 StopSTDIOForwarding(); 2932 2933 // Fail if we don't have a current process. 2934 if (!m_debugged_process_up || 2935 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { 2936 if (log) 2937 log->Printf( 2938 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2939 __FUNCTION__); 2940 return SendErrorResponse(0x15); 2941 } 2942 2943 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; 2944 2945 // Consume the ';' after D. 2946 packet.SetFilePos(1); 2947 if (packet.GetBytesLeft()) { 2948 if (packet.GetChar() != ';') 2949 return SendIllFormedResponse(packet, "D missing expected ';'"); 2950 2951 // Grab the PID from which we will detach (assume hex encoding). 2952 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16); 2953 if (pid == LLDB_INVALID_PROCESS_ID) 2954 return SendIllFormedResponse(packet, "D failed to parse the process id"); 2955 } 2956 2957 if (pid != LLDB_INVALID_PROCESS_ID && m_debugged_process_up->GetID() != pid) { 2958 return SendIllFormedResponse(packet, "Invalid pid"); 2959 } 2960 2961 const Status error = m_debugged_process_up->Detach(); 2962 if (error.Fail()) { 2963 if (log) 2964 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to detach from " 2965 "pid %" PRIu64 ": %s\n", 2966 __FUNCTION__, m_debugged_process_up->GetID(), 2967 error.AsCString()); 2968 return SendErrorResponse(0x01); 2969 } 2970 2971 return SendOKResponse(); 2972 } 2973 2974 GDBRemoteCommunication::PacketResult 2975 GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo( 2976 StringExtractorGDBRemote &packet) { 2977 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 2978 2979 packet.SetFilePos(strlen("qThreadStopInfo")); 2980 const lldb::tid_t tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID); 2981 if (tid == LLDB_INVALID_THREAD_ID) { 2982 if (log) 2983 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not " 2984 "parse thread id from request \"%s\"", 2985 __FUNCTION__, packet.GetStringRef().c_str()); 2986 return SendErrorResponse(0x15); 2987 } 2988 return SendStopReplyPacketForThread(tid); 2989 } 2990 2991 GDBRemoteCommunication::PacketResult 2992 GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo( 2993 StringExtractorGDBRemote &) { 2994 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 2995 2996 // Ensure we have a debugged process. 2997 if (!m_debugged_process_up || 2998 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) 2999 return SendErrorResponse(50); 3000 LLDB_LOG(log, "preparing packet for pid {0}", m_debugged_process_up->GetID()); 3001 3002 StreamString response; 3003 const bool threads_with_valid_stop_info_only = false; 3004 JSONArray::SP threads_array_sp = GetJSONThreadsInfo( 3005 *m_debugged_process_up, threads_with_valid_stop_info_only); 3006 if (!threads_array_sp) { 3007 LLDB_LOG(log, "failed to prepare a packet for pid {0}", 3008 m_debugged_process_up->GetID()); 3009 return SendErrorResponse(52); 3010 } 3011 3012 threads_array_sp->Write(response); 3013 StreamGDBRemote escaped_response; 3014 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize()); 3015 return SendPacketNoLock(escaped_response.GetString()); 3016 } 3017 3018 GDBRemoteCommunication::PacketResult 3019 GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo( 3020 StringExtractorGDBRemote &packet) { 3021 // Fail if we don't have a current process. 3022 if (!m_debugged_process_up || 3023 m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID) 3024 return SendErrorResponse(68); 3025 3026 packet.SetFilePos(strlen("qWatchpointSupportInfo")); 3027 if (packet.GetBytesLeft() == 0) 3028 return SendOKResponse(); 3029 if (packet.GetChar() != ':') 3030 return SendErrorResponse(67); 3031 3032 auto hw_debug_cap = m_debugged_process_up->GetHardwareDebugSupportInfo(); 3033 3034 StreamGDBRemote response; 3035 if (hw_debug_cap == llvm::None) 3036 response.Printf("num:0;"); 3037 else 3038 response.Printf("num:%d;", hw_debug_cap->second); 3039 3040 return SendPacketNoLock(response.GetString()); 3041 } 3042 3043 GDBRemoteCommunication::PacketResult 3044 GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress( 3045 StringExtractorGDBRemote &packet) { 3046 // Fail if we don't have a current process. 3047 if (!m_debugged_process_up || 3048 m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID) 3049 return SendErrorResponse(67); 3050 3051 packet.SetFilePos(strlen("qFileLoadAddress:")); 3052 if (packet.GetBytesLeft() == 0) 3053 return SendErrorResponse(68); 3054 3055 std::string file_name; 3056 packet.GetHexByteString(file_name); 3057 3058 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS; 3059 Status error = 3060 m_debugged_process_up->GetFileLoadAddress(file_name, file_load_address); 3061 if (error.Fail()) 3062 return SendErrorResponse(69); 3063 3064 if (file_load_address == LLDB_INVALID_ADDRESS) 3065 return SendErrorResponse(1); // File not loaded 3066 3067 StreamGDBRemote response; 3068 response.PutHex64(file_load_address); 3069 return SendPacketNoLock(response.GetString()); 3070 } 3071 3072 GDBRemoteCommunication::PacketResult 3073 GDBRemoteCommunicationServerLLGS::Handle_QPassSignals( 3074 StringExtractorGDBRemote &packet) { 3075 std::vector<int> signals; 3076 packet.SetFilePos(strlen("QPassSignals:")); 3077 3078 // Read sequence of hex signal numbers divided by a semicolon and optionally 3079 // spaces. 3080 while (packet.GetBytesLeft() > 0) { 3081 int signal = packet.GetS32(-1, 16); 3082 if (signal < 0) 3083 return SendIllFormedResponse(packet, "Failed to parse signal number."); 3084 signals.push_back(signal); 3085 3086 packet.SkipSpaces(); 3087 char separator = packet.GetChar(); 3088 if (separator == '\0') 3089 break; // End of string 3090 if (separator != ';') 3091 return SendIllFormedResponse(packet, "Invalid separator," 3092 " expected semicolon."); 3093 } 3094 3095 // Fail if we don't have a current process. 3096 if (!m_debugged_process_up) 3097 return SendErrorResponse(68); 3098 3099 Status error = m_debugged_process_up->IgnoreSignals(signals); 3100 if (error.Fail()) 3101 return SendErrorResponse(69); 3102 3103 return SendOKResponse(); 3104 } 3105 3106 void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() { 3107 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3108 3109 // Tell the stdio connection to shut down. 3110 if (m_stdio_communication.IsConnected()) { 3111 auto connection = m_stdio_communication.GetConnection(); 3112 if (connection) { 3113 Status error; 3114 connection->Disconnect(&error); 3115 3116 if (error.Success()) { 3117 if (log) 3118 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process " 3119 "terminal stdio - SUCCESS", 3120 __FUNCTION__); 3121 } else { 3122 if (log) 3123 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process " 3124 "terminal stdio - FAIL: %s", 3125 __FUNCTION__, error.AsCString()); 3126 } 3127 } 3128 } 3129 } 3130 3131 NativeThreadProtocol *GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix( 3132 StringExtractorGDBRemote &packet) { 3133 // We have no thread if we don't have a process. 3134 if (!m_debugged_process_up || 3135 m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID) 3136 return nullptr; 3137 3138 // If the client hasn't asked for thread suffix support, there will not be a 3139 // thread suffix. Use the current thread in that case. 3140 if (!m_thread_suffix_supported) { 3141 const lldb::tid_t current_tid = GetCurrentThreadID(); 3142 if (current_tid == LLDB_INVALID_THREAD_ID) 3143 return nullptr; 3144 else if (current_tid == 0) { 3145 // Pick a thread. 3146 return m_debugged_process_up->GetThreadAtIndex(0); 3147 } else 3148 return m_debugged_process_up->GetThreadByID(current_tid); 3149 } 3150 3151 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); 3152 3153 // Parse out the ';'. 3154 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') { 3155 if (log) 3156 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse " 3157 "error: expected ';' prior to start of thread suffix: packet " 3158 "contents = '%s'", 3159 __FUNCTION__, packet.GetStringRef().c_str()); 3160 return nullptr; 3161 } 3162 3163 if (!packet.GetBytesLeft()) 3164 return nullptr; 3165 3166 // Parse out thread: portion. 3167 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) { 3168 if (log) 3169 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse " 3170 "error: expected 'thread:' but not found, packet contents = " 3171 "'%s'", 3172 __FUNCTION__, packet.GetStringRef().c_str()); 3173 return nullptr; 3174 } 3175 packet.SetFilePos(packet.GetFilePos() + strlen("thread:")); 3176 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0); 3177 if (tid != 0) 3178 return m_debugged_process_up->GetThreadByID(tid); 3179 3180 return nullptr; 3181 } 3182 3183 lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const { 3184 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) { 3185 // Use whatever the debug process says is the current thread id since the 3186 // protocol either didn't specify or specified we want any/all threads 3187 // marked as the current thread. 3188 if (!m_debugged_process_up) 3189 return LLDB_INVALID_THREAD_ID; 3190 return m_debugged_process_up->GetCurrentThreadID(); 3191 } 3192 // Use the specific current thread id set by the gdb remote protocol. 3193 return m_current_tid; 3194 } 3195 3196 uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() { 3197 std::lock_guard<std::mutex> guard(m_saved_registers_mutex); 3198 return m_next_saved_registers_id++; 3199 } 3200 3201 void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() { 3202 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 3203 3204 LLDB_LOG(log, "clearing auxv buffer: {0}", m_active_auxv_buffer_up.get()); 3205 m_active_auxv_buffer_up.reset(); 3206 } 3207 3208 FileSpec 3209 GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path, 3210 const ArchSpec &arch) { 3211 if (m_debugged_process_up) { 3212 FileSpec file_spec; 3213 if (m_debugged_process_up 3214 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec) 3215 .Success()) { 3216 if (FileSystem::Instance().Exists(file_spec)) 3217 return file_spec; 3218 } 3219 } 3220 3221 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch); 3222 } 3223