9#include "lldb/Host/Config.h"
14#include <netinet/in.h>
16#include <sys/socket.h>
21#include <sys/sysctl.h>
88#include "llvm/ADT/ScopeExit.h"
89#include "llvm/ADT/StringMap.h"
90#include "llvm/ADT/StringSwitch.h"
91#include "llvm/Support/FormatAdapters.h"
92#include "llvm/Support/Threading.h"
93#include "llvm/Support/raw_ostream.h"
95#define DEBUGSERVER_BASENAME "debugserver"
113 llvm::consumeError(file.takeError());
117 ((
Process *)p)->DumpPluginHistory(stream);
123#define LLDB_PROPERTIES_processgdbremote
124#include "ProcessGDBRemoteProperties.inc"
127#define LLDB_PROPERTIES_processgdbremote
128#include "ProcessGDBRemotePropertiesEnum.inc"
133 static llvm::StringRef GetSettingName() {
138 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
139 m_collection_sp->Initialize(g_processgdbremote_properties);
142 ~PluginProperties()
override =
default;
144 uint64_t GetPacketTimeout() {
145 const uint32_t idx = ePropertyPacketTimeout;
146 return GetPropertyAtIndexAs<uint64_t>(
147 idx, g_processgdbremote_properties[idx].default_uint_value);
150 bool SetPacketTimeout(uint64_t timeout) {
151 const uint32_t idx = ePropertyPacketTimeout;
155 FileSpec GetTargetDefinitionFile()
const {
156 const uint32_t idx = ePropertyTargetDefinitionFile;
157 return GetPropertyAtIndexAs<FileSpec>(idx, {});
160 bool GetUseSVR4()
const {
161 const uint32_t idx = ePropertyUseSVR4;
162 return GetPropertyAtIndexAs<bool>(
163 idx, g_processgdbremote_properties[idx].default_uint_value != 0);
166 bool GetUseGPacketForReading()
const {
167 const uint32_t idx = ePropertyUseGPacketForReading;
168 return GetPropertyAtIndexAs<bool>(idx,
true);
175 static PluginProperties g_settings;
183#if defined(__APPLE__)
184#define LOW_PORT (IPPORT_RESERVED)
185#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
187#define LOW_PORT (1024u)
188#define HIGH_PORT (49151u)
192 return "GDB Remote protocol based debugging plug-in.";
201 const FileSpec *crash_file_path,
bool can_connect) {
203 if (crash_file_path ==
nullptr)
204 process_sp = std::shared_ptr<ProcessGDBRemote>(
223 bool plugin_specified_by_name) {
224 if (plugin_specified_by_name)
228 Module *exe_module = target_sp->GetExecutableModulePointer();
232 switch (exe_objfile->
GetType()) {
256 :
Process(target_sp, listener_sp),
258 m_async_broadcaster(nullptr,
"lldb.process.gdb-remote.async-broadcaster"),
260 Listener::MakeListener(
"lldb.process.gdb-remote.async-listener")),
261 m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(),
262 m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(),
263 m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(),
264 m_max_memory_size(0), m_remote_stub_max_memory_size(0),
265 m_addr_to_mmap_size(), m_thread_create_bp_sp(),
266 m_waiting_for_attach(false), m_command_sp(), m_breakpoint_pc_offset(0),
268 m_erased_flash_ranges(), m_vfork_in_progress_count(0) {
270 "async thread should exit");
272 "async thread continue");
274 "async thread did exit");
278 const uint32_t async_event_mask =
284 "ProcessGDBRemote::%s failed to listen for "
285 "m_async_broadcaster events",
289 const uint64_t timeout_seconds =
291 if (timeout_seconds > 0)
317 const FileSpec &target_definition_fspec) {
323 if (module_object_sp) {
326 "gdb-server-target-definition",
error));
328 if (target_definition_sp) {
330 target_definition_sp->GetValueForKey(
"host-info"));
332 if (
auto host_info_dict = target_object->GetAsDictionary()) {
334 host_info_dict->GetValueForKey(
"triple");
335 if (
auto triple_string_value = triple_value->GetAsString()) {
336 std::string triple_string =
337 std::string(triple_string_value->GetValue());
338 ArchSpec host_arch(triple_string.c_str());
347 target_definition_sp->GetValueForKey(
"breakpoint-pc-offset");
348 if (breakpoint_pc_offset_value) {
349 if (
auto breakpoint_pc_int_value =
350 breakpoint_pc_offset_value->GetAsSignedInteger())
355 *target_definition_sp,
GetTarget().GetArchitecture()) > 0) {
364 const llvm::StringRef &comma_separated_register_numbers,
365 std::vector<uint32_t> ®nums,
int base) {
367 for (llvm::StringRef x : llvm::split(comma_separated_register_numbers,
',')) {
369 if (llvm::to_integer(x, reg, base))
370 regnums.push_back(reg);
372 return regnums.size();
385 if (host_packet_timeout > std::chrono::seconds(0)) {
403 if (target_definition_fspec) {
409 target_definition_fspec.
GetPath() +
420 if (remote_process_arch.
IsValid())
421 arch_to_use = remote_process_arch;
423 arch_to_use = remote_host_arch;
426 arch_to_use = target_arch;
432 std::vector<DynamicRegisterInfo::Register> registers;
433 uint32_t reg_num = 0;
437 const int packet_len =
438 ::snprintf(packet,
sizeof(packet),
"qRegisterInfo%x", reg_num);
439 assert(packet_len < (
int)
sizeof(packet));
446 llvm::StringRef name;
447 llvm::StringRef value;
451 if (name ==
"name") {
453 }
else if (name ==
"alt-name") {
455 }
else if (name ==
"bitsize") {
456 if (!value.getAsInteger(0, reg_info.
byte_size))
458 }
else if (name ==
"offset") {
460 }
else if (name ==
"encoding") {
464 }
else if (name ==
"format") {
468 llvm::StringSwitch<Format>(value)
483 }
else if (name ==
"set") {
485 }
else if (name ==
"gcc" || name ==
"ehframe") {
487 }
else if (name ==
"dwarf") {
489 }
else if (name ==
"generic") {
491 }
else if (name ==
"container-regs") {
493 }
else if (name ==
"invalidate-regs") {
499 registers.push_back(reg_info);
508 if (registers.empty())
523 bool wait_for_launch) {
568 error.SetErrorStringWithFormat(
569 "Process %" PRIu64
" was reported after connecting to "
570 "'%s', but state was not stopped: %s",
573 error.SetErrorStringWithFormat(
"Process %" PRIu64
574 " was reported after connecting to '%s', "
575 "but no stop reply packet was received",
576 pid, remote_url.str().c_str());
580 "ProcessGDBRemote::%s pid %" PRIu64
581 ": normalizing target architecture initial triple: %s "
582 "(GetTarget().GetArchitecture().IsValid() %s, "
583 "m_gdb_comm.GetHostArchitecture().IsValid(): %s)",
584 __FUNCTION__,
GetID(),
585 GetTarget().GetArchitecture().GetTriple().getTriple().c_str(),
600 "ProcessGDBRemote::%s pid %" PRIu64
601 ": normalized target architecture triple: %s",
602 __FUNCTION__,
GetID(),
603 GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
620 LLDB_LOGF(log,
"ProcessGDBRemote::%s() entered", __FUNCTION__);
622 uint32_t launch_flags = launch_info.
GetFlags().
Get();
646 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
648 "ProcessGDBRemote::%s provided with STDIO paths via "
649 "launch_info: stdin=%s, stdout=%s, stderr=%s",
651 stdin_file_spec ? stdin_file_spec.GetPath().c_str() :
"<null>",
652 stdout_file_spec ? stdout_file_spec.GetPath().c_str() :
"<null>",
653 stderr_file_spec ? stderr_file_spec.GetPath().c_str() :
"<null>");
656 "ProcessGDBRemote::%s no STDIO paths given via launch_info",
660 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
661 if (stdin_file_spec || disable_stdio) {
676 if (
error.Success()) {
678 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
683 if (!stdin_file_spec)
685 FileSpec::Style::native);
686 if (!stdout_file_spec)
688 FileSpec::Style::native);
689 if (!stderr_file_spec)
691 FileSpec::Style::native);
692 }
else if (platform_sp && platform_sp->IsHost()) {
697 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
701 if (!stdin_file_spec)
702 stdin_file_spec = secondary_name;
704 if (!stdout_file_spec)
705 stdout_file_spec = secondary_name;
707 if (!stderr_file_spec)
708 stderr_file_spec = secondary_name;
712 "ProcessGDBRemote::%s adjusted STDIO paths for local platform "
713 "(IsHost() is true) using secondary: stdin=%s, stdout=%s, "
716 stdin_file_spec ? stdin_file_spec.GetPath().c_str() :
"<null>",
717 stdout_file_spec ? stdout_file_spec.GetPath().c_str() :
"<null>",
718 stderr_file_spec ? stderr_file_spec.GetPath().c_str() :
"<null>");
722 "ProcessGDBRemote::%s final STDIO paths after all "
723 "adjustments: stdin=%s, stdout=%s, stderr=%s",
725 stdin_file_spec ? stdin_file_spec.GetPath().c_str() :
"<null>",
726 stdout_file_spec ? stdout_file_spec.GetPath().c_str() :
"<null>",
727 stderr_file_spec ? stderr_file_spec.GetPath().c_str() :
"<null>");
731 if (stdout_file_spec)
733 if (stderr_file_spec)
740 GetTarget().GetArchitecture().GetArchitectureName());
743 if (launch_event_data !=
nullptr && *launch_event_data !=
'\0')
756 std::chrono::seconds(10));
764 error.SetErrorStringWithFormatv(
"Cannot launch '{0}': {1}",
766 llvm::fmt_consume(std::move(err)));
773 LLDB_LOGF(log,
"failed to connect to debugserver: %s",
795 if (!disable_stdio) {
801 LLDB_LOGF(log,
"failed to connect to debugserver: %s",
error.AsCString());
811 if (!connect_url.empty()) {
812 LLDB_LOGF(log,
"ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,
813 connect_url.str().c_str());
814 std::unique_ptr<ConnectionFileDescriptor> conn_up(
817 const uint32_t max_retry_count = 50;
818 uint32_t retry_count = 0;
827 if (retry_count >= max_retry_count)
830 std::this_thread::sleep_for(std::chrono::milliseconds(100));
837 error.SetErrorString(
"not connected to remote gdb server");
848 error.SetErrorString(
"not connected to remote gdb server");
861 auto handle_cmds = [&] (
const Args &args) ->
void {
865 entry.c_str(), response);
871 handle_cmds(platform_sp->GetExtraStartupCommands());
888 if (remote_process_arch.
IsValid()) {
889 process_arch = remote_process_arch;
890 LLDB_LOG(log,
"gdb-remote had process architecture, using {0} {1}",
896 "gdb-remote did not have process architecture, using gdb-remote "
897 "host architecture {0} {1}",
908 LLDB_LOG(log,
"analyzing target arch, currently {0} {1}",
920 if ((process_arch.
GetMachine() == llvm::Triple::arm ||
921 process_arch.
GetMachine() == llvm::Triple::thumb) &&
922 process_arch.
GetTriple().getVendor() == llvm::Triple::Apple) {
925 "remote process is ARM/Apple, "
926 "setting target arch to {0} {1}",
931 const llvm::Triple &remote_triple = process_arch.
GetTriple();
932 llvm::Triple new_target_triple = target_arch.
GetTriple();
933 if (new_target_triple.getVendorName().size() == 0) {
934 new_target_triple.setVendor(remote_triple.getVendor());
936 if (new_target_triple.getOSName().size() == 0) {
937 new_target_triple.setOS(remote_triple.getOS());
939 if (new_target_triple.getEnvironmentName().size() == 0)
940 new_target_triple.setEnvironment(remote_triple.getEnvironment());
943 ArchSpec new_target_arch = target_arch;
944 new_target_arch.
SetTriple(new_target_triple);
950 "final target arch after adjustments for remote architecture: "
978 if (platform_sp && platform_sp->IsConnected())
990 UUID standalone_uuid;
992 bool standalone_value_is_offset;
994 standalone_value_is_offset)) {
997 if (standalone_uuid.
IsValid()) {
998 const bool force_symbol_search =
true;
999 const bool notify =
true;
1000 const bool set_address_in_target =
true;
1001 const bool allow_memory_image_last_resort =
false;
1003 this,
"", standalone_uuid, standalone_value,
1004 standalone_value_is_offset, force_symbol_search, notify,
1005 set_address_in_target, allow_memory_image_last_resort);
1018 if (bin_addrs.size()) {
1020 const bool value_is_slide =
false;
1021 for (
addr_t addr : bin_addrs) {
1022 const bool notify =
true;
1029 .LoadPlatformBinaryAndSetup(
this, addr, notify))
1032 const bool force_symbol_search =
true;
1033 const bool set_address_in_target =
true;
1034 const bool allow_memory_image_last_resort =
false;
1037 this, llvm::StringRef(), uuid, addr, value_is_slide,
1038 force_symbol_search, notify, set_address_in_target,
1039 allow_memory_image_last_resort);
1054 size_t(llvm::count(offsets->offsets, offsets->offsets[0])) ==
1055 offsets->offsets.size();
1059 bool changed =
false;
1060 module_sp->SetLoadAddress(
GetTarget(), offsets->offsets[0],
1079 LLDB_LOGF(log,
"ProcessGDBRemote::%s()", __FUNCTION__);
1085 if (
error.Success()) {
1089 const int packet_len =
1090 ::snprintf(packet,
sizeof(packet),
"vAttach;%" PRIx64, attach_pid);
1093 std::make_shared<EventDataBytes>(llvm::StringRef(packet, packet_len));
1108 if (process_name && process_name[0]) {
1110 if (
error.Success()) {
1131 auto data_sp = std::make_shared<EventDataBytes>(packet.
GetString());
1152llvm::Expected<std::string>
1157llvm::Expected<std::vector<uint8_t>>
1169 process_arch.
Clear();
1186 LLDB_LOGF(log,
"ProcessGDBRemote::Resume()");
1190 if (listener_sp->StartListeningForEvents(
1192 listener_sp->StartListeningForEvents(
1199 bool continue_packet_error =
false;
1201 std::string pid_prefix;
1203 pid_prefix = llvm::formatv(
"p{0:x-}.",
GetID());
1210 continue_packet.
Format(
"vCont;c:{0}-1", pid_prefix);
1218 for (tid_collection::const_iterator
1221 t_pos != t_end; ++t_pos)
1222 continue_packet.
Format(
";c:{0}{1:x-}", pid_prefix, *t_pos);
1224 continue_packet_error =
true;
1229 for (tid_sig_collection::const_iterator
1232 s_pos != s_end; ++s_pos)
1233 continue_packet.
Format(
";C{0:x-2}:{1}{2:x-}", s_pos->second,
1234 pid_prefix, s_pos->first);
1236 continue_packet_error =
true;
1241 for (tid_collection::const_iterator
1244 t_pos != t_end; ++t_pos)
1245 continue_packet.
Format(
";s:{0}{1:x-}", pid_prefix, *t_pos);
1247 continue_packet_error =
true;
1252 for (tid_sig_collection::const_iterator
1255 s_pos != s_end; ++s_pos)
1256 continue_packet.
Format(
";S{0:x-2}:{1}{2:x-}", s_pos->second,
1257 pid_prefix, s_pos->first);
1259 continue_packet_error =
true;
1262 if (continue_packet_error)
1263 continue_packet.
Clear();
1266 continue_packet_error =
true;
1268 if (continue_packet_error) {
1276 if (num_continue_c_tids > 0) {
1277 if (num_continue_c_tids == num_threads) {
1281 continue_packet_error =
false;
1282 }
else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
1283 num_continue_s_tids == 0 && num_continue_S_tids == 0) {
1287 continue_packet_error =
false;
1291 if (continue_packet_error && num_continue_C_tids > 0) {
1292 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1293 num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
1294 num_continue_S_tids == 0) {
1297 if (num_continue_C_tids > 1) {
1302 if (num_continue_C_tids > 1) {
1303 continue_packet_error =
false;
1306 continue_packet_error =
true;
1309 if (!continue_packet_error)
1313 continue_packet_error =
false;
1316 if (!continue_packet_error) {
1318 continue_packet.
Printf(
"C%2.2x", continue_signo);
1323 if (continue_packet_error && num_continue_s_tids > 0) {
1324 if (num_continue_s_tids == num_threads) {
1330 continue_packet_error =
false;
1331 }
else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1332 num_continue_s_tids == 1 && num_continue_S_tids == 0) {
1336 continue_packet_error =
false;
1340 if (!continue_packet_error && num_continue_S_tids > 0) {
1341 if (num_continue_S_tids == num_threads) {
1344 continue_packet_error =
false;
1345 if (num_continue_S_tids > 1) {
1346 for (
size_t i = 1; i < num_threads; ++i) {
1348 continue_packet_error =
true;
1351 if (!continue_packet_error) {
1354 continue_packet.
Printf(
"S%2.2x", step_signo);
1356 }
else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1357 num_continue_s_tids == 0 && num_continue_S_tids == 1) {
1361 continue_packet_error =
false;
1366 if (continue_packet_error) {
1367 error.SetErrorString(
"can't make continue packet for this resume");
1371 error.SetErrorString(
"Trying to resume but the async thread is dead.");
1372 LLDB_LOGF(log,
"ProcessGDBRemote::DoResume: Trying to resume but the "
1373 "async thread is dead.");
1378 std::make_shared<EventDataBytes>(continue_packet.
GetString());
1381 if (!listener_sp->GetEvent(event_sp, std::chrono::seconds(5))) {
1382 error.SetErrorString(
"Resume timed out.");
1383 LLDB_LOGF(log,
"ProcessGDBRemote::DoResume: Resume timed out.");
1385 error.SetErrorString(
"Broadcast continue, but the async thread was "
1386 "killed before we got an ack back.");
1388 "ProcessGDBRemote::DoResume: Broadcast continue, but the "
1389 "async thread was killed before we got an ack back.");
1405 llvm::StringRef value) {
1411 auto pid_tid = thread_ids.
GetPidTid(pid);
1412 if (pid_tid && pid_tid->first == pid) {
1418 }
while (thread_ids.GetChar() ==
',');
1424 llvm::StringRef value) {
1426 for (llvm::StringRef x : llvm::split(value,
',')) {
1428 if (llvm::to_integer(x,
pc, 16))
1440 if (thread_infos && thread_infos->
GetSize() > 0) {
1464 const std::string &stop_info_str = std::string(stop_info.
GetStringRef());
1467 const size_t thread_pcs_pos = stop_info_str.find(
";thread-pcs:");
1468 if (thread_pcs_pos != std::string::npos) {
1469 const size_t start = thread_pcs_pos + strlen(
";thread-pcs:");
1470 const size_t end = stop_info_str.find(
';', start);
1471 if (end != std::string::npos) {
1472 std::string value = stop_info_str.substr(start, end - start);
1477 const size_t threads_pos = stop_info_str.find(
";threads:");
1478 if (threads_pos != std::string::npos) {
1479 const size_t start = threads_pos + strlen(
";threads:");
1480 const size_t end = stop_info_str.find(
';', start);
1481 if (end != std::string::npos) {
1482 std::string value = stop_info_str.substr(start, end - start);
1490 bool sequence_mutex_unavailable =
false;
1492 if (sequence_mutex_unavailable) {
1507 if (num_thread_ids == 0) {
1513 ThreadList old_thread_list_copy(old_thread_list);
1514 if (num_thread_ids > 0) {
1515 for (
size_t i = 0; i < num_thread_ids; ++i) {
1520 thread_sp = std::make_shared<ThreadGDBRemote>(*
this, tid);
1521 LLDB_LOGV(log,
"Making new thread: {0} for thread ID: {1:x}.",
1522 thread_sp.get(), thread_sp->GetID());
1524 LLDB_LOGV(log,
"Found old thread: {0} for thread ID: {1:x}.",
1525 thread_sp.get(), thread_sp->GetID());
1535 size_t old_num_thread_ids = old_thread_list_copy.
GetSize(
false);
1536 for (
size_t i = 0; i < old_num_thread_ids; i++) {
1538 if (old_thread_sp) {
1539 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1554 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1567 if (thread_infos_sp) {
1571 const size_t n = thread_infos->
GetSize();
1572 for (
size_t i = 0; i < n; ++i) {
1578 if (tid == thread->
GetID())
1607 for (
size_t i = 0; i < num_thread_ids; i++) {
1611 thread->
GetProcess()->GetBreakpointSiteList().FindByAddress(
pc);
1613 if (bp_site_sp->ValidForThisThread(*thread)) {
1616 *thread, bp_site_sp->
GetID()));
1639 for (
const auto &pair : expedited_register_map) {
1643 reg_value_extractor.
GetHexBytes(buffer_sp->GetData(),
'\xcc');
1644 uint32_t lldb_regnum = gdb_reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1652 uint8_t signo,
const std::string &thread_name,
const std::string &reason,
1653 const std::string &description, uint32_t exc_type,
1654 const std::vector<addr_t> &exc_data,
addr_t thread_dispatch_qaddr,
1655 bool queue_vars_valid,
1657 LazyBool associated_with_dispatch_queue,
addr_t dispatch_queue_t,
1658 std::string &queue_name,
QueueKind queue_kind, uint64_t queue_serial) {
1674 thread_sp = std::make_shared<ThreadGDBRemote>(*
this, tid);
1682 reg_ctx_sp->InvalidateIfNeeded(
true);
1690 if (reg_ctx_sp->ReconfigureRegisterInfo()) {
1693 reg_ctx_sp->InvalidateAllRegisters();
1700 thread_sp->SetName(thread_name.empty() ?
nullptr : thread_name.c_str());
1705 if (queue_vars_valid)
1706 gdb_thread->
SetQueueInfo(std::move(queue_name), queue_kind, queue_serial,
1707 dispatch_queue_t, associated_with_dispatch_queue);
1718 StopInfoSP current_stop_info_sp = thread_sp->GetPrivateStopInfo(
false);
1720 current_stop_info_sp) {
1721 thread_sp->SetStopInfo(current_stop_info_sp);
1725 if (!thread_sp->StopInfoIsUpToDate()) {
1730 thread_sp = memory_thread_sp;
1732 if (exc_type != 0) {
1740 if (interrupt_thread)
1741 thread_sp = interrupt_thread;
1743 const size_t exc_data_size = exc_data.size();
1744 thread_sp->SetStopInfo(
1746 *thread_sp, exc_type, exc_data_size,
1747 exc_data_size >= 1 ? exc_data[0] : 0,
1748 exc_data_size >= 2 ? exc_data[1] : 0,
1749 exc_data_size >= 3 ? exc_data[2] : 0));
1752 bool handled =
false;
1753 bool did_exec =
false;
1756 if (!reason.empty() && reason !=
"none") {
1757 if (reason ==
"trace") {
1758 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1760 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1765 if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
1766 thread_sp->SetStopInfo(
1768 *thread_sp, bp_site_sp->GetID()));
1770 thread_sp->SetStopInfo(
1773 }
else if (reason ==
"breakpoint") {
1774 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1776 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1785 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
1786 thread_sp->SetStopInfo(
1788 *thread_sp, bp_site_sp->GetID()));
1791 thread_sp->SetStopInfo(invalid_stop_info_sp);
1794 }
else if (reason ==
"trap") {
1796 }
else if (reason ==
"watchpoint") {
1832 bool silently_continue =
false;
1842 silently_continue =
true;
1846 if (!wp_resource_sp) {
1848 LLDB_LOGF(log,
"failed to find watchpoint");
1855 watch_id = wp_resource_sp->GetConstituentAtIndex(0)->GetID();
1858 *thread_sp, watch_id, silently_continue));
1860 }
else if (reason ==
"exception") {
1862 *thread_sp, description.c_str()));
1864 }
else if (reason ==
"exec") {
1866 thread_sp->SetStopInfo(
1869 }
else if (reason ==
"processor trace") {
1871 *thread_sp, description.c_str()));
1872 }
else if (reason ==
"fork") {
1877 thread_sp->SetStopInfo(
1880 }
else if (reason ==
"vfork") {
1886 *thread_sp, child_pid, child_tid));
1888 }
else if (reason ==
"vforkdone") {
1889 thread_sp->SetStopInfo(
1893 }
else if (!signo) {
1894 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1896 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
pc);
1902 if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
1904 *thread_sp, bp_site_sp->GetID()));
1909 if (!handled && signo && !did_exec) {
1917 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1926 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
1928 thread_sp->GetRegisterContext()->SetPC(
pc);
1929 thread_sp->SetStopInfo(
1931 *thread_sp, bp_site_sp->GetID()));
1934 thread_sp->SetStopInfo(invalid_stop_info_sp);
1942 thread_sp->SetStopInfo(
1946 *thread_sp, signo, description.c_str()));
1957 if (interrupt_thread)
1958 thread_sp = interrupt_thread;
1961 *thread_sp, signo, description.c_str()));
1965 if (!description.empty()) {
1968 const char *stop_info_desc = stop_info_sp->GetDescription();
1969 if (!stop_info_desc || !stop_info_desc[0])
1970 stop_info_sp->SetDescription(description.c_str());
1973 *thread_sp, description.c_str()));
1983 const std::string &description) {
1992 *thread_sp, signo, description.c_str()));
2001 static constexpr llvm::StringLiteral g_key_tid(
"tid");
2002 static constexpr llvm::StringLiteral g_key_name(
"name");
2003 static constexpr llvm::StringLiteral g_key_reason(
"reason");
2004 static constexpr llvm::StringLiteral g_key_metype(
"metype");
2005 static constexpr llvm::StringLiteral g_key_medata(
"medata");
2006 static constexpr llvm::StringLiteral g_key_qaddr(
"qaddr");
2007 static constexpr llvm::StringLiteral g_key_dispatch_queue_t(
2008 "dispatch_queue_t");
2009 static constexpr llvm::StringLiteral g_key_associated_with_dispatch_queue(
2010 "associated_with_dispatch_queue");
2011 static constexpr llvm::StringLiteral g_key_queue_name(
"qname");
2012 static constexpr llvm::StringLiteral g_key_queue_kind(
"qkind");
2013 static constexpr llvm::StringLiteral g_key_queue_serial_number(
"qserialnum");
2014 static constexpr llvm::StringLiteral g_key_registers(
"registers");
2015 static constexpr llvm::StringLiteral g_key_memory(
"memory");
2016 static constexpr llvm::StringLiteral g_key_description(
"description");
2017 static constexpr llvm::StringLiteral g_key_signal(
"signal");
2023 std::string thread_name;
2025 std::string description;
2026 uint32_t exc_type = 0;
2027 std::vector<addr_t> exc_data;
2030 bool queue_vars_valid =
false;
2033 std::string queue_name;
2035 uint64_t queue_serial_number = 0;
2040 thread_dict->
ForEach([
this, &tid, &expedited_register_map, &thread_name,
2041 &signo, &reason, &description, &exc_type, &exc_data,
2042 &thread_dispatch_qaddr, &queue_vars_valid,
2043 &associated_with_dispatch_queue, &dispatch_queue_t,
2044 &queue_name, &queue_kind, &queue_serial_number](
2045 llvm::StringRef key,
2047 if (key == g_key_tid) {
2050 }
else if (key == g_key_metype) {
2052 exc_type =
object->GetUnsignedIntegerValue(0);
2053 }
else if (key == g_key_medata) {
2062 }
else if (key == g_key_name) {
2064 }
else if (key == g_key_qaddr) {
2065 thread_dispatch_qaddr =
2067 }
else if (key == g_key_queue_name) {
2068 queue_vars_valid =
true;
2070 }
else if (key == g_key_queue_kind) {
2071 std::string queue_kind_str = std::string(object->
GetStringValue());
2072 if (queue_kind_str ==
"serial") {
2073 queue_vars_valid =
true;
2075 }
else if (queue_kind_str ==
"concurrent") {
2076 queue_vars_valid =
true;
2079 }
else if (key == g_key_queue_serial_number) {
2080 queue_serial_number =
object->GetUnsignedIntegerValue(0);
2081 if (queue_serial_number != 0)
2082 queue_vars_valid =
true;
2083 }
else if (key == g_key_dispatch_queue_t) {
2084 dispatch_queue_t =
object->GetUnsignedIntegerValue(0);
2086 queue_vars_valid =
true;
2087 }
else if (key == g_key_associated_with_dispatch_queue) {
2088 queue_vars_valid =
true;
2089 bool associated =
object->GetBooleanValue();
2094 }
else if (key == g_key_reason) {
2096 }
else if (key == g_key_description) {
2098 }
else if (key == g_key_registers) {
2101 if (registers_dict) {
2103 [&expedited_register_map](llvm::StringRef key,
2106 if (llvm::to_integer(key, reg))
2107 expedited_register_map[reg] =
2112 }
else if (key == g_key_memory) {
2118 if (mem_cache_dict) {
2121 "address", mem_cache_addr)) {
2122 if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
2123 llvm::StringRef str;
2124 if (mem_cache_dict->GetValueForKeyAsString(
"bytes", str)) {
2125 StringExtractor bytes(str);
2126 bytes.SetFilePos(0);
2128 const size_t byte_size = bytes.GetStringRef().size() / 2;
2129 WritableDataBufferSP data_buffer_sp(
2130 new DataBufferHeap(byte_size, 0));
2131 const size_t bytes_copied =
2132 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2133 if (bytes_copied == byte_size)
2134 m_memory_cache.AddL1CacheData(mem_cache_addr,
2144 }
else if (key == g_key_signal)
2149 return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2150 reason, description, exc_type, exc_data,
2151 thread_dispatch_qaddr, queue_vars_valid,
2152 associated_with_dispatch_queue, dispatch_queue_t,
2153 queue_name, queue_kind, queue_serial_number);
2159 const char stop_type = stop_packet.
GetChar();
2160 switch (stop_type) {
2179 const uint8_t signo = stop_packet.
GetHexU8();
2180 llvm::StringRef key;
2181 llvm::StringRef value;
2182 std::string thread_name;
2184 std::string description;
2185 uint32_t exc_type = 0;
2186 std::vector<addr_t> exc_data;
2188 bool queue_vars_valid =
2192 std::string queue_name;
2194 uint64_t queue_serial_number = 0;
2198 if (key.compare(
"metype") == 0) {
2200 value.getAsInteger(16, exc_type);
2201 }
else if (key.compare(
"medata") == 0) {
2204 value.getAsInteger(16, x);
2205 exc_data.push_back(x);
2206 }
else if (key.compare(
"thread") == 0) {
2209 auto pid_tid = thread_id.
GetPidTid(pid);
2211 stop_pid = pid_tid->first;
2212 tid = pid_tid->second;
2215 }
else if (key.compare(
"threads") == 0) {
2216 std::lock_guard<std::recursive_mutex> guard(
2219 }
else if (key.compare(
"thread-pcs") == 0) {
2224 while (!value.empty()) {
2225 llvm::StringRef pc_str;
2226 std::tie(pc_str, value) = value.split(
',');
2227 if (pc_str.getAsInteger(16,
pc))
2231 }
else if (key.compare(
"jstopinfo") == 0) {
2240 }
else if (key.compare(
"hexname") == 0) {
2245 }
else if (key.compare(
"name") == 0) {
2246 thread_name = std::string(value);
2247 }
else if (key.compare(
"qaddr") == 0) {
2248 value.getAsInteger(16, thread_dispatch_qaddr);
2249 }
else if (key.compare(
"dispatch_queue_t") == 0) {
2250 queue_vars_valid =
true;
2251 value.getAsInteger(16, dispatch_queue_t);
2252 }
else if (key.compare(
"qname") == 0) {
2253 queue_vars_valid =
true;
2257 }
else if (key.compare(
"qkind") == 0) {
2258 queue_kind = llvm::StringSwitch<QueueKind>(value)
2263 }
else if (key.compare(
"qserialnum") == 0) {
2264 if (!value.getAsInteger(0, queue_serial_number))
2265 queue_vars_valid =
true;
2266 }
else if (key.compare(
"reason") == 0) {
2267 reason = std::string(value);
2268 }
else if (key.compare(
"description") == 0) {
2272 }
else if (key.compare(
"memory") == 0) {
2286 llvm::StringRef addr_str, bytes_str;
2287 std::tie(addr_str, bytes_str) = value.split(
'=');
2288 if (!addr_str.empty() && !bytes_str.empty()) {
2290 if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2295 const size_t bytes_copied =
2297 if (bytes_copied == byte_size)
2301 }
else if (key.compare(
"watch") == 0 || key.compare(
"rwatch") == 0 ||
2302 key.compare(
"awatch") == 0) {
2305 value.getAsInteger(16, wp_addr);
2313 reason =
"watchpoint";
2315 ostr.
Printf(
"%" PRIu64, wp_addr);
2316 description = std::string(ostr.
GetString());
2317 }
else if (key.compare(
"library") == 0) {
2323 }
else if (key.compare(
"fork") == 0 || key.compare(
"vfork") == 0) {
2329 LLDB_LOG(log,
"Invalid PID/TID to fork: {0}", value);
2335 ostr.
Printf(
"%" PRIu64
" %" PRIu64, pid_tid->first, pid_tid->second);
2336 description = std::string(ostr.
GetString());
2337 }
else if (key.compare(
"addressing_bits") == 0) {
2338 uint64_t addressing_bits;
2339 if (!value.getAsInteger(0, addressing_bits)) {
2342 }
else if (key.compare(
"low_mem_addressing_bits") == 0) {
2343 uint64_t addressing_bits;
2344 if (!value.getAsInteger(0, addressing_bits)) {
2347 }
else if (key.compare(
"high_mem_addressing_bits") == 0) {
2348 uint64_t addressing_bits;
2349 if (!value.getAsInteger(0, addressing_bits)) {
2352 }
else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2354 if (!key.getAsInteger(16, reg))
2355 expedited_register_map[reg] = std::string(std::move(value));
2362 "Received stop for incorrect PID = {0} (inferior PID = {1})",
2382 tid, expedited_register_map, signo, thread_name, reason, description,
2383 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2384 associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2385 queue_kind, queue_serial_number);
2452 LLDB_LOGF(log,
"ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2456 if (
error.Success())
2458 "ProcessGDBRemote::DoDetach() detach packet sent successfully");
2461 "ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2462 error.AsCString() ?
error.AsCString() :
"<unknown error>");
2465 if (!
error.Success())
2480 LLDB_LOGF(log,
"ProcessGDBRemote::DoDestroy()");
2483 int exit_status = SIGABRT;
2484 std::string exit_string;
2491 exit_status = kill_res.get();
2492#if defined(__APPLE__)
2504 if (platform_sp && platform_sp->IsHost()) {
2507 reap_pid = waitpid(
GetID(), &status, WNOHANG);
2508 LLDB_LOGF(log,
"Reaped pid: %d, status: %d.\n", reap_pid, status);
2512 exit_string.assign(
"killed");
2514 exit_string.assign(llvm::toString(kill_res.takeError()));
2517 exit_string.assign(
"killed or interrupted while attaching.");
2523 exit_string.assign(
"destroying when not connected to debugserver");
2535 const bool did_exec =
2536 response.
GetStringRef().find(
";reason:exec;") != std::string::npos;
2539 LLDB_LOGF(log,
"ProcessGDBRemote::SetLastStopPacket () - detected exec");
2569 LLDB_LOG_ERROR(log, list.takeError(),
"Failed to read module list: {0}.");
2571 addr = list->m_link_map;
2591 const size_t n = thread_infos->
GetSize();
2592 for (
size_t i = 0; i < n; ++i) {
2608 size_t max_memory_size =
2610 if (size > max_memory_size) {
2614 size = max_memory_size;
2619 packet_len = ::snprintf(packet,
sizeof(packet),
"%c%" PRIx64
",%" PRIx64,
2620 binary_memory_read ?
'x' :
'm', (uint64_t)addr,
2622 assert(packet_len + 1 < (
int)
sizeof(packet));
2630 if (binary_memory_read) {
2636 if (data_received_size > size) {
2639 data_received_size = size;
2641 memcpy(buf, response.
GetStringRef().data(), data_received_size);
2642 return data_received_size;
2645 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size),
'\xdd');
2648 error.SetErrorStringWithFormat(
"memory read failed for 0x%" PRIx64, addr);
2650 error.SetErrorStringWithFormat(
2651 "GDB server does not support reading memory");
2653 error.SetErrorStringWithFormat(
2654 "unexpected response to GDB server memory read packet '%s': '%s'",
2657 error.SetErrorStringWithFormat(
"failed to send packet: '%s'", packet);
2666llvm::Expected<std::vector<uint8_t>>
2673 return llvm::createStringError(llvm::inconvertibleErrorCode(),
2674 "Error reading memory tags from remote");
2678 llvm::ArrayRef<uint8_t> tag_data = buffer_sp->GetData();
2679 std::vector<uint8_t> got;
2680 got.reserve(tag_data.size());
2681 std::copy(tag_data.begin(), tag_data.end(), std::back_inserter(got));
2687 const std::vector<uint8_t> &tags) {
2694 std::vector<ObjectFile::LoadableData> entries) {
2699 std::begin(entries), std::end(entries),
2705 if (
error.Success())
2719 for (
size_t i = 0; i < size; ++i)
2738 status.
SetErrorString(
"Unable to erase flash in multiple regions");
2743 if (blocksize == 0) {
2744 status.
SetErrorString(
"Unable to erase flash because blocksize is 0");
2750 lldb::addr_t block_start_addr = addr - (addr % blocksize);
2751 size += (addr - block_start_addr);
2752 if ((size % blocksize) != 0)
2753 size += (blocksize - size % blocksize);
2795 "unexpected response to GDB server flash erase packet '%s': '%s'",
2824 "unexpected response to GDB server flash done packet: '%s'",
2838 if (size > max_memory_size) {
2842 size = max_memory_size;
2855 error.SetErrorString(
"Writing to flash memory is not allowed");
2863 if (!
error.Success())
2865 packet.
Printf(
"vFlashWrite:%" PRIx64
":", addr);
2868 packet.
Printf(
"M%" PRIx64
",%" PRIx64
":", addr, (uint64_t)size);
2880 error.SetErrorStringWithFormat(
"memory write failed for 0x%" PRIx64,
2883 error.SetErrorStringWithFormat(
2884 "GDB server does not support writing memory");
2886 error.SetErrorStringWithFormat(
2887 "unexpected response to GDB server memory write packet '%s': '%s'",
2890 error.SetErrorStringWithFormat(
"failed to send packet: '%s'",
2897 uint32_t permissions,
2906 return allocated_addr;
2912 if (permissions & lldb::ePermissionsReadable)
2914 if (permissions & lldb::ePermissionsWritable)
2916 if (permissions & lldb::ePermissionsExecutable)
2925 "ProcessGDBRemote::%s no direct stub support for memory "
2926 "allocation, and InferiorCallMmap also failed - is stub "
2927 "missing register context save/restore capability?",
2933 error.SetErrorStringWithFormat(
2934 "unable to allocate %" PRIu64
" bytes of memory with permissions %s",
2938 return allocated_addr;
2960 switch (supported) {
2964 error.SetErrorString(
2965 "tried to deallocate memory without ever allocating memory");
2970 error.SetErrorStringWithFormat(
2971 "unable to deallocate memory at 0x%" PRIx64, addr);
2982 error.SetErrorStringWithFormat(
2983 "unable to deallocate memory at 0x%" PRIx64, addr);
3005 assert(bp_site !=
nullptr);
3016 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3017 ") address = 0x%" PRIx64,
3018 site_id, (uint64_t)addr);
3023 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3024 ") address = 0x%" PRIx64
" -- SUCCESS (already enabled)",
3025 site_id, (uint64_t)addr);
3046 if (error_no == 0) {
3062 if (error_no != UINT8_MAX)
3063 error.SetErrorStringWithFormat(
3064 "error: %d sending the breakpoint request", error_no);
3066 error.SetErrorString(
"error sending the breakpoint request");
3073 LLDB_LOGF(log,
"Software breakpoints are unsupported");
3086 if (error_no == 0) {
3097 if (error_no != UINT8_MAX)
3098 error.SetErrorStringWithFormat(
3099 "error: %d sending the hardware breakpoint request "
3100 "(hardware breakpoint resources might be exhausted or unavailable)",
3103 error.SetErrorString(
"error sending the hardware breakpoint request "
3104 "(hardware breakpoint resources "
3105 "might be exhausted or unavailable)");
3111 LLDB_LOGF(log,
"Hardware breakpoints are unsupported");
3118 error.SetErrorString(
"hardware breakpoints are not supported");
3129 assert(bp_site !=
nullptr);
3134 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3135 ") addr = 0x%8.8" PRIx64,
3136 site_id, (uint64_t)addr);
3151 error.SetErrorToGenericError();
3158 error.SetErrorToGenericError();
3161 if (
error.Success())
3165 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3166 ") addr = 0x%8.8" PRIx64
" -- SUCCESS (already disabled)",
3167 site_id, (uint64_t)addr);
3171 if (
error.Success())
3172 error.SetErrorToGenericError();
3180 bool read = wp_res_sp->WatchpointResourceRead();
3181 bool write = wp_res_sp->WatchpointResourceWrite();
3183 assert((read || write) &&
3184 "WatchpointResource type is neither read nor write");
3196 error.SetErrorString(
"No watchpoint specified");
3200 addr_t addr = wp_sp->GetLoadAddress();
3202 LLDB_LOGF(log,
"ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
")",
3204 if (wp_sp->IsEnabled()) {
3206 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3207 ") addr = 0x%8.8" PRIx64
": watchpoint already enabled.",
3208 watchID, (uint64_t)addr);
3212 bool read = wp_sp->WatchpointRead();
3213 bool write = wp_sp->WatchpointWrite() || wp_sp->WatchpointModify();
3214 size_t size = wp_sp->GetByteSize();
3217 WatchpointHardwareFeature supported_features =
3220 std::vector<WatchpointResourceSP> resources =
3222 addr, size, read, write, supported_features, target_arch);
3247 bool set_all_resources =
true;
3248 std::vector<WatchpointResourceSP> succesfully_set_resources;
3249 for (
const auto &wp_res_sp : resources) {
3250 addr_t addr = wp_res_sp->GetLoadAddress();
3251 size_t size = wp_res_sp->GetByteSize();
3256 set_all_resources =
false;
3259 succesfully_set_resources.push_back(wp_res_sp);
3262 if (set_all_resources) {
3263 wp_sp->SetEnabled(
true, notify);
3264 for (
const auto &wp_res_sp : resources) {
3267 wp_res_sp->AddConstituent(wp_sp);
3275 for (
const auto &wp_res_sp : succesfully_set_resources) {
3276 addr_t addr = wp_res_sp->GetLoadAddress();
3277 size_t size = wp_res_sp->GetByteSize();
3282 error.SetErrorString(
"Setting one of the watchpoint resources failed");
3290 error.SetErrorString(
"Watchpoint argument was NULL.");
3298 addr_t addr = wp_sp->GetLoadAddress();
3301 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3302 ") addr = 0x%8.8" PRIx64,
3303 watchID, (uint64_t)addr);
3305 if (!wp_sp->IsEnabled()) {
3307 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3308 ") addr = 0x%8.8" PRIx64
" -- SUCCESS (already disabled)",
3309 watchID, (uint64_t)addr);
3313 wp_sp->SetEnabled(
false, notify);
3317 if (wp_sp->IsHardware()) {
3318 bool disabled_all =
true;
3320 std::vector<WatchpointResourceSP> unused_resources;
3322 if (wp_res_sp->ConstituentsContains(wp_sp)) {
3324 addr_t addr = wp_res_sp->GetLoadAddress();
3325 size_t size = wp_res_sp->GetByteSize();
3328 disabled_all =
false;
3330 wp_res_sp->RemoveConstituent(wp_sp);
3331 if (wp_res_sp->GetNumberOfConstituents() == 0)
3332 unused_resources.push_back(wp_res_sp);
3336 for (
auto &wp_res_sp : unused_resources)
3339 wp_sp->SetEnabled(
false, notify);
3341 error.SetErrorString(
"Failure disabling one of the watchpoint locations");
3354 LLDB_LOGF(log,
"ProcessGDBRemote::DoSignal (signal = %d)", signo);
3357 error.SetErrorStringWithFormat(
"failed to send signal %i", signo);
3368 if (platform_sp && !platform_sp->IsHost())
3369 return Status(
"Lost debug server connection");
3373 const char *error_string =
error.AsCString();
3374 if (error_string ==
nullptr)
3380#define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3383#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3385#if defined(FD_CLOEXEC)
3386 int flags = ::fcntl(fd, F_GETFD);
3389 return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3398 using namespace std::placeholders;
3403 static FileSpec g_debugserver_file_spec;
3410 const std::weak_ptr<ProcessGDBRemote> this_wp =
3411 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3416#if defined(__APPLE__)
3420 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID,
3422 struct kinfo_proc processInfo;
3423 size_t bufsize =
sizeof(processInfo);
3424 if (sysctl(mib, (
unsigned)(
sizeof(mib)/
sizeof(
int)), &processInfo,
3425 &bufsize, NULL, 0) == 0 && bufsize > 0) {
3426 if (processInfo.kp_proc.p_flag & P_TRANSLATED) {
3427 FileSpec rosetta_debugserver(
"/Library/Apple/usr/libexec/oah/debugserver");
3433 int communication_fd = -1;
3434#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3438 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
3439 error.SetErrorToErrno();
3443 int our_socket = sockets[0];
3444 int gdb_socket = sockets[1];
3445 auto cleanup_our = llvm::make_scope_exit([&]() { close(our_socket); });
3446 auto cleanup_gdb = llvm::make_scope_exit([&]() { close(gdb_socket); });
3450 communication_fd = gdb_socket;
3454 nullptr,
GetTarget().GetPlatform().get(), debugserver_launch_info,
3455 nullptr,
nullptr, communication_fd);
3457 if (
error.Success())
3463#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3466 cleanup_our.release();
3468 std::make_unique<ConnectionFileDescriptor>(our_socket,
true));
3476 LLDB_LOGF(log,
"failed to start debugserver process: %s",
3486 error.SetErrorString(
"connection failed");
3493 std::weak_ptr<ProcessGDBRemote> process_wp,
lldb::pid_t debugserver_pid,
3502 "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3503 ", signo=%i (0x%x), exit_status=%i)",
3504 __FUNCTION__, debugserver_pid, signo, signo, exit_status);
3506 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3507 LLDB_LOGF(log,
"ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3508 static_cast<void *
>(process_sp.get()));
3509 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3515 std::this_thread::sleep_for(std::chrono::milliseconds(500));
3519 const StateType state = process_sp->GetState();
3528 llvm::StringRef signal_name =
3529 process_sp->GetUnixSignals()->GetSignalAsStringRef(signo);
3531 if (!signal_name.empty())
3532 stream.
Format(format_str, signal_name);
3534 stream.
Format(format_str, signo);
3536 process_sp->SetExitStatus(-1, stream.
GetString());
3552 static llvm::once_flag g_once_flag;
3554 llvm::call_once(g_once_flag, []() {
3563 debugger, PluginProperties::GetSettingName())) {
3564 const bool is_global_setting =
true;
3567 "Properties for the gdb-remote process plug-in.", is_global_setting);
3574 LLDB_LOGF(log,
"ProcessGDBRemote::%s ()", __FUNCTION__);
3581 llvm::Expected<HostThread> async_thread =
3585 if (!async_thread) {
3587 "failed to launch host thread: {0}");
3593 "ProcessGDBRemote::%s () - Called when Async thread was "
3603 LLDB_LOGF(log,
"ProcessGDBRemote::%s ()", __FUNCTION__);
3618 "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3624 LLDB_LOGF(log,
"ProcessGDBRemote::%s(pid = %" PRIu64
") thread starting...",
3625 __FUNCTION__,
GetID());
3643 "ProcessGDBRemote::%s(pid = %" PRIu64
3644 ") listener.WaitForEvent (NULL, event_sp)...",
3645 __FUNCTION__,
GetID());
3648 const uint32_t event_type = event_sp->GetType();
3651 "ProcessGDBRemote::%s(pid = %" PRIu64
3652 ") Got an event of type: %d...",
3653 __FUNCTION__,
GetID(), event_type);
3655 switch (event_type) {
3660 if (continue_packet) {
3661 const char *continue_cstr =
3662 (
const char *)continue_packet->
GetBytes();
3663 const size_t continue_cstr_len = continue_packet->
GetByteSize();
3665 "ProcessGDBRemote::%s(pid = %" PRIu64
3666 ") got eBroadcastBitAsyncContinue: %s",
3667 __FUNCTION__,
GetID(), continue_cstr);
3669 if (::strstr(continue_cstr,
"vAttach") ==
nullptr)
3676 llvm::StringRef(continue_cstr, continue_cstr_len),
3687 switch (stop_state) {
3700 int exit_status = response.
GetHexU8();
3701 std::string desc_string;
3703 llvm::StringRef desc_str;
3704 llvm::StringRef desc_token;
3706 if (desc_token !=
"description")
3721 if (::strstr(continue_cstr,
"vAttach") !=
nullptr &&
3724 "System Integrity Protection");
3725 }
else if (::strstr(continue_cstr,
"vAttach") !=
nullptr &&
3745 "ProcessGDBRemote::%s(pid = %" PRIu64
3746 ") got eBroadcastBitAsyncThreadShouldExit...",
3747 __FUNCTION__,
GetID());
3753 "ProcessGDBRemote::%s(pid = %" PRIu64
3754 ") got unknown event 0x%8.8x",
3755 __FUNCTION__,
GetID(), event_type);
3762 "ProcessGDBRemote::%s(pid = %" PRIu64
3763 ") listener.WaitForEvent (NULL, event_sp) => false",
3764 __FUNCTION__,
GetID());
3769 LLDB_LOGF(log,
"ProcessGDBRemote::%s(pid = %" PRIu64
") thread exiting...",
3770 __FUNCTION__,
GetID());
3802 LLDB_LOGF(log,
"Hit New Thread Notification breakpoint.");
3808 LLDB_LOG(log,
"Check if need to update ignored signals");
3822 LLDB_LOG(log,
"Signals' version hasn't changed. version={0}",
3827 auto signals_to_ignore =
3832 "Signals' version changed. old version={0}, new version={1}, "
3833 "signals ignored={2}, update result={3}",
3835 signals_to_ignore.size(),
error);
3837 if (
error.Success())
3847 LLDB_LOGF(log,
"Enabled noticing new thread breakpoint.");
3853 platform_sp->SetThreadCreationBreakpoint(
GetTarget());
3857 log,
"Successfully created new thread notification breakpoint %i",
3862 LLDB_LOGF(log,
"Failed to create new thread notification breakpoint.");
3872 LLDB_LOGF(log,
"Disabling new thread notification breakpoint.");
3893 if (return_value != 0) {
3895 error.SetErrorString(
"Sending events is not supported for this process.");
3897 error.SetErrorStringWithFormat(
"Error sending event data: %d.",
3908 buf = std::make_shared<DataBufferHeap>(response->c_str(),
3909 response->length());
3926 args_dict->GetAsDictionary()->AddIntegerItem(
"thread", tid);
3929 packet <<
"jThreadExtendedInfo:";
3930 args_dict->Dump(packet,
false);
3937 packet << (char)(0x7d ^ 0x20);
3946 if (!response.
Empty()) {
3959 args_dict->GetAsDictionary()->AddIntegerItem(
"image_list_address",
3960 image_list_address);
3961 args_dict->GetAsDictionary()->AddIntegerItem(
"image_count", image_count);
3969 args_dict->GetAsDictionary()->AddBooleanItem(
"fetch_all_solibs",
true);
3975 const std::vector<lldb::addr_t> &load_addresses) {
3979 for (
auto addr : load_addresses)
3980 addresses->AddIntegerItem(addr);
3982 args_dict->GetAsDictionary()->AddItem(
"solib_addresses", addresses);
3995 std::chrono::seconds(10));
3998 packet <<
"jGetLoadedDynamicLibrariesInfos:";
3999 args_dict->Dump(packet,
false);
4006 packet << (char)(0x7d ^ 0x20);
4015 if (!response.
Empty()) {
4037 if (!response.
Empty()) {
4052 packet <<
"jGetSharedCacheInfo:";
4053 args_dict->Dump(packet,
false);
4060 packet << (char)(0x7d ^ 0x20);
4069 if (!response.
Empty()) {
4093 const uint64_t reasonable_largeish_default = 128 * 1024;
4094 const uint64_t conservative_default = 512;
4098 if (stub_max_size !=
UINT64_MAX && stub_max_size != 0) {
4104 if (stub_max_size > reasonable_largeish_default) {
4105 stub_max_size = reasonable_largeish_default;
4111 if (stub_max_size > 70)
4112 stub_max_size -= 32 + 32 + 6;
4118 log->
Warning(
"Packet size is too small. "
4119 "LLDB may face problems while writing memory");
4130 uint64_t user_specified_max) {
4131 if (user_specified_max != 0) {
4159 module_spec = cached->second;
4160 return bool(module_spec);
4164 LLDB_LOGF(log,
"ProcessGDBRemote::%s - failed to get module info for %s:%s",
4165 __FUNCTION__, module_file_spec.
GetPath().c_str(),
4172 module_spec.
Dump(stream);
4173 LLDB_LOGF(log,
"ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4174 __FUNCTION__, module_file_spec.
GetPath().c_str(),
4183 llvm::ArrayRef<FileSpec> module_file_specs,
const llvm::Triple &triple) {
4186 for (
const FileSpec &spec : module_file_specs)
4191 triple.getTriple())] = spec;
4205typedef std::vector<std::string> stringVec;
4207typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
4208struct RegisterSetInfo {
4212typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4214struct GdbServerTargetInfo {
4218 RegisterSetMap reg_set_map;
4235 std::map<uint64_t, FieldEnum::Enumerator> enumerators;
4238 "evalue", [&enumerators, &log](
const XMLNode &enumerator_node) {
4239 std::optional<llvm::StringRef> name;
4240 std::optional<uint64_t> value;
4243 [&name, &value, &log](
const llvm::StringRef &attr_name,
4244 const llvm::StringRef &attr_value) {
4245 if (attr_name ==
"name") {
4246 if (attr_value.size())
4249 LLDB_LOG(log,
"ProcessGDBRemote::ParseEnumEvalues "
4250 "Ignoring empty name in evalue");
4251 }
else if (attr_name ==
"value") {
4252 uint64_t parsed_value = 0;
4253 if (llvm::to_integer(attr_value, parsed_value))
4254 value = parsed_value;
4257 "ProcessGDBRemote::ParseEnumEvalues "
4258 "Invalid value \"{0}\" in "
4263 "ProcessGDBRemote::ParseEnumEvalues Ignoring "
4264 "unknown attribute "
4265 "\"{0}\" in evalue",
4273 enumerators.insert_or_assign(
4281 for (
auto [_, enumerator] : enumerators)
4282 final_enumerators.push_back(enumerator);
4284 return final_enumerators;
4288ParseEnums(
XMLNode feature_node,
4289 llvm::StringMap<std::unique_ptr<FieldEnum>> ®isters_enum_types) {
4294 "enum", [log, ®isters_enum_types](
const XMLNode &enum_node) {
4298 const llvm::StringRef &attr_value) {
4299 if (attr_name ==
"id")
4317 if (!enumerators.empty()) {
4319 "ProcessGDBRemote::ParseEnums Found enum type \"{0}\"",
4321 registers_enum_types.insert_or_assign(
4322 id, std::make_unique<FieldEnum>(
id, enumerators));
4331static std::vector<RegisterFlags::Field> ParseFlagsFields(
4332 XMLNode flags_node,
unsigned size,
4333 const llvm::StringMap<std::unique_ptr<FieldEnum>> ®isters_enum_types) {
4335 const unsigned max_start_bit = size * 8 - 1;
4338 std::vector<RegisterFlags::Field> fields;
4340 ®isters_enum_types](
4343 std::optional<llvm::StringRef> name;
4344 std::optional<unsigned> start;
4345 std::optional<unsigned> end;
4346 std::optional<llvm::StringRef> type;
4349 &log](
const llvm::StringRef &attr_name,
4350 const llvm::StringRef &attr_value) {
4353 if (attr_name ==
"name") {
4356 "ProcessGDBRemote::ParseFlagsFields Found field node name \"{0}\"",
4359 }
else if (attr_name ==
"start") {
4360 unsigned parsed_start = 0;
4361 if (llvm::to_integer(attr_value, parsed_start)) {
4362 if (parsed_start > max_start_bit) {
4364 "ProcessGDBRemote::ParseFlagsFields Invalid start {0} in "
4367 parsed_start, max_start_bit);
4369 start = parsed_start;
4373 "ProcessGDBRemote::ParseFlagsFields Invalid start \"{0}\" in "
4377 }
else if (attr_name ==
"end") {
4378 unsigned parsed_end = 0;
4379 if (llvm::to_integer(attr_value, parsed_end))
4380 if (parsed_end > max_start_bit) {
4382 "ProcessGDBRemote::ParseFlagsFields Invalid end {0} in "
4385 parsed_end, max_start_bit);
4390 "ProcessGDBRemote::ParseFlagsFields Invalid end \"{0}\" in "
4394 }
else if (attr_name ==
"type") {
4399 "ProcessGDBRemote::ParseFlagsFields Ignoring unknown attribute "
4400 "\"{0}\" in field node",
4407 if (name && start && end) {
4411 "ProcessGDBRemote::ParseFlagsFields Start {0} > end {1} in field "
4412 "\"{2}\", ignoring",
4413 *start, *end, name->data());
4417 "ProcessGDBRemote::ParseFlagsFields Ignoring field \"{2}\" "
4419 "size > 64 bits, this is not supported",
4424 if (type && !type->empty()) {
4425 auto found = registers_enum_types.find(*type);
4426 if (found != registers_enum_types.end()) {
4427 enum_type = found->second.get();
4430 uint64_t max_value =
4433 if (enumerator.m_value > max_value) {
4434 enum_type =
nullptr;
4437 "ProcessGDBRemote::ParseFlagsFields In enum \"{0}\" "
4438 "evalue \"{1}\" with value {2} exceeds the maximum value "
4439 "of field \"{3}\" ({4}), ignoring enum",
4440 type->data(), enumerator.m_name, enumerator.m_value,
4441 name->data(), max_value);
4447 "ProcessGDBRemote::ParseFlagsFields Could not find type "
4449 "for field \"{1}\", ignoring",
4450 type->data(), name->data());
4467 llvm::StringMap<std::unique_ptr<RegisterFlags>> ®isters_flags_types,
4468 const llvm::StringMap<std::unique_ptr<FieldEnum>> ®isters_enum_types) {
4473 [&log, ®isters_flags_types,
4474 ®isters_enum_types](
const XMLNode &flags_node) ->
bool {
4475 LLDB_LOG(log,
"ProcessGDBRemote::ParseFlags Found flags node \"{0}\"",
4478 std::optional<llvm::StringRef>
id;
4479 std::optional<unsigned> size;
4481 [&
id, &size, &log](
const llvm::StringRef &name,
4482 const llvm::StringRef &value) {
4485 }
else if (name ==
"size") {
4486 unsigned parsed_size = 0;
4487 if (llvm::to_integer(value, parsed_size))
4491 "ProcessGDBRemote::ParseFlags Invalid size \"{0}\" "
4497 "ProcessGDBRemote::ParseFlags Ignoring unknown "
4498 "attribute \"{0}\" in flags node",
4506 std::vector<RegisterFlags::Field> fields =
4507 ParseFlagsFields(flags_node, *size, registers_enum_types);
4508 if (fields.size()) {
4510 std::sort(fields.rbegin(), fields.rend());
4511 std::vector<RegisterFlags::Field>::const_iterator overlap =
4512 std::adjacent_find(fields.begin(), fields.end(),
4515 return lhs.Overlaps(rhs);
4519 if (overlap == fields.end()) {
4520 if (registers_flags_types.contains(*
id)) {
4534 "ProcessGDBRemote::ParseFlags Definition of flags "
4536 "previous definition, using original definition instead.",
4539 registers_flags_types.insert_or_assign(
4540 *
id, std::make_unique<RegisterFlags>(
id->str(), *size,
4541 std::move(fields)));
4545 std::vector<RegisterFlags::Field>::const_iterator next =
4549 "ProcessGDBRemote::ParseFlags Ignoring flags because fields "
4550 "{0} (start: {1} end: {2}) and {3} (start: {4} end: {5}) "
4552 overlap->GetName().c_str(), overlap->GetStart(),
4553 overlap->GetEnd(), next->GetName().c_str(), next->GetStart(),
4559 "ProcessGDBRemote::ParseFlags Ignoring definition of flags "
4560 "\"{0}\" because it contains no fields.",
4570 XMLNode feature_node, GdbServerTargetInfo &target_info,
4571 std::vector<DynamicRegisterInfo::Register> ®isters,
4572 llvm::StringMap<std::unique_ptr<RegisterFlags>> ®isters_flags_types,
4573 llvm::StringMap<std::unique_ptr<FieldEnum>> ®isters_enum_types) {
4580 ParseEnums(feature_node, registers_enum_types);
4581 for (
const auto &enum_type : registers_enum_types)
4584 ParseFlags(feature_node, registers_flags_types, registers_enum_types);
4585 for (
const auto &flags : registers_flags_types)
4586 flags.second->DumpToLog(log);
4590 [&target_info, ®isters, ®isters_flags_types,
4591 log](
const XMLNode ®_node) ->
bool {
4592 std::string gdb_group;
4593 std::string gdb_type;
4595 bool encoding_set =
false;
4596 bool format_set =
false;
4600 &encoding_set, &format_set, ®_info,
4601 log](
const llvm::StringRef &name,
4602 const llvm::StringRef &value) ->
bool {
4603 if (name ==
"name") {
4605 }
else if (name ==
"bitsize") {
4606 if (llvm::to_integer(value, reg_info.
byte_size))
4608 llvm::divideCeil(reg_info.
byte_size, CHAR_BIT);
4609 }
else if (name ==
"type") {
4610 gdb_type = value.str();
4611 }
else if (name ==
"group") {
4612 gdb_group = value.str();
4613 }
else if (name ==
"regnum") {
4615 }
else if (name ==
"offset") {
4617 }
else if (name ==
"altname") {
4619 }
else if (name ==
"encoding") {
4620 encoding_set =
true;
4622 }
else if (name ==
"format") {
4628 llvm::StringSwitch<lldb::Format>(value)
4639 }
else if (name ==
"group_id") {
4641 llvm::to_integer(value, set_id);
4642 RegisterSetMap::const_iterator pos =
4643 target_info.reg_set_map.find(set_id);
4644 if (pos != target_info.reg_set_map.end())
4645 reg_info.
set_name = pos->second.name;
4646 }
else if (name ==
"gcc_regnum" || name ==
"ehframe_regnum") {
4648 }
else if (name ==
"dwarf_regnum") {
4650 }
else if (name ==
"generic") {
4652 }
else if (name ==
"value_regnums") {
4655 }
else if (name ==
"invalidate_regnums") {
4660 "ProcessGDBRemote::ParseRegisters unhandled reg "
4661 "attribute %s = %s",
4662 name.data(), value.data());
4667 if (!gdb_type.empty()) {
4669 llvm::StringMap<std::unique_ptr<RegisterFlags>>::iterator it =
4670 registers_flags_types.find(gdb_type);
4671 if (it != registers_flags_types.end()) {
4672 auto flags_type = it->second.get();
4673 if (reg_info.
byte_size == flags_type->GetSize())
4677 "ProcessGDBRemote::ParseRegisters Size of register "
4678 "flags %s (%d bytes) for "
4679 "register %s does not match the register size (%d "
4680 "bytes). Ignoring this set of flags.",
4681 flags_type->GetID().c_str(), flags_type->GetSize(),
4688 if (!gdb_type.empty() && !(encoding_set || format_set)) {
4689 if (llvm::StringRef(gdb_type).starts_with(
"int")) {
4692 }
else if (gdb_type ==
"data_ptr" || gdb_type ==
"code_ptr") {
4695 }
else if (gdb_type ==
"float") {
4698 }
else if (gdb_type ==
"aarch64v" ||
4699 llvm::StringRef(gdb_type).starts_with(
"vec") ||
4700 gdb_type ==
"i387_ext" || gdb_type ==
"uint128") {
4708 "ProcessGDBRemote::ParseRegisters Could not determine lldb"
4709 "format and encoding for gdb type %s",
4719 if (!gdb_group.empty()) {
4730 "ProcessGDBRemote::%s Skipping zero bitsize register %s",
4733 registers.push_back(reg_info);
4748 ArchSpec &arch_to_use, std::string xml_filename,
4749 std::vector<DynamicRegisterInfo::Register> ®isters) {
4752 if (errorToBool(raw.takeError()))
4757 if (xml_document.
ParseMemory(raw->c_str(), raw->size(),
4758 xml_filename.c_str())) {
4759 GdbServerTargetInfo target_info;
4760 std::vector<XMLNode> feature_nodes;
4766 const XMLNode &node) ->
bool {
4767 llvm::StringRef name = node.
GetName();
4768 if (name ==
"architecture") {
4770 }
else if (name ==
"osabi") {
4772 }
else if (name ==
"xi:include" || name ==
"include") {
4775 target_info.includes.push_back(href);
4776 }
else if (name ==
"feature") {
4777 feature_nodes.push_back(node);
4778 }
else if (name ==
"groups") {
4780 "group", [&target_info](
const XMLNode &node) ->
bool {
4782 RegisterSetInfo set_info;
4785 [&set_id, &set_info](
const llvm::StringRef &name,
4786 const llvm::StringRef &value) ->
bool {
4789 llvm::to_integer(value, set_id);
4796 target_info.reg_set_map[set_id] = set_info;
4809 feature_nodes.push_back(feature_node);
4811 const XMLNode &node) ->
bool {
4812 llvm::StringRef name = node.
GetName();
4813 if (name ==
"xi:include" || name ==
"include") {
4816 target_info.includes.push_back(href);
4830 if (!arch_to_use.
IsValid() && !target_info.arch.empty()) {
4832 arch_to_use.
SetTriple(llvm::StringSwitch<std::string>(target_info.arch)
4833 .Case(
"i386:x86-64",
"x86_64")
4834 .Case(
"riscv:rv64",
"riscv64")
4835 .Case(
"riscv:rv32",
"riscv32")
4836 .Default(target_info.arch) +
4844 for (
auto &feature_node : feature_nodes) {
4845 ParseRegisters(feature_node, target_info, registers,
4849 for (
const auto &include : target_info.includes) {
4861 std::vector<DynamicRegisterInfo::Register> ®isters,
4863 std::map<uint32_t, uint32_t> remote_to_local_map;
4864 uint32_t remote_regnum = 0;
4865 for (
auto it : llvm::enumerate(registers)) {
4873 remote_to_local_map[remote_reg_info.
regnum_remote] = it.index();
4879 auto proc_to_lldb = [&remote_to_local_map](uint32_t process_regnum) {
4880 auto lldb_regit = remote_to_local_map.find(process_regnum);
4881 return lldb_regit != remote_to_local_map.end() ? lldb_regit->second
4885 llvm::transform(remote_reg_info.value_regs,
4886 remote_reg_info.value_regs.begin(), proc_to_lldb);
4887 llvm::transform(remote_reg_info.invalidate_regs,
4888 remote_reg_info.invalidate_regs.begin(), proc_to_lldb);
4895 abi_sp->AugmentRegisterInfo(registers);
4919 std::vector<DynamicRegisterInfo::Register> registers;