11#include "lldb/Host/Config.h"
45#include "llvm/Support/JSON.h"
46#include "llvm/Support/ScopedPrinter.h"
47#include "llvm/TargetParser/Triple.h"
61enum GDBRemoteServerError {
64 eErrorNoProcess = eErrorFirst,
74 m_process_factory(process_factory), m_current_process(nullptr),
75 m_continue_process(nullptr), m_stdio_communication() {
230 bool &interrupt,
bool &quit) {
265 return Status(
"%s: no process command line specified to launch",
268 const bool should_forward_stdio =
275 if (should_forward_stdio) {
281 return Status(std::move(Err));
288 "process but one already exists");
292 return Status(process_or.takeError());
299 SetEnabledExtensions(*m_current_process);
306 if (should_forward_stdio) {
311 "pid = {0}: setting up stdout/stderr redirection via $O "
312 "gdb-remote commands",
313 m_current_process->GetID());
316 auto terminal_fd = m_current_process->GetTerminalFileDescriptor();
317 if (terminal_fd >= 0) {
319 "ProcessGDBRemoteCommunicationServerLLGS::%s setting "
320 "inferior STDIO fd to %d",
321 __FUNCTION__, terminal_fd);
322 Status status = SetSTDIOFileDescriptor(terminal_fd);
327 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
328 "inferior STDIO since terminal fd reported as %d",
329 __FUNCTION__, terminal_fd);
333 "pid = {0} skipping stdout/stderr redirection via $O: inferior "
334 "will communicate over client-provided file descriptors",
335 m_current_process->GetID());
338 printf(
"Launched '%s' as process %" PRIu64
"...\n",
339 m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
340 m_current_process->GetID());
347 LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
353 return Status(
"cannot attach to process %" PRIu64
354 " when another process with pid %" PRIu64
355 " is being debugged.",
361 Status status(process_or.takeError());
362 llvm::errs() << llvm::formatv(
"failed to attach to process {0}: {1}\n", pid,
370 SetEnabledExtensions(*m_current_process);
373 auto terminal_fd = m_current_process->GetTerminalFileDescriptor();
374 if (terminal_fd >= 0) {
376 "ProcessGDBRemoteCommunicationServerLLGS::%s setting "
377 "inferior STDIO fd to %d",
378 __FUNCTION__, terminal_fd);
379 Status status = SetSTDIOFileDescriptor(terminal_fd);
384 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
385 "inferior STDIO since terminal fd reported as %d",
386 __FUNCTION__, terminal_fd);
389 printf(
"Attached to process %" PRIu64
"...\n", pid);
394 llvm::StringRef process_name,
bool include_existing) {
397 std::chrono::milliseconds polling_interval = std::chrono::milliseconds(1);
403 process_name, llvm::sys::path::Style::native);
406 if (include_existing) {
407 LLDB_LOG(log,
"including existing processes in search");
411 LLDB_LOG(log,
"placed '{0}' processes in the exclusion list.",
412 exclusion_list.size());
415 LLDB_LOG(log,
"waiting for '{0}' to appear", process_name);
417 auto is_in_exclusion_list =
419 for (
auto &excluded : exclusion_list) {
420 if (excluded.GetProcessID() == info.GetProcessID())
428 loop_process_list.clear();
431 llvm::erase_if(loop_process_list, is_in_exclusion_list);
434 if (loop_process_list.size() == 1) {
435 auto matching_process_pid = loop_process_list[0].GetProcessID();
436 LLDB_LOG(log,
"found pid {0}", matching_process_pid);
441 if (loop_process_list.size() > 1) {
444 "Multiple executables with name: '{0}' found. Pids: ",
446 for (
size_t i = 0; i < loop_process_list.size() - 1; ++i) {
447 error_stream.
Format(
"{0}, ", loop_process_list[i].GetProcessID());
449 error_stream.
Format(
"{0}.", loop_process_list.back().GetProcessID());
457 LLDB_LOG(log,
"sleep {0} seconds", polling_interval);
458 std::this_thread::sleep_for(polling_interval);
464 assert(process &&
"process cannot be NULL");
468 "GDBRemoteCommunicationServerLLGS::%s called with "
469 "NativeProcessProtocol pid %" PRIu64
", current state: %s",
470 __FUNCTION__, process->
GetID(),
478 assert(process &&
"process cannot be NULL");
484 LLDB_LOG(log,
"pid = {0}, failed to retrieve process exit status",
489 response.
PutHex8(GDBRemoteServerError::eErrorExitStatus);
493 LLDB_LOG(log,
"pid = {0}, returning exit type {1}", process->
GetID(),
502 response.
Format(
"{0:g}", *wait_status);
505 response.
Format(
";process:{0:x-}", process->
GetID());
516 for (i = buf_size - 1; i >= 0; i--)
519 for (i = 0; i < buf_size; i++)
525 switch (reg_info.encoding) {
540 switch (reg_info.format) {
550 return "vector-sint8";
552 return "vector-uint8";
554 return "vector-sint16";
556 return "vector-uint16";
558 return "vector-sint32";
560 return "vector-uint32";
562 return "vector-float32";
564 return "vector-uint64";
566 return "vector-uint128";
573 switch (reg_info.kinds[RegisterKind::eRegisterKindGeneric]) {
611 response.
Printf(
"%" PRIx32, *reg_num);
613 response.
Printf(
"%" PRIu32, *reg_num);
619 const RegisterInfo ®_info,
const RegisterValue *reg_value_p,
625 reg_value_p = ®_value;
635 if (reg_info.byte_size > 0) {
636 std::basic_string<uint8_t> zeros(reg_info.byte_size,
'\0');
642static std::optional<json::Object>
648 json::Object register_object;
650#ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
651 const auto expedited_regs =
654 const auto expedited_regs =
657 if (expedited_regs.empty())
660 for (
auto ®_num : expedited_regs) {
661 const RegisterInfo *
const reg_info_p =
663 if (reg_info_p ==
nullptr) {
665 "%s failed to get register info for register index %" PRIu32,
666 __FUNCTION__, reg_num);
670 if (reg_info_p->value_regs !=
nullptr)
677 LLDB_LOGF(log,
"%s failed to read register '%s' index %" PRIu32
": %s",
679 reg_info_p->name ? reg_info_p->name :
"<unnamed-register>",
680 reg_num,
error.AsCString());
688 register_object.try_emplace(llvm::to_string(reg_num),
692 return register_object;
696 switch (stop_reason) {
710 return "processor trace";
727static llvm::Expected<json::Array>
731 json::Array threads_array;
738 std::string description;
739 if (!thread.GetStopReason(tid_stop_info, description))
740 return llvm::make_error<llvm::StringError>(
741 "failed to get stop reason", llvm::inconvertibleErrorCode());
743 const int signum = tid_stop_info.
signo;
746 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
748 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
749 __FUNCTION__, process.
GetID(), tid, signum,
753 json::Object thread_obj;
757 thread_obj.try_emplace(
"registers", std::move(*registers));
760 thread_obj.try_emplace(
"tid",
static_cast<int64_t
>(tid));
763 thread_obj.try_emplace(
"signal", signum);
765 const std::string thread_name = thread.GetName();
766 if (!thread_name.empty())
767 thread_obj.try_emplace(
"name", thread_name);
771 thread_obj.try_emplace(
"reason", stop_reason);
773 if (!description.empty())
774 thread_obj.try_emplace(
"description", description);
778 thread_obj.try_emplace(
781 json::Array medata_array;
784 medata_array.push_back(
787 thread_obj.try_emplace(
"medata", std::move(medata_array));
789 threads_array.push_back(std::move(thread_obj));
791 return threads_array;
801 LLDB_LOG(log,
"preparing packet for pid {0} tid {1}", process.
GetID(),
807 std::string description;
819 int signum = tid_stop_info.
signo;
822 "pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}",
827 response.
PutHex8(signum & 0xff);
835 const std::string thread_name = thread.
GetName();
836 if (!thread_name.empty()) {
837 size_t thread_name_len = thread_name.length();
839 if (::strcspn(thread_name.c_str(),
"$#+-;:") == thread_name_len) {
865 response.
Printf(
"%" PRIx64, listed_thread.GetID());
875 if (thread_num > 1) {
876 const bool threads_with_valid_stop_info_only =
true;
882 unescaped_response.
AsRawOstream() << std::move(*threads_info);
887 "failed to prepare a jstopinfo field for pid {1}: {0}",
893 char delimiter =
':';
899 const RegisterInfo *
const reg_info_p =
905 LLDB_LOGF(log,
"%s failed to read register '%s' index %" PRIu32
": %s",
907 reg_info_p->name ? reg_info_p->name :
"<unnamed-register>",
908 reg_to_read,
error.AsCString());
927 const auto expedited_regs =
930 for (
auto ®_num : expedited_regs) {
931 const RegisterInfo *
const reg_info_p =
934 if (reg_info_p !=
nullptr && reg_info_p->value_regs ==
nullptr) {
937 if (
error.Success()) {
938 response.
Printf(
"%.02x:", reg_num);
944 "GDBRemoteCommunicationServerLLGS::%s failed to read "
945 "register '%s' index %" PRIu32
": %s",
947 reg_info_p->name ? reg_info_p->name :
"<unnamed-register>",
948 reg_num,
error.AsCString());
954 if (reason_str !=
nullptr) {
955 response.
Printf(
"reason:%s;", reason_str);
958 if (!description.empty()) {
989 response.
Printf(
"%s:p%" PRIx64
".%" PRIx64
";", reason_str,
1006 if (response.
Empty())
1026 if (listed_thread.GetID() != thread_to_skip) {
1028 if (!stop_reply.
Empty())
1036 assert(process &&
"process cannot be NULL");
1039 LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1042 *process, StateType::eStateExited,
false);
1045 "GDBRemoteCommunicationServerLLGS::%s failed to send stop "
1046 "notification for PID %" PRIu64
", state: eStateExited",
1047 __FUNCTION__, process->
GetID());
1078 assert(process &&
"process cannot be NULL");
1081 LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1084 *process, StateType::eStateStopped,
false);
1087 "GDBRemoteCommunicationServerLLGS::%s failed to send stop "
1088 "notification for PID %" PRIu64
", state: eStateExited",
1089 __FUNCTION__, process->
GetID());
1095 assert(process &&
"process cannot be NULL");
1099 "GDBRemoteCommunicationServerLLGS::%s called with "
1100 "NativeProcessProtocol pid %" PRIu64
", state: %s",
1105 case StateType::eStateRunning:
1108 case StateType::eStateStopped:
1119 case StateType::eStateExited:
1130 "GDBRemoteCommunicationServerLLGS::%s didn't handle state "
1131 "change for pid %" PRIu64
", new state: %s",
1144 std::unique_ptr<NativeProcessProtocol> child_process) {
1156 bool interrupt =
false;
1161 std::chrono::microseconds(0),
error, interrupt, done);
1167 "GDBRemoteCommunicationServerLLGS::%s processing a packet "
1169 __FUNCTION__,
error.AsCString());
1177 std::unique_ptr<Connection> connection) {
1178 IOObjectSP read_object_sp = connection->GetReadObject();
1191 if ((buffer ==
nullptr) || (len == 0)) {
1210 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1213 error.SetErrorString(
"failed to create ConnectionFileDescriptor");
1220 error.SetErrorString(
1221 "failed to set connection for inferior I/O communication");
1243 LLDB_LOG(log,
"Failed to set up stdio forwarding: {0}",
error);
1257 buffer,
sizeof buffer, std::chrono::microseconds(0), status, &
error);
1268 "GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1269 "forwarding as communication returned status %d (error: "
1271 __FUNCTION__, status,
error.AsCString());
1303 Expected<TraceStopRequest> stop_request =
1304 json::parse<TraceStopRequest>(packet.
Peek(),
"TraceStopRequest");
1324 Expected<TraceStartRequest> request =
1325 json::parse<TraceStartRequest>(packet.
Peek(),
"TraceStartRequest");
1345 Expected<TraceGetStateRequest> request =
1346 json::parse<TraceGetStateRequest>(packet.
Peek(),
"TraceGetStateRequest");
1363 llvm::Expected<TraceGetBinaryDataRequest> request =
1364 llvm::json::parse<TraceGetBinaryDataRequest>(packet.
Peek(),
1365 "TraceGetBinaryDataRequest");
1369 if (Expected<std::vector<uint8_t>> bytes =
1432 LLDB_LOG(log,
"No debugged process found.");
1438 LLDB_LOG(log,
"Killing process {0}", it->first);
1441 LLDB_LOG(log,
"Failed to kill debugged process {0}: {1}", it->first,
1462 "vKill failed to parse the process id");
1480 packet.
SetFilePos(::strlen(
"QSetDisableASLR:"));
1491 packet.
SetFilePos(::strlen(
"QSetWorkingDir:"));
1533 LLDB_LOG(log,
"process {0} cannot be resumed (state={1})", process.
GetID(),
1552 LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1557 "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1570 packet.
GetHexMaxU32(
false, std::numeric_limits<uint32_t>::max());
1571 if (signo == std::numeric_limits<uint32_t>::max())
1577 if (*packet.
Peek() ==
';')
1581 packet,
"unexpected content after $C{signal-number}");
1587 LLDB_LOG(log,
"process cannot be resumed (state={0})",
1608 static_cast<int>(signo)};
1612 resume_actions.
Append(action);
1618 LLDB_LOG(log,
"failed to send signal for process {0}: {1}",
1639 LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1644 const bool has_continue_address = (packet.
GetBytesLeft() > 0);
1645 if (has_continue_address) {
1646 LLDB_LOG(log,
"not implemented for c[address] variant [{0} remains]",
1654 "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1675 response.
Printf(
"vCont;c;C;s;S;t");
1696 LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1703 "GDBRemoteCommunicationServerLLGS::%s missing action from "
1709 if (::strcmp(packet.
Peek(),
";s") == 0) {
1715 std::unordered_map<lldb::pid_t, ResumeActionList> thread_actions;
1727 const char action = packet.
GetChar();
1731 if (thread_action.
signal == 0)
1733 packet,
"Could not parse signal in vCont packet C action");
1743 if (thread_action.
signal == 0)
1745 packet,
"Could not parse signal in vCont packet S action");
1776 pid = pid_tid->first;
1777 tid = pid_tid->second;
1783 packet,
"'t' action not supported for individual threads");
1789 LLDB_LOG(log,
"no process selected via Hc");
1798 thread_action.
tid = tid;
1803 packet,
"vCont: p-1 is not valid with a specific tid");
1805 thread_actions[process_it.first].Append(thread_action);
1807 thread_actions[pid].Append(thread_action);
1810 assert(thread_actions.size() >= 1);
1811 if (thread_actions.size() > 1 && !
m_non_stop)
1814 "Resuming multiple processes is supported in non-stop mode only");
1816 for (std::pair<lldb::pid_t, ResumeActionList> x : thread_actions) {
1819 LLDB_LOG(log,
"vCont failed for process {0}: process not debugged",
1836 assert(process_it->second.process_up);
1838 if (process_it->second.process_up->IsRunning()) {
1841 Status error = process_it->second.process_up->Interrupt();
1843 LLDB_LOG(log,
"vCont failed to halt process {0}: {1}", x.first,
1848 LLDB_LOG(log,
"halted process {0}", x.first);
1852 assert(thread_actions.size() == 1);
1868 LLDB_LOG(log,
"setting current thread id to {0}", tid);
1877 LLDB_LOG(log,
"setting continue thread id to {0}", tid);
1891 return x.front() !=
'W' && x.front() !=
'X';
1901 if (!stop_reply.
Empty())
1928 bool force_synchronous) {
1935 if (it.second.process_up->IsRunning())
1945 switch (process_state) {
1971 LLDB_LOG(log,
"pid {0}, current state reporting not handled: {1}",
1972 process.
GetID(), process_state);
1998 packet.
GetHexMaxU32(
false, std::numeric_limits<uint32_t>::max());
1999 if (reg_index == std::numeric_limits<uint32_t>::max())
2018 if (reg_info->alt_name && reg_info->alt_name[0]) {
2024 response.
Printf(
"bitsize:%" PRIu32
";", reg_info->byte_size * 8);
2027 response.
Printf(
"offset:%" PRIu32
";", reg_info->byte_offset);
2030 if (!encoding.empty())
2031 response <<
"encoding:" << encoding <<
';';
2034 if (!format.empty())
2035 response <<
"format:" << format <<
';';
2037 const char *
const register_set_name =
2039 if (register_set_name)
2040 response <<
"set:" << register_set_name <<
';';
2042 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
2044 response.
Printf(
"ehframe:%" PRIu32
";",
2045 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
2048 response.
Printf(
"dwarf:%" PRIu32
";",
2049 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
2052 if (!kind_generic.empty())
2053 response <<
"generic:" << kind_generic <<
';';
2061 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
2078 LLDB_LOG(log,
"iterating over threads of process {0}", process.
GetID());
2080 LLDB_LOG(log,
"iterated thread tid={0}", thread.GetID());
2081 response.
PutChar(had_any ?
',' :
'm');
2094 bool had_any =
false;
2123 LLDB_LOG(log,
"failed, no thread available");
2130 std::vector<uint8_t> regs_buffer;
2135 if (reg_info ==
nullptr) {
2136 LLDB_LOG(log,
"failed to get register info for register index {0}",
2141 if (reg_info->value_regs !=
nullptr)
2147 LLDB_LOG(log,
"failed to read register at index {0}", reg_num);
2151 if (reg_info->byte_offset + reg_info->byte_size >= regs_buffer.size())
2154 regs_buffer.resize(reg_info->byte_offset + reg_info->byte_size);
2157 memcpy(regs_buffer.data() + reg_info->byte_offset, reg_value.
GetBytes(),
2158 reg_info->byte_size);
2175 packet.
GetHexMaxU32(
false, std::numeric_limits<uint32_t>::max());
2176 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2178 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2179 "parse register number from request \"%s\"",
2187 LLDB_LOG(log,
"failed, no thread available");
2198 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2199 "register %" PRIu32
" beyond register count %" PRIu32,
2207 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2208 "register %" PRIu32
" returned NULL",
2209 __FUNCTION__, reg_index);
2221 "GDBRemoteCommunicationServerLLGS::%s failed, read of "
2222 "requested register %" PRIu32
" (%s) failed: %s",
2223 __FUNCTION__, reg_index, reg_info->name,
error.AsCString());
2227 const uint8_t *
const data =
2228 static_cast<const uint8_t *
>(reg_value.
GetBytes());
2231 "GDBRemoteCommunicationServerLLGS::%s failed to get data "
2232 "bytes from requested register %" PRIu32,
2233 __FUNCTION__, reg_index);
2255 packet.
GetHexMaxU32(
false, std::numeric_limits<uint32_t>::max());
2256 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2258 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2259 "parse register number from request \"%s\"",
2267 packet,
"P packet missing '=' char after register number");
2277 "GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2278 "available (thread index 0)",
2288 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2289 "register %" PRIu32
" returned NULL",
2290 __FUNCTION__, reg_index);
2298 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2299 "register %" PRIu32
" beyond register count %" PRIu32,
2304 if (
reg_size != reg_info->byte_size)
2315 "GDBRemoteCommunicationServerLLGS::%s failed, write of "
2316 "requested register %" PRIu32
" (%s) failed: %s",
2317 __FUNCTION__, reg_index, reg_info->name,
error.AsCString());
2332 "GDBRemoteCommunicationServerLLGS::%s failed, H command "
2333 "missing {g,c} variant",
2338 const char h_variant = packet.
GetChar();
2340 switch (h_variant) {
2352 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2353 __FUNCTION__, h_variant);
2355 "H variant unsupported, should be c or g");
2359 auto pid_tid = packet.
GetPidTid(default_process ? default_process->
GetID()
2363 inconvertibleErrorCode(),
"Malformed thread-id"));
2372 inconvertibleErrorCode(),
"No current process and no PID provided"));
2378 inconvertibleErrorCode(),
2379 llvm::formatv(
"No process with PID {0} debugged", pid)));
2385 new_process_it->second.process_up->GetThreadByID(tid);
2388 "GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2396 switch (h_variant) {
2408 assert(
false &&
"unsupported $H variant - shouldn't get here");
2410 "H variant unsupported, should be c or g");
2425 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2459 LLDB_LOG(log,
"failed, no process available");
2486 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2509 const uint64_t byte_count = packet.
GetHexMaxU64(
false, 0);
2510 if (byte_count == 0) {
2512 "GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2513 "zero-length packet",
2519 std::string buf(byte_count,
'\0');
2524 size_t bytes_read = 0;
2526 read_addr, &buf[0], byte_count, bytes_read);
2529 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2530 " mem 0x%" PRIx64
": failed to read. Error: %s",
2536 if (bytes_read == 0) {
2538 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2539 " mem 0x%" PRIx64
": read 0 of %" PRIu64
" requested bytes",
2546 char kind = packet.
GetChar(
'?');
2550 assert(kind ==
'm');
2551 for (
size_t i = 0; i < bytes_read; ++i)
2566 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2581 Permissions perms = {};
2585 perms |= ePermissionsReadable;
2588 perms |= ePermissionsWritable;
2591 perms |= ePermissionsExecutable;
2615 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2643 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2666 const uint64_t byte_count = packet.
GetHexMaxU64(
false, 0);
2667 if (byte_count == 0) {
2668 LLDB_LOG(log,
"nothing to write: zero-length packet");
2675 packet,
"Comma sep missing in M packet after byte length");
2678 std::vector<uint8_t> buf(byte_count, 0);
2684 const uint64_t convert_count = packet.
GetHexBytes(buf, 0);
2685 if (convert_count != byte_count) {
2687 "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} "
2691 "not match hex-encoded content "
2696 size_t bytes_written = 0;
2700 LLDB_LOG(log,
"pid {0} mem {1:x}: failed to write. Error: {2}",
2705 if (bytes_written == 0) {
2706 LLDB_LOG(log,
"pid {0} mem {1:x}: wrote 0 of {2} requested bytes",
2730 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2757 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2763 packet.
SetFilePos(strlen(
"qMemoryRegionInfo:"));
2784 response.
Printf(
"start:%" PRIx64
";size:%" PRIx64
";",
2833 LLDB_LOG(log,
"failed, no process available");
2841 packet,
"Too short Z packet, missing software/hardware specifier");
2843 bool want_breakpoint =
true;
2844 bool want_hardware =
false;
2849 switch (stoppoint_type) {
2851 want_hardware =
false;
2852 want_breakpoint =
true;
2855 want_hardware =
true;
2856 want_breakpoint =
true;
2860 want_hardware =
true;
2861 want_breakpoint =
false;
2865 want_hardware =
true;
2866 want_breakpoint =
false;
2870 want_hardware =
true;
2871 want_breakpoint =
false;
2875 packet,
"Z packet had invalid software/hardware specifier");
2880 packet,
"Malformed Z packet, expecting comma after stoppoint type");
2889 packet,
"Malformed Z packet, expecting comma after address");
2893 packet.
GetHexMaxU32(
false, std::numeric_limits<uint32_t>::max());
2894 if (size == std::numeric_limits<uint32_t>::max())
2896 packet,
"Malformed Z packet, failed to parse size argument");
2898 if (want_breakpoint) {
2902 if (
error.Success())
2905 LLDB_LOG(log,
"pid {0} failed to set breakpoint: {1}",
2911 addr, size, watch_flags, want_hardware);
2912 if (
error.Success())
2915 LLDB_LOG(log,
"pid {0} failed to set watchpoint: {1}",
2927 LLDB_LOG(log,
"failed, no process available");
2935 packet,
"Too short z packet, missing software/hardware specifier");
2937 bool want_breakpoint =
true;
2938 bool want_hardware =
false;
2942 switch (stoppoint_type) {
2944 want_breakpoint =
true;
2945 want_hardware =
true;
2948 want_breakpoint =
true;
2951 want_breakpoint =
false;
2954 want_breakpoint =
false;
2957 want_breakpoint =
false;
2961 packet,
"z packet had invalid software/hardware specifier");
2966 packet,
"Malformed z packet, expecting comma after stoppoint type");
2975 packet,
"Malformed z packet, expecting comma after address");
2986 if (want_breakpoint) {
2990 if (
error.Success())
2993 LLDB_LOG(log,
"pid {0} failed to remove breakpoint: {1}",
2999 if (
error.Success())
3002 LLDB_LOG(log,
"pid {0} failed to remove watchpoint: {1}",
3017 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3055llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
3060 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3061 "No thread available");
3069 response.
Printf(
"<?xml version=\"1.0\"?>\n");
3070 response.
Printf(
"<target version=\"1.0\">\n");
3074 response.
Printf(
"<architecture>%s</architecture>\n",
3081 response.
Indent(
"<feature>\n");
3084 if (registers_count)
3087 for (
int reg_index = 0; reg_index < registers_count; reg_index++) {
3088 const RegisterInfo *reg_info =
3093 "%s failed to get register info for register index %" PRIu32,
3094 "target.xml", reg_index);
3099 response.
Printf(
"<reg name=\"%s\" bitsize=\"%" PRIu32
3100 "\" regnum=\"%d\" ",
3101 reg_info->name, reg_info->byte_size * 8, reg_index);
3104 response.
Printf(
"offset=\"%" PRIu32
"\" ", reg_info->byte_offset);
3106 if (reg_info->alt_name && reg_info->alt_name[0])
3107 response.
Printf(
"altname=\"%s\" ", reg_info->alt_name);
3110 if (!encoding.empty())
3111 response <<
"encoding=\"" << encoding <<
"\" ";
3114 if (!format.empty())
3115 response <<
"format=\"" << format <<
"\" ";
3117 const char *
const register_set_name =
3119 if (register_set_name)
3120 response <<
"group=\"" << register_set_name <<
"\" ";
3122 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
3124 response.
Printf(
"ehframe_regnum=\"%" PRIu32
"\" ",
3125 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
3127 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] !=
3129 response.
Printf(
"dwarf_regnum=\"%" PRIu32
"\" ",
3130 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
3133 if (!kind_generic.empty())
3134 response <<
"generic=\"" << kind_generic <<
"\" ";
3136 if (reg_info->value_regs &&
3143 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
3144 response.
PutCString(
"invalidate_regnums=\"");
3152 if (registers_count)
3155 response.
Indent(
"</feature>\n");
3157 response.
Indent(
"</target>\n");
3158 return MemoryBuffer::getMemBufferCopy(response.
GetString(),
"target.xml");
3161llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
3163 llvm::StringRef annex) {
3167 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3168 "No process available");
3171 if (
object ==
"auxv") {
3174 if (!buffer_or_error)
3175 return llvm::errorCodeToError(buffer_or_error.getError());
3176 return std::move(*buffer_or_error);
3179 if (
object ==
"siginfo") {
3182 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3183 "no current thread");
3186 if (!buffer_or_error)
3187 return buffer_or_error.takeError();
3188 return std::move(*buffer_or_error);
3191 if (
object ==
"libraries-svr4") {
3194 return library_list.takeError();
3197 response.
Printf(
"<library-list-svr4 version=\"1.0\">");
3198 for (
auto const &library : *library_list) {
3199 response.
Printf(
"<library name=\"%s\" ",
3201 response.
Printf(
"lm=\"0x%" PRIx64
"\" ", library.link_map);
3202 response.
Printf(
"l_addr=\"0x%" PRIx64
"\" ", library.base_addr);
3203 response.
Printf(
"l_ld=\"0x%" PRIx64
"\" />", library.ld_addr);
3205 response.
Printf(
"</library-list-svr4>");
3206 return MemoryBuffer::getMemBufferCopy(response.
GetString(), __FUNCTION__);
3209 if (
object ==
"features" && annex ==
"target.xml")
3212 return llvm::make_error<UnimplementedError>();
3218 SmallVector<StringRef, 5> fields;
3220 StringRef(packet.
GetStringRef()).split(fields,
':', 4);
3221 if (fields.size() != 5)
3223 StringRef &xfer_object = fields[1];
3224 StringRef &xfer_action = fields[2];
3225 StringRef &xfer_annex = fields[3];
3227 if (xfer_action !=
"read")
3230 const uint64_t xfer_offset =
3231 offset_data.
GetHexMaxU64(
false, std::numeric_limits<uint64_t>::max());
3232 if (xfer_offset == std::numeric_limits<uint64_t>::max())
3235 if (offset_data.
GetChar() !=
',')
3237 "qXfer packet missing comma after offset");
3239 const uint64_t xfer_length =
3240 offset_data.
GetHexMaxU64(
false, std::numeric_limits<uint64_t>::max());
3241 if (xfer_length == std::numeric_limits<uint64_t>::max())
3245 std::string buffer_key = (xfer_object + xfer_action + xfer_annex).str();
3252 .insert(std::make_pair(buffer_key, std::move(*buffer_up)))
3258 bool done_with_buffer =
false;
3259 llvm::StringRef buffer = buffer_it->second->getBuffer();
3260 if (xfer_offset >= buffer.size()) {
3263 done_with_buffer =
true;
3266 buffer = buffer.drop_front(xfer_offset);
3269 if (xfer_length >= buffer.size()) {
3272 done_with_buffer =
true;
3276 buffer = buffer.take_front(xfer_length);
3282 if (done_with_buffer)
3294 packet.
SetFilePos(strlen(
"QSaveRegisterState"));
3301 packet,
"No thread specified in QSaveRegisterState packet");
3304 "No thread was is set with the Hg packet");
3311 WritableDataBufferSP register_data_sp;
3314 LLDB_LOG(log,
"pid {0} failed to save all register values: {1}",
3322 "GetNextRegisterSaveID() returned an existing register save id");
3332 response.
Printf(
"%" PRIu32, save_id);
3342 packet.
SetFilePos(strlen(
"QRestoreRegisterState:"));
3345 packet,
"QRestoreRegisterState packet missing register save id");
3349 LLDB_LOG(log,
"QRestoreRegisterState packet has malformed save id, "
3350 "expecting decimal uint32_t");
3359 packet,
"No thread specified in QRestoreRegisterState packet");
3362 "No thread was is set with the Hg packet");
3369 DataBufferSP register_data_sp;
3377 "pid {0} does not have a register set save buffer for id {1}",
3381 register_data_sp = it->second;
3389 LLDB_LOG(log,
"pid {0} failed to restore all register values: {1}",
3411 "vAttach failed to parse the process id");
3415 "GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
3423 "GDBRemoteCommunicationServerLLGS::%s failed to attach to "
3424 "pid %" PRIu64
": %s\n",
3425 __FUNCTION__, pid,
error.AsCString());
3448 std::string process_name;
3451 "vAttachWait failed to parse process name");
3453 LLDB_LOG(log,
"attempting to attach to process named '{0}'", process_name);
3457 LLDB_LOG(log,
"failed to attach to process named '{0}': {1}", process_name,
3487 std::string process_name;
3490 "vAttachOrWait failed to parse process name");
3492 LLDB_LOG(log,
"attempting to attach to process named '{0}'", process_name);
3496 LLDB_LOG(log,
"failed to attach to process named '{0}': {1}", process_name,
3514 if (!s.consume_front(
"vRun;"))
3517 llvm::SmallVector<llvm::StringRef, 16> argv;
3520 for (llvm::StringRef hex_arg : argv) {
3525 LLDB_LOGF(log,
"LLGSPacketHandler::%s added arg: \"%s\"", __FUNCTION__,
3564 llvm::Error detach_error = llvm::Error::success();
3565 bool detached =
false;
3570 "GDBRemoteCommunicationServerLLGS::%s detaching %" PRId64,
3571 __FUNCTION__, it->first);
3572 if (llvm::Error e = it->second.process_up->Detach().ToError())
3573 detach_error = llvm::joinErrors(std::move(detach_error), std::move(e));
3603 packet.
SetFilePos(strlen(
"qThreadStopInfo"));
3607 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
3608 "parse thread id from request \"%s\"",
3628 const bool threads_with_valid_stop_info_only =
false;
3629 llvm::Expected<json::Value> threads_info =
3631 if (!threads_info) {
3633 "failed to prepare a packet for pid {1}: {0}",
3652 packet.
SetFilePos(strlen(
"qWatchpointSupportInfo"));
3661 if (hw_debug_cap == std::nullopt)
3662 response.
Printf(
"num:0;");
3664 response.
Printf(
"num:%d;", hw_debug_cap->second);
3677 packet.
SetFilePos(strlen(
"qFileLoadAddress:"));
3681 std::string file_name;
3694 response.
PutHex64(file_load_address);
3701 std::vector<int> signals;
3707 int signal = packet.
GetS32(-1, 16);
3710 signals.push_back(signal);
3713 char separator = packet.
GetChar();
3714 if (separator ==
'\0')
3716 if (separator !=
';')
3718 " expected semicolon.");
3742 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3752 const char *current_char = packet.
Peek();
3753 if (!current_char || *current_char ==
',')
3758 char previous_char = packet.
GetChar();
3759 current_char = packet.
Peek();
3761 if (previous_char !=
',' || (current_char && *current_char ==
':'))
3763 "Invalid addr,length pair in qMemTags packet");
3767 packet,
"Too short qMemtags: packet (looking for length)");
3771 const char *invalid_type_err =
"Invalid type field in qMemTags: packet";
3777 const char *first_type_char = packet.
Peek();
3778 if (first_type_char && (*first_type_char ==
'+' || *first_type_char ==
'-'))
3785 packet.
GetU64(std::numeric_limits<uint64_t>::max(), 16);
3788 raw_type > std::numeric_limits<uint32_t>::max() ||
3798 int32_t type =
reinterpret_cast<int32_t &
>(raw_type_32);
3801 std::vector<uint8_t> tags;
3823 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3833 const char *current_char = packet.
Peek();
3834 if (!current_char || *current_char ==
',')
3839 char previous_char = packet.
GetChar();
3840 current_char = packet.
Peek();
3842 if (previous_char !=
',' || (current_char && *current_char ==
':'))
3844 "Invalid addr,length pair in QMemTags packet");
3848 packet,
"Too short QMemtags: packet (looking for length)");
3852 const char *invalid_type_err =
"Invalid type field in QMemTags: packet";
3857 const char *first_type_char = packet.
Peek();
3858 if (first_type_char && (*first_type_char ==
'+' || *first_type_char ==
'-'))
3866 packet.
GetU64(std::numeric_limits<uint64_t>::max(), 16);
3867 if (raw_type > std::numeric_limits<uint32_t>::max())
3873 int32_t type =
reinterpret_cast<int32_t &
>(raw_type_32);
3878 "Missing tag data in QMemTags: packet");
3881 const char *invalid_data_err =
"Invalid tag data in QMemTags: packet";
3888 std::vector<uint8_t> tag_data;
3893 tag_data.resize(byte_count);
3894 size_t converted_bytes = packet.
GetHexBytes(tag_data, 0);
3895 if (converted_bytes != byte_count) {
3913 std::string path_hint;
3916 assert(packet_str.startswith(
"qSaveCore"));
3917 if (packet_str.consume_front(
"qSaveCore;")) {
3918 for (
auto x : llvm::split(packet_str,
';')) {
3919 if (x.consume_front(
"path-hint:"))
3942 assert(packet_str.startswith(
"QNonStop:"));
3943 packet_str.consume_front(
"QNonStop:");
3944 if (packet_str ==
"0") {
3948 if (process_it.second.process_up->IsRunning()) {
3950 Status error = process_it.second.process_up->Interrupt();
3953 "while disabling nonstop, failed to halt process {0}: {1}",
3954 process_it.first,
error);
3968 }
else if (packet_str ==
"1") {
3979 std::deque<std::string> &queue) {
4021 return interrupt_res;
4033 inconvertibleErrorCode(),
"Malformed thread-id"));
4042 inconvertibleErrorCode(),
"No current process and no PID provided"));
4050 if (!new_process_it->second.process_up->GetThreadByID(tid))
4064 connection->Disconnect(&
error);
4066 if (
error.Success()) {
4068 "GDBRemoteCommunicationServerLLGS::%s disconnect process "
4069 "terminal stdio - SUCCESS",
4073 "GDBRemoteCommunicationServerLLGS::%s disconnect process "
4074 "terminal stdio - FAIL: %s",
4075 __FUNCTION__,
error.AsCString());
4094 else if (current_tid == 0) {
4106 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
4107 "error: expected ';' prior to start of thread suffix: packet "
4117 if (strncmp(packet.
Peek(),
"thread:", strlen(
"thread:")) != 0) {
4119 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
4120 "error: expected 'thread:' but not found, packet contents = "
4164 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
4175 llvm::StringRef value) {
4177 for (
const char &c : value) {
4200 const llvm::ArrayRef<llvm::StringRef> client_features) {
4201 std::vector<std::string> ret =
4203 ret.insert(ret.end(), {
4204 "QThreadSuffixSupported+",
4205 "QListThreadsInStopReply+",
4206 "qXfer:features:read+",
4213 if (
bool(plugin_features & Extension::pass_signals))
4214 ret.push_back(
"QPassSignals+");
4215 if (
bool(plugin_features & Extension::auxv))
4216 ret.push_back(
"qXfer:auxv:read+");
4217 if (
bool(plugin_features & Extension::libraries_svr4))
4218 ret.push_back(
"qXfer:libraries-svr4:read+");
4219 if (
bool(plugin_features & Extension::siginfo_read))
4220 ret.push_back(
"qXfer:siginfo:read+");
4221 if (
bool(plugin_features & Extension::memory_tagging))
4222 ret.push_back(
"memory-tagging+");
4223 if (
bool(plugin_features & Extension::savecore))
4224 ret.push_back(
"qSaveCore+");
4228 for (llvm::StringRef x : client_features)
4230 llvm::StringSwitch<Extension>(x)
4231 .Case(
"multiprocess+", Extension::multiprocess)
4232 .Case(
"fork-events+", Extension::fork)
4233 .Case(
"vfork-events+", Extension::vfork)
4244 ret.push_back(
"multiprocess+");
4246 ret.push_back(
"fork-events+");
4248 ret.push_back(
"vfork-events+");
4274 response.
Format(
"p{0:x-}.", pid);
4275 response.
Format(
"{0:x-}", tid);
4280 bool reverse_connect) {
4282 if (std::optional<URI> url =
URI::Parse(url_arg)) {
4283 if (reverse_connect)
4284 return url_arg.str();
4289 std::string new_url = llvm::StringSwitch<std::string>(url->scheme)
4290 .Case(
"tcp",
"listen")
4291 .Case(
"unix",
"unix-accept")
4292 .Case(
"unix-abstract",
"unix-abstract-accept")
4293 .Default(url->scheme.str());
4294 llvm::append_range(new_url, url_arg.substr(url->scheme.size()));
4298 std::string host_port = url_arg.str();
4301 if (url_arg.startswith(
":"))
4302 host_port.insert(0,
"localhost");
4306 return (reverse_connect ?
"connect://" :
"listen://") + host_port;
4309 return (reverse_connect ?
"unix-connect://" :
"unix-accept://") +
static const size_t reg_size
static llvm::raw_ostream & error(Stream &strm)
static llvm::StringRef GetEncodingNameOrEmpty(const RegisterInfo ®_info)
static llvm::StringRef GetFormatNameOrEmpty(const RegisterInfo ®_info)
static void WriteRegisterValueInHexFixedWidth(StreamString &response, NativeRegisterContext ®_ctx, const RegisterInfo ®_info, const RegisterValue *reg_value_p, lldb::ByteOrder byte_order)
static void AppendHexValue(StreamString &response, const uint8_t *buf, uint32_t buf_size, bool swap)
static std::optional< json::Object > GetRegistersAsJSON(NativeThreadProtocol &thread)
static const char * GetStopReasonString(StopReason stop_reason)
static void CollectRegNums(const uint32_t *reg_num, StreamString &response, bool usehex)
static bool ResumeActionListStopsAllThreads(ResumeActionList &actions)
static llvm::StringRef GetKindGenericOrEmpty(const RegisterInfo ®_info)
static llvm::Expected< json::Array > GetJSONThreadsInfo(NativeProcessProtocol &process, bool abridged)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
#define LLDB_LOGF(log,...)
#define LLDB_LOG_ERROR(log, error,...)
An architecture specification class.
llvm::Triple & GetTriple()
Architecture triple accessor.
lldb::ByteOrder GetByteOrder() const
Returns the byte order for the architecture specification.
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
void AppendArgument(llvm::StringRef arg_str, char quote_char='\0')
Appends a new argument to the end of the list argument list.
virtual size_t Read(void *dst, size_t dst_len, const Timeout< std::micro > &timeout, lldb::ConnectionStatus &status, Status *error_ptr)
Read bytes from the current connection.
bool IsConnected() const
Check if the connection is valid.
virtual void SetConnection(std::unique_ptr< Connection > connection)
Sets the connection that it to be used by this class.
size_t WriteAll(const void *src, size_t src_len, lldb::ConnectionStatus &status, Status *error_ptr)
Repeatedly attempt writing until either src_len bytes are written or a permanent failure occurs.
lldb_private::Connection * GetConnection()
void SetCloseOnEOF(bool b)
virtual lldb::IOObjectSP GetReadObject()
Returns the underlying IOObject used by the Connection.
A uniqued constant string class.
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
static FileSystem & Instance()