14#include "llvm/ADT/ScopeExit.h"
15#include "llvm/Support/Process.h"
16#include "llvm/Support/ScopedPrinter.h"
17#include "llvm/Support/Threading.h"
86using namespace std::chrono;
92 if (inserted || previous->second == action)
100 :
public Cloneable<ProcessOptionValueProperties, OptionValueProperties> {
116 if (
this != instance_properties)
128 "Continue tracing the parent process and detach the child.",
133 "Trace the child process and detach the parent.",
139#define LLDB_PROPERTIES_process
140#include "TargetProperties.inc"
143#define LLDB_PROPERTIES_process
144#include "TargetPropertiesEnum.inc"
147#define LLDB_PROPERTIES_process_experimental
148#include "TargetProperties.inc"
151#define LLDB_PROPERTIES_process_experimental
152#include "TargetPropertiesEnum.inc"
156 :
public Cloneable<ProcessExperimentalOptionValueProperties,
157 OptionValueProperties> {
173 if (process ==
nullptr) {
175 m_collection_sp = std::make_shared<ProcessOptionValueProperties>(
"process");
181 ePropertyMemCacheLineSize);
185 "thread",
"Settings specific to threads.",
true,
189 std::make_unique<ProcessExperimentalProperties>();
192 "Experimental settings - setting these won't produce "
193 "errors if the setting is not present.",
199 ePropertyPythonOSPluginPath,
200 [
this] {
m_process->LoadOperatingSystemPlugin(
true); });
202 ePropertyDisableLangRuntimeUnwindPlans,
205 ePropertyVirtualAddressableBits,
208 ePropertyHighmemVirtualAddressableBits,
216 const uint32_t idx = ePropertyDisableMemCache;
218 idx, g_process_properties[idx].default_uint_value != 0);
223 const uint32_t idx = ePropertyVerifyMemoryReads;
225 idx, g_process_properties[idx].default_uint_value != 0);
230 const uint32_t idx = ePropertyMemCacheLineSize;
232 idx, g_process_properties[idx].default_uint_value);
237 const uint32_t idx = ePropertyExtraStartCommand;
243 const uint32_t idx = ePropertyExtraStartCommand;
248 const uint32_t idx = ePropertyPythonOSPluginPath;
253 const uint32_t idx = ePropertyVirtualAddressableBits;
255 idx, g_process_properties[idx].default_uint_value);
259 const uint32_t idx = ePropertyVirtualAddressableBits;
264 const uint32_t idx = ePropertyHighmemVirtualAddressableBits;
266 idx, g_process_properties[idx].default_uint_value);
270 const uint32_t idx = ePropertyHighmemVirtualAddressableBits;
283 thread_sp->ClearStackFrames();
287 const uint32_t idx = ePropertyPythonOSPluginPath;
292 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
294 idx, g_process_properties[idx].default_uint_value != 0);
298 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
303 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
305 idx, g_process_properties[idx].default_uint_value != 0);
309 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
314 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
316 idx, g_process_properties[idx].default_uint_value != 0);
320 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
325 const uint32_t idx = ePropertyDisableLangRuntimeUnwindPlans;
327 idx, g_process_properties[idx].default_uint_value != 0);
331 const uint32_t idx = ePropertyDisableLangRuntimeUnwindPlans;
339 for (
auto thread_sp :
m_process->Threads()) {
340 thread_sp->ClearStackFrames();
341 thread_sp->DiscardThreadPlans(
true);
346 const uint32_t idx = ePropertyDetachKeepsStopped;
348 idx, g_process_properties[idx].default_uint_value != 0);
352 const uint32_t idx = ePropertyDetachKeepsStopped;
357 const uint32_t idx = ePropertyWarningOptimization;
359 idx, g_process_properties[idx].default_uint_value != 0);
363 const uint32_t idx = ePropertyWarningUnsupportedLanguage;
365 idx, g_process_properties[idx].default_uint_value != 0);
369 const uint32_t idx = ePropertyStopOnExec;
371 idx, g_process_properties[idx].default_uint_value != 0);
375 const uint32_t idx = ePropertyUseDelayedBreakpoints;
377 idx, g_process_properties[idx].default_uint_value != 0);
381 const uint32_t idx = ePropertyUtilityExpressionTimeout;
383 idx, g_process_properties[idx].default_uint_value);
384 return std::chrono::seconds(value);
388 const uint32_t idx = ePropertyInterruptTimeout;
390 idx, g_process_properties[idx].default_uint_value);
391 return std::chrono::seconds(value);
395 const uint32_t idx = ePropertySteppingRunsAllThreads;
397 idx, g_process_properties[idx].default_uint_value != 0);
402 const uint32_t idx = ePropertyAlwaysRunThreadNames;
415 const bool fail_value =
true;
421 .value_or(fail_value);
426 exp_values->SetPropertyAtIndex(ePropertyOSPluginReportsAllThreads,
431 const uint32_t idx = ePropertyFollowForkMode;
434 g_process_properties[idx].default_uint_value));
438 const uint32_t idx = ePropertyTrackMemoryCacheChanges;
440 idx, g_process_properties[idx].default_uint_value != 0);
444 llvm::StringRef plugin_name,
448 static std::atomic<uint32_t> g_process_unique_id{0};
452 if (!plugin_name.empty()) {
455 if (create_callback) {
456 process_sp = create_callback(target_sp, listener_sp, crash_file_path,
459 if (process_sp->CanDebug(target_sp,
true)) {
460 process_sp->m_process_unique_id = ++g_process_unique_id;
467 process_sp = create_callback(target_sp, listener_sp, crash_file_path,
470 if (process_sp->CanDebug(target_sp,
false)) {
471 process_sp->m_process_unique_id = ++g_process_unique_id;
482 static constexpr llvm::StringLiteral class_name(
"lldb.process");
495 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
499 "lldb.process.internal_state_broadcaster"),
501 nullptr,
"lldb.process.internal_state_control_broadcaster"),
503 Listener::MakeListener(
"lldb.process.internal_state_listener")),
529 LLDB_LOGF(log,
"%p Process::Process()",
static_cast<void *
>(
this));
567 uint64_t platform_cache_line_size =
568 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
569 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
570 value_sp->SetValueAs(platform_cache_line_size);
580 LLDB_LOGF(log,
"%p Process::~Process()",
static_cast<void *
>(
this));
597 return *g_settings_ptr;
632 std::vector<Notifications> empty_notifications;
665 if (pos->baton == callbacks.
baton &&
676 std::vector<Notifications>::iterator notification_pos,
679 notification_pos != notification_end; ++notification_pos) {
680 if (notification_pos->process_state_changed)
681 notification_pos->process_state_changed(notification_pos->baton,
this,
700 std::chrono::seconds(0)) &&
714 auto Result =
m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout);
720 "waited from m_iohandler_sync to change from {0}. New value is {1}.",
721 iohandler_id, *Result);
723 LLDB_LOG(log,
"timed out waiting for m_iohandler_sync to change from {0}.",
736 event_sp_ptr->reset();
744 LLDB_LOG(log,
"timeout = {0}", timeout);
749 "Process::%s returning without waiting for events; process "
750 "private and public states are already 'stopped'.",
754 if (hijack_listener_sp && use_run_lock)
762 if (event_sp_ptr && event_sp)
763 *event_sp_ptr = event_sp;
765 bool pop_process_io_handler = (hijack_listener_sp.get() !=
nullptr);
767 event_sp, stream, select_most_relevant, pop_process_io_handler);
776 if (hijack_listener_sp && use_run_lock)
785 if (hijack_listener_sp && use_run_lock)
799 bool &pop_process_io_handler) {
800 const bool handle_pop = pop_process_io_handler;
802 pop_process_io_handler =
false;
814 switch (event_state) {
822 stream->
Printf(
"Process %" PRIu64
" %s\n", process_sp->GetID(),
825 pop_process_io_handler =
true;
835 process_sp->GetStatus(*stream);
836 pop_process_io_handler =
true;
847 if (num_reasons > 0) {
850 if (num_reasons == 1) {
854 stream->
Printf(
"Process %" PRIu64
" stopped and restarted: %s\n",
856 reason ? reason :
"<UNKNOWN REASON>");
858 stream->
Printf(
"Process %" PRIu64
859 " stopped and restarted, reasons:\n",
860 process_sp->GetID());
862 for (
size_t i = 0; i < num_reasons; i++) {
866 stream->
Printf(
"\t%s\n", reason ? reason :
"<UNKNOWN REASON>");
876 ThreadList &thread_list = process_sp->GetThreadList();
877 std::lock_guard<std::recursive_mutex> guard(thread_list.
GetMutex());
881 if (curr_thread && curr_thread->IsValid())
882 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
883 bool prefer_curr_thread = curr_thread_stop_info_sp &&
884 curr_thread_stop_info_sp->ShouldSelect();
886 if (!prefer_curr_thread) {
894 if (!stop_info || !stop_info->ShouldSelect())
896 StopReason thread_stop_reason = stop_info->GetStopReason();
899 plan_thread = thread;
900 }
else if (!other_thread) {
901 other_thread = thread;
906 else if (other_thread)
910 if (curr_thread && curr_thread->IsValid())
911 thread = curr_thread;
925 Debugger &debugger = process_sp->GetTarget().GetDebugger();
927 &process_sp->GetTarget()) {
928 ThreadSP thread_sp = process_sp->GetThreadList().GetSelectedThread();
930 if (!thread_sp || !thread_sp->IsValid())
933 const bool only_threads_with_stop_reason =
true;
934 const uint32_t start_frame =
935 thread_sp->GetSelectedFrameIndex(select_most_relevant);
936 const uint32_t num_frames = 1;
937 const uint32_t num_frames_with_source = 1;
938 const bool stop_format =
true;
940 process_sp->GetStatus(*stream);
941 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
942 start_frame, num_frames,
943 num_frames_with_source,
945 if (curr_thread_stop_info_sp) {
948 curr_thread_stop_info_sp, &crashing_address);
951 ValueObject::GetExpressionPathFormat::
952 eGetExpressionPathFormatHonorPointers;
954 valobj_sp->GetExpressionPath(*stream, format);
955 stream->
Printf(
" accessed 0x%" PRIx64
"\n", crashing_address);
960 process_sp->GetTarget().shared_from_this());
962 stream->
Printf(
"Target %d: (", target_idx);
964 stream->
PutCString(
"Target <unknown index>: (");
971 pop_process_io_handler =
true;
976 if (handle_pop && pop_process_io_handler)
977 process_sp->PopProcessIOHandler();
996 LLDB_LOG(log,
"timeout = {0}, event_sp)...", timeout);
1003 if (listener_sp->GetEventForBroadcasterWithType(
1009 LLDB_LOG(log,
"got no event or was interrupted.");
1012 LLDB_LOG(log,
"timeout = {0}, event_sp) => {1}", timeout, state);
1019 LLDB_LOGF(log,
"Process::%s...", __FUNCTION__);
1025 LLDB_LOGF(log,
"Process::%s (event_ptr) => %s", __FUNCTION__,
1028 LLDB_LOGF(log,
"Process::%s no events found", __FUNCTION__);
1036 LLDB_LOG(log,
"timeout = {0}, event_sp)...", timeout);
1046 LLDB_LOG(log,
"timeout = {0}, event_sp) => {1}", timeout,
1053 bool control_only) {
1055 LLDB_LOG(log,
"timeout = {0}, event_sp)...", timeout);
1088 LLDB_LOG(log,
"(plugin = {0} status = {1} ({1:x8}), description=\"{2}\")",
1095 "(plugin = {0}) ignoring exit status because state was already set "
1107 if (
ModuleSP mod = target_sp->GetExecutableModule())
1108 module_uuid = mod->GetUUID();
1115 info->
exit_desc = {status, exit_string.str()};
1125 if (!exit_string.empty())
1171 bool clear_unused_threads =
true;
1174 std::lock_guard<std::recursive_mutex> guard(
m_thread_list.GetMutex());
1194 size_t num_old_threads = old_thread_list.
GetSize(
false);
1195 for (
size_t i = 0; i < num_old_threads; ++i)
1228 new_thread_list = real_thread_list;
1269 bool internal,
bool condense_trivial,
1270 bool skip_unreported_plans) {
1272 strm, tid, desc_level, internal, condense_trivial, skip_unreported_plans);
1275 bool internal,
bool condense_trivial,
1276 bool skip_unreported_plans) {
1277 m_thread_plans.DumpPlans(strm, desc_level, internal, condense_trivial,
1278 skip_unreported_plans);
1311 auto [iterator, inserted] =
1316 return iterator->second;
1340 if (new_state_is_stopped) {
1351 LLDB_LOGF(log,
"(plugin = %s, state = %s, restarted = %i)",
1362 "(plugin = %s, state = %s) -- unlocking run lock for detach",
1367 if ((old_state_is_stopped != new_state_is_stopped)) {
1368 if (new_state_is_stopped && !restarted) {
1369 LLDB_LOGF(log,
"(plugin = %s, state = %s) -- unlocking run lock",
1382 LLDB_LOGF(log,
"(plugin = %s) -- SetRunning failed, not resuming.",
1385 "resume request failed - process already running");
1388 if (!
error.Success()) {
1397 LLDB_LOGF(log,
"Process::ResumeSynchronous -- locking run lock");
1399 LLDB_LOGF(log,
"Process::Resume: -- SetRunning failed, not resuming.");
1401 "resume request failed: process already running");
1409 if (
error.Success()) {
1413 const bool must_be_alive =
1417 "process not in stopped state after synchronous resume: %s",
1433 if (!hijacking_name.starts_with(
"lldb.internal"))
1462 bool state_changed =
false;
1467 std::lock_guard<std::recursive_mutex> thread_guard(
m_thread_list.GetMutex());
1471 state_changed = old_state != new_state;
1475 if (old_state_is_stopped != new_state_is_stopped) {
1476 if (new_state_is_stopped)
1482 if (state_changed) {
1503 if (!
m_mod_id.IsLastResumeForUserExpression())
1504 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1507 LLDB_LOGF(log,
"(plugin = %s, state = %s, stop_id = %u",
1514 LLDB_LOGF(log,
"(plugin = %s, state = %s) state didn't change. Ignoring...",
1520 m_mod_id.SetRunningUserExpression(on);
1524 m_mod_id.SetRunningUtilityFunction(on);
1536 std::vector<LanguageRuntime *> language_runtimes;
1539 return language_runtimes;
1549 language_runtimes.emplace_back(runtime);
1552 return language_runtimes;
1562 LanguageRuntimeCollection::iterator pos;
1569 runtime = runtime_sp.get();
1571 runtime = pos->second.get();
1597 if (runtime->CouldHaveDynamicValue(in_value))
1627 if (
error.Success())
1642 "invalid breakpoint site ID: %" PRIu64, break_id);
1650 bool forbid_delay) {
1658 "eager breakpoint requested, but failed to flush breakpoints: {0}");
1660 auto site_sp = site.shared_from_this();
1665 return llvm::Error::success();
1669 return llvm::Error::success();
1682 llvm_unreachable(
"Unhandled BreakpointAction");
1694 "invalid breakpoint site ID: %" PRIu64, break_id);
1734 llvm_unreachable(
"unhandled process state");
1760 "warning: failed to resolve indirect function at 0x%" PRIx64
1761 " for breakpoint %i.%i: %s\n",
1763 constituent.
GetID(),
1764 error.AsCString() ?
error.AsCString() :
"unknown error");
1770 Address resolved_address(load_addr);
1794 llvm::Error
error = llvm::Error::success();
1795 for (
auto [site, action] : site_to_action) {
1806 bool use_hardware) {
1816 bp_site_sp->AddConstituent(constituent);
1817 constituent->SetBreakpointSite(bp_site_sp);
1818 return bp_site_sp->GetID();
1824 bool bp_from_address =
1825 constituent->GetBreakpoint().GetResolver()->GetResolverTy() ==
1827 bool forbid_delay = use_hardware || bp_from_address;
1831 if (
error.Success()) {
1832 constituent->SetBreakpointSite(bp_site_sp);
1839 "warning: failed to set breakpoint site at 0x%" PRIx64
1840 " for breakpoint %i.%i: %s\n",
1841 load_addr, constituent->GetBreakpoint().GetID(), constituent->GetID(),
1842 error.AsCString() ?
error.AsCString() :
"unknown error");
1850 uint32_t num_constituents =
1851 bp_site_sp->RemoveConstituent(constituent_id, constituent_loc_id);
1852 if (num_constituents == 0) {
1862 uint8_t *buf)
const {
1868 bp_sites_in_range.
ForEach([bp_addr, size,
1872 size_t intersect_size;
1873 size_t opcode_offset;
1875 &intersect_size, &opcode_offset)) {
1876 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1877 assert(bp_addr < intersect_addr + intersect_size &&
1878 intersect_addr + intersect_size <= bp_addr + size);
1879 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1880 size_t buf_offset = intersect_addr - bp_addr;
1881 ::memcpy(buf + buf_offset,
1891 if (!data_buffer_sp || data_buffer_sp->GetByteSize() == 0)
1895 data_buffer_sp->GetBytes());
1902 return platform_sp->GetSoftwareBreakpointTrapOpcode(
GetTarget(), bp_site);
1908 assert(bp_site !=
nullptr);
1912 log,
"Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
1913 bp_site->
GetID(), (uint64_t)bp_addr);
1917 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1918 " -- already enabled",
1919 bp_site->
GetID(), (uint64_t)bp_addr);
1925 "BreakpointSite contains an invalid load address.");
1932 if (bp_opcode_size == 0) {
1934 "Process::GetSoftwareBreakpointTrapOpcode() "
1935 "returned zero, unable to get breakpoint "
1936 "trap for address 0x%" PRIx64,
1941 if (bp_opcode_bytes ==
nullptr) {
1943 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1949 error) == bp_opcode_size) {
1953 uint8_t verify_bp_opcode_bytes[64];
1954 if (
DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
1955 error) == bp_opcode_size) {
1956 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
1957 bp_opcode_size) == 0) {
1961 "Process::EnableSoftwareBreakpoint (site_id = %d) "
1962 "addr = 0x%" PRIx64
" -- SUCCESS",
1963 bp_site->
GetID(), (uint64_t)bp_addr);
1966 "failed to verify the breakpoint trap in memory.");
1969 "Unable to read memory to verify breakpoint trap.");
1972 "Unable to write breakpoint trap to memory.");
1975 "Unable to read memory at breakpoint address.");
1977 if (log &&
error.Fail())
1980 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1982 bp_site->
GetID(), (uint64_t)bp_addr,
error.AsCString());
1988 assert(bp_site !=
nullptr);
1993 "Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
1994 ") addr = 0x%" PRIx64,
1995 breakID, (uint64_t)bp_addr);
2001 const size_t break_op_size = bp_site->
GetByteSize();
2003 if (break_op_size > 0) {
2005 uint8_t curr_break_op[8];
2006 assert(break_op_size <=
sizeof(curr_break_op));
2007 bool break_op_found =
false;
2012 bool verify =
false;
2014 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
2015 break_op_found =
true;
2019 break_op_size,
error) == break_op_size) {
2023 "Memory write failed when restoring original opcode.");
2026 "Original breakpoint trap is no longer in memory.");
2033 uint8_t verify_opcode[8];
2034 assert(break_op_size <
sizeof(verify_opcode));
2040 break_op_size) == 0) {
2044 "Process::DisableSoftwareBreakpoint (site_id = %d) "
2045 "addr = 0x%" PRIx64
" -- SUCCESS",
2046 bp_site->
GetID(), (uint64_t)bp_addr);
2051 "Failed to restore original opcode.");
2056 "breakpoint trap was restored.");
2060 "Unable to read memory that should contain the breakpoint trap.");
2065 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2066 " -- already disabled",
2067 bp_site->
GetID(), (uint64_t)bp_addr);
2073 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2075 bp_site->
GetID(), (uint64_t)bp_addr,
error.AsCString());
2081 size_t cache_bytes_read,
size_t size,
2082 const Status &cache_error) {
2085 const bool truncated = cache_error.
Fail();
2087 std::vector<uint8_t> verify_buf(size, 0);
2090 addr, verify_buf.data(), verify_buf.size(), verify_error);
2091 const size_t comparable = std::min(cache_bytes_read, verify_bytes_read);
2093 const char *mismatch =
nullptr;
2094 if (!truncated && cache_bytes_read != verify_bytes_read)
2095 mismatch =
"byte count";
2096 else if (memcmp(cache_buf, verify_buf.data(), comparable) != 0)
2097 mismatch =
"contents";
2098 else if (!truncated && cache_error.
Success() != verify_error.
Success())
2099 mismatch =
"status";
2105 "memory cache verification failed on {0}: read of {1} bytes at "
2106 "{2:x} returned {3} bytes ({4}) from the cache and {5} bytes ({6}) "
2108 mismatch, size, addr, cache_bytes_read, cache_error,
2109 verify_bytes_read, verify_error);
2110 assert(
false &&
"memory cache returned something the process did not");
2120 llvm::Expected<AddressSpaceInfo> info =
2145llvm::SmallVector<llvm::MutableArrayRef<uint8_t>>
2147 llvm::MutableArrayRef<uint8_t> buffer) {
2148 llvm::SmallVector<Range<lldb::addr_t, size_t>> fixed_ranges;
2149 fixed_ranges.reserve(ranges.size());
2151 fixed_ranges.emplace_back(
FixAnyAddress(range.GetRangeBase()),
2152 range.GetByteSize());
2156 llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> results =
2160 for (
auto [range, result] : llvm::zip(fixed_ranges, results)) {
2161 if (!result.empty()) {
2164 range.GetByteSize(),
error);
2172llvm::SmallVector<llvm::MutableArrayRef<uint8_t>>
2174 llvm::MutableArrayRef<uint8_t> buffer) {
2175 auto total_ranges_len = llvm::sum_of(
2176 llvm::map_range(ranges, [](
auto range) {
return range.size; }));
2180 assert(buffer.size() >= total_ranges_len &&
2181 "Process::DoReadMemoryRanges: provided buffer is too short");
2182 if (buffer.size() < total_ranges_len) {
2183 llvm::MutableArrayRef<uint8_t> empty;
2184 return {ranges.size(), empty};
2187 llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> results;
2191 for (
auto [addr, range_len] : ranges) {
2193 size_t num_bytes_read =
2200 assert(num_bytes_read <= range_len &&
"read more than requested bytes");
2201 if (num_bytes_read > range_len) {
2204 results.emplace_back();
2208 results.push_back(buffer.take_front(num_bytes_read));
2210 buffer = buffer.drop_front(num_bytes_read);
2217 const uint8_t *buf,
size_t size,
2219 size_t max_matches) {
2221 assert(buf !=
nullptr);
2223 assert(alignment > 0);
2224 assert(max_matches > 0);
2227 assert(start_addr < end_addr);
2229 lldb::addr_t start = llvm::alignTo(start_addr, alignment);
2230 while (matches.size() < max_matches && (start + size) < end_addr) {
2235 if (found_addr % alignment) {
2238 start = llvm::alignTo(start + 1, alignment);
2242 matches.emplace_back(found_addr, size);
2243 start = found_addr + alignment;
2249 size_t alignment,
size_t max_matches,
2252 if (buf ==
nullptr) {
2260 if (ranges.empty()) {
2264 if (alignment == 0) {
2268 if (max_matches == 0) {
2273 int resolved_ranges = 0;
2275 for (
size_t i = 0; i < ranges.size(); ++i) {
2276 if (matches.size() >= max_matches)
2289 DoFindInMemory(start_addr, end_addr, buf, size, matches, alignment,
2293 if (resolved_ranges > 0)
2304 if (buf ==
nullptr) {
2316 if (alignment == 0) {
2331 DoFindInMemory(start_addr, end_addr, buf, size, matches, alignment, 1);
2332 if (matches.empty())
2336 return matches[0].GetBaseAddress().GetLoadAddress(&target);
2339llvm::SmallVector<std::optional<std::string>>
2341 llvm::SmallVector<std::optional<std::string>> output_strs(addresses.size(),
2343 llvm::SmallVector<Range<addr_t, size_t>> ranges{
2344 llvm::map_range(addresses, [=](
addr_t ptr) {
2349 uint64_t num_completed_strings = 0;
2351 while (num_completed_strings != addresses.size()) {
2352 llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> read_results =
2358 for (
auto [range, read_result, output_str] :
2359 llvm::zip(ranges, read_results, output_strs)) {
2361 if (range.GetByteSize() == 0)
2365 if (read_result.empty()) {
2366 output_str = std::nullopt;
2367 range.SetByteSize(0);
2368 num_completed_strings++;
2373 auto read_result_str = llvm::toStringRef(read_result);
2375 const char *null_terminator_pos = llvm::find(read_result_str,
'\0');
2376 output_str->append(read_result_str.begin(), null_terminator_pos);
2379 if (null_terminator_pos != read_result_str.end()) {
2380 range.SetByteSize(0);
2381 num_completed_strings++;
2385 range.SetRangeBase(range.GetRangeBase() + read_result.size());
2402 out_str.append(buf, length);
2405 if (length ==
sizeof(buf) - 1)
2406 curr_addr += length;
2410 return out_str.size();
2418 size_t total_cstr_len = 0;
2419 if (dst && dst_max_len) {
2420 result_error.
Clear();
2422 memset(dst, 0, dst_max_len);
2424 const size_t cache_line_size =
m_memory_cache.GetMemoryCacheLineSize();
2425 size_t bytes_left = dst_max_len - 1;
2426 char *curr_dst = dst;
2428 while (bytes_left > 0) {
2429 addr_t cache_line_bytes_left =
2430 cache_line_size - (curr_addr % cache_line_size);
2432 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2434 size_t bytes_read =
ReadMemory(curr_addr, curr_dst, bytes_to_read,
error);
2436 if (bytes_read == 0) {
2437 result_error = std::move(
error);
2438 dst[total_cstr_len] =
'\0';
2441 const size_t len = strlen(curr_dst);
2443 total_cstr_len += len;
2445 if (len < bytes_to_read)
2448 curr_dst += bytes_read;
2449 curr_addr += bytes_read;
2450 bytes_left -= bytes_read;
2456 result_error.
Clear();
2458 return total_cstr_len;
2466 addr = abi_sp->FixAnyAddress(addr);
2468 if (buf ==
nullptr || size == 0)
2471 size_t bytes_read = 0;
2472 uint8_t *bytes = (uint8_t *)buf;
2474 while (bytes_read < size) {
2475 const size_t curr_size = size - bytes_read;
2476 const size_t curr_bytes_read =
2478 bytes_read += curr_bytes_read;
2479 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2491 size_t integer_byte_size,
2492 uint64_t fail_value,
2501llvm::SmallVector<std::optional<uint64_t>>
2503 unsigned integer_byte_size) {
2504 if (addresses.empty())
2508 if (!llvm::is_contained({1u, 2u, 4u, 8u}, integer_byte_size))
2509 return llvm::SmallVector<std::optional<uint64_t>>(addresses.size(),
2512 llvm::SmallVector<Range<addr_t, size_t>> ranges{
2513 llvm::map_range(addresses, [=](
addr_t ptr) {
2517 std::vector<uint8_t> buffer(integer_byte_size * addresses.size(), 0);
2518 llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> memory =
2521 llvm::SmallVector<std::optional<uint64_t>> result;
2522 result.reserve(addresses.size());
2526 for (llvm::MutableArrayRef<uint8_t> range : memory) {
2527 if (range.size() != integer_byte_size) {
2528 result.push_back(std::nullopt);
2532 DataExtractor data(range.data(), integer_byte_size, byte_order, addr_size);
2534 result.push_back(data.
GetMaxU64(&offset, integer_byte_size));
2535 assert(offset == integer_byte_size);
2541 size_t integer_byte_size,
2557 "a successful read always yields an integer");
2561 return error.ToError();
2562 return llvm::createStringError(
2563 "failed to read pointer from memory at 0x%" PRIx64, vm_addr);
2566llvm::SmallVector<std::optional<addr_t>>
2576 if (addr_byte_size <= 4)
2577 scalar = (uint32_t)ptr_value;
2586 size_t bytes_written = 0;
2587 const uint8_t *bytes = (
const uint8_t *)buf;
2589 while (bytes_written < size) {
2590 const size_t curr_size = size - bytes_written;
2592 addr + bytes_written, bytes + bytes_written, curr_size,
error);
2593 bytes_written += curr_bytes_written;
2594 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2597 return bytes_written;
2603 addr = abi_sp->FixAnyAddress(addr);
2607 if (buf ==
nullptr || size == 0)
2621 const uint8_t *ubuf = (
const uint8_t *)buf;
2622 uint64_t bytes_written = 0;
2624 bp_sites_in_range.
ForEach([
this, addr, size, &bytes_written, &ubuf,
2633 size_t intersect_size;
2634 size_t opcode_offset;
2636 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2639 assert(addr <= intersect_addr && intersect_addr < addr + size);
2640 assert(addr < intersect_addr + intersect_size &&
2641 intersect_addr + intersect_size <= addr + size);
2642 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2645 const addr_t curr_addr = addr + bytes_written;
2646 if (intersect_addr > curr_addr) {
2649 size_t curr_size = intersect_addr - curr_addr;
2650 size_t curr_bytes_written =
2652 bytes_written += curr_bytes_written;
2653 if (curr_bytes_written != curr_size) {
2657 if (
error.Success())
2665 bytes_written += intersect_size;
2669 if (bytes_written < size)
2672 size - bytes_written,
error);
2674 return bytes_written;
2681 if (byte_size > 0) {
2683 const size_t mem_size =
2696 bool is_signed,
Scalar &scalar,
2699 if (byte_size == 0) {
2701 }
else if (byte_size & (byte_size - 1)) {
2703 "byte size %u is not a power of 2", byte_size);
2704 }
else if (byte_size <=
sizeof(uval)) {
2706 if (bytes_read == byte_size) {
2711 scalar = data.
GetMaxU32(&offset, byte_size);
2713 scalar = data.
GetMaxU64(&offset, byte_size);
2722 "byte size of %u is too large for integer scalar type", byte_size);
2729 for (
const auto &
Entry : entries) {
2732 if (!
error.Success())
2742 "cannot allocate memory while process is running");
2750 return alloced_addr;
2756 if (
error.Success()) {
2757 std::string buffer(size, 0);
2767 LLDB_LOGF(log,
"Process::%s pid %" PRIu64
" CanJIT () is %s", __FUNCTION__,
2788 "deallocation of memory at 0x%" PRIx64
" failed.", (uint64_t)ptr);
2795 return *subclass_override;
2797 bool reported_after =
true;
2800 return reported_after;
2803 if (triple.isMIPS() || triple.isPPC64() || triple.isRISCV() ||
2804 triple.isAArch64() || triple.isArmMClass() || triple.isARM() ||
2805 triple.isLoongArch())
2806 reported_after =
false;
2808 return reported_after;
2811llvm::Expected<ModuleSP>
2815 "Process::ReadModuleFromMemory reading %s binary from memory",
2819 return llvm::createStringError(
"failed to allocate module");
2822 std::unique_ptr<Progress> progress_up;
2823 bool disable_memory_symtab_caching;
2828 progress_up = std::make_unique<Progress>(
"Reading binary from memory",
2831 disable_memory_symtab_caching =
false;
2834 disable_memory_symtab_caching =
true;
2837 if (module_sp->GetMemoryObjectFile(shared_from_this(), header_addr,
error,
2838 disable_memory_symtab_caching,
2842 return error.takeError();
2846 uint32_t &permissions) {
2850 if (!
error.Success())
2908 LaunchPrivate(launch_info, state_after_launch, first_stop_event_sp);
2937 if (launch_info.
GetFlags().
Test(eLaunchFlagStopAtEntry))
2996 std::string local_exec_file_path = exe_spec_to_use.
GetPath();
2998 local_exec_file_path.c_str());
3001 const bool restarted =
false;
3011 const char *error_string =
error.AsCString();
3012 if (error_string ==
nullptr)
3013 error_string =
"launch failed";
3068 "Unexpected process state after the launch: %s, expected %s, "
3078 if (
error.Success()) {
3121 LLDB_LOGF(log,
"Process::Halt() failed to stop, state is: %s",
3124 "Did not get stopped event after loading the core file.");
3165 uint32_t exec_count)
3170 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
3171 __FUNCTION__,
static_cast<void *
>(process), exec_count);
3180 "Process::AttachCompletionHandler::%s called with state %s (%d)",
3204 "Process::AttachCompletionHandler::%s state %s: reduced "
3205 "remaining exec count to %" PRIu32
", requesting resume",
3212 "Process::AttachCompletionHandler::%s state %s: no more "
3213 "execs expected to start, continuing with attach",
3256 bool wait_for_launch) {
3274 auto start_private_state_thread = [
this] {
3289 sizeof(process_name))) {
3292 if (wait_for_launch) {
3294 if (
error.Success()) {
3302 if (
error.AsCString() ==
nullptr)
3310 start_private_state_thread();
3316 "could not start private state thread.");
3329 platform_sp->FindProcesses(match_info, process_infos);
3330 const uint32_t num_matches = process_infos.size();
3331 if (num_matches == 1) {
3332 attach_pid = process_infos[0].GetProcessID();
3336 process_name,
sizeof(process_name));
3337 if (num_matches > 1) {
3340 for (
size_t i = 0; i < num_matches; i++) {
3341 process_infos[i].DumpAsTableRow(
3342 s, platform_sp->GetUserIDResolver(),
true,
false);
3345 "more than one process named %s:\n%s", process_name,
3349 "could not find a process named %s", process_name);
3353 "invalid platform, can't find processes by name");
3364 if (
error.Success()) {
3369 if (
error.Success()) {
3373 start_private_state_thread();
3379 "could not start private state thread.");
3385 const char *error_string =
error.AsCString();
3386 if (error_string ==
nullptr)
3387 error_string =
"attach failed";
3398 LLDB_LOGF(log,
"Process::%s()", __FUNCTION__);
3407 "Process::{0} replacing process architecture with DidAttach() "
3408 "architecture: \"{1}\"",
3409 __FUNCTION__, process_arch.
GetTriple().getTriple());
3417 assert(platform_sp);
3421 if (target_arch.
IsValid() && !platform_sp->IsCompatibleArchitecture(
3422 target_arch, process_host_arch,
3426 target_arch, process_host_arch, &platform_arch);
3431 "switching platform to {0} and architecture to {1} based on "
3433 platform_sp->GetName(), platform_arch.
GetTriple().getTriple());
3435 }
else if (!process_arch.
IsValid()) {
3445 "Process::%s switching architecture to %s based on info "
3446 "the platform retrieved for pid %" PRIu64,
3447 __FUNCTION__, process_arch.
GetTriple().getTriple().c_str(),
3466 "after DynamicLoader::DidAttach(), target "
3467 "executable is {0} (using {1} plugin)",
3468 exe_module_sp ? exe_module_sp->GetFileSpec() :
FileSpec(),
3476 if (system_runtime) {
3481 "after SystemRuntime::DidAttach(), target "
3482 "executable is {0} (using {1} plugin)",
3483 exe_module_sp ? exe_module_sp->GetFileSpec() :
FileSpec(),
3504 if (module_sp && module_sp->IsExecutable()) {
3505 if (
GetTarget().GetExecutableModulePointer() != module_sp.get())
3506 new_executable_module_sp = module_sp;
3510 if (new_executable_module_sp) {
3513 if (
GetTarget().GetExecutableModulePointer())
3522 "Process::%s after looping through modules, target executable is %s",
3524 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3544 if (
error.Success()) {
3587 "Process::PrivateResume() m_stop_id = %u, public state: %s "
3588 "private state: %s",
3597 if (!
GetModID().IsLastResumeForUserExpression())
3602 if (
error.Success()) {
3612 LLDB_LOGF(log,
"Process::PrivateResume WillResume direction=%d",
3617 "Process::PrivateResume PreResumeActions failed, not resuming.");
3620 "Process::PrivateResume PreResumeActions failed, not resuming.");
3625 "Failed to update some delayed breakpoints: {0}");
3627 if (
error.Success()) {
3631 "Process::PrivateResume thinks the process has resumed.");
3633 LLDB_LOGF(log,
"Process::PrivateResume() DoResume failed.");
3643 "Process::PrivateResume() asked to simulate a start & stop.");
3649 LLDB_LOGF(log,
"Process::PrivateResume() got an error \"%s\".",
3650 error.AsCString(
"<unknown error>"));
3685 halt_listener_sp,
nullptr,
3686 use_run_lock, select_most_relevant);
3701 const uint8_t *buf,
size_t size) {
3702 const size_t region_size = high - low;
3704 if (region_size < size)
3708 std::vector<size_t> bad_char_heuristic(256, size);
3709 for (
size_t idx = 0; idx < size - 1; idx++) {
3710 decltype(bad_char_heuristic)::size_type bcu_idx = buf[idx];
3711 bad_char_heuristic[bcu_idx] = size - idx - 1;
3715 llvm::SmallVector<uint8_t, 0> mem;
3720 const size_t max_read_size = std::max<size_t>(size, 0x10000);
3722 for (
addr_t cur_addr = low; cur_addr <= (high - size);) {
3723 if (cur_addr + size > mem_pos + mem.size()) {
3729 mem.resize_for_overwrite(max_read_size);
3732 std::min<addr_t>(mem.size(), high - cur_addr),
3735 if (size > mem.size()) {
3745 int64_t j = size - 1;
3746 while (j >= 0 && buf[j] == mem[cur_addr + j - mem_pos])
3750 cur_addr += bad_char_heuristic[mem[cur_addr + size - 1 - mem_pos]];
3764 LLDB_LOGF(log,
"Process::%s() About to stop.", __FUNCTION__);
3774 &exit_event_sp,
true, listener_sp);
3784 LLDB_LOGF(log,
"Process::%s() Process exited while waiting to stop.",
3788 exit_event_sp.reset();
3791 LLDB_LOGF(log,
"Process::%s() failed to stop, state is: %s", __FUNCTION__,
3799 "Attempt to stop the target in order to detach timed out. "
3815 if (
error.Success()) {
3818 if (!
error.Success()) {
3821 }
else if (exit_event_sp) {
3835 "Failed to update some delayed breakpoints during detach: {0}");
3838 if (
error.Success()) {
3849 if (exit_event_sp) {
3884 bool keep_stopped =
false;
3891 if (
error.Success()) {
3908 "Failed to update some delayed breakpoints during destroy: {0}");
3912 if (
error.Success()) {
3931 if (exit_event_sp) {
3951 if (
error.Success()) {
3953 if (
error.Success())
3960 assert(signals_sp &&
"null signals_sp");
3980 bool return_value =
true;
3997 return_value =
true;
4001 return_value =
false;
4013 return_value =
true;
4019 return_value =
false;
4032 return_value =
true;
4035 return_value =
false;
4054 "Process::ShouldBroadcastEvent (%p) stopped due to an "
4055 "interrupt, state: %s",
4060 return_value =
true;
4063 bool should_resume =
false;
4075 "Process::ShouldBroadcastEvent: should_resume: %i state: "
4076 "%s was_restarted: %i report_stop_vote: %d.",
4080 switch (report_stop_vote) {
4082 return_value =
true;
4086 return_value =
false;
4090 if (!was_restarted) {
4092 "Process::ShouldBroadcastEvent (%p) Restarting process "
4099 return_value =
true;
4122 "Process::ShouldBroadcastEvent (%p) => new state: %s, last "
4123 "broadcast state: %s - %s",
4126 return_value ?
"YES" :
"NO");
4127 return return_value;
4131 llvm::Expected<HostThread> private_state_thread =
4136 if (!private_state_thread) {
4138 "failed to launch host thread: {0}");
4142 assert(private_state_thread->IsJoinable());
4162 std::shared_ptr<PrivateStateThread> *backup_ptr) {
4166 LLDB_LOGF(log,
"Process::%s()%s ", __FUNCTION__,
4167 already_running ?
" already running"
4168 :
" starting private state thread");
4170 if (backup_ptr ==
nullptr && already_running)
4175 char thread_name[1024];
4176 uint32_t max_len = llvm::get_max_thread_name_length();
4177 if (max_len > 0 && max_len <= 30) {
4180 if (already_running)
4181 snprintf(thread_name,
sizeof(thread_name),
"intern-state-OV");
4183 snprintf(thread_name,
sizeof(thread_name),
"intern-state");
4185 if (already_running)
4186 snprintf(thread_name,
sizeof(thread_name),
4187 "<lldb.process.internal-state-override(pid=%" PRIu64
")>",
4190 snprintf(thread_name,
sizeof(thread_name),
4191 "<lldb.process.internal-state(pid=%" PRIu64
")>",
GetID());
4200 PrivateStateThread::Purpose::RunningExpression));
4205 if (run_lock_is_running)
4231 "Went to stop the private state thread, but it was already invalid.");
4242 LLDB_LOGF(log,
"Process::%s (signal = %d)", __FUNCTION__, signal);
4251 LLDB_LOGF(log,
"Sending control event of type: %d.", signal);
4252 std::shared_ptr<EventDataReceipt> event_receipt_sp(
new EventDataReceipt());
4257 bool receipt_received =
false;
4259 while (!receipt_received) {
4264 if (!receipt_received) {
4279 "Private state thread already dead, no need to signal it to stop.");
4284 if (thread !=
nullptr)
4302#ifdef LLDB_SIMULATE_SLOW_STOPS
4309 std::this_thread::sleep_for(std::chrono::milliseconds(10));
4316 LLDB_LOGF(log,
"Ran next event action, result was %d.", action_result);
4318 switch (action_result) {
4344 if (should_broadcast) {
4347 "Process::%s (pid = %" PRIu64
4348 ") broadcasting new state %s (old state %s) to %s",
4356 if (!
GetTarget().GetDebugger().IsForwardingEvents() &&
4361 LLDB_LOGF(log,
"Process::%s updated m_iohandler_sync to %d",
4395 if (is_hijacked || !
GetTarget().GetDebugger().IsHandlingEvents())
4404 "Process::%s (pid = %" PRIu64
4405 ") suppressing state %s (old state %s): should_broadcast == false",
4434 bool control_only =
true;
4437 LLDB_LOGF(log,
"Process::%s (arg = %p, pid = %" PRIu64
") thread starting...",
4438 __FUNCTION__,
static_cast<void *
>(
this),
GetID());
4440 bool exit_now =
false;
4441 bool interrupt_requested =
false;
4447 "Process::%s (arg = %p, pid = %" PRIu64
4448 ") got a control event: %d",
4449 __FUNCTION__,
static_cast<void *
>(
this),
GetID(),
4450 event_sp->GetType());
4452 switch (event_sp->GetType()) {
4458 control_only =
true;
4462 control_only =
false;
4470 "Process::%s (arg = %p, pid = %" PRIu64
4471 ") woke up with an interrupt while attaching - "
4472 "forwarding interrupt.",
4473 __FUNCTION__,
static_cast<void *
>(
this),
GetID());
4484 "Process::%s (arg = %p, pid = %" PRIu64
4485 ") woke up with an interrupt - Halting.",
4486 __FUNCTION__,
static_cast<void *
>(
this),
GetID());
4488 if (
error.Fail() && log)
4490 "Process::%s (arg = %p, pid = %" PRIu64
4491 ") failed to halt the process: %s",
4492 __FUNCTION__,
static_cast<void *
>(
this),
GetID(),
4499 interrupt_requested =
true;
4508 "Process::%s ignoring interrupt as we have already stopped.",
4524 if (interrupt_requested) {
4534 interrupt_requested =
false;
4537 "Process::%s interrupt_requested, but a non-stopped "
4538 "state '%s' received.",
4549 "Process::%s (arg = %p, pid = %" PRIu64
4550 ") about to exit with internal state %s...",
4551 __FUNCTION__,
static_cast<void *
>(
this),
GetID(),
4559 LLDB_LOGF(log,
"Process::%s (arg = %p, pid = %" PRIu64
") thread exiting...",
4560 __FUNCTION__,
static_cast<void *
>(
this),
GetID());
4580 return "Process::ProcessEventData";
4588 bool &found_valid_stopinfo) {
4589 found_valid_stopinfo =
false;
4595 ThreadList &curr_thread_list = process_sp->GetThreadList();
4596 uint32_t num_threads = curr_thread_list.
GetSize();
4608 std::vector<std::pair<ThreadSP, size_t>> not_suspended_threads;
4609 for (uint32_t idx = 0; idx < num_threads; ++idx) {
4617 not_suspended_threads.emplace_back(thread_sp, thread_sp->GetIndexID());
4625 bool still_should_stop =
false;
4633 for (
auto [thread_sp, thread_index] : not_suspended_threads) {
4634 if (curr_thread_list.
GetSize() != num_threads) {
4638 "Number of threads changed from %u to %u while processing event.",
4639 num_threads, curr_thread_list.
GetSize());
4643 if (thread_sp->GetIndexID() != thread_index) {
4646 "The thread {0} changed from {1} to {2} while processing event.",
4647 thread_sp.get(), thread_index, thread_sp->GetIndexID());
4651 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4652 if (stop_info_sp && stop_info_sp->IsValid()) {
4653 found_valid_stopinfo =
true;
4654 bool this_thread_wants_to_stop;
4655 if (stop_info_sp->GetOverrideShouldStop()) {
4656 this_thread_wants_to_stop =
4657 stop_info_sp->GetOverriddenShouldStopValue();
4659 stop_info_sp->PerformAction(event_ptr);
4672 thread_sp->ClearSelectedFrameIndex();
4675 if (stop_info_sp->HasTargetRunSinceMe()) {
4680 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
4683 if (!still_should_stop)
4684 still_should_stop = this_thread_wants_to_stop;
4688 return still_should_stop;
4728 process_sp->SetPublicState(
4735 process_sp->WillPublicStop();
4750 bool does_anybody_have_an_opinion =
false;
4751 bool still_should_stop =
ShouldStop(event_ptr, does_anybody_have_an_opinion);
4757 if (!still_should_stop && does_anybody_have_an_opinion) {
4762 process_sp->PrivateResume();
4765 !process_sp->StateChangedIsHijackedForSynchronousResume();
4773 if (process_sp->GetTarget().RunStopHooks())
4783 s->
Printf(
" process = %p (pid = %" PRIu64
"), ",
4784 static_cast<void *
>(process_sp.get()), process_sp->GetID());
4813 if (data ==
nullptr)
4821 if (data ==
nullptr)
4831 if (data !=
nullptr)
4839 if (data !=
nullptr)
4850 if (data !=
nullptr)
4857 const char *reason) {
4860 if (data !=
nullptr)
4865 const Event *event_ptr) {
4867 if (data ==
nullptr)
4877 if (data !=
nullptr)
4920 auto event_data_sp =
4921 std::make_shared<ProcessEventData>(shared_from_this(),
GetState());
4922 return std::make_shared<Event>(event_type, event_data_sp);
4948 auto data_sp = std::make_shared<EventDataStructuredData>(
4949 shared_from_this(), object_sp, plugin_sp);
4957 return find_it->second;
4968 size_t bytes_available = one_profile_data.size();
4969 if (bytes_available > 0) {
4971 LLDB_LOGF(log,
"Process::GetProfileData (buf = %p, size = %" PRIu64
")",
4972 static_cast<void *
>(buf),
static_cast<uint64_t
>(buf_size));
4973 if (bytes_available > buf_size) {
4974 memcpy(buf, one_profile_data.c_str(), buf_size);
4975 one_profile_data.erase(0, buf_size);
4976 bytes_available = buf_size;
4978 memcpy(buf, one_profile_data.c_str(), bytes_available);
4982 return bytes_available;
4990 if (bytes_available > 0) {
4992 LLDB_LOGF(log,
"Process::GetSTDOUT (buf = %p, size = %" PRIu64
")",
4993 static_cast<void *
>(buf),
static_cast<uint64_t
>(buf_size));
4994 if (bytes_available > buf_size) {
4997 bytes_available = buf_size;
5003 return bytes_available;
5009 if (bytes_available > 0) {
5011 LLDB_LOGF(log,
"Process::GetSTDERR (buf = %p, size = %" PRIu64
")",
5012 static_cast<void *
>(buf),
static_cast<uint64_t
>(buf_size));
5013 if (bytes_available > buf_size) {
5016 bytes_available = buf_size;
5022 return bytes_available;
5028 process->
AppendSTDOUT(
static_cast<const char *
>(src), src_len);
5034 assert(!*stdio_secondary_fd &&
"process stdio is already set up");
5035 *stdio_secondary_fd = secondary_fd;
5040 std::make_unique<ConnectionFileDescriptor>(fd,
true));
5051 std::make_shared<IOHandlerProcessSTDIO>(
this, fd);
5065 "failed to open the secondary side of the inferior's "
5068 std::optional<int> secondary_fd;
5092 llvm::sys::Process::SafelyCloseFileDescriptor(*fd);
5106 if (io_handler_sp) {
5108 LLDB_LOGF(log,
"Process::%s pushing IO handler", __FUNCTION__);
5110 io_handler_sp->SetIsDone(
false);
5115 bool cancel_top_handler = !
m_mod_id.IsRunningUtilityFunction();
5117 cancel_top_handler);
5143class RestorePlanState {
5146 : m_thread_plan_sp(thread_plan_sp) {
5147 if (m_thread_plan_sp) {
5148 m_private = m_thread_plan_sp->GetPrivate();
5149 m_is_controlling = m_thread_plan_sp->IsControllingPlan();
5150 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
5154 ~RestorePlanState() { Clean(); }
5157 if (!m_already_reset && m_thread_plan_sp) {
5158 m_already_reset =
true;
5159 m_thread_plan_sp->SetPrivate(m_private);
5160 m_thread_plan_sp->SetIsControllingPlan(m_is_controlling);
5161 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
5167 bool m_already_reset =
false;
5168 bool m_private =
false;
5169 bool m_is_controlling =
false;
5170 bool m_okay_to_discard =
false;
5176 const milliseconds default_one_thread_timeout(250);
5181 : default_one_thread_timeout;
5190 return std::min<microseconds>(default_one_thread_timeout,
5194static Timeout<std::micro>
5196 bool before_first_timeout) {
5202 if (before_first_timeout)
5206 return std::nullopt;
5211static std::optional<ExpressionResults>
5213 RestorePlanState &restorer,
const EventSP &event_sp,
5214 EventSP &event_to_broadcast_sp,
5216 bool handle_interrupts) {
5219 ThreadSP thread_sp = thread_plan_sp->GetTarget()
5222 .FindThreadByID(thread_id);
5225 "The thread on which we were running the "
5226 "expression: tid = {0}, exited while "
5227 "the expression was running.",
5233 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
5234 LLDB_LOG(log,
"execution completed successfully");
5242 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5244 stop_info_sp->ShouldNotify(event_sp.get())) {
5245 LLDB_LOG(log,
"stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
5252 thread_plan_sp->SetPrivate(
false);
5253 event_to_broadcast_sp = event_sp;
5258 if (!handle_interrupts &&
5260 return std::nullopt;
5262 LLDB_LOG(log,
"thread plan did not successfully complete");
5264 event_to_broadcast_sp = event_sp;
5277 if (!thread_plan_sp) {
5283 if (!thread_plan_sp->ValidatePlan(
nullptr)) {
5286 "RunThreadPlan called with an invalid thread plan.");
5292 "RunThreadPlan called on wrong process.");
5297 if (thread ==
nullptr) {
5299 "RunThreadPlan called with invalid thread.");
5317 "cannot run the process's other threads to evaluate this "
5318 "expression: the current context does not allow resuming them");
5326 "cannot retry this expression with the process's other threads "
5327 "running: the current context does not allow that fallback");
5335 RestorePlanState thread_plan_restorer(thread_plan_sp);
5342 thread_plan_sp->SetPrivate(
false);
5348 thread_plan_sp->SetIsControllingPlan(
true);
5349 thread_plan_sp->SetOkayToDiscard(
false);
5359 "RunThreadPlan called while the private state was not stopped.");
5364 const uint32_t thread_idx_id = thread->GetIndexID();
5367 if (!selected_frame_sp) {
5368 thread->SetSelectedFrame(
nullptr);
5370 if (!selected_frame_sp) {
5371 diagnostic_manager.
Printf(
5373 "RunThreadPlan called without a selected frame on thread %d",
5384 "RunThreadPlan called with one thread "
5385 "timeout greater than total timeout");
5395 : selected_frame_sp->GetStackID();
5403 uint32_t selected_tid;
5405 if (selected_thread_sp) {
5406 selected_tid = selected_thread_sp->GetIndexID();
5414 std::shared_ptr<PrivateStateThread> backup_private_state_thread;
5425 LLDB_LOGF(log,
"Running thread plan on private state thread, spinning up "
5426 "another state thread to handle the events.");
5436 thread->QueueThreadPlan(stopper_base_plan_sp,
false);
5444 &backup_private_state_thread);
5449 diagnostic_manager.
Printf(
5451 "could not spin up a thread to handle events for an expression"
5452 " run on the private state thread.");
5458 thread->QueueThreadPlan(
5459 thread_plan_sp,
false);
5492 "Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
5493 " to run thread plan \"%s\".",
5494 thread_idx_id, expr_thread_id, s.
GetData());
5501 bool before_first_timeout =
true;
5503 bool do_resume =
true;
5504 bool handle_running_event =
true;
5507 uint32_t num_resumes = 0;
5513 before_first_timeout =
false;
5515 LLDB_LOGF(log,
"Stop others: %u, try all: %u, before_first: %u.\n",
5517 before_first_timeout);
5524 Event *other_events = listener_sp->PeekAtNextEvent();
5525 if (other_events !=
nullptr) {
5528 "RunThreadPlan called with pending events on the queue.");
5541#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5549 bool miss_first_event =
true;
5551 bool pending_stop_on_vfork_done =
false;
5555 std::optional<PolicyStack::Guard> policy_guard;
5556 if (backup_private_state_thread)
5566 "Top of while loop: do_resume: %i handle_running_event: %i "
5567 "before_first_timeout: %i.",
5568 do_resume, handle_running_event, before_first_timeout);
5570 if (do_resume || handle_running_event) {
5577 if (!resume_error.
Success()) {
5578 diagnostic_manager.
Printf(
5580 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
5591 "Process::RunThreadPlan(): didn't get any event after "
5592 "resume %" PRIu32
", exiting.",
5596 "didn't get any event after resume %" PRIu32
5607 bool restarted =
false;
5614 "Process::RunThreadPlan(): didn't get running event after "
5615 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
5616 "handle_running_event: %i).",
5618 handle_running_event);
5625 const bool clear_thread_plans =
false;
5626 const bool use_run_lock =
false;
5627 Halt(clear_thread_plans, use_run_lock);
5631 "didn't get running event after initial "
5632 "resume, got %s instead.",
5639 log->
PutCString(
"Process::RunThreadPlan(): resuming succeeded.");
5647 log->
PutCString(
"Process::RunThreadPlan(): waiting for next event.");
5651 handle_running_event =
true;
5660 auto now = system_clock::now();
5662 "Process::RunThreadPlan(): about to wait - now is %s - "
5664 llvm::to_string(now).c_str(),
5665 llvm::to_string(now + *timeout).c_str());
5667 LLDB_LOGF(log,
"Process::RunThreadPlan(): about to wait forever.");
5671#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5673 if (miss_first_event) {
5674 std::this_thread::sleep_for(std::chrono::milliseconds(1));
5675 miss_first_event =
false;
5679 got_event = listener_sp->GetEvent(event_sp, timeout);
5683 bool keep_going =
false;
5685 const bool clear_thread_plans =
false;
5686 const bool use_run_lock =
false;
5687 Halt(clear_thread_plans, use_run_lock);
5690 "execution halted by user interrupt.");
5691 LLDB_LOGF(log,
"Process::RunThreadPlan(): Got interrupted by "
5692 "eBroadcastBitInterrupted, exiting.");
5698 "Process::RunThreadPlan(): in while loop, got event: %s.",
5701 switch (stop_state) {
5707 LLDB_LOGF(log,
"Process::RunThreadPlan(): Got a stop and "
5708 "restart, so we'll continue waiting.");
5711 handle_running_event =
true;
5716 bool handled_fork =
false;
5719 if (
StopInfoSP stop_info_sp = fork_thread_sp->GetStopInfo()) {
5720 StopReason reason = stop_info_sp->GetStopReason();
5724 handled_fork =
true;
5729 LLDB_LOGF(log,
"Process::RunThreadPlan(): stopped for "
5730 "fork, stop-on-fork is set.");
5741 "Process::RunThreadPlan(): got vfork with "
5742 "stop-on-fork, deferring stop to "
5744 pending_stop_on_vfork_done =
true;
5747 handle_running_event =
true;
5749 pending_stop_on_vfork_done) {
5754 LLDB_LOGF(log,
"Process::RunThreadPlan(): vfork cycle "
5755 "complete, stop-on-fork is set.");
5756 pending_stop_on_vfork_done =
false;
5759 LLDB_LOGF(log,
"Process::RunThreadPlan(): got fork "
5760 "event, continuing.");
5763 handle_running_event =
true;
5769 if (!handled_fork) {
5770 const bool handle_interrupts =
true;
5772 expr_thread_id, thread_plan_sp, thread_plan_restorer,
5773 event_sp, event_to_broadcast_sp, options,
5787 handle_running_event =
false;
5792 "Process::RunThreadPlan(): execution stopped with "
5793 "unexpected state: %s.",
5797 event_to_broadcast_sp = event_sp;
5801 "execution stopped with unexpected state.");
5813 log->
PutCString(
"Process::RunThreadPlan(): got_event was true, but "
5814 "the event pointer was null. How odd...");
5826 if (before_first_timeout) {
5828 "Running function with one thread timeout timed out.");
5830 LLDB_LOG(log,
"Restarting function with all threads enabled and "
5831 "timeout: {0} timed out, abandoning execution.",
5834 LLDB_LOG(log,
"Running function with timeout: {0} timed out, "
5835 "abandoning execution.",
5848 bool back_to_top =
true;
5849 uint32_t try_halt_again = 0;
5850 bool do_halt =
true;
5851 const uint32_t num_retries = 5;
5852 while (try_halt_again < num_retries) {
5855 LLDB_LOGF(log,
"Process::RunThreadPlan(): Running Halt.");
5856 const bool clear_thread_plans =
false;
5857 const bool use_run_lock =
false;
5858 Halt(clear_thread_plans, use_run_lock);
5862 log->
PutCString(
"Process::RunThreadPlan(): Halt succeeded.");
5872 "Process::RunThreadPlan(): Stopped with event: %s",
5877 log->
PutCString(
" Event was the Halt interruption event.");
5884 log->
PutCString(
"Process::RunThreadPlan(): Went to halt "
5885 "but got a restarted event, there must be "
5886 "an un-restarted stopped event so try "
5888 "Exiting wait loop.");
5897 const bool handle_interrupts =
false;
5899 expr_thread_id, thread_plan_sp, thread_plan_restorer,
5900 event_sp, event_to_broadcast_sp, options,
5901 handle_interrupts)) {
5902 return_value = *result;
5903 back_to_top =
false;
5909 log->
PutCString(
"Process::RunThreadPlan(): try_all_threads "
5910 "was false, we stopped so now we're "
5913 back_to_top =
false;
5917 if (before_first_timeout) {
5920 before_first_timeout =
false;
5921 thread_plan_sp->SetStopOthers(
false);
5924 "Process::RunThreadPlan(): about to resume.");
5931 log->
PutCString(
"Process::RunThreadPlan(): running all "
5932 "threads timed out.");
5934 back_to_top =
false;
5940 log->
PutCString(
"Process::RunThreadPlan(): halt said it "
5941 "succeeded, but I got no event. "
5942 "I'm getting out of here passing Interrupted.");
5944 back_to_top =
false;
5953 if (!back_to_top || try_halt_again > num_retries)
5960 policy_guard.reset();
5964 if (backup_private_state_thread &&
5965 backup_private_state_thread->IsJoinable()) {
5969 if (stopper_base_plan_sp) {
5970 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5980 return return_value;
5986 s.
PutCString(
"Thread state after unsuccessful completion: \n");
6001 thread_plan_sp->RestoreThreadState();
6012 log->
PutCString(
"Process::RunThreadPlan(): Stop event that "
6013 "interrupted us is NULL.");
6018 const char *event_explanation =
nullptr;
6022 event_explanation =
"<no event>";
6025 event_explanation =
"<user interrupt>";
6033 event_explanation =
"<no event data>";
6040 event_explanation =
"<no process>";
6046 uint32_t num_threads = thread_list.
GetSize();
6047 uint32_t thread_index;
6049 ts.
Printf(
"<%u threads> ", num_threads);
6051 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
6059 ts.
Printf(
"<0x%4.4" PRIx64
" ", thread->GetID());
6061 thread->GetRegisterContext().get();
6063 if (register_context)
6064 ts.
Printf(
"[ip 0x%" PRIx64
"] ", register_context->
GetPC());
6072 const char *stop_desc = stop_info_sp->GetDescription();
6079 event_explanation = ts.
GetData();
6083 if (event_explanation)
6085 "Process::RunThreadPlan(): execution interrupted: %s %s",
6086 s.
GetData(), event_explanation);
6088 LLDB_LOGF(log,
"Process::RunThreadPlan(): execution interrupted: %s",
6092 if (should_unwind) {
6094 "Process::RunThreadPlan: ExecutionInterrupted - "
6095 "discarding thread plans up to %p.",
6096 static_cast<void *
>(thread_plan_sp.get()));
6097 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
6100 "Process::RunThreadPlan: ExecutionInterrupted - for "
6101 "plan: %p not discarding.",
6102 static_cast<void *
>(thread_plan_sp.get()));
6106 log->
PutCString(
"Process::RunThreadPlan(): execution set up error.");
6109 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
6112 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
6114 log->
PutCString(
"Process::RunThreadPlan(): thread plan is done");
6116 }
else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
6119 "Process::RunThreadPlan(): thread plan was discarded");
6124 "Process::RunThreadPlan(): thread plan stopped in mid course");
6127 log->
PutCString(
"Process::RunThreadPlan(): discarding thread plan "
6128 "'cause unwind_on_error is set.");
6129 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
6139 exe_ctx.
SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
6146 if (
GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
6147 selected_stack_id.
IsValid()) {
6149 std::lock_guard<std::recursive_mutex> guard(
GetThreadList().GetMutex());
6155 old_frame_sp.get());
6162 if (event_to_broadcast_sp) {
6164 log->
PutCString(
"Process::RunThreadPlan(): rebroadcasting event.");
6168 return return_value;
6177 strm.
Printf(
"Process %" PRIu64
" exited with status = %i (0x%8.8x) %s\n",
6178 GetID(), exit_status, exit_status,
6179 exit_description ? exit_description :
"");
6182 strm.
PutCString(
"Connected to remote target.\n");
6186 core_args->Format(strm);
6190 strm.
Printf(
"Process %" PRIu64
" is running.\n",
GetID());
6195 bool only_threads_with_stop_reason,
6196 uint32_t start_frame, uint32_t num_frames,
6197 uint32_t num_frames_with_source,
6199 size_t num_thread_infos_dumped = 0;
6206 uint32_t num_threads;
6207 std::vector<lldb::tid_t> thread_id_array;
6210 std::lock_guard<std::recursive_mutex> guard(
GetThreadList().GetMutex());
6212 num_threads = curr_thread_list.
GetSize();
6214 thread_id_array.resize(num_threads);
6215 for (idx = 0; idx < num_threads; ++idx)
6219 for (uint32_t i = 0; i < num_threads; i++) {
6222 if (only_threads_with_stop_reason) {
6223 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
6224 if (!stop_info_sp || !stop_info_sp->ShouldShow())
6227 thread_sp->GetStatus(strm, start_frame, num_frames,
6228 num_frames_with_source, stop_format,
6230 ++num_thread_infos_dumped;
6233 LLDB_LOGF(log,
"Process::GetThreadStatus - thread 0x" PRIu64
6234 " vanished while running Thread::GetStatus.");
6237 return num_thread_infos_dumped;
6261 result = this_result;
6325 "Setting Process code address mask to {0:x}", code_address_mask);
6331 "Setting Process data address mask to {0:x}", data_address_mask);
6337 "Setting Process highmem code address mask to {0:x}",
6344 "Setting Process highmem data address mask to {0:x}",
6351 addr = abi_sp->FixCodeAddress(addr);
6357 addr = abi_sp->FixDataAddress(addr);
6363 addr = abi_sp->FixAnyAddress(addr);
6369 LLDB_LOGF(log,
"Process::%s()", __FUNCTION__);
6405 if (address ==
nullptr) {
6413 std::map<addr_t, addr_t>::const_iterator iter =
6416 function_addr = (*iter).second;
6421 "Unable to call resolver for indirect function %s",
6426 function_addr = abi_sp->FixCodeAddress(function_addr);
6428 std::pair<addr_t, addr_t>(addr, function_addr));
6431 return function_addr;
6447 runtime.second->ModulesDidLoad(module_list);
6453 runtime->ModulesDidLoad(module_list);
6464 pair.second->ModulesDidLoad(*
this, module_list);
6488 if (plugins[language])
6490 sc.
module_sp->ReportWarningUnsupportedLanguage(
6501 return platform_sp->GetProcessInfo(
GetID(), info);
6514 if (!memory_history) {
6518 threads = std::make_shared<ThreadCollection>(
6519 memory_history->GetHistoryThreads(addr));
6526 InstrumentationRuntimeCollection::iterator pos;
6531 return (*pos).second;
6536 module_spec.
Clear();
6563 Address retval = default_stop_addr;
6567 if (!default_stop_addr.
IsValid())
6570 const char *plugin_name =
nullptr;
6571 const char *flavor =
nullptr;
6572 const char *cpu =
nullptr;
6573 const char *features =
nullptr;
6577 if (disassembler_sp)
6578 insn_list = &disassembler_sp->GetInstructionList();
6580 if (insn_list ==
nullptr) {
6584 size_t insn_offset =
6591 insn_offset,
false ,
nullptr);
6596 if (branch_index > insn_offset) {
6597 Address next_branch_insn_address =
6599 if (next_branch_insn_address.
IsValid() &&
6601 retval = next_branch_insn_address;
6611 load_addr = abi->FixAnyAddress(load_addr);
6613 std::optional<MemoryRegionInfo> cached_region =
6615 if (cached_region) {
6616 range_info = *cached_region;
6621 if (
error.Success()) {
6638 region_list.clear();
6644 region_list.clear();
6655 region_list.push_back(std::move(region_info));
6663 !(abi && (abi->FixAnyAddress(range_end) != range_end)));
6682 if (supported_type_names.
GetSize() == 0) {
6683 LLDB_LOG(log,
"no structured data types supported");
6688 std::set<llvm::StringRef> type_names;
6691 "the process supports the following async structured data types:");
6700 const llvm::StringRef type_name =
object->GetStringValue();
6701 if (type_name.empty())
6704 type_names.insert(type_name);
6715 if (type_names.empty())
6727 std::vector<llvm::StringRef> names_to_remove;
6728 for (llvm::StringRef type_name : type_names) {
6729 if (plugin_sp->SupportsStructuredDataType(type_name)) {
6731 std::make_pair(type_name, plugin_sp));
6732 names_to_remove.push_back(type_name);
6733 LLDB_LOG(log,
"using plugin {0} for type name {1}",
6734 plugin_sp->GetPluginName(), type_name);
6739 for (llvm::StringRef type_name : names_to_remove)
6740 type_names.erase(type_name);
6757 llvm::StringRef type_name;
6769 find_it->second->HandleArrivalOfStructuredData(*
this, type_name, object_sp);
6781 llvm::function_ref<llvm::Expected<std::unique_ptr<UtilityFunction>>()>
6783 if (platform !=
GetTarget().GetPlatform().get())
6784 return llvm::createStringError(
6785 "the platform requesting the load-image utility function is not "
6786 "the target's platform");
6788 llvm::Expected<std::unique_ptr<UtilityFunction>> factory_result = factory();
6802 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6803 "Can't trace a non-live process.");
6804 return llvm::make_error<UnimplementedError>();
6809 bool trap_exceptions) {
6811 if (thread ==
nullptr || address ==
nullptr)
6823 auto type_system_or_err =
6825 if (!type_system_or_err) {
6826 llvm::consumeError(type_system_or_err.takeError());
6829 auto ts = *type_system_or_err;
6835 *thread, *address, void_ptr_type, llvm::ArrayRef<addr_t>(), options));
6839 StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
6847 call_plan_sp->GetReturnValueObject()->GetValueAsUnsigned(
6869 if (!arch || !tag_manager) {
6870 return llvm::createStringError(
6871 llvm::inconvertibleErrorCode(),
6872 "This architecture does not support memory tagging");
6876 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6877 "Process does not support memory tagging");
6883llvm::Expected<std::vector<lldb::addr_t>>
6885 llvm::Expected<const MemoryTagManager *> tag_manager_or_err =
6887 if (!tag_manager_or_err)
6888 return tag_manager_or_err.takeError();
6891 llvm::Expected<std::vector<uint8_t>> tag_data =
6894 return tag_data.takeError();
6901 const std::vector<lldb::addr_t> &tags) {
6902 llvm::Expected<const MemoryTagManager *> tag_manager_or_err =
6904 if (!tag_manager_or_err)
6908 llvm::Expected<std::vector<uint8_t>> packed_tags =
6932 if (!dirty_page_list)
6938 llvm::AddressRange range(0, 0);
6939 for (
addr_t page_addr : *dirty_page_list) {
6940 if (range.empty()) {
6942 range = llvm::AddressRange(page_addr, page_addr + page_size);
6944 if (range.end() == page_addr) {
6946 range = llvm::AddressRange(range.start(), page_addr + page_size);
6950 ranges.
Append(range.start(), range.size(), {range, lldb_permissions});
6951 range = llvm::AddressRange(page_addr, page_addr + page_size);
6957 ranges.
Append(range.start(), range.size(), {range, lldb_permissions});
6987 std::set<addr_t> &stack_ends) {
6992 std::vector<lldb_private::MemoryRegionInfo> dynamic_loader_mem_regions;
6998 save_thread_predicate);
6999 for (
const auto ®ion : dynamic_loader_mem_regions) {
7002 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0)
7011 std::set<addr_t> &stack_ends) {
7012 const bool try_dirty_pages =
true;
7021 StackFrameSP frame_sp = thread_sp->GetStackFrameAtIndex(0);
7027 const addr_t sp = reg_ctx_sp->GetSP();
7028 const size_t red_zone = process.
GetABI()->GetRedZoneSize();
7031 const size_t stack_head = (
sp - red_zone);
7039 stack_ends.insert(range_end);
7043 AddRegion(sp_region, try_dirty_pages, ranges);
7054 std::set<addr_t> &stack_ends) {
7057 const bool try_dirty_pages =
false;
7058 for (
const auto ®ion : regions)
7059 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0)
7060 AddRegion(region, try_dirty_pages, ranges);
7070 std::set<addr_t> &stack_ends) {
7073 bool have_dirty_page_info =
false;
7074 for (
const auto ®ion : regions) {
7075 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0 &&
7077 have_dirty_page_info =
true;
7080 if (!have_dirty_page_info) {
7083 const bool try_dirty_pages =
false;
7084 for (
const auto ®ion : regions)
7085 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0 &&
7087 AddRegion(region, try_dirty_pages, ranges);
7102 std::set<addr_t> &stack_ends) {
7103 const bool try_dirty_pages =
true;
7107 for (
const auto ®ion : regions) {
7109 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0 &&
7111 AddRegion(region, try_dirty_pages, ranges);
7117static lldb_private::MemoryRegionInfo
7133 if (option_ranges.IsEmpty())
7136 for (
const auto &range : regions) {
7137 auto *entry = option_ranges.FindEntryThatIntersects(range.GetRange());
7139 if (*entry != range.GetRange()) {
7156 if (regions.empty())
7158 "failed to get any valid memory regions from the process");
7161 "callers must set the core_style to something other than "
7162 "eSaveCoreUnspecified");
7166 std::set<addr_t> stack_ends;
7178 switch (core_style) {
7201 "no valid address ranges found for core style");
7206std::vector<ThreadSP>
7208 std::vector<ThreadSP> thread_list;
7211 thread_list.push_back(thread_sp);
7222 if (low_memory_addr_bits == 0 && high_memory_addr_bits == 0)
7225 if (low_memory_addr_bits != 0) {
7232 if (high_memory_addr_bits != 0) {
7240llvm::Expected<AddressSpaceInfo>
7243 return llvm::createStringError(
"process doesn't support address spaces");
7246 if (address_space_name == info.name)
7250 std::string names = llvm::join(
7254 return llvm::createStringError(
7255 "invalid address space \"%s\", expected one of: %s",
7256 address_space_name.str().c_str(), names.c_str());
7259llvm::Expected<AddressSpaceInfo>
7262 return llvm::createStringError(
"process doesn't support address spaces");
7265 if (info.space_id == address_space_id)
7272 return std::to_string(info.
space_id);
7275 return llvm::createStringError(
"invalid address space id %" PRIu64
7276 ", expected one of: %s",
7277 address_space_id, ids.c_str());
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
#define LLDB_LOGF(log,...)
#define LLDB_LOG_ERROR(log, error,...)
static void GetCoreFileSaveRangesFull(Process &process, const MemoryRegionInfos ®ions, CoreFileMemoryRanges &ranges, std::set< addr_t > &stack_ends)
static std::optional< ExpressionResults > HandleStoppedEvent(lldb::tid_t thread_id, const ThreadPlanSP &thread_plan_sp, RestorePlanState &restorer, const EventSP &event_sp, EventSP &event_to_broadcast_sp, const EvaluateExpressionOptions &options, bool handle_interrupts)
static void SaveDynamicLoaderSections(Process &process, const SaveCoreOptions &options, CoreFileMemoryRanges &ranges, std::set< addr_t > &stack_ends)
static CoreFileMemoryRange CreateCoreFileMemoryRange(const lldb_private::MemoryRegionInfo ®ion)
static constexpr unsigned g_string_read_width
static bool AddDirtyPages(const lldb_private::MemoryRegionInfo ®ion, CoreFileMemoryRanges &ranges)
static constexpr OptionEnumValueElement g_follow_fork_mode_values[]
static void GetUserSpecifiedCoreFileSaveRanges(Process &process, const MemoryRegionInfos ®ions, const SaveCoreOptions &options, CoreFileMemoryRanges &ranges)
static void GetCoreFileSaveRangesDirtyOnly(Process &process, const MemoryRegionInfos ®ions, CoreFileMemoryRanges &ranges, std::set< addr_t > &stack_ends)
static bool ShouldShowError(Process &process)
static void AddRegion(const lldb_private::MemoryRegionInfo ®ion, bool try_dirty_pages, CoreFileMemoryRanges &ranges)
static Timeout< std::micro > GetExpressionTimeout(const EvaluateExpressionOptions &options, bool before_first_timeout)
static microseconds GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options)
static addr_t ComputeConstituentLoadAddress(BreakpointLocation &constituent, Process &proc)
static lldb_private::MemoryRegionInfo Intersect(const lldb_private::MemoryRegionInfo &lhs, const lldb_private::MemoryRegionInfo::RangeType &rhs)
static void SaveOffRegionsWithStackPointers(Process &process, const SaveCoreOptions &core_options, const MemoryRegionInfos ®ions, CoreFileMemoryRanges &ranges, std::set< addr_t > &stack_ends)
static void GetCoreFileSaveRangesStackOnly(Process &process, const MemoryRegionInfos ®ions, CoreFileMemoryRanges &ranges, std::set< addr_t > &stack_ends)
#define LLDB_SCOPED_TIMER()
ProcessExperimentalOptionValueProperties()
const Property * GetPropertyAtIndex(size_t idx, const ExecutionContext *exe_ctx) const override
ProcessOptionValueProperties(llvm::StringRef name)
static lldb::ABISP FindPlugin(lldb::ProcessSP process_sp, const ArchSpec &arch)
A section + offset based address range class.
Address & GetBaseAddress()
Get accessor for the base address of the range.
bool ContainsFileAddress(const Address &so_addr) const
Check if a section offset address is contained in this range.
lldb::addr_t GetByteSize() const
Get accessor for the byte size of this range.
A section + offset based address class.
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
lldb::addr_t GetOpcodeLoadAddress(Target *target, AddressClass addr_class=AddressClass::eInvalid) const
Get the load address as an opcode load address.
bool IsValid() const
Check if the object state is valid.
Symbol * CalculateSymbolContextSymbol() const
A class which holds the metadata from a remote stub/corefile note about how many bits are used for ad...
uint32_t GetHighmemAddressableBits() const
static lldb::addr_t AddressableBitToMask(uint32_t addressable_bits)
uint32_t GetLowmemAddressableBits() const
An architecture specification class.
uint32_t GetAddressByteSize() const
Returns the size in bytes of an address of the current architecture.
bool IsValid() const
Tests if this ArchSpec is valid.
llvm::Triple & GetTriple()
Architecture triple accessor.
bool IsCompatibleMatch(const ArchSpec &rhs) const
Shorthand for IsMatch(rhs, CompatibleMatch).
bool IsExactMatch(const ArchSpec &rhs) const
Shorthand for IsMatch(rhs, ExactMatch).
lldb::ByteOrder GetByteOrder() const
Returns the byte order for the architecture specification.
virtual const MemoryTagManager * GetMemoryTagManager() const
A command line argument class.
General Outline: A breakpoint location is defined by the breakpoint that produces it,...
void SetIsIndirect(bool is_indirect)
bool ShouldResolveIndirectFunctions()
Returns whether we should resolve Indirect functions in setting the breakpoint site for this location...
lldb::break_id_t GetID() const
Returns the breakpoint location ID.
Address & GetAddress()
Gets the Address for this breakpoint location.
Breakpoint & GetBreakpoint()
Gets the Breakpoint that created this breakpoint location.
Class that manages the actual breakpoint that will be inserted into the running program.
BreakpointSite::Type GetType() const
void SetType(BreakpointSite::Type type)
bool IntersectsRange(lldb::addr_t addr, size_t size, lldb::addr_t *intersect_addr, size_t *intersect_size, size_t *opcode_offset) const
Says whether addr and size size intersects with the address intersect_addr.
uint8_t * GetTrapOpcodeBytes()
Returns the Opcode Bytes for this breakpoint.
uint8_t * GetSavedOpcodeBytes()
Gets the original instruction bytes that were overwritten by the trap.
bool IsHardware() const override
bool m_enabled
Boolean indicating if this breakpoint site enabled or not.
Broadcaster(lldb::BroadcasterManagerSP manager_sp, std::string name)
Construct with a broadcaster with a name.
lldb::ListenerSP GetPrimaryListener()
void RestoreBroadcaster()
Restore the state of the Broadcaster from a previous hijack attempt.
void SetEventName(uint32_t event_mask, const char *name)
Set the name for an event bit.
bool HijackBroadcaster(const lldb::ListenerSP &listener_sp, uint32_t event_mask=UINT32_MAX)
Provides a simple mechanism to temporarily redirect events from broadcaster.
void BroadcastEventIfUnique(lldb::EventSP &event_sp)
void SetPrimaryListener(lldb::ListenerSP listener_sp)
const char * GetHijackingListenerName()
void BroadcastEvent(lldb::EventSP &event_sp)
Broadcast an event which has no associated data.
bool IsHijackedForEvent(uint32_t event_mask)
void CheckInWithManager()
A class that implements CRTP-based "virtual constructor" idiom.
Generic representation of a type in a programming language.
CompilerType GetBasicTypeFromAST(lldb::BasicType basic_type) const
Create related types using the current type's AST.
CompilerType GetPointerType() const
Return a new CompilerType that is a pointer to this type.
const char * AsCString(const char *value_if_empty) const
Get the string value as a C string.
Status FinalizeCoreFileSaveRanges()
Finalize and merge all overlapping ranges in this collection.
A class to manage flag bits.
lldb::StreamUP GetAsyncErrorStream()
TargetList & GetTargetList()
Get accessor for the target list.
bool IsTopIOHandler(const lldb::IOHandlerSP &reader_sp)
bool RemoveIOHandler(const lldb::IOHandlerSP &reader_sp)
Remove the given IO handler if it's currently active.
void FlushStatusLine()
Discard the statusline's cached frame at its next redraw.
void RunIOHandlerAsync(const lldb::IOHandlerSP &reader_sp, bool cancel_top_handler=true)
Run the given IO handler and return immediately.
PlatformList & GetPlatformList()
lldb::ListenerSP GetListener()
size_t void PutString(lldb::Severity severity, llvm::StringRef str)
size_t Printf(lldb::Severity severity, const char *format,...) __attribute__((format(printf
static lldb::DisassemblerSP DisassembleRange(const ArchSpec &arch, const char *plugin_name, const char *flavor, const char *cpu, const char *features, Target &target, llvm::ArrayRef< AddressRange > disasm_ranges, bool force_live_memory=false)
Encapsulates dynamic check functions used by expressions.
A plug-in interface definition class for dynamic loaders.
virtual void DidAttach()=0
Called after attaching a process.
virtual void CalculateDynamicSaveCoreRanges(lldb_private::Process &process, std::vector< lldb_private::MemoryRegionInfo > &ranges, llvm::function_ref< bool(const lldb_private::Thread &)> save_thread_predicate)
Returns a list of memory ranges that should be saved in the core file, specific for this dynamic load...
virtual void DidLaunch()=0
Called after launching a process.
static DynamicLoader * FindPlugin(Process *process, llvm::StringRef plugin_name)
Find a dynamic loader plugin for a given process.
void SetUnwindOnError(bool unwind=false)
bool GetStopOthers() const
bool DoesIgnoreBreakpoints() const
bool IsForUtilityExpr() const
bool GetTryAllThreads() const
void SetTrapExceptions(bool b)
void SetTryAllThreads(bool try_others=true)
void SetTimeout(const Timeout< std::micro > &timeout)
void SetStopOthers(bool stop_others=true)
bool DoesUnwindOnError() const
const Timeout< std::micro > & GetTimeout() const
bool GetStopOnFork() const
void SetIgnoreBreakpoints(bool ignore=false)
const Timeout< std::micro > & GetOneThreadTimeout() const
virtual llvm::StringRef GetFlavor() const =0
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
void SetFrameSP(const lldb::StackFrameSP &frame_sp)
Set accessor to set only the frame shared pointer.
void SetProcessPtr(Process *process)
Set accessor to set only the process shared pointer from a process pointer.
void SetThreadPtr(Thread *thread)
Set accessor to set only the thread shared pointer from a thread pointer.
void SetTargetPtr(Target *target)
Set accessor to set only the target shared pointer from a target pointer.
StackFrame & GetFrameRef() const
Returns a reference to the thread object.
bool HasFrameScope() const
Returns true the ExecutionContext object contains a valid target, process, thread and frame.
void SetFramePtr(StackFrame *frame)
Set accessor to set only the frame shared pointer from a frame pointer.
Process * GetProcessPtr() const
Returns a pointer to the process object.
Thread * GetThreadPtr() const
Returns a pointer to the thread object.
llvm::StringRef GetFilename() const
Filename string const get accessor.
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
static FileSystem & Instance()
bool Test(ValueType bit) const
Test a single flag bit.
bool GetIsOptimized()
Get whether compiler optimizations were enabled for this function.
static lldb::thread_t GetCurrentThread()
Get the thread token (the one returned by ThreadCreate when the thread was created) for the calling t...
uint32_t GetIndexOfInstructionAtAddress(const Address &addr)
lldb::InstructionSP GetInstructionAtIndex(size_t idx) const
uint32_t GetIndexOfNextBranchInstruction(uint32_t start, bool ignore_calls, bool *found_calls) const
Get the index of the next branch instruction.
static void ModulesDidLoad(lldb_private::ModuleList &module_list, Process *process, InstrumentationRuntimeCollection &runtimes)
Class used by the Process to hold a list of its JITLoaders.
void ModulesDidLoad(ModuleList &module_list)
static void LoadPlugins(Process *process, lldb_private::JITLoaderList &list)
Find a JIT loader plugin for a given process.
virtual lldb::LanguageType GetLanguageType() const =0
static LanguageRuntime * FindPlugin(Process *process, lldb::LanguageType language)
virtual bool CouldHaveDynamicValue(ValueObject &in_value)=0
static lldb::LanguageType GetPrimaryLanguage(lldb::LanguageType language)
static std::set< lldb::LanguageType > GetSupportedLanguages()
static lldb::ListenerSP MakeListener(llvm::StringRef name)
void PutCString(const char *cstr)
void PutString(llvm::StringRef str)
static lldb::MemoryHistorySP FindPlugin(const lldb::ProcessSP process)
LazyBool GetMapped() const
int GetPageSize() const
Get the target system's VM page size in bytes.
LazyBool GetReadable() const
LazyBool GetExecutable() const
uint32_t GetLLDBPermissions() const
Range< lldb::addr_t, lldb::addr_t > RangeType
const std::optional< std::vector< lldb::addr_t > > & GetDirtyPageList() const
Get a vector of target VM pages that are dirty – that have been modified – within this memory region.
LazyBool GetWritable() const
void SetLLDBPermissions(uint32_t permissions)
virtual llvm::Expected< std::vector< lldb::addr_t > > UnpackTagsData(const std::vector< uint8_t > &tags, size_t granules=0) const =0
virtual lldb::addr_t GetGranuleSize() const =0
virtual llvm::Expected< std::vector< uint8_t > > PackTags(const std::vector< lldb::addr_t > &tags) const =0
virtual int32_t GetAllocationTagType() const =0
A collection class for Module objects.
A class that describes an executable image and its associated object and symbol files.
const FileSpec & GetFileSpec() const
Get const accessor for the module file specification.
A plug-in interface definition class for halted OS helpers.
virtual lldb::ThreadSP CreateThread(lldb::tid_t tid, lldb::addr_t context)
static OperatingSystem * FindPlugin(Process *process, const char *plugin_name)
Find a halted OS plugin for a given process.
virtual bool UpdateThreadList(ThreadList &old_thread_list, ThreadList &real_thread_list, ThreadList &new_thread_list)=0
virtual bool DoesPluginReportAllThreads()=0
auto GetPropertyAtIndexAs(size_t idx, const ExecutionContext *exe_ctx=nullptr) const
Property * ProtectedGetPropertyAtIndex(size_t idx)
static lldb::OptionValuePropertiesSP CreateLocalCopy(const Properties &global_properties)
void SetMaximumValue(uint64_t v)
void SetMinimumValue(uint64_t v)
OptionValueProperties * GetAsProperties()
virtual llvm::StringRef GetPluginName()=0
static llvm::SmallVector< ProcessCreateInstance > GetProcessCreateCallbacks()
static ProcessCreateInstance GetProcessCreateCallbackForPluginName(llvm::StringRef name)
static llvm::SmallVector< StructuredDataPluginCallbacks > GetStructuredDataPluginCallbacks()
static LanguageSet GetAllTypeSystemSupportedLanguagesForTypes()
RAII guard that pops a policy on destruction.
Guard PushPrivateState(Policy::PrivateStatePurpose purpose=Policy::PrivateStatePurpose::Default)
All Push* methods delegate to the named static factories on Policy, which already inherit from Curren...
static PolicyStack & Get()
An address in a process, qualified by an address space.
lldb::addr_t GetValue() const
lldb::addr_space_t GetAddressSpace() const
bool IsInDefaultAddressSpace() const
uint32_t GetResumeCount() const
lldb::ListenerSP GetListenerForProcess(Debugger &debugger)
bool GetWaitForLaunch() const
ProcessExperimentalProperties()
lldb::pid_t GetProcessID() const
lldb::ListenerSP m_listener_sp
FileSpec & GetExecutableFile()
bool IsScriptedProcess() const
ArchSpec & GetArchitecture()
void SetNameMatchType(NameMatch name_match_type)
ProcessInstanceInfo & GetProcessInfo()
static void DumpTableHeader(Stream &s, bool show_args, bool verbose)
bool GetDetachKeepsStopped() const
bool TrackMemoryCacheChanges() const
bool GetSteppingRunsAllThreads() const
void SetStopOnSharedLibraryEvents(bool stop)
Args GetExtraStartupCommands() const
std::unique_ptr< ProcessExperimentalProperties > m_experimental_properties_up
FollowForkMode GetFollowForkMode() const
uint32_t GetVirtualAddressableBits() const
~ProcessProperties() override
void SetIgnoreBreakpointsInExpressions(bool ignore)
bool GetUnwindOnErrorInExpressions() const
Args GetAlwaysRunThreadNames() const
std::chrono::seconds GetInterruptTimeout() const
bool GetDisableLangRuntimeUnwindPlans() const
void SetDetachKeepsStopped(bool keep_stopped)
bool GetVerifyMemoryReads() const
void SetDisableLangRuntimeUnwindPlans(bool disable)
std::chrono::seconds GetUtilityExpressionTimeout() const
void AddressMaskChangedCallback()
void SetVirtualAddressableBits(uint32_t bits)
bool GetStopOnSharedLibraryEvents() const
void SetHighmemVirtualAddressableBits(uint32_t bits)
void SetOSPluginReportsAllThreads(bool does_report)
bool GetWarningsOptimization() const
void DisableLanguageRuntimeUnwindPlansCallback()
void SetUnwindOnErrorInExpressions(bool ignore)
bool GetDisableMemoryCache() const
bool GetUseDelayedBreakpoints() const
FileSpec GetPythonOSPluginPath() const
bool GetStopOnExec() const
void SetPythonOSPluginPath(const FileSpec &file)
void SetExtraStartupCommands(const Args &args)
bool GetOSPluginReportsAllThreads() const
bool GetWarningsUnsupportedLanguage() const
uint32_t GetHighmemVirtualAddressableBits() const
OptionValueProperties * GetExperimentalProperties() const
bool GetIgnoreBreakpointsInExpressions() const
uint64_t GetMemoryCacheLineSize() const
ProcessProperties(lldb_private::Process *process)
bool TryLock(ProcessRunLock *lock)
Try to acquire the read lock.
Read/write lock around the process running/stopped state.
EventActionResult HandleBeingInterrupted() override
const char * GetExitString() override
EventActionResult PerformAction(lldb::EventSP &event_sp) override
AttachCompletionHandler(Process *process, uint32_t exec_count)
std::string m_exit_string
NextEventAction(Process *process)
lldb::ProcessWP m_process_wp
static bool GetRestartedFromEvent(const Event *event_ptr)
virtual bool ShouldStop(Event *event_ptr, bool &found_valid_stopinfo)
void SetUpdateStateOnRemoval()
static void AddRestartedReason(Event *event_ptr, const char *reason)
void SetInterrupted(bool new_value)
lldb::ProcessSP GetProcessSP() const
void SetRestarted(bool new_value)
static void SetRestartedInEvent(Event *event_ptr, bool new_value)
static lldb::ProcessSP GetProcessFromEvent(const Event *event_ptr)
static void SetInterruptedInEvent(Event *event_ptr, bool new_value)
bool ForwardEventToPendingListeners(Event *event_ptr) override
This will be queried for a Broadcaster with a primary and some secondary listeners after the primary ...
llvm::StringRef GetFlavor() const override
~ProcessEventData() override
bool GetInterrupted() const
bool GetRestarted() const
size_t GetNumRestartedReasons()
static bool GetInterruptedFromEvent(const Event *event_ptr)
const char * GetRestartedReasonAtIndex(size_t idx)
static bool SetUpdateStateOnRemoval(Event *event_ptr)
static lldb::StateType GetStateFromEvent(const Event *event_ptr)
lldb::StateType GetState() const
static const Process::ProcessEventData * GetEventDataFromEvent(const Event *event_ptr)
static llvm::StringRef GetFlavorString()
void DoOnRemoval(Event *event_ptr) override
void Dump(Stream *s) const override
A plug-in interface definition class for debugging a process.
virtual Status EnableBreakpointSite(BreakpointSite *bp_site)
Status WillAttachToProcessWithName(const char *process_name, bool wait_for_launch)
Called before attaching to a process.
virtual llvm::Expected< TraceSupportedResponse > TraceSupported()
Get the processor tracing type supported for this process.
lldb::IOHandlerSP m_process_input_reader
friend class ProcessProperties
virtual Status DoSignal(int signal)
Sends a process a UNIX signal signal.
virtual Status WillResume()
Called before resuming to a process.
std::mutex m_process_input_reader_mutex
lldb::addr_t m_code_address_mask
Mask for code an data addresses.
StopPointSiteList< lldb_private::BreakpointSite > & GetBreakpointSiteList()
std::vector< lldb::addr_t > m_image_tokens
virtual Status DoHalt(bool &caused_stop)
Halts a running process.
virtual void DidLaunch()
Called after launching a process.
virtual Status DisableSoftwareBreakpoint(BreakpointSite *bp_site)
lldb::pid_t GetID() const
Returns the pid of the process or LLDB_INVALID_PROCESS_ID if there is no known pid.
lldb::break_id_t CreateBreakpointSite(const lldb::BreakpointLocationSP &owner, bool use_hardware)
virtual Status WillSignal()
Called before sending a signal to a process.
void ResetImageToken(size_t token)
lldb::JITLoaderListUP m_jit_loaders_up
lldb::addr_t CallocateMemory(size_t size, uint32_t permissions, Status &error)
The public interface to allocating memory in the process, this also clears the allocated memory.
void SetNextEventAction(Process::NextEventAction *next_event_action)
Status Destroy(bool force_kill)
Kills the process and shuts down all threads that were spawned to track and monitor the process.
virtual Status WillDetach()
Called before detaching from a process.
virtual Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info)
Launch a new process.
StopPointSiteList< lldb_private::BreakpointSite > m_breakpoint_site_list
This is the list of breakpoint locations we intend to insert in the target.
void ControlPrivateStateThread(uint32_t signal)
ThreadList & GetThreadList()
void SetAddressableBitMasks(AddressableBits bit_masks)
void ClearPreResumeActions()
virtual DataExtractor GetAuxvData()
Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp)
Construct with a shared pointer to a target, and the Process listener.
void PrintWarningUnsupportedLanguage(const SymbolContext &sc)
Print a user-visible warning about a function written in a language that this version of LLDB doesn't...
Status LaunchPrivate(ProcessLaunchInfo &launch_info, lldb::StateType &state, lldb::EventSP &event_sp)
std::vector< std::string > m_profile_data
bool m_can_interpret_function_calls
Status Resume()
Resumes all of a process's threads as configured using the Thread run control functions.
void PruneThreadPlans()
Prune ThreadPlanStacks for all unreported threads.
MemoryRegionInfoCache m_memory_region_infos_cache
void SetUnixSignals(lldb::UnixSignalsSP &&signals_sp)
std::string m_stdout_data
Remember if stdin must be forwarded to remote debug server.
bool RemoveInvalidMemoryRange(const LoadRange ®ion)
DelayedBreakpointCache m_delayed_breakpoints
uint32_t GetNextThreadIndexID(uint64_t thread_id)
Status PrivateResume()
The "private" side of resuming a process.
void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers)
void SetSTDIOFileDescriptor(int file_descriptor, std::optional< int > secondary_fd=std::nullopt)
Associates a file descriptor with the process' STDIO handling and configures an asynchronous reading ...
void SendAsyncInterrupt(Thread *thread=nullptr)
Send an async interrupt request.
void AddInvalidMemoryRegion(const LoadRange ®ion)
virtual void ModulesDidLoad(ModuleList &module_list)
InstrumentationRuntimeCollection m_instrumentation_runtimes
llvm::Error ExecuteBreakpointSiteAction(BreakpointSite &site, Process::BreakpointAction action, bool forbid_delay)
Performs action on site.
std::atomic< bool > m_destructing
std::shared_ptr< PrivateStateThread > m_current_private_state_thread_sp
This is filled on construction with the "main" private state which will be exposed to clients of this...
virtual llvm::Error UpdateBreakpointSites(const BreakpointSiteToActionMap &site_to_action)
virtual Status DoGetMemoryRegionInfo(lldb::addr_t load_addr, MemoryRegionInfo &range_info)
DoGetMemoryRegionInfo is called by GetMemoryRegionInfo after it has removed non address bits from loa...
@ eBroadcastInternalStateControlResume
@ eBroadcastInternalStateControlStop
@ eBroadcastInternalStateControlPause
int GetExitStatus()
Get the exit status for a process.
OperatingSystem * GetOperatingSystem()
lldb::ExpressionResults RunThreadPlan(ExecutionContext &exe_ctx, lldb::ThreadPlanSP &thread_plan_sp, const EvaluateExpressionOptions &requested_options, DiagnosticManager &diagnostic_manager)
Status WillAttachToProcessWithID(lldb::pid_t pid)
Called before attaching to a process.
virtual Status DoDetach(bool keep_stopped)
Detaches from a running or stopped process.
std::unique_ptr< UtilityFunction > m_dlopen_utility_func_up
void SetRunningUtilityFunction(bool on)
void DisableAllBreakpointSites()
uint32_t m_process_unique_id
Each lldb_private::Process class that is created gets a unique integer ID that increments with each n...
int64_t ReadSignedIntegerFromMemory(lldb::addr_t load_addr, size_t byte_size, int64_t fail_value, Status &error)
Address AdvanceAddressToNextBranchInstruction(Address default_stop_addr, AddressRange range_bounds)
Find the next branch instruction to set a breakpoint on.
virtual bool GetLoadAddressPermissions(lldb::addr_t load_addr, uint32_t &permissions)
Attempt to get the attributes for a region of memory in the process.
static bool HandleProcessStateChangedEvent(const lldb::EventSP &event_sp, Stream *stream, SelectMostRelevant select_most_relevant, bool &pop_process_io_handler)
Centralize the code that handles and prints descriptions for process state changes.
bool SetPublicRunLockToRunning()
virtual size_t GetAsyncProfileData(char *buf, size_t buf_size, Status &error)
Get any available profile data.
void CloseSTDIOSecondaryFileDescriptor()
Close m_stdio_secondary_fd if it is still open.
lldb::addr_t FixDataAddress(lldb::addr_t pc)
lldb::addr_t AllocateMemory(size_t size, uint32_t permissions, Status &error)
The public interface to allocating memory in the process.
std::unique_ptr< NextEventAction > m_next_event_action_up
void SetHighmemDataAddressMask(lldb::addr_t data_address_mask)
bool PruneThreadPlansForTID(lldb::tid_t tid)
Prune ThreadPlanStacks for unreported threads.
virtual void DidDetach()
Called after detaching from a process.
void PausePrivateStateThread()
virtual llvm::SmallVector< llvm::MutableArrayRef< uint8_t > > DoReadMemoryRanges(llvm::ArrayRef< Range< lldb::addr_t, size_t > > ranges, llvm::MutableArrayRef< uint8_t > buffer)
Reads each range individually via ReadMemoryFromInferior, bypassing the memory cache.
Status EnableBreakpointSiteByID(lldb::user_id_t break_id)
ProcessModID GetModID() const
Get the Modification ID of the process.
size_t ReadMemoryFromInferior(lldb::addr_t vm_addr, void *buf, size_t size, Status &error)
Read of memory from a process.
size_t ReadScalarIntegerFromMemory(lldb::addr_t addr, uint32_t byte_size, bool is_signed, Scalar &scalar, Status &error)
virtual Status Launch(ProcessLaunchInfo &launch_info)
Launch a new process.
std::mutex m_run_thread_plan_lock
static void SettingsInitialize()
void BroadcastStructuredData(const StructuredData::ObjectSP &object_sp, const lldb::StructuredDataPluginSP &plugin_sp)
Broadcasts the given structured data object from the given plugin.
void Flush()
Flush all data in the process.
bool m_clear_thread_plans_on_stop
size_t ReadCStringFromMemory(lldb::addr_t vm_addr, char *cstr, size_t cstr_max_len, Status &error)
Read a null-terminated C string from memory.
void ResumePrivateStateThread()
void MapSupportedStructuredDataPlugins(const StructuredData::Array &supported_type_names)
Loads any plugins associated with asynchronous structured data and maps the relevant supported type n...
bool GetEventsPrivate(lldb::EventSP &event_sp, const Timeout< std::micro > &timeout, bool control_only)
lldb::ABISP m_abi_sp
This is the current signal set for this process.
virtual void DidSignal()
Called after sending a signal to a process.
size_t ReadMemory(const ProcessAddress &process_addr, void *buf, size_t size, Status &error)
Read of memory from a process.
std::map< lldb::BreakpointSiteSP, BreakpointAction, SiteIDCmp > BreakpointSiteToActionMap
virtual SystemRuntime * GetSystemRuntime()
Get the system runtime plug-in for this process.
void RemoveBreakpointOpcodesFromBuffer(lldb::addr_t addr, size_t size, uint8_t *buf) const
std::map< uint64_t, uint32_t > m_thread_id_to_index_id_map
lldb::StateType GetPrivateState() const
void SetPrivateStateNoLock(lldb::StateType new_state)
bool DumpThreadPlansForTID(Stream &strm, lldb::tid_t tid, lldb::DescriptionLevel desc_level, bool internal, bool condense_trivial, bool skip_unreported_plans)
Dump the thread plans associated with thread with tid.
lldb::ListenerSP m_private_state_listener_sp
uint32_t m_extended_thread_stop_id
The natural stop id when extended_thread_list was last updated.
bool PreResumeActionCallback(void *)
lldb::RunDirection m_base_direction
ThreadPlanBase run direction.
Range< lldb::addr_t, lldb::addr_t > LoadRange
static constexpr llvm::StringRef ResumeSynchronousHijackListenerName
void SetBreakpointSiteEnabled(BreakpointSite &site, bool is_enabled=true)
bool WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value, Status &error)
QueueList m_queue_list
The list of libdispatch queues at a given stop point.
void ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
virtual Status WillDestroy()
lldb::ThreadSP CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context)
std::vector< PreResumeCallbackAndBaton > m_pre_resume_actions
void SetCanJIT(bool can_jit)
Sets whether executing JIT-compiled code in this process is possible.
lldb::StateType GetStateChangedEventsPrivate(lldb::EventSP &event_sp, const Timeout< std::micro > &timeout)
void LoadOperatingSystemPlugin(bool flush)
lldb::StructuredDataPluginSP GetStructuredDataPlugin(llvm::StringRef type_name) const
Returns the StructuredDataPlugin associated with a given type name, if there is one.
lldb::DynamicLoaderUP m_dyld_up
friend class ProcessEventData
void ResetExtendedCrashInfoDict()
AddressRanges FindRangesInMemory(const uint8_t *buf, uint64_t size, const AddressRanges &ranges, size_t alignment, size_t max_matches, Status &error)
virtual bool GetModuleSpec(const FileSpec &module_file_spec, const ArchSpec &arch, ModuleSpec &module_spec)
Try to fetch the module specification for a module with the given file name and architecture.
virtual size_t DoWriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, Status &error)
Actually do the writing of memory to a process.
virtual Status WriteObjectFile(std::vector< ObjectFile::LoadableData > entries)
std::recursive_mutex m_stdio_communication_mutex
static lldb::ProcessSP FindPlugin(lldb::TargetSP target_sp, llvm::StringRef plugin_name, lldb::ListenerSP listener_sp, const FileSpec *crash_file_path, bool can_connect)
Find a Process plug-in that can debug module using the currently selected architecture.
StopPointSiteList< lldb_private::WatchpointResource > m_watchpoint_resource_list
Watchpoint resources currently in use.
Status DisableBreakpointSiteByID(lldb::user_id_t break_id)
llvm::Expected< const MemoryTagManager * > GetMemoryTagManager()
If this architecture and process supports memory tagging, return a tag manager that can be used to ma...
~Process() override
Destructor.
virtual Status DoWriteMemoryTags(lldb::addr_t addr, size_t len, int32_t type, const std::vector< uint8_t > &tags)
Does the final operation to write memory tags.
std::recursive_mutex m_profile_data_comm_mutex
bool IsBreakpointSitePhysicallyEnabled(const BreakpointSite &site)
std::vector< AddressSpaceInfo > m_address_spaces
A list of address spaces for this process.
lldb::InstrumentationRuntimeSP GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type)
ProcessRunLock::ProcessRunLocker StopLocker
Status ResumeSynchronous(Stream *stream)
Resume a process, and wait for it to stop.
lldb::addr_t FixAnyAddress(lldb::addr_t pc)
Use this method when you do not know, or do not care what kind of address you are fixing.
virtual Status DoWillLaunch(Module *module)
Called before launching to a process.
virtual Status ConnectRemote(llvm::StringRef remote_url)
Attach to a remote system via a URL.
void AppendSTDOUT(const char *s, size_t len)
llvm::StringMap< lldb::StructuredDataPluginSP > m_structured_data_plugin_map
virtual Status DisableBreakpointSite(BreakpointSite *bp_site)
size_t GetThreadStatus(Stream &ostrm, bool only_threads_with_stop_reason, uint32_t start_frame, uint32_t num_frames, uint32_t num_frames_with_source, bool stop_format)
void CalculateExecutionContext(ExecutionContext &exe_ctx) override
Reconstruct the object's execution context into sc.
Event * PeekAtStateChangedEvents()
std::vector< Notifications > m_notifications
The list of notifications that this process can deliver.
bool HasAssignedIndexIDToThread(uint64_t sb_thread_id)
llvm::SmallVector< std::optional< uint64_t > > ReadUnsignedIntegersFromMemory(llvm::ArrayRef< lldb::addr_t > addresses, unsigned byte_size)
Use Process::ReadMemoryRanges to efficiently read multiple unsigned integers from memory at once.
void StopPrivateStateThread()
size_t AddImageToken(lldb::addr_t image_ptr)
llvm::Error FlushDelayedBreakpoints()
lldb::StateType GetPrivateStateNoLock() const
virtual void DoFindInMemory(lldb::addr_t start_addr, lldb::addr_t end_addr, const uint8_t *buf, size_t size, AddressRanges &matches, size_t alignment, size_t max_matches)
virtual bool DestroyRequiresHalt()
lldb::EventSP CreateEventFromProcessState(uint32_t event_type)
StructuredData::DictionarySP m_crash_info_dict_sp
A repository for extra crash information, consulted in GetExtendedCrashInformation.
Status CalculateCoreFileSaveRanges(const SaveCoreOptions &core_options, CoreFileMemoryRanges &ranges)
Helper function for Process::SaveCore(...) that calculates the address ranges that should be saved.
lldb::TargetSP CalculateTarget() override
bool SetPublicRunLockToStopped()
void SetHighmemCodeAddressMask(lldb::addr_t code_address_mask)
lldb::ByteOrder GetByteOrder() const
Status Detach(bool keep_stopped)
Detaches from a running or stopped process.
void UpdateThreadListIfNeeded()
virtual llvm::Expected< std::vector< lldb::addr_t > > ReadMemoryTags(lldb::addr_t addr, size_t len)
Read memory tags for the range addr to addr+len.
virtual void DidResume()
Called after resuming a process.
virtual void DidExec()
Called after a process re-execs itself.
void SetCodeAddressMask(lldb::addr_t code_address_mask)
AllocatedMemoryCache m_allocated_memory_cache
virtual Status LoadCore()
llvm::Expected< lldb::addr_t > ReadPointerFromMemory(lldb::addr_t vm_addr)
std::mutex m_exit_status_mutex
Mutex so m_exit_status m_exit_string can be safely accessed from multiple threads.
Status Signal(int signal)
Sends a process a UNIX signal signal.
void SetDynamicLoader(lldb::DynamicLoaderUP dyld)
ThreadPlanStackMap m_thread_plans
This is the list of thread plans for threads in m_thread_list, as well as threads we knew existed,...
std::recursive_mutex m_thread_mutex
virtual Status ConfigureStructuredData(llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp)
Configure asynchronous structured data feature.
Guarded< std::optional< int >, std::mutex > m_stdio_secondary_fd
The secondary side of the pseudo terminal the inferior uses for stdio.
virtual Status DoWillAttachToProcessWithName(const char *process_name, bool wait_for_launch)
Called before attaching to a process.
bool m_currently_handling_do_on_removals
void HandlePrivateEvent(lldb::EventSP &event_sp)
void BroadcastAsyncProfileData(const std::string &one_profile_data)
lldb::StateType GetState()
Get accessor for the current process state.
virtual Status DoWillAttachToProcessWithID(lldb::pid_t pid)
Called before attaching to a process.
ProcessRunLock & GetRunLock()
virtual Status DoLoadCore()
Predicate< uint32_t > m_iohandler_sync
LanguageRuntimeCollection m_language_runtimes
Should we detach if the process object goes away with an explicit call to Kill or Detach?
virtual Status GetMemoryRegions(lldb_private::MemoryRegionInfos ®ion_list)
Obtain all the mapped memory regions within this process.
size_t WriteMemoryPrivate(lldb::addr_t addr, const void *buf, size_t size, Status &error)
void SetRunningUserExpression(bool on)
enum lldb_private::Process::@120260360120067272255351105340035202127223005263 m_can_jit
bool IsPossibleDynamicValue(ValueObject &in_value)
std::recursive_mutex m_delayed_breakpoints_mutex
llvm::Expected< lldb::ModuleSP > ReadModuleFromMemory(const FileSpec &file_spec, lldb::addr_t header_addr, size_t size_to_read=512)
Creates and populates a module using an in-memory object file.
Status m_dlopen_utility_func_error
The error from the one attempt to create m_dlopen_utility_func_up, set only if that attempt failed.
void RemoveConstituentFromBreakpointSite(lldb::user_id_t site_id, lldb::user_id_t constituent_id, lldb::BreakpointSiteSP &bp_site_sp)
void VerifyMemoryRead(lldb::addr_t addr, const void *cache_buf, size_t cache_bytes_read, size_t size, const Status &cache_error)
Re-read size bytes at addr and assert they match the cache.
lldb::addr_t FindInMemory(lldb::addr_t low, lldb::addr_t high, const uint8_t *buf, size_t size)
Find a pattern within a memory region.
lldb::OperatingSystemUP m_os_up
uint32_t GetLastNaturalStopID() const
lldb::StateType WaitForProcessToStop(const Timeout< std::micro > &timeout, lldb::EventSP *event_sp_ptr=nullptr, bool wait_always=true, lldb::ListenerSP hijack_listener=lldb::ListenerSP(), Stream *stream=nullptr, bool use_run_lock=true, SelectMostRelevant select_most_relevant=DoNoSelectMostRelevantFrame)
lldb::UnixSignalsSP m_unix_signals_sp
bool StateChangedIsHijackedForSynchronousResume()
const char * GetExitDescription()
Get a textual description of what the process exited.
void SetPublicState(lldb::StateType new_state, bool restarted)
lldb::tid_t m_interrupt_tid
void SetDataAddressMask(lldb::addr_t data_address_mask)
virtual Status DoConnectRemote(llvm::StringRef remote_url)
Attach to a remote system via a URL.
uint64_t ReadUnsignedIntegerFromMemory(lldb::addr_t load_addr, size_t byte_size, uint64_t fail_value, Status &error)
Reads an unsigned integer of the specified byte size from process memory.
llvm::once_flag m_dlopen_utility_func_flag_once
void AddCacheData(lldb::addr_t addr, const lldb::WritableDataBufferSP &data_buffer_sp)
Cache memory, restoring the original bytes under any breakpoint.
virtual void UpdateQueueListIfNeeded()
virtual Status UpdateAutomaticSignalFiltering()
virtual lldb::addr_t GetImageInfoAddress()
Get the image information address for the current process.
std::map< lldb::addr_t, lldb::addr_t > m_resolved_indirect_addresses
This helps with the Public event coalescing in ShouldBroadcastEvent.
virtual Status DoAttachToProcessWithID(lldb::pid_t pid, const ProcessAttachInfo &attach_info)
Attach to an existing process using a process ID.
llvm::SmallVector< std::optional< std::string > > ReadCStringsFromMemory(llvm::ArrayRef< lldb::addr_t > addresses)
void SetCanRunCode(bool can_run_code)
Sets whether executing code in this process is possible.
Status ClearBreakpointSiteByID(lldb::user_id_t break_id)
virtual Status EnableSoftwareBreakpoint(BreakpointSite *bp_site)
void AppendSTDERR(const char *s, size_t len)
bool GetShouldDetach() const
static llvm::StringRef GetStaticBroadcasterClass()
uint32_t m_thread_index_id
Each thread is created with a 1 based index that won't get re-used.
bool ProcessIOHandlerExists() const
virtual Status DoResume(lldb::RunDirection direction)
Resumes all of a process's threads as configured using the Thread run control functions.
bool RouteAsyncStructuredData(const StructuredData::ObjectSP object_sp)
Route the incoming structured data dictionary to the right plugin.
virtual void DidDestroy()
bool IsBreakpointSiteEnabled(const BreakpointSite &site)
Broadcaster m_private_state_control_broadcaster
lldb::addr_t GetHighmemCodeAddressMask()
The highmem masks are for targets where we may have different masks for low memory versus high memory...
bool PushProcessIOHandler()
Broadcaster m_private_state_broadcaster
virtual bool DetachRequiresHalt()
virtual bool IsAlive()
Check if a process is still alive.
bool m_destroy_in_process
virtual bool ShouldUseMemoryCache(const ProcessAddress &process_addr)
Whether ReadMemory should serve reads of process_addr out of the memory cache.
ThreadList m_thread_list_real
The threads for this process as are known to the protocol we are debugging with.
lldb::addr_t m_data_address_mask
virtual ArchSpec GetSystemArchitecture()
Get the system architecture for this process.
Status DeallocateMemory(lldb::addr_t ptr)
The public interface to deallocating memory in the process.
virtual Status DisableWatchpoint(lldb::WatchpointSP wp_sp, bool notify=true)
void RegisterNotificationCallbacks(const Process::Notifications &callbacks)
Register for process and thread notifications.
virtual void DidAttach(ArchSpec &process_arch)
Called after attaching a process.
virtual lldb::addr_t ResolveIndirectFunction(const Address *address, Status &error)
Resolve dynamically loaded indirect functions.
lldb::StateType m_last_broadcast_state
LanguageRuntime * GetLanguageRuntime(lldb::LanguageType language)
ProcessModID m_mod_id
Tracks the state of the process over stops and other alterations.
virtual bool FindModuleUUID(ModuleSpec &spec)
Given a module spec, try to find the UUID information.
void SetID(lldb::pid_t new_pid)
Sets the stored pid.
virtual JITLoaderList & GetJITLoaders()
uint32_t AssignIndexIDToThread(uint64_t thread_id)
virtual bool SetExitStatus(int exit_status, llvm::StringRef exit_string)
Set accessor for the process exit status (return code).
uint32_t m_queue_list_stop_id
The natural stop id when queue list was last fetched.
void PrintWarningOptimization(const SymbolContext &sc)
Print a user-visible warning about a module being built with optimization.
virtual bool DoCanAllocateMemory()
Determines whether DoAllocateMemory is expected to succeed, without running code in the process.
@ eBroadcastBitStructuredData
@ eBroadcastBitStateChanged
@ eBroadcastBitProfileData
virtual std::optional< bool > DoGetWatchpointReportedAfter()
Provide an override value in the subclass for lldb's CPU-based logic for whether watchpoint exception...
static ProcessProperties & GetGlobalProperties()
void StopSTDIOMonitoring(bool drain)
Stop monitoring the process' stdio.
lldb::addr_t m_highmem_code_address_mask
lldb::addr_t GetImagePtrFromToken(size_t token) const
int m_exit_status
The exit status of the process, or -1 if not set.
std::vector< LanguageRuntime * > GetLanguageRuntimes()
void SetShouldDetach(bool b)
bool StartPrivateStateThread(lldb::StateType state, bool run_lock_is_running, std::shared_ptr< PrivateStateThread > *backup_ptr=nullptr)
MemoryCache m_memory_cache
static void STDIOReadThreadBytesReceived(void *baton, const void *src, size_t src_len)
virtual bool GetProcessInfo(ProcessInstanceInfo &info)
virtual void DidHalt()
Called after halting a process.
lldb::addr_t FixCodeAddress(lldb::addr_t pc)
Some targets might use bits in a code address to indicate a mode switch, ARM uses bit zero to signify...
lldb::StateType WaitForProcessStopPrivate(lldb::EventSP &event_sp, const Timeout< std::micro > &timeout)
void RestoreProcessEvents()
Restores the process event broadcasting to its normal state.
virtual bool SupportsMemoryTagging()
Check whether the process supports memory tagging.
bool SetPrivateRunLockToRunning()
void DumpThreadPlans(Stream &strm, lldb::DescriptionLevel desc_level, bool internal, bool condense_trivial, bool skip_unreported_plans)
Dump all the thread plans for this process.
uint32_t GetAddressByteSize() const
uint32_t GetStopID() const
void SetPrivateState(lldb::StateType state)
llvm::Expected< AddressSpaceInfo > GetAddressSpaceInfo(llvm::StringRef address_space_name)
lldb::addr_t m_highmem_data_address_mask
virtual Status DoDestroy()=0
Status StopForDestroyOrDetach(lldb::EventSP &exit_event_sp)
bool GetWatchpointReportedAfter()
Whether lldb will be notified about watchpoints after the instruction has completed executing,...
lldb::StateType GetNextEvent(lldb::EventSP &event_sp)
virtual bool DoUpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list)=0
Update the thread list following process plug-in's specific logic.
virtual llvm::Expected< std::vector< uint8_t > > DoReadMemoryTags(lldb::addr_t addr, size_t len, int32_t type)
Does the final operation to read memory tags.
bool StateChangedIsExternallyHijacked()
bool RunPreResumeActions()
lldb::StateType GetPublicState() const
bool PopProcessIOHandler()
virtual size_t GetSTDERR(char *buf, size_t buf_size, Status &error)
Get any available STDERR.
size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, Status &error)
Write memory to a process.
virtual llvm::Expected< bool > SaveCore(llvm::StringRef outfile)
Save core dump into the specified file.
bool ProcessIOHandlerIsActive()
Status DestroyImpl(bool force_kill)
bool m_force_next_event_delivery
void GetStatus(Stream &ostrm, bool is_verbose=false)
lldb::SystemRuntimeUP m_system_runtime_up
virtual Status WillHalt()
Called before halting to a process.
bool ShouldBroadcastEvent(Event *event_ptr)
This is the part of the event handling that for a process event.
virtual DynamicLoader * GetDynamicLoader()
Get the dynamic loader plug-in for this process.
std::string m_exit_string
A textual description of why a process exited.
lldb::DynamicCheckerFunctionsUP m_dynamic_checkers_up
The functions used by the expression parser to validate data that expressions use.
void SyncIOHandler(uint32_t iohandler_id, const Timeout< std::micro > &timeout)
Waits for the process state to be running within a given msec timeout.
void ForceNextEventDelivery()
ThreadPlanStack * FindThreadPlans(lldb::tid_t tid)
Find the thread plan stack associated with thread with tid.
virtual Status Attach(ProcessAttachInfo &attach_info)
Attach to an existing process using the process attach info.
virtual void Finalize(bool destructing)
This object is about to be destroyed, do any necessary cleanup.
lldb::addr_t GetDataAddressMask()
std::recursive_mutex & GetPrivateStateMutex()
virtual bool ShouldUseDelayedBreakpoints() const
Reports whether this process should delay physically enabling/disabling breakpoints until the process...
void SynchronouslyNotifyStateChanged(lldb::StateType state)
bool SetPrivateRunLockToStopped()
void SetSTDIOPseudoTerminal(PseudoTerminal &pty)
Associates the primary side of pty with the process' STDIO handling.
bool CanJIT()
Determines whether executing JIT-compiled code in this process is possible.
virtual Status DoAttachToProcessWithName(const char *process_name, const ProcessAttachInfo &attach_info)
Attach to an existing process using a partial process name.
ThreadList m_thread_list
The threads for this process as the user will see them.
bool UpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list)
Update the thread list.
const lldb::UnixSignalsSP & GetUnixSignals()
llvm::Expected< UtilityFunction & > GetLoadImageUtilityFunction(Platform *platform, llvm::function_ref< llvm::Expected< std::unique_ptr< UtilityFunction > >()> factory)
Get the cached UtilityFunction that assists in loading binary images into the process.
void SetBaseDirection(lldb::RunDirection direction)
Set the base run direction for the process.
Status WriteMemoryTags(lldb::addr_t addr, size_t len, const std::vector< lldb::addr_t > &tags)
Write memory tags for a range of memory.
virtual size_t DoReadMemory(const ProcessAddress &process_addr, void *buf, size_t size, Status &error)=0
Actually do the reading of memory from a process.
virtual std::optional< CoreArgs > GetCoreFileArgs()
Provide arguments of a command that triggered a core dump.
virtual bool IsLiveDebugSession() const
Check if a process is a live debug session, or a corefile/post-mortem.
std::weak_ptr< Target > m_target_wp
The target that owns this process.
virtual void DoDidExec()
Subclasses of Process should implement this function if they need to do anything after a process exec...
llvm::SmallVector< std::optional< lldb::addr_t > > ReadPointersFromMemory(llvm::ArrayRef< lldb::addr_t > ptr_locs)
Use Process::ReadMemoryRanges to efficiently read multiple pointers from memory at once.
virtual void RefreshStateAfterStop()=0
Currently called as part of ShouldStop.
llvm::SmallVector< llvm::MutableArrayRef< uint8_t > > ReadMemoryRanges(llvm::ArrayRef< Range< lldb::addr_t, size_t > > ranges, llvm::MutableArrayRef< uint8_t > buffer)
Read from multiple memory ranges and write the results into buffer.
lldb::addr_t GetCodeAddressMask()
Get the current address mask in the Process.
bool UnregisterNotificationCallbacks(const Process::Notifications &callbacks)
Unregister for process and thread notifications.
bool HijackProcessEvents(lldb::ListenerSP listener_sp)
If you need to ensure that you and only you will hear about some public event, then make a new listen...
Status GetMemoryRegionInfo(lldb::addr_t load_addr, MemoryRegionInfo &range_info)
Locate the memory region that contains load_addr.
friend class DynamicLoader
static void SettingsTerminate()
lldb::addr_t GetHighmemDataAddressMask()
ThreadList m_extended_thread_list
Constituent for extended threads that may be generated, cleared on natural stops.
bool CallVoidArgVoidPtrReturn(const Address *address, lldb::addr_t &returned_func, bool trap_exceptions=false)
void AddPreResumeAction(PreResumeActionCallback callback, void *baton)
size_t GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site)
Status Halt(bool clear_thread_plans=false, bool use_run_lock=true)
Halts a running process.
const lldb::ABISP & GetABI()
Status WillLaunch(Module *module)
Called before launching to a process.
std::vector< lldb::ThreadSP > CalculateCoreFileThreadList(const SaveCoreOptions &core_options)
Helper function for Process::SaveCore(...) that calculates the thread list based upon options set wit...
size_t WriteScalarToMemory(lldb::addr_t vm_addr, const Scalar &scalar, size_t size, Status &error)
Write all or part of a scalar value to memory.
virtual size_t GetSTDOUT(char *buf, size_t buf_size, Status &error)
Get any available STDOUT.
lldb::ThreadCollectionSP GetHistoryThreads(lldb::addr_t addr)
bool PrivateStateThreadIsRunning() const
lldb::thread_result_t RunPrivateStateThread(PrivateStateThread::Purpose purpose)
lldb::StateType GetStateChangedEvents(lldb::EventSP &event_sp, const Timeout< std::micro > &timeout, lldb::ListenerSP hijack_listener)
ThreadedCommunication m_stdio_communication
std::atomic< bool > m_finalizing
The tid of the thread that issued the async interrupt, used by thread plan timeout.
std::recursive_mutex m_language_runtimes_mutex
std::string m_stderr_data
Target & GetTarget()
Get the target object pointer for this module.
virtual Status EnableWatchpoint(lldb::WatchpointSP wp_sp, bool notify=true)
lldb::OptionValuePropertiesSP m_collection_sp
T GetPropertyAtIndexAs(uint32_t idx, T default_value, const ExecutionContext *exe_ctx=nullptr) const
static llvm::StringRef GetExperimentalSettingsName()
bool SetPropertyAtIndex(uint32_t idx, T t, const ExecutionContext *exe_ctx=nullptr) const
lldb::OptionValuePropertiesSP GetValueProperties() const
A pseudo terminal helper class.
int ReleaseSecondaryFileDescriptor()
Release the secondary file descriptor.
llvm::Error OpenSecondary(int oflag)
Open the secondary for the current primary pseudo terminal.
@ invalid_fd
Invalid file descriptor value.
int ReleasePrimaryFileDescriptor()
Release the primary file descriptor.
void Append(const Entry &entry)
uint64_t GetPC(uint64_t fail_value=LLDB_INVALID_ADDRESS)
lldb::SaveCoreStyle GetStyle() const
bool HasSpecifiedThreads() const
const MemoryRanges & GetCoreFileMemoryRanges() const
bool ShouldThreadBeSaved(lldb::tid_t tid) const
size_t GetByteSize() const
bool SignExtend(uint32_t bit_pos)
unsigned long long ULongLong(unsigned long long fail_value=0) const
Scalar::Type GetType() const
size_t GetAsMemoryData(void *dst, size_t dst_len, lldb::ByteOrder dst_byte_order, Status &error) const
long long SLongLong(long long fail_value=0) const
This base class provides an interface to stack frames.
virtual StackID & GetStackID()
void CalculateExecutionContext(ExecutionContext &exe_ctx) override
Reconstruct the object's execution context into sc.
void Clear()
Clear the object state.
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
static Status FromErrorString(const char *str)
bool Fail() const
Test for error condition.
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
bool Success() const
Test for success condition.
static lldb::ValueObjectSP GetCrashingDereference(lldb::StopInfoSP &stop_info_sp, lldb::addr_t *crashing_address=nullptr)
void ForEach(std::function< void(StopPointSite *)> const &callback)
lldb::break_id_t GetID() const
virtual lldb::addr_t GetLoadAddress() const
uint32_t GetByteSize() const
lldb::break_id_t GetID() const
const char * GetData() const
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
bool ForEach(std::function< bool(Object *object)> const &foreach_callback) const
bool GetValueForKeyAsString(llvm::StringRef key, llvm::StringRef &result) const
A class which can hold structured data.
std::shared_ptr< Object > ObjectSP
Defines a symbol context baton that can be handed other debug core functions.
lldb::LanguageType GetLanguage() const
Function * function
The Function for a given query.
lldb::ModuleSP module_sp
The Module for a given query.
lldb::addr_t GetLoadAddress(Target *target) const
ConstString GetName() const
Address GetAddress() const
A plug-in interface definition class for system runtimes.
virtual void DidAttach()
Called after attaching to a process.
void ModulesDidLoad(const ModuleList &module_list) override
Called when modules have been loaded in the process.
virtual void DidLaunch()
Called after launching a process.
static SystemRuntime * FindPlugin(Process *process)
Find a system runtime plugin for a given process.
uint32_t GetIndexOfTarget(lldb::TargetSP target_sp) const
lldb::TargetSP GetSelectedTarget()
bool SetPreferDynamicValue(lldb::DynamicValueType d)
bool GetUseFastStepping() const
lldb::DynamicValueType GetPreferDynamicValue() const
void SetFirstPrivateStopTime()
void SetFirstPublicStopTime()
Module * GetExecutableModulePointer()
void MarkExecutableModule(const lldb::ModuleSP &module_sp)
Make module_sp the main executable without clearing the other images, unlike RebuildModuleListWithExe...
Debugger & GetDebugger() const
void UpdateSignalsFromDummy(lldb::UnixSignalsSP signals_sp, lldb::StreamSP warning_stream_sp)
Updates the signals in signals_sp using the stored dummy signals.
void ClearAllLoadedSections()
void ClearModules(bool delete_locations)
Architecture * GetArchitecturePlugin() const
TargetStats & GetStatistics()
bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform=false, bool merge=true)
Set the architecture for this target.
llvm::Expected< lldb::TypeSystemSP > GetScratchTypeSystemForLanguage(lldb::LanguageType language, bool create_on_demand=true)
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
void DidExec()
Called as the last function in Process::DidExec().
bool RunStopHooks(bool at_initial_stop=false)
Status Install(ProcessLaunchInfo *launch_info)
lldb::PlatformSP GetPlatform()
const ArchSpec & GetArchitecture() const
void RebuildModuleListWithExecutable(lldb::ModuleSP &module_sp, LoadDependentFiles load_dependent_files=eLoadDependentsDefault)
Clear the module list and rebuild it around a new main executable.
void SetPlatform(const lldb::PlatformSP &platform_sp)
virtual ThreadIterable Threads()
static llvm::Expected< HostThread > LaunchThread(llvm::StringRef name, std::function< lldb::thread_result_t()> thread_function, size_t min_stack_byte_size=0)
lldb::ThreadSP GetSelectedThread()
uint32_t GetSize(bool can_update=true)
bool SetSelectedThreadByID(lldb::tid_t tid, bool notify=false)
lldb::ThreadSP FindThreadByIndexID(uint32_t index_id, bool can_update=true)
lldb::ThreadSP GetThreadAtIndex(uint32_t idx, bool can_update=true)
std::recursive_mutex & GetMutex() const override
lldb::ThreadSP GetExpressionExecutionThread()
static void SettingsInitialize()
static void SettingsTerminate()
static ThreadProperties & GetGlobalProperties()
Represents UUID's of various sizes.
RAII guard that should be acquired when an utility function is called within a given process.
lldb::LanguageType GetObjectRuntimeLanguage()
#define LLDB_INVALID_BREAK_ID
#define LLDB_INVALID_ADDRESS_MASK
Address Mask Bits not used for addressing are set to 1 in the mask; all mask bits set is an invalid v...
#define LLDB_INVALID_THREAD_ID
#define UNUSED_IF_ASSERT_DISABLED(x)
#define LLDB_INVALID_ADDRESS
#define LLDB_INVALID_PROCESS_ID
@ DoNoSelectMostRelevantFrame
@ SelectMostRelevantFrame
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
bool StateIsStoppedState(lldb::StateType state, bool must_exist)
Check if a state represents a state where the process or thread is stopped.
void RegisterAssertFrameRecognizer(Process *process)
Registers the assert stack frame recognizer.
bool StateIsRunningState(lldb::StateType state)
Check if a state represents a state where the process or thread is running.
lldb::ProcessSP(* ProcessCreateInstance)(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, const FileSpec *crash_file_path, bool can_connect)
@ eBroadcastAlways
Always send a broadcast when the value is modified.
const char * StateAsCString(lldb::StateType state)
Converts a StateType to a C string.
std::vector< ProcessInstanceInfo > ProcessInstanceInfoList
static uint32_t bits(const uint32_t val, const uint32_t msbit, const uint32_t lsbit)
std::shared_ptr< lldb_private::OptionValueProperties > OptionValuePropertiesSP
std::shared_ptr< lldb_private::ThreadPlan > ThreadPlanSP
std::shared_ptr< lldb_private::ABI > ABISP
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::BreakpointSite > BreakpointSiteSP
std::shared_ptr< lldb_private::BreakpointLocation > BreakpointLocationSP
DescriptionLevel
Description levels for "void GetDescription(Stream *, DescriptionLevel)" calls.
@ eDescriptionLevelVerbose
RunDirection
Execution directions.
std::shared_ptr< lldb_private::IOHandler > IOHandlerSP
std::shared_ptr< lldb_private::Thread > ThreadSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
std::shared_ptr< lldb_private::UnixSignals > UnixSignalsSP
std::shared_ptr< lldb_private::Platform > PlatformSP
StateType
Process and Thread States.
@ eStateUnloaded
Process is object is valid, but not currently loaded.
@ eStateConnected
Process is connected to remote debug services, but not launched or attached to anything yet.
@ eStateDetached
Process has been detached and can't be examined.
@ eStateStopped
Process or thread is stopped and can be examined.
@ eStateSuspended
Process or thread is in a suspended state as far as the debugger is concerned while other processes o...
@ eStateRunning
Process or thread is running and can't be examined.
@ eStateLaunching
Process is in the process of launching.
@ eStateAttaching
Process is currently trying to attach.
@ eStateExited
Process has exited and can't be examined.
@ eStateStepping
Process or thread is in the process of stepping and can not be examined.
@ eStateCrashed
Process or thread has crashed and can be examined.
LanguageType
Programming language type.
@ eLanguageTypeMipsAssembler
Mips_Assembler.
@ eLanguageTypeUnknown
Unknown or invalid language value.
@ eLanguageTypeC
Non-standardized C, such as K&R.
std::shared_ptr< lldb_private::MemoryHistory > MemoryHistorySP
ExpressionResults
The results of expression evaluation.
@ eExpressionHitBreakpoint
@ eExpressionStoppedForDebug
@ eExpressionThreadVanished
std::shared_ptr< lldb_private::StructuredDataPlugin > StructuredDataPluginSP
std::shared_ptr< lldb_private::Process > ProcessSP
InstrumentationRuntimeType
std::shared_ptr< lldb_private::Disassembler > DisassemblerSP
std::shared_ptr< lldb_private::LanguageRuntime > LanguageRuntimeSP
std::shared_ptr< lldb_private::Event > EventSP
std::unique_ptr< lldb_private::DynamicLoader > DynamicLoaderUP
ByteOrder
Byte ordering definitions.
std::shared_ptr< lldb_private::Watchpoint > WatchpointSP
std::shared_ptr< lldb_private::Listener > ListenerSP
std::shared_ptr< lldb_private::StopInfo > StopInfoSP
std::shared_ptr< lldb_private::WritableDataBuffer > WritableDataBufferSP
StopReason
Thread stop reasons.
@ eStopReasonPlanComplete
std::shared_ptr< lldb_private::Target > TargetSP
std::shared_ptr< lldb_private::RegisterContext > RegisterContextSP
std::shared_ptr< lldb_private::InstrumentationRuntime > InstrumentationRuntimeSP
std::shared_ptr< lldb_private::Module > ModuleSP
std::shared_ptr< lldb_private::OptionValue > OptionValueSP
std::shared_ptr< lldb_private::ThreadCollection > ThreadCollectionSP
A single address space reported by a process.
lldb::addr_space_t space_id
A SmallBitVector that represents a set of source languages (lldb::LanguageType).
bool can_run_all_threads
Whether expression evaluation may resume all threads to avoid deadlocks (e.g.
bool can_try_all_threads
Whether the expression runner may fall back to running all threads after a single-thread attempt time...
Describes what view of the process a thread should see and what operations it is allowed to perform.
Capabilities capabilities
@ Private
Parent (unwinder) frames, private state, private run lock.
BreakpointSiteToActionMap m_site_to_action
void Enqueue(lldb::BreakpointSiteSP site, BreakpointAction action)
A notification structure that can be used by clients to listen for changes in a process's lifetime.
void(* process_state_changed)(void *baton, Process *process, lldb::StateType state)
void(* initialize)(void *baton, Process *process)
The PrivateStateThread struct gathers all the bits of state needed to manage handling Process events,...
ProcessRunLock m_public_run_lock
Process & m_process
The process state that we show to client code.
ProcessRunLock & GetRunLock()
Purpose m_purpose
This will be the thread name given to the Private State HostThread when it gets spun up.
HostThread m_private_state_thread
bool IsOnThread(const HostThread &thread) const
std::string m_thread_name
Policy::PrivateStatePurpose Purpose
Why this PST exists.
ProcessRunLock m_private_run_lock
bool Contains(BaseType r) const
BaseType GetRangeBase() const
SizeType GetByteSize() const
void SetRangeBase(BaseType b)
Set the start value for the range, and keep the same size.
BaseType GetRangeEnd() const
Range Intersect(const Range &rhs) const
void SetByteSize(SizeType s)
std::optional< ExitDescription > exit_desc
Helper RAII class for collecting telemetry.
void DispatchOnExit(llvm::unique_function< void(Info *info)> final_callback)
void DispatchNow(llvm::unique_function< void(Info *info)> populate_fields_cb)
void SetDebugger(Debugger *debugger)