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) {
569 "Process %" PRIu64
" was reported after connecting to "
570 "'%s', but state was not stopped: %s",
574 "Process %" PRIu64
" 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));
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));
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) {
1373 "Trying to resume but the async thread is dead.");
1374 LLDB_LOGF(log,
"ProcessGDBRemote::DoResume: Trying to resume but the "
1375 "async thread is dead.");
1380 std::make_shared<EventDataBytes>(continue_packet.
GetString());
1383 if (!listener_sp->GetEvent(event_sp, std::chrono::seconds(5))) {
1385 LLDB_LOGF(log,
"ProcessGDBRemote::DoResume: Resume timed out.");
1388 "Broadcast continue, but the async thread was "
1389 "killed before we got an ack back.");
1391 "ProcessGDBRemote::DoResume: Broadcast continue, but the "
1392 "async thread was killed before we got an ack back.");
1408 llvm::StringRef value) {
1414 auto pid_tid = thread_ids.
GetPidTid(pid);
1415 if (pid_tid && pid_tid->first == pid) {
1421 }
while (thread_ids.GetChar() ==
',');
1427 llvm::StringRef value) {
1429 for (llvm::StringRef x : llvm::split(value,
',')) {
1431 if (llvm::to_integer(x,
pc, 16))
1443 if (thread_infos && thread_infos->
GetSize() > 0) {
1467 const std::string &stop_info_str = std::string(stop_info.
GetStringRef());
1470 const size_t thread_pcs_pos = stop_info_str.find(
";thread-pcs:");
1471 if (thread_pcs_pos != std::string::npos) {
1472 const size_t start = thread_pcs_pos + strlen(
";thread-pcs:");
1473 const size_t end = stop_info_str.find(
';', start);
1474 if (end != std::string::npos) {
1475 std::string value = stop_info_str.substr(start, end - start);
1480 const size_t threads_pos = stop_info_str.find(
";threads:");
1481 if (threads_pos != std::string::npos) {
1482 const size_t start = threads_pos + strlen(
";threads:");
1483 const size_t end = stop_info_str.find(
';', start);
1484 if (end != std::string::npos) {
1485 std::string value = stop_info_str.substr(start, end - start);
1493 bool sequence_mutex_unavailable =
false;
1495 if (sequence_mutex_unavailable) {
1510 if (num_thread_ids == 0) {
1516 ThreadList old_thread_list_copy(old_thread_list);
1517 if (num_thread_ids > 0) {
1518 for (
size_t i = 0; i < num_thread_ids; ++i) {
1523 thread_sp = std::make_shared<ThreadGDBRemote>(*
this, tid);
1524 LLDB_LOGV(log,
"Making new thread: {0} for thread ID: {1:x}.",
1525 thread_sp.get(), thread_sp->GetID());
1527 LLDB_LOGV(log,
"Found old thread: {0} for thread ID: {1:x}.",
1528 thread_sp.get(), thread_sp->GetID());
1538 size_t old_num_thread_ids = old_thread_list_copy.
GetSize(
false);
1539 for (
size_t i = 0; i < old_num_thread_ids; i++) {
1541 if (old_thread_sp) {
1542 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1557 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1570 if (thread_infos_sp) {
1574 const size_t n = thread_infos->
GetSize();
1575 for (
size_t i = 0; i < n; ++i) {
1581 if (tid == thread->
GetID())
1609 for (
size_t i = 0; i < num_thread_ids; i++) {
1613 thread->
GetProcess()->GetBreakpointSiteList().FindByAddress(
pc);
1615 if (bp_site_sp->ValidForThisThread(*thread)) {
1618 *thread, bp_site_sp->
GetID()));
1641 for (
const auto &pair : expedited_register_map) {
1645 reg_value_extractor.
GetHexBytes(buffer_sp->GetData(),
'\xcc');
1646 uint32_t lldb_regnum = gdb_reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1654 uint8_t signo,
const std::string &thread_name,
const std::string &reason,
1655 const std::string &description, uint32_t exc_type,
1656 const std::vector<addr_t> &exc_data,
addr_t thread_dispatch_qaddr,
1657 bool queue_vars_valid,
1659 LazyBool associated_with_dispatch_queue,
addr_t dispatch_queue_t,
1660 std::string &queue_name,
QueueKind queue_kind, uint64_t queue_serial) {
1676 thread_sp = std::make_shared<ThreadGDBRemote>(*
this, tid);
1684 reg_ctx_sp->InvalidateIfNeeded(
true);
1692 if (reg_ctx_sp->ReconfigureRegisterInfo()) {
1695 reg_ctx_sp->InvalidateAllRegisters();
1702 thread_sp->SetName(thread_name.empty() ?
nullptr : thread_name.c_str());
1707 if (queue_vars_valid)
1708 gdb_thread->
SetQueueInfo(std::move(queue_name), queue_kind, queue_serial,
1709 dispatch_queue_t, associated_with_dispatch_queue);
1720 StopInfoSP current_stop_info_sp = thread_sp->GetPrivateStopInfo(
false);
1722 current_stop_info_sp) {
1723 thread_sp->SetStopInfo(current_stop_info_sp);
1727 if (!thread_sp->StopInfoIsUpToDate()) {
1732 thread_sp = memory_thread_sp;
1734 if (exc_type != 0) {
1742 if (interrupt_thread)
1743 thread_sp = interrupt_thread;
1745 const size_t exc_data_size = exc_data.size();
1746 thread_sp->SetStopInfo(
1748 *thread_sp, exc_type, exc_data_size,
1749 exc_data_size >= 1 ? exc_data[0] : 0,
1750 exc_data_size >= 2 ? exc_data[1] : 0,
1751 exc_data_size >= 3 ? exc_data[2] : 0));
1754 bool handled =
false;
1755 bool did_exec =
false;
1758 if (!reason.empty() && reason !=
"none") {
1759 if (reason ==
"trace") {
1760 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1762 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1767 if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
1768 thread_sp->SetStopInfo(
1770 *thread_sp, bp_site_sp->GetID()));
1772 thread_sp->SetStopInfo(
1775 }
else if (reason ==
"breakpoint") {
1776 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1778 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1787 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
1788 thread_sp->SetStopInfo(
1790 *thread_sp, bp_site_sp->GetID()));
1793 thread_sp->SetStopInfo(invalid_stop_info_sp);
1796 }
else if (reason ==
"trap") {
1798 }
else if (reason ==
"watchpoint") {
1834 bool silently_continue =
false;
1844 silently_continue =
true;
1848 if (!wp_resource_sp) {
1850 LLDB_LOGF(log,
"failed to find watchpoint");
1857 watch_id = wp_resource_sp->GetConstituentAtIndex(0)->GetID();
1860 *thread_sp, watch_id, silently_continue));
1862 }
else if (reason ==
"exception") {
1864 *thread_sp, description.c_str()));
1866 }
else if (reason ==
"exec") {
1868 thread_sp->SetStopInfo(
1871 }
else if (reason ==
"processor trace") {
1873 *thread_sp, description.c_str()));
1874 }
else if (reason ==
"fork") {
1879 thread_sp->SetStopInfo(
1882 }
else if (reason ==
"vfork") {
1888 *thread_sp, child_pid, child_tid));
1890 }
else if (reason ==
"vforkdone") {
1891 thread_sp->SetStopInfo(
1895 }
else if (!signo) {
1896 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1898 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
pc);
1904 if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
1906 *thread_sp, bp_site_sp->GetID()));
1911 if (!handled && signo && !did_exec) {
1919 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1928 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
1930 thread_sp->GetRegisterContext()->SetPC(
pc);
1931 thread_sp->SetStopInfo(
1933 *thread_sp, bp_site_sp->GetID()));
1936 thread_sp->SetStopInfo(invalid_stop_info_sp);
1944 thread_sp->SetStopInfo(
1948 *thread_sp, signo, description.c_str()));
1959 if (interrupt_thread)
1960 thread_sp = interrupt_thread;
1963 *thread_sp, signo, description.c_str()));
1967 if (!description.empty()) {
1970 const char *stop_info_desc = stop_info_sp->GetDescription();
1971 if (!stop_info_desc || !stop_info_desc[0])
1972 stop_info_sp->SetDescription(description.c_str());
1975 *thread_sp, description.c_str()));
1985 const std::string &description) {
1994 *thread_sp, signo, description.c_str()));
2003 static constexpr llvm::StringLiteral g_key_tid(
"tid");
2004 static constexpr llvm::StringLiteral g_key_name(
"name");
2005 static constexpr llvm::StringLiteral g_key_reason(
"reason");
2006 static constexpr llvm::StringLiteral g_key_metype(
"metype");
2007 static constexpr llvm::StringLiteral g_key_medata(
"medata");
2008 static constexpr llvm::StringLiteral g_key_qaddr(
"qaddr");
2009 static constexpr llvm::StringLiteral g_key_dispatch_queue_t(
2010 "dispatch_queue_t");
2011 static constexpr llvm::StringLiteral g_key_associated_with_dispatch_queue(
2012 "associated_with_dispatch_queue");
2013 static constexpr llvm::StringLiteral g_key_queue_name(
"qname");
2014 static constexpr llvm::StringLiteral g_key_queue_kind(
"qkind");
2015 static constexpr llvm::StringLiteral g_key_queue_serial_number(
"qserialnum");
2016 static constexpr llvm::StringLiteral g_key_registers(
"registers");
2017 static constexpr llvm::StringLiteral g_key_memory(
"memory");
2018 static constexpr llvm::StringLiteral g_key_description(
"description");
2019 static constexpr llvm::StringLiteral g_key_signal(
"signal");
2025 std::string thread_name;
2027 std::string description;
2028 uint32_t exc_type = 0;
2029 std::vector<addr_t> exc_data;
2032 bool queue_vars_valid =
false;
2035 std::string queue_name;
2037 uint64_t queue_serial_number = 0;
2042 thread_dict->
ForEach([
this, &tid, &expedited_register_map, &thread_name,
2043 &signo, &reason, &description, &exc_type, &exc_data,
2044 &thread_dispatch_qaddr, &queue_vars_valid,
2045 &associated_with_dispatch_queue, &dispatch_queue_t,
2046 &queue_name, &queue_kind, &queue_serial_number](
2047 llvm::StringRef key,
2049 if (key == g_key_tid) {
2052 }
else if (key == g_key_metype) {
2054 exc_type =
object->GetUnsignedIntegerValue(0);
2055 }
else if (key == g_key_medata) {
2064 }
else if (key == g_key_name) {
2066 }
else if (key == g_key_qaddr) {
2067 thread_dispatch_qaddr =
2069 }
else if (key == g_key_queue_name) {
2070 queue_vars_valid =
true;
2072 }
else if (key == g_key_queue_kind) {
2073 std::string queue_kind_str = std::string(object->
GetStringValue());
2074 if (queue_kind_str ==
"serial") {
2075 queue_vars_valid =
true;
2077 }
else if (queue_kind_str ==
"concurrent") {
2078 queue_vars_valid =
true;
2081 }
else if (key == g_key_queue_serial_number) {
2082 queue_serial_number =
object->GetUnsignedIntegerValue(0);
2083 if (queue_serial_number != 0)
2084 queue_vars_valid =
true;
2085 }
else if (key == g_key_dispatch_queue_t) {
2086 dispatch_queue_t =
object->GetUnsignedIntegerValue(0);
2088 queue_vars_valid =
true;
2089 }
else if (key == g_key_associated_with_dispatch_queue) {
2090 queue_vars_valid =
true;
2091 bool associated =
object->GetBooleanValue();
2096 }
else if (key == g_key_reason) {
2098 }
else if (key == g_key_description) {
2100 }
else if (key == g_key_registers) {
2103 if (registers_dict) {
2105 [&expedited_register_map](llvm::StringRef key,
2108 if (llvm::to_integer(key, reg))
2109 expedited_register_map[reg] =
2114 }
else if (key == g_key_memory) {
2120 if (mem_cache_dict) {
2123 "address", mem_cache_addr)) {
2124 if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
2125 llvm::StringRef str;
2126 if (mem_cache_dict->GetValueForKeyAsString(
"bytes", str)) {
2127 StringExtractor bytes(str);
2128 bytes.SetFilePos(0);
2130 const size_t byte_size = bytes.GetStringRef().size() / 2;
2131 WritableDataBufferSP data_buffer_sp(
2132 new DataBufferHeap(byte_size, 0));
2133 const size_t bytes_copied =
2134 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2135 if (bytes_copied == byte_size)
2136 m_memory_cache.AddL1CacheData(mem_cache_addr,
2146 }
else if (key == g_key_signal)
2151 return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2152 reason, description, exc_type, exc_data,
2153 thread_dispatch_qaddr, queue_vars_valid,
2154 associated_with_dispatch_queue, dispatch_queue_t,
2155 queue_name, queue_kind, queue_serial_number);
2161 const char stop_type = stop_packet.
GetChar();
2162 switch (stop_type) {
2181 const uint8_t signo = stop_packet.
GetHexU8();
2182 llvm::StringRef key;
2183 llvm::StringRef value;
2184 std::string thread_name;
2186 std::string description;
2187 uint32_t exc_type = 0;
2188 std::vector<addr_t> exc_data;
2190 bool queue_vars_valid =
2194 std::string queue_name;
2196 uint64_t queue_serial_number = 0;
2200 if (key.compare(
"metype") == 0) {
2202 value.getAsInteger(16, exc_type);
2203 }
else if (key.compare(
"medata") == 0) {
2206 value.getAsInteger(16, x);
2207 exc_data.push_back(x);
2208 }
else if (key.compare(
"thread") == 0) {
2211 auto pid_tid = thread_id.
GetPidTid(pid);
2213 stop_pid = pid_tid->first;
2214 tid = pid_tid->second;
2217 }
else if (key.compare(
"threads") == 0) {
2218 std::lock_guard<std::recursive_mutex> guard(
2221 }
else if (key.compare(
"thread-pcs") == 0) {
2226 while (!value.empty()) {
2227 llvm::StringRef pc_str;
2228 std::tie(pc_str, value) = value.split(
',');
2229 if (pc_str.getAsInteger(16,
pc))
2233 }
else if (key.compare(
"jstopinfo") == 0) {
2242 }
else if (key.compare(
"hexname") == 0) {
2247 }
else if (key.compare(
"name") == 0) {
2248 thread_name = std::string(value);
2249 }
else if (key.compare(
"qaddr") == 0) {
2250 value.getAsInteger(16, thread_dispatch_qaddr);
2251 }
else if (key.compare(
"dispatch_queue_t") == 0) {
2252 queue_vars_valid =
true;
2253 value.getAsInteger(16, dispatch_queue_t);
2254 }
else if (key.compare(
"qname") == 0) {
2255 queue_vars_valid =
true;
2259 }
else if (key.compare(
"qkind") == 0) {
2260 queue_kind = llvm::StringSwitch<QueueKind>(value)
2265 }
else if (key.compare(
"qserialnum") == 0) {
2266 if (!value.getAsInteger(0, queue_serial_number))
2267 queue_vars_valid =
true;
2268 }
else if (key.compare(
"reason") == 0) {
2269 reason = std::string(value);
2270 }
else if (key.compare(
"description") == 0) {
2274 }
else if (key.compare(
"memory") == 0) {
2288 llvm::StringRef addr_str, bytes_str;
2289 std::tie(addr_str, bytes_str) = value.split(
'=');
2290 if (!addr_str.empty() && !bytes_str.empty()) {
2292 if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2297 const size_t bytes_copied =
2299 if (bytes_copied == byte_size)
2303 }
else if (key.compare(
"watch") == 0 || key.compare(
"rwatch") == 0 ||
2304 key.compare(
"awatch") == 0) {
2307 value.getAsInteger(16, wp_addr);
2315 reason =
"watchpoint";
2317 ostr.
Printf(
"%" PRIu64, wp_addr);
2318 description = std::string(ostr.
GetString());
2319 }
else if (key.compare(
"swbreak") == 0 || key.compare(
"hwbreak") == 0) {
2320 reason =
"breakpoint";
2321 }
else if (key.compare(
"library") == 0) {
2327 }
else if (key.compare(
"fork") == 0 || key.compare(
"vfork") == 0) {
2333 LLDB_LOG(log,
"Invalid PID/TID to fork: {0}", value);
2339 ostr.
Printf(
"%" PRIu64
" %" PRIu64, pid_tid->first, pid_tid->second);
2340 description = std::string(ostr.
GetString());
2341 }
else if (key.compare(
"addressing_bits") == 0) {
2342 uint64_t addressing_bits;
2343 if (!value.getAsInteger(0, addressing_bits)) {
2346 }
else if (key.compare(
"low_mem_addressing_bits") == 0) {
2347 uint64_t addressing_bits;
2348 if (!value.getAsInteger(0, addressing_bits)) {
2351 }
else if (key.compare(
"high_mem_addressing_bits") == 0) {
2352 uint64_t addressing_bits;
2353 if (!value.getAsInteger(0, addressing_bits)) {
2356 }
else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2358 if (!key.getAsInteger(16, reg))
2359 expedited_register_map[reg] = std::string(std::move(value));
2369 "Received stop for incorrect PID = {0} (inferior PID = {1})",
2389 tid, expedited_register_map, signo, thread_name, reason, description,
2390 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2391 associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2392 queue_kind, queue_serial_number);
2459 LLDB_LOGF(log,
"ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2463 if (
error.Success())
2465 "ProcessGDBRemote::DoDetach() detach packet sent successfully");
2468 "ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2469 error.AsCString() ?
error.AsCString() :
"<unknown error>");
2472 if (!
error.Success())
2487 LLDB_LOGF(log,
"ProcessGDBRemote::DoDestroy()");
2490 int exit_status = SIGABRT;
2491 std::string exit_string;
2498 exit_status = kill_res.get();
2499#if defined(__APPLE__)
2511 if (platform_sp && platform_sp->IsHost()) {
2514 reap_pid = waitpid(
GetID(), &status, WNOHANG);
2515 LLDB_LOGF(log,
"Reaped pid: %d, status: %d.\n", reap_pid, status);
2519 exit_string.assign(
"killed");
2521 exit_string.assign(llvm::toString(kill_res.takeError()));
2524 exit_string.assign(
"killed or interrupted while attaching.");
2530 exit_string.assign(
"destroying when not connected to debugserver");
2542 const bool did_exec =
2543 response.
GetStringRef().find(
";reason:exec;") != std::string::npos;
2546 LLDB_LOGF(log,
"ProcessGDBRemote::SetLastStopPacket () - detected exec");
2576 LLDB_LOG_ERROR(log, list.takeError(),
"Failed to read module list: {0}.");
2578 addr = list->m_link_map;
2598 const size_t n = thread_infos->
GetSize();
2599 for (
size_t i = 0; i < n; ++i) {
2615 size_t max_memory_size =
2617 if (size > max_memory_size) {
2621 size = max_memory_size;
2626 packet_len = ::snprintf(packet,
sizeof(packet),
"%c%" PRIx64
",%" PRIx64,
2627 binary_memory_read ?
'x' :
'm', (uint64_t)addr,
2629 assert(packet_len + 1 < (
int)
sizeof(packet));
2637 if (binary_memory_read) {
2643 if (data_received_size > size) {
2646 data_received_size = size;
2648 memcpy(buf, response.
GetStringRef().data(), data_received_size);
2649 return data_received_size;
2652 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size),
'\xdd');
2656 "memory read failed for 0x%" PRIx64, addr);
2659 "GDB server does not support reading memory");
2662 "unexpected response to GDB server memory read packet '%s': '%s'",
2675llvm::Expected<std::vector<uint8_t>>
2682 return llvm::createStringError(llvm::inconvertibleErrorCode(),
2683 "Error reading memory tags from remote");
2687 llvm::ArrayRef<uint8_t> tag_data = buffer_sp->GetData();
2688 std::vector<uint8_t> got;
2689 got.reserve(tag_data.size());
2690 std::copy(tag_data.begin(), tag_data.end(), std::back_inserter(got));
2696 const std::vector<uint8_t> &tags) {
2703 std::vector<ObjectFile::LoadableData> entries) {
2708 std::begin(entries), std::end(entries),
2714 if (
error.Success())
2728 for (
size_t i = 0; i < size; ++i)
2753 if (blocksize == 0) {
2761 lldb::addr_t block_start_addr = addr - (addr % blocksize);
2762 size += (addr - block_start_addr);
2763 if ((size % blocksize) != 0)
2764 size += (blocksize - size % blocksize);
2801 "flash erase failed for 0x%" PRIx64, addr);
2804 "GDB server does not support flashing");
2807 "unexpected response to GDB server flash erase packet '%s': '%s'",
2834 "GDB server does not support flashing");
2837 "unexpected response to GDB server flash done packet: '%s'",
2852 if (size > max_memory_size) {
2856 size = max_memory_size;
2877 if (!
error.Success())
2879 packet.
Printf(
"vFlashWrite:%" PRIx64
":", addr);
2882 packet.
Printf(
"M%" PRIx64
",%" PRIx64
":", addr, (uint64_t)size);
2895 "memory write failed for 0x%" PRIx64, addr);
2898 "GDB server does not support writing memory");
2901 "unexpected response to GDB server memory write packet '%s': '%s'",
2911 uint32_t permissions,
2920 return allocated_addr;
2926 if (permissions & lldb::ePermissionsReadable)
2928 if (permissions & lldb::ePermissionsWritable)
2930 if (permissions & lldb::ePermissionsExecutable)
2939 "ProcessGDBRemote::%s no direct stub support for memory "
2940 "allocation, and InferiorCallMmap also failed - is stub "
2941 "missing register context save/restore capability?",
2948 "unable to allocate %" PRIu64
" bytes of memory with permissions %s",
2952 return allocated_addr;
2974 switch (supported) {
2979 "tried to deallocate memory without ever allocating memory");
2985 "unable to deallocate memory at 0x%" PRIx64, addr);
2997 "unable to deallocate memory at 0x%" PRIx64, addr);
3019 assert(bp_site !=
nullptr);
3030 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3031 ") address = 0x%" PRIx64,
3032 site_id, (uint64_t)addr);
3037 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3038 ") address = 0x%" PRIx64
" -- SUCCESS (already enabled)",
3039 site_id, (uint64_t)addr);
3060 if (error_no == 0) {
3076 if (error_no != UINT8_MAX)
3078 "error: %d sending the breakpoint request", error_no);
3087 LLDB_LOGF(log,
"Software breakpoints are unsupported");
3100 if (error_no == 0) {
3111 if (error_no != UINT8_MAX)
3113 "error: %d sending the hardware breakpoint request "
3114 "(hardware breakpoint resources might be exhausted or unavailable)",
3118 "error sending the hardware breakpoint request "
3119 "(hardware breakpoint resources "
3120 "might be exhausted or unavailable)");
3126 LLDB_LOGF(log,
"Hardware breakpoints are unsupported");
3144 assert(bp_site !=
nullptr);
3149 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3150 ") addr = 0x%8.8" PRIx64,
3151 site_id, (uint64_t)addr);
3176 if (
error.Success())
3180 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3181 ") addr = 0x%8.8" PRIx64
" -- SUCCESS (already disabled)",
3182 site_id, (uint64_t)addr);
3186 if (
error.Success())
3195 bool read = wp_res_sp->WatchpointResourceRead();
3196 bool write = wp_res_sp->WatchpointResourceWrite();
3198 assert((read || write) &&
3199 "WatchpointResource type is neither read nor write");
3215 addr_t addr = wp_sp->GetLoadAddress();
3217 LLDB_LOGF(log,
"ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
")",
3219 if (wp_sp->IsEnabled()) {
3221 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3222 ") addr = 0x%8.8" PRIx64
": watchpoint already enabled.",
3223 watchID, (uint64_t)addr);
3227 bool read = wp_sp->WatchpointRead();
3228 bool write = wp_sp->WatchpointWrite() || wp_sp->WatchpointModify();
3229 size_t size = wp_sp->GetByteSize();
3232 WatchpointHardwareFeature supported_features =
3235 std::vector<WatchpointResourceSP> resources =
3237 addr, size, read, write, supported_features, target_arch);
3262 bool set_all_resources =
true;
3263 std::vector<WatchpointResourceSP> succesfully_set_resources;
3264 for (
const auto &wp_res_sp : resources) {
3265 addr_t addr = wp_res_sp->GetLoadAddress();
3266 size_t size = wp_res_sp->GetByteSize();
3271 set_all_resources =
false;
3274 succesfully_set_resources.push_back(wp_res_sp);
3277 if (set_all_resources) {
3278 wp_sp->SetEnabled(
true, notify);
3279 for (
const auto &wp_res_sp : resources) {
3282 wp_res_sp->AddConstituent(wp_sp);
3290 for (
const auto &wp_res_sp : succesfully_set_resources) {
3291 addr_t addr = wp_res_sp->GetLoadAddress();
3292 size_t size = wp_res_sp->GetByteSize();
3298 "Setting one of the watchpoint resources failed");
3314 addr_t addr = wp_sp->GetLoadAddress();
3317 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3318 ") addr = 0x%8.8" PRIx64,
3319 watchID, (uint64_t)addr);
3321 if (!wp_sp->IsEnabled()) {
3323 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3324 ") addr = 0x%8.8" PRIx64
" -- SUCCESS (already disabled)",
3325 watchID, (uint64_t)addr);
3329 wp_sp->SetEnabled(
false, notify);
3333 if (wp_sp->IsHardware()) {
3334 bool disabled_all =
true;
3336 std::vector<WatchpointResourceSP> unused_resources;
3338 if (wp_res_sp->ConstituentsContains(wp_sp)) {
3340 addr_t addr = wp_res_sp->GetLoadAddress();
3341 size_t size = wp_res_sp->GetByteSize();
3344 disabled_all =
false;
3346 wp_res_sp->RemoveConstituent(wp_sp);
3347 if (wp_res_sp->GetNumberOfConstituents() == 0)
3348 unused_resources.push_back(wp_res_sp);
3352 for (
auto &wp_res_sp : unused_resources)
3355 wp_sp->SetEnabled(
false, notify);
3358 "Failure disabling one of the watchpoint locations");
3371 LLDB_LOGF(log,
"ProcessGDBRemote::DoSignal (signal = %d)", signo);
3386 if (platform_sp && !platform_sp->IsHost())
3391 const char *error_string =
error.AsCString();
3392 if (error_string ==
nullptr)
3398#define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3401#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3403#if defined(FD_CLOEXEC)
3404 int flags = ::fcntl(fd, F_GETFD);
3407 return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3416 using namespace std::placeholders;
3421 static FileSpec g_debugserver_file_spec;
3428 const std::weak_ptr<ProcessGDBRemote> this_wp =
3429 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3434#if defined(__APPLE__)
3438 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID,
3440 struct kinfo_proc processInfo;
3441 size_t bufsize =
sizeof(processInfo);
3442 if (sysctl(mib, (
unsigned)(
sizeof(mib)/
sizeof(
int)), &processInfo,
3443 &bufsize, NULL, 0) == 0 && bufsize > 0) {
3444 if (processInfo.kp_proc.p_flag & P_TRANSLATED) {
3445 FileSpec rosetta_debugserver(
"/Library/Apple/usr/libexec/oah/debugserver");
3452#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3456 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
3461 int our_socket = sockets[0];
3462 int gdb_socket = sockets[1];
3463 auto cleanup_our = llvm::make_scope_exit([&]() { close(our_socket); });
3464 auto cleanup_gdb = llvm::make_scope_exit([&]() { close(gdb_socket); });
3468 communication_fd = gdb_socket;
3472 nullptr,
GetTarget().GetPlatform().get(), debugserver_launch_info,
3473 nullptr,
nullptr, communication_fd);
3475 if (
error.Success())
3481#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3484 cleanup_our.release();
3486 std::make_unique<ConnectionFileDescriptor>(our_socket,
true));
3494 LLDB_LOGF(log,
"failed to start debugserver process: %s",
3511 std::weak_ptr<ProcessGDBRemote> process_wp,
lldb::pid_t debugserver_pid,
3520 "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3521 ", signo=%i (0x%x), exit_status=%i)",
3522 __FUNCTION__, debugserver_pid, signo, signo, exit_status);
3524 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3525 LLDB_LOGF(log,
"ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3526 static_cast<void *
>(process_sp.get()));
3527 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3533 std::this_thread::sleep_for(std::chrono::milliseconds(500));
3537 const StateType state = process_sp->GetState();
3546 llvm::StringRef signal_name =
3547 process_sp->GetUnixSignals()->GetSignalAsStringRef(signo);
3549 if (!signal_name.empty())
3550 stream.
Format(format_str, signal_name);
3552 stream.
Format(format_str, signo);
3554 process_sp->SetExitStatus(-1, stream.
GetString());
3570 static llvm::once_flag g_once_flag;
3572 llvm::call_once(g_once_flag, []() {
3581 debugger, PluginProperties::GetSettingName())) {
3582 const bool is_global_setting =
true;
3585 "Properties for the gdb-remote process plug-in.", is_global_setting);
3592 LLDB_LOGF(log,
"ProcessGDBRemote::%s ()", __FUNCTION__);
3599 llvm::Expected<HostThread> async_thread =
3603 if (!async_thread) {
3605 "failed to launch host thread: {0}");
3611 "ProcessGDBRemote::%s () - Called when Async thread was "
3621 LLDB_LOGF(log,
"ProcessGDBRemote::%s ()", __FUNCTION__);
3636 "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3642 LLDB_LOGF(log,
"ProcessGDBRemote::%s(pid = %" PRIu64
") thread starting...",
3643 __FUNCTION__,
GetID());
3661 "ProcessGDBRemote::%s(pid = %" PRIu64
3662 ") listener.WaitForEvent (NULL, event_sp)...",
3663 __FUNCTION__,
GetID());
3666 const uint32_t event_type = event_sp->GetType();
3669 "ProcessGDBRemote::%s(pid = %" PRIu64
3670 ") Got an event of type: %d...",
3671 __FUNCTION__,
GetID(), event_type);
3673 switch (event_type) {
3678 if (continue_packet) {
3679 const char *continue_cstr =
3680 (
const char *)continue_packet->
GetBytes();
3681 const size_t continue_cstr_len = continue_packet->
GetByteSize();
3683 "ProcessGDBRemote::%s(pid = %" PRIu64
3684 ") got eBroadcastBitAsyncContinue: %s",
3685 __FUNCTION__,
GetID(), continue_cstr);
3687 if (::strstr(continue_cstr,
"vAttach") ==
nullptr)
3694 llvm::StringRef(continue_cstr, continue_cstr_len),
3705 switch (stop_state) {
3718 int exit_status = response.
GetHexU8();
3719 std::string desc_string;
3721 llvm::StringRef desc_str;
3722 llvm::StringRef desc_token;
3724 if (desc_token !=
"description")
3739 if (::strstr(continue_cstr,
"vAttach") !=
nullptr &&
3742 "System Integrity Protection");
3743 }
else if (::strstr(continue_cstr,
"vAttach") !=
nullptr &&
3763 "ProcessGDBRemote::%s(pid = %" PRIu64
3764 ") got eBroadcastBitAsyncThreadShouldExit...",
3765 __FUNCTION__,
GetID());
3771 "ProcessGDBRemote::%s(pid = %" PRIu64
3772 ") got unknown event 0x%8.8x",
3773 __FUNCTION__,
GetID(), event_type);
3780 "ProcessGDBRemote::%s(pid = %" PRIu64
3781 ") listener.WaitForEvent (NULL, event_sp) => false",
3782 __FUNCTION__,
GetID());
3787 LLDB_LOGF(log,
"ProcessGDBRemote::%s(pid = %" PRIu64
") thread exiting...",
3788 __FUNCTION__,
GetID());
3820 LLDB_LOGF(log,
"Hit New Thread Notification breakpoint.");
3826 LLDB_LOG(log,
"Check if need to update ignored signals");
3840 LLDB_LOG(log,
"Signals' version hasn't changed. version={0}",
3845 auto signals_to_ignore =
3850 "Signals' version changed. old version={0}, new version={1}, "
3851 "signals ignored={2}, update result={3}",
3853 signals_to_ignore.size(),
error);
3855 if (
error.Success())
3865 LLDB_LOGF(log,
"Enabled noticing new thread breakpoint.");
3871 platform_sp->SetThreadCreationBreakpoint(
GetTarget());
3875 log,
"Successfully created new thread notification breakpoint %i",
3880 LLDB_LOGF(log,
"Failed to create new thread notification breakpoint.");
3890 LLDB_LOGF(log,
"Disabling new thread notification breakpoint.");
3911 if (return_value != 0) {
3914 "Sending events is not supported for this process.");
3927 buf = std::make_shared<DataBufferHeap>(response->c_str(),
3928 response->length());
3945 args_dict->GetAsDictionary()->AddIntegerItem(
"thread", tid);
3948 packet <<
"jThreadExtendedInfo:";
3949 args_dict->Dump(packet,
false);
3956 packet << (char)(0x7d ^ 0x20);
3965 if (!response.
Empty()) {
3978 args_dict->GetAsDictionary()->AddIntegerItem(
"image_list_address",
3979 image_list_address);
3980 args_dict->GetAsDictionary()->AddIntegerItem(
"image_count", image_count);
3988 args_dict->GetAsDictionary()->AddBooleanItem(
"fetch_all_solibs",
true);
3994 const std::vector<lldb::addr_t> &load_addresses) {
3998 for (
auto addr : load_addresses)
3999 addresses->AddIntegerItem(addr);
4001 args_dict->GetAsDictionary()->AddItem(
"solib_addresses", addresses);
4014 std::chrono::seconds(10));
4017 packet <<
"jGetLoadedDynamicLibrariesInfos:";
4018 args_dict->Dump(packet,
false);
4025 packet << (char)(0x7d ^ 0x20);
4034 if (!response.
Empty()) {
4056 if (!response.
Empty()) {
4071 packet <<
"jGetSharedCacheInfo:";
4072 args_dict->Dump(packet,
false);
4079 packet << (char)(0x7d ^ 0x20);
4088 if (!response.
Empty()) {
4112 const uint64_t reasonable_largeish_default = 128 * 1024;
4113 const uint64_t conservative_default = 512;
4117 if (stub_max_size !=
UINT64_MAX && stub_max_size != 0) {
4123 if (stub_max_size > reasonable_largeish_default) {
4124 stub_max_size = reasonable_largeish_default;
4130 if (stub_max_size > 70)
4131 stub_max_size -= 32 + 32 + 6;
4137 log->
Warning(
"Packet size is too small. "
4138 "LLDB may face problems while writing memory");
4149 uint64_t user_specified_max) {
4150 if (user_specified_max != 0) {
4178 module_spec = cached->second;
4179 return bool(module_spec);
4183 LLDB_LOGF(log,
"ProcessGDBRemote::%s - failed to get module info for %s:%s",
4184 __FUNCTION__, module_file_spec.
GetPath().c_str(),
4191 module_spec.
Dump(stream);
4192 LLDB_LOGF(log,
"ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4193 __FUNCTION__, module_file_spec.
GetPath().c_str(),
4202 llvm::ArrayRef<FileSpec> module_file_specs,
const llvm::Triple &triple) {
4205 for (
const FileSpec &spec : module_file_specs)
4210 triple.getTriple())] = spec;
4224typedef std::vector<std::string> stringVec;
4226typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
4227struct RegisterSetInfo {
4231typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4233struct GdbServerTargetInfo {
4237 RegisterSetMap reg_set_map;
4254 std::map<uint64_t, FieldEnum::Enumerator> enumerators;
4257 "evalue", [&enumerators, &log](
const XMLNode &enumerator_node) {
4258 std::optional<llvm::StringRef> name;
4259 std::optional<uint64_t> value;
4262 [&name, &value, &log](
const llvm::StringRef &attr_name,
4263 const llvm::StringRef &attr_value) {
4264 if (attr_name ==
"name") {
4265 if (attr_value.size())
4268 LLDB_LOG(log,
"ProcessGDBRemote::ParseEnumEvalues "
4269 "Ignoring empty name in evalue");
4270 }
else if (attr_name ==
"value") {
4271 uint64_t parsed_value = 0;
4272 if (llvm::to_integer(attr_value, parsed_value))
4273 value = parsed_value;
4276 "ProcessGDBRemote::ParseEnumEvalues "
4277 "Invalid value \"{0}\" in "
4282 "ProcessGDBRemote::ParseEnumEvalues Ignoring "
4283 "unknown attribute "
4284 "\"{0}\" in evalue",
4292 enumerators.insert_or_assign(
4300 for (
auto [_, enumerator] : enumerators)
4301 final_enumerators.push_back(enumerator);
4303 return final_enumerators;
4307ParseEnums(
XMLNode feature_node,
4308 llvm::StringMap<std::unique_ptr<FieldEnum>> ®isters_enum_types) {
4313 "enum", [log, ®isters_enum_types](
const XMLNode &enum_node) {
4317 const llvm::StringRef &attr_value) {
4318 if (attr_name ==
"id")
4336 if (!enumerators.empty()) {
4338 "ProcessGDBRemote::ParseEnums Found enum type \"{0}\"",
4340 registers_enum_types.insert_or_assign(
4341 id, std::make_unique<FieldEnum>(
id, enumerators));
4350static std::vector<RegisterFlags::Field> ParseFlagsFields(
4351 XMLNode flags_node,
unsigned size,
4352 const llvm::StringMap<std::unique_ptr<FieldEnum>> ®isters_enum_types) {
4354 const unsigned max_start_bit = size * 8 - 1;
4357 std::vector<RegisterFlags::Field> fields;
4359 ®isters_enum_types](
4362 std::optional<llvm::StringRef> name;
4363 std::optional<unsigned> start;
4364 std::optional<unsigned> end;
4365 std::optional<llvm::StringRef> type;
4368 &log](
const llvm::StringRef &attr_name,
4369 const llvm::StringRef &attr_value) {
4372 if (attr_name ==
"name") {
4375 "ProcessGDBRemote::ParseFlagsFields Found field node name \"{0}\"",
4378 }
else if (attr_name ==
"start") {
4379 unsigned parsed_start = 0;
4380 if (llvm::to_integer(attr_value, parsed_start)) {
4381 if (parsed_start > max_start_bit) {
4383 "ProcessGDBRemote::ParseFlagsFields Invalid start {0} in "
4386 parsed_start, max_start_bit);
4388 start = parsed_start;
4392 "ProcessGDBRemote::ParseFlagsFields Invalid start \"{0}\" in "
4396 }
else if (attr_name ==
"end") {
4397 unsigned parsed_end = 0;
4398 if (llvm::to_integer(attr_value, parsed_end))
4399 if (parsed_end > max_start_bit) {
4401 "ProcessGDBRemote::ParseFlagsFields Invalid end {0} in "
4404 parsed_end, max_start_bit);
4409 "ProcessGDBRemote::ParseFlagsFields Invalid end \"{0}\" in "
4413 }
else if (attr_name ==
"type") {
4418 "ProcessGDBRemote::ParseFlagsFields Ignoring unknown attribute "
4419 "\"{0}\" in field node",
4426 if (name && start && end) {
4430 "ProcessGDBRemote::ParseFlagsFields Start {0} > end {1} in field "
4431 "\"{2}\", ignoring",
4432 *start, *end, name->data());
4436 "ProcessGDBRemote::ParseFlagsFields Ignoring field \"{2}\" "
4438 "size > 64 bits, this is not supported",
4443 if (type && !type->empty()) {
4444 auto found = registers_enum_types.find(*type);
4445 if (found != registers_enum_types.end()) {
4446 enum_type = found->second.get();
4449 uint64_t max_value =
4452 if (enumerator.m_value > max_value) {
4453 enum_type =
nullptr;
4456 "ProcessGDBRemote::ParseFlagsFields In enum \"{0}\" "
4457 "evalue \"{1}\" with value {2} exceeds the maximum value "
4458 "of field \"{3}\" ({4}), ignoring enum",
4459 type->data(), enumerator.m_name, enumerator.m_value,
4460 name->data(), max_value);
4466 "ProcessGDBRemote::ParseFlagsFields Could not find type "
4468 "for field \"{1}\", ignoring",
4469 type->data(), name->data());
4486 llvm::StringMap<std::unique_ptr<RegisterFlags>> ®isters_flags_types,
4487 const llvm::StringMap<std::unique_ptr<FieldEnum>> ®isters_enum_types) {
4492 [&log, ®isters_flags_types,
4493 ®isters_enum_types](
const XMLNode &flags_node) ->
bool {
4494 LLDB_LOG(log,
"ProcessGDBRemote::ParseFlags Found flags node \"{0}\"",
4497 std::optional<llvm::StringRef>
id;
4498 std::optional<unsigned> size;
4500 [&
id, &size, &log](
const llvm::StringRef &name,
4501 const llvm::StringRef &value) {
4504 }
else if (name ==
"size") {
4505 unsigned parsed_size = 0;
4506 if (llvm::to_integer(value, parsed_size))
4510 "ProcessGDBRemote::ParseFlags Invalid size \"{0}\" "
4516 "ProcessGDBRemote::ParseFlags Ignoring unknown "
4517 "attribute \"{0}\" in flags node",
4525 std::vector<RegisterFlags::Field> fields =
4526 ParseFlagsFields(flags_node, *size, registers_enum_types);
4527 if (fields.size()) {
4529 std::sort(fields.rbegin(), fields.rend());
4530 std::vector<RegisterFlags::Field>::const_iterator overlap =
4531 std::adjacent_find(fields.begin(), fields.end(),
4534 return lhs.Overlaps(rhs);
4538 if (overlap == fields.end()) {
4539 if (registers_flags_types.contains(*
id)) {
4553 "ProcessGDBRemote::ParseFlags Definition of flags "
4555 "previous definition, using original definition instead.",
4558 registers_flags_types.insert_or_assign(
4559 *
id, std::make_unique<RegisterFlags>(
id->str(), *size,
4560 std::move(fields)));
4564 std::vector<RegisterFlags::Field>::const_iterator next =
4568 "ProcessGDBRemote::ParseFlags Ignoring flags because fields "
4569 "{0} (start: {1} end: {2}) and {3} (start: {4} end: {5}) "
4571 overlap->GetName().c_str(), overlap->GetStart(),
4572 overlap->GetEnd(), next->GetName().c_str(), next->GetStart(),
4578 "ProcessGDBRemote::ParseFlags Ignoring definition of flags "
4579 "\"{0}\" because it contains no fields.",
4589 XMLNode feature_node, GdbServerTargetInfo &target_info,
4590 std::vector<DynamicRegisterInfo::Register> ®isters,
4591 llvm::StringMap<std::unique_ptr<RegisterFlags>> ®isters_flags_types,
4592 llvm::StringMap<std::unique_ptr<FieldEnum>> ®isters_enum_types) {
4599 ParseEnums(feature_node, registers_enum_types);
4600 for (
const auto &enum_type : registers_enum_types)
4603 ParseFlags(feature_node, registers_flags_types, registers_enum_types);
4604 for (
const auto &flags : registers_flags_types)
4605 flags.second->DumpToLog(log);
4609 [&target_info, ®isters, ®isters_flags_types,
4610 log](
const XMLNode ®_node) ->
bool {
4611 std::string gdb_group;
4612 std::string gdb_type;
4614 bool encoding_set =
false;
4615 bool format_set =
false;
4619 &encoding_set, &format_set, ®_info,
4620 log](
const llvm::StringRef &name,
4621 const llvm::StringRef &value) ->
bool {
4622 if (name ==
"name") {
4624 }
else if (name ==
"bitsize") {
4625 if (llvm::to_integer(value, reg_info.
byte_size))
4627 llvm::divideCeil(reg_info.
byte_size, CHAR_BIT);
4628 }
else if (name ==
"type") {
4629 gdb_type = value.str();
4630 }
else if (name ==
"group") {
4631 gdb_group = value.str();
4632 }
else if (name ==
"regnum") {
4634 }
else if (name ==
"offset") {
4636 }
else if (name ==
"altname") {
4638 }
else if (name ==
"encoding") {
4639 encoding_set =
true;
4641 }
else if (name ==
"format") {
4647 llvm::StringSwitch<lldb::Format>(value)
4658 }
else if (name ==
"group_id") {
4660 llvm::to_integer(value, set_id);
4661 RegisterSetMap::const_iterator pos =
4662 target_info.reg_set_map.find(set_id);
4663 if (pos != target_info.reg_set_map.end())
4664 reg_info.
set_name = pos->second.name;
4665 }
else if (name ==
"gcc_regnum" || name ==
"ehframe_regnum") {
4667 }
else if (name ==
"dwarf_regnum") {
4669 }
else if (name ==
"generic") {
4671 }
else if (name ==
"value_regnums") {
4674 }
else if (name ==
"invalidate_regnums") {
4679 "ProcessGDBRemote::ParseRegisters unhandled reg "
4680 "attribute %s = %s",
4681 name.data(), value.data());
4686 if (!gdb_type.empty()) {
4688 llvm::StringMap<std::unique_ptr<RegisterFlags>>::iterator it =
4689 registers_flags_types.find(gdb_type);
4690 if (it != registers_flags_types.end()) {
4691 auto flags_type = it->second.get();
4692 if (reg_info.
byte_size == flags_type->GetSize())
4696 "ProcessGDBRemote::ParseRegisters Size of register "
4697 "flags %s (%d bytes) for "
4698 "register %s does not match the register size (%d "
4699 "bytes). Ignoring this set of flags.",
4700 flags_type->GetID().c_str(), flags_type->GetSize(),
4707 if (!gdb_type.empty() && !(encoding_set || format_set)) {
4708 if (llvm::StringRef(gdb_type).starts_with(
"int")) {
4711 }
else if (gdb_type ==
"data_ptr" || gdb_type ==
"code_ptr") {
4714 }
else if (gdb_type ==
"float") {
4717 }
else if (gdb_type ==
"aarch64v" ||
4718 llvm::StringRef(gdb_type).starts_with(
"vec") ||
4719 gdb_type ==
"i387_ext" || gdb_type ==
"uint128" ||
4732 "ProcessGDBRemote::ParseRegisters Could not determine lldb"
4733 "format and encoding for gdb type %s",
4743 if (!gdb_group.empty()) {
4754 "ProcessGDBRemote::%s Skipping zero bitsize register %s",
4757 registers.push_back(reg_info);
4772 ArchSpec &arch_to_use, std::string xml_filename,
4773 std::vector<DynamicRegisterInfo::Register> ®isters) {
4776 if (errorToBool(raw.takeError()))
4781 if (xml_document.
ParseMemory(raw->c_str(), raw->size(),
4782 xml_filename.c_str())) {
4783 GdbServerTargetInfo target_info;
4784 std::vector<XMLNode> feature_nodes;
4790 const XMLNode &node) ->
bool {
4791 llvm::StringRef name = node.
GetName();
4792 if (name ==
"architecture") {
4794 }
else if (name ==
"osabi") {
4796 }
else if (name ==
"xi:include" || name ==
"include") {
4799 target_info.includes.push_back(href);
4800 }
else if (name ==
"feature") {
4801 feature_nodes.push_back(node);
4802 }
else if (name ==
"groups") {
4804 "group", [&target_info](
const XMLNode &node) ->
bool {
4806 RegisterSetInfo set_info;
4809 [&set_id, &set_info](
const llvm::StringRef &name,
4810 const llvm::StringRef &value) ->
bool {
4813 llvm::to_integer(value, set_id);
4820 target_info.reg_set_map[set_id] = set_info;
4833 feature_nodes.push_back(feature_node);
4835 const XMLNode &node) ->
bool {
4836 llvm::StringRef name = node.
GetName();
4837 if (name ==
"xi:include" || name ==
"include") {
4840 target_info.includes.push_back(href);
4854 if (!arch_to_use.
IsValid() && !target_info.arch.empty()) {
4856 arch_to_use.
SetTriple(llvm::StringSwitch<std::string>(target_info.arch)
4857 .Case(
"i386:x86-64",
"x86_64")
4858 .Case(
"riscv:rv64",
"riscv64")
4859 .Case(
"riscv:rv32",
"riscv32")
4860 .Default(target_info.arch) +
4868 for (
auto &feature_node : feature_nodes) {
4869 ParseRegisters(feature_node, target_info, registers,
4873 for (
const auto &include : target_info.includes) {
4885 std::vector<DynamicRegisterInfo::Register> ®isters,
4887 std::map<uint32_t, uint32_t> remote_to_local_map;
4888 uint32_t remote_regnum = 0;
4889 for (
auto it : llvm::enumerate(registers)) {
4897 remote_to_local_map[remote_reg_info.
regnum_remote] = it.index();
4903 auto proc_to_lldb = [&remote_to_local_map](uint32_t process_regnum) {
4904 auto lldb_regit = remote_to_local_map.find(process_regnum);
4905 return lldb_regit != remote_to_local_map.end() ? lldb_regit->second