11#include "lldb/Host/Config.h"
44#include "llvm/Support/JSON.h"
45#include "llvm/Support/ScopedPrinter.h"
46#include "llvm/TargetParser/Triple.h"
60enum GDBRemoteServerError {
63 eErrorNoProcess = eErrorFirst,
73 m_process_manager(process_manager), m_current_process(nullptr),
74 m_continue_process(nullptr), m_stdio_communication() {
229 bool &interrupt,
bool &quit) {
264 return Status(
"%s: no process command line specified to launch",
267 const bool should_forward_stdio =
274 if (should_forward_stdio) {
280 return Status(std::move(Err));
287 "process but one already exists");
290 return Status(process_or.takeError());
297 SetEnabledExtensions(*m_current_process);
304 if (should_forward_stdio) {
309 "pid = {0}: setting up stdout/stderr redirection via $O "
310 "gdb-remote commands",
311 m_current_process->GetID());
314 auto terminal_fd = m_current_process->GetTerminalFileDescriptor();
315 if (terminal_fd >= 0) {
317 "ProcessGDBRemoteCommunicationServerLLGS::%s setting "
318 "inferior STDIO fd to %d",
319 __FUNCTION__, terminal_fd);
320 Status status = SetSTDIOFileDescriptor(terminal_fd);
325 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
326 "inferior STDIO since terminal fd reported as %d",
327 __FUNCTION__, terminal_fd);
331 "pid = {0} skipping stdout/stderr redirection via $O: inferior "
332 "will communicate over client-provided file descriptors",
333 m_current_process->GetID());
336 printf(
"Launched '%s' as process %" PRIu64
"...\n",
337 m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
338 m_current_process->GetID());
345 LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
351 return Status(
"cannot attach to process %" PRIu64
352 " when another process with pid %" PRIu64
353 " is being debugged.",
359 Status status(process_or.takeError());
360 llvm::errs() << llvm::formatv(
"failed to attach to process {0}: {1}\n", pid,
368 SetEnabledExtensions(*m_current_process);
371 auto terminal_fd = m_current_process->GetTerminalFileDescriptor();
372 if (terminal_fd >= 0) {
374 "ProcessGDBRemoteCommunicationServerLLGS::%s setting "
375 "inferior STDIO fd to %d",
376 __FUNCTION__, terminal_fd);
377 Status status = SetSTDIOFileDescriptor(terminal_fd);
382 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
383 "inferior STDIO since terminal fd reported as %d",
384 __FUNCTION__, terminal_fd);
387 printf(
"Attached to process %" PRIu64
"...\n", pid);
392 llvm::StringRef process_name,
bool include_existing) {
395 std::chrono::milliseconds polling_interval = std::chrono::milliseconds(1);
401 process_name, llvm::sys::path::Style::native);
404 if (include_existing) {
405 LLDB_LOG(log,
"including existing processes in search");
409 LLDB_LOG(log,
"placed '{0}' processes in the exclusion list.",
410 exclusion_list.size());
413 LLDB_LOG(log,
"waiting for '{0}' to appear", process_name);
415 auto is_in_exclusion_list =
417 for (
auto &excluded : exclusion_list) {
418 if (excluded.GetProcessID() == info.GetProcessID())
426 loop_process_list.clear();
429 llvm::erase_if(loop_process_list, is_in_exclusion_list);
432 if (loop_process_list.size() == 1) {
433 auto matching_process_pid = loop_process_list[0].GetProcessID();
434 LLDB_LOG(log,
"found pid {0}", matching_process_pid);
439 if (loop_process_list.size() > 1) {
442 "Multiple executables with name: '{0}' found. Pids: ",
444 for (
size_t i = 0; i < loop_process_list.size() - 1; ++i) {
445 error_stream.
Format(
"{0}, ", loop_process_list[i].GetProcessID());
447 error_stream.
Format(
"{0}.", loop_process_list.back().GetProcessID());
455 LLDB_LOG(log,
"sleep {0} seconds", polling_interval);
456 std::this_thread::sleep_for(polling_interval);
462 assert(process &&
"process cannot be NULL");
466 "GDBRemoteCommunicationServerLLGS::%s called with "
467 "NativeProcessProtocol pid %" PRIu64
", current state: %s",
468 __FUNCTION__, process->
GetID(),
476 assert(process &&
"process cannot be NULL");
482 LLDB_LOG(log,
"pid = {0}, failed to retrieve process exit status",
487 response.
PutHex8(GDBRemoteServerError::eErrorExitStatus);
491 LLDB_LOG(log,
"pid = {0}, returning exit type {1}", process->
GetID(),
500 response.
Format(
"{0:g}", *wait_status);
503 response.
Format(
";process:{0:x-}", process->
GetID());
511 uint32_t buf_size,
bool swap) {
514 for (i = buf_size - 1; i >= 0; i--)
517 for (i = 0; i < buf_size; i++)
538 switch (reg_info.
format) {
548 return "vector-sint8";
550 return "vector-uint8";
552 return "vector-sint16";
554 return "vector-uint16";
556 return "vector-sint32";
558 return "vector-uint32";
560 return "vector-float32";
562 return "vector-uint64";
564 return "vector-uint128";
571 switch (reg_info.
kinds[RegisterKind::eRegisterKindGeneric]) {
609 response.
Printf(
"%" PRIx32, *reg_num);
611 response.
Printf(
"%" PRIu32, *reg_num);
623 reg_value_p = ®_value;
634 std::vector<uint8_t> zeros(reg_info.
byte_size,
'\0');
640static std::optional<json::Object>
646 json::Object register_object;
648#ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
649 const auto expedited_regs =
652 const auto expedited_regs =
655 if (expedited_regs.empty())
658 for (
auto ®_num : expedited_regs) {
661 if (reg_info_p ==
nullptr) {
663 "%s failed to get register info for register index %" PRIu32,
664 __FUNCTION__, reg_num);
675 LLDB_LOGF(log,
"%s failed to read register '%s' index %" PRIu32
": %s",
677 reg_info_p->
name ? reg_info_p->
name :
"<unnamed-register>",
678 reg_num,
error.AsCString());
686 register_object.try_emplace(llvm::to_string(reg_num),
690 return register_object;
694 switch (stop_reason) {
708 return "processor trace";
725static llvm::Expected<json::Array>
729 json::Array threads_array;
736 std::string description;
737 if (!thread.GetStopReason(tid_stop_info, description))
738 return llvm::make_error<llvm::StringError>(
739 "failed to get stop reason", llvm::inconvertibleErrorCode());
741 const int signum = tid_stop_info.
signo;
744 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
746 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
747 __FUNCTION__, process.
GetID(), tid, signum,
751 json::Object thread_obj;
755 thread_obj.try_emplace(
"registers", std::move(*registers));
758 thread_obj.try_emplace(
"tid",
static_cast<int64_t
>(tid));
761 thread_obj.try_emplace(
"signal", signum);
763 const std::string thread_name = thread.GetName();
764 if (!thread_name.empty())
765 thread_obj.try_emplace(
"name", thread_name);
769 thread_obj.try_emplace(
"reason", stop_reason);
771 if (!description.empty())
772 thread_obj.try_emplace(
"description", description);
776 thread_obj.try_emplace(
779 json::Array medata_array;
782 medata_array.push_back(
785 thread_obj.try_emplace(
"medata", std::move(medata_array));
787 threads_array.push_back(std::move(thread_obj));
789 return threads_array;
799 LLDB_LOG(log,
"preparing packet for pid {0} tid {1}", process.
GetID(),
805 std::string description;
817 int signum = tid_stop_info.
signo;
820 "pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}",
825 response.
PutHex8(signum & 0xff);
833 const std::string thread_name = thread.
GetName();
834 if (!thread_name.empty()) {
835 size_t thread_name_len = thread_name.length();
837 if (::strcspn(thread_name.c_str(),
"$#+-;:") == thread_name_len) {
859 uint32_t thread_num = 0;
863 response.
Printf(
"%" PRIx64, listed_thread.GetID());
873 if (thread_num > 1) {
874 const bool threads_with_valid_stop_info_only =
true;
880 unescaped_response.
AsRawOstream() << std::move(*threads_info);
885 "failed to prepare a jstopinfo field for pid {1}: {0}",
891 char delimiter =
':';
903 LLDB_LOGF(log,
"%s failed to read register '%s' index %" PRIu32
": %s",
905 reg_info_p->
name ? reg_info_p->
name :
"<unnamed-register>",
906 reg_to_read,
error.AsCString());
925 const auto expedited_regs =
928 for (
auto ®_num : expedited_regs) {
932 if (reg_info_p !=
nullptr && reg_info_p->
value_regs ==
nullptr) {
935 if (
error.Success()) {
936 response.
Printf(
"%.02x:", reg_num);
942 "GDBRemoteCommunicationServerLLGS::%s failed to read "
943 "register '%s' index %" PRIu32
": %s",
945 reg_info_p->
name ? reg_info_p->
name :
"<unnamed-register>",
946 reg_num,
error.AsCString());
952 if (reason_str !=
nullptr) {
953 response.
Printf(
"reason:%s;", reason_str);
956 if (!description.empty()) {
987 response.
Printf(
"%s:p%" PRIx64
".%" PRIx64
";", reason_str,
1004 if (response.
Empty())
1024 if (listed_thread.GetID() != thread_to_skip) {
1026 if (!stop_reply.
Empty())
1034 assert(process &&
"process cannot be NULL");
1037 LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1040 *process, StateType::eStateExited,
false);
1043 "GDBRemoteCommunicationServerLLGS::%s failed to send stop "
1044 "notification for PID %" PRIu64
", state: eStateExited",
1045 __FUNCTION__, process->
GetID());
1076 assert(process &&
"process cannot be NULL");
1079 LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1082 *process, StateType::eStateStopped,
false);
1085 "GDBRemoteCommunicationServerLLGS::%s failed to send stop "
1086 "notification for PID %" PRIu64
", state: eStateExited",
1087 __FUNCTION__, process->
GetID());
1093 assert(process &&
"process cannot be NULL");
1097 "GDBRemoteCommunicationServerLLGS::%s called with "
1098 "NativeProcessProtocol pid %" PRIu64
", state: %s",
1103 case StateType::eStateRunning:
1106 case StateType::eStateStopped:
1117 case StateType::eStateExited:
1128 "GDBRemoteCommunicationServerLLGS::%s didn't handle state "
1129 "change for pid %" PRIu64
", new state: %s",
1142 std::unique_ptr<NativeProcessProtocol> child_process) {
1154 bool interrupt =
false;
1159 std::chrono::microseconds(0),
error, interrupt, done);
1165 "GDBRemoteCommunicationServerLLGS::%s processing a packet "
1167 __FUNCTION__,
error.AsCString());
1175 std::unique_ptr<Connection> connection) {
1176 IOObjectSP read_object_sp = connection->GetReadObject();
1189 if ((buffer ==
nullptr) || (len == 0)) {
1208 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1211 error.SetErrorString(
"failed to create ConnectionFileDescriptor");
1218 error.SetErrorString(
1219 "failed to set connection for inferior I/O communication");
1241 LLDB_LOG(log,
"Failed to set up stdio forwarding: {0}",
error);
1255 buffer,
sizeof buffer, std::chrono::microseconds(0), status, &
error);
1266 "GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1267 "forwarding as communication returned status %d (error: "
1269 __FUNCTION__, status,
error.AsCString());
1301 Expected<TraceStopRequest> stop_request =
1302 json::parse<TraceStopRequest>(packet.
Peek(),
"TraceStopRequest");
1322 Expected<TraceStartRequest> request =
1323 json::parse<TraceStartRequest>(packet.
Peek(),
"TraceStartRequest");
1343 Expected<TraceGetStateRequest> request =
1344 json::parse<TraceGetStateRequest>(packet.
Peek(),
"TraceGetStateRequest");
1361 llvm::Expected<TraceGetBinaryDataRequest> request =
1362 llvm::json::parse<TraceGetBinaryDataRequest>(packet.
Peek(),
1363 "TraceGetBinaryDataRequest");
1367 if (Expected<std::vector<uint8_t>> bytes =
1430 LLDB_LOG(log,
"No debugged process found.");
1436 LLDB_LOG(log,
"Killing process {0}", it->first);
1439 LLDB_LOG(log,
"Failed to kill debugged process {0}: {1}", it->first,
1460 "vKill failed to parse the process id");
1478 packet.
SetFilePos(::strlen(
"QSetDisableASLR:"));
1489 packet.
SetFilePos(::strlen(
"QSetWorkingDir:"));
1531 LLDB_LOG(log,
"process {0} cannot be resumed (state={1})", process.
GetID(),
1550 LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1555 "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1567 const uint32_t signo =
1568 packet.
GetHexMaxU32(
false, std::numeric_limits<uint32_t>::max());
1569 if (signo == std::numeric_limits<uint32_t>::max())
1575 if (*packet.
Peek() ==
';')
1579 packet,
"unexpected content after $C{signal-number}");
1585 LLDB_LOG(log,
"process cannot be resumed (state={0})",
1606 static_cast<int>(signo)};
1610 resume_actions.
Append(action);
1616 LLDB_LOG(log,
"failed to send signal for process {0}: {1}",
1637 LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1642 const bool has_continue_address = (packet.
GetBytesLeft() > 0);
1643 if (has_continue_address) {
1644 LLDB_LOG(log,
"not implemented for c[address] variant [{0} remains]",
1652 "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1673 response.
Printf(
"vCont;c;C;s;S;t");
1694 LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1701 "GDBRemoteCommunicationServerLLGS::%s missing action from "
1707 if (::strcmp(packet.
Peek(),
";s") == 0) {
1713 std::unordered_map<lldb::pid_t, ResumeActionList> thread_actions;
1725 const char action = packet.
GetChar();
1729 if (thread_action.
signal == 0)
1731 packet,
"Could not parse signal in vCont packet C action");
1741 if (thread_action.
signal == 0)
1743 packet,
"Could not parse signal in vCont packet S action");
1774 pid = pid_tid->first;
1775 tid = pid_tid->second;
1781 packet,
"'t' action not supported for individual threads");
1787 LLDB_LOG(log,
"no process selected via Hc");
1796 thread_action.
tid = tid;
1801 packet,
"vCont: p-1 is not valid with a specific tid");
1803 thread_actions[process_it.first].Append(thread_action);
1805 thread_actions[pid].Append(thread_action);
1808 assert(thread_actions.size() >= 1);
1809 if (thread_actions.size() > 1 && !
m_non_stop)
1812 "Resuming multiple processes is supported in non-stop mode only");
1814 for (std::pair<lldb::pid_t, ResumeActionList> x : thread_actions) {
1817 LLDB_LOG(log,
"vCont failed for process {0}: process not debugged",
1834 assert(process_it->second.process_up);
1836 if (process_it->second.process_up->IsRunning()) {
1839 Status error = process_it->second.process_up->Interrupt();
1841 LLDB_LOG(log,
"vCont failed to halt process {0}: {1}", x.first,
1846 LLDB_LOG(log,
"halted process {0}", x.first);
1850 assert(thread_actions.size() == 1);
1866 LLDB_LOG(log,
"setting current thread id to {0}", tid);
1875 LLDB_LOG(log,
"setting continue thread id to {0}", tid);
1889 return x.front() !=
'W' && x.front() !=
'X';
1899 if (!stop_reply.
Empty())
1926 bool force_synchronous) {
1933 if (it.second.process_up->IsRunning())
1943 switch (process_state) {
1969 LLDB_LOG(log,
"pid {0}, current state reporting not handled: {1}",
1970 process.
GetID(), process_state);
1995 const uint32_t reg_index =
1996 packet.
GetHexMaxU32(
false, std::numeric_limits<uint32_t>::max());
1997 if (reg_index == std::numeric_limits<uint32_t>::max())
2028 if (!encoding.empty())
2029 response <<
"encoding:" << encoding <<
';';
2032 if (!format.empty())
2033 response <<
"format:" << format <<
';';
2035 const char *
const register_set_name =
2037 if (register_set_name)
2038 response <<
"set:" << register_set_name <<
';';
2040 if (reg_info->
kinds[RegisterKind::eRegisterKindEHFrame] !=
2042 response.
Printf(
"ehframe:%" PRIu32
";",
2043 reg_info->
kinds[RegisterKind::eRegisterKindEHFrame]);
2046 response.
Printf(
"dwarf:%" PRIu32
";",
2047 reg_info->
kinds[RegisterKind::eRegisterKindDWARF]);
2050 if (!kind_generic.empty())
2051 response <<
"generic:" << kind_generic <<
';';
2076 LLDB_LOG(log,
"iterating over threads of process {0}", process.
GetID());
2078 LLDB_LOG(log,
"iterated thread tid={0}", thread.GetID());
2079 response.
PutChar(had_any ?
',' :
'm');
2092 bool had_any =
false;
2121 LLDB_LOG(log,
"failed, no thread available");
2128 std::vector<uint8_t> regs_buffer;
2133 if (reg_info ==
nullptr) {
2134 LLDB_LOG(log,
"failed to get register info for register index {0}",
2145 LLDB_LOG(log,
"failed to read register at index {0}", reg_num);
2172 const uint32_t reg_index =
2173 packet.
GetHexMaxU32(
false, std::numeric_limits<uint32_t>::max());
2174 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2176 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2177 "parse register number from request \"%s\"",
2185 LLDB_LOG(log,
"failed, no thread available");
2196 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2197 "register %" PRIu32
" beyond register count %" PRIu32,
2205 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2206 "register %" PRIu32
" returned NULL",
2207 __FUNCTION__, reg_index);
2219 "GDBRemoteCommunicationServerLLGS::%s failed, read of "
2220 "requested register %" PRIu32
" (%s) failed: %s",
2221 __FUNCTION__, reg_index, reg_info->
name,
error.AsCString());
2225 const uint8_t *
const data =
2226 static_cast<const uint8_t *
>(reg_value.
GetBytes());
2229 "GDBRemoteCommunicationServerLLGS::%s failed to get data "
2230 "bytes from requested register %" PRIu32,
2231 __FUNCTION__, reg_index);
2236 for (uint32_t i = 0; i < reg_value.
GetByteSize(); ++i)
2252 const uint32_t reg_index =
2253 packet.
GetHexMaxU32(
false, std::numeric_limits<uint32_t>::max());
2254 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2256 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2257 "parse register number from request \"%s\"",
2265 packet,
"P packet missing '=' char after register number");
2274 "GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2275 "available (thread index 0)",
2285 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2286 "register %" PRIu32
" returned NULL",
2287 __FUNCTION__, reg_index);
2295 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2296 "register %" PRIu32
" beyond register count %" PRIu32,
2312 "GDBRemoteCommunicationServerLLGS::%s failed, write of "
2313 "requested register %" PRIu32
" (%s) failed: %s",
2314 __FUNCTION__, reg_index, reg_info->
name,
error.AsCString());
2329 "GDBRemoteCommunicationServerLLGS::%s failed, H command "
2330 "missing {g,c} variant",
2335 const char h_variant = packet.
GetChar();
2337 switch (h_variant) {
2349 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2350 __FUNCTION__, h_variant);
2352 "H variant unsupported, should be c or g");
2356 auto pid_tid = packet.
GetPidTid(default_process ? default_process->
GetID()
2360 inconvertibleErrorCode(),
"Malformed thread-id"));
2369 inconvertibleErrorCode(),
"No current process and no PID provided"));
2375 inconvertibleErrorCode(),
2376 llvm::formatv(
"No process with PID {0} debugged", pid)));
2382 new_process_it->second.process_up->GetThreadByID(tid);
2385 "GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2393 switch (h_variant) {
2405 assert(
false &&
"unsupported $H variant - shouldn't get here");
2407 "H variant unsupported, should be c or g");
2422 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2456 LLDB_LOG(log,
"failed, no process available");
2483 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2506 const uint64_t byte_count = packet.
GetHexMaxU64(
false, 0);
2507 if (byte_count == 0) {
2509 "GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2510 "zero-length packet",
2516 std::string buf(byte_count,
'\0');
2521 size_t bytes_read = 0;
2523 read_addr, &buf[0], byte_count, bytes_read);
2526 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2527 " mem 0x%" PRIx64
": failed to read. Error: %s",
2533 if (bytes_read == 0) {
2535 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2536 " mem 0x%" PRIx64
": read 0 of %" PRIu64
" requested bytes",
2543 char kind = packet.
GetChar(
'?');
2547 assert(kind ==
'm');
2548 for (
size_t i = 0; i < bytes_read; ++i)
2563 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2578 Permissions perms = {};
2582 perms |= ePermissionsReadable;
2585 perms |= ePermissionsWritable;
2588 perms |= ePermissionsExecutable;
2612 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2640 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2663 const uint64_t byte_count = packet.
GetHexMaxU64(
false, 0);
2664 if (byte_count == 0) {
2665 LLDB_LOG(log,
"nothing to write: zero-length packet");
2672 packet,
"Comma sep missing in M packet after byte length");
2675 std::vector<uint8_t> buf(byte_count, 0);
2681 const uint64_t convert_count = packet.
GetHexBytes(buf, 0);
2682 if (convert_count != byte_count) {
2684 "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} "
2688 "not match hex-encoded content "
2693 size_t bytes_written = 0;
2697 LLDB_LOG(log,
"pid {0} mem {1:x}: failed to write. Error: {2}",
2702 if (bytes_written == 0) {
2703 LLDB_LOG(log,
"pid {0} mem {1:x}: wrote 0 of {2} requested bytes",
2727 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2754 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2760 packet.
SetFilePos(strlen(
"qMemoryRegionInfo:"));
2781 response.
Printf(
"start:%" PRIx64
";size:%" PRIx64
";",
2830 LLDB_LOG(log,
"failed, no process available");
2838 packet,
"Too short Z packet, missing software/hardware specifier");
2840 bool want_breakpoint =
true;
2841 bool want_hardware =
false;
2842 uint32_t watch_flags = 0;
2846 switch (stoppoint_type) {
2848 want_hardware =
false;
2849 want_breakpoint =
true;
2852 want_hardware =
true;
2853 want_breakpoint =
true;
2857 want_hardware =
true;
2858 want_breakpoint =
false;
2862 want_hardware =
true;
2863 want_breakpoint =
false;
2867 want_hardware =
true;
2868 want_breakpoint =
false;
2872 packet,
"Z packet had invalid software/hardware specifier");
2877 packet,
"Malformed Z packet, expecting comma after stoppoint type");
2886 packet,
"Malformed Z packet, expecting comma after address");
2889 const uint32_t size =
2890 packet.
GetHexMaxU32(
false, std::numeric_limits<uint32_t>::max());
2891 if (size == std::numeric_limits<uint32_t>::max())
2893 packet,
"Malformed Z packet, failed to parse size argument");
2895 if (want_breakpoint) {
2899 if (
error.Success())
2902 LLDB_LOG(log,
"pid {0} failed to set breakpoint: {1}",
2908 addr, size, watch_flags, want_hardware);
2909 if (
error.Success())
2912 LLDB_LOG(log,
"pid {0} failed to set watchpoint: {1}",
2924 LLDB_LOG(log,
"failed, no process available");
2932 packet,
"Too short z packet, missing software/hardware specifier");
2934 bool want_breakpoint =
true;
2935 bool want_hardware =
false;
2939 switch (stoppoint_type) {
2941 want_breakpoint =
true;
2942 want_hardware =
true;
2945 want_breakpoint =
true;
2948 want_breakpoint =
false;
2951 want_breakpoint =
false;
2954 want_breakpoint =
false;
2958 packet,
"z packet had invalid software/hardware specifier");
2963 packet,
"Malformed z packet, expecting comma after stoppoint type");
2972 packet,
"Malformed z packet, expecting comma after address");
2983 if (want_breakpoint) {
2987 if (
error.Success())
2990 LLDB_LOG(log,
"pid {0} failed to remove breakpoint: {1}",
2996 if (
error.Success())
2999 LLDB_LOG(log,
"pid {0} failed to remove watchpoint: {1}",
3014 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3052llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
3057 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3058 "No thread available");
3066 response.
Printf(
"<?xml version=\"1.0\"?>\n");
3067 response.
Printf(
"<target version=\"1.0\">\n");
3071 response.
Printf(
"<architecture>%s</architecture>\n",
3078 response.
Indent(
"<feature>\n");
3081 if (registers_count)
3084 for (
int reg_index = 0; reg_index < registers_count; reg_index++) {
3090 "%s failed to get register info for register index %" PRIu32,
3091 "target.xml", reg_index);
3096 response.
Printf(
"<reg name=\"%s\" bitsize=\"%" PRIu32
3097 "\" regnum=\"%d\" ",
3107 if (!encoding.empty())
3108 response <<
"encoding=\"" << encoding <<
"\" ";
3111 if (!format.empty())
3112 response <<
"format=\"" << format <<
"\" ";
3114 const char *
const register_set_name =
3116 if (register_set_name)
3117 response <<
"group=\"" << register_set_name <<
"\" ";
3119 if (reg_info->
kinds[RegisterKind::eRegisterKindEHFrame] !=
3121 response.
Printf(
"ehframe_regnum=\"%" PRIu32
"\" ",
3122 reg_info->
kinds[RegisterKind::eRegisterKindEHFrame]);
3124 if (reg_info->
kinds[RegisterKind::eRegisterKindDWARF] !=
3126 response.
Printf(
"dwarf_regnum=\"%" PRIu32
"\" ",
3127 reg_info->
kinds[RegisterKind::eRegisterKindDWARF]);
3130 if (!kind_generic.empty())
3131 response <<
"generic=\"" << kind_generic <<
"\" ";
3141 response.
PutCString(
"invalidate_regnums=\"");
3149 if (registers_count)
3152 response.
Indent(
"</feature>\n");
3154 response.
Indent(
"</target>\n");
3155 return MemoryBuffer::getMemBufferCopy(response.
GetString(),
"target.xml");
3158llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
3160 llvm::StringRef annex) {
3164 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3165 "No process available");
3168 if (
object ==
"auxv") {
3171 if (!buffer_or_error)
3172 return llvm::errorCodeToError(buffer_or_error.getError());
3173 return std::move(*buffer_or_error);
3176 if (
object ==
"siginfo") {
3179 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3180 "no current thread");
3183 if (!buffer_or_error)
3184 return buffer_or_error.takeError();
3185 return std::move(*buffer_or_error);
3188 if (
object ==
"libraries-svr4") {
3191 return library_list.takeError();
3194 response.
Printf(
"<library-list-svr4 version=\"1.0\">");
3195 for (
auto const &library : *library_list) {
3196 response.
Printf(
"<library name=\"%s\" ",
3198 response.
Printf(
"lm=\"0x%" PRIx64
"\" ", library.link_map);
3199 response.
Printf(
"l_addr=\"0x%" PRIx64
"\" ", library.base_addr);
3200 response.
Printf(
"l_ld=\"0x%" PRIx64
"\" />", library.ld_addr);
3202 response.
Printf(
"</library-list-svr4>");
3203 return MemoryBuffer::getMemBufferCopy(response.
GetString(), __FUNCTION__);
3206 if (
object ==
"features" && annex ==
"target.xml")
3209 return llvm::make_error<UnimplementedError>();
3215 SmallVector<StringRef, 5> fields;
3217 StringRef(packet.
GetStringRef()).split(fields,
':', 4);
3218 if (fields.size() != 5)
3220 StringRef &xfer_object = fields[1];
3221 StringRef &xfer_action = fields[2];
3222 StringRef &xfer_annex = fields[3];
3224 if (xfer_action !=
"read")
3227 const uint64_t xfer_offset =
3228 offset_data.
GetHexMaxU64(
false, std::numeric_limits<uint64_t>::max());
3229 if (xfer_offset == std::numeric_limits<uint64_t>::max())
3232 if (offset_data.
GetChar() !=
',')
3234 "qXfer packet missing comma after offset");
3236 const uint64_t xfer_length =
3237 offset_data.
GetHexMaxU64(
false, std::numeric_limits<uint64_t>::max());
3238 if (xfer_length == std::numeric_limits<uint64_t>::max())
3242 std::string buffer_key = (xfer_object + xfer_action + xfer_annex).str();
3249 .insert(std::make_pair(buffer_key, std::move(*buffer_up)))
3255 bool done_with_buffer =
false;
3256 llvm::StringRef buffer = buffer_it->second->getBuffer();
3257 if (xfer_offset >= buffer.size()) {
3260 done_with_buffer =
true;
3263 buffer = buffer.drop_front(xfer_offset);
3266 if (xfer_length >= buffer.size()) {
3269 done_with_buffer =
true;
3273 buffer = buffer.take_front(xfer_length);
3279 if (done_with_buffer)
3291 packet.
SetFilePos(strlen(
"QSaveRegisterState"));
3298 packet,
"No thread specified in QSaveRegisterState packet");
3301 "No thread was is set with the Hg packet");
3311 LLDB_LOG(log,
"pid {0} failed to save all register values: {1}",
3319 "GetNextRegisterSaveID() returned an existing register save id");
3329 response.
Printf(
"%" PRIu32, save_id);
3339 packet.
SetFilePos(strlen(
"QRestoreRegisterState:"));
3342 packet,
"QRestoreRegisterState packet missing register save id");
3344 const uint32_t save_id = packet.
GetU32(0);
3346 LLDB_LOG(log,
"QRestoreRegisterState packet has malformed save id, "
3347 "expecting decimal uint32_t");
3356 packet,
"No thread specified in QRestoreRegisterState packet");
3359 "No thread was is set with the Hg packet");
3374 "pid {0} does not have a register set save buffer for id {1}",
3378 register_data_sp = it->second;
3386 LLDB_LOG(log,
"pid {0} failed to restore all register values: {1}",
3408 "vAttach failed to parse the process id");
3412 "GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
3420 "GDBRemoteCommunicationServerLLGS::%s failed to attach to "
3421 "pid %" PRIu64
": %s\n",
3422 __FUNCTION__, pid,
error.AsCString());
3445 std::string process_name;
3448 "vAttachWait failed to parse process name");
3450 LLDB_LOG(log,
"attempting to attach to process named '{0}'", process_name);
3454 LLDB_LOG(log,
"failed to attach to process named '{0}': {1}", process_name,
3484 std::string process_name;
3487 "vAttachOrWait failed to parse process name");
3489 LLDB_LOG(log,
"attempting to attach to process named '{0}'", process_name);
3493 LLDB_LOG(log,
"failed to attach to process named '{0}': {1}", process_name,
3511 if (!s.consume_front(
"vRun;"))
3514 llvm::SmallVector<llvm::StringRef, 16> argv;
3517 for (llvm::StringRef hex_arg : argv) {
3522 LLDB_LOGF(log,
"LLGSPacketHandler::%s added arg: \"%s\"", __FUNCTION__,
3561 llvm::Error detach_error = llvm::Error::success();
3562 bool detached =
false;
3567 "GDBRemoteCommunicationServerLLGS::%s detaching %" PRId64,
3568 __FUNCTION__, it->first);
3569 if (llvm::Error e = it->second.process_up->Detach().ToError())
3570 detach_error = llvm::joinErrors(std::move(detach_error), std::move(e));
3600 packet.
SetFilePos(strlen(
"qThreadStopInfo"));
3604 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
3605 "parse thread id from request \"%s\"",
3625 const bool threads_with_valid_stop_info_only =
false;
3626 llvm::Expected<json::Value> threads_info =
3628 if (!threads_info) {
3630 "failed to prepare a packet for pid {1}: {0}",
3649 packet.
SetFilePos(strlen(
"qWatchpointSupportInfo"));
3658 if (hw_debug_cap == std::nullopt)
3659 response.
Printf(
"num:0;");
3661 response.
Printf(
"num:%d;", hw_debug_cap->second);
3674 packet.
SetFilePos(strlen(
"qFileLoadAddress:"));
3678 std::string file_name;
3691 response.
PutHex64(file_load_address);
3698 std::vector<int> signals;
3704 int signal = packet.
GetS32(-1, 16);
3707 signals.push_back(signal);
3710 char separator = packet.
GetChar();
3711 if (separator ==
'\0')
3713 if (separator !=
';')
3715 " expected semicolon.");
3739 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3749 const char *current_char = packet.
Peek();
3750 if (!current_char || *current_char ==
',')
3755 char previous_char = packet.
GetChar();
3756 current_char = packet.
Peek();
3758 if (previous_char !=
',' || (current_char && *current_char ==
':'))
3760 "Invalid addr,length pair in qMemTags packet");
3764 packet,
"Too short qMemtags: packet (looking for length)");
3768 const char *invalid_type_err =
"Invalid type field in qMemTags: packet";
3774 const char *first_type_char = packet.
Peek();
3775 if (first_type_char && (*first_type_char ==
'+' || *first_type_char ==
'-'))
3782 packet.
GetU64(std::numeric_limits<uint64_t>::max(), 16);
3785 raw_type > std::numeric_limits<uint32_t>::max() ||
3794 uint32_t raw_type_32 = raw_type;
3795 int32_t type =
reinterpret_cast<int32_t &
>(raw_type_32);
3798 std::vector<uint8_t> tags;
3820 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3830 const char *current_char = packet.
Peek();
3831 if (!current_char || *current_char ==
',')
3836 char previous_char = packet.
GetChar();
3837 current_char = packet.
Peek();
3839 if (previous_char !=
',' || (current_char && *current_char ==
':'))
3841 "Invalid addr,length pair in QMemTags packet");
3845 packet,
"Too short QMemtags: packet (looking for length)");
3849 const char *invalid_type_err =
"Invalid type field in QMemTags: packet";
3854 const char *first_type_char = packet.
Peek();
3855 if (first_type_char && (*first_type_char ==
'+' || *first_type_char ==
'-'))
3863 packet.
GetU64(std::numeric_limits<uint64_t>::max(), 16);
3864 if (raw_type > std::numeric_limits<uint32_t>::max())
3869 uint32_t raw_type_32 = raw_type;
3870 int32_t type =
reinterpret_cast<int32_t &
>(raw_type_32);
3875 "Missing tag data in QMemTags: packet");
3878 const char *invalid_data_err =
"Invalid tag data in QMemTags: packet";
3885 std::vector<uint8_t> tag_data;
3890 tag_data.resize(byte_count);
3891 size_t converted_bytes = packet.
GetHexBytes(tag_data, 0);
3892 if (converted_bytes != byte_count) {
3910 std::string path_hint;
3913 assert(packet_str.startswith(
"qSaveCore"));
3914 if (packet_str.consume_front(
"qSaveCore;")) {
3915 for (
auto x : llvm::split(packet_str,
';')) {
3916 if (x.consume_front(
"path-hint:"))
3939 assert(packet_str.startswith(
"QNonStop:"));
3940 packet_str.consume_front(
"QNonStop:");
3941 if (packet_str ==
"0") {
3945 if (process_it.second.process_up->IsRunning()) {
3947 Status error = process_it.second.process_up->Interrupt();
3950 "while disabling nonstop, failed to halt process {0}: {1}",
3951 process_it.first,
error);
3965 }
else if (packet_str ==
"1") {
3976 std::deque<std::string> &queue) {
4018 return interrupt_res;
4030 inconvertibleErrorCode(),
"Malformed thread-id"));
4039 inconvertibleErrorCode(),
"No current process and no PID provided"));
4047 if (!new_process_it->second.process_up->GetThreadByID(tid))
4061 connection->Disconnect(&
error);
4063 if (
error.Success()) {
4065 "GDBRemoteCommunicationServerLLGS::%s disconnect process "
4066 "terminal stdio - SUCCESS",
4070 "GDBRemoteCommunicationServerLLGS::%s disconnect process "
4071 "terminal stdio - FAIL: %s",
4072 __FUNCTION__,
error.AsCString());
4091 else if (current_tid == 0) {
4103 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
4104 "error: expected ';' prior to start of thread suffix: packet "
4114 if (strncmp(packet.
Peek(),
"thread:", strlen(
"thread:")) != 0) {
4116 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
4117 "error: expected 'thread:' but not found, packet contents = "
4161 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
4172 llvm::StringRef value) {
4174 for (
const char &c : value) {
4197 const llvm::ArrayRef<llvm::StringRef> client_features) {
4198 std::vector<std::string> ret =
4200 ret.insert(ret.end(), {
4201 "QThreadSuffixSupported+",
4202 "QListThreadsInStopReply+",
4203 "qXfer:features:read+",
4210 if (
bool(plugin_features & Extension::pass_signals))
4211 ret.push_back(
"QPassSignals+");
4212 if (
bool(plugin_features & Extension::auxv))
4213 ret.push_back(
"qXfer:auxv:read+");
4214 if (
bool(plugin_features & Extension::libraries_svr4))
4215 ret.push_back(
"qXfer:libraries-svr4:read+");
4216 if (
bool(plugin_features & Extension::siginfo_read))
4217 ret.push_back(
"qXfer:siginfo:read+");
4218 if (
bool(plugin_features & Extension::memory_tagging))
4219 ret.push_back(
"memory-tagging+");
4220 if (
bool(plugin_features & Extension::savecore))
4221 ret.push_back(
"qSaveCore+");
4225 for (llvm::StringRef x : client_features)
4227 llvm::StringSwitch<Extension>(x)
4228 .Case(
"multiprocess+", Extension::multiprocess)
4229 .Case(
"fork-events+", Extension::fork)
4230 .Case(
"vfork-events+", Extension::vfork)
4241 ret.push_back(
"multiprocess+");
4243 ret.push_back(
"fork-events+");
4245 ret.push_back(
"vfork-events+");
4271 response.
Format(
"p{0:x-}.", pid);
4272 response.
Format(
"{0:x-}", tid);
4277 bool reverse_connect) {
4279 if (std::optional<URI> url =
URI::Parse(url_arg)) {
4280 if (reverse_connect)
4281 return url_arg.str();
4286 std::string new_url = llvm::StringSwitch<std::string>(url->scheme)
4287 .Case(
"tcp",
"listen")
4288 .Case(
"unix",
"unix-accept")
4289 .Case(
"unix-abstract",
"unix-abstract-accept")
4290 .Default(url->scheme.str());
4291 llvm::append_range(new_url, url_arg.substr(url->scheme.size()));
4295 std::string host_port = url_arg.str();
4298 if (url_arg.startswith(
":"))
4299 host_port.insert(0,
"localhost");
4303 return (reverse_connect ?
"connect://" :
"listen://") + host_port;
4306 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.