13 #include "llvm/ADT/ScopeExit.h"
14 #include "llvm/Support/ScopedPrinter.h"
15 #include "llvm/Support/Threading.h"
77 using namespace std::chrono;
81 #define ENABLE_MEMORY_CACHING
83 #ifdef ENABLE_MEMORY_CACHING
84 #define DISABLE_MEM_CACHE_DEFAULT false
86 #define DISABLE_MEM_CACHE_DEFAULT true
90 :
public Cloneable<ProcessOptionValueProperties, OptionValueProperties> {
106 if (
this != instance_properties)
110 return ProtectedGetPropertyAtIndex(idx);
118 "Continue tracing the parent process and detach the child.",
123 "Trace the child process and detach the parent.",
127 #define LLDB_PROPERTIES_process
128 #include "TargetProperties.inc"
131 #define LLDB_PROPERTIES_process
132 #include "TargetPropertiesEnum.inc"
136 #define LLDB_PROPERTIES_process_experimental
137 #include "TargetProperties.inc"
140 #define LLDB_PROPERTIES_process_experimental
141 #include "TargetPropertiesEnum.inc"
145 :
public Cloneable<ProcessExperimentalOptionValueProperties,
146 OptionValueProperties> {
153 ProcessExperimentalProperties::ProcessExperimentalProperties()
163 if (process ==
nullptr) {
166 std::make_shared<ProcessOptionValueProperties>(
ConstString(
"process"));
175 ePropertyPythonOSPluginPath,
180 std::make_unique<ProcessExperimentalProperties>();
183 ConstString(
"Experimental settings - setting these won't produce "
184 "errors if the setting is not present."),
191 const uint32_t idx = ePropertyDisableMemCache;
193 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
197 const uint32_t idx = ePropertyMemCacheLineSize;
199 nullptr, idx, g_process_properties[idx].default_uint_value);
204 const uint32_t idx = ePropertyExtraStartCommand;
210 const uint32_t idx = ePropertyExtraStartCommand;
215 const uint32_t idx = ePropertyPythonOSPluginPath;
220 const uint32_t idx = ePropertyVirtualAddressableBits;
222 nullptr, idx, g_process_properties[idx].default_uint_value);
226 const uint32_t idx = ePropertyVirtualAddressableBits;
230 const uint32_t idx = ePropertyPythonOSPluginPath;
235 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
237 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
241 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
246 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
248 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
252 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
257 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
259 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
263 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
268 const uint32_t idx = ePropertyDisableLangRuntimeUnwindPlans;
270 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
274 const uint32_t idx = ePropertyDisableLangRuntimeUnwindPlans;
280 const uint32_t idx = ePropertyDetachKeepsStopped;
282 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
286 const uint32_t idx = ePropertyDetachKeepsStopped;
291 const uint32_t idx = ePropertyWarningOptimization;
293 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
297 const uint32_t idx = ePropertyWarningUnsupportedLanguage;
299 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
303 const uint32_t idx = ePropertyStopOnExec;
305 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
309 const uint32_t idx = ePropertyUtilityExpressionTimeout;
311 nullptr, idx, g_process_properties[idx].default_uint_value);
312 return std::chrono::seconds(value);
316 const uint32_t idx = ePropertyInterruptTimeout;
318 nullptr, idx, g_process_properties[idx].default_uint_value);
319 return std::chrono::seconds(value);
323 const uint32_t idx = ePropertySteppingRunsAllThreads;
325 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
329 const bool fail_value =
true;
333 exp_property->
GetValue()->GetAsProperties();
338 nullptr, ePropertyOSPluginReportsAllThreads, fail_value);
345 exp_property->
GetValue()->GetAsProperties();
348 nullptr, ePropertyOSPluginReportsAllThreads, does_report);
352 const uint32_t idx = ePropertyFollowForkMode;
354 nullptr, idx, g_process_properties[idx].default_uint_value);
358 llvm::StringRef plugin_name,
359 ListenerSP listener_sp,
362 static uint32_t g_process_unique_id = 0;
364 ProcessSP process_sp;
365 ProcessCreateInstance create_callback =
nullptr;
366 if (!plugin_name.empty()) {
369 if (create_callback) {
370 process_sp = create_callback(target_sp, listener_sp, crash_file_path,
373 if (process_sp->CanDebug(target_sp,
true)) {
374 process_sp->m_process_unique_id = ++g_process_unique_id;
384 process_sp = create_callback(target_sp, listener_sp, crash_file_path,
387 if (process_sp->CanDebug(target_sp,
false)) {
388 process_sp->m_process_unique_id = ++g_process_unique_id;
404 :
Process(target_sp, listener_sp,
411 const UnixSignalsSP &unix_signals_sp)
413 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
414 Process::GetStaticBroadcasterClass().AsCString()),
417 m_private_state_broadcaster(nullptr,
418 "lldb.process.internal_state_broadcaster"),
419 m_private_state_control_broadcaster(
420 nullptr,
"lldb.process.internal_state_control_broadcaster"),
421 m_private_state_listener_sp(
422 Listener::MakeListener(
"lldb.process.internal_state_listener")),
423 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
424 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
425 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
426 m_thread_list(this), m_thread_plans(*this), m_extended_thread_list(this),
427 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
428 m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
429 m_breakpoint_site_list(), m_dynamic_checkers_up(),
430 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
431 m_stdio_communication(
"process.stdio"), m_stdio_communication_mutex(),
432 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
433 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
434 m_memory_cache(*this), m_allocated_memory_cache(*this),
435 m_should_detach(false), m_next_event_action_up(), m_public_run_lock(),
436 m_private_run_lock(), m_finalizing(false),
437 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
438 m_last_broadcast_state(
eStateInvalid), m_destroy_in_process(false),
439 m_can_interpret_function_calls(false), m_run_thread_plan_lock(),
440 m_can_jit(eCanJITDontKnow) {
444 LLDB_LOGF(log,
"%p Process::Process()",
static_cast<void *
>(
this));
480 OptionValueSP value_sp =
482 ->GetPropertyAtIndex(
nullptr,
true, ePropertyMemCacheLineSize)
485 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
486 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
487 value_sp->SetUInt64Value(platform_cache_line_size);
494 LLDB_LOGF(log,
"%p Process::~Process()",
static_cast<void *
>(
this));
508 return *g_settings_ptr;
540 std::vector<Notifications> empty_notifications;
583 if (pos->baton == callbacks.
baton &&
594 std::vector<Notifications>::iterator notification_pos,
597 notification_pos != notification_end; ++notification_pos) {
598 if (notification_pos->process_state_changed)
599 notification_pos->process_state_changed(notification_pos->baton,
this,
618 std::chrono::seconds(0)) &&
638 "waited from m_iohandler_sync to change from {0}. New value is {1}.",
639 iohandler_id, *Result);
641 LLDB_LOG(log,
"timed out waiting for m_iohandler_sync to change from {0}.",
647 EventSP *event_sp_ptr,
bool wait_always,
648 ListenerSP hijack_listener_sp,
649 Stream *stream,
bool use_run_lock) {
654 event_sp_ptr->reset();
662 LLDB_LOG(log,
"timeout = {0}", timeout);
667 "Process::%s returning without waiting for events; process "
668 "private and public states are already 'stopped'.",
672 if (hijack_listener_sp && use_run_lock)
680 if (event_sp_ptr && event_sp)
681 *event_sp_ptr = event_sp;
683 bool pop_process_io_handler = (hijack_listener_sp.get() !=
nullptr);
685 pop_process_io_handler);
694 if (hijack_listener_sp && use_run_lock)
703 if (hijack_listener_sp && use_run_lock)
716 bool &pop_process_io_handler) {
717 const bool handle_pop = pop_process_io_handler;
719 pop_process_io_handler =
false;
720 ProcessSP process_sp =
731 switch (event_state) {
739 stream->
Printf(
"Process %" PRIu64
" %s\n", process_sp->GetID(),
742 pop_process_io_handler =
true;
752 process_sp->GetStatus(*stream);
753 pop_process_io_handler =
true;
764 if (num_reasons > 0) {
767 if (num_reasons == 1) {
771 stream->
Printf(
"Process %" PRIu64
" stopped and restarted: %s\n",
773 reason ? reason :
"<UNKNOWN REASON>");
775 stream->
Printf(
"Process %" PRIu64
776 " stopped and restarted, reasons:\n",
777 process_sp->GetID());
779 for (
size_t i = 0; i < num_reasons; i++) {
783 stream->
Printf(
"\t%s\n", reason ? reason :
"<UNKNOWN REASON>");
789 StopInfoSP curr_thread_stop_info_sp;
793 ThreadList &thread_list = process_sp->GetThreadList();
794 std::lock_guard<std::recursive_mutex> guard(thread_list.
GetMutex());
799 bool prefer_curr_thread =
false;
800 if (curr_thread && curr_thread->IsValid()) {
801 curr_thread_stop_reason = curr_thread->GetStopReason();
802 switch (curr_thread_stop_reason) {
811 uint64_t signo = curr_thread->GetStopInfo()->GetValue();
812 if (process_sp->GetUnixSignals()->GetShouldStop(signo))
813 prefer_curr_thread =
true;
816 prefer_curr_thread =
true;
819 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
822 if (!prefer_curr_thread) {
825 ThreadSP plan_thread;
826 ThreadSP other_thread;
828 const size_t num_threads = thread_list.
GetSize();
830 for (i = 0; i < num_threads; ++i) {
832 StopReason thread_stop_reason = thread->GetStopReason();
833 switch (thread_stop_reason) {
842 uint64_t signo = thread->GetStopInfo()->GetValue();
843 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
845 other_thread = thread;
861 other_thread = thread;
865 plan_thread = thread;
871 else if (other_thread)
874 if (curr_thread && curr_thread->IsValid())
875 thread = curr_thread;
889 Debugger &debugger = process_sp->GetTarget().GetDebugger();
891 &process_sp->GetTarget()) {
892 ThreadSP thread_sp = process_sp->GetThreadList().GetSelectedThread();
894 if (!thread_sp || !thread_sp->IsValid())
897 const bool only_threads_with_stop_reason =
true;
898 const uint32_t start_frame = thread_sp->GetSelectedFrameIndex();
900 const uint32_t num_frames_with_source = 1;
901 const bool stop_format =
true;
903 process_sp->GetStatus(*stream);
904 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
905 start_frame, num_frames,
906 num_frames_with_source,
908 if (curr_thread_stop_info_sp) {
911 curr_thread_stop_info_sp, &crashing_address);
914 ValueObject::GetExpressionPathFormat::
915 eGetExpressionPathFormatHonorPointers;
917 valobj_sp->GetExpressionPath(*stream, format);
918 stream->
Printf(
" accessed 0x%" PRIx64
"\n", crashing_address);
923 process_sp->GetTarget().shared_from_this());
925 stream->
Printf(
"Target %d: (", target_idx);
927 stream->
Printf(
"Target <unknown index>: (");
929 stream->
Printf(
") stopped.\n");
934 pop_process_io_handler =
true;
939 if (handle_pop && pop_process_io_handler)
940 process_sp->PopProcessIOHandler();
957 ListenerSP hijack_listener_sp) {
959 LLDB_LOG(log,
"timeout = {0}, event_sp)...", timeout);
961 ListenerSP listener_sp = hijack_listener_sp;
966 if (listener_sp->GetEventForBroadcasterWithType(
972 LLDB_LOG(log,
"got no event or was interrupted.");
975 LLDB_LOG(log,
"timeout = {0}, event_sp) => {1}", timeout, state);
982 LLDB_LOGF(log,
"Process::%s...", __FUNCTION__);
985 event_ptr =
m_listener_sp->PeekAtNextEventForBroadcasterWithType(
989 LLDB_LOGF(log,
"Process::%s (event_ptr) => %s", __FUNCTION__,
992 LLDB_LOGF(log,
"Process::%s no events found", __FUNCTION__);
1002 LLDB_LOG(log,
"timeout = {0}, event_sp)...", timeout);
1012 LLDB_LOG(log,
"timeout = {0}, event_sp) => {1}", timeout,
1019 bool control_only) {
1021 LLDB_LOG(log,
"timeout = {0}, event_sp)...", timeout);
1056 log,
"Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1057 status, status, cstr ?
"\"" :
"", cstr ? cstr :
"NULL", cstr ?
"\"" :
"");
1061 LLDB_LOGF(log,
"Process::SetExitStatus () ignoring exit status because "
1062 "state was already set to eStateExited");
1111 "Process::SetProcessExitStatus (pid=%" PRIu64
1112 ", exited=%i, signal=%i, exit_status=%i)\n",
1113 pid, exited, signo, exit_status);
1118 ProcessSP process_sp(target_sp->GetProcessSP());
1120 const char *signal_cstr =
nullptr;
1122 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1124 process_sp->SetExitStatus(exit_status, signal_cstr);
1142 bool clear_unused_threads =
true;
1165 size_t num_old_threads = old_thread_list.
GetSize(
false);
1166 for (
size_t i = 0; i < num_old_threads; ++i)
1199 new_thread_list = real_thread_list;
1239 bool internal,
bool condense_trivial,
1240 bool skip_unreported_plans) {
1242 strm, tid, desc_level,
internal, condense_trivial, skip_unreported_plans);
1245 bool internal,
bool condense_trivial,
1246 bool skip_unreported_plans) {
1248 skip_unreported_plans);
1282 std::map<uint64_t, uint32_t>::iterator iterator =
1288 result = iterator->second;
1300 if (new_state_is_stopped) {
1311 LLDB_LOGF(log,
"Process::SetPublicState (state = %s, restarted = %i)",
1322 "Process::SetPublicState (%s) -- unlocking run lock for detach",
1327 if ((old_state_is_stopped != new_state_is_stopped)) {
1328 if (new_state_is_stopped && !restarted) {
1329 LLDB_LOGF(log,
"Process::SetPublicState (%s) -- unlocking run lock",
1340 LLDB_LOGF(log,
"Process::Resume -- locking run lock");
1342 Status error(
"Resume request failed - process still running.");
1343 LLDB_LOGF(log,
"Process::Resume: -- TrySetRunning failed, not resuming.");
1347 if (!
error.Success()) {
1358 LLDB_LOGF(log,
"Process::ResumeSynchronous -- locking run lock");
1360 Status error(
"Resume request failed - process still running.");
1361 LLDB_LOGF(log,
"Process::Resume: -- TrySetRunning failed, not resuming.");
1365 ListenerSP listener_sp(
1370 if (
error.Success()) {
1372 listener_sp, stream);
1373 const bool must_be_alive =
1376 error.SetErrorStringWithFormat(
1377 "process not in stopped state after synchronous resume: %s",
1393 if (hijacking_name &&
1403 if (hijacking_name &&
1417 bool state_changed =
false;
1425 state_changed = old_state != new_state;
1429 if (old_state_is_stopped != new_state_is_stopped) {
1430 if (new_state_is_stopped)
1436 if (state_changed) {
1460 LLDB_LOGF(log,
"Process::SetPrivateState (%s) stop_id = %u",
1467 "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1489 std::vector<LanguageRuntime *> language_runtimes;
1492 return language_runtimes;
1502 language_runtimes.emplace_back(runtime);
1505 return language_runtimes;
1515 LanguageRuntimeCollection::iterator pos;
1518 lldb::LanguageRuntimeSP runtime_sp(
1522 runtime = runtime_sp.get();
1524 runtime = pos->second.get();
1550 if (runtime->CouldHaveDynamicValue(in_value))
1579 if (
error.Success())
1589 if (bp_site_sp->IsEnabled())
1592 error.SetErrorStringWithFormat(
"invalid breakpoint site ID: %" PRIu64,
1603 if (!bp_site_sp->IsEnabled())
1606 error.SetErrorStringWithFormat(
"invalid breakpoint site ID: %" PRIu64,
1614 bool use_hardware) {
1617 bool show_error =
true;
1640 owner->SetIsIndirect(
false);
1642 if (owner->ShouldResolveIndirectFunctions()) {
1648 if (!
error.Success() && show_error) {
1650 "warning: failed to resolve indirect function at 0x%" PRIx64
1651 " for breakpoint %i.%i: %s\n",
1653 owner->GetBreakpoint().GetID(), owner->GetID(),
1654 error.AsCString() ?
error.AsCString() :
"unknown error");
1657 Address resolved_address(load_addr);
1659 owner->SetIsIndirect(
true);
1661 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&
GetTarget());
1663 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&
GetTarget());
1666 BreakpointSiteSP bp_site_sp;
1674 bp_site_sp->AddOwner(owner);
1675 owner->SetBreakpointSite(bp_site_sp);
1676 return bp_site_sp->GetID();
1679 load_addr, use_hardware));
1682 if (
error.Success()) {
1683 owner->SetBreakpointSite(bp_site_sp);
1686 if (show_error || use_hardware) {
1689 "warning: failed to set breakpoint site at 0x%" PRIx64
1690 " for breakpoint %i.%i: %s\n",
1691 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1692 error.AsCString() ?
error.AsCString() :
"unknown error");
1704 BreakpointSiteSP &bp_site_sp) {
1705 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1706 if (num_owners == 0) {
1715 uint8_t *buf)
const {
1716 size_t bytes_removed = 0;
1720 bp_sites_in_range)) {
1721 bp_sites_in_range.
ForEach([bp_addr, size,
1724 addr_t intersect_addr;
1725 size_t intersect_size;
1726 size_t opcode_offset;
1727 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1728 &intersect_size, &opcode_offset)) {
1729 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1730 assert(bp_addr < intersect_addr + intersect_size &&
1731 intersect_addr + intersect_size <= bp_addr + size);
1732 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1733 size_t buf_offset = intersect_addr - bp_addr;
1734 ::memcpy(buf + buf_offset,
1735 bp_site->GetSavedOpcodeBytes() + opcode_offset,
1741 return bytes_removed;
1745 PlatformSP platform_sp(
GetTarget().GetPlatform());
1747 return platform_sp->GetSoftwareBreakpointTrapOpcode(
GetTarget(), bp_site);
1753 assert(bp_site !=
nullptr);
1757 log,
"Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
1758 bp_site->
GetID(), (uint64_t)bp_addr);
1762 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1763 " -- already enabled",
1764 bp_site->
GetID(), (uint64_t)bp_addr);
1769 error.SetErrorString(
"BreakpointSite contains an invalid load address.");
1776 if (bp_opcode_size == 0) {
1777 error.SetErrorStringWithFormat(
"Process::GetSoftwareBreakpointTrapOpcode() "
1778 "returned zero, unable to get breakpoint "
1779 "trap for address 0x%" PRIx64,
1784 if (bp_opcode_bytes ==
nullptr) {
1785 error.SetErrorString(
1786 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1792 error) == bp_opcode_size) {
1796 uint8_t verify_bp_opcode_bytes[64];
1797 if (
DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
1798 error) == bp_opcode_size) {
1799 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
1800 bp_opcode_size) == 0) {
1804 "Process::EnableSoftwareBreakpoint (site_id = %d) "
1805 "addr = 0x%" PRIx64
" -- SUCCESS",
1806 bp_site->
GetID(), (uint64_t)bp_addr);
1808 error.SetErrorString(
1809 "failed to verify the breakpoint trap in memory.");
1811 error.SetErrorString(
1812 "Unable to read memory to verify breakpoint trap.");
1814 error.SetErrorString(
"Unable to write breakpoint trap to memory.");
1816 error.SetErrorString(
"Unable to read memory at breakpoint address.");
1818 if (log &&
error.Fail())
1821 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1823 bp_site->
GetID(), (uint64_t)bp_addr,
error.AsCString());
1829 assert(bp_site !=
nullptr);
1834 "Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
1835 ") addr = 0x%" PRIx64,
1836 breakID, (uint64_t)bp_addr);
1839 error.SetErrorString(
"Breakpoint site is a hardware breakpoint.");
1841 const size_t break_op_size = bp_site->
GetByteSize();
1843 if (break_op_size > 0) {
1845 uint8_t curr_break_op[8];
1846 assert(break_op_size <=
sizeof(curr_break_op));
1847 bool break_op_found =
false;
1852 bool verify =
false;
1854 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
1855 break_op_found =
true;
1859 break_op_size,
error) == break_op_size) {
1862 error.SetErrorString(
1863 "Memory write failed when restoring original opcode.");
1865 error.SetErrorString(
1866 "Original breakpoint trap is no longer in memory.");
1873 uint8_t verify_opcode[8];
1874 assert(break_op_size <
sizeof(verify_opcode));
1880 break_op_size) == 0) {
1884 "Process::DisableSoftwareBreakpoint (site_id = %d) "
1885 "addr = 0x%" PRIx64
" -- SUCCESS",
1886 bp_site->
GetID(), (uint64_t)bp_addr);
1890 error.SetErrorString(
"Failed to restore original opcode.");
1893 error.SetErrorString(
"Failed to read memory to verify that "
1894 "breakpoint trap was restored.");
1897 error.SetErrorString(
1898 "Unable to read memory that should contain the breakpoint trap.");
1903 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1904 " -- already disabled",
1905 bp_site->
GetID(), (uint64_t)bp_addr);
1911 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1913 bp_site->
GetID(), (uint64_t)bp_addr,
error.AsCString());
1922 if (ABISP abi_sp =
GetABI())
1923 addr = abi_sp->FixAnyAddress(addr);
1927 #if defined(VERIFY_MEMORY_READS)
1940 assert(verify_buf.size() == size);
1941 const size_t cache_bytes_read =
1944 const size_t verify_bytes_read =
1946 verify_buf.size(), verify_error);
1947 assert(cache_bytes_read == verify_bytes_read);
1948 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1950 return cache_bytes_read;
1953 #else // !defined(VERIFY_MEMORY_READS)
1957 #endif // defined (VERIFY_MEMORY_READS)
1974 out_str.append(buf, length);
1977 if (length ==
sizeof(buf) - 1)
1978 curr_addr += length;
1982 return out_str.size();
1990 size_t total_cstr_len = 0;
1991 if (dst && dst_max_len) {
1992 result_error.
Clear();
1994 memset(dst, 0, dst_max_len);
1998 size_t bytes_left = dst_max_len - 1;
1999 char *curr_dst = dst;
2001 while (bytes_left > 0) {
2002 addr_t cache_line_bytes_left =
2003 cache_line_size - (curr_addr % cache_line_size);
2005 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2006 size_t bytes_read =
ReadMemory(curr_addr, curr_dst, bytes_to_read,
error);
2008 if (bytes_read == 0) {
2009 result_error =
error;
2010 dst[total_cstr_len] =
'\0';
2013 const size_t len = strlen(curr_dst);
2015 total_cstr_len += len;
2017 if (len < bytes_to_read)
2020 curr_dst += bytes_read;
2021 curr_addr += bytes_read;
2022 bytes_left -= bytes_read;
2028 result_error.
Clear();
2030 return total_cstr_len;
2037 if (ABISP abi_sp =
GetABI())
2038 addr = abi_sp->FixAnyAddress(addr);
2040 if (buf ==
nullptr || size == 0)
2043 size_t bytes_read = 0;
2044 uint8_t *bytes = (uint8_t *)buf;
2046 while (bytes_read < size) {
2047 const size_t curr_size = size - bytes_read;
2048 const size_t curr_bytes_read =
2050 bytes_read += curr_bytes_read;
2051 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2063 size_t integer_byte_size,
2064 uint64_t fail_value,
2074 size_t integer_byte_size,
2096 if (addr_byte_size <= 4)
2106 size_t bytes_written = 0;
2107 const uint8_t *bytes = (
const uint8_t *)buf;
2109 while (bytes_written < size) {
2110 const size_t curr_size = size - bytes_written;
2112 addr + bytes_written, bytes + bytes_written, curr_size,
error);
2113 bytes_written += curr_bytes_written;
2114 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2117 return bytes_written;
2122 if (ABISP abi_sp =
GetABI())
2123 addr = abi_sp->FixAnyAddress(addr);
2125 #if defined(ENABLE_MEMORY_CACHING)
2129 if (buf ==
nullptr || size == 0)
2143 if (bp_sites_in_range.
IsEmpty())
2146 const uint8_t *ubuf = (
const uint8_t *)buf;
2147 uint64_t bytes_written = 0;
2149 bp_sites_in_range.
ForEach([
this, addr, size, &bytes_written, &ubuf,
2158 size_t intersect_size;
2159 size_t opcode_offset;
2161 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2164 assert(addr <= intersect_addr && intersect_addr < addr + size);
2165 assert(addr < intersect_addr + intersect_size &&
2166 intersect_addr + intersect_size <= addr + size);
2167 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2170 const addr_t curr_addr = addr + bytes_written;
2171 if (intersect_addr > curr_addr) {
2174 size_t curr_size = intersect_addr - curr_addr;
2175 size_t curr_bytes_written =
2177 bytes_written += curr_bytes_written;
2178 if (curr_bytes_written != curr_size) {
2182 if (
error.Success())
2183 error.SetErrorToGenericError();
2190 bytes_written += intersect_size;
2194 if (bytes_written < size)
2197 size - bytes_written,
error);
2199 return bytes_written;
2206 if (byte_size > 0) {
2208 const size_t mem_size =
2213 error.SetErrorString(
"failed to get scalar as memory data");
2215 error.SetErrorString(
"invalid scalar value");
2221 bool is_signed,
Scalar &scalar,
2224 if (byte_size == 0) {
2225 error.SetErrorString(
"byte size is zero");
2226 }
else if (byte_size & (byte_size - 1)) {
2227 error.SetErrorStringWithFormat(
"byte size %u is not a power of 2",
2229 }
else if (byte_size <=
sizeof(uval)) {
2231 if (bytes_read == byte_size) {
2236 scalar = data.
GetMaxU32(&offset, byte_size);
2238 scalar = data.
GetMaxU64(&offset, byte_size);
2244 error.SetErrorStringWithFormat(
2245 "byte size of %u is too large for integer scalar type", byte_size);
2252 for (
const auto &
Entry : entries) {
2255 if (!
error.Success())
2261 #define USE_ALLOCATE_MEMORY_CACHE 1
2265 error.SetErrorToGenericError();
2269 #if defined(USE_ALLOCATE_MEMORY_CACHE)
2275 "Process::AllocateMemory(size=%" PRIu64
2276 ", permissions=%s) => 0x%16.16" PRIx64
2277 " (m_stop_id = %u m_memory_id = %u)",
2281 return allocated_addr;
2288 if (
error.Success()) {
2301 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2307 "Process::%s pid %" PRIu64
2308 " allocation test passed, CanJIT () is true",
2309 __FUNCTION__,
GetID());
2313 "Process::%s pid %" PRIu64
2314 " allocation test failed, CanJIT () is false: %s",
2335 #if defined(USE_ALLOCATE_MEMORY_CACHE)
2337 error.SetErrorStringWithFormat(
2338 "deallocation of memory at 0x%" PRIx64
" failed.", (uint64_t)ptr);
2345 "Process::DeallocateMemory(addr=0x%16.16" PRIx64
2346 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2355 size_t size_to_read) {
2359 "Process::ReadModuleFromMemory reading %s binary from memory",
2365 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2366 shared_from_this(), header_addr,
error, size_to_read);
2378 if (!
error.Success())
2387 permissions |= lldb::ePermissionsReadable;
2390 permissions |= lldb::ePermissionsWritable;
2393 permissions |= lldb::ePermissionsExecutable;
2400 error.SetErrorString(
"watchpoints are not supported");
2406 error.SetErrorString(
"watchpoints are not supported");
2442 EventSP first_stop_event_sp;
2444 LaunchPrivate(launch_info, state_after_launch, first_stop_event_sp);
2466 if (launch_info.
GetFlags().
Test(eLaunchFlagStopAtEntry))
2473 EventSP &event_sp) {
2494 error.SetErrorString(
"executable module does not exist");
2521 return Status(
"file doesn't exist: '%s'", local_exec_file_path.c_str());
2524 const bool restarted =
false;
2533 error.SetErrorString(
"failed to acquire process run lock");
2539 const char *error_string =
error.AsCString();
2540 if (error_string ==
nullptr)
2541 error_string =
"launch failed";
2554 error.SetErrorString(
"failed to catch stop after launch");
2596 return Status(
"Unexpected process state after the launch: %s, expected %s, "
2605 if (
error.Success()) {
2606 ListenerSP listener_sp(
2633 lldb::EventSP event_sp;
2639 LLDB_LOGF(log,
"Process::Halt() failed to stop, state is: %s",
2641 error.SetErrorString(
2642 "Did not get stopped event after loading the core file.");
2681 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2682 __FUNCTION__,
static_cast<void *
>(process), exec_count);
2691 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2696 return eEventActionSuccess;
2700 return eEventActionRetry;
2711 if (m_exec_count > 0) {
2715 "Process::AttachCompletionHandler::%s state %s: reduced "
2716 "remaining exec count to %" PRIu32
", requesting resume",
2720 return eEventActionRetry;
2723 "Process::AttachCompletionHandler::%s state %s: no more "
2724 "execs expected to start, continuing with attach",
2728 return eEventActionSuccess;
2739 return eEventActionExit;
2744 return eEventActionSuccess;
2772 sizeof(process_name))) {
2775 if (wait_for_launch) {
2777 if (
error.Success()) {
2780 const bool restarted =
false;
2786 error.SetErrorString(
"failed to acquire process run lock");
2792 if (
error.AsCString() ==
nullptr)
2793 error.SetErrorString(
"attach failed");
2806 PlatformSP platform_sp(
GetTarget().GetPlatform());
2812 platform_sp->FindProcesses(match_info, process_infos);
2813 const uint32_t num_matches = process_infos.size();
2814 if (num_matches == 1) {
2815 attach_pid = process_infos[0].GetProcessID();
2819 process_name,
sizeof(process_name));
2820 if (num_matches > 1) {
2823 for (
size_t i = 0; i < num_matches; i++) {
2824 process_infos[i].DumpAsTableRow(
2825 s, platform_sp->GetUserIDResolver(),
true,
false);
2827 error.SetErrorStringWithFormat(
2828 "more than one process named %s:\n%s", process_name,
2831 error.SetErrorStringWithFormat(
2832 "could not find a process named %s", process_name);
2835 error.SetErrorString(
2836 "invalid platform, can't find processes by name");
2841 error.SetErrorString(
"invalid process name");
2847 if (
error.Success()) {
2852 const bool restarted =
false;
2857 error.SetErrorString(
"failed to acquire process run lock");
2860 if (
error.Success()) {
2868 const char *error_string =
error.AsCString();
2869 if (error_string ==
nullptr)
2870 error_string =
"attach failed";
2881 LLDB_LOGF(log,
"Process::%s()", __FUNCTION__);
2891 const char *triple_str = process_arch.
GetTriple().getTriple().c_str();
2893 "Process::%s replacing process architecture with DidAttach() "
2895 __FUNCTION__, triple_str ? triple_str :
"<null>");
2902 PlatformSP platform_sp(
GetTarget().GetPlatform());
2903 assert(platform_sp);
2908 !platform_sp->IsCompatibleArchitecture(target_arch, process_host_arch,
2912 target_arch, process_host_arch, &platform_arch);
2917 "switching platform to {0} and architecture to {1} based on "
2919 platform_sp->GetName(), platform_arch.
GetTriple().getTriple());
2921 }
else if (!process_arch.
IsValid()) {
2931 "Process::%s switching architecture to %s based on info "
2932 "the platform retrieved for pid %" PRIu64,
2933 __FUNCTION__, process_arch.
GetTriple().getTriple().c_str(),
2953 "after DynamicLoader::DidAttach(), target "
2954 "executable is {0} (using {1} plugin)",
2955 exe_module_sp ? exe_module_sp->GetFileSpec() :
FileSpec(),
2963 if (system_runtime) {
2968 "after SystemRuntime::DidAttach(), target "
2969 "executable is {0} (using {1} plugin)",
2970 exe_module_sp ? exe_module_sp->GetFileSpec() :
FileSpec(),
2986 ModuleSP new_executable_module_sp;
2988 if (module_sp && module_sp->IsExecutable()) {
2989 if (
GetTarget().GetExecutableModulePointer() != module_sp.get())
2990 new_executable_module_sp = module_sp;
2994 if (new_executable_module_sp) {
3001 "Process::%s after looping through modules, target executable is %s",
3003 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3017 if (
error.Success()) {
3044 "Process::PrivateResume() m_stop_id = %u, public state: %s "
3045 "private state: %s",
3055 if (
error.Success()) {
3066 error.SetErrorString(
3067 "Process::PrivateResume PreResumeActions failed, not resuming.");
3071 if (
error.Success()) {
3074 LLDB_LOGF(log,
"Process thinks the process has resumed.");
3076 LLDB_LOGF(log,
"Process::PrivateResume() DoResume failed.");
3086 "Process::PrivateResume() asked to simulate a start & stop.");
3092 LLDB_LOGF(log,
"Process::PrivateResume() got an error \"%s\".",
3093 error.AsCString(
"<unknown error>"));
3099 return Status(
"Process is not running.");
3105 ListenerSP halt_listener_sp(
3125 halt_listener_sp,
nullptr, use_run_lock);
3147 LLDB_LOGF(log,
"Process::%s() About to stop.", __FUNCTION__);
3149 ListenerSP listener_sp(
3157 &exit_event_sp,
true, listener_sp);
3167 LLDB_LOGF(log,
"Process::%s() Process exited while waiting to stop.",
3171 exit_event_sp.reset();
3174 LLDB_LOGF(log,
"Process::%s() failed to stop, state is: %s", __FUNCTION__,
3182 "Attempt to stop the target in order to detach timed out. "
3192 EventSP exit_event_sp;
3198 if (
error.Success()) {
3201 if (!
error.Success()) {
3204 }
else if (exit_event_sp) {
3217 if (
error.Success()) {
3228 if (exit_event_sp) {
3263 bool keep_stopped =
false;
3270 if (
error.Success()) {
3271 EventSP exit_event_sp;
3287 if (
error.Success()) {
3303 if (exit_event_sp) {
3323 if (
error.Success()) {
3325 if (
error.Success())
3332 assert(signals_sp &&
"null signals_sp");
3352 bool return_value =
true;
3370 return_value =
true;
3374 return_value =
false;
3386 return_value =
true;
3392 return_value =
false;
3405 return_value =
true;
3408 return_value =
false;
3427 "Process::ShouldBroadcastEvent (%p) stopped due to an "
3428 "interrupt, state: %s",
3433 return_value =
true;
3436 bool should_resume =
false;
3448 "Process::ShouldBroadcastEvent: should_resume: %i state: "
3449 "%s was_restarted: %i report_stop_vote: %d.",
3453 switch (report_stop_vote) {
3455 return_value =
true;
3459 return_value =
false;
3463 if (!was_restarted) {
3465 "Process::ShouldBroadcastEvent (%p) Restarting process "
3472 return_value =
true;
3495 "Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3496 "broadcast state: %s - %s",
3499 return_value ?
"YES" :
"NO");
3500 return return_value;
3507 LLDB_LOGF(log,
"Process::%s()%s ", __FUNCTION__,
3508 already_running ?
" already running"
3509 :
" starting private state thread");
3511 if (!is_secondary_thread && already_running)
3516 char thread_name[1024];
3517 uint32_t max_len = llvm::get_max_thread_name_length();
3518 if (max_len > 0 && max_len <= 30) {
3521 if (already_running)
3522 snprintf(thread_name,
sizeof(thread_name),
"intern-state-OV");
3524 snprintf(thread_name,
sizeof(thread_name),
"intern-state");
3526 if (already_running)
3527 snprintf(thread_name,
sizeof(thread_name),
3528 "<lldb.process.internal-state-override(pid=%" PRIu64
")>",
3531 snprintf(thread_name,
sizeof(thread_name),
3532 "<lldb.process.internal-state(pid=%" PRIu64
")>",
GetID());
3535 llvm::Expected<HostThread> private_state_thread =
3538 [
this, is_secondary_thread] {
3542 if (!private_state_thread) {
3548 assert(private_state_thread->IsJoinable());
3569 "Went to stop the private state thread, but it was already invalid.");
3580 LLDB_LOGF(log,
"Process::%s (signal = %d)", __FUNCTION__, signal);
3589 LLDB_LOGF(log,
"Sending control event of type: %d.", signal);
3590 std::shared_ptr<EventDataReceipt> event_receipt_sp(
new EventDataReceipt());
3595 bool receipt_received =
false;
3597 while (!receipt_received) {
3602 if (!receipt_received) {
3619 "Private state thread already dead, no need to signal it to stop.");
3642 LLDB_LOGF(log,
"Ran next event action, result was %d.", action_result);
3644 switch (action_result) {
3670 if (should_broadcast) {
3674 "Process::%s (pid = %" PRIu64
3675 ") broadcasting new state %s (old state %s) to %s",
3678 is_hijacked ?
"hijacked" :
"public");
3685 if (!
GetTarget().GetDebugger().IsForwardingEvents() &&
3690 LLDB_LOGF(log,
"Process::%s updated m_iohandler_sync to %d",
3724 if (is_hijacked || !
GetTarget().GetDebugger().IsHandlingEvents())
3734 "Process::%s (pid = %" PRIu64
3735 ") suppressing state %s (old state %s): should_broadcast == false",
3757 bool control_only =
true;
3760 LLDB_LOGF(log,
"Process::%s (arg = %p, pid = %" PRIu64
") thread starting...",
3761 __FUNCTION__,
static_cast<void *
>(
this),
GetID());
3763 bool exit_now =
false;
3764 bool interrupt_requested =
false;
3770 "Process::%s (arg = %p, pid = %" PRIu64
3771 ") got a control event: %d",
3772 __FUNCTION__,
static_cast<void *
>(
this),
GetID(),
3773 event_sp->GetType());
3775 switch (event_sp->GetType()) {
3781 control_only =
true;
3785 control_only =
false;
3793 "Process::%s (arg = %p, pid = %" PRIu64
3794 ") woke up with an interrupt while attaching - "
3795 "forwarding interrupt.",
3796 __FUNCTION__,
static_cast<void *
>(
this),
GetID());
3800 "Process::%s (arg = %p, pid = %" PRIu64
3801 ") woke up with an interrupt - Halting.",
3802 __FUNCTION__,
static_cast<void *
>(
this),
GetID());
3804 if (
error.Fail() && log)
3806 "Process::%s (arg = %p, pid = %" PRIu64
3807 ") failed to halt the process: %s",
3808 __FUNCTION__,
static_cast<void *
>(
this),
GetID(),
3815 interrupt_requested =
true;
3824 "Process::%s ignoring interrupt as we have already stopped.",
3840 if (interrupt_requested) {
3845 interrupt_requested =
false;
3848 "Process::%s interrupt_requested, but a non-stopped "
3849 "state '%s' received.",
3860 "Process::%s (arg = %p, pid = %" PRIu64
3861 ") about to exit with internal state %s...",
3862 __FUNCTION__,
static_cast<void *
>(
this),
GetID(),
3870 LLDB_LOGF(log,
"Process::%s (arg = %p, pid = %" PRIu64
") thread exiting...",
3871 __FUNCTION__,
static_cast<void *
>(
this),
GetID());
3876 if (!is_secondary_thread)
3887 :
EventData(), m_process_wp(), m_state(state) {
3895 static ConstString g_flavor(
"Process::ProcessEventData");
3904 bool &found_valid_stopinfo) {
3905 found_valid_stopinfo =
false;
3907 ProcessSP process_sp(m_process_wp.lock());
3911 ThreadList &curr_thread_list = process_sp->GetThreadList();
3925 ThreadList not_suspended_thread_list(process_sp.get());
3926 std::vector<uint32_t> thread_index_array(num_threads);
3928 for (idx = 0; idx < num_threads; ++idx) {
3936 not_suspended_thread_list.
AddThread(thread_sp);
3937 thread_index_array[not_suspended_idx] = thread_sp->GetIndexID();
3938 not_suspended_idx++;
3947 bool still_should_stop =
false;
3955 for (idx = 0; idx < not_suspended_thread_list.
GetSize(); ++idx) {
3956 curr_thread_list = process_sp->GetThreadList();
3957 if (curr_thread_list.
GetSize() != num_threads) {
3961 "Number of threads changed from %u to %u while processing event.",
3962 num_threads, curr_thread_list.
GetSize());
3966 lldb::ThreadSP thread_sp = not_suspended_thread_list.
GetThreadAtIndex(idx);
3968 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
3971 "The thread at position %u changed from %u to %u while "
3972 "processing event.",
3973 idx, thread_index_array[idx], thread_sp->GetIndexID());
3977 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
3978 if (stop_info_sp && stop_info_sp->IsValid()) {
3979 found_valid_stopinfo =
true;
3980 bool this_thread_wants_to_stop;
3981 if (stop_info_sp->GetOverrideShouldStop()) {
3982 this_thread_wants_to_stop =
3983 stop_info_sp->GetOverriddenShouldStopValue();
3985 stop_info_sp->PerformAction(event_ptr);
3993 if (stop_info_sp->HasTargetRunSinceMe()) {
3998 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
4001 if (!still_should_stop)
4002 still_should_stop = this_thread_wants_to_stop;
4006 return still_should_stop;
4010 ProcessSP process_sp(m_process_wp.lock());
4023 if (m_update_state != 1)
4026 process_sp->SetPublicState(
4033 process_sp->WillPublicStop();
4048 bool does_anybody_have_an_opinion =
false;
4049 bool still_should_stop = ShouldStop(event_ptr, does_anybody_have_an_opinion);
4051 if (GetRestarted()) {
4055 if (!still_should_stop && does_anybody_have_an_opinion) {
4060 process_sp->PrivateResume();
4063 !process_sp->StateChangedIsHijackedForSynchronousResume();
4071 if (process_sp->GetTarget().RunStopHooks())
4078 ProcessSP process_sp(m_process_wp.lock());
4081 s->
Printf(
" process = %p (pid = %" PRIu64
"), ",
4082 static_cast<void *
>(process_sp.get()), process_sp->GetID());
4102 ProcessSP process_sp;
4111 if (data ==
nullptr)
4119 if (data ==
nullptr)
4129 if (data !=
nullptr)
4137 if (data !=
nullptr)
4148 if (data !=
nullptr)
4155 const char *reason) {
4158 if (data !=
nullptr)
4163 const Event *event_ptr) {
4165 if (data ==
nullptr)
4175 if (data !=
nullptr)
4239 const StructuredDataPluginSP &plugin_sp) {
4245 StructuredDataPluginSP
4249 return find_it->second;
4251 return StructuredDataPluginSP();
4260 size_t bytes_available = one_profile_data.size();
4261 if (bytes_available > 0) {
4263 LLDB_LOGF(log,
"Process::GetProfileData (buf = %p, size = %" PRIu64
")",
4264 static_cast<void *
>(buf),
static_cast<uint64_t
>(buf_size));
4265 if (bytes_available > buf_size) {
4266 memcpy(buf, one_profile_data.c_str(), buf_size);
4267 one_profile_data.erase(0, buf_size);
4268 bytes_available = buf_size;
4270 memcpy(buf, one_profile_data.c_str(), bytes_available);
4274 return bytes_available;
4282 if (bytes_available > 0) {
4284 LLDB_LOGF(log,
"Process::GetSTDOUT (buf = %p, size = %" PRIu64
")",
4285 static_cast<void *
>(buf),
static_cast<uint64_t
>(buf_size));
4286 if (bytes_available > buf_size) {
4289 bytes_available = buf_size;
4295 return bytes_available;
4301 if (bytes_available > 0) {
4303 LLDB_LOGF(log,
"Process::GetSTDERR (buf = %p, size = %" PRIu64
")",
4304 static_cast<void *
>(buf),
static_cast<uint64_t
>(buf_size));
4305 if (bytes_available > buf_size) {
4308 bytes_available = buf_size;
4314 return bytes_available;
4320 process->
AppendSTDOUT(
static_cast<const char *
>(src), src_len);
4329 m_read_file(GetInputFD(),
File::eOpenOptionReadOnly, false),
4330 m_write_file(write_fd,
File::eOpenOptionWriteOnly, false) {
4331 m_pipe.CreateNew(
false);
4337 std::lock_guard<std::mutex> guard(m_mutex);
4338 SetIsDone(!running);
4339 m_is_running = running;
4345 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4346 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4352 const int read_fd = m_read_file.GetDescriptor();
4354 TerminalState terminal_state(terminal,
false);
4356 llvm::consumeError(terminal.SetCanonical(
false));
4357 llvm::consumeError(terminal.SetEcho(
false));
4360 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4364 std::lock_guard<std::mutex> guard(m_mutex);
4381 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4382 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4392 if (
error.Success()) {
4401 SetIsRunning(
false);
4406 std::lock_guard<std::mutex> guard(m_mutex);
4421 size_t bytes_written = 0;
4422 m_pipe.Write(&ch, 1, bytes_written);
4434 size_t bytes_written = 0;
4435 Status result = m_pipe.Write(&ch, 1, bytes_written);
4464 bool m_is_running =
false;
4470 std::make_unique<ConnectionFileDescriptor>(fd,
true));
4480 std::make_shared<IOHandlerProcessSTDIO>(
this, fd);
4492 if (io_handler_sp) {
4494 LLDB_LOGF(log,
"Process::%s pushing IO handler", __FUNCTION__);
4496 io_handler_sp->SetIsDone(
false);
4503 cancel_top_handler);
4528 class RestorePlanState {
4530 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4531 : m_thread_plan_sp(thread_plan_sp) {
4532 if (m_thread_plan_sp) {
4533 m_private = m_thread_plan_sp->GetPrivate();
4534 m_is_controlling = m_thread_plan_sp->IsControllingPlan();
4535 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4539 ~RestorePlanState() { Clean(); }
4542 if (!m_already_reset && m_thread_plan_sp) {
4543 m_already_reset =
true;
4544 m_thread_plan_sp->SetPrivate(m_private);
4545 m_thread_plan_sp->SetIsControllingPlan(m_is_controlling);
4546 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4551 lldb::ThreadPlanSP m_thread_plan_sp;
4552 bool m_already_reset =
false;
4554 bool m_is_controlling;
4555 bool m_okay_to_discard;
4561 const milliseconds default_one_thread_timeout(250);
4566 : default_one_thread_timeout;
4575 return std::min<microseconds>(default_one_thread_timeout,
4581 bool before_first_timeout) {
4587 if (before_first_timeout)
4596 static llvm::Optional<ExpressionResults>
4598 RestorePlanState &restorer,
const EventSP &event_sp,
4599 EventSP &event_to_broadcast_sp,
4601 bool handle_interrupts) {
4604 ThreadSP thread_sp = thread_plan_sp->GetTarget()
4607 .FindThreadByID(thread_id);
4610 "The thread on which we were running the "
4611 "expression: tid = {0}, exited while "
4612 "the expression was running.",
4617 ThreadPlanSP plan = thread_sp->GetCompletedPlan();
4618 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
4619 LLDB_LOG(log,
"execution completed successfully");
4627 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4629 stop_info_sp->ShouldNotify(event_sp.get())) {
4630 LLDB_LOG(log,
"stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
4637 thread_plan_sp->SetPrivate(
false);
4638 event_to_broadcast_sp = event_sp;
4643 if (!handle_interrupts &&
4647 LLDB_LOG(log,
"thread plan did not successfully complete");
4649 event_to_broadcast_sp = event_sp;
4655 lldb::ThreadPlanSP &thread_plan_sp,
4662 if (!thread_plan_sp) {
4665 "RunThreadPlan called with empty thread plan.");
4669 if (!thread_plan_sp->ValidatePlan(
nullptr)) {
4672 "RunThreadPlan called with an invalid thread plan.");
4678 "RunThreadPlan called on wrong process.");
4683 if (thread ==
nullptr) {
4685 "RunThreadPlan called with invalid thread.");
4696 RestorePlanState thread_plan_restorer(thread_plan_sp);
4703 thread_plan_sp->SetPrivate(
false);
4709 thread_plan_sp->SetIsControllingPlan(
true);
4710 thread_plan_sp->SetOkayToDiscard(
false);
4720 "RunThreadPlan called while the private state was not stopped.");
4727 if (!selected_frame_sp) {
4730 if (!selected_frame_sp) {
4731 diagnostic_manager.
Printf(
4733 "RunThreadPlan called without a selected frame on thread %d",
4744 "RunThreadPlan called with one thread "
4745 "timeout greater than total timeout");
4749 StackID ctx_frame_id = selected_frame_sp->GetStackID();
4759 if (selected_thread_sp) {
4760 selected_tid = selected_thread_sp->GetIndexID();
4761 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4768 lldb::ThreadPlanSP stopper_base_plan_sp;
4777 LLDB_LOGF(log,
"Running thread plan on private state thread, spinning up "
4778 "another state thread to handle the events.");
4801 thread_plan_sp,
false);
4815 ListenerSP listener_sp(
4818 lldb::EventSP event_to_broadcast_sp;
4834 "Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
4835 " to run thread plan \"%s\".",
4836 thread_idx_id, expr_thread_id, s.
GetData());
4840 lldb::EventSP event_sp;
4843 bool before_first_timeout =
true;
4845 bool do_resume =
true;
4846 bool handle_running_event =
true;
4855 before_first_timeout =
false;
4857 LLDB_LOGF(log,
"Stop others: %u, try all: %u, before_first: %u.\n",
4859 before_first_timeout);
4866 Event *other_events = listener_sp->PeekAtNextEvent();
4867 if (other_events !=
nullptr) {
4870 "RunThreadPlan called with pending events on the queue.");
4883 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
4891 bool miss_first_event =
true;
4899 "Top of while loop: do_resume: %i handle_running_event: %i "
4900 "before_first_timeout: %i.",
4901 do_resume, handle_running_event, before_first_timeout);
4903 if (do_resume || handle_running_event) {
4910 if (!resume_error.
Success()) {
4911 diagnostic_manager.
Printf(
4913 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
4924 "Process::RunThreadPlan(): didn't get any event after "
4925 "resume %" PRIu32
", exiting.",
4929 "didn't get any event after resume %" PRIu32
4940 bool restarted =
false;
4947 "Process::RunThreadPlan(): didn't get running event after "
4948 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
4949 "handle_running_event: %i).",
4951 handle_running_event);
4958 const bool clear_thread_plans =
false;
4959 const bool use_run_lock =
false;
4960 Halt(clear_thread_plans, use_run_lock);
4963 diagnostic_manager.
Printf(
4965 "didn't get running event after initial resume, got %s instead.",
4972 log->
PutCString(
"Process::RunThreadPlan(): resuming succeeded.");
4980 log->
PutCString(
"Process::RunThreadPlan(): waiting for next event.");
4984 handle_running_event =
true;
4993 auto now = system_clock::now();
4995 "Process::RunThreadPlan(): about to wait - now is %s - "
4997 llvm::to_string(now).c_str(),
4998 llvm::to_string(now + *timeout).c_str());
5000 LLDB_LOGF(log,
"Process::RunThreadPlan(): about to wait forever.");
5004 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5006 if (miss_first_event) {
5007 std::this_thread::sleep_for(std::chrono::milliseconds(1));
5008 miss_first_event =
false;
5012 got_event = listener_sp->GetEvent(event_sp, timeout);
5016 bool keep_going =
false;
5018 const bool clear_thread_plans =
false;
5019 const bool use_run_lock =
false;
5020 Halt(clear_thread_plans, use_run_lock);
5023 "execution halted by user interrupt.");
5024 LLDB_LOGF(log,
"Process::RunThreadPlan(): Got interrupted by "
5025 "eBroadcastBitInterrupted, exiting.");
5031 "Process::RunThreadPlan(): in while loop, got event: %s.",
5034 switch (stop_state) {
5040 LLDB_LOGF(log,
"Process::RunThreadPlan(): Got a stop and "
5041 "restart, so we'll continue waiting.");
5044 handle_running_event =
true;
5046 const bool handle_interrupts =
true;
5048 expr_thread_id, thread_plan_sp, thread_plan_restorer,
5049 event_sp, event_to_broadcast_sp, options,
5062 handle_running_event =
false;
5067 "Process::RunThreadPlan(): execution stopped with "
5068 "unexpected state: %s.",
5072 event_to_broadcast_sp = event_sp;
5076 "execution stopped with unexpected state.");
5088 log->
PutCString(
"Process::RunThreadPlan(): got_event was true, but "
5089 "the event pointer was null. How odd...");
5101 if (before_first_timeout) {
5103 "Running function with one thread timeout timed out.");
5105 LLDB_LOG(log,
"Restarting function with all threads enabled and "
5106 "timeout: {0} timed out, abandoning execution.",
5109 LLDB_LOG(log,
"Running function with timeout: {0} timed out, "
5110 "abandoning execution.",
5123 bool back_to_top =
true;
5125 bool do_halt =
true;
5127 while (try_halt_again < num_retries) {
5130 LLDB_LOGF(log,
"Process::RunThreadPlan(): Running Halt.");
5131 const bool clear_thread_plans =
false;
5132 const bool use_run_lock =
false;
5133 Halt(clear_thread_plans, use_run_lock);
5137 log->
PutCString(
"Process::RunThreadPlan(): Halt succeeded.");
5147 "Process::RunThreadPlan(): Stopped with event: %s",
5152 log->
PutCString(
" Event was the Halt interruption event.");
5159 log->
PutCString(
"Process::RunThreadPlan(): Went to halt "
5160 "but got a restarted event, there must be "
5161 "an un-restarted stopped event so try "
5163 "Exiting wait loop.");
5172 const bool handle_interrupts =
false;
5174 expr_thread_id, thread_plan_sp, thread_plan_restorer,
5175 event_sp, event_to_broadcast_sp, options,
5176 handle_interrupts)) {
5177 return_value = *result;
5178 back_to_top =
false;
5184 log->
PutCString(
"Process::RunThreadPlan(): try_all_threads "
5185 "was false, we stopped so now we're "
5188 back_to_top =
false;
5192 if (before_first_timeout) {
5195 before_first_timeout =
false;
5196 thread_plan_sp->SetStopOthers(
false);
5199 "Process::RunThreadPlan(): about to resume.");
5206 log->
PutCString(
"Process::RunThreadPlan(): running all "
5207 "threads timed out.");
5209 back_to_top =
false;
5215 log->
PutCString(
"Process::RunThreadPlan(): halt said it "
5216 "succeeded, but I got no event. "
5217 "I'm getting out of here passing Interrupted.");
5219 back_to_top =
false;
5228 if (!back_to_top || try_halt_again > num_retries)
5237 if (backup_private_state_thread.
IsJoinable()) {
5241 if (stopper_base_plan_sp) {
5252 return return_value;
5258 s.
PutCString(
"Thread state after unsuccessful completion: \n");
5272 thread_plan_sp->RestoreThreadState();
5283 log->
PutCString(
"Process::RunThreadPlan(): Stop event that "
5284 "interrupted us is NULL.");
5289 const char *event_explanation =
nullptr;
5293 event_explanation =
"<no event>";
5296 event_explanation =
"<user interrupt>";
5304 event_explanation =
"<no event data>";
5311 event_explanation =
"<no process>";
5320 ts.
Printf(
"<%u threads> ", num_threads);
5322 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5334 if (register_context)
5335 ts.
Printf(
"[ip 0x%" PRIx64
"] ", register_context->
GetPC());
5337 ts.
Printf(
"[ip unknown] ");
5343 const char *stop_desc = stop_info_sp->GetDescription();
5350 event_explanation = ts.
GetData();
5354 if (event_explanation)
5356 "Process::RunThreadPlan(): execution interrupted: %s %s",
5357 s.
GetData(), event_explanation);
5359 LLDB_LOGF(log,
"Process::RunThreadPlan(): execution interrupted: %s",
5363 if (should_unwind) {
5365 "Process::RunThreadPlan: ExecutionInterrupted - "
5366 "discarding thread plans up to %p.",
5367 static_cast<void *
>(thread_plan_sp.get()));
5371 "Process::RunThreadPlan: ExecutionInterrupted - for "
5372 "plan: %p not discarding.",