LLDB mainline
Process.cpp
Go to the documentation of this file.
1//===-- Process.cpp -------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include <atomic>
10#include <memory>
11#include <mutex>
12#include <optional>
13
14#include "llvm/ADT/ScopeExit.h"
15#include "llvm/Support/ScopedPrinter.h"
16#include "llvm/Support/Threading.h"
17
20#include "lldb/Core/Debugger.h"
21#include "lldb/Core/Module.h"
30#include "lldb/Host/Host.h"
31#include "lldb/Host/HostInfo.h"
33#include "lldb/Host/Pipe.h"
34#include "lldb/Host/Terminal.h"
40#include "lldb/Symbol/Symbol.h"
41#include "lldb/Target/ABI.h"
53#include "lldb/Target/Process.h"
58#include "lldb/Target/Target.h"
60#include "lldb/Target/Thread.h"
66#include "lldb/Utility/Event.h"
68#include "lldb/Utility/Log.h"
72#include "lldb/Utility/State.h"
73#include "lldb/Utility/Timer.h"
74
75using namespace lldb;
76using namespace lldb_private;
77using namespace std::chrono;
78
79// Comment out line below to disable memory caching, overriding the process
80// setting target.process.disable-memory-cache
81#define ENABLE_MEMORY_CACHING
82
83#ifdef ENABLE_MEMORY_CACHING
84#define DISABLE_MEM_CACHE_DEFAULT false
85#else
86#define DISABLE_MEM_CACHE_DEFAULT true
87#endif
88
90 : public Cloneable<ProcessOptionValueProperties, OptionValueProperties> {
91public:
92 ProcessOptionValueProperties(llvm::StringRef name) : Cloneable(name) {}
93
94 const Property *
96 const ExecutionContext *exe_ctx) const override {
97 // When getting the value for a key from the process options, we will
98 // always try and grab the setting from the current process if there is
99 // one. Else we just use the one from this instance.
100 if (exe_ctx) {
101 Process *process = exe_ctx->GetProcessPtr();
102 if (process) {
103 ProcessOptionValueProperties *instance_properties =
104 static_cast<ProcessOptionValueProperties *>(
105 process->GetValueProperties().get());
106 if (this != instance_properties)
107 return instance_properties->ProtectedGetPropertyAtIndex(idx);
108 }
109 }
110 return ProtectedGetPropertyAtIndex(idx);
111 }
112};
113
115 {
117 "parent",
118 "Continue tracing the parent process and detach the child.",
119 },
120 {
122 "child",
123 "Trace the child process and detach the parent.",
124 },
125};
126
127#define LLDB_PROPERTIES_process
128#include "TargetProperties.inc"
129
130enum {
131#define LLDB_PROPERTIES_process
132#include "TargetPropertiesEnum.inc"
134};
135
136#define LLDB_PROPERTIES_process_experimental
137#include "TargetProperties.inc"
138
139enum {
140#define LLDB_PROPERTIES_process_experimental
141#include "TargetPropertiesEnum.inc"
142};
143
145 : public Cloneable<ProcessExperimentalOptionValueProperties,
146 OptionValueProperties> {
147public:
149 : Cloneable(Properties::GetExperimentalSettingsName()) {}
150};
151
155 m_collection_sp->Initialize(g_process_experimental_properties);
156}
157
159 : Properties(),
160 m_process(process) // Can be nullptr for global ProcessProperties
161{
162 if (process == nullptr) {
163 // Global process properties, set them up one time
164 m_collection_sp = std::make_shared<ProcessOptionValueProperties>("process");
165 m_collection_sp->Initialize(g_process_properties);
166 m_collection_sp->AppendProperty(
167 "thread", "Settings specific to threads.", true,
169 } else {
172 m_collection_sp->SetValueChangedCallback(
173 ePropertyPythonOSPluginPath,
174 [this] { m_process->LoadOperatingSystemPlugin(true); });
175 }
176
178 std::make_unique<ProcessExperimentalProperties>();
179 m_collection_sp->AppendProperty(
181 "Experimental settings - setting these won't produce "
182 "errors if the setting is not present.",
183 true, m_experimental_properties_up->GetValueProperties());
184}
185
187
189 const uint32_t idx = ePropertyDisableMemCache;
190 return GetPropertyAtIndexAs<bool>(
191 idx, g_process_properties[idx].default_uint_value != 0);
192}
193
195 const uint32_t idx = ePropertyMemCacheLineSize;
196 return GetPropertyAtIndexAs<uint64_t>(
197 idx, g_process_properties[idx].default_uint_value);
198}
199
201 Args args;
202 const uint32_t idx = ePropertyExtraStartCommand;
203 m_collection_sp->GetPropertyAtIndexAsArgs(idx, args);
204 return args;
205}
206
208 const uint32_t idx = ePropertyExtraStartCommand;
209 m_collection_sp->SetPropertyAtIndexFromArgs(idx, args);
210}
211
213 const uint32_t idx = ePropertyPythonOSPluginPath;
214 return GetPropertyAtIndexAs<FileSpec>(idx, {});
215}
216
218 const uint32_t idx = ePropertyVirtualAddressableBits;
219 return GetPropertyAtIndexAs<uint64_t>(
220 idx, g_process_properties[idx].default_uint_value);
221}
222
224 const uint32_t idx = ePropertyVirtualAddressableBits;
225 SetPropertyAtIndex(idx, static_cast<uint64_t>(bits));
226}
227
229 const uint32_t idx = ePropertyHighmemVirtualAddressableBits;
230 return GetPropertyAtIndexAs<uint64_t>(
231 idx, g_process_properties[idx].default_uint_value);
232}
233
235 const uint32_t idx = ePropertyHighmemVirtualAddressableBits;
236 SetPropertyAtIndex(idx, static_cast<uint64_t>(bits));
237}
238
240 const uint32_t idx = ePropertyPythonOSPluginPath;
241 SetPropertyAtIndex(idx, file);
242}
243
245 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
246 return GetPropertyAtIndexAs<bool>(
247 idx, g_process_properties[idx].default_uint_value != 0);
248}
249
251 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
252 SetPropertyAtIndex(idx, ignore);
253}
254
256 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
257 return GetPropertyAtIndexAs<bool>(
258 idx, g_process_properties[idx].default_uint_value != 0);
259}
260
262 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
263 SetPropertyAtIndex(idx, ignore);
264}
265
267 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
268 return GetPropertyAtIndexAs<bool>(
269 idx, g_process_properties[idx].default_uint_value != 0);
270}
271
273 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
274 SetPropertyAtIndex(idx, stop);
275}
276
278 const uint32_t idx = ePropertyDisableLangRuntimeUnwindPlans;
279 return GetPropertyAtIndexAs<bool>(
280 idx, g_process_properties[idx].default_uint_value != 0);
281}
282
284 const uint32_t idx = ePropertyDisableLangRuntimeUnwindPlans;
285 SetPropertyAtIndex(idx, disable);
286 m_process->Flush();
287}
288
290 const uint32_t idx = ePropertyDetachKeepsStopped;
291 return GetPropertyAtIndexAs<bool>(
292 idx, g_process_properties[idx].default_uint_value != 0);
293}
294
296 const uint32_t idx = ePropertyDetachKeepsStopped;
297 SetPropertyAtIndex(idx, stop);
298}
299
301 const uint32_t idx = ePropertyWarningOptimization;
302 return GetPropertyAtIndexAs<bool>(
303 idx, g_process_properties[idx].default_uint_value != 0);
304}
305
307 const uint32_t idx = ePropertyWarningUnsupportedLanguage;
308 return GetPropertyAtIndexAs<bool>(
309 idx, g_process_properties[idx].default_uint_value != 0);
310}
311
313 const uint32_t idx = ePropertyStopOnExec;
314 return GetPropertyAtIndexAs<bool>(
315 idx, g_process_properties[idx].default_uint_value != 0);
316}
317
319 const uint32_t idx = ePropertyUtilityExpressionTimeout;
320 uint64_t value = GetPropertyAtIndexAs<uint64_t>(
321 idx, g_process_properties[idx].default_uint_value);
322 return std::chrono::seconds(value);
323}
324
325std::chrono::seconds ProcessProperties::GetInterruptTimeout() const {
326 const uint32_t idx = ePropertyInterruptTimeout;
327 uint64_t value = GetPropertyAtIndexAs<uint64_t>(
328 idx, g_process_properties[idx].default_uint_value);
329 return std::chrono::seconds(value);
330}
331
333 const uint32_t idx = ePropertySteppingRunsAllThreads;
334 return GetPropertyAtIndexAs<bool>(
335 idx, g_process_properties[idx].default_uint_value != 0);
336}
337
339 const bool fail_value = true;
340 const Property *exp_property =
341 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental);
342 OptionValueProperties *exp_values =
343 exp_property->GetValue()->GetAsProperties();
344 if (!exp_values)
345 return fail_value;
346
347 return exp_values
348 ->GetPropertyAtIndexAs<bool>(ePropertyOSPluginReportsAllThreads)
349 .value_or(fail_value);
350}
351
353 const Property *exp_property =
354 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental);
355 OptionValueProperties *exp_values =
356 exp_property->GetValue()->GetAsProperties();
357 if (exp_values)
358 exp_values->SetPropertyAtIndex(ePropertyOSPluginReportsAllThreads,
359 does_report);
360}
361
363 const uint32_t idx = ePropertyFollowForkMode;
364 return GetPropertyAtIndexAs<FollowForkMode>(
365 idx, static_cast<FollowForkMode>(
366 g_process_properties[idx].default_uint_value));
367}
368
370 llvm::StringRef plugin_name,
371 ListenerSP listener_sp,
372 const FileSpec *crash_file_path,
373 bool can_connect) {
374 static uint32_t g_process_unique_id = 0;
375
376 ProcessSP process_sp;
377 ProcessCreateInstance create_callback = nullptr;
378 if (!plugin_name.empty()) {
379 create_callback =
381 if (create_callback) {
382 process_sp = create_callback(target_sp, listener_sp, crash_file_path,
383 can_connect);
384 if (process_sp) {
385 if (process_sp->CanDebug(target_sp, true)) {
386 process_sp->m_process_unique_id = ++g_process_unique_id;
387 } else
388 process_sp.reset();
389 }
390 }
391 } else {
392 for (uint32_t idx = 0;
393 (create_callback =
395 ++idx) {
396 process_sp = create_callback(target_sp, listener_sp, crash_file_path,
397 can_connect);
398 if (process_sp) {
399 if (process_sp->CanDebug(target_sp, false)) {
400 process_sp->m_process_unique_id = ++g_process_unique_id;
401 break;
402 } else
403 process_sp.reset();
404 }
405 }
406 }
407 return process_sp;
408}
409
411 static ConstString class_name("lldb.process");
412 return class_name;
413}
414
416 : Process(target_sp, listener_sp, UnixSignals::CreateForHost()) {
417 // This constructor just delegates to the full Process constructor,
418 // defaulting to using the Host's UnixSignals.
419}
420
422 const UnixSignalsSP &unix_signals_sp)
423 : ProcessProperties(this),
424 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
425 Process::GetStaticBroadcasterClass().AsCString()),
426 m_target_wp(target_sp), m_public_state(eStateUnloaded),
427 m_private_state(eStateUnloaded),
428 m_private_state_broadcaster(nullptr,
429 "lldb.process.internal_state_broadcaster"),
430 m_private_state_control_broadcaster(
431 nullptr, "lldb.process.internal_state_control_broadcaster"),
432 m_private_state_listener_sp(
433 Listener::MakeListener("lldb.process.internal_state_listener")),
434 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
435 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
436 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
437 m_thread_list(this), m_thread_plans(*this), m_extended_thread_list(this),
438 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
439 m_watchpoint_resource_list(), m_notifications(), m_image_tokens(),
440 m_breakpoint_site_list(), m_dynamic_checkers_up(),
441 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
442 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
443 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
444 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
445 m_memory_cache(*this), m_allocated_memory_cache(*this),
446 m_should_detach(false), m_next_event_action_up(), m_public_run_lock(),
447 m_private_run_lock(), m_currently_handling_do_on_removals(false),
448 m_resume_requested(false), m_finalizing(false), m_destructing(false),
449 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
450 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
451 m_can_interpret_function_calls(false), m_run_thread_plan_lock(),
452 m_can_jit(eCanJITDontKnow) {
454
455 Log *log = GetLog(LLDBLog::Object);
456 LLDB_LOGF(log, "%p Process::Process()", static_cast<void *>(this));
457
459 m_unix_signals_sp = std::make_shared<UnixSignals>();
460
461 SetEventName(eBroadcastBitStateChanged, "state-changed");
463 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
464 SetEventName(eBroadcastBitSTDERR, "stderr-available");
465 SetEventName(eBroadcastBitProfileData, "profile-data-available");
466 SetEventName(eBroadcastBitStructuredData, "structured-data-available");
467
469 eBroadcastInternalStateControlStop, "control-stop");
471 eBroadcastInternalStateControlPause, "control-pause");
473 eBroadcastInternalStateControlResume, "control-resume");
474
475 // The listener passed into process creation is the primary listener:
476 // It always listens for all the event bits for Process:
477 SetPrimaryListener(listener_sp);
478
479 m_private_state_listener_sp->StartListeningForEvents(
482
483 m_private_state_listener_sp->StartListeningForEvents(
487 // We need something valid here, even if just the default UnixSignalsSP.
488 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
489
490 // Allow the platform to override the default cache line size
491 OptionValueSP value_sp =
492 m_collection_sp->GetPropertyAtIndex(ePropertyMemCacheLineSize)
493 ->GetValue();
494 uint64_t platform_cache_line_size =
495 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
496 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
497 value_sp->SetValueAs(platform_cache_line_size);
498
500}
501
503 Log *log = GetLog(LLDBLog::Object);
504 LLDB_LOGF(log, "%p Process::~Process()", static_cast<void *>(this));
506
507 // ThreadList::Clear() will try to acquire this process's mutex, so
508 // explicitly clear the thread list here to ensure that the mutex is not
509 // destroyed before the thread list.
511}
512
514 // NOTE: intentional leak so we don't crash if global destructor chain gets
515 // called as other threads still use the result of this function
516 static ProcessProperties *g_settings_ptr =
517 new ProcessProperties(nullptr);
518 return *g_settings_ptr;
519}
520
521void Process::Finalize(bool destructing) {
522 if (m_finalizing.exchange(true))
523 return;
524 if (destructing)
525 m_destructing.exchange(true);
526
527 // Destroy the process. This will call the virtual function DoDestroy under
528 // the hood, giving our derived class a chance to do the ncessary tear down.
529 DestroyImpl(false);
530
531 // Clear our broadcaster before we proceed with destroying
533
534 // Do any cleanup needed prior to being destructed... Subclasses that
535 // override this method should call this superclass method as well.
536
537 // We need to destroy the loader before the derived Process class gets
538 // destroyed since it is very likely that undoing the loader will require
539 // access to the real process.
540 m_dynamic_checkers_up.reset();
541 m_abi_sp.reset();
542 m_os_up.reset();
543 m_system_runtime_up.reset();
544 m_dyld_up.reset();
545 m_jit_loaders_up.reset();
553 std::vector<Notifications> empty_notifications;
554 m_notifications.swap(empty_notifications);
555 m_image_tokens.clear();
557 m_allocated_memory_cache.Clear(/*deallocate_memory=*/true);
558 {
559 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
560 m_language_runtimes.clear();
561 }
564 // Clear the last natural stop ID since it has a strong reference to this
565 // process
567 // We have to be very careful here as the m_private_state_listener might
568 // contain events that have ProcessSP values in them which can keep this
569 // process around forever. These events need to be cleared out.
571 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
573 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
576}
577
579 m_notifications.push_back(callbacks);
580 if (callbacks.initialize != nullptr)
581 callbacks.initialize(callbacks.baton, this);
582}
583
585 std::vector<Notifications>::iterator pos, end = m_notifications.end();
586 for (pos = m_notifications.begin(); pos != end; ++pos) {
587 if (pos->baton == callbacks.baton &&
588 pos->initialize == callbacks.initialize &&
589 pos->process_state_changed == callbacks.process_state_changed) {
590 m_notifications.erase(pos);
591 return true;
592 }
593 }
594 return false;
595}
596
598 std::vector<Notifications>::iterator notification_pos,
599 notification_end = m_notifications.end();
600 for (notification_pos = m_notifications.begin();
601 notification_pos != notification_end; ++notification_pos) {
602 if (notification_pos->process_state_changed)
603 notification_pos->process_state_changed(notification_pos->baton, this,
604 state);
605 }
606}
607
608// FIXME: We need to do some work on events before the general Listener sees
609// them.
610// For instance if we are continuing from a breakpoint, we need to ensure that
611// we do the little "insert real insn, step & stop" trick. But we can't do
612// that when the event is delivered by the broadcaster - since that is done on
613// the thread that is waiting for new events, so if we needed more than one
614// event for our handling, we would stall. So instead we do it when we fetch
615// the event off of the queue.
616//
617
619 StateType state = eStateInvalid;
620
621 if (GetPrimaryListener()->GetEventForBroadcaster(this, event_sp,
622 std::chrono::seconds(0)) &&
623 event_sp)
624 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
625
626 return state;
627}
628
629void Process::SyncIOHandler(uint32_t iohandler_id,
630 const Timeout<std::micro> &timeout) {
631 // don't sync (potentially context switch) in case where there is no process
632 // IO
634 return;
635
636 auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout);
637
639 if (Result) {
640 LLDB_LOG(
641 log,
642 "waited from m_iohandler_sync to change from {0}. New value is {1}.",
643 iohandler_id, *Result);
644 } else {
645 LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.",
646 iohandler_id);
647 }
648}
649
651 const Timeout<std::micro> &timeout, EventSP *event_sp_ptr, bool wait_always,
652 ListenerSP hijack_listener_sp, Stream *stream, bool use_run_lock,
653 SelectMostRelevant select_most_relevant) {
654 // We can't just wait for a "stopped" event, because the stopped event may
655 // have restarted the target. We have to actually check each event, and in
656 // the case of a stopped event check the restarted flag on the event.
657 if (event_sp_ptr)
658 event_sp_ptr->reset();
659 StateType state = GetState();
660 // If we are exited or detached, we won't ever get back to any other valid
661 // state...
662 if (state == eStateDetached || state == eStateExited)
663 return state;
664
666 LLDB_LOG(log, "timeout = {0}", timeout);
667
668 if (!wait_always && StateIsStoppedState(state, true) &&
670 LLDB_LOGF(log,
671 "Process::%s returning without waiting for events; process "
672 "private and public states are already 'stopped'.",
673 __FUNCTION__);
674 // We need to toggle the run lock as this won't get done in
675 // SetPublicState() if the process is hijacked.
676 if (hijack_listener_sp && use_run_lock)
678 return state;
679 }
680
681 while (state != eStateInvalid) {
682 EventSP event_sp;
683 state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
684 if (event_sp_ptr && event_sp)
685 *event_sp_ptr = event_sp;
686
687 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
689 event_sp, stream, select_most_relevant, pop_process_io_handler);
690
691 switch (state) {
692 case eStateCrashed:
693 case eStateDetached:
694 case eStateExited:
695 case eStateUnloaded:
696 // We need to toggle the run lock as this won't get done in
697 // SetPublicState() if the process is hijacked.
698 if (hijack_listener_sp && use_run_lock)
700 return state;
701 case eStateStopped:
703 continue;
704 else {
705 // We need to toggle the run lock as this won't get done in
706 // SetPublicState() if the process is hijacked.
707 if (hijack_listener_sp && use_run_lock)
709 return state;
710 }
711 default:
712 continue;
713 }
714 }
715 return state;
716}
717
719 const EventSP &event_sp, Stream *stream,
720 SelectMostRelevant select_most_relevant,
721 bool &pop_process_io_handler) {
722 const bool handle_pop = pop_process_io_handler;
723
724 pop_process_io_handler = false;
725 ProcessSP process_sp =
727
728 if (!process_sp)
729 return false;
730
731 StateType event_state =
733 if (event_state == eStateInvalid)
734 return false;
735
736 switch (event_state) {
737 case eStateInvalid:
738 case eStateUnloaded:
739 case eStateAttaching:
740 case eStateLaunching:
741 case eStateStepping:
742 case eStateDetached:
743 if (stream)
744 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
745 StateAsCString(event_state));
746 if (event_state == eStateDetached)
747 pop_process_io_handler = true;
748 break;
749
750 case eStateConnected:
751 case eStateRunning:
752 // Don't be chatty when we run...
753 break;
754
755 case eStateExited:
756 if (stream)
757 process_sp->GetStatus(*stream);
758 pop_process_io_handler = true;
759 break;
760
761 case eStateStopped:
762 case eStateCrashed:
763 case eStateSuspended:
764 // Make sure the program hasn't been auto-restarted:
766 if (stream) {
767 size_t num_reasons =
769 if (num_reasons > 0) {
770 // FIXME: Do we want to report this, or would that just be annoyingly
771 // chatty?
772 if (num_reasons == 1) {
773 const char *reason =
775 event_sp.get(), 0);
776 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
777 process_sp->GetID(),
778 reason ? reason : "<UNKNOWN REASON>");
779 } else {
780 stream->Printf("Process %" PRIu64
781 " stopped and restarted, reasons:\n",
782 process_sp->GetID());
783
784 for (size_t i = 0; i < num_reasons; i++) {
785 const char *reason =
787 event_sp.get(), i);
788 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
789 }
790 }
791 }
792 }
793 } else {
794 StopInfoSP curr_thread_stop_info_sp;
795 // Lock the thread list so it doesn't change on us, this is the scope for
796 // the locker:
797 {
798 ThreadList &thread_list = process_sp->GetThreadList();
799 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
800
801 ThreadSP curr_thread(thread_list.GetSelectedThread());
802 ThreadSP thread;
803 StopReason curr_thread_stop_reason = eStopReasonInvalid;
804 bool prefer_curr_thread = false;
805 if (curr_thread && curr_thread->IsValid()) {
806 curr_thread_stop_reason = curr_thread->GetStopReason();
807 switch (curr_thread_stop_reason) {
808 case eStopReasonNone:
810 // Don't prefer the current thread if it didn't stop for a reason.
811 break;
812 case eStopReasonSignal: {
813 // We need to do the same computation we do for other threads
814 // below in case the current thread happens to be the one that
815 // stopped for the no-stop signal.
816 uint64_t signo = curr_thread->GetStopInfo()->GetValue();
817 if (process_sp->GetUnixSignals()->GetShouldStop(signo))
818 prefer_curr_thread = true;
819 } break;
820 default:
821 prefer_curr_thread = true;
822 break;
823 }
824 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
825 }
826
827 if (!prefer_curr_thread) {
828 // Prefer a thread that has just completed its plan over another
829 // thread as current thread.
830 ThreadSP plan_thread;
831 ThreadSP other_thread;
832
833 const size_t num_threads = thread_list.GetSize();
834 size_t i;
835 for (i = 0; i < num_threads; ++i) {
836 thread = thread_list.GetThreadAtIndex(i);
837 StopReason thread_stop_reason = thread->GetStopReason();
838 switch (thread_stop_reason) {
840 case eStopReasonNone:
841 break;
842
843 case eStopReasonSignal: {
844 // Don't select a signal thread if we weren't going to stop at
845 // that signal. We have to have had another reason for stopping
846 // here, and the user doesn't want to see this thread.
847 uint64_t signo = thread->GetStopInfo()->GetValue();
848 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
849 if (!other_thread)
850 other_thread = thread;
851 }
852 break;
853 }
854 case eStopReasonTrace:
858 case eStopReasonExec:
859 case eStopReasonFork:
860 case eStopReasonVFork:
865 if (!other_thread)
866 other_thread = thread;
867 break;
869 if (!plan_thread)
870 plan_thread = thread;
871 break;
872 }
873 }
874 if (plan_thread)
875 thread_list.SetSelectedThreadByID(plan_thread->GetID());
876 else if (other_thread)
877 thread_list.SetSelectedThreadByID(other_thread->GetID());
878 else {
879 if (curr_thread && curr_thread->IsValid())
880 thread = curr_thread;
881 else
882 thread = thread_list.GetThreadAtIndex(0);
883
884 if (thread)
885 thread_list.SetSelectedThreadByID(thread->GetID());
886 }
887 }
888 }
889 // Drop the ThreadList mutex by here, since GetThreadStatus below might
890 // have to run code, e.g. for Data formatters, and if we hold the
891 // ThreadList mutex, then the process is going to have a hard time
892 // restarting the process.
893 if (stream) {
894 Debugger &debugger = process_sp->GetTarget().GetDebugger();
895 if (debugger.GetTargetList().GetSelectedTarget().get() ==
896 &process_sp->GetTarget()) {
897 ThreadSP thread_sp = process_sp->GetThreadList().GetSelectedThread();
898
899 if (!thread_sp || !thread_sp->IsValid())
900 return false;
901
902 const bool only_threads_with_stop_reason = true;
903 const uint32_t start_frame =
904 thread_sp->GetSelectedFrameIndex(select_most_relevant);
905 const uint32_t num_frames = 1;
906 const uint32_t num_frames_with_source = 1;
907 const bool stop_format = true;
908
909 process_sp->GetStatus(*stream);
910 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
911 start_frame, num_frames,
912 num_frames_with_source,
913 stop_format);
914 if (curr_thread_stop_info_sp) {
915 lldb::addr_t crashing_address;
917 curr_thread_stop_info_sp, &crashing_address);
918 if (valobj_sp) {
922 stream->PutCString("Likely cause: ");
923 valobj_sp->GetExpressionPath(*stream, format);
924 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
925 }
926 }
927 } else {
928 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
929 process_sp->GetTarget().shared_from_this());
930 if (target_idx != UINT32_MAX)
931 stream->Printf("Target %d: (", target_idx);
932 else
933 stream->Printf("Target <unknown index>: (");
934 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
935 stream->Printf(") stopped.\n");
936 }
937 }
938
939 // Pop the process IO handler
940 pop_process_io_handler = true;
941 }
942 break;
943 }
944
945 if (handle_pop && pop_process_io_handler)
946 process_sp->PopProcessIOHandler();
947
948 return true;
949}
950
952 if (listener_sp) {
953 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
955 } else
956 return false;
957}
958
960
962 const Timeout<std::micro> &timeout,
963 ListenerSP hijack_listener_sp) {
965 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
966
967 ListenerSP listener_sp = hijack_listener_sp;
968 if (!listener_sp)
969 listener_sp = GetPrimaryListener();
970
971 StateType state = eStateInvalid;
972 if (listener_sp->GetEventForBroadcasterWithType(
974 timeout)) {
975 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
976 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
977 else
978 LLDB_LOG(log, "got no event or was interrupted.");
979 }
980
981 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
982 return state;
983}
984
987
988 LLDB_LOGF(log, "Process::%s...", __FUNCTION__);
989
990 Event *event_ptr;
991 event_ptr = GetPrimaryListener()->PeekAtNextEventForBroadcasterWithType(
993 if (log) {
994 if (event_ptr) {
995 LLDB_LOGF(log, "Process::%s (event_ptr) => %s", __FUNCTION__,
997 } else {
998 LLDB_LOGF(log, "Process::%s no events found", __FUNCTION__);
999 }
1000 }
1001 return event_ptr;
1002}
1003
1006 const Timeout<std::micro> &timeout) {
1007 Log *log = GetLog(LLDBLog::Process);
1008 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
1009
1010 StateType state = eStateInvalid;
1011 if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1014 timeout))
1015 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1016 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1017
1018 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
1019 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
1020 return state;
1021}
1022
1024 const Timeout<std::micro> &timeout,
1025 bool control_only) {
1026 Log *log = GetLog(LLDBLog::Process);
1027 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
1028
1029 if (control_only)
1030 return m_private_state_listener_sp->GetEventForBroadcaster(
1031 &m_private_state_control_broadcaster, event_sp, timeout);
1032 else
1033 return m_private_state_listener_sp->GetEvent(event_sp, timeout);
1034}
1035
1038}
1039
1041 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1042
1044 return m_exit_status;
1045 return -1;
1046}
1047
1049 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1050
1052 return m_exit_string.c_str();
1053 return nullptr;
1054}
1055
1056bool Process::SetExitStatus(int status, llvm::StringRef exit_string) {
1057 // Use a mutex to protect setting the exit status.
1058 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1059
1061 LLDB_LOG(log, "(plugin = {0} status = {1} ({1:x8}), description=\"{2}\")",
1062 GetPluginName(), status, exit_string);
1063
1064 // We were already in the exited state
1066 LLDB_LOG(
1067 log,
1068 "(plugin = {0}) ignoring exit status because state was already set "
1069 "to eStateExited",
1070 GetPluginName());
1071 return false;
1072 }
1073
1074 m_exit_status = status;
1075 if (!exit_string.empty())
1076 m_exit_string = exit_string.str();
1077 else
1078 m_exit_string.clear();
1079
1080 // Clear the last natural stop ID since it has a strong reference to this
1081 // process
1083
1085
1086 // Allow subclasses to do some cleanup
1087 DidExit();
1088
1089 return true;
1090}
1091
1093 switch (m_private_state.GetValue()) {
1094 case eStateConnected:
1095 case eStateAttaching:
1096 case eStateLaunching:
1097 case eStateStopped:
1098 case eStateRunning:
1099 case eStateStepping:
1100 case eStateCrashed:
1101 case eStateSuspended:
1102 return true;
1103 default:
1104 return false;
1105 }
1106}
1107
1108// This static callback can be used to watch for local child processes on the
1109// current host. The child process exits, the process will be found in the
1110// global target list (we want to be completely sure that the
1111// lldb_private::Process doesn't go away before we can deliver the signal.
1113 lldb::pid_t pid, bool exited,
1114 int signo, // Zero for no signal
1115 int exit_status // Exit value of process if signal is zero
1116 ) {
1117 Log *log = GetLog(LLDBLog::Process);
1118 LLDB_LOGF(log,
1119 "Process::SetProcessExitStatus (pid=%" PRIu64
1120 ", exited=%i, signal=%i, exit_status=%i)\n",
1121 pid, exited, signo, exit_status);
1122
1123 if (exited) {
1125 if (target_sp) {
1126 ProcessSP process_sp(target_sp->GetProcessSP());
1127 if (process_sp) {
1128 llvm::StringRef signal_str =
1129 process_sp->GetUnixSignals()->GetSignalAsStringRef(signo);
1130 process_sp->SetExitStatus(exit_status, signal_str);
1131 }
1132 }
1133 return true;
1134 }
1135 return false;
1136}
1137
1139 ThreadList &new_thread_list) {
1141 return DoUpdateThreadList(old_thread_list, new_thread_list);
1142}
1143
1145 const uint32_t stop_id = GetStopID();
1146 if (m_thread_list.GetSize(false) == 0 ||
1147 stop_id != m_thread_list.GetStopID()) {
1148 bool clear_unused_threads = true;
1149 const StateType state = GetPrivateState();
1150 if (StateIsStoppedState(state, true)) {
1151 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
1152 m_thread_list.SetStopID(stop_id);
1153
1154 // m_thread_list does have its own mutex, but we need to hold onto the
1155 // mutex between the call to UpdateThreadList(...) and the
1156 // os->UpdateThreadList(...) so it doesn't change on us
1157 ThreadList &old_thread_list = m_thread_list;
1158 ThreadList real_thread_list(this);
1159 ThreadList new_thread_list(this);
1160 // Always update the thread list with the protocol specific thread list,
1161 // but only update if "true" is returned
1162 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1163 // Don't call into the OperatingSystem to update the thread list if we
1164 // are shutting down, since that may call back into the SBAPI's,
1165 // requiring the API lock which is already held by whoever is shutting
1166 // us down, causing a deadlock.
1168 if (os && !m_destroy_in_process) {
1169 // Clear any old backing threads where memory threads might have been
1170 // backed by actual threads from the lldb_private::Process subclass
1171 size_t num_old_threads = old_thread_list.GetSize(false);
1172 for (size_t i = 0; i < num_old_threads; ++i)
1173 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1174 // See if the OS plugin reports all threads. If it does, then
1175 // it is safe to clear unseen thread's plans here. Otherwise we
1176 // should preserve them in case they show up again:
1177 clear_unused_threads = GetOSPluginReportsAllThreads();
1178
1179 // Turn off dynamic types to ensure we don't run any expressions.
1180 // Objective-C can run an expression to determine if a SBValue is a
1181 // dynamic type or not and we need to avoid this. OperatingSystem
1182 // plug-ins can't run expressions that require running code...
1183
1184 Target &target = GetTarget();
1185 const lldb::DynamicValueType saved_prefer_dynamic =
1186 target.GetPreferDynamicValue();
1187 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1189
1190 // Now let the OperatingSystem plug-in update the thread list
1191
1192 os->UpdateThreadList(
1193 old_thread_list, // Old list full of threads created by OS plug-in
1194 real_thread_list, // The actual thread list full of threads
1195 // created by each lldb_private::Process
1196 // subclass
1197 new_thread_list); // The new thread list that we will show to the
1198 // user that gets filled in
1199
1200 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1201 target.SetPreferDynamicValue(saved_prefer_dynamic);
1202 } else {
1203 // No OS plug-in, the new thread list is the same as the real thread
1204 // list.
1205 new_thread_list = real_thread_list;
1206 }
1207
1208 m_thread_list_real.Update(real_thread_list);
1209 m_thread_list.Update(new_thread_list);
1210 m_thread_list.SetStopID(stop_id);
1211
1213 // Clear any extended threads that we may have accumulated previously
1216
1219 }
1220 }
1221 // Now update the plan stack map.
1222 // If we do have an OS plugin, any absent real threads in the
1223 // m_thread_list have already been removed from the ThreadPlanStackMap.
1224 // So any remaining threads are OS Plugin threads, and those we want to
1225 // preserve in case they show up again.
1226 m_thread_plans.Update(m_thread_list, clear_unused_threads);
1227 }
1228 }
1229}
1230
1232 return m_thread_plans.Find(tid);
1233}
1234
1236 return m_thread_plans.PrunePlansForTID(tid);
1237}
1238
1240 m_thread_plans.Update(GetThreadList(), true, false);
1241}
1242
1244 lldb::DescriptionLevel desc_level,
1245 bool internal, bool condense_trivial,
1246 bool skip_unreported_plans) {
1248 strm, tid, desc_level, internal, condense_trivial, skip_unreported_plans);
1249}
1251 bool internal, bool condense_trivial,
1252 bool skip_unreported_plans) {
1253 m_thread_plans.DumpPlans(strm, desc_level, internal, condense_trivial,
1254 skip_unreported_plans);
1255}
1256
1258 if (m_system_runtime_up) {
1259 if (m_queue_list.GetSize() == 0 ||
1261 const StateType state = GetPrivateState();
1262 if (StateIsStoppedState(state, true)) {
1263 m_system_runtime_up->PopulateQueueList(m_queue_list);
1265 }
1266 }
1267 }
1268}
1269
1272 if (os)
1273 return os->CreateThread(tid, context);
1274 return ThreadSP();
1275}
1276
1277uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1278 return AssignIndexIDToThread(thread_id);
1279}
1280
1281bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1282 return (m_thread_id_to_index_id_map.find(thread_id) !=
1284}
1285
1286uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1287 uint32_t result = 0;
1288 std::map<uint64_t, uint32_t>::iterator iterator =
1289 m_thread_id_to_index_id_map.find(thread_id);
1290 if (iterator == m_thread_id_to_index_id_map.end()) {
1291 result = ++m_thread_index_id;
1292 m_thread_id_to_index_id_map[thread_id] = result;
1293 } else {
1294 result = iterator->second;
1295 }
1296
1297 return result;
1298}
1299
1302 return m_private_state.GetValue();
1303 else
1304 return m_public_state.GetValue();
1305}
1306
1307void Process::SetPublicState(StateType new_state, bool restarted) {
1308 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1309 if (new_state_is_stopped) {
1310 // This will only set the time if the public stop time has no value, so
1311 // it is ok to call this multiple times. With a public stop we can't look
1312 // at the stop ID because many private stops might have happened, so we
1313 // can't check for a stop ID of zero. This allows the "statistics" command
1314 // to dump the time it takes to reach somewhere in your code, like a
1315 // breakpoint you set.
1317 }
1318
1320 LLDB_LOGF(log, "(plugin = %s, state = %s, restarted = %i)",
1321 GetPluginName().data(), StateAsCString(new_state), restarted);
1322 const StateType old_state = m_public_state.GetValue();
1323 m_public_state.SetValue(new_state);
1324
1325 // On the transition from Run to Stopped, we unlock the writer end of the run
1326 // lock. The lock gets locked in Resume, which is the public API to tell the
1327 // program to run.
1329 if (new_state == eStateDetached) {
1330 LLDB_LOGF(log,
1331 "(plugin = %s, state = %s) -- unlocking run lock for detach",
1332 GetPluginName().data(), StateAsCString(new_state));
1334 } else {
1335 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1336 if ((old_state_is_stopped != new_state_is_stopped)) {
1337 if (new_state_is_stopped && !restarted) {
1338 LLDB_LOGF(log, "(plugin = %s, state = %s) -- unlocking run lock",
1339 GetPluginName().data(), StateAsCString(new_state));
1341 }
1342 }
1343 }
1344 }
1345}
1346
1349 LLDB_LOGF(log, "(plugin = %s) -- locking run lock", GetPluginName().data());
1351 Status error("Resume request failed - process still running.");
1352 LLDB_LOGF(log, "(plugin = %s) -- TrySetRunning failed, not resuming.",
1353 GetPluginName().data());
1354 return error;
1355 }
1357 if (!error.Success()) {
1358 // Undo running state change
1360 }
1361 return error;
1362}
1363
1366 LLDB_LOGF(log, "Process::ResumeSynchronous -- locking run lock");
1368 Status error("Resume request failed - process still running.");
1369 LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");
1370 return error;
1371 }
1372
1373 ListenerSP listener_sp(
1375 HijackProcessEvents(listener_sp);
1376
1378 if (error.Success()) {
1379 StateType state =
1380 WaitForProcessToStop(std::nullopt, nullptr, true, listener_sp, stream,
1381 true /* use_run_lock */, SelectMostRelevantFrame);
1382 const bool must_be_alive =
1383 false; // eStateExited is ok, so this must be false
1384 if (!StateIsStoppedState(state, must_be_alive))
1385 error.SetErrorStringWithFormat(
1386 "process not in stopped state after synchronous resume: %s",
1387 StateAsCString(state));
1388 } else {
1389 // Undo running state change
1391 }
1392
1393 // Undo the hijacking of process events...
1395
1396 return error;
1397}
1398
1401 llvm::StringRef hijacking_name = GetHijackingListenerName();
1402 if (!hijacking_name.starts_with("lldb.internal"))
1403 return true;
1404 }
1405 return false;
1406}
1407
1410 llvm::StringRef hijacking_name = GetHijackingListenerName();
1411 if (hijacking_name == ResumeSynchronousHijackListenerName)
1412 return true;
1413 }
1414 return false;
1415}
1416
1418
1420 // Use m_destructing not m_finalizing here. If we are finalizing a process
1421 // that we haven't started tearing down, we'd like to be able to nicely
1422 // detach if asked, but that requires the event system be live. That will
1423 // not be true for an in-the-middle-of-being-destructed Process, since the
1424 // event system relies on Process::shared_from_this, which may have already
1425 // been destroyed.
1426 if (m_destructing)
1427 return;
1428
1430 bool state_changed = false;
1431
1432 LLDB_LOGF(log, "(plugin = %s, state = %s)", GetPluginName().data(),
1433 StateAsCString(new_state));
1434
1435 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1436 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1437
1438 const StateType old_state = m_private_state.GetValueNoLock();
1439 state_changed = old_state != new_state;
1440
1441 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1442 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1443 if (old_state_is_stopped != new_state_is_stopped) {
1444 if (new_state_is_stopped)
1446 else
1448 }
1449
1450 if (state_changed) {
1452 EventSP event_sp(
1454 new ProcessEventData(shared_from_this(), new_state)));
1455 if (StateIsStoppedState(new_state, false)) {
1456 // Note, this currently assumes that all threads in the list stop when
1457 // the process stops. In the future we will want to support a debugging
1458 // model where some threads continue to run while others are stopped.
1459 // When that happens we will either need a way for the thread list to
1460 // identify which threads are stopping or create a special thread list
1461 // containing only threads which actually stopped.
1462 //
1463 // The process plugin is responsible for managing the actual behavior of
1464 // the threads and should have stopped any threads that are going to stop
1465 // before we get here.
1467
1468 if (m_mod_id.BumpStopID() == 0)
1470
1474 LLDB_LOGF(log, "(plugin = %s, state = %s, stop_id = %u",
1475 GetPluginName().data(), StateAsCString(new_state),
1477 }
1478
1480 } else {
1481 LLDB_LOGF(log, "(plugin = %s, state = %s) state didn't change. Ignoring...",
1482 GetPluginName().data(), StateAsCString(new_state));
1483 }
1484}
1485
1488}
1489
1492}
1493
1495
1497 if (!m_abi_sp)
1498 m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());
1499 return m_abi_sp;
1500}
1501
1502std::vector<LanguageRuntime *> Process::GetLanguageRuntimes() {
1503 std::vector<LanguageRuntime *> language_runtimes;
1504
1505 if (m_finalizing)
1506 return language_runtimes;
1507
1508 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
1509 // Before we pass off a copy of the language runtimes, we must make sure that
1510 // our collection is properly populated. It's possible that some of the
1511 // language runtimes were not loaded yet, either because nobody requested it
1512 // yet or the proper condition for loading wasn't yet met (e.g. libc++.so
1513 // hadn't been loaded).
1514 for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {
1515 if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type))
1516 language_runtimes.emplace_back(runtime);
1517 }
1518
1519 return language_runtimes;
1520}
1521
1523 if (m_finalizing)
1524 return nullptr;
1525
1526 LanguageRuntime *runtime = nullptr;
1527
1528 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
1529 LanguageRuntimeCollection::iterator pos;
1530 pos = m_language_runtimes.find(language);
1531 if (pos == m_language_runtimes.end() || !pos->second) {
1532 lldb::LanguageRuntimeSP runtime_sp(
1533 LanguageRuntime::FindPlugin(this, language));
1534
1535 m_language_runtimes[language] = runtime_sp;
1536 runtime = runtime_sp.get();
1537 } else
1538 runtime = pos->second.get();
1539
1540 if (runtime)
1541 // It's possible that a language runtime can support multiple LanguageTypes,
1542 // for example, CPPLanguageRuntime will support eLanguageTypeC_plus_plus,
1543 // eLanguageTypeC_plus_plus_03, etc. Because of this, we should get the
1544 // primary language type and make sure that our runtime supports it.
1545 assert(runtime->GetLanguageType() == Language::GetPrimaryLanguage(language));
1546
1547 return runtime;
1548}
1549
1551 if (m_finalizing)
1552 return false;
1553
1554 if (in_value.IsDynamic())
1555 return false;
1556 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1557
1558 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1559 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1560 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1561 }
1562
1563 for (LanguageRuntime *runtime : GetLanguageRuntimes()) {
1564 if (runtime->CouldHaveDynamicValue(in_value))
1565 return true;
1566 }
1567
1568 return false;
1569}
1570
1572 m_dynamic_checkers_up.reset(dynamic_checkers);
1573}
1574
1577}
1578
1582}
1583
1585 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1586 // bp_site->SetEnabled(true);
1587 DisableBreakpointSite(bp_site);
1588 });
1589}
1590
1593
1594 if (error.Success())
1596
1597 return error;
1598}
1599
1601 Status error;
1602 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1603 if (bp_site_sp) {
1604 if (bp_site_sp->IsEnabled())
1605 error = DisableBreakpointSite(bp_site_sp.get());
1606 } else {
1607 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1608 break_id);
1609 }
1610
1611 return error;
1612}
1613
1615 Status error;
1616 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1617 if (bp_site_sp) {
1618 if (!bp_site_sp->IsEnabled())
1619 error = EnableBreakpointSite(bp_site_sp.get());
1620 } else {
1621 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1622 break_id);
1623 }
1624 return error;
1625}
1626
1629 bool use_hardware) {
1630 addr_t load_addr = LLDB_INVALID_ADDRESS;
1631
1632 bool show_error = true;
1633 switch (GetState()) {
1634 case eStateInvalid:
1635 case eStateUnloaded:
1636 case eStateConnected:
1637 case eStateAttaching:
1638 case eStateLaunching:
1639 case eStateDetached:
1640 case eStateExited:
1641 show_error = false;
1642 break;
1643
1644 case eStateStopped:
1645 case eStateRunning:
1646 case eStateStepping:
1647 case eStateCrashed:
1648 case eStateSuspended:
1649 show_error = IsAlive();
1650 break;
1651 }
1652
1653 // Reset the IsIndirect flag here, in case the location changes from pointing
1654 // to a indirect symbol to a regular symbol.
1655 constituent->SetIsIndirect(false);
1656
1657 if (constituent->ShouldResolveIndirectFunctions()) {
1658 Symbol *symbol = constituent->GetAddress().CalculateSymbolContextSymbol();
1659 if (symbol && symbol->IsIndirect()) {
1660 Status error;
1661 Address symbol_address = symbol->GetAddress();
1662 load_addr = ResolveIndirectFunction(&symbol_address, error);
1663 if (!error.Success() && show_error) {
1665 "warning: failed to resolve indirect function at 0x%" PRIx64
1666 " for breakpoint %i.%i: %s\n",
1667 symbol->GetLoadAddress(&GetTarget()),
1668 constituent->GetBreakpoint().GetID(), constituent->GetID(),
1669 error.AsCString() ? error.AsCString() : "unknown error");
1670 return LLDB_INVALID_BREAK_ID;
1671 }
1672 Address resolved_address(load_addr);
1673 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1674 constituent->SetIsIndirect(true);
1675 } else
1676 load_addr = constituent->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1677 } else
1678 load_addr = constituent->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1679
1680 if (load_addr != LLDB_INVALID_ADDRESS) {
1681 BreakpointSiteSP bp_site_sp;
1682
1683 // Look up this breakpoint site. If it exists, then add this new
1684 // constituent, otherwise create a new breakpoint site and add it.
1685
1686 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1687
1688 if (bp_site_sp) {
1689 bp_site_sp->AddConstituent(constituent);
1690 constituent->SetBreakpointSite(bp_site_sp);
1691 return bp_site_sp->GetID();
1692 } else {
1693 bp_site_sp.reset(
1694 new BreakpointSite(constituent, load_addr, use_hardware));
1695 if (bp_site_sp) {
1696 Status error = EnableBreakpointSite(bp_site_sp.get());
1697 if (error.Success()) {
1698 constituent->SetBreakpointSite(bp_site_sp);
1699 return m_breakpoint_site_list.Add(bp_site_sp);
1700 } else {
1701 if (show_error || use_hardware) {
1702 // Report error for setting breakpoint...
1704 "warning: failed to set breakpoint site at 0x%" PRIx64
1705 " for breakpoint %i.%i: %s\n",
1706 load_addr, constituent->GetBreakpoint().GetID(),
1707 constituent->GetID(),
1708 error.AsCString() ? error.AsCString() : "unknown error");
1709 }
1710 }
1711 }
1712 }
1713 }
1714 // We failed to enable the breakpoint
1715 return LLDB_INVALID_BREAK_ID;
1716}
1717
1719 lldb::user_id_t constituent_id, lldb::user_id_t constituent_loc_id,
1720 BreakpointSiteSP &bp_site_sp) {
1721 uint32_t num_constituents =
1722 bp_site_sp->RemoveConstituent(constituent_id, constituent_loc_id);
1723 if (num_constituents == 0) {
1724 // Don't try to disable the site if we don't have a live process anymore.
1725 if (IsAlive())
1726 DisableBreakpointSite(bp_site_sp.get());
1727 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1728 }
1729}
1730
1732 uint8_t *buf) const {
1733 size_t bytes_removed = 0;
1734 StopPointSiteList<BreakpointSite> bp_sites_in_range;
1735
1736 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1737 bp_sites_in_range)) {
1738 bp_sites_in_range.ForEach([bp_addr, size,
1739 buf](BreakpointSite *bp_site) -> void {
1740 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1741 addr_t intersect_addr;
1742 size_t intersect_size;
1743 size_t opcode_offset;
1744 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1745 &intersect_size, &opcode_offset)) {
1746 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1747 assert(bp_addr < intersect_addr + intersect_size &&
1748 intersect_addr + intersect_size <= bp_addr + size);
1749 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1750 size_t buf_offset = intersect_addr - bp_addr;
1751 ::memcpy(buf + buf_offset,
1752 bp_site->GetSavedOpcodeBytes() + opcode_offset,
1753 intersect_size);
1754 }
1755 }
1756 });
1757 }
1758 return bytes_removed;
1759}
1760
1762 PlatformSP platform_sp(GetTarget().GetPlatform());
1763 if (platform_sp)
1764 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
1765 return 0;
1766}
1767
1769 Status error;
1770 assert(bp_site != nullptr);
1772 const addr_t bp_addr = bp_site->GetLoadAddress();
1773 LLDB_LOGF(
1774 log, "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
1775 bp_site->GetID(), (uint64_t)bp_addr);
1776 if (bp_site->IsEnabled()) {
1777 LLDB_LOGF(
1778 log,
1779 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1780 " -- already enabled",
1781 bp_site->GetID(), (uint64_t)bp_addr);
1782 return error;
1783 }
1784
1785 if (bp_addr == LLDB_INVALID_ADDRESS) {
1786 error.SetErrorString("BreakpointSite contains an invalid load address.");
1787 return error;
1788 }
1789 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1790 // trap for the breakpoint site
1791 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1792
1793 if (bp_opcode_size == 0) {
1794 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
1795 "returned zero, unable to get breakpoint "
1796 "trap for address 0x%" PRIx64,
1797 bp_addr);
1798 } else {
1799 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1800
1801 if (bp_opcode_bytes == nullptr) {
1802 error.SetErrorString(
1803 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1804 return error;
1805 }
1806
1807 // Save the original opcode by reading it
1808 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
1809 error) == bp_opcode_size) {
1810 // Write a software breakpoint in place of the original opcode
1811 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
1812 bp_opcode_size) {
1813 uint8_t verify_bp_opcode_bytes[64];
1814 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
1815 error) == bp_opcode_size) {
1816 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
1817 bp_opcode_size) == 0) {
1818 bp_site->SetEnabled(true);
1820 LLDB_LOGF(log,
1821 "Process::EnableSoftwareBreakpoint (site_id = %d) "
1822 "addr = 0x%" PRIx64 " -- SUCCESS",
1823 bp_site->GetID(), (uint64_t)bp_addr);
1824 } else
1825 error.SetErrorString(
1826 "failed to verify the breakpoint trap in memory.");
1827 } else
1828 error.SetErrorString(
1829 "Unable to read memory to verify breakpoint trap.");
1830 } else
1831 error.SetErrorString("Unable to write breakpoint trap to memory.");
1832 } else
1833 error.SetErrorString("Unable to read memory at breakpoint address.");
1834 }
1835 if (log && error.Fail())
1836 LLDB_LOGF(
1837 log,
1838 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1839 " -- FAILED: %s",
1840 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1841 return error;
1842}
1843
1845 Status error;
1846 assert(bp_site != nullptr);
1848 addr_t bp_addr = bp_site->GetLoadAddress();
1849 lldb::user_id_t breakID = bp_site->GetID();
1850 LLDB_LOGF(log,
1851 "Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
1852 ") addr = 0x%" PRIx64,
1853 breakID, (uint64_t)bp_addr);
1854
1855 if (bp_site->IsHardware()) {
1856 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1857 } else if (bp_site->IsEnabled()) {
1858 const size_t break_op_size = bp_site->GetByteSize();
1859 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
1860 if (break_op_size > 0) {
1861 // Clear a software breakpoint instruction
1862 uint8_t curr_break_op[8];
1863 assert(break_op_size <= sizeof(curr_break_op));
1864 bool break_op_found = false;
1865
1866 // Read the breakpoint opcode
1867 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
1868 break_op_size) {
1869 bool verify = false;
1870 // Make sure the breakpoint opcode exists at this address
1871 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
1872 break_op_found = true;
1873 // We found a valid breakpoint opcode at this address, now restore
1874 // the saved opcode.
1875 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
1876 break_op_size, error) == break_op_size) {
1877 verify = true;
1878 } else
1879 error.SetErrorString(
1880 "Memory write failed when restoring original opcode.");
1881 } else {
1882 error.SetErrorString(
1883 "Original breakpoint trap is no longer in memory.");
1884 // Set verify to true and so we can check if the original opcode has
1885 // already been restored
1886 verify = true;
1887 }
1888
1889 if (verify) {
1890 uint8_t verify_opcode[8];
1891 assert(break_op_size < sizeof(verify_opcode));
1892 // Verify that our original opcode made it back to the inferior
1893 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
1894 break_op_size) {
1895 // compare the memory we just read with the original opcode
1896 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
1897 break_op_size) == 0) {
1898 // SUCCESS
1899 bp_site->SetEnabled(false);
1900 LLDB_LOGF(log,
1901 "Process::DisableSoftwareBreakpoint (site_id = %d) "
1902 "addr = 0x%" PRIx64 " -- SUCCESS",
1903 bp_site->GetID(), (uint64_t)bp_addr);
1904 return error;
1905 } else {
1906 if (break_op_found)
1907 error.SetErrorString("Failed to restore original opcode.");
1908 }
1909 } else
1910 error.SetErrorString("Failed to read memory to verify that "
1911 "breakpoint trap was restored.");
1912 }
1913 } else
1914 error.SetErrorString(
1915 "Unable to read memory that should contain the breakpoint trap.");
1916 }
1917 } else {
1918 LLDB_LOGF(
1919 log,
1920 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1921 " -- already disabled",
1922 bp_site->GetID(), (uint64_t)bp_addr);
1923 return error;
1924 }
1925
1926 LLDB_LOGF(
1927 log,
1928 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1929 " -- FAILED: %s",
1930 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1931 return error;
1932}
1933
1934// Uncomment to verify memory caching works after making changes to caching
1935// code
1936//#define VERIFY_MEMORY_READS
1937
1938size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
1939 if (ABISP abi_sp = GetABI())
1940 addr = abi_sp->FixAnyAddress(addr);
1941
1942 error.Clear();
1943 if (!GetDisableMemoryCache()) {
1944#if defined(VERIFY_MEMORY_READS)
1945 // Memory caching is enabled, with debug verification
1946
1947 if (buf && size) {
1948 // Uncomment the line below to make sure memory caching is working.
1949 // I ran this through the test suite and got no assertions, so I am
1950 // pretty confident this is working well. If any changes are made to
1951 // memory caching, uncomment the line below and test your changes!
1952
1953 // Verify all memory reads by using the cache first, then redundantly
1954 // reading the same memory from the inferior and comparing to make sure
1955 // everything is exactly the same.
1956 std::string verify_buf(size, '\0');
1957 assert(verify_buf.size() == size);
1958 const size_t cache_bytes_read =
1959 m_memory_cache.Read(this, addr, buf, size, error);
1960 Status verify_error;
1961 const size_t verify_bytes_read =
1962 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
1963 verify_buf.size(), verify_error);
1964 assert(cache_bytes_read == verify_bytes_read);
1965 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1966 assert(verify_error.Success() == error.Success());
1967 return cache_bytes_read;
1968 }
1969 return 0;
1970#else // !defined(VERIFY_MEMORY_READS)
1971 // Memory caching is enabled, without debug verification
1972
1973 return m_memory_cache.Read(addr, buf, size, error);
1974#endif // defined (VERIFY_MEMORY_READS)
1975 } else {
1976 // Memory caching is disabled
1977
1978 return ReadMemoryFromInferior(addr, buf, size, error);
1979 }
1980}
1981
1982size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
1983 Status &error) {
1984 char buf[256];
1985 out_str.clear();
1986 addr_t curr_addr = addr;
1987 while (true) {
1988 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
1989 if (length == 0)
1990 break;
1991 out_str.append(buf, length);
1992 // If we got "length - 1" bytes, we didn't get the whole C string, we need
1993 // to read some more characters
1994 if (length == sizeof(buf) - 1)
1995 curr_addr += length;
1996 else
1997 break;
1998 }
1999 return out_str.size();
2000}
2001
2002// Deprecated in favor of ReadStringFromMemory which has wchar support and
2003// correct code to find null terminators.
2005 size_t dst_max_len,
2006 Status &result_error) {
2007 size_t total_cstr_len = 0;
2008 if (dst && dst_max_len) {
2009 result_error.Clear();
2010 // NULL out everything just to be safe
2011 memset(dst, 0, dst_max_len);
2012 Status error;
2013 addr_t curr_addr = addr;
2014 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2015 size_t bytes_left = dst_max_len - 1;
2016 char *curr_dst = dst;
2017
2018 while (bytes_left > 0) {
2019 addr_t cache_line_bytes_left =
2020 cache_line_size - (curr_addr % cache_line_size);
2021 addr_t bytes_to_read =
2022 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2023 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
2024
2025 if (bytes_read == 0) {
2026 result_error = error;
2027 dst[total_cstr_len] = '\0';
2028 break;
2029 }
2030 const size_t len = strlen(curr_dst);
2031
2032 total_cstr_len += len;
2033
2034 if (len < bytes_to_read)
2035 break;
2036
2037 curr_dst += bytes_read;
2038 curr_addr += bytes_read;
2039 bytes_left -= bytes_read;
2040 }
2041 } else {
2042 if (dst == nullptr)
2043 result_error.SetErrorString("invalid arguments");
2044 else
2045 result_error.Clear();
2046 }
2047 return total_cstr_len;
2048}
2049
2050size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
2051 Status &error) {
2053
2054 if (ABISP abi_sp = GetABI())
2055 addr = abi_sp->FixAnyAddress(addr);
2056
2057 if (buf == nullptr || size == 0)
2058 return 0;
2059
2060 size_t bytes_read = 0;
2061 uint8_t *bytes = (uint8_t *)buf;
2062
2063 while (bytes_read < size) {
2064 const size_t curr_size = size - bytes_read;
2065 const size_t curr_bytes_read =
2066 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2067 bytes_read += curr_bytes_read;
2068 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2069 break;
2070 }
2071
2072 // Replace any software breakpoint opcodes that fall into this range back
2073 // into "buf" before we return
2074 if (bytes_read > 0)
2075 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2076 return bytes_read;
2077}
2078
2080 size_t integer_byte_size,
2081 uint64_t fail_value,
2082 Status &error) {
2083 Scalar scalar;
2084 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2085 error))
2086 return scalar.ULongLong(fail_value);
2087 return fail_value;
2088}
2089
2091 size_t integer_byte_size,
2092 int64_t fail_value,
2093 Status &error) {
2094 Scalar scalar;
2095 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2096 error))
2097 return scalar.SLongLong(fail_value);
2098 return fail_value;
2099}
2100
2102 Scalar scalar;
2103 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2104 error))
2105 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2106 return LLDB_INVALID_ADDRESS;
2107}
2108
2110 Status &error) {
2111 Scalar scalar;
2112 const uint32_t addr_byte_size = GetAddressByteSize();
2113 if (addr_byte_size <= 4)
2114 scalar = (uint32_t)ptr_value;
2115 else
2116 scalar = ptr_value;
2117 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2118 addr_byte_size;
2119}
2120
2121size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
2122 Status &error) {
2123 size_t bytes_written = 0;
2124 const uint8_t *bytes = (const uint8_t *)buf;
2125
2126 while (bytes_written < size) {
2127 const size_t curr_size = size - bytes_written;
2128 const size_t curr_bytes_written = DoWriteMemory(
2129 addr + bytes_written, bytes + bytes_written, curr_size, error);
2130 bytes_written += curr_bytes_written;
2131 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2132 break;
2133 }
2134 return bytes_written;
2135}
2136
2137size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
2138 Status &error) {
2139 if (ABISP abi_sp = GetABI())
2140 addr = abi_sp->FixAnyAddress(addr);
2141
2142#if defined(ENABLE_MEMORY_CACHING)
2143 m_memory_cache.Flush(addr, size);
2144#endif
2145
2146 if (buf == nullptr || size == 0)
2147 return 0;
2148
2150
2151 // We need to write any data that would go where any current software traps
2152 // (enabled software breakpoints) any software traps (breakpoints) that we
2153 // may have placed in our tasks memory.
2154
2155 StopPointSiteList<BreakpointSite> bp_sites_in_range;
2156 if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range))
2157 return WriteMemoryPrivate(addr, buf, size, error);
2158
2159 // No breakpoint sites overlap
2160 if (bp_sites_in_range.IsEmpty())
2161 return WriteMemoryPrivate(addr, buf, size, error);
2162
2163 const uint8_t *ubuf = (const uint8_t *)buf;
2164 uint64_t bytes_written = 0;
2165
2166 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2167 &error](BreakpointSite *bp) -> void {
2168 if (error.Fail())
2169 return;
2170
2172 return;
2173
2174 addr_t intersect_addr;
2175 size_t intersect_size;
2176 size_t opcode_offset;
2177 const bool intersects = bp->IntersectsRange(
2178 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2179 UNUSED_IF_ASSERT_DISABLED(intersects);
2180 assert(intersects);
2181 assert(addr <= intersect_addr && intersect_addr < addr + size);
2182 assert(addr < intersect_addr + intersect_size &&
2183 intersect_addr + intersect_size <= addr + size);
2184 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2185
2186 // Check for bytes before this breakpoint
2187 const addr_t curr_addr = addr + bytes_written;
2188 if (intersect_addr > curr_addr) {
2189 // There are some bytes before this breakpoint that we need to just
2190 // write to memory
2191 size_t curr_size = intersect_addr - curr_addr;
2192 size_t curr_bytes_written =
2193 WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error);
2194 bytes_written += curr_bytes_written;
2195 if (curr_bytes_written != curr_size) {
2196 // We weren't able to write all of the requested bytes, we are
2197 // done looping and will return the number of bytes that we have
2198 // written so far.
2199 if (error.Success())
2200 error.SetErrorToGenericError();
2201 }
2202 }
2203 // Now write any bytes that would cover up any software breakpoints
2204 // directly into the breakpoint opcode buffer
2205 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written,
2206 intersect_size);
2207 bytes_written += intersect_size;
2208 });
2209
2210 // Write any remaining bytes after the last breakpoint if we have any left
2211 if (bytes_written < size)
2212 bytes_written +=
2213 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2214 size - bytes_written, error);
2215
2216 return bytes_written;
2217}
2218
2219size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
2220 size_t byte_size, Status &error) {
2221 if (byte_size == UINT32_MAX)
2222 byte_size = scalar.GetByteSize();
2223 if (byte_size > 0) {
2224 uint8_t buf[32];
2225 const size_t mem_size =
2226 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2227 if (mem_size > 0)
2228 return WriteMemory(addr, buf, mem_size, error);
2229 else
2230 error.SetErrorString("failed to get scalar as memory data");
2231 } else {
2232 error.SetErrorString("invalid scalar value");
2233 }
2234 return 0;
2235}
2236
2237size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2238 bool is_signed, Scalar &scalar,
2239 Status &error) {
2240 uint64_t uval = 0;
2241 if (byte_size == 0) {
2242 error.SetErrorString("byte size is zero");
2243 } else if (byte_size & (byte_size - 1)) {
2244 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2245 byte_size);
2246 } else if (byte_size <= sizeof(uval)) {
2247 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2248 if (bytes_read == byte_size) {
2249 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2251 lldb::offset_t offset = 0;
2252 if (byte_size <= 4)
2253 scalar = data.GetMaxU32(&offset, byte_size);
2254 else
2255 scalar = data.GetMaxU64(&offset, byte_size);
2256 if (is_signed)
2257 scalar.SignExtend(byte_size * 8);
2258 return bytes_read;
2259 }
2260 } else {
2261 error.SetErrorStringWithFormat(
2262 "byte size of %u is too large for integer scalar type", byte_size);
2263 }
2264 return 0;
2265}
2266
2267Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {
2268 Status error;
2269 for (const auto &Entry : entries) {
2270 WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),
2271 error);
2272 if (!error.Success())
2273 break;
2274 }
2275 return error;
2276}
2277
2278#define USE_ALLOCATE_MEMORY_CACHE 1
2279addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
2280 Status &error) {
2281 if (GetPrivateState() != eStateStopped) {
2282 error.SetErrorToGenericError();
2283 return LLDB_INVALID_ADDRESS;
2284 }
2285
2286#if defined(USE_ALLOCATE_MEMORY_CACHE)
2287 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2288#else
2289 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2290 Log *log = GetLog(LLDBLog::Process);
2291 LLDB_LOGF(log,
2292 "Process::AllocateMemory(size=%" PRIu64
2293 ", permissions=%s) => 0x%16.16" PRIx64
2294 " (m_stop_id = %u m_memory_id = %u)",
2295 (uint64_t)size, GetPermissionsAsCString(permissions),
2296 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2298 return allocated_addr;
2299#endif
2300}
2301
2302addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
2303 Status &error) {
2304 addr_t return_addr = AllocateMemory(size, permissions, error);
2305 if (error.Success()) {
2306 std::string buffer(size, 0);
2307 WriteMemory(return_addr, buffer.c_str(), size, error);
2308 }
2309 return return_addr;
2310}
2311
2313 if (m_can_jit == eCanJITDontKnow) {
2314 Log *log = GetLog(LLDBLog::Process);
2315 Status err;
2316
2317 uint64_t allocated_memory = AllocateMemory(
2318 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2319 err);
2320
2321 if (err.Success()) {
2323 LLDB_LOGF(log,
2324 "Process::%s pid %" PRIu64
2325 " allocation test passed, CanJIT () is true",
2326 __FUNCTION__, GetID());
2327 } else {
2329 LLDB_LOGF(log,
2330 "Process::%s pid %" PRIu64
2331 " allocation test failed, CanJIT () is false: %s",
2332 __FUNCTION__, GetID(), err.AsCString());
2333 }
2334
2335 DeallocateMemory(allocated_memory);
2336 }
2337
2338 return m_can_jit == eCanJITYes;
2339}
2340
2341void Process::SetCanJIT(bool can_jit) {
2342 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2343}
2344
2345void Process::SetCanRunCode(bool can_run_code) {
2346 SetCanJIT(can_run_code);
2347 m_can_interpret_function_calls = can_run_code;
2348}
2349
2351 Status error;
2352#if defined(USE_ALLOCATE_MEMORY_CACHE)
2354 error.SetErrorStringWithFormat(
2355 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2356 }
2357#else
2359
2360 Log *log = GetLog(LLDBLog::Process);
2361 LLDB_LOGF(log,
2362 "Process::DeallocateMemory(addr=0x%16.16" PRIx64
2363 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2364 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2366#endif
2367 return error;
2368}
2369
2371 if (std::optional<bool> subclass_override = DoGetWatchpointReportedAfter())
2372 return *subclass_override;
2373
2374 bool reported_after = true;
2375 const ArchSpec &arch = GetTarget().GetArchitecture();
2376 if (!arch.IsValid())
2377 return reported_after;
2378 llvm::Triple triple = arch.GetTriple();
2379
2380 if (triple.isMIPS() || triple.isPPC64() || triple.isRISCV() ||
2381 triple.isAArch64() || triple.isArmMClass() || triple.isARM())
2382 reported_after = false;
2383
2384 return reported_after;
2385}
2386
2388 lldb::addr_t header_addr,
2389 size_t size_to_read) {
2390 Log *log = GetLog(LLDBLog::Host);
2391 if (log) {
2392 LLDB_LOGF(log,
2393 "Process::ReadModuleFromMemory reading %s binary from memory",
2394 file_spec.GetPath().c_str());
2395 }
2396 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2397 if (module_sp) {
2398 Status error;
2399 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2400 shared_from_this(), header_addr, error, size_to_read);
2401 if (objfile)
2402 return module_sp;
2403 }
2404 return ModuleSP();
2405}
2406
2408 uint32_t &permissions) {
2409 MemoryRegionInfo range_info;
2410 permissions = 0;
2411 Status error(GetMemoryRegionInfo(load_addr, range_info));
2412 if (!error.Success())
2413 return false;
2414 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2415 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2417 return false;
2418 }
2419 permissions = range_info.GetLLDBPermissions();
2420 return true;
2421}
2422
2424 Status error;
2425 error.SetErrorString("watchpoints are not supported");
2426 return error;
2427}
2428
2430 Status error;
2431 error.SetErrorString("watchpoints are not supported");
2432 return error;
2433}
2434
2437 const Timeout<std::micro> &timeout) {
2438 StateType state;
2439
2440 while (true) {
2441 event_sp.reset();
2442 state = GetStateChangedEventsPrivate(event_sp, timeout);
2443
2444 if (StateIsStoppedState(state, false))
2445 break;
2446
2447 // If state is invalid, then we timed out
2448 if (state == eStateInvalid)
2449 break;
2450
2451 if (event_sp)
2452 HandlePrivateEvent(event_sp);
2453 }
2454 return state;
2455}
2456
2458 std::lock_guard<std::recursive_mutex> guard(m_thread_mutex);
2459 if (flush)
2461 m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr));
2462 if (flush)
2463 Flush();
2464}
2465
2467 StateType state_after_launch = eStateInvalid;
2468 EventSP first_stop_event_sp;
2469 Status status =
2470 LaunchPrivate(launch_info, state_after_launch, first_stop_event_sp);
2471 if (status.Fail())
2472 return status;
2473
2474 if (state_after_launch != eStateStopped &&
2475 state_after_launch != eStateCrashed)
2476 return Status();
2477
2478 // Note, the stop event was consumed above, but not handled. This
2479 // was done to give DidLaunch a chance to run. The target is either
2480 // stopped or crashed. Directly set the state. This is done to
2481 // prevent a stop message with a bunch of spurious output on thread
2482 // status, as well as not pop a ProcessIOHandler.
2483 SetPublicState(state_after_launch, false);
2484
2487 else
2489
2490 // Target was stopped at entry as was intended. Need to notify the
2491 // listeners about it.
2492 if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2493 HandlePrivateEvent(first_stop_event_sp);
2494
2495 return Status();
2496}
2497
2499 EventSP &event_sp) {
2500 Status error;
2501 m_abi_sp.reset();
2502 m_dyld_up.reset();
2503 m_jit_loaders_up.reset();
2504 m_system_runtime_up.reset();
2505 m_os_up.reset();
2506
2507 {
2508 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
2509 m_process_input_reader.reset();
2510 }
2511
2513
2514 // The "remote executable path" is hooked up to the local Executable
2515 // module. But we should be able to debug a remote process even if the
2516 // executable module only exists on the remote. However, there needs to
2517 // be a way to express this path, without actually having a module.
2518 // The way to do that is to set the ExecutableFile in the LaunchInfo.
2519 // Figure that out here:
2520
2521 FileSpec exe_spec_to_use;
2522 if (!exe_module) {
2523 if (!launch_info.GetExecutableFile() && !launch_info.IsScriptedProcess()) {
2524 error.SetErrorString("executable module does not exist");
2525 return error;
2526 }
2527 exe_spec_to_use = launch_info.GetExecutableFile();
2528 } else
2529 exe_spec_to_use = exe_module->GetFileSpec();
2530
2531 if (exe_module && FileSystem::Instance().Exists(exe_module->GetFileSpec())) {
2532 // Install anything that might need to be installed prior to launching.
2533 // For host systems, this will do nothing, but if we are connected to a
2534 // remote platform it will install any needed binaries
2535 error = GetTarget().Install(&launch_info);
2536 if (error.Fail())
2537 return error;
2538 }
2539
2540 // Listen and queue events that are broadcasted during the process launch.
2541 ListenerSP listener_sp(Listener::MakeListener("LaunchEventHijack"));
2542 HijackProcessEvents(listener_sp);
2543 auto on_exit = llvm::make_scope_exit([this]() { RestoreProcessEvents(); });
2544
2547
2548 error = WillLaunch(exe_module);
2549 if (error.Fail()) {
2550 std::string local_exec_file_path = exe_spec_to_use.GetPath();
2551 return Status("file doesn't exist: '%s'", local_exec_file_path.c_str());
2552 }
2553
2554 const bool restarted = false;
2555 SetPublicState(eStateLaunching, restarted);
2556 m_should_detach = false;
2557
2559 // Now launch using these arguments.
2560 error = DoLaunch(exe_module, launch_info);
2561 } else {
2562 // This shouldn't happen
2563 error.SetErrorString("failed to acquire process run lock");
2564 }
2565
2566 if (error.Fail()) {
2567 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2569 const char *error_string = error.AsCString();
2570 if (error_string == nullptr)
2571 error_string = "launch failed";
2572 SetExitStatus(-1, error_string);
2573 }
2574 return error;
2575 }
2576
2577 // Now wait for the process to launch and return control to us, and then
2578 // call DidLaunch:
2579 state = WaitForProcessStopPrivate(event_sp, seconds(10));
2580
2581 if (state == eStateInvalid || !event_sp) {
2582 // We were able to launch the process, but we failed to catch the
2583 // initial stop.
2584 error.SetErrorString("failed to catch stop after launch");
2585 SetExitStatus(0, error.AsCString());
2586 Destroy(false);
2587 return error;
2588 }
2589
2590 if (state == eStateExited) {
2591 // We exited while trying to launch somehow. Don't call DidLaunch
2592 // as that's not likely to work, and return an invalid pid.
2593 HandlePrivateEvent(event_sp);
2594 return Status();
2595 }
2596
2597 if (state == eStateStopped || state == eStateCrashed) {
2598 DidLaunch();
2599
2600 // Now that we know the process type, update its signal responses from the
2601 // ones stored in the Target:
2602 if (m_unix_signals_sp) {
2605 }
2606
2608 if (dyld)
2609 dyld->DidLaunch();
2610
2612
2613 SystemRuntime *system_runtime = GetSystemRuntime();
2614 if (system_runtime)
2615 system_runtime->DidLaunch();
2616
2617 if (!m_os_up)
2619
2620 // We successfully launched the process and stopped, now it the
2621 // right time to set up signal filters before resuming.
2623 return Status();
2624 }
2625
2626 return Status("Unexpected process state after the launch: %s, expected %s, "
2627 "%s, %s or %s",
2631}
2632
2635 if (error.Success()) {
2636 ListenerSP listener_sp(
2637 Listener::MakeListener("lldb.process.load_core_listener"));
2638 HijackProcessEvents(listener_sp);
2639
2642 else
2644
2646 if (dyld)
2647 dyld->DidAttach();
2648
2650
2651 SystemRuntime *system_runtime = GetSystemRuntime();
2652 if (system_runtime)
2653 system_runtime->DidAttach();
2654
2655 if (!m_os_up)
2657
2658 // We successfully loaded a core file, now pretend we stopped so we can
2659 // show all of the threads in the core file and explore the crashed state.
2661
2662 // Wait for a stopped event since we just posted one above...
2663 lldb::EventSP event_sp;
2664 StateType state =
2665 WaitForProcessToStop(std::nullopt, &event_sp, true, listener_sp,
2666 nullptr, true, SelectMostRelevantFrame);
2667
2668 if (!StateIsStoppedState(state, false)) {
2669 Log *log = GetLog(LLDBLog::Process);
2670 LLDB_LOGF(log, "Process::Halt() failed to stop, state is: %s",
2671 StateAsCString(state));
2672 error.SetErrorString(
2673 "Did not get stopped event after loading the core file.");
2676 }
2677 return error;
2678}
2679
2681 if (!m_dyld_up)
2682 m_dyld_up.reset(DynamicLoader::FindPlugin(this, ""));
2683 return m_dyld_up.get();
2684}
2685
2687 m_dyld_up = std::move(dyld_up);
2688}
2689
2691
2692llvm::Expected<bool> Process::SaveCore(llvm::StringRef outfile) {
2693 return false;
2694}
2695
2697 if (!m_jit_loaders_up) {
2698 m_jit_loaders_up = std::make_unique<JITLoaderList>();
2700 }
2701 return *m_jit_loaders_up;
2702}
2703
2707 return m_system_runtime_up.get();
2708}
2709
2711 uint32_t exec_count)
2712 : NextEventAction(process), m_exec_count(exec_count) {
2713 Log *log = GetLog(LLDBLog::Process);
2714 LLDB_LOGF(
2715 log,
2716 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2717 __FUNCTION__, static_cast<void *>(process), exec_count);
2718}
2719
2722 Log *log = GetLog(LLDBLog::Process);
2723
2724 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2725 LLDB_LOGF(log,
2726 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2727 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
2728
2729 switch (state) {
2730 case eStateAttaching:
2731 return eEventActionSuccess;
2732
2733 case eStateRunning:
2734 case eStateConnected:
2735 return eEventActionRetry;
2736
2737 case eStateStopped:
2738 case eStateCrashed:
2739 // During attach, prior to sending the eStateStopped event,
2740 // lldb_private::Process subclasses must set the new process ID.
2742 // We don't want these events to be reported, so go set the
2743 // ShouldReportStop here:
2745
2746 if (m_exec_count > 0) {
2747 --m_exec_count;
2748
2749 LLDB_LOGF(log,
2750 "Process::AttachCompletionHandler::%s state %s: reduced "
2751 "remaining exec count to %" PRIu32 ", requesting resume",
2752 __FUNCTION__, StateAsCString(state), m_exec_count);
2753
2754 RequestResume();
2755 return eEventActionRetry;
2756 } else {
2757 LLDB_LOGF(log,
2758 "Process::AttachCompletionHandler::%s state %s: no more "
2759 "execs expected to start, continuing with attach",
2760 __FUNCTION__, StateAsCString(state));
2761
2763 return eEventActionSuccess;
2764 }
2765 break;
2766
2767 default:
2768 case eStateExited:
2769 case eStateInvalid:
2770 break;
2771 }
2772
2773 m_exit_string.assign("No valid Process");
2774 return eEventActionExit;
2775}
2776
2779 return eEventActionSuccess;
2780}
2781
2783 return m_exit_string.c_str();
2784}
2785
2787 if (m_listener_sp)
2788 return m_listener_sp;
2789 else
2790 return debugger.GetListener();
2791}
2792
2794 return DoWillLaunch(module);
2795}
2796
2798 return DoWillAttachToProcessWithID(pid);
2799}
2800
2802 bool wait_for_launch) {
2803 return DoWillAttachToProcessWithName(process_name, wait_for_launch);
2804}
2805
2807 m_abi_sp.reset();
2808 {
2809 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
2810 m_process_input_reader.reset();
2811 }
2812 m_dyld_up.reset();
2813 m_jit_loaders_up.reset();
2814 m_system_runtime_up.reset();
2815 m_os_up.reset();
2816
2817 lldb::pid_t attach_pid = attach_info.GetProcessID();
2818 Status error;
2819 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
2820 char process_name[PATH_MAX];
2821
2822 if (attach_info.GetExecutableFile().GetPath(process_name,
2823 sizeof(process_name))) {
2824 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2825
2826 if (wait_for_launch) {
2827 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2828 if (error.Success()) {
2830 m_should_detach = true;
2831 const bool restarted = false;
2832 SetPublicState(eStateAttaching, restarted);
2833 // Now attach using these arguments.
2834 error = DoAttachToProcessWithName(process_name, attach_info);
2835 } else {
2836 // This shouldn't happen
2837 error.SetErrorString("failed to acquire process run lock");
2838 }
2839
2840 if (error.Fail()) {
2841 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2843 if (error.AsCString() == nullptr)
2844 error.SetErrorString("attach failed");
2845
2846 SetExitStatus(-1, error.AsCString());
2847 }
2848 } else {
2850 this, attach_info.GetResumeCount()));
2852 }
2853 return error;
2854 }
2855 } else {
2856 ProcessInstanceInfoList process_infos;
2857 PlatformSP platform_sp(GetTarget().GetPlatform());
2858
2859 if (platform_sp) {
2860 ProcessInstanceInfoMatch match_info;
2861 match_info.GetProcessInfo() = attach_info;
2863 platform_sp->FindProcesses(match_info, process_infos);
2864 const uint32_t num_matches = process_infos.size();
2865 if (num_matches == 1) {
2866 attach_pid = process_infos[0].GetProcessID();
2867 // Fall through and attach using the above process ID
2868 } else {
2870 process_name, sizeof(process_name));
2871 if (num_matches > 1) {
2872 StreamString s;
2874 for (size_t i = 0; i < num_matches; i++) {
2875 process_infos[i].DumpAsTableRow(
2876 s, platform_sp->GetUserIDResolver(), true, false);
2877 }
2878 error.SetErrorStringWithFormat(
2879 "more than one process named %s:\n%s", process_name,
2880 s.GetData());
2881 } else
2882 error.SetErrorStringWithFormat(
2883 "could not find a process named %s", process_name);
2884 }
2885 } else {
2886 error.SetErrorString(
2887 "invalid platform, can't find processes by name");
2888 return error;
2889 }
2890 }
2891 } else {
2892 error.SetErrorString("invalid process name");
2893 }
2894 }
2895
2896 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
2897 error = WillAttachToProcessWithID(attach_pid);
2898 if (error.Success()) {
2899
2901 // Now attach using these arguments.
2902 m_should_detach = true;
2903 const bool restarted = false;
2904 SetPublicState(eStateAttaching, restarted);
2905 error = DoAttachToProcessWithID(attach_pid, attach_info);
2906 } else {
2907 // This shouldn't happen
2908 error.SetErrorString("failed to acquire process run lock");
2909 }
2910
2911 if (error.Success()) {
2913 this, attach_info.GetResumeCount()));
2915 } else {
2918
2919 const char *error_string = error.AsCString();
2920 if (error_string == nullptr)
2921 error_string = "attach failed";
2922
2923 SetExitStatus(-1, error_string);
2924 }
2925 }
2926 }
2927 return error;
2928}
2929
2932 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
2933
2934 // Let the process subclass figure out at much as it can about the process
2935 // before we go looking for a dynamic loader plug-in.
2936 ArchSpec process_arch;
2937 DidAttach(process_arch);
2938
2939 if (process_arch.IsValid()) {
2940 LLDB_LOG(log,
2941 "Process::{0} replacing process architecture with DidAttach() "
2942 "architecture: \"{1}\"",
2943 __FUNCTION__, process_arch.GetTriple().getTriple());
2944 GetTarget().SetArchitecture(process_arch);
2945 }
2946
2947 // We just attached. If we have a platform, ask it for the process
2948 // architecture, and if it isn't the same as the one we've already set,
2949 // switch architectures.
2950 PlatformSP platform_sp(GetTarget().GetPlatform());
2951 assert(platform_sp);
2952 ArchSpec process_host_arch = GetSystemArchitecture();
2953 if (platform_sp) {
2954 const ArchSpec &target_arch = GetTarget().GetArchitecture();
2955 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture(
2956 target_arch, process_host_arch,
2957 ArchSpec::CompatibleMatch, nullptr)) {
2958 ArchSpec platform_arch;
2960 target_arch, process_host_arch, &platform_arch);
2961 if (platform_sp) {
2962 GetTarget().SetPlatform(platform_sp);
2963 GetTarget().SetArchitecture(platform_arch);
2964 LLDB_LOG(log,
2965 "switching platform to {0} and architecture to {1} based on "
2966 "info from attach",
2967 platform_sp->GetName(), platform_arch.GetTriple().getTriple());
2968 }
2969 } else if (!process_arch.IsValid()) {
2970 ProcessInstanceInfo process_info;
2971 GetProcessInfo(process_info);
2972 const ArchSpec &process_arch = process_info.GetArchitecture();
2973 const ArchSpec &target_arch = GetTarget().GetArchitecture();
2974 if (process_arch.IsValid() &&
2975 target_arch.IsCompatibleMatch(process_arch) &&
2976 !target_arch.IsExactMatch(process_arch)) {
2977 GetTarget().SetArchitecture(process_arch);
2978 LLDB_LOGF(log,
2979 "Process::%s switching architecture to %s based on info "
2980 "the platform retrieved for pid %" PRIu64,
2981 __FUNCTION__, process_arch.GetTriple().getTriple().c_str(),
2982 GetID());
2983 }
2984 }
2985 }
2986 // Now that we know the process type, update its signal responses from the
2987 // ones stored in the Target:
2988 if (m_unix_signals_sp) {
2991 }
2992
2993 // We have completed the attach, now it is time to find the dynamic loader
2994 // plug-in
2996 if (dyld) {
2997 dyld->DidAttach();
2998 if (log) {
2999 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3000 LLDB_LOG(log,
3001 "after DynamicLoader::DidAttach(), target "
3002 "executable is {0} (using {1} plugin)",
3003 exe_module_sp ? exe_module_sp->GetFileSpec() : FileSpec(),
3004 dyld->GetPluginName());
3005 }
3006 }
3007
3009
3010 SystemRuntime *system_runtime = GetSystemRuntime();
3011 if (system_runtime) {
3012 system_runtime->DidAttach();
3013 if (log) {
3014 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3015 LLDB_LOG(log,
3016 "after SystemRuntime::DidAttach(), target "
3017 "executable is {0} (using {1} plugin)",
3018 exe_module_sp ? exe_module_sp->GetFileSpec() : FileSpec(),
3019 system_runtime->GetPluginName());
3020 }
3021 }
3022
3023 if (!m_os_up) {
3025 if (m_os_up) {
3026 // Somebody might have gotten threads before now, but we need to force the
3027 // update after we've loaded the OperatingSystem plugin or it won't get a
3028 // chance to process the threads.
3031 }
3032 }
3033 // Figure out which one is the executable, and set that in our target:
3034 ModuleSP new_executable_module_sp;
3035 for (ModuleSP module_sp : GetTarget().GetImages().Modules()) {
3036 if (module_sp && module_sp->IsExecutable()) {
3037 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3038 new_executable_module_sp = module_sp;
3039 break;
3040 }
3041 }
3042 if (new_executable_module_sp) {
3043 GetTarget().SetExecutableModule(new_executable_module_sp,
3045 if (log) {
3046 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3047 LLDB_LOGF(
3048 log,
3049 "Process::%s after looping through modules, target executable is %s",
3050 __FUNCTION__,
3051 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3052 : "<none>");
3053 }
3054 }
3055}
3056
3057Status Process::ConnectRemote(llvm::StringRef remote_url) {
3058 m_abi_sp.reset();
3059 {
3060 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
3061 m_process_input_reader.reset();
3062 }
3063
3064 // Find the process and its architecture. Make sure it matches the
3065 // architecture of the current Target, and if not adjust it.
3066
3067 Status error(DoConnectRemote(remote_url));
3068 if (error.Success()) {
3069 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3070 EventSP event_sp;
3071 StateType state = WaitForProcessStopPrivate(event_sp, std::nullopt);
3072
3073 if (state == eStateStopped || state == eStateCrashed) {
3074 // If we attached and actually have a process on the other end, then
3075 // this ended up being the equivalent of an attach.
3077
3078 // This delays passing the stopped event to listeners till
3079 // CompleteAttach gets a chance to complete...
3080 HandlePrivateEvent(event_sp);
3081 }
3082 }
3083
3086 else
3088 }
3089 return error;
3090}
3091
3094 LLDB_LOGF(log,
3095 "Process::PrivateResume() m_stop_id = %u, public state: %s "
3096 "private state: %s",
3099
3100 // If signals handing status changed we might want to update our signal
3101 // filters before resuming.
3103
3105 // Tell the process it is about to resume before the thread list
3106 if (error.Success()) {
3107 // Now let the thread list know we are about to resume so it can let all of
3108 // our threads know that they are about to be resumed. Threads will each be
3109 // called with Thread::WillResume(StateType) where StateType contains the
3110 // state that they are supposed to have when the process is resumed
3111 // (suspended/running/stepping). Threads should also check their resume
3112 // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
3113 // start back up with a signal.
3114 if (m_thread_list.WillResume()) {
3115 // Last thing, do the PreResumeActions.
3116 if (!RunPreResumeActions()) {
3117 error.SetErrorString(
3118 "Process::PrivateResume PreResumeActions failed, not resuming.");
3119 } else {
3121 error = DoResume();
3122 if (error.Success()) {
3123 DidResume();
3125 LLDB_LOGF(log, "Process thinks the process has resumed.");
3126 } else {
3127 LLDB_LOGF(log, "Process::PrivateResume() DoResume failed.");
3128 return error;
3129 }
3130 }
3131 } else {
3132 // Somebody wanted to run without running (e.g. we were faking a step
3133 // from one frame of a set of inlined frames that share the same PC to
3134 // another.) So generate a continue & a stopped event, and let the world
3135 // handle them.
3136 LLDB_LOGF(log,
3137 "Process::PrivateResume() asked to simulate a start & stop.");
3138
3141 }
3142 } else
3143 LLDB_LOGF(log, "Process::PrivateResume() got an error \"%s\".",
3144 error.AsCString("<unknown error>"));
3145 return error;
3146}
3147
3148Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
3150 return Status("Process is not running.");
3151
3152 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
3153 // case it was already set and some thread plan logic calls halt on its own.
3154 m_clear_thread_plans_on_stop |= clear_thread_plans;
3155
3156 ListenerSP halt_listener_sp(
3157 Listener::MakeListener("lldb.process.halt_listener"));
3158 HijackProcessEvents(halt_listener_sp);
3159
3160 EventSP event_sp;
3161
3163
3165 // Don't hijack and eat the eStateExited as the code that was doing the
3166 // attach will be waiting for this event...
3168 Destroy(false);
3169 SetExitStatus(SIGKILL, "Cancelled async attach.");
3170 return Status();
3171 }
3172
3173 // Wait for the process halt timeout seconds for the process to stop.
3174 // If we are going to use the run lock, that means we're stopping out to the
3175 // user, so we should also select the most relevant frame.
3176 SelectMostRelevant select_most_relevant =
3178 StateType state = WaitForProcessToStop(GetInterruptTimeout(), &event_sp, true,
3179 halt_listener_sp, nullptr,
3180 use_run_lock, select_most_relevant);
3182
3183 if (state == eStateInvalid || !event_sp) {
3184 // We timed out and didn't get a stop event...
3185 return Status("Halt timed out. State = %s", StateAsCString(GetState()));
3186 }
3187
3188 BroadcastEvent(event_sp);
3189
3190 return Status();
3191}
3192
3194 Status error;
3195
3196 // Check both the public & private states here. If we're hung evaluating an
3197 // expression, for instance, then the public state will be stopped, but we
3198 // still need to interrupt.
3201 Log *log = GetLog(LLDBLog::Process);
3202 LLDB_LOGF(log, "Process::%s() About to stop.", __FUNCTION__);
3203
3204 ListenerSP listener_sp(
3205 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3206 HijackProcessEvents(listener_sp);
3207
3209
3210 // Consume the interrupt event.
3212 &exit_event_sp, true, listener_sp);
3213
3215
3216 // If the process exited while we were waiting for it to stop, put the
3217 // exited event into the shared pointer passed in and return. Our caller
3218 // doesn't need to do anything else, since they don't have a process
3219 // anymore...
3220
3221 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
3222 LLDB_LOGF(log, "Process::%s() Process exited while waiting to stop.",
3223 __FUNCTION__);
3224 return error;
3225 } else
3226 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3227
3228 if (state != eStateStopped) {
3229 LLDB_LOGF(log, "Process::%s() failed to stop, state is: %s", __FUNCTION__,
3230 StateAsCString(state));
3231 // If we really couldn't stop the process then we should just error out
3232 // here, but if the lower levels just bobbled sending the event and we
3233 // really are stopped, then continue on.
3234 StateType private_state = m_private_state.GetValue();
3235 if (private_state != eStateStopped) {
3236 return Status(
3237 "Attempt to stop the target in order to detach timed out. "
3238 "State = %s",
3240 }
3241 }
3242 }
3243 return error;
3244}
3245
3246Status Process::Detach(bool keep_stopped) {
3247 EventSP exit_event_sp;
3248 Status error;
3249 m_destroy_in_process = true;
3250
3251 error = WillDetach();
3252
3253 if (error.Success()) {
3254 if (DetachRequiresHalt()) {
3255 error = StopForDestroyOrDetach(exit_event_sp);
3256 if (!error.Success()) {
3257 m_destroy_in_process = false;
3258 return error;
3259 } else if (exit_event_sp) {
3260 // We shouldn't need to do anything else here. There's no process left
3261 // to detach from...
3263 m_destroy_in_process = false;
3264 return error;
3265 }
3266 }
3267
3270
3271 error = DoDetach(keep_stopped);
3272 if (error.Success()) {
3273 DidDetach();
3275 } else {
3276 return error;
3277 }
3278 }
3279 m_destroy_in_process = false;
3280
3281 // If we exited when we were waiting for a process to stop, then forward the
3282 // event here so we don't lose the event
3283 if (exit_event_sp) {
3284 // Directly broadcast our exited event because we shut down our private
3285 // state thread above
3286 BroadcastEvent(exit_event_sp);
3287 }
3288
3289 // If we have been interrupted (to kill us) in the middle of running, we may
3290 // not end up propagating the last events through the event system, in which
3291 // case we might strand the write lock. Unlock it here so when we do to tear
3292 // down the process we don't get an error destroying the lock.
3293
3295 return error;
3296}
3297
3298Status Process::Destroy(bool force_kill) {
3299 // If we've already called Process::Finalize then there's nothing useful to
3300 // be done here. Finalize has actually called Destroy already.
3301 if (m_finalizing)
3302 return {};
3303 return DestroyImpl(force_kill);
3304}
3305
3307 // Tell ourselves we are in the process of destroying the process, so that we
3308 // don't do any unnecessary work that might hinder the destruction. Remember
3309 // to set this back to false when we are done. That way if the attempt
3310 // failed and the process stays around for some reason it won't be in a
3311 // confused state.
3312
3313 if (force_kill)
3314 m_should_detach = false;
3315
3316 if (GetShouldDetach()) {
3317 // FIXME: This will have to be a process setting:
3318 bool keep_stopped = false;
3319 Detach(keep_stopped);
3320 }
3321
3322 m_destroy_in_process = true;
3323
3325 if (error.Success()) {
3326 EventSP exit_event_sp;
3327 if (DestroyRequiresHalt()) {
3328 error = StopForDestroyOrDetach(exit_event_sp);
3329 }
3330
3332 // Ditch all thread plans, and remove all our breakpoints: in case we
3333 // have to restart the target to kill it, we don't want it hitting a
3334 // breakpoint... Only do this if we've stopped, however, since if we
3335 // didn't manage to halt it above, then we're not going to have much luck
3336 // doing this now.
3339 }
3340
3341 error = DoDestroy();
3342 if (error.Success()) {
3343 DidDestroy();
3345 }
3348 m_stdin_forward = false;
3349
3350 {
3351 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
3353 m_process_input_reader->SetIsDone(true);
3354 m_process_input_reader->Cancel();
3355 m_process_input_reader.reset();
3356 }
3357 }
3358
3359 // If we exited when we were waiting for a process to stop, then forward
3360 // the event here so we don't lose the event
3361 if (exit_event_sp) {
3362 // Directly broadcast our exited event because we shut down our private
3363 // state thread above
3364 BroadcastEvent(exit_event_sp);
3365 }
3366
3367 // If we have been interrupted (to kill us) in the middle of running, we
3368 // may not end up propagating the last events through the event system, in
3369 // which case we might strand the write lock. Unlock it here so when we do
3370 // to tear down the process we don't get an error destroying the lock.
3372 }
3373
3374 m_destroy_in_process = false;
3375
3376 return error;
3377}
3378
3381 if (error.Success()) {
3382 error = DoSignal(signal);
3383 if (error.Success())
3384 DidSignal();
3385 }
3386 return error;
3387}
3388
3390 assert(signals_sp && "null signals_sp");
3391 m_unix_signals_sp = std::move(signals_sp);
3392}
3393
3395 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3396 return m_unix_signals_sp;
3397}
3398
3401}
3402
3405}
3406
3408 const StateType state =
3410 bool return_value = true;
3412
3413 switch (state) {
3414 case eStateDetached:
3415 case eStateExited:
3416 case eStateUnloaded:
3420 m_stdin_forward = false;
3421
3422 [[fallthrough]];
3423 case eStateConnected:
3424 case eStateAttaching:
3425 case eStateLaunching:
3426 // These events indicate changes in the state of the debugging session,
3427 // always report them.
3428 return_value = true;
3429 break;
3430 case eStateInvalid:
3431 // We stopped for no apparent reason, don't report it.
3432 return_value = false;
3433 break;
3434 case eStateRunning:
3435 case eStateStepping:
3436 // If we've started the target running, we handle the cases where we are
3437 // already running and where there is a transition from stopped to running
3438 // differently. running -> running: Automatically suppress extra running
3439 // events stopped -> running: Report except when there is one or more no
3440 // votes
3441 // and no yes votes.
3444 return_value = true;
3445 else {
3446 switch (m_last_broadcast_state) {
3447 case eStateRunning:
3448 case eStateStepping:
3449 // We always suppress multiple runnings with no PUBLIC stop in between.
3450 return_value = false;
3451 break;
3452 default:
3453 // TODO: make this work correctly. For now always report
3454 // run if we aren't running so we don't miss any running events. If I
3455 // run the lldb/test/thread/a.out file and break at main.cpp:58, run
3456 // and hit the breakpoints on multiple threads, then somehow during the
3457 // stepping over of all breakpoints no run gets reported.
3458
3459 // This is a transition from stop to run.
3460 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3461 case eVoteYes:
3462 case eVoteNoOpinion:
3463 return_value = true;
3464 break;
3465 case eVoteNo:
3466 return_value = false;
3467 break;
3468 }
3469 break;
3470 }
3471 }
3472 break;
3473 case eStateStopped:
3474 case eStateCrashed:
3475 case eStateSuspended:
3476 // We've stopped. First see if we're going to restart the target. If we
3477 // are going to stop, then we always broadcast the event. If we aren't
3478 // going to stop, let the thread plans decide if we're going to report this
3479 // event. If no thread has an opinion, we don't report it.
3480
3484 LLDB_LOGF(log,
3485 "Process::ShouldBroadcastEvent (%p) stopped due to an "
3486 "interrupt, state: %s",
3487 static_cast<void *>(event_ptr), StateAsCString(state));
3488 // Even though we know we are going to stop, we should let the threads
3489 // have a look at the stop, so they can properly set their state.
3490 m_thread_list.ShouldStop(event_ptr);
3491 return_value = true;
3492 } else {
3493 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3494 bool should_resume = false;
3495
3496 // It makes no sense to ask "ShouldStop" if we've already been
3497 // restarted... Asking the thread list is also not likely to go well,
3498 // since we are running again. So in that case just report the event.
3499
3500 if (!was_restarted)
3501 should_resume = !m_thread_list.ShouldStop(event_ptr);
3502
3503 if (was_restarted || should_resume || m_resume_requested) {
3504 Vote report_stop_vote = m_thread_list.ShouldReportStop(event_ptr);
3505 LLDB_LOGF(log,
3506 "Process::ShouldBroadcastEvent: should_resume: %i state: "
3507 "%s was_restarted: %i report_stop_vote: %d.",
3508 should_resume, StateAsCString(state), was_restarted,
3509 report_stop_vote);
3510
3511 switch (report_stop_vote) {
3512 case eVoteYes:
3513 return_value = true;
3514 break;
3515 case eVoteNoOpinion:
3516 case eVoteNo:
3517 return_value = false;
3518 break;
3519 }
3520
3521 if (!was_restarted) {
3522 LLDB_LOGF(log,
3523 "Process::ShouldBroadcastEvent (%p) Restarting process "
3524 "from state: %s",
3525 static_cast<void *>(event_ptr), StateAsCString(state));
3527 PrivateResume();
3528 }
3529 } else {
3530 return_value = true;
3532 }
3533 }
3534 break;
3535 }
3536
3537 // Forcing the next event delivery is a one shot deal. So reset it here.
3539
3540 // We do some coalescing of events (for instance two consecutive running
3541 // events get coalesced.) But we only coalesce against events we actually
3542 // broadcast. So we use m_last_broadcast_state to track that. NB - you
3543 // can't use "m_public_state.GetValue()" for that purpose, as was originally
3544 // done, because the PublicState reflects the last event pulled off the
3545 // queue, and there may be several events stacked up on the queue unserviced.
3546 // So the PublicState may not reflect the last broadcasted event yet.
3547 // m_last_broadcast_state gets updated here.
3548
3549 if (return_value)
3550 m_last_broadcast_state = state;
3551
3552 LLDB_LOGF(log,
3553 "Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3554 "broadcast state: %s - %s",
3555 static_cast<void *>(event_ptr), StateAsCString(state),
3557 return_value ? "YES" : "NO");
3558 return return_value;
3559}
3560
3561bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3562 Log *log = GetLog(LLDBLog::Events);
3563
3564 bool already_running = PrivateStateThreadIsValid();
3565 LLDB_LOGF(log, "Process::%s()%s ", __FUNCTION__,
3566 already_running ? " already running"
3567 : " starting private state thread");
3568
3569 if (!is_secondary_thread && already_running)
3570 return true;
3571
3572 // Create a thread that watches our internal state and controls which events
3573 // make it to clients (into the DCProcess event queue).
3574 char thread_name[1024];
3575 uint32_t max_len = llvm::get_max_thread_name_length();
3576 if (max_len > 0 && max_len <= 30) {
3577 // On platforms with abbreviated thread name lengths, choose thread names
3578 // that fit within the limit.
3579 if (already_running)
3580 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3581 else
3582 snprintf(thread_name, sizeof(thread_name), "intern-state");
3583 } else {
3584 if (already_running)
3585 snprintf(thread_name, sizeof(thread_name),
3586 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3587 GetID());
3588 else
3589 snprintf(thread_name, sizeof(thread_name),
3590 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3591 }
3592
3593 llvm::Expected<HostThread> private_state_thread =
3595 thread_name,
3596 [this, is_secondary_thread] {
3597 return RunPrivateStateThread(is_secondary_thread);
3598 },
3599 8 * 1024 * 1024);
3600 if (!private_state_thread) {
3601 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), private_state_thread.takeError(),
3602 "failed to launch host thread: {0}");
3603 return false;
3604 }
3605
3606 assert(private_state_thread->IsJoinable());
3607 m_private_state_thread = *private_state_thread;
3609 return true;
3610}
3611
3614}
3615
3618}
3619
3623 else {
3624 Log *log = GetLog(LLDBLog::Process);
3625 LLDB_LOGF(
3626 log,
3627 "Went to stop the private state thread, but it was already invalid.");
3628 }
3629}
3630
3632 Log *log = GetLog(LLDBLog::Process);
3633
3634 assert(signal == eBroadcastInternalStateControlStop ||
3637
3638 LLDB_LOGF(log, "Process::%s (signal = %d)", __FUNCTION__, signal);
3639
3640 // Signal the private state thread
3642 // Broadcast the event.
3643 // It is important to do this outside of the if below, because it's
3644 // possible that the thread state is invalid but that the thread is waiting
3645 // on a control event instead of simply being on its way out (this should
3646 // not happen, but it apparently can).
3647 LLDB_LOGF(log, "Sending control event of type: %d.", signal);
3648 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3650 event_receipt_sp);
3651
3652 // Wait for the event receipt or for the private state thread to exit
3653 bool receipt_received = false;
3655 while (!receipt_received) {
3656 // Check for a receipt for n seconds and then check if the private
3657 // state thread is still around.
3658 receipt_received =
3659 event_receipt_sp->WaitForEventReceived(GetUtilityExpressionTimeout());
3660 if (!receipt_received) {
3661 // Check if the private state thread is still around. If it isn't
3662 // then we are done waiting
3664 break; // Private state thread exited or is exiting, we are done
3665 }
3666 }
3667 }
3668
3669 if (signal == eBroadcastInternalStateControlStop) {
3670 thread_result_t result = {};
3673 }
3674 } else {
3675 LLDB_LOGF(
3676 log,
3677 "Private state thread already dead, no need to signal it to stop.");
3678 }
3679}
3680
3684 nullptr);
3685 else
3687}
3688
3690 Log *log = GetLog(LLDBLog::Process);
3691 m_resume_requested = false;
3692
3693 const StateType new_state =
3695
3696 // First check to see if anybody wants a shot at this event:
3699 m_next_event_action_up->PerformAction(event_sp);
3700 LLDB_LOGF(log, "Ran next event action, result was %d.", action_result);
3701
3702 switch (action_result) {
3704 SetNextEventAction(nullptr);
3705 break;
3706
3708 break;
3709
3711 // Handle Exiting Here. If we already got an exited event, we should
3712 // just propagate it. Otherwise, swallow this event, and set our state
3713 // to exit so the next event will kill us.
3714 if (new_state != eStateExited) {
3715 // FIXME: should cons up an exited event, and discard this one.
3716 SetExitStatus(0, m_next_event_action_up->GetExitString());
3717 SetNextEventAction(nullptr);
3718 return;
3719 }
3720 SetNextEventAction(nullptr);
3721 break;
3722 }
3723 }
3724
3725 // See if we should broadcast this state to external clients?
3726 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3727
3728 if (should_broadcast) {
3729 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3730 if (log) {
3731 LLDB_LOGF(log,
3732 "Process::%s (pid = %" PRIu64
3733 ") broadcasting new state %s (old state %s) to %s",
3734 __FUNCTION__, GetID(), StateAsCString(new_state),
3736 is_hijacked ? "hijacked" : "public");
3737 }
3739 if (StateIsRunningState(new_state)) {
3740 // Only push the input handler if we aren't fowarding events, as this
3741 // means the curses GUI is in use... Or don't push it if we are launching
3742 // since it will come up stopped.
3743 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3744 new_state != eStateLaunching && new_state != eStateAttaching) {
3748 LLDB_LOGF(log, "Process::%s updated m_iohandler_sync to %d",
3749 __FUNCTION__, m_iohandler_sync.GetValue());
3750 }
3751 } else if (StateIsStoppedState(new_state, false)) {
3753 // If the lldb_private::Debugger is handling the events, we don't want
3754 // to pop the process IOHandler here, we want to do it when we receive
3755 // the stopped event so we can carefully control when the process
3756 // IOHandler is popped because when we stop we want to display some
3757 // text stating how and why we stopped, then maybe some
3758 // process/thread/frame info, and then we want the "(lldb) " prompt to
3759 // show up. If we pop the process IOHandler here, then we will cause
3760 // the command interpreter to become the top IOHandler after the
3761 // process pops off and it will update its prompt right away... See the
3762 // Debugger.cpp file where it calls the function as
3763 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3764 // Otherwise we end up getting overlapping "(lldb) " prompts and
3765 // garbled output.
3766 //
3767 // If we aren't handling the events in the debugger (which is indicated
3768 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
3769 // we are hijacked, then we always pop the process IO handler manually.
3770 // Hijacking happens when the internal process state thread is running
3771 // thread plans, or when commands want to run in synchronous mode and
3772 // they call "process->WaitForProcessToStop()". An example of something
3773 // that will hijack the events is a simple expression:
3774 //
3775 // (lldb) expr (int)puts("hello")
3776 //
3777 // This will cause the internal process state thread to resume and halt
3778 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3779 // events) and we do need the IO handler to be pushed and popped
3780 // correctly.
3781
3782 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3784 }
3785 }
3786
3787 BroadcastEvent(event_sp);
3788 } else {
3789 if (log) {
3790 LLDB_LOGF(
3791 log,
3792 "Process::%s (pid = %" PRIu64
3793 ") suppressing state %s (old state %s): should_broadcast == false",
3794 __FUNCTION__, GetID(), StateAsCString(new_state),
3796 }
3797 }
3798}
3799
3801 EventSP event_sp;
3803 if (error.Fail())
3804 return error;
3805
3806 // Ask the process subclass to actually halt our process
3807 bool caused_stop;
3808 error = DoHalt(caused_stop);
3809
3810 DidHalt();
3811 return error;
3812}
3813
3815 bool control_only = true;
3816
3817 Log *log = GetLog(LLDBLog::Process);
3818 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3819 __FUNCTION__, static_cast<void *>(this), GetID());
3820
3821 bool exit_now = false;
3822 bool interrupt_requested = false;
3823 while (!exit_now) {
3824 EventSP event_sp;
3825 GetEventsPrivate(event_sp, std::nullopt, control_only);
3826 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
3827 LLDB_LOGF(log,
3828 "Process::%s (arg = %p, pid = %" PRIu64
3829 ") got a control event: %d",
3830 __FUNCTION__, static_cast<void *>(this), GetID(),
3831 event_sp->GetType());
3832
3833 switch (event_sp->GetType()) {
3835 exit_now = true;
3836 break; // doing any internal state management below
3837
3839 control_only = true;
3840 break;
3841
3843 control_only = false;
3844 break;
3845 }
3846
3847 continue;
3848 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
3850 LLDB_LOGF(log,
3851 "Process::%s (arg = %p, pid = %" PRIu64
3852 ") woke up with an interrupt while attaching - "
3853 "forwarding interrupt.",
3854 __FUNCTION__, static_cast<void *>(this), GetID());
3855 // The server may be spinning waiting for a process to appear, in which
3856 // case we should tell it to stop doing that. Normally, we don't NEED
3857 // to do that because we will next close the communication to the stub
3858 // and that will get it to shut down. But there are remote debugging
3859 // cases where relying on that side-effect causes the shutdown to be
3860 // flakey, so we should send a positive signal to interrupt the wait.
3864 LLDB_LOGF(log,
3865 "Process::%s (arg = %p, pid = %" PRIu64
3866 ") woke up with an interrupt - Halting.",
3867 __FUNCTION__, static_cast<void *>(this), GetID());
3869 if (error.Fail() && log)
3870 LLDB_LOGF(log,
3871 "Process::%s (arg = %p, pid = %" PRIu64
3872 ") failed to halt the process: %s",
3873 __FUNCTION__, static_cast<void *>(this), GetID(),
3874 error.AsCString());
3875 // Halt should generate a stopped event. Make a note of the fact that
3876 // we were doing the interrupt, so we can set the interrupted flag
3877 // after we receive the event. We deliberately set this to true even if
3878 // HaltPrivate failed, so that we can interrupt on the next natural
3879 // stop.
3880 interrupt_requested = true;
3881 } else {
3882 // This can happen when someone (e.g. Process::Halt) sees that we are
3883 // running and sends an interrupt request, but the process actually
3884 // stops before we receive it. In that case, we can just ignore the
3885 // request. We use m_last_broadcast_state, because the Stopped event
3886 // may not have been popped of the event queue yet, which is when the
3887 // public state gets updated.
3888 LLDB_LOGF(log,
3889 "Process::%s ignoring interrupt as we have already stopped.",
3890 __FUNCTION__);
3891 }
3892 continue;
3893 }
3894
3895 const StateType internal_state =
3897
3898 if (internal_state != eStateInvalid) {
3900 StateIsStoppedState(internal_state, true)) {
3903 }
3904
3905 if (interrupt_requested) {
3906 if (StateIsStoppedState(internal_state, true)) {
3907 // We requested the interrupt, so mark this as such in the stop event
3908 // so clients can tell an interrupted process from a natural stop
3909 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
3910 interrupt_requested = false;
3911 } else if (log) {
3912 LLDB_LOGF(log,
3913 "Process::%s interrupt_requested, but a non-stopped "
3914 "state '%s' received.",
3915 __FUNCTION__, StateAsCString(internal_state));
3916 }
3917 }
3918
3919 HandlePrivateEvent(event_sp);
3920 }
3921
3922 if (internal_state == eStateInvalid || internal_state == eStateExited ||
3923 internal_state == eStateDetached) {
3924 LLDB_LOGF(log,
3925 "Process::%s (arg = %p, pid = %" PRIu64
3926 ") about to exit with internal state %s...",
3927 __FUNCTION__, static_cast<void *>(this), GetID(),
3928 StateAsCString(internal_state));
3929
3930 break;
3931 }
3932 }
3933
3934 // Verify log is still enabled before attempting to write to it...
3935 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
3936 __FUNCTION__, static_cast<void *>(this), GetID());
3937
3938 // If we are a secondary thread, then the primary thread we are working for
3939 // will have already acquired the public_run_lock, and isn't done with what
3940 // it was doing yet, so don't try to change it on the way out.
3941 if (!is_secondary_thread)
3943 return {};
3944}
3945
3946// Process Event Data
3947
3949
3951 StateType state)
3952 : EventData(), m_process_wp(), m_state(state) {
3953 if (process_sp)
3954 m_process_wp = process_sp;
3955}
3956
3958
3960 return "Process::ProcessEventData";
3961}
3962
3965}
3966
3968 bool &found_valid_stopinfo) {
3969 found_valid_stopinfo = false;
3970
3971 ProcessSP process_sp(m_process_wp.lock());
3972 if (!process_sp)
3973 return false;
3974
3975 ThreadList &curr_thread_list = process_sp->GetThreadList();
3976 uint32_t num_threads = curr_thread_list.GetSize();
3977 uint32_t idx;
3978
3979 // The actions might change one of the thread's stop_info's opinions about
3980 // whether we should stop the process, so we need to query that as we go.
3981
3982 // One other complication here, is that we try to catch any case where the
3983 // target has run (except for expressions) and immediately exit, but if we
3984 // get that wrong (which is possible) then the thread list might have
3985 // changed, and that would cause our iteration here to crash. We could
3986 // make a copy of the thread list, but we'd really like to also know if it
3987 // has changed at all, so we make up a vector of the thread ID's and check
3988 // what we get back against this list & bag out if anything differs.
3989 ThreadList not_suspended_thread_list(process_sp.get());
3990 std::vector<uint32_t> thread_index_array(num_threads);
3991 uint32_t not_suspended_idx = 0;
3992 for (idx = 0; idx < num_threads; ++idx) {
3993 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3994
3995 /*
3996 Filter out all suspended threads, they could not be the reason
3997 of stop and no need to perform any actions on them.
3998 */
3999 if (thread_sp->GetResumeState() != eStateSuspended) {
4000 not_suspended_thread_list.AddThread(thread_sp);
4001 thread_index_array[not_suspended_idx] = thread_sp->GetIndexID();
4002 not_suspended_idx++;
4003 }
4004 }
4005
4006 // Use this to track whether we should continue from here. We will only
4007 // continue the target running if no thread says we should stop. Of course
4008 // if some thread's PerformAction actually sets the target running, then it
4009 // doesn't matter what the other threads say...
4010
4011 bool still_should_stop = false;
4012
4013 // Sometimes - for instance if we have a bug in the stub we are talking to,
4014 // we stop but no thread has a valid stop reason. In that case we should
4015 // just stop, because we have no way of telling what the right thing to do
4016 // is, and it's better to let the user decide than continue behind their
4017 // backs.
4018
4019 for (idx = 0; idx < not_suspended_thread_list.GetSize(); ++idx) {
4020 curr_thread_list = process_sp->GetThreadList();
4021 if (curr_thread_list.GetSize() != num_threads) {
4023 LLDB_LOGF(
4024 log,
4025 "Number of threads changed from %u to %u while processing event.",
4026 num_threads, curr_thread_list.GetSize());
4027 break;
4028 }
4029
4030 lldb::ThreadSP thread_sp = not_suspended_thread_list.GetThreadAtIndex(idx);
4031
4032 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4034 LLDB_LOGF(log,
4035 "The thread at position %u changed from %u to %u while "
4036 "processing event.",
4037 idx, thread_index_array[idx], thread_sp->GetIndexID());
4038 break;
4039 }
4040
4041 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4042 if (stop_info_sp && stop_info_sp->IsValid()) {
4043 found_valid_stopinfo = true;
4044 bool this_thread_wants_to_stop;
4045 if (stop_info_sp->GetOverrideShouldStop()) {
4046 this_thread_wants_to_stop =
4047 stop_info_sp->GetOverriddenShouldStopValue();
4048 } else {
4049 stop_info_sp->PerformAction(event_ptr);
4050 // The stop action might restart the target. If it does, then we
4051 // want to mark that in the event so that whoever is receiving it
4052 // will know to wait for the running event and reflect that state
4053 // appropriately. We also need to stop processing actions, since they
4054 // aren't expecting the target to be running.
4055
4056 // FIXME: we might have run.
4057 if (stop_info_sp->HasTargetRunSinceMe()) {
4058 SetRestarted(true);
4059 break;
4060 }
4061
4062 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
4063 }
4064
4065 if (!still_should_stop)
4066 still_should_stop = this_thread_wants_to_stop;
4067 }
4068 }
4069
4070 return still_should_stop;
4071}
4072
4074 ProcessSP process_sp(m_process_wp.lock());
4075
4076 if (!process_sp)
4077 return;
4078
4079 // This function gets called twice for each event, once when the event gets
4080 // pulled off of the private process event queue, and then any number of
4081 // times, first when it gets pulled off of the public event queue, then other
4082 // times when we're pretending that this is where we stopped at the end of
4083 // expression evaluation. m_update_state is used to distinguish these three
4084 // cases; it is 0 when we're just pulling it off for private handling, and >
4085 // 1 for expression evaluation, and we don't want to do the breakpoint
4086 // command handling then.
4087 if (m_update_state != 1)
4088 return;
4089
4090 process_sp->SetPublicState(
4092
4093 if (m_state == eStateStopped && !m_restarted) {
4094 // Let process subclasses know we are about to do a public stop and do
4095 // anything they might need to in order to speed up register and memory
4096 // accesses.
4097 process_sp->WillPublicStop();
4098 }
4099
4100 // If this is a halt event, even if the halt stopped with some reason other
4101 // than a plain interrupt (e.g. we had already stopped for a breakpoint when
4102 // the halt request came through) don't do the StopInfo actions, as they may
4103 // end up restarting the process.
4104 if (m_interrupted)
4105 return;
4106
4107 // If we're not stopped or have restarted, then skip the StopInfo actions:
4108 if (m_state != eStateStopped || m_restarted) {
4109 return;
4110 }
4111
4112 bool does_anybody_have_an_opinion = false;
4113 bool still_should_stop = ShouldStop(event_ptr, does_anybody_have_an_opinion);
4114
4115 if (GetRestarted()) {
4116 return;
4117 }
4118
4119 if (!still_should_stop && does_anybody_have_an_opinion) {
4120 // We've been asked to continue, so do that here.
4121 SetRestarted(true);
4122 // Use the private resume method here, since we aren't changing the run
4123 // lock state.
4124 process_sp->PrivateResume();
4125 } else {
4126 bool hijacked = process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) &&
4127 !process_sp->StateChangedIsHijackedForSynchronousResume();
4128
4129 if (!hijacked) {
4130 // If we didn't restart, run the Stop Hooks here.
4131 // Don't do that if state changed events aren't hooked up to the
4132 // public (or SyncResume) broadcasters. StopHooks are just for
4133 // real public stops. They might also restart the target,
4134 // so watch for that.
4135 if (process_sp->GetTarget().RunStopHooks())
4136 SetRestarted(true);
4137 }
4138 }
4139}
4140
4142 ProcessSP process_sp(m_process_wp.lock());
4143
4144 if (process_sp)
4145 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4146 static_cast<void *>(process_sp.get()), process_sp->GetID());
4147 else
4148 s->PutCString(" process = NULL, ");
4149
4150 s->Printf("state = %s", StateAsCString(GetState()));
4151}
4152
4155 if (event_ptr) {
4156 const EventData *event_data = event_ptr->GetData();
4157 if (event_data &&
4159 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4160 }
4161 return nullptr;
4162}
4163
4166 ProcessSP process_sp;
4167 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4168 if (data)
4169 process_sp = data->GetProcessSP();
4170 return process_sp;
4171}
4172
4174 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4175 if (data == nullptr)
4176 return eStateInvalid;
4177 else
4178 return data->GetState();
4179}
4180
4182 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4183 if (data == nullptr)
4184 return false;
4185 else
4186 return data->GetRestarted();
4187}
4188
4190 bool new_value) {
4191 ProcessEventData *data =
4192 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4193 if (data != nullptr)
4194 data->SetRestarted(new_value);
4195}
4196
4197size_t
4199 ProcessEventData *data =
4200 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4201 if (data != nullptr)
4202 return data->GetNumRestartedReasons();
4203 else
4204 return 0;
4205}
4206
4207const char *
4209 size_t idx) {
4210 ProcessEventData *data =
4211 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4212 if (data != nullptr)
4213 return data->GetRestartedReasonAtIndex(idx);
4214 else
4215 return nullptr;
4216}
4217
4219 const char *reason) {
4220 ProcessEventData *data =
4221 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4222 if (data != nullptr)
4223 data->AddRestartedReason(reason);
4224}
4225
4227 const Event *event_ptr) {
4228 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4229 if (data == nullptr)
4230 return false;
4231 else
4232 return data->GetInterrupted();
4233}
4234
4236 bool new_value) {
4237 ProcessEventData *data =
4238 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4239 if (data != nullptr)
4240 data->SetInterrupted(new_value);
4241}
4242
4244 ProcessEventData *data =
4245 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4246 if (data) {
4248 return true;
4249 }
4250 return false;
4251}
4252
4254
4256 exe_ctx.SetTargetPtr(&GetTarget());
4257 exe_ctx.SetProcessPtr(this);
4258 exe_ctx.SetThreadPtr(nullptr);
4259 exe_ctx.SetFramePtr(nullptr);
4260}
4261
4262// uint32_t
4263// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4264// std::vector<lldb::pid_t> &pids)
4265//{
4266// return 0;
4267//}
4268//
4269// ArchSpec
4270// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4271//{
4272// return Host::GetArchSpecForExistingProcess (pid);
4273//}
4274//
4275// ArchSpec
4276// Process::GetArchSpecForExistingProcess (const char *process_name)
4277//{
4278// return Host::GetArchSpecForExistingProcess (process_name);
4279//}
4280
4282 auto event_data_sp =
4283 std::make_shared<ProcessEventData>(shared_from_this(), GetState());
4284 return std::make_shared<Event>(event_type, event_data_sp);
4285}
4286
4287void Process::AppendSTDOUT(const char *s, size_t len) {
4288 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4289 m_stdout_data.append(s, len);
4291 BroadcastEventIfUnique(event_sp);
4292}
4293
4294void Process::AppendSTDERR(const char *s, size_t len) {
4295 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4296 m_stderr_data.append(s, len);
4298 BroadcastEventIfUnique(event_sp);
4299}
4300
4301void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4302 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4303 m_profile_data.push_back(one_profile_data);
4305 BroadcastEventIfUnique(event_sp);
4306}
4307
4309 const StructuredDataPluginSP &plugin_sp) {
4310 auto data_sp = std::make_shared<EventDataStructuredData>(
4311 shared_from_this(), object_sp, plugin_sp);
4313}
4314
4316Process::GetStructuredDataPlugin(llvm::StringRef type_name) const {
4317 auto find_it = m_structured_data_plugin_map.find(type_name);
4318 if (find_it != m_structured_data_plugin_map.end())
4319 return find_it->second;
4320 else
4321 return StructuredDataPluginSP();
4322}
4323
4324size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
4325 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4326 if (m_profile_data.empty())
4327 return 0;
4328
4329 std::string &one_profile_data = m_profile_data.front();
4330 size_t bytes_available = one_profile_data.size();
4331 if (bytes_available > 0) {
4332 Log *log = GetLog(LLDBLog::Process);
4333 LLDB_LOGF(log, "Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4334 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4335 if (bytes_available > buf_size) {
4336 memcpy(buf, one_profile_data.c_str(), buf_size);
4337 one_profile_data.erase(0, buf_size);
4338 bytes_available = buf_size;
4339 } else {
4340 memcpy(buf, one_profile_data.c_str(), bytes_available);
4341 m_profile_data.erase(m_profile_data.begin());
4342 }
4343 }
4344 return bytes_available;
4345}
4346
4347// Process STDIO
4348
4349size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
4350 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4351 size_t bytes_available = m_stdout_data.size();
4352 if (bytes_available > 0) {
4353 Log *log = GetLog(LLDBLog::Process);
4354 LLDB_LOGF(log, "Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4355 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4356 if (bytes_available > buf_size) {
4357 memcpy(buf, m_stdout_data.c_str(), buf_size);
4358 m_stdout_data.erase(0, buf_size);
4359 bytes_available = buf_size;
4360 } else {
4361 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4362 m_stdout_data.clear();
4363 }
4364 }
4365 return bytes_available;
4366}
4367
4368size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
4369 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4370 size_t bytes_available = m_stderr_data.size();
4371 if (bytes_available > 0) {
4372 Log *log = GetLog(LLDBLog::Process);
4373 LLDB_LOGF(log, "Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4374 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4375 if (bytes_available > buf_size) {
4376 memcpy(buf, m_stderr_data.c_str(), buf_size);
4377 m_stderr_data.erase(0, buf_size);
4378 bytes_available = buf_size;
4379 } else {
4380 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4381 m_stderr_data.clear();
4382 }
4383 }
4384 return bytes_available;
4385}
4386
4387void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4388 size_t src_len) {
4389 Process *process = (Process *)baton;
4390 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
4391}
4392
4394public:
4395 IOHandlerProcessSTDIO(Process *process, int write_fd)
4396 : IOHandler(process->GetTarget().GetDebugger(),
4397 IOHandler::Type::ProcessIO),
4398 m_process(process),
4399 m_read_file(GetInputFD(), File::eOpenOptionReadOnly, false),
4400 m_write_file(write_fd, File::eOpenOptionWriteOnly, false) {
4401 m_pipe.CreateNew(false);
4402 }
4403
4404 ~IOHandlerProcessSTDIO() override = default;
4405
4406 void SetIsRunning(bool running) {
4407 std::lock_guard<std::mutex> guard(m_mutex);
4408 SetIsDone(!running);
4409 m_is_running = running;
4410 }
4411
4412 // Each IOHandler gets to run until it is done. It should read data from the
4413 // "in" and place output into "out" and "err and return when done.
4414 void Run() override {
4415 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4416 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4417 SetIsDone(true);
4418 return;
4419 }
4420
4421 SetIsDone(false);
4422 const int read_fd = m_read_file.GetDescriptor();
4423 Terminal terminal(read_fd);
4424 TerminalState terminal_state(terminal, false);
4425 // FIXME: error handling?
4426 llvm::consumeError(terminal.SetCanonical(false));
4427 llvm::consumeError(terminal.SetEcho(false));
4428// FD_ZERO, FD_SET are not supported on windows
4429#ifndef _WIN32
4430 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4431 SetIsRunning(true);
4432 while (true) {
4433 {
4434 std::lock_guard<std::mutex> guard(m_mutex);
4435 if (GetIsDone())
4436 break;
4437 }
4438
4439 SelectHelper select_helper;
4440 select_helper.FDSetRead(read_fd);
4441 select_helper.FDSetRead(pipe_read_fd);
4442 Status error = select_helper.Select();
4443
4444 if (error.Fail())
4445 break;
4446
4447 char ch = 0;
4448 size_t n;
4449 if (select_helper.FDIsSetRead(read_fd)) {
4450 n = 1;
4451 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4452 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4453 break;
4454 } else
4455 break;
4456 }
4457
4458 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4459 size_t bytes_read;
4460 // Consume the interrupt byte
4461 Status error = m_pipe.Read(&ch, 1, bytes_read);
4462 if (error.Success()) {
4463 if (ch == 'q')
4464 break;
4465 if (ch == 'i')
4466 if (StateIsRunningState(m_process->GetState()))
4467 m_process->SendAsyncInterrupt();
4468 }
4469 }
4470 }
4471 SetIsRunning(false);
4472#endif
4473 }
4474
4475 void Cancel() override {
4476 std::lock_guard<std::mutex> guard(m_mutex);
4477 SetIsDone(true);
4478 // Only write to our pipe to cancel if we are in
4479 // IOHandlerProcessSTDIO::Run(). We can end up with a python command that
4480 // is being run from the command interpreter:
4481 //
4482 // (lldb) step_process_thousands_of_times
4483 //
4484 // In this case the command interpreter will be in the middle of handling
4485 // the command and if the process pushes and pops the IOHandler thousands
4486 // of times, we can end up writing to m_pipe without ever consuming the
4487 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4488 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4489 if (m_is_running) {
4490 char ch = 'q'; // Send 'q' for quit
4491 size_t bytes_written = 0;
4492 m_pipe.Write(&ch, 1, bytes_written);
4493 }
4494 }
4495
4496 bool Interrupt() override {
4497 // Do only things that are safe to do in an interrupt context (like in a
4498 // SIGINT handler), like write 1 byte to a file descriptor. This will
4499 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4500 // that was written to the pipe and then call
4501 // m_process->SendAsyncInterrupt() from a much safer location in code.
4502 if (m_active) {
4503 char ch = 'i'; // Send 'i' for interrupt
4504 size_t bytes_written = 0;
4505 Status result = m_pipe.Write(&ch, 1, bytes_written);
4506 return result.Success();
4507 } else {
4508 // This IOHandler might be pushed on the stack, but not being run
4509 // currently so do the right thing if we aren't actively watching for
4510 // STDIN by sending the interrupt to the process. Otherwise the write to
4511 // the pipe above would do nothing. This can happen when the command
4512 // interpreter is running and gets a "expression ...". It will be on the
4513 // IOHandler thread and sending the input is complete to the delegate
4514 // which will cause the expression to run, which will push the process IO
4515 // handler, but not run it.
4516
4517 if (StateIsRunningState(m_process->GetState())) {
4518 m_process->SendAsyncInterrupt();
4519 return true;
4520 }
4521 }
4522 return false;
4523 }
4524
4525 void GotEOF() override {}
4526
4527protected:
4529 NativeFile m_read_file; // Read from this file (usually actual STDIN for LLDB
4530 NativeFile m_write_file; // Write to this file (usually the primary pty for
4531 // getting io to debuggee)
4533 std::mutex m_mutex;
4534 bool m_is_running = false;
4535};
4536
4538 // First set up the Read Thread for reading/handling process I/O
4540 std::make_unique<ConnectionFileDescriptor>(fd, true));
4545
4546 // Now read thread is set up, set up input reader.
4547 {
4548 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
4551 std::make_shared<IOHandlerProcessSTDIO>(this, fd);
4552 }
4553 }
4554}
4555
4557 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
4558 IOHandlerSP io_handler_sp(m_process_input_reader);
4559 if (io_handler_sp)
4560 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4561 return false;
4562}
4563
4565 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
4566 IOHandlerSP io_handler_sp(m_process_input_reader);
4567 if (io_handler_sp) {
4568 Log *log = GetLog(LLDBLog::Process);
4569 LLDB_LOGF(log, "Process::%s pushing IO handler", __FUNCTION__);
4570
4571 io_handler_sp->SetIsDone(false);
4572 // If we evaluate an utility function, then we don't cancel the current
4573 // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
4574 // existing IOHandler that potentially provides the user interface (e.g.
4575 // the IOHandler for Editline).
4576 bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();
4577 GetTarget().GetDebugger().RunIOHandlerAsync(io_handler_sp,
4578 cancel_top_handler);
4579 return true;
4580 }
4581 return false;
4582}
4583
4585 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
4586 IOHandlerSP io_handler_sp(m_process_input_reader);
4587 if (io_handler_sp)
4588 return GetTarget().GetDebugger().RemoveIOHandler(io_handler_sp);
4589 return false;
4590}
4591
4592// The process needs to know about installed plug-ins
4594
4596
4597namespace {
4598// RestorePlanState is used to record the "is private", "is controlling" and
4599// "okay
4600// to discard" fields of the plan we are running, and reset it on Clean or on
4601// destruction. It will only reset the state once, so you can call Clean and
4602// then monkey with the state and it won't get reset on you again.
4603
4604class RestorePlanState {
4605public:
4606 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4607 : m_thread_plan_sp(thread_plan_sp) {
4608 if (m_thread_plan_sp) {
4609 m_private = m_thread_plan_sp->GetPrivate();
4610 m_is_controlling = m_thread_plan_sp->IsControllingPlan();
4611 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4612 }
4613 }
4614
4615 ~RestorePlanState() { Clean(); }
4616
4617 void Clean() {
4618 if (!m_already_reset && m_thread_plan_sp) {
4619 m_already_reset = true;
4620 m_thread_plan_sp->SetPrivate(m_private);
4621 m_thread_plan_sp->SetIsControllingPlan(m_is_controlling);
4622 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4623 }
4624 }
4625
4626private:
4627 lldb::ThreadPlanSP m_thread_plan_sp;
4628 bool m_already_reset = false;
4629 bool m_private = false;
4630 bool m_is_controlling = false;
4631 bool m_okay_to_discard = false;
4632};
4633} // anonymous namespace
4634
4635static microseconds
4637 const milliseconds default_one_thread_timeout(250);
4638
4639 // If the overall wait is forever, then we don't need to worry about it.
4640 if (!options.GetTimeout()) {
4641 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4642 : default_one_thread_timeout;
4643 }
4644
4645 // If the one thread timeout is set, use it.
4646 if (options.GetOneThreadTimeout())
4647 return *options.GetOneThreadTimeout();
4648
4649 // Otherwise use half the total timeout, bounded by the
4650 // default_one_thread_timeout.
4651 return std::min<microseconds>(default_one_thread_timeout,
4652 *options.GetTimeout() / 2);
4653}
4654
4657 bool before_first_timeout) {
4658 // If we are going to run all threads the whole time, or if we are only going
4659 // to run one thread, we can just return the overall timeout.
4660 if (!options.GetStopOthers() || !options.GetTryAllThreads())
4661 return options.GetTimeout();
4662
4663 if (before_first_timeout)
4664 return GetOneThreadExpressionTimeout(options);
4665
4666 if (!options.GetTimeout())
4667 return std::nullopt;
4668 else
4669 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
4670}
4671
4672static std::optional<ExpressionResults>
4673HandleStoppedEvent(lldb::tid_t thread_id, const ThreadPlanSP &thread_plan_sp,
4674 RestorePlanState &restorer, const EventSP &event_sp,
4675 EventSP &event_to_broadcast_sp,
4676 const EvaluateExpressionOptions &options,
4677 bool handle_interrupts) {
4679
4680 ThreadSP thread_sp = thread_plan_sp->GetTarget()
4681 .GetProcessSP()
4682 ->GetThreadList()
4683 .FindThreadByID(thread_id);
4684 if (!thread_sp) {
4685 LLDB_LOG(log,
4686 "The thread on which we were running the "
4687 "expression: tid = {0}, exited while "
4688 "the expression was running.",
4689 thread_id);
4691 }
4692
4693 ThreadPlanSP plan = thread_sp->GetCompletedPlan();
4694 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
4695 LLDB_LOG(log, "execution completed successfully");
4696
4697 // Restore the plan state so it will get reported as intended when we are
4698 // done.
4699 restorer.Clean();
4700 return eExpressionCompleted;
4701 }
4702
4703 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4704 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
4705 stop_info_sp->ShouldNotify(event_sp.get())) {
4706 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
4707 if (!options.DoesIgnoreBreakpoints()) {
4708 // Restore the plan state and then force Private to false. We are going
4709 // to stop because of this plan so we need it to become a public plan or
4710 // it won't report correctly when we continue to its termination later
4711 // on.
4712 restorer.Clean();
4713 thread_plan_sp->SetPrivate(false);
4714 event_to_broadcast_sp = event_sp;
4715 }
4717 }
4718
4719 if (!handle_interrupts &&
4721 return std::nullopt;
4722
4723 LLDB_LOG(log, "thread plan did not successfully complete");
4724 if (!options.DoesUnwindOnError())
4725 event_to_broadcast_sp = event_sp;
4727}
4728
4731 lldb::ThreadPlanSP &thread_plan_sp,
4732 const EvaluateExpressionOptions &options,
4733 DiagnosticManager &diagnostic_manager) {
4735
4736 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4737
4738 if (!thread_plan_sp) {
4739 diagnostic_manager.PutString(
4741 "RunThreadPlan called with empty thread plan.");
4742 return eExpressionSetupError;
4743 }
4744
4745 if (!thread_plan_sp->ValidatePlan(nullptr)) {
4746 diagnostic_manager.PutString(
4748 "RunThreadPlan called with an invalid thread plan.");
4749 return eExpressionSetupError;
4750 }
4751
4752 if (exe_ctx.GetProcessPtr() != this) {
4753 diagnostic_manager.PutString(eDiagnosticSeverityError,
4754 "RunThreadPlan called on wrong process.");
4755 return eExpressionSetupError;
4756 }
4757
4758 Thread *thread = exe_ctx.GetThreadPtr();
4759 if (thread == nullptr) {
4760 diagnostic_manager.PutString(eDiagnosticSeverityError,
4761 "RunThreadPlan called with invalid thread.");
4762 return eExpressionSetupError;
4763 }
4764
4765 // Record the thread's id so we can tell when a thread we were using
4766 // to run the expression exits during the expression evaluation.
4767 lldb::tid_t expr_thread_id = thread->GetID();
4768
4769 // We need to change some of the thread plan attributes for the thread plan
4770 // runner. This will restore them when we are done:
4771
4772 RestorePlanState thread_plan_restorer(thread_plan_sp);
4773
4774 // We rely on the thread plan we are running returning "PlanCompleted" if
4775 // when it successfully completes. For that to be true the plan can't be
4776 // private - since private plans suppress themselves in the GetCompletedPlan
4777 // call.
4778
4779 thread_plan_sp->SetPrivate(false);
4780
4781 // The plans run with RunThreadPlan also need to be terminal controlling plans
4782 // or when they are done we will end up asking the plan above us whether we
4783 // should stop, which may give the wrong answer.
4784
4785 thread_plan_sp->SetIsControllingPlan(true);
4786 thread_plan_sp->SetOkayToDiscard(false);
4787
4788 // If we are running some utility expression for LLDB, we now have to mark
4789 // this in the ProcesModID of this process. This RAII takes care of marking
4790 // and reverting the mark it once we are done running the expression.
4791 UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);
4792
4794 diagnostic_manager.PutString(
4796 "RunThreadPlan called while the private state was not stopped.");
4797 return eExpressionSetupError;
4798 }
4799
4800 // Save the thread & frame from the exe_ctx for restoration after we run
4801 const uint32_t thread_idx_id = thread->GetIndexID();
4802 StackFrameSP selected_frame_sp =
4804 if (!selected_frame_sp) {
4805 thread->SetSelectedFrame(nullptr);
4806 selected_frame_sp = thread->GetSelectedFrame(DoNoSelectMostRelevantFrame);
4807 if (!selected_frame_sp) {
4808 diagnostic_manager.Printf(
4810 "RunThreadPlan called without a selected frame on thread %d",
4811 thread_idx_id);
4812 return eExpressionSetupError;
4813 }
4814 }
4815
4816 // Make sure the timeout values make sense. The one thread timeout needs to
4817 // be smaller than the overall timeout.
4818 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4819 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
4820 diagnostic_manager.PutString(eDiagnosticSeverityError,
4821 "RunThreadPlan called with one thread "
4822 "timeout greater than total timeout");
4823 return eExpressionSetupError;
4824 }
4825
4826 StackID ctx_frame_id = selected_frame_sp->GetStackID();
4827
4828 // N.B. Running the target may unset the currently selected thread and frame.
4829 // We don't want to do that either, so we should arrange to reset them as
4830 // well.
4831
4832 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
4833
4834 uint32_t selected_tid;
4835 StackID selected_stack_id;
4836 if (selected_thread_sp) {
4837 selected_tid = selected_thread_sp->GetIndexID();
4838 selected_stack_id =
4839 selected_thread_sp->GetSelectedFrame(DoNoSelectMostRelevantFrame)
4840 ->GetStackID();
4841 } else {
4842 selected_tid = LLDB_INVALID_THREAD_ID;
4843 }
4844
4845 HostThread backup_private_state_thread;
4846 lldb::StateType old_state = eStateInvalid;
4847 lldb::ThreadPlanSP stopper_base_plan_sp;
4848
4851 // Yikes, we are running on the private state thread! So we can't wait for
4852 // public events on this thread, since we are the thread that is generating
4853 // public events. The simplest thing to do is to spin up a temporary thread
4854 // to handle private state thread events while we are fielding public
4855 // events here.
4856 LLDB_LOGF(log, "Running thread plan on private state thread, spinning up "
4857 "another state thread to handle the events.");
4858
4859 backup_private_state_thread = m_private_state_thread;
4860
4861 // One other bit of business: we want to run just this thread plan and
4862 // anything it pushes, and then stop, returning control here. But in the
4863 // normal course of things, the plan above us on the stack would be given a
4864 // shot at the stop event before deciding to stop, and we don't want that.
4865 // So we insert a "stopper" base plan on the stack before the plan we want
4866 // to run. Since base plans always stop and return control to the user,
4867 // that will do just what we want.
4868 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4869 thread->QueueThreadPlan(stopper_base_plan_sp, false);
4870 // Have to make sure our public state is stopped, since otherwise the
4871 // reporting logic below doesn't work correctly.
4872 old_state = m_public_state.GetValue();
4874
4875 // Now spin up the private state thread:
4877 }
4878
4879 thread->QueueThreadPlan(
4880 thread_plan_sp, false); // This used to pass "true" does that make sense?
4881
4882 if (options.GetDebug()) {
4883 // In this case, we aren't actually going to run, we just want to stop
4884 // right away. Flush this thread so we will refetch the stacks and show the
4885 // correct backtrace.
4886 // FIXME: To make this prettier we should invent some stop reason for this,
4887 // but that
4888 // is only cosmetic, and this functionality is only of use to lldb
4889 // developers who can live with not pretty...
4890 thread->Flush();
4892 }
4893
4894 ListenerSP listener_sp(
4895 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4896
4897 lldb::EventSP event_to_broadcast_sp;
4898
4899 {
4900 // This process event hijacker Hijacks the Public events and its destructor
4901 // makes sure that the process events get restored on exit to the function.
4902 //
4903 // If the event needs to propagate beyond the hijacker (e.g., the process
4904 // exits during execution), then the event is put into
4905 // event_to_broadcast_sp for rebroadcasting.
4906
4907 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
4908
4909 if (log) {
4910 StreamString s;
4911 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4912 LLDB_LOGF(log,
4913 "Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
4914 " to run thread plan \"%s\".",
4915 thread_idx_id, expr_thread_id, s.GetData());
4916 }
4917
4918 bool got_event;
4919 lldb::EventSP event_sp;
4921
4922 bool before_first_timeout = true; // This is set to false the first time
4923 // that we have to halt the target.
4924 bool do_resume = true;
4925 bool handle_running_event = true;
4926
4927 // This is just for accounting:
4928 uint32_t num_resumes = 0;
4929
4930 // If we are going to run all threads the whole time, or if we are only
4931 // going to run one thread, then we don't need the first timeout. So we
4932 // pretend we are after the first timeout already.
4933 if (!options.GetStopOthers() || !options.GetTryAllThreads())
4934 before_first_timeout = false;
4935
4936 LLDB_LOGF(log, "Stop others: %u, try all: %u, before_first: %u.\n",
4937 options.GetStopOthers(), options.GetTryAllThreads(),
4938 before_first_timeout);
4939
4940 // This isn't going to work if there are unfetched events on the queue. Are
4941 // there cases where we might want to run the remaining events here, and
4942 // then try to call the function? That's probably being too tricky for our
4943 // own good.
4944
4945 Event *other_events = listener_sp->PeekAtNextEvent();
4946 if (other_events != nullptr) {
4947 diagnostic_manager.PutString(
4949 "RunThreadPlan called with pending events on the queue.");
4950 return eExpressionSetupError;
4951 }
4952
4953 // We also need to make sure that the next event is delivered. We might be
4954 // calling a function as part of a thread plan, in which case the last
4955 // delivered event could be the running event, and we don't want event
4956 // coalescing to cause us to lose OUR running event...
4958
4959// This while loop must exit out the bottom, there's cleanup that we need to do
4960// when we are done. So don't call return anywhere within it.
4961
4962#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
4963 // It's pretty much impossible to write test cases for things like: One
4964 // thread timeout expires, I go to halt, but the process already stopped on
4965 // the function call stop breakpoint. Turning on this define will make us
4966 // not fetch the first event till after the halt. So if you run a quick
4967 // function, it will have completed, and the completion event will be
4968 // waiting, when you interrupt for halt. The expression evaluation should
4969 // still succeed.
4970 bool miss_first_event = true;
4971#endif
4972 while (true) {
4973 // We usually want to resume the process if we get to the top of the
4974 // loop. The only exception is if we get two running events with no
4975 // intervening stop, which can happen, we will just wait for then next
4976 // stop event.
4977 LLDB_LOGF(log,
4978 "Top of while loop: do_resume: %i handle_running_event: %i "
4979 "before_first_timeout: %i.",
4980 do_resume, handle_running_event, before_first_timeout);
4981
4982 if (do_resume || handle_running_event) {
4983 // Do the initial resume and wait for the running event before going
4984 // further.
4985
4986 if (do_resume) {
4987 num_resumes++;
4988 Status resume_error = PrivateResume();
4989 if (!resume_error.Success()) {
4990 diagnostic_manager.Printf(
4992 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
4993 resume_error.AsCString());
4994 return_value = eExpressionSetupError;
4995 break;
4996 }
4997 }
4998
4999 got_event =
5000 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
5001 if (!got_event) {
5002 LLDB_LOGF(log,
5003 "Process::RunThreadPlan(): didn't get any event after "
5004 "resume %" PRIu32 ", exiting.",
5005 num_resumes);
5006
5007 diagnostic_manager.Printf(eDiagnosticSeverityError,
5008 "didn't get any event after resume %" PRIu32
5009 ", exiting.",
5010 num_resumes);
5011 return_value = eExpressionSetupError;
5012 break;
5013 }
5014
5015 stop_state =
5017
5018 if (stop_state != eStateRunning) {
5019 bool restarted = false;
5020
5021 if (stop_state == eStateStopped) {
5023 event_sp.get());
5024 LLDB_LOGF(
5025 log,
5026 "Process::RunThreadPlan(): didn't get running event after "
5027 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
5028 "handle_running_event: %i).",
5029 num_resumes, StateAsCString(stop_state), restarted, do_resume,
5030 handle_running_event);
5031 }
5032
5033 if (restarted) {
5034 // This is probably an overabundance of caution, I don't think I
5035 // should ever get a stopped & restarted event here. But if I do,
5036 // the best thing is to Halt and then get out of here.
5037 const bool clear_thread_plans = false;
5038 const bool use_run_lock = false;
5039 Halt(clear_thread_plans, use_run_lock);
5040 }
5041
5042 diagnostic_manager.Printf(
5044 "didn't get running event after initial resume, got %s instead.",
5045 StateAsCString(stop_state));
5046 return_value = eExpressionSetupError;
5047 break;
5048 }
5049
5050 if (log)
5051 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
5052 // We need to call the function synchronously, so spin waiting for it
5053 // to return. If we get interrupted while executing, we're going to
5054 // lose our context, and won't be able to gather the result at this
5055 // point. We set the timeout AFTER the resume, since the resume takes
5056 // some time and we don't want to charge that to the timeout.
5057 } else {
5058 if (log)
5059 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
5060 }
5061
5062 do_resume = true;
5063 handle_running_event = true;
5064
5065 // Now wait for the process to stop again:
5066 event_sp.reset();
5067
5068 Timeout<std::micro> timeout =
5069 GetExpressionTimeout(options, before_first_timeout);
5070 if (log) {
5071 if (timeout) {
5072 auto now = system_clock::now();
5073 LLDB_LOGF(log,
5074 "Process::RunThreadPlan(): about to wait - now is %s - "
5075 "endpoint is %s",
5076 llvm::to_string(now).c_str(),
5077 llvm::to_string(now + *timeout).c_str());
5078 } else {
5079 LLDB_LOGF(log, "Process::RunThreadPlan(): about to wait forever.");
5080 }
5081 }
5082
5083#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5084 // See comment above...
5085 if (miss_first_event) {
5086 std::this_thread::sleep_for(std::chrono::milliseconds(1));
5087 miss_first_event = false;
5088 got_event = false;
5089 } else
5090#endif
5091 got_event = listener_sp->GetEvent(event_sp, timeout);
5092
5093 if (got_event) {
5094 if (event_sp) {
5095 bool keep_going = false;
5096 if (event_sp->GetType() == eBroadcastBitInterrupt) {
5097 const bool clear_thread_plans = false;
5098 const bool use_run_lock = false;
5099 Halt(clear_thread_plans, use_run_lock);
5100 return_value = eExpressionInterrupted;
5101 diagnostic_manager.PutString(eDiagnosticSeverityRemark,
5102 "execution halted by user interrupt.");
5103 LLDB_LOGF(log, "Process::RunThreadPlan(): Got interrupted by "
5104 "eBroadcastBitInterrupted, exiting.");
5105 break;
5106 } else {
5107 stop_state =
5109 LLDB_LOGF(log,
5110 "Process::RunThreadPlan(): in while loop, got event: %s.",
5111 StateAsCString(stop_state));
5112
5113 switch (stop_state) {
5114 case lldb::eStateStopped: {
5116 event_sp.get())) {
5117 // If we were restarted, we just need to go back up to fetch
5118 // another event.
5119 LLDB_LOGF(log, "Process::RunThreadPlan(): Got a stop and "
5120 "restart, so we'll continue waiting.");
5121 keep_going = true;
5122 do_resume = false;
5123 handle_running_event = true;
5124 } else {
5125 const bool handle_interrupts = true;
5126 return_value = *HandleStoppedEvent(
5127 expr_thread_id, thread_plan_sp, thread_plan_restorer,
5128 event_sp, event_to_broadcast_sp, options,
5129 handle_interrupts);
5130 if (return_value == eExpressionThreadVanished)
5131 keep_going = false;
5132 }
5133 } break;
5134
5136 // This shouldn't really happen, but sometimes we do get two
5137 // running events without an intervening stop, and in that case
5138 // we should just go back to waiting for the stop.
5139 do_resume = false;
5140 keep_going = true;
5141 handle_running_event = false;
5142 break;
5143
5144 default:
5145 LLDB_LOGF(log,
5146 "Process::RunThreadPlan(): execution stopped with "
5147 "unexpected state: %s.",
5148 StateAsCString(stop_state));
5149
5150 if (stop_state == eStateExited)
5151 event_to_broadcast_sp = event_sp;
5152
5153 diagnostic_manager.PutString(
5155 "execution stopped with unexpected state.");
5156 return_value = eExpressionInterrupted;
5157 break;
5158 }
5159 }
5160
5161 if (keep_going)
5162 continue;
5163 else
5164 break;
5165 } else {
5166 if (log)
5167 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5168 "the event pointer was null. How odd...");
5169 return_value = eExpressionInterrupted;
5170 break;
5171 }
5172 } else {
5173 // If we didn't get an event that means we've timed out... We will
5174 // interrupt the process here. Depending on what we were asked to do
5175 // we will either exit, or try with all threads running for the same
5176 // timeout.
5177
5178 if (log) {
5179 if (options.GetTryAllThreads()) {
5180 if (before_first_timeout) {
5181 LLDB_LOG(log,
5182 "Running function with one thread timeout timed out.");
5183 } else
5184 LLDB_LOG(log, "Restarting function with all threads enabled and "
5185 "timeout: {0} timed out, abandoning execution.",
5186 timeout);
5187 } else
5188 LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5189 "abandoning execution.",
5190 timeout);
5191 }
5192
5193 // It is possible that between the time we issued the Halt, and we get
5194 // around to calling Halt the target could have stopped. That's fine,
5195 // Halt will figure that out and send the appropriate Stopped event.
5196 // BUT it is also possible that we stopped & restarted (e.g. hit a
5197 // signal with "stop" set to false.) In
5198 // that case, we'll get the stopped & restarted event, and we should go
5199 // back to waiting for the Halt's stopped event. That's what this
5200 // while loop does.
5201
5202 bool back_to_top = true;
5203 uint32_t try_halt_again = 0;
5204 bool do_halt = true;
5205 const uint32_t num_retries = 5;
5206 while (try_halt_again < num_retries) {
5207 Status halt_error;
5208 if (do_halt) {
5209 LLDB_LOGF(log, "Process::RunThreadPlan(): Running Halt.");
5210 const bool clear_thread_plans = false;
5211 const bool use_run_lock = false;
5212 Halt(clear_thread_plans, use_run_lock);
5213 }
5214 if (halt_error.Success()) {
5215 if (log)
5216 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5217
5218 got_event =
5219 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
5220
5221 if (got_event) {
5222 stop_state =
5224 if (log) {
5225 LLDB_LOGF(log,
5226 "Process::RunThreadPlan(): Stopped with event: %s",
5227 StateAsCString(stop_state));
5228 if (stop_state == lldb::eStateStopped &&
5230 event_sp.get()))
5231 log->PutCString(" Event was the Halt interruption event.");
5232 }
5233
5234 if (stop_state == lldb::eStateStopped) {
5236 event_sp.get())) {
5237 if (log)
5238 log->PutCString("Process::RunThreadPlan(): Went to halt "
5239 "but got a restarted event, there must be "
5240 "an un-restarted stopped event so try "
5241 "again... "
5242 "Exiting wait loop.");
5243 try_halt_again++;
5244 do_halt = false;
5245 continue;
5246 }
5247
5248 // Between the time we initiated the Halt and the time we
5249 // delivered it, the process could have already finished its
5250 // job. Check that here:
5251 const bool handle_interrupts = false;
5252 if (auto result = HandleStoppedEvent(
5253 expr_thread_id, thread_plan_sp, thread_plan_restorer,
5254 event_sp, event_to_broadcast_sp, options,
5255 handle_interrupts)) {
5256 return_value = *result;
5257 back_to_top = false;
5258 break;
5259 }
5260
5261 if (!options.GetTryAllThreads()) {
5262 if (log)
5263 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5264 "was false, we stopped so now we're "
5265 "quitting.");
5266 return_value = eExpressionInterrupted;
5267 back_to_top = false;
5268 break;
5269 }
5270
5271 if (before_first_timeout) {
5272 // Set all the other threads to run, and return to the top of
5273 // the loop, which will continue;
5274 before_first_timeout = false;
5275 thread_plan_sp->SetStopOthers(false);
5276 if (log)
5277 log->PutCString(
5278 "Process::RunThreadPlan(): about to resume.");
5279
5280 back_to_top = true;
5281 break;
5282 } else {
5283 // Running all threads failed, so return Interrupted.
5284 if (log)
5285 log->PutCString("Process::RunThreadPlan(): running all "
5286 "threads timed out.");
5287 return_value = eExpressionInterrupted;
5288 back_to_top = false;
5289 break;
5290 }
5291 }
5292 } else {
5293 if (log)
5294 log->PutCString("Process::RunThreadPlan(): halt said it "
5295 "succeeded, but I got no event. "
5296 "I'm getting out of here passing Interrupted.");
5297 return_value = eExpressionInterrupted;
5298 back_to_top = false;
5299 break;
5300 }
5301 } else {
5302 try_halt_again++;
5303 continue;
5304 }
5305 }
5306
5307 if (!back_to_top || try_halt_again > num_retries)
5308 break;
5309 else
5310 continue;
5311 }
5312 } // END WAIT LOOP
5313
5314 // If we had to start up a temporary private state thread to run this
5315 // thread plan, shut it down now.
5316 if (backup_private_state_thread.IsJoinable()) {
5318 Status error;
5319 m_private_state_thread = backup_private_state_thread;
5320 if (stopper_base_plan_sp) {
5321 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5322 }
5323 if (old_state != eStateInvalid)
5324 m_public_state.SetValueNoLock(old_state);
5325 }
5326
5327 // If our thread went away on us, we need to get out of here without
5328 // doing any more work. We don't have to clean up the thread plan, that
5329 // will have happened when the Thread was destroyed.
5330 if (return_value == eExpressionThreadVanished) {
5331 return return_value;
5332 }
5333
5334 if (return_value != eExpressionCompleted && log) {
5335 // Print a backtrace into the log so we can figure out where we are:
5336 StreamString s;
5337 s.PutCString("Thread state after unsuccessful completion: \n");
5338 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
5339 log->PutString(s.GetString());
5340 }
5341 // Restore the thread state if we are going to discard the plan execution.
5342 // There are three cases where this could happen: 1) The execution
5343 // successfully completed 2) We hit a breakpoint, and ignore_breakpoints
5344 // was true 3) We got some other error, and discard_on_error was true
5345 bool should_unwind = (return_value == eExpressionInterrupted &&
5346 options.DoesUnwindOnError()) ||
5347 (return_value == eExpressionHitBreakpoint &&
5348 options.DoesIgnoreBreakpoints());
5349
5350 if (return_value == eExpressionCompleted || should_unwind) {
5351 thread_plan_sp->RestoreThreadState();
5352 }
5353
5354 // Now do some processing on the results of the run:
5355 if (return_value == eExpressionInterrupted ||
5356 return_value == eExpressionHitBreakpoint) {
5357 if (log) {
5358 StreamString s;
5359 if (event_sp)
5360 event_sp->Dump(&s);
5361 else {
5362 log->PutCString("Process::RunThreadPlan(): Stop event that "
5363 "interrupted us is NULL.");
5364 }
5365
5366 StreamString ts;
5367
5368 const char *event_explanation = nullptr;
5369
5370 do {
5371 if (!event_sp) {
5372 event_explanation = "<no event>";
5373 break;
5374 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5375 event_explanation = "<user interrupt>";
5376 break;
5377 } else {
5378 const Process::ProcessEventData *event_data =
5380 event_sp.get());
5381
5382 if (!event_data) {
5383 event_explanation = "<no event data>";
5384 break;
5385 }
5386
5387 Process *process = event_data->GetProcessSP().get();
5388
5389 if (!process) {
5390 event_explanation = "<no process>";
5391 break;
5392 }
5393
5394 ThreadList &thread_list = process->GetThreadList();
5395
5396 uint32_t num_threads = thread_list.GetSize();
5397 uint32_t thread_index;
5398
5399 ts.Printf("<%u threads> ", num_threads);
5400
5401 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5402 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5403
5404 if (!thread) {
5405 ts.Printf("<?> ");
5406 continue;
5407 }
5408
5409 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5410 RegisterContext *register_context =
5411 thread->GetRegisterContext().get();
5412
5413 if (register_context)
5414 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5415 else
5416 ts.Printf("[ip unknown] ");
5417
5418 // Show the private stop info here, the public stop info will be
5419 // from the last natural stop.
5420 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5421 if (stop_info_sp) {
5422 const char *stop_desc = stop_info_sp->GetDescription();
5423 if (stop_desc)
5424 ts.PutCString(stop_desc);
5425 }
5426 ts.Printf(">");
5427 }
5428
5429 event_explanation = ts.GetData();
5430 }
5431 } while (false);
5432
5433 if (event_explanation)
5434 LLDB_LOGF(log,
5435 "Process::RunThreadPlan(): execution interrupted: %s %s",
5436 s.GetData(), event_explanation);
5437 else
5438 LLDB_LOGF(log, "Process::RunThreadPlan(): execution interrupted: %s",
5439 s.GetData());
5440 }
5441
5442 if (should_unwind) {
5443 LLDB_LOGF(log,
5444 "Process::RunThreadPlan: ExecutionInterrupted - "
5445 "discarding thread plans up to %p.",
5446 static_cast<void *>(thread_plan_sp.get()));
5447 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5448 } else {
5449 LLDB_LOGF(log,
5450 "Process::RunThreadPlan: ExecutionInterrupted - for "
5451 "plan: %p not discarding.",
5452 static_cast<void *>(thread_plan_sp.get()));
5453 }
5454 } else if (return_value == eExpressionSetupError) {
5455 if (log)
5456 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5457
5458 if (options.DoesUnwindOnError()) {
5459 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5460 }
5461 } else {
5462 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5463 if (log)
5464 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5465 return_value = eExpressionCompleted;
5466 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5467 if (log)
5468 log->PutCString(
5469 "Process::RunThreadPlan(): thread plan was discarded");
5470 return_value = eExpressionDiscarded;
5471 } else {
5472 if (log)
5473 log->PutCString(
5474 "Process::RunThreadPlan(): thread plan stopped in mid course");
5475 if (options.DoesUnwindOnError() && thread_plan_sp) {
5476 if (log)
5477 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5478 "'cause unwind_on_error is set.");
5479 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5480 }
5481 }
5482 }
5483
5484 // Thread we ran the function in may have gone away because we ran the
5485 // target Check that it's still there, and if it is put it back in the
5486 // context. Also restore the frame in the context if it is still present.
5487 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5488 if (thread) {
5489 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5490 }
5491
5492 // Also restore the current process'es selected frame & thread, since this
5493 // function calling may be done behind the user's back.
5494
5495 if (selected_tid != LLDB_INVALID_THREAD_ID) {
5496 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5497 selected_stack_id.IsValid()) {
5498 // We were able to restore the selected thread, now restore the frame:
5499 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5500 StackFrameSP old_frame_sp =
5501 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5502 selected_stack_id);
5503 if (old_frame_sp)
5504 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5505 old_frame_sp.get());
5506 }
5507 }
5508 }
5509
5510 // If the process exited during the run of the thread plan, notify everyone.
5511
5512 if (event_to_broadcast_sp) {
5513 if (log)
5514 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5515 BroadcastEvent(event_to_broadcast_sp);
5516 }
5517
5518 return return_value;
5519}
5520
5522 const char *result_name = "<unknown>";
5523
5524 switch (result) {
5526 result_name = "eExpressionCompleted";
5527 break;
5529 result_name = "eExpressionDiscarded";
5530 break;
5532 result_name = "eExpressionInterrupted";
5533 break;
5535 result_name = "eExpressionHitBreakpoint";
5536 break;
5538 result_name = "eExpressionSetupError";
5539 break;
5541 result_name = "eExpressionParseError";
5542 break;
5544 result_name = "eExpressionResultUnavailable";
5545 break;
5547 result_name = "eExpressionTimedOut";
5548 break;
5550 result_name = "eExpressionStoppedForDebug";
5551 break;
5553 result_name = "eExpressionThreadVanished";
5554 }
5555 return result_name;
5556}
5557
5559 const StateType state = GetState();
5560 if (StateIsStoppedState(state, false)) {
5561 if (state == eStateExited) {
5562 int exit_status = GetExitStatus();
5563 const char *exit_description = GetExitDescription();
5564 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5565 GetID(), exit_status, exit_status,
5566 exit_description ? exit_description : "");
5567 } else {
5568 if (state == eStateConnected)
5569 strm.Printf("Connected to remote target.\n");
5570 else
5571 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5572 }
5573 } else {
5574 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5575 }
5576}
5577
5579 bool only_threads_with_stop_reason,
5580 uint32_t start_frame, uint32_t num_frames,
5581 uint32_t num_frames_with_source,
5582 bool stop_format) {
5583 size_t num_thread_infos_dumped = 0;
5584
5585 // You can't hold the thread list lock while calling Thread::GetStatus. That
5586 // very well might run code (e.g. if we need it to get return values or
5587 // arguments.) For that to work the process has to be able to acquire it.
5588 // So instead copy the thread ID's, and look them up one by one:
5589
5590 uint32_t num_threads;
5591 std::vector<lldb::tid_t> thread_id_array;
5592 // Scope for thread list locker;
5593 {
5594 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5595 ThreadList &curr_thread_list = GetThreadList();
5596 num_threads = curr_thread_list.GetSize();
5597 uint32_t idx;
5598 thread_id_array.resize(num_threads);
5599 for (idx = 0; idx < num_threads; ++idx)
5600 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5601 }
5602
5603 for (uint32_t i = 0; i < num_threads; i++) {
5604 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5605 if (thread_sp) {
5606 if (only_threads_with_stop_reason) {
5607 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5608 if (!stop_info_sp || !stop_info_sp->IsValid())
5609 continue;
5610 }
5611 thread_sp->GetStatus(strm, start_frame, num_frames,
5612 num_frames_with_source,
5613 stop_format);
5614 ++num_thread_infos_dumped;
5615 } else {
5616 Log *log = GetLog(LLDBLog::Process);
5617 LLDB_LOGF(log, "Process::GetThreadStatus - thread 0x" PRIu64
5618 " vanished while running Thread::GetStatus.");
5619 }
5620 }
5621 return num_thread_infos_dumped;
5622}
5623
5626}
5627
5630 region.GetByteSize());
5631}
5632
5634 void *baton) {
5635 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5636}
5637
5639 bool result = true;
5640 while (!m_pre_resume_actions.empty()) {
5641 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5642 m_pre_resume_actions.pop_back();
5643 bool this_result = action.callback(action.baton);
5644 if (result)
5645 result = this_result;
5646 }
5647 return result;
5648}
5649
5651
5653{
5654 PreResumeCallbackAndBaton element(callback, baton);
5655 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5656 if (found_iter != m_pre_resume_actions.end())
5657 {
5658 m_pre_resume_actions.erase(found_iter);
5659 }
5660}
5661
5664 return m_private_run_lock;
5665 else
5666 return m_public_run_lock;
5667}
5668
5670{
5672}
5673
5674
5681}
5682
5684 if (uint32_t num_bits_setting = GetVirtualAddressableBits())
5685 return AddressableBits::AddressableBitToMask(num_bits_setting);
5686
5687 return m_code_address_mask;
5688}
5689
5691 if (uint32_t num_bits_setting = GetVirtualAddressableBits())
5692 return AddressableBits::AddressableBitToMask(num_bits_setting);
5693
5694 return m_data_address_mask;
5695}
5696
5698 if (uint32_t num_bits_setting = GetHighmemVirtualAddressableBits())
5699 return AddressableBits::AddressableBitToMask(num_bits_setting);
5700
5703 return GetCodeAddressMask();
5704}
5705
5707 if (uint32_t num_bits_setting = GetHighmemVirtualAddressableBits())
5708 return AddressableBits::AddressableBitToMask(num_bits_setting);
5709
5712 return GetDataAddressMask();
5713}
5714
5717 "Setting Process code address mask to {0:x}", code_address_mask);
5718 m_code_address_mask = code_address_mask;
5719}
5720
5723 "Setting Process data address mask to {0:x}", data_address_mask);
5724 m_data_address_mask = data_address_mask;
5725}
5726
5729 "Setting Process highmem code address mask to {0:x}",
5730 code_address_mask);
5731 m_highmem_code_address_mask = code_address_mask;
5732}
5733
5736 "Setting Process highmem data address mask to {0:x}",
5737 data_address_mask);
5738 m_highmem_data_address_mask = data_address_mask;
5739}
5740
5742 if (ABISP abi_sp = GetABI())
5743 addr = abi_sp->FixCodeAddress(addr);
5744 return addr;
5745}
5746
5748 if (ABISP abi_sp = GetABI())
5749 addr = abi_sp->FixDataAddress(addr);
5750 return addr;
5751}
5752
5754 if (ABISP abi_sp = GetABI())
5755 addr = abi_sp->FixAnyAddress(addr);
5756 return addr;
5757}
5758
5760 Log *log = GetLog(LLDBLog::Process);
5761 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
5762
5763 Target &target = GetTarget();
5764 target.CleanupProcess();
5765 target.ClearModules(false);
5766 m_dynamic_checkers_up.reset();
5767 m_abi_sp.reset();
5768 m_system_runtime_up.reset();
5769 m_os_up.reset();
5770 m_dyld_up.reset();
5771 m_jit_loaders_up.reset();
5772 m_image_tokens.clear();
5773 // After an exec, the inferior is a new process and these memory regions are
5774 // no longer allocated.
5775 m_allocated_memory_cache.Clear(/*deallocte_memory=*/false);
5776 {
5777 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
5778 m_language_runtimes.clear();
5779 }
5782 m_memory_cache.Clear(true);
5783 DoDidExec();
5785 // Flush the process (threads and all stack frames) after running
5786 // CompleteAttach() in case the dynamic loader loaded things in new
5787 // locations.
5788 Flush();
5789
5790 // After we figure out what was loaded/unloaded in CompleteAttach, we need to
5791 // let the target know so it can do any cleanup it needs to.
5792 target.DidExec();
5793}
5794
5796 if (address == nullptr) {
5797 error.SetErrorString("Invalid address argument");
5798 return LLDB_INVALID_ADDRESS;
5799 }
5800
5801 addr_t function_addr = LLDB_INVALID_ADDRESS;
5802
5803 addr_t addr = address->GetLoadAddress(&GetTarget());
5804 std::map<addr_t, addr_t>::const_iterator iter =
5806 if (iter != m_resolved_indirect_addresses.end()) {
5807 function_addr = (*iter).second;
5808 } else {
5809 if (!CallVoidArgVoidPtrReturn(address, function_addr)) {
5810 Symbol *symbol = address->CalculateSymbolContextSymbol();
5811 error.SetErrorStringWithFormat(
5812 "Unable to call resolver for indirect function %s",
5813 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5814 function_addr = LLDB_INVALID_ADDRESS;
5815 } else {
5816 if (ABISP abi_sp = GetABI())
5817 function_addr = abi_sp->FixCodeAddress(function_addr);
5819 std::pair<addr_t, addr_t>(addr, function_addr));
5820 }
5821 }
5822 return function_addr;
5823}
5824
5826 // Inform the system runtime of the modified modules.
5827 SystemRuntime *sys_runtime = GetSystemRuntime();
5828 if (sys_runtime)
5829 sys_runtime->ModulesDidLoad(module_list);
5830
5831 GetJITLoaders().ModulesDidLoad(module_list);
5832
5833 // Give the instrumentation runtimes a chance to be created before informing
5834 // them of the modified modules.
5837 for (auto &runtime : m_instrumentation_runtimes)
5838 runtime.second->ModulesDidLoad(module_list);
5839
5840 // Give the language runtimes a chance to be created before informing them of
5841 // the modified modules.
5842 for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {
5843 if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type))
5844 runtime->ModulesDidLoad(module_list);
5845 }
5846
5847 // If we don't have an operating system plug-in, try to load one since
5848 // loading shared libraries might cause a new one to try and load
5849 if (!m_os_up)
5851
5852 // Inform the structured-data plugins of the modified modules.
5853 for (auto &pair : m_structured_data_plugin_map) {
5854 if (pair.second)
5855 pair.second->ModulesDidLoad(*this, module_list);
5856 }
5857}
5858
5861 return;
5862 if (!sc.module_sp || !sc.function || !sc.function->GetIsOptimized())
5863 return;
5864 sc.module_sp->ReportWarningOptimization(GetTarget().GetDebugger().GetID());
5865}
5866
5869 return;
5870 if (!sc.module_sp)
5871 return;
5872 LanguageType language = sc.GetLanguage();
5873 if (language == eLanguageTypeUnknown)
5874 return;
5875 LanguageSet plugins =
5877 if (plugins[language])
5878 return;
5879 sc.module_sp->ReportWarningUnsupportedLanguage(
5880 language, GetTarget().GetDebugger().GetID());
5881}
5882
5884 info.Clear();
5885
5886 PlatformSP platform_sp = GetTarget().GetPlatform();
5887 if (!platform_sp)
5888 return false;
5889
5890 return platform_sp->GetProcessInfo(GetID(), info);
5891}
5892
5894 ThreadCollectionSP threads;
5895
5896 const MemoryHistorySP &memory_history =
5897 MemoryHistory::FindPlugin(shared_from_this());
5898
5899 if (!memory_history) {
5900 return threads;
5901 }
5902
5903 threads = std::make_shared<ThreadCollection>(
5904 memory_history->GetHistoryThreads(addr));
5905
5906 return threads;
5907}
5908
5911 InstrumentationRuntimeCollection::iterator pos;
5912 pos = m_instrumentation_runtimes.find(type);
5913 if (pos == m_instrumentation_runtimes.end()) {
5914 return InstrumentationRuntimeSP();
5915 } else
5916 return (*pos).second;
5917}
5918
5919bool Process::GetModuleSpec(const FileSpec &module_file_spec,
5920 const ArchSpec &arch, ModuleSpec &module_spec) {
5921 module_spec.Clear();
5922 return false;
5923}
5924
5926 m_image_tokens.push_back(image_ptr);
5927 return m_image_tokens.size() - 1;
5928}
5929
5931 if (token < m_image_tokens.size())
5932 return m_image_tokens[token];
5934}
5935
5936void Process::ResetImageToken(size_t token) {
5937 if (token < m_image_tokens.size())
5939}
5940
5941Address
5943 AddressRange range_bounds) {
5944 Target &target = GetTarget();
5945 DisassemblerSP disassembler_sp;
5946 InstructionList *insn_list = nullptr;
5947
5948 Address retval = default_stop_addr;
5949
5950 if (!target.GetUseFastStepping())
5951 return retval;
5952 if (!default_stop_addr.IsValid())
5953 return retval;
5954
5955 const char *plugin_name = nullptr;
5956 const char *flavor = nullptr;
5957 disassembler_sp = Disassembler::DisassembleRange(
5958 target.GetArchitecture(), plugin_name, flavor, GetTarget(), range_bounds);
5959 if (disassembler_sp)
5960 insn_list = &disassembler_sp->GetInstructionList();
5961
5962 if (insn_list == nullptr) {
5963 return retval;
5964 }
5965
5966 size_t insn_offset =
5967 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
5968 if (insn_offset == UINT32_MAX) {
5969 return retval;
5970 }
5971
5972 uint32_t branch_index = insn_list->GetIndexOfNextBranchInstruction(
5973 insn_offset, false /* ignore_calls*/, nullptr);
5974 if (branch_index == UINT32_MAX) {
5975 return retval;
5976 }
5977
5978 if (branch_index > insn_offset) {
5979 Address next_branch_insn_address =
5980 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
5981 if (next_branch_insn_address.IsValid() &&
5982 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
5983 retval = next_branch_insn_address;
5984 }
5985 }
5986
5987 return retval;
5988}
5989
5991 MemoryRegionInfo &range_info) {
5992 if (const lldb::ABISP &abi = GetABI())
5993 load_addr = abi->FixAnyAddress(load_addr);
5994 return DoGetMemoryRegionInfo(load_addr, range_info);
5995}
5996
5998 Status error;
5999
6000 lldb::addr_t range_end = 0;
6001 const lldb::ABISP &abi = GetABI();
6002
6003 region_list.clear();
6004 do {
6006 error = GetMemoryRegionInfo(range_end, region_info);
6007 // GetMemoryRegionInfo should only return an error if it is unimplemented.
6008 if (error.Fail()) {
6009 region_list.clear();
6010 break;
6011 }
6012
6013 // We only check the end address, not start and end, because we assume that
6014 // the start will not have non-address bits until the first unmappable
6015 // region. We will have exited the loop by that point because the previous
6016 // region, the last mappable region, will have non-address bits in its end
6017 // address.
6018 range_end = region_info.GetRange().GetRangeEnd();
6019 if (region_info.GetMapped() == MemoryRegionInfo::eYes) {
6020 region_list.push_back(std::move(region_info));
6021 }
6022 } while (
6023 // For a process with no non-address bits, all address bits
6024 // set means the end of memory.
6025 range_end != LLDB_INVALID_ADDRESS &&
6026 // If we have non-address bits and some are set then the end
6027 // is at or beyond the end of mappable memory.
6028 !(abi && (abi->FixAnyAddress(range_end) != range_end)));
6029
6030 return error;
6031}
6032
6033Status
6034Process::ConfigureStructuredData(llvm::StringRef type_name,
6035 const StructuredData::ObjectSP &config_sp) {
6036 // If you get this, the Process-derived class needs to implement a method to
6037 // enable an already-reported asynchronous structured data feature. See
6038 // ProcessGDBRemote for an example implementation over gdb-remote.
6039 return Status("unimplemented");
6040}
6041
6043 const StructuredData::Array &supported_type_names) {
6044 Log *log = GetLog(LLDBLog::Process);
6045
6046 // Bail out early if there are no type names to map.
6047 if (supported_type_names.GetSize() == 0) {
6048 LLDB_LOG(log, "no structured data types supported");
6049 return;
6050 }
6051
6052 // These StringRefs are backed by the input parameter.
6053 std::set<llvm::StringRef> type_names;
6054
6055 LLDB_LOG(log,
6056 "the process supports the following async structured data types:");
6057
6058 supported_type_names.ForEach(
6059 [&type_names, &log](StructuredData::Object *object) {
6060 // There shouldn't be null objects in the array.
6061 if (!object)
6062 return false;
6063
6064 // All type names should be strings.
6065 const llvm::StringRef type_name = object->GetStringValue();
6066 if (type_name.empty())
6067 return false;
6068
6069 type_names.insert(type_name);
6070 LLDB_LOG(log, "- {0}", type_name);
6071 return true;
6072 });
6073
6074 // For each StructuredDataPlugin, if the plugin handles any of the types in
6075 // the supported_type_names, map that type name to that plugin. Stop when
6076 // we've consumed all the type names.
6077 // FIXME: should we return an error if there are type names nobody
6078 // supports?
6079 for (uint32_t plugin_index = 0; !type_names.empty(); plugin_index++) {
6080 auto create_instance =
6082 plugin_index);
6083 if (!create_instance)
6084 break;
6085
6086 // Create the plugin.
6087 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
6088 if (!plugin_sp) {
6089 // This plugin doesn't think it can work with the process. Move on to the
6090 // next.
6091 continue;
6092 }
6093
6094 // For any of the remaining type names, map any that this plugin supports.
6095 std::vector<llvm::StringRef> names_to_remove;
6096 for (llvm::StringRef type_name : type_names) {
6097 if (plugin_sp->SupportsStructuredDataType(type_name)) {
6099 std::make_pair(type_name, plugin_sp));
6100 names_to_remove.push_back(type_name);
6101 LLDB_LOG(log, "using plugin {0} for type name {1}",
6102 plugin_sp->GetPluginName(), type_name);
6103 }
6104 }
6105
6106 // Remove the type names that were consumed by this plugin.
6107 for (llvm::StringRef type_name : names_to_remove)
6108 type_names.erase(type_name);
6109 }
6110}
6111
6113 const StructuredData::ObjectSP object_sp) {
6114 // Nothing to do if there's no data.
6115 if (!object_sp)
6116 return false;
6117
6118 // The contract is this must be a dictionary, so we can look up the routing
6119 // key via the top-level 'type' string value within the dictionary.
6120 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
6121 if (!dictionary)
6122 return false;
6123
6124 // Grab the async structured type name (i.e. the feature/plugin name).
6125 llvm::StringRef type_name;
6126 if (!dictionary->GetValueForKeyAsString("type", type_name))
6127 return false;
6128
6129 // Check if there's a plugin registered for this type name.
6130 auto find_it = m_structured_data_plugin_map.find(type_name);
6131 if (find_it == m_structured_data_plugin_map.end()) {
6132 // We don't have a mapping for this structured data type.
6133 return false;
6134 }
6135
6136 // Route the structured data to the plugin.
6137 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
6138 return true;
6139}
6140
6142 // Default implementation does nothign.
6143 // No automatic signal filtering to speak of.
6144 return Status();
6145}
6146
6148 Platform *platform,
6149 llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) {
6150 if (platform != GetTarget().GetPlatform().get())
6151 return nullptr;
6152 llvm::call_once(m_dlopen_utility_func_flag_once,
6153 [&] { m_dlopen_utility_func_up = factory(); });
6154 return m_dlopen_utility_func_up.get();
6155}
6156
6157llvm::Expected<TraceSupportedResponse> Process::TraceSupported() {
6158 if (!IsLiveDebugSession())
6159 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6160 "Can't trace a non-live process.");
6161 return llvm::make_error<UnimplementedError>();
6162}
6163
6165 addr_t &returned_func,
6166 bool trap_exceptions) {
6168 if (thread == nullptr || address == nullptr)
6169 return false;
6170
6172 options.SetStopOthers(true);
6173 options.SetUnwindOnError(true);
6174 options.SetIgnoreBreakpoints(true);
6175 options.SetTryAllThreads(true);
6176 options.SetDebug(false);
6178 options.SetTrapExceptions(trap_exceptions);
6179
6180 auto type_system_or_err =
6182 if (!type_system_or_err) {
6183 llvm::consumeError(type_system_or_err.takeError());
6184 return false;
6185 }
6186 auto ts = *type_system_or_err;
6187 if (!ts)
6188 return false;
6189 CompilerType void_ptr_type =
6192 *thread, *address, void_ptr_type, llvm::ArrayRef<addr_t>(), options));
6193 if (call_plan_sp) {
6194 DiagnosticManager diagnostics;
6195
6196 StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
6197 if (frame) {
6198 ExecutionContext exe_ctx;
6199 frame->CalculateExecutionContext(exe_ctx);
6200 ExpressionResults result =
6201 RunThreadPlan(exe_ctx, call_plan_sp, options, diagnostics);
6202 if (result == eExpressionCompleted) {
6203 returned_func =
6204 call_plan_sp->GetReturnValueObject()->GetValueAsUnsigned(
6206
6207 if (GetAddressByteSize() == 4) {
6208 if (returned_func == UINT32_MAX)
6209 return false;
6210 } else if (GetAddressByteSize() == 8) {
6211 if (returned_func == UINT64_MAX)
6212 return false;
6213 }
6214 return true;
6215 }
6216 }
6217 }
6218
6219 return false;
6220}
6221
6222llvm::Expected<const MemoryTagManager *> Process::GetMemoryTagManager() {
6224 const MemoryTagManager *tag_manager =
6225 arch ? arch->GetMemoryTagManager() : nullptr;
6226 if (!arch || !tag_manager) {
6227 return llvm::createStringError(
6228 llvm::inconvertibleErrorCode(),
6229 "This architecture does not support memory tagging");
6230 }
6231
6232 if (!SupportsMemoryTagging()) {
6233 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6234 "Process does not support memory tagging");
6235 }
6236
6237 return tag_manager;
6238}
6239
6240llvm::Expected<std::vector<lldb::addr_t>>
6242 llvm::Expected<const MemoryTagManager *> tag_manager_or_err =
6244 if (!tag_manager_or_err)
6245 return tag_manager_or_err.takeError();
6246
6247 const MemoryTagManager *tag_manager = *tag_manager_or_err;
6248 llvm::Expected<std::vector<uint8_t>> tag_data =
6249 DoReadMemoryTags(addr, len, tag_manager->GetAllocationTagType());
6250 if (!tag_data)
6251 return tag_data.takeError();
6252
6253 return tag_manager->UnpackTagsData(*tag_data,
6254 len / tag_manager->GetGranuleSize());
6255}
6256
6258 const std::vector<lldb::addr_t> &tags) {
6259 llvm::Expected<const MemoryTagManager *> tag_manager_or_err =
6261 if (!tag_manager_or_err)
6262 return Status(tag_manager_or_err.takeError());
6263
6264 const MemoryTagManager *tag_manager = *tag_manager_or_err;
6265 llvm::Expected<std::vector<uint8_t>> packed_tags =
6266 tag_manager->PackTags(tags);
6267 if (!packed_tags) {
6268 return Status(packed_tags.takeError());
6269 }
6270
6271 return DoWriteMemoryTags(addr, len, tag_manager->GetAllocationTagType(),
6272 *packed_tags);
6273}
6274
6275// Create a CoreFileMemoryRange from a MemoryRegionInfo
6278 const addr_t addr = region.GetRange().GetRangeBase();
6279 llvm::AddressRange range(addr, addr + region.GetRange().GetByteSize());
6280 return {range, region.GetLLDBPermissions()};
6281}
6282
6283// Add dirty pages to the core file ranges and return true if dirty pages
6284// were added. Return false if the dirty page information is not valid or in
6285// the region.
6286static bool AddDirtyPages(const MemoryRegionInfo &region,
6288 const auto &dirty_page_list = region.GetDirtyPageList();
6289 if (!dirty_page_list)
6290 return false;
6291 const uint32_t lldb_permissions = region.GetLLDBPermissions();
6292 const addr_t page_size = region.GetPageSize();
6293 if (page_size == 0)
6294 return false;
6295 llvm::AddressRange range(0, 0);
6296 for (addr_t page_addr : *dirty_page_list) {
6297 if (range.empty()) {
6298 // No range yet, initialize the range with the current dirty page.
6299 range = llvm::AddressRange(page_addr, page_addr + page_size);
6300 } else {
6301 if (range.end() == page_addr) {
6302 // Combine consective ranges.
6303 range = llvm::AddressRange(range.start(), page_addr + page_size);
6304 } else {
6305 // Add previous contiguous range and init the new range with the
6306 // current dirty page.
6307 ranges.push_back({range, lldb_permissions});
6308 range = llvm::AddressRange(page_addr, page_addr + page_size);
6309 }
6310 }
6311 }
6312 // The last range
6313 if (!range.empty())
6314 ranges.push_back({range, lldb_permissions});
6315 return true;
6316}
6317
6318// Given a region, add the region to \a ranges.
6319//
6320// Only add the region if it isn't empty and if it has some permissions.
6321// If \a try_dirty_pages is true, then try to add only the dirty pages for a
6322// given region. If the region has dirty page information, only dirty pages
6323// will be added to \a ranges, else the entire range will be added to \a
6324// ranges.
6325static void AddRegion(const MemoryRegionInfo &region, bool try_dirty_pages,
6327 // Don't add empty ranges or ranges with no permissions.
6328 if (region.GetRange().GetByteSize() == 0 || region.GetLLDBPermissions() == 0)
6329 return;
6330 if (try_dirty_pages && AddDirtyPages(region, ranges))
6331 return;
6332 ranges.push_back(CreateCoreFileMemoryRange(region));
6333}
6334
6335// Save all memory regions that are not empty or have at least some permissions
6336// for a full core file style.
6338 const MemoryRegionInfos &regions,
6340
6341 // Don't add only dirty pages, add full regions.
6342const bool try_dirty_pages = false;
6343 for (const auto &region : regions)
6344 AddRegion(region, try_dirty_pages, ranges);
6345}
6346
6347// Save only the dirty pages to the core file. Make sure the process has at
6348// least some dirty pages, as some OS versions don't support reporting what
6349// pages are dirty within an memory region. If no memory regions have dirty
6350// page information fall back to saving out all ranges with write permissions.
6351static void
6353 const MemoryRegionInfos &regions,
6355 // Iterate over the regions and find all dirty pages.
6356 bool have_dirty_page_info = false;
6357 for (const auto &region : regions) {
6358 if (AddDirtyPages(region, ranges))
6359 have_dirty_page_info = true;
6360 }
6361
6362 if (!have_dirty_page_info) {
6363 // We didn't find support for reporting dirty pages from the process
6364 // plug-in so fall back to any region with write access permissions.
6365 const bool try_dirty_pages = false;
6366 for (const auto &region : regions)
6367 if (region.GetWritable() == MemoryRegionInfo::eYes)
6368 AddRegion(region, try_dirty_pages, ranges);
6369 }
6370}
6371
6372// Save all thread stacks to the core file. Some OS versions support reporting
6373// when a memory region is stack related. We check on this information, but we
6374// also use the stack pointers of each thread and add those in case the OS
6375// doesn't support reporting stack memory. This function also attempts to only
6376// emit dirty pages from the stack if the memory regions support reporting
6377// dirty regions as this will make the core file smaller. If the process
6378// doesn't support dirty regions, then it will fall back to adding the full
6379// stack region.
6380static void
6382 const MemoryRegionInfos &regions,
6384 // Some platforms support annotating the region information that tell us that
6385 // it comes from a thread stack. So look for those regions first.
6386
6387 // Keep track of which stack regions we have added
6388 std::set<addr_t> stack_bases;
6389
6390 const bool try_dirty_pages = true;
6391 for (const auto &region : regions) {
6392 if (region.IsStackMemory() == MemoryRegionInfo::eYes) {
6393 stack_bases.insert(region.GetRange().GetRangeBase());
6394 AddRegion(region, try_dirty_pages, ranges);
6395 }
6396 }
6397
6398 // Also check with our threads and get the regions for their stack pointers
6399 // and add those regions if not already added above.
6400 for (lldb::ThreadSP thread_sp : process.GetThreadList().Threads()) {
6401 if (!thread_sp)
6402 continue;
6403 StackFrameSP frame_sp = thread_sp->GetStackFrameAtIndex(0);
6404 if (!frame_sp)
6405 continue;
6406 RegisterContextSP reg_ctx_sp = frame_sp->GetRegisterContext();
6407 if (!reg_ctx_sp)
6408 continue;
6409 const addr_t sp = reg_ctx_sp->GetSP();
6411 if (process.GetMemoryRegionInfo(sp, sp_region).Success()) {
6412 // Only add this region if not already added above. If our stack pointer
6413 // is pointing off in the weeds, we will want this range.
6414 if (stack_bases.count(sp_region.GetRange().GetRangeBase()) == 0)
6415 AddRegion(sp_region, try_dirty_pages, ranges);
6416 }
6417 }
6418}
6419
6421 CoreFileMemoryRanges &ranges) {
6423 Status err = GetMemoryRegions(regions);
6424 if (err.Fail())
6425 return err;
6426 if (regions.empty())
6427 return Status("failed to get any valid memory regions from the process");
6428
6429 switch (core_style) {
6431 err = Status("callers must set the core_style to something other than "
6432 "eSaveCoreUnspecified");
6433 break;
6434
6435 case eSaveCoreFull:
6436 GetCoreFileSaveRangesFull(*this, regions, ranges);
6437 break;
6438
6439 case eSaveCoreDirtyOnly:
6440 GetCoreFileSaveRangesDirtyOnly(*this, regions, ranges);
6441 break;
6442
6443 case eSaveCoreStackOnly:
6444 GetCoreFileSaveRangesStackOnly(*this, regions, ranges);
6445 break;
6446 }
6447
6448 if (err.Fail())
6449 return err;
6450
6451 if (ranges.empty())
6452 return Status("no valid address ranges found for core style");
6453
6454 return Status(); // Success!
6455}
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition: Log.h:342
#define LLDB_LOGF(log,...)
Definition: Log.h:349
#define LLDB_LOG_ERROR(log, error,...)
Definition: Log.h:365
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)
Definition: Process.cpp:4673
static void GetCoreFileSaveRangesFull(Process &process, const MemoryRegionInfos &regions, Process::CoreFileMemoryRanges &ranges)
Definition: Process.cpp:6337
static void GetCoreFileSaveRangesStackOnly(Process &process, const MemoryRegionInfos &regions, Process::CoreFileMemoryRanges &ranges)
Definition: Process.cpp:6381
static constexpr OptionEnumValueElement g_follow_fork_mode_values[]
Definition: Process.cpp:114
static void GetCoreFileSaveRangesDirtyOnly(Process &process, const MemoryRegionInfos &regions, Process::CoreFileMemoryRanges &ranges)
Definition: Process.cpp:6352
static Timeout< std::micro > GetExpressionTimeout(const EvaluateExpressionOptions &options, bool before_first_timeout)
Definition: Process.cpp:4656
@ ePropertyExperimental
Definition: Process.cpp:133
static microseconds GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options)
Definition: Process.cpp:4636
static Process::CoreFileMemoryRange CreateCoreFileMemoryRange(const MemoryRegionInfo &region)
Definition: Process.cpp:6277
static void AddRegion(const MemoryRegionInfo &region, bool try_dirty_pages, Process::CoreFileMemoryRanges &ranges)
Definition: Process.cpp:6325
static bool AddDirtyPages(const MemoryRegionInfo &region, Process::CoreFileMemoryRanges &ranges)
Definition: Process.cpp:6286
#define LLDB_SCOPED_TIMER()
Definition: Timer.h:83
void Run() override
Definition: Process.cpp:4414
void SetIsRunning(bool running)
Definition: Process.cpp:4406
void Cancel() override
Definition: Process.cpp:4475
NativeFile m_read_file
Definition: Process.cpp:4529
~IOHandlerProcessSTDIO() override=default
void GotEOF() override
Definition: Process.cpp:4525
bool Interrupt() override
Definition: Process.cpp:4496
NativeFile m_write_file
Definition: Process.cpp:4530
IOHandlerProcessSTDIO(Process *process, int write_fd)
Definition: Process.cpp:4395
A windows-based implementation of Pipe, a class that abtracts unix style pipes.
const Property * GetPropertyAtIndex(size_t idx, const ExecutionContext *exe_ctx) const override
Definition: Process.cpp:95
ProcessOptionValueProperties(llvm::StringRef name)
Definition: Process.cpp:92
lldb_private::Status Select()
void FDSetRead(lldb::socket_t fd)
bool FDIsSetRead(lldb::socket_t fd) const
static lldb::ABISP FindPlugin(lldb::ProcessSP process_sp, const ArchSpec &arch)
Definition: ABI.cpp:27
A section + offset based address range class.
Definition: AddressRange.h:25
bool ContainsFileAddress(const Address &so_addr) const
Check if a section offset address is contained in this range.
A section + offset based address class.
Definition: Address.h:62
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition: Address.cpp:313
lldb::addr_t GetOpcodeLoadAddress(Target *target, AddressClass addr_class=AddressClass::eInvalid) const
Get the load address as an opcode load address.
Definition: Address.cpp:370
bool IsValid() const
Check if the object state is valid.
Definition: Address.h:355
Symbol * CalculateSymbolContextSymbol() const
Definition: Address.cpp:899
static lldb::addr_t AddressableBitToMask(uint32_t addressable_bits)
lldb::addr_t AllocateMemory(size_t byte_size, uint32_t permissions, Status &error)
Definition: Memory.cpp:386
void Clear(bool deallocate_memory)
Definition: Memory.cpp:349
bool DeallocateMemory(lldb::addr_t ptr)
Definition: Memory.cpp:417
An architecture specification class.
Definition: ArchSpec.h:31
uint32_t GetAddressByteSize() const
Returns the size in bytes of an address of the current architecture.
Definition: ArchSpec.cpp:691
bool IsValid() const
Tests if this ArchSpec is valid.
Definition: ArchSpec.h:348
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition: ArchSpec.h:450
bool IsCompatibleMatch(const ArchSpec &rhs) const
Shorthand for IsMatch(rhs, CompatibleMatch).
Definition: ArchSpec.h:502
bool IsExactMatch(const ArchSpec &rhs) const
Shorthand for IsMatch(rhs, ExactMatch).
Definition: ArchSpec.h:497
lldb::ByteOrder GetByteOrder() const
Returns the byte order for the architecture specification.
Definition: ArchSpec.cpp:738
virtual const MemoryTagManager * GetMemoryTagManager() const
Definition: Architecture.h:110
A command line argument class.
Definition: Args.h:33
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 IsEnabled() const
Tells whether the current breakpoint site is enabled or not.
void SetEnabled(bool enabled)
Sets whether the current breakpoint site is enabled or not.
An event broadcasting class.
Definition: Broadcaster.h:145
lldb::ListenerSP GetPrimaryListener()
Definition: Broadcaster.h:318
void RestoreBroadcaster()
Restore the state of the Broadcaster from a previous hijack attempt.
Definition: Broadcaster.h:303
void SetEventName(uint32_t event_mask, const char *name)
Set the name for an event bit.
Definition: Broadcaster.h:242
bool HijackBroadcaster(const lldb::ListenerSP &listener_sp, uint32_t event_mask=UINT32_MAX)
Provides a simple mechanism to temporarily redirect events from broadcaster.
Definition: Broadcaster.h:293
void BroadcastEventIfUnique(lldb::EventSP &event_sp)
Definition: Broadcaster.h:171
void SetPrimaryListener(lldb::ListenerSP listener_sp)
Definition: Broadcaster.h:314
const char * GetHijackingListenerName()
Definition: Broadcaster.h:468
void BroadcastEvent(lldb::EventSP &event_sp)
Broadcast an event which has no associated data.
Definition: Broadcaster.h:167
bool IsHijackedForEvent(uint32_t event_mask)
Definition: Broadcaster.h:298
A class that implements CRTP-based "virtual constructor" idiom.
Definition: Cloneable.h:40
bool IsConnected() const
Check if the connection is valid.
Generic representation of a type in a programming language.
Definition: CompilerType.h:36
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.
A uniqued constant string class.
Definition: ConstString.h:40
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
Definition: ConstString.h:188
An data extractor class.
Definition: DataExtractor.h:48
uint32_t GetMaxU32(lldb::offset_t *offset_ptr, size_t byte_size) const
Extract an integer of size byte_size from *offset_ptr.
uint64_t GetMaxU64(lldb::offset_t *offset_ptr, size_t byte_size) const
Extract an unsigned integer of size byte_size from *offset_ptr.
A class to manage flag bits.
Definition: Debugger.h:79
static lldb::TargetSP FindTargetWithProcessID(lldb::pid_t pid)
Definition: Debugger.cpp:798
StreamFile & GetErrorStream()
Definition: Debugger.h:156
TargetList & GetTargetList()
Get accessor for the target list.
Definition: Debugger.h:206
bool IsTopIOHandler(const lldb::IOHandlerSP &reader_sp)
Definition: Debugger.cpp:1145
bool RemoveIOHandler(const lldb::IOHandlerSP &reader_sp)
Remove the given IO handler if it's currently active.
Definition: Debugger.cpp:1175
void RunIOHandlerAsync(const lldb::IOHandlerSP &reader_sp, bool cancel_top_handler=true)
Run the given IO handler and return immediately.
Definition: Debugger.cpp:1179
lldb::StreamSP GetAsyncErrorStream()
Definition: Debugger.cpp:1283
PlatformList & GetPlatformList()
Definition: Debugger.h:208
lldb::ListenerSP GetListener()
Definition: Debugger.h:185
size_t Printf(DiagnosticSeverity severity, const char *format,...) __attribute__((format(printf
size_t void PutString(DiagnosticSeverity severity, llvm::StringRef str)
static lldb::DisassemblerSP DisassembleRange(const ArchSpec &arch, const char *plugin_name, const char *flavor, Target &target, const AddressRange &disasm_range, bool force_live_memory=false)
Encapsulates dynamic check functions used by expressions.
A plug-in interface definition class for dynamic loaders.
Definition: DynamicLoader.h:52
virtual void DidAttach()=0
Called after attaching a process.
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)
Definition: Target.h:334
void SetTryAllThreads(bool try_others=true)
Definition: Target.h:367
void SetTimeout(const Timeout< std::micro > &timeout)
Definition: Target.h:355
void SetStopOthers(bool stop_others=true)
Definition: Target.h:371
const Timeout< std::micro > & GetTimeout() const
Definition: Target.h:353
void SetIgnoreBreakpoints(bool ignore=false)
Definition: Target.h:338
const Timeout< std::micro > & GetOneThreadTimeout() const
Definition: Target.h:357
virtual llvm::StringRef GetFlavor() const =0
EventData * GetData()
Definition: Event.h:189
"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.
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.
A file utility class.
Definition: FileSpec.h:56
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition: FileSpec.cpp:367
static FileSystem & Instance()
An abstract base class for files.
Definition: File.h:36
bool Test(ValueType bit) const
Test a single flag bit.
Definition: Flags.h:96
bool GetIsOptimized()
Get whether compiler optimizations were enabled for this function.
Definition: Function.cpp:500
Status Join(lldb::thread_result_t *result)
Definition: HostThread.cpp:20
bool EqualsThread(lldb::thread_t thread) const
Definition: HostThread.cpp:44
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.
Definition: JITLoaderList.h:22
void ModulesDidLoad(ModuleList &module_list)
static void LoadPlugins(Process *process, lldb_private::JITLoaderList &list)
Find a JIT loader plugin for a given process.
Definition: JITLoader.cpp:18
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)
Definition: Language.cpp:364
static std::set< lldb::LanguageType > GetSupportedLanguages()
Definition: Language.cpp:414
static lldb::ListenerSP MakeListener(const char *name)
Definition: Listener.cpp:385
void PutCString(const char *cstr)
Definition: Log.cpp:134
void PutString(llvm::StringRef str)
Definition: Log.cpp:136
uint32_t GetMemoryCacheLineSize() const
Definition: Memory.h:34
bool RemoveInvalidRange(lldb::addr_t base_addr, lldb::addr_t byte_size)
Definition: Memory.cpp:111
void Flush(lldb::addr_t addr, size_t size)
Definition: Memory.cpp:53
void Clear(bool clear_invalid_ranges=false)
Definition: Memory.cpp:32
size_t Read(lldb::addr_t addr, void *dst, size_t dst_len, Status &error)
Definition: Memory.cpp:154
void AddInvalidRange(lldb::addr_t base_addr, lldb::addr_t byte_size)
Definition: Memory.cpp:101
static lldb::MemoryHistorySP FindPlugin(const lldb::ProcessSP process)
OptionalBool GetWritable() const
OptionalBool GetMapped() const
int GetPageSize() const
Get the target system's VM page size in bytes.
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.
OptionalBool GetReadable() const
OptionalBool GetExecutable() const
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.
Definition: ModuleList.h:103
A class that describes an executable image and its associated object and symbol files.
Definition: Module.h:88
const FileSpec & GetFileSpec() const
Get const accessor for the module file specification.
Definition: Module.h:452
A plug-in interface definition class for object file parsers.
Definition: ObjectFile.h:44
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
auto GetPropertyAtIndexAs(size_t idx, const ExecutionContext *exe_ctx=nullptr) const
Property * ProtectedGetPropertyAtIndex(size_t idx)
bool SetPropertyAtIndex(size_t idx, T t, const ExecutionContext *exe_ctx=nullptr) const
static lldb::OptionValuePropertiesSP CreateLocalCopy(const Properties &global_properties)
lldb::PlatformSP GetOrCreate(llvm::StringRef name)
Definition: Platform.cpp:2142
A plug-in interface definition class for debug platform that includes many platform abilities such as...
Definition: Platform.h:74
virtual llvm::StringRef GetPluginName()=0
static ProcessCreateInstance GetProcessCreateCallbackAtIndex(uint32_t idx)
static ProcessCreateInstance GetProcessCreateCallbackForPluginName(llvm::StringRef name)
static StructuredDataPluginCreateInstance GetStructuredDataPluginCreateCallbackAtIndex(uint32_t idx)
static LanguageSet GetAllTypeSystemSupportedLanguagesForTypes()
void SetValue(T value, PredicateBroadcastType broadcast_type)
Value set accessor.
Definition: Predicate.h:90
T GetValue() const
Value get accessor.
Definition: Predicate.h:71
std::optional< T > WaitForValueNotEqualTo(T value, const Timeout< std::micro > &timeout=std::nullopt)
Wait for m_value to not be equal to value.
Definition: Predicate.h:185
uint32_t GetResumeCount() const
Definition: Process.h:151
lldb::ListenerSP GetListenerForProcess(Debugger &debugger)
Definition: Process.cpp:2786
lldb::pid_t GetProcessID() const
Definition: ProcessInfo.h:67
FileSpec & GetExecutableFile()
Definition: ProcessInfo.h:42
bool IsScriptedProcess() const
ArchSpec & GetArchitecture()
Definition: ProcessInfo.h:61
void SetNameMatchType(NameMatch name_match_type)
Definition: ProcessInfo.h:235
ProcessInstanceInfo & GetProcessInfo()
Definition: ProcessInfo.h:225
static void DumpTableHeader(Stream &s, bool show_args, bool verbose)
void SetRunningUserExpression(bool on)
Definition: Process.h:284
uint32_t GetMemoryID() const
Definition: Process.h:250
void SetStopEventForLastNaturalStopID(lldb::EventSP event_sp)
Definition: Process.h:302
uint32_t GetStopID() const
Definition: Process.h:248
bool IsRunningUtilityFunction() const
Definition: Process.h:244
bool IsLastResumeForUserExpression() const
Definition: Process.h:268
void SetRunningUtilityFunction(bool on)
Definition: Process.h:291
bool GetDetachKeepsStopped() const
Definition: Process.cpp:289
bool GetSteppingRunsAllThreads() const
Definition: Process.cpp:332
void SetStopOnSharedLibraryEvents(bool stop)
Definition: Process.cpp:272
Args GetExtraStartupCommands() const
Definition: Process.cpp:200
std::unique_ptr< ProcessExperimentalProperties > m_experimental_properties_up
Definition: Process.h:114
FollowForkMode GetFollowForkMode() const
Definition: Process.cpp:362
uint32_t GetVirtualAddressableBits() const
Definition: Process.cpp:217
void SetIgnoreBreakpointsInExpressions(bool ignore)
Definition: Process.cpp:250
bool GetUnwindOnErrorInExpressions() const
Definition: Process.cpp:255
std::chrono::seconds GetInterruptTimeout() const
Definition: Process.cpp:325
bool GetDisableLangRuntimeUnwindPlans() const
Definition: Process.cpp:277
void SetDetachKeepsStopped(bool keep_stopped)
Definition: Process.cpp:295
void SetDisableLangRuntimeUnwindPlans(bool disable)
Definition: Process.cpp:283
std::chrono::seconds GetUtilityExpressionTimeout() const
Definition: Process.cpp:318
void SetVirtualAddressableBits(uint32_t bits)
Definition: Process.cpp:223
bool GetStopOnSharedLibraryEvents() const
Definition: Process.cpp:266
void SetHighmemVirtualAddressableBits(uint32_t bits)
Definition: Process.cpp:234
void SetOSPluginReportsAllThreads(bool does_report)
Definition: Process.cpp:352
bool GetWarningsOptimization() const
Definition: Process.cpp:300
void SetUnwindOnErrorInExpressions(bool ignore)
Definition: Process.cpp:261
bool GetDisableMemoryCache() const
Definition: Process.cpp:188
FileSpec GetPythonOSPluginPath() const
Definition: Process.cpp:212
void SetPythonOSPluginPath(const FileSpec &file)
Definition: Process.cpp:239
void SetExtraStartupCommands(const Args &args)
Definition: Process.cpp:207
bool GetOSPluginReportsAllThreads() const
Definition: Process.cpp:338
bool GetWarningsUnsupportedLanguage() const
Definition: Process.cpp:306
uint32_t GetHighmemVirtualAddressableBits() const
Definition: Process.cpp:228
bool GetIgnoreBreakpointsInExpressions() const
Definition: Process.cpp:244
uint64_t GetMemoryCacheLineSize() const
Definition: Process.cpp:194
ProcessProperties(lldb_private::Process *process)
Definition: Process.cpp:158
A class used to prevent the process from starting while other threads are accessing its data,...
EventActionResult HandleBeingInterrupted() override
Definition: Process.cpp:2778
EventActionResult PerformAction(lldb::EventSP &event_sp) override
Definition: Process.cpp:2721
AttachCompletionHandler(Process *process, uint32_t exec_count)
Definition: Process.cpp:2710
static bool GetRestartedFromEvent(const Event *event_ptr)
Definition: Process.cpp:4181
virtual bool ShouldStop(Event *event_ptr, bool &found_valid_stopinfo)
Definition: Process.cpp:3967
static void AddRestartedReason(Event *event_ptr, const char *reason)
Definition: Process.cpp:4218
void SetInterrupted(bool new_value)
Definition: Process.h:471
lldb::ProcessSP GetProcessSP() const
Definition: Process.h:421
void SetRestarted(bool new_value)
Definition: Process.h:469
static void SetRestartedInEvent(Event *event_ptr, bool new_value)
Definition: Process.cpp:4189
static lldb::ProcessSP GetProcessFromEvent(const Event *event_ptr)
Definition: Process.cpp:4165
static void SetInterruptedInEvent(Event *event_ptr, bool new_value)
Definition: Process.cpp:4235
llvm::StringRef GetFlavor() const override
Definition: Process.cpp:3963
static bool GetInterruptedFromEvent(const Event *event_ptr)
Definition: Process.cpp:4226
const char * GetRestartedReasonAtIndex(size_t idx)
Definition: Process.h:428
static bool SetUpdateStateOnRemoval(Event *event_ptr)
Definition: Process.cpp:4243
static lldb::StateType GetStateFromEvent(const Event *event_ptr)
Definition: Process.cpp:4173
lldb::StateType GetState() const
Definition: Process.h:423
static const Process::ProcessEventData * GetEventDataFromEvent(const Event *event_ptr)
Definition: Process.cpp:4154
static llvm::StringRef GetFlavorString()
Definition: Process.cpp:3959
void DoOnRemoval(Event *event_ptr) override
Definition: Process.cpp:4073
void Dump(Stream *s) const override
Definition: Process.cpp:4141
A plug-in interface definition class for debugging a process.
Definition: Process.h:340
virtual Status EnableBreakpointSite(BreakpointSite *bp_site)
Definition: Process.h:2143
Status WillAttachToProcessWithName(const char *process_name, bool wait_for_launch)
Called before attaching to a process.
Definition: Process.cpp:2801
virtual llvm::Expected< TraceSupportedResponse > TraceSupported()
Get the processor tracing type supported for this process.
Definition: Process.cpp:6157
lldb::IOHandlerSP m_process_input_reader
Definition: Process.h:3076
friend class ProcessProperties
Definition: Process.h:2331
UtilityFunction * GetLoadImageUtilityFunction(Platform *platform, llvm::function_ref< std::unique_ptr< UtilityFunction >()> factory)
Get the cached UtilityFunction that assists in loading binary images into the process.
Definition: Process.cpp:6147
virtual Status DoSignal(int signal)
Sends a process a UNIX signal signal.
Definition: Process.h:1221
virtual Status WillResume()
Called before resuming to a process.
Definition: Process.h:1112
std::mutex m_process_input_reader_mutex
Definition: Process.h:3077
lldb::addr_t m_code_address_mask
Mask for code an data addresses.
Definition: Process.h:3123
StopPointSiteList< lldb_private::BreakpointSite > & GetBreakpointSiteList()
Definition: Process.cpp:1575
std::vector< lldb::addr_t > m_image_tokens
Definition: Process.h:3059
bool PrivateStateThreadIsValid() const
Definition: Process.h:2883
virtual Status DoHalt(bool &caused_stop)
Halts a running process.
Definition: Process.h:1164
virtual void DidLaunch()
Called after launching a process.
Definition: Process.h:1104
virtual Status DisableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition: Process.cpp:1844
lldb::pid_t GetID() const
Returns the pid of the process or LLDB_INVALID_PROCESS_ID if there is no known pid.
Definition: Process.h:537
lldb::break_id_t CreateBreakpointSite(const lldb::BreakpointLocationSP &owner, bool use_hardware)
Definition: Process.cpp:1628
virtual Status WillSignal()
Called before sending a signal to a process.
Definition: Process.h:1215
void ResetImageToken(size_t token)
Definition: Process.cpp:5936
lldb::JITLoaderListUP m_jit_loaders_up
Definition: Process.h:3065
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.
Definition: Process.cpp:2302
void SetNextEventAction(Process::NextEventAction *next_event_action)
Definition: Process.h:2860
Status Destroy(bool force_kill)
Kills the process and shuts down all threads that were spawned to track and monitor the process.
Definition: Process.cpp:3298
virtual Status WillDetach()
Called before detaching from a process.
Definition: Process.h:1183
virtual Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info)
Launch a new process.
Definition: Process.h:1094
StopPointSiteList< lldb_private::BreakpointSite > m_breakpoint_site_list
This is the list of breakpoint locations we intend to insert in the target.
Definition: Process.h:3061
void ControlPrivateStateThread(uint32_t signal)
Definition: Process.cpp:3631
ThreadList & GetThreadList()
Definition: Process.h:2212
void ClearPreResumeActions()
Definition: Process.cpp:5650
virtual DataExtractor GetAuxvData()
Definition: Process.cpp:2690
Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp)
Construct with a shared pointer to a target, and the Process listener.
Definition: Process.cpp:415
lldb::ExpressionResults RunThreadPlan(ExecutionContext &exe_ctx, lldb::ThreadPlanSP &thread_plan_sp, const EvaluateExpressionOptions &options, DiagnosticManager &diagnostic_manager)
Definition: Process.cpp:4730
void PrintWarningUnsupportedLanguage(const SymbolContext &sc)
Print a user-visible warning about a function written in a language that this version of LLDB doesn't...
Definition: Process.cpp:5867
lldb::StateType GetPrivateState()
Definition: Process.cpp:1417
Status LaunchPrivate(ProcessLaunchInfo &launch_info, lldb::StateType &state, lldb::EventSP &event_sp)
Definition: Process.cpp:2498
std::vector< std::string > m_profile_data
Definition: Process.h:3085
bool m_can_interpret_function_calls
Definition: Process.h:3136
Status Resume()
Resumes all of a process's threads as configured using the Thread run control functions.
Definition: Process.cpp:1347
void PruneThreadPlans()
Prune ThreadPlanStacks for all unreported threads.
Definition: Process.cpp:1239
void SetUnixSignals(lldb::UnixSignalsSP &&signals_sp)
Definition: Process.cpp:3389
virtual void DidExit()
Definition: Process.h:1423
std::string m_stdout_data
Remember if stdin must be forwarded to remote debug server.
Definition: Process.h:3082
bool RemoveInvalidMemoryRange(const LoadRange &region)
Definition: Process.cpp:5628
uint32_t GetNextThreadIndexID(uint64_t thread_id)
Definition: Process.cpp:1277
Status PrivateResume()
The "private" side of resuming a process.
Definition: Process.cpp:3092
void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers)
Definition: Process.cpp:1571
enum lldb_private::Process::@32 m_can_jit
void AddInvalidMemoryRegion(const LoadRange &region)
Definition: Process.cpp:5624
virtual void ModulesDidLoad(ModuleList &module_list)
Definition: Process.cpp:5825
InstrumentationRuntimeCollection m_instrumentation_runtimes
Definition: Process.h:3093
std::atomic< bool > m_destructing
Definition: Process.h:3111
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...
Definition: Process.h:2795
int GetExitStatus()
Get the exit status for a process.
Definition: Process.cpp:1040
OperatingSystem * GetOperatingSystem()
Definition: Process.h:2357
Status WillAttachToProcessWithID(lldb::pid_t pid)
Called before attaching to a process.
Definition: Process.cpp:2797
virtual Status DoDetach(bool keep_stopped)
Detaches from a running or stopped process.
Definition: Process.h:1190
std::unique_ptr< UtilityFunction > m_dlopen_utility_func_up
Definition: Process.h:3144
void SetRunningUtilityFunction(bool on)
Definition: Process.cpp:1490
void DisableAllBreakpointSites()
Definition: Process.cpp:1584
int64_t ReadSignedIntegerFromMemory(lldb::addr_t load_addr, size_t byte_size, int64_t fail_value, Status &error)
Definition: Process.cpp:2090
Address AdvanceAddressToNextBranchInstruction(Address default_stop_addr, AddressRange range_bounds)
Find the next branch instruction to set a breakpoint on.
Definition: Process.cpp:5942
virtual bool GetLoadAddressPermissions(lldb::addr_t load_addr, uint32_t &permissions)
Attempt to get the attributes for a region of memory in the process.
Definition: Process.cpp:2407
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.
Definition: Process.cpp:718
virtual size_t GetAsyncProfileData(char *buf, size_t buf_size, Status &error)
Get any available profile data.
Definition: Process.cpp:4324
lldb::addr_t FixDataAddress(lldb::addr_t pc)
Definition: Process.cpp:5747
lldb::addr_t AllocateMemory(size_t size, uint32_t permissions, Status &error)
The public interface to allocating memory in the process.
Definition: Process.cpp:2279
std::unique_ptr< NextEventAction > m_next_event_action_up
Definition: Process.h:3094
void SetHighmemDataAddressMask(lldb::addr_t data_address_mask)
Definition: Process.cpp:5734
bool PruneThreadPlansForTID(lldb::tid_t tid)
Prune ThreadPlanStacks for unreported threads.
Definition: Process.cpp:1235
virtual void DidDetach()
Called after detaching from a process.
Definition: Process.h:1202
void PausePrivateStateThread()
Definition: Process.cpp:3612
HostThread m_private_state_thread
Thread ID for the thread that watches internal state events.
Definition: Process.h:3021
Status EnableBreakpointSiteByID(lldb::user_id_t break_id)
Definition: Process.cpp:1614
size_t ReadMemoryFromInferior(lldb::addr_t vm_addr, void *buf, size_t size, Status &error)
Read of memory from a process.
Definition: Process.cpp:2050
size_t ReadScalarIntegerFromMemory(lldb::addr_t addr, uint32_t byte_size, bool is_signed, Scalar &scalar, Status &error)
Definition: Process.cpp:2237
virtual Status Launch(ProcessLaunchInfo &launch_info)
Launch a new process.
Definition: Process.cpp:2466
std::mutex m_run_thread_plan_lock
Definition: Process.h:3139
static void SettingsInitialize()
Definition: Process.cpp:4593
void BroadcastStructuredData(const StructuredData::ObjectSP &object_sp, const lldb::StructuredDataPluginSP &plugin_sp)
Broadcasts the given structured data object from the given plugin.
Definition: Process.cpp:4308
void Flush()
Flush all data in the process.
Definition: Process.cpp:5675
bool m_clear_thread_plans_on_stop
Definition: Process.h:3129
virtual Status DoResume()
Resumes all of a process's threads as configured using the Thread run control functions.
Definition: Process.h:1129
ProcessRunLock m_public_run_lock
Definition: Process.h:3096
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.
Definition: Process.cpp:2004
void ResumePrivateStateThread()
Definition: Process.cpp:3616
void MapSupportedStructuredDataPlugins(const StructuredData::Array &supported_type_names)
Loads any plugins associated with asynchronous structured data and maps the relevant supported type n...
Definition: Process.cpp:6042
bool GetEventsPrivate(lldb::EventSP &event_sp, const Timeout< std::micro > &timeout, bool control_only)
Definition: Process.cpp:1023
lldb::ABISP m_abi_sp
This is the current signal set for this process.
Definition: Process.h:3075
virtual void DidSignal()
Called after sending a signal to a process.
Definition: Process.h:1241
virtual SystemRuntime * GetSystemRuntime()
Get the system runtime plug-in for this process.
Definition: Process.cpp:2704
std::map< uint64_t, uint32_t > m_thread_id_to_index_id_map
Definition: Process.h:3030
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.
Definition: Process.cpp:1243
lldb::ListenerSP m_private_state_listener_sp
Definition: Process.h:3019
uint32_t m_extended_thread_stop_id
The natural stop id when extended_thread_list was last updated.
Definition: Process.h:3049
static constexpr llvm::StringRef ResumeSynchronousHijackListenerName
Definition: Process.h:389
bool WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value, Status &error)
Definition: Process.cpp:2109
QueueList m_queue_list
The list of libdispatch queues at a given stop point.
Definition: Process.h:3052
void ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
Definition: Process.cpp:5652
virtual Status WillDestroy()
Definition: Process.h:1229
lldb::ThreadSP CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context)
Definition: Process.cpp:1270
std::vector< PreResumeCallbackAndBaton > m_pre_resume_actions
Definition: Process.h:3095
void SetCanJIT(bool can_jit)
Sets whether executing JIT-compiled code in this process is possible.
Definition: Process.cpp:2341
lldb::StateType GetStateChangedEventsPrivate(lldb::EventSP &event_sp, const Timeout< std::micro > &timeout)
Definition: Process.cpp:1005
void LoadOperatingSystemPlugin(bool flush)
Definition: Process.cpp:2457
lldb::StructuredDataPluginSP GetStructuredDataPlugin(llvm::StringRef type_name) const
Returns the StructuredDataPlugin associated with a given type name, if there is one.
Definition: Process.cpp:4316
lldb::DynamicLoaderUP m_dyld_up
Definition: Process.h:3064
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.
Definition: Process.cpp:5919
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.
Definition: Process.h:1672
virtual Status WriteObjectFile(std::vector< ObjectFile::LoadableData > entries)
Definition: Process.cpp:2267
std::recursive_mutex m_stdio_communication_mutex
Definition: Process.h:3079
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.
Definition: Process.cpp:369
StopPointSiteList< lldb_private::WatchpointResource > m_watchpoint_resource_list
Watchpoint resources currently in use.
Definition: Process.h:3056
Status DisableBreakpointSiteByID(lldb::user_id_t break_id)
Definition: Process.cpp:1600
llvm::Expected< const MemoryTagManager * > GetMemoryTagManager()
If this architecture and process supports memory tagging, return a tag manager that can be used to ma...
Definition: Process.cpp:6222
~Process() override
Destructor.
Definition: Process.cpp:502
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.
Definition: Process.h:2983
std::recursive_mutex m_profile_data_comm_mutex
Definition: Process.h:3084
lldb::InstrumentationRuntimeSP GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type)
Definition: Process.cpp:5910
Status ResumeSynchronous(Stream *stream)
Resume a process, and wait for it to stop.
Definition: Process.cpp:1364
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.
Definition: Process.cpp:5753
lldb::thread_result_t RunPrivateStateThread(bool is_secondary_thread)
Definition: Process.cpp:3814
virtual Status DoWillLaunch(Module *module)
Called before launching to a process.
Definition: Process.h:1075
virtual Status ConnectRemote(llvm::StringRef remote_url)
Attach to a remote system via a URL.
Definition: Process.cpp:3057
void AppendSTDOUT(const char *s, size_t len)
Definition: Process.cpp:4287
llvm::StringMap< lldb::StructuredDataPluginSP > m_structured_data_plugin_map
Definition: Process.h:3140
virtual Status DisableBreakpointSite(BreakpointSite *bp_site)
Definition: Process.h:2150
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)
Definition: Process.cpp:5578
void CalculateExecutionContext(ExecutionContext &exe_ctx) override
Reconstruct the object's execution context into sc.
Definition: Process.cpp:4255
virtual size_t ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size, Status &error)
Read of memory from a process.
Definition: Process.cpp:1938
Event * PeekAtStateChangedEvents()
Definition: Process.cpp:985
std::vector< Notifications > m_notifications
The list of notifications that this process can deliver.
Definition: Process.h:3057
bool HasAssignedIndexIDToThread(uint64_t sb_thread_id)
Definition: Process.cpp:1281
ThreadSafeValue< lldb::StateType > m_private_state
Definition: Process.h:3011
void StopPrivateStateThread()
Definition: Process.cpp:3620
size_t AddImageToken(lldb::addr_t image_ptr)
Definition: Process.cpp:5925
virtual bool DestroyRequiresHalt()
Definition: Process.h:1235
lldb::EventSP CreateEventFromProcessState(uint32_t event_type)
Definition: Process.cpp:4281
lldb::TargetSP CalculateTarget() override
Definition: Process.cpp:4253
void SetHighmemCodeAddressMask(lldb::addr_t code_address_mask)
Definition: Process.cpp:5727
lldb::ByteOrder GetByteOrder() const
Definition: Process.cpp:3399
Status Detach(bool keep_stopped)
Detaches from a running or stopped process.
Definition: Process.cpp:3246
void UpdateThreadListIfNeeded()
Definition: Process.cpp:1144
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.
Definition: Process.cpp:6241
virtual void DidResume()
Called after resuming a process.
Definition: Process.h:1139
virtual void DidExec()
Called after a process re-execs itself.
Definition: Process.cpp:5759
void SetCodeAddressMask(lldb::addr_t code_address_mask)
Definition: Process.cpp:5715
AllocatedMemoryCache m_allocated_memory_cache
Definition: Process.h:3088
virtual Status LoadCore()
Definition: Process.cpp:2633
std::mutex m_exit_status_mutex
Mutex so m_exit_status m_exit_string can be safely accessed from multiple threads.
Definition: Process.h:3033
Status Signal(int signal)
Sends a process a UNIX signal signal.
Definition: Process.cpp:3379
void SetDynamicLoader(lldb::DynamicLoaderUP dyld)
Definition: Process.cpp:2686
ThreadPlanStackMap m_thread_plans
This is the list of thread plans for threads in m_thread_list, as well as threads we knew existed,...
Definition: Process.h:3042
std::recursive_mutex m_thread_mutex
Definition: Process.h:3035
virtual Status ConfigureStructuredData(llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp)
Configure asynchronous structured data feature.
Definition: Process.cpp:6034
virtual Status DoWillAttachToProcessWithName(const char *process_name, bool wait_for_launch)
Called before attaching to a process.
Definition: Process.h:971
bool StartPrivateStateThread(bool is_secondary_thread=false)
Definition: Process.cpp:3561
void HandlePrivateEvent(lldb::EventSP &event_sp)
Definition: Process.cpp:3689
void BroadcastAsyncProfileData(const std::string &one_profile_data)
Definition: Process.cpp:4301
lldb::StateType GetState()
Get accessor for the current process state.
Definition: Process.cpp:1300
virtual Status DoWillAttachToProcessWithID(lldb::pid_t pid)
Called before attaching to a process.
Definition: Process.h:954
ProcessRunLock & GetRunLock()
Definition: Process.cpp:5662
virtual Status DoLoadCore()
Definition: Process.h:615
Predicate< uint32_t > m_iohandler_sync
Definition: Process.h:3086
LanguageRuntimeCollection m_language_runtimes
Should we detach if the process object goes away with an explicit call to Kill or Detach?
Definition: Process.h:3091
virtual Status GetMemoryRegions(lldb_private::MemoryRegionInfos &region_list)
Obtain all the mapped memory regions within this process.
Definition: Process.cpp:5997
size_t WriteMemoryPrivate(lldb::addr_t addr, const void *buf, size_t size, Status &error)
Definition: Process.cpp:2121
void GetStatus(Stream &ostrm)
Definition: Process.cpp:5558
void SetRunningUserExpression(bool on)
Definition: Process.cpp:1486
bool IsPossibleDynamicValue(ValueObject &in_value)
Definition: Process.cpp:1550
static bool SetProcessExitStatus(lldb::pid_t pid, bool exited, int signo, int status)
Static function that can be used with the host function Host::StartMonitoringChildProcess ().
Definition: Process.cpp:1112
void RemoveConstituentFromBreakpointSite(lldb::user_id_t site_id, lldb::user_id_t constituent_id, lldb::BreakpointSiteSP &bp_site_sp)
Definition: Process.cpp:1718
lldb::OperatingSystemUP m_os_up
Definition: Process.h:3071
uint32_t GetLastNaturalStopID() const
Definition: Process.h:1483
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)
Definition: Process.cpp:650
lldb::UnixSignalsSP m_unix_signals_sp
Definition: Process.h:3074
bool StateChangedIsHijackedForSynchronousResume()
Definition: Process.cpp:1408
const char * GetExitDescription()
Get a textual description of what the process exited.
Definition: Process.cpp:1048
void SetPublicState(lldb::StateType new_state, bool restarted)
Definition: Process.cpp:1307
void SetDataAddressMask(lldb::addr_t data_address_mask)
Definition: Process.cpp:5721
virtual Status DoConnectRemote(llvm::StringRef remote_url)
Attach to a remote system via a URL.
Definition: Process.h:983
bool() PreResumeActionCallback(void *)
Definition: Process.h:2496
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.
Definition: Process.cpp:2079
llvm::once_flag m_dlopen_utility_func_flag_once
Definition: Process.h:3145
virtual void UpdateQueueListIfNeeded()
Definition: Process.cpp:1257
virtual Status UpdateAutomaticSignalFiltering()
Definition: Process.cpp:6141
virtual lldb::addr_t GetImageInfoAddress()
Get the image information address for the current process.
Definition: Process.cpp:1494
std::map< lldb::addr_t, lldb::addr_t > m_resolved_indirect_addresses
This helps with the Public event coalescing in ShouldBroadcastEvent.
Definition: Process.h:3134
virtual Status DoAttachToProcessWithID(lldb::pid_t pid, const ProcessAttachInfo &attach_info)
Attach to an existing process using a process ID.
Definition: Process.h:1003
void SetCanRunCode(bool can_run_code)
Sets whether executing code in this process is possible.
Definition: Process.cpp:2345
Status ClearBreakpointSiteByID(lldb::user_id_t break_id)
Definition: Process.cpp:1591
virtual Status EnableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition: Process.cpp:1768
void AppendSTDERR(const char *s, size_t len)
Definition: Process.cpp:4294
bool GetShouldDetach() const
Definition: Process.h:780
Status CalculateCoreFileSaveRanges(lldb::SaveCoreStyle core_style, CoreFileMemoryRanges &ranges)
Helper function for Process::SaveCore(...) that calculates the address ranges that should be saved.
Definition: Process.cpp:6420
uint32_t m_thread_index_id
Each thread is created with a 1 based index that won't get re-used.
Definition: Process.h:3028
bool ProcessIOHandlerExists() const
Definition: Process.h:3211
bool RouteAsyncStructuredData(const StructuredData::ObjectSP object_sp)
Route the incoming structured data dictionary to the right plugin.
Definition: Process.cpp:6112
virtual void DidDestroy()
Definition: Process.h:1233
lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error)
Definition: Process.cpp:2101
static const char * ExecutionResultAsCString(lldb::ExpressionResults result)
Definition: Process.cpp:5521
Broadcaster m_private_state_control_broadcaster
Definition: Process.h:3015
lldb::addr_t GetHighmemCodeAddressMask()
The highmem masks are for targets where we may have different masks for low memory versus high memory...
Definition: Process.cpp:5697
bool IsRunning() const
Definition: Process.cpp:1036
size_t RemoveBreakpointOpcodesFromBuffer(lldb::addr_t addr, size_t size, uint8_t *buf) const
Definition: Process.cpp:1731
Broadcaster m_private_state_broadcaster
Definition: Process.h:3012
virtual bool DetachRequiresHalt()
Definition: Process.h:1204
virtual bool IsAlive()
Check if a process is still alive.
Definition: Process.cpp:1092
ThreadList m_thread_list_real
The threads for this process as are known to the protocol we are debugging with.
Definition: Process.h:3036
ThreadSafeValue< lldb::StateType > m_public_state
Definition: Process.h:3009
lldb::addr_t m_data_address_mask
Definition: Process.h:3124
virtual ArchSpec GetSystemArchitecture()
Get the system architecture for this process.
Definition: Process.h:746
Status DeallocateMemory(lldb::addr_t ptr)
The public interface to deallocating memory in the process.
Definition: Process.cpp:2350
virtual Status DisableWatchpoint(lldb::WatchpointSP wp_sp, bool notify=true)
Definition: Process.cpp:2429
void RegisterNotificationCallbacks(const Process::Notifications &callbacks)
Register for process and thread notifications.
Definition: Process.cpp:578
virtual void DidAttach(ArchSpec &process_arch)
Called after attaching a process.
Definition: Process.h:1041
virtual lldb::addr_t ResolveIndirectFunction(const Address *address, Status &error)
Resolve dynamically loaded indirect functions.
Definition: Process.cpp:5795
lldb::StateType m_last_broadcast_state
Definition: Process.h:3131
LanguageRuntime * GetLanguageRuntime(lldb::LanguageType language)
Definition: Process.cpp:1522
ProcessModID m_mod_id
Tracks the state of the process over stops and other alterations.
Definition: Process.h:3023
void SetID(lldb::pid_t new_pid)
Sets the stored pid.
Definition: Process.h:542
virtual JITLoaderList & GetJITLoaders()
Definition: Process.cpp:2696
uint32_t AssignIndexIDToThread(uint64_t thread_id)
Definition: Process.cpp:1286
virtual bool SetExitStatus(int exit_status, llvm::StringRef exit_string)
Set accessor for the process exit status (return code).
Definition: Process.cpp:1056
uint32_t m_queue_list_stop_id
The natural stop id when queue list was last fetched.
Definition: Process.h:3053
void PrintWarningOptimization(const SymbolContext &sc)
Print a user-visible warning about a module being built with optimization.
Definition: Process.cpp:5859
@ eBroadcastInternalStateControlResume
Definition: Process.h:369
@ eBroadcastInternalStateControlStop
Definition: Process.h:367
@ eBroadcastInternalStateControlPause
Definition: Process.h:368
ProcessRunLock m_private_run_lock
Definition: Process.h:3097
virtual std::optional< bool > DoGetWatchpointReportedAfter()
Provide an override value in the subclass for lldb's CPU-based logic for whether watchpoint exception...
Definition: Process.h:2814
static ProcessProperties & GetGlobalProperties()
Definition: Process.cpp:513
lldb::addr_t m_highmem_code_address_mask
Definition: Process.h:3125
lldb::addr_t GetImagePtrFromToken(size_t token) const
Definition: Process.cpp:5930
int m_exit_status
The exit status of the process, or -1 if not set.
Definition: Process.h:3031
std::vector< LanguageRuntime * > GetLanguageRuntimes()
Definition: Process.cpp:1502
MemoryCache m_memory_cache
Definition: Process.h:3087
static void STDIOReadThreadBytesReceived(void *baton, const void *src, size_t src_len)
Definition: Process.cpp:4387
virtual bool GetProcessInfo(ProcessInstanceInfo &info)
Definition: Process.cpp:5883
virtual void DidHalt()
Called after halting a process.
Definition: Process.h:1174
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...
Definition: Process.cpp:5741
lldb::StateType WaitForProcessStopPrivate(lldb::EventSP &event_sp, const Timeout< std::micro > &timeout)
Definition: Process.cpp:2436
void RestoreProcessEvents()
Restores the process event broadcasting to its normal state.
Definition: Process.cpp:959
virtual bool SupportsMemoryTagging()
Check whether the process supports memory tagging.
Definition: Process.h:2939
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.
Definition: Process.cpp:1250
uint32_t GetAddressByteSize() const
Definition: Process.cpp:3403
uint32_t GetStopID() const
Definition: Process.h:1475
void SetPrivateState(lldb::StateType state)
Definition: Process.cpp:1419
lldb::addr_t m_highmem_data_address_mask
Definition: Process.h:3126
virtual Status DoDestroy()=0
Status StopForDestroyOrDetach(lldb::EventSP &exit_event_sp)
Definition: Process.cpp:3193
bool GetWatchpointReportedAfter()
Whether lldb will be notified about watchpoints after the instruction has completed executing,...
Definition: Process.cpp:2370
lldb::StateType GetNextEvent(lldb::EventSP &event_sp)
Definition: Process.cpp:618
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.
Definition: Process.h:2958
bool StateChangedIsExternallyHijacked()
Definition: Process.cpp:1399
virtual size_t GetSTDERR(char *buf, size_t buf_size, Status &error)
Get any available STDERR.
Definition: Process.cpp:4368
size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, Status &error)
Write memory to a process.
Definition: Process.cpp:2137
virtual llvm::Expected< bool > SaveCore(llvm::StringRef outfile)
Save core dump into the specified file.
Definition: Process.cpp:2692
bool ProcessIOHandlerIsActive()
Definition: Process.cpp:4556
Status DestroyImpl(bool force_kill)
Definition: Process.cpp:3306
bool m_force_next_event_delivery
Definition: Process.h:3130
lldb::SystemRuntimeUP m_system_runtime_up
Definition: Process.h:3072
virtual Status WillHalt()
Called before halting to a process.
Definition: Process.h:1147
bool ShouldBroadcastEvent(Event *event_ptr)
This is the part of the event handling that for a process event.
Definition: Process.cpp:3407
virtual DynamicLoader * GetDynamicLoader()
Get the dynamic loader plug-in for this process.
Definition: Process.cpp:2680
std::string m_exit_string
A textual description of why a process exited.
Definition: Process.h:3032
lldb::DynamicCheckerFunctionsUP m_dynamic_checkers_up
The functions used by the expression parser to validate data that expressions use.
Definition: Process.h:3066
void SyncIOHandler(uint32_t iohandler_id, const Timeout< std::micro > &timeout)
Waits for the process state to be running within a given msec timeout.
Definition: Process.cpp:629
void ForceNextEventDelivery()
Definition: Process.h:2889
ThreadPlanStack * FindThreadPlans(lldb::tid_t tid)
Find the thread plan stack associated with thread with tid.
Definition: Process.cpp:1231
std::vector< CoreFileMemoryRange > CoreFileMemoryRanges
Definition: Process.h:733
void SetSTDIOFileDescriptor(int file_descriptor)
Definition: Process.cpp:4537
virtual Status Attach(ProcessAttachInfo &attach_info)
Attach to an existing process using the process attach info.
Definition: Process.cpp:2806
virtual void Finalize(bool destructing)
This object is about to be destroyed, do any necessary cleanup.
Definition: Process.cpp:521
lldb::addr_t GetDataAddressMask()
Definition: Process.cpp:5690
void SynchronouslyNotifyStateChanged(lldb::StateType state)
Definition: Process.cpp:597
bool CanJIT()
Determines whether executing JIT-compiled code in this process is possible.
Definition: Process.cpp:2312
static ConstString & GetStaticBroadcasterClass()
Definition: Process.cpp:410
virtual Status DoAttachToProcessWithName(const char *process_name, const ProcessAttachInfo &attach_info)
Attach to an existing process using a partial process name.
Definition: Process.h:1026
ThreadList m_thread_list
The threads for this process as the user will see them.
Definition: Process.h:3038
bool UpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list)
Update the thread list.
Definition: Process.cpp:1138
const lldb::UnixSignalsSP & GetUnixSignals()
Definition: Process.cpp:3394
Status WriteMemoryTags(lldb::addr_t addr, size_t len, const std::vector< lldb::addr_t > &tags)
Write memory tags for a range of memory.
Definition: Process.cpp:6257
virtual size_t DoReadMemory(lldb::addr_t vm_addr, void *buf, size_t size, Status &error)=0
Actually do the reading of memory from a process.
virtual bool IsLiveDebugSession() const
Definition: Process.h:1518
std::weak_ptr< Target > m_target_wp
The target that owns this process.
Definition: Process.h:3007
virtual void DoDidExec()
Subclasses of Process should implement this function if they need to do anything after a process exec...
Definition: Process.h:1053
virtual void RefreshStateAfterStop()=0
Currently called as part of ShouldStop.
lldb::addr_t GetCodeAddressMask()
Get the current address mask in the Process.
Definition: Process.cpp:5683
bool UnregisterNotificationCallbacks(const Process::Notifications &callbacks)
Unregister for process and thread notifications.
Definition: Process.cpp:584
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...
Definition: Process.cpp:951
virtual Status DoDeallocateMemory(lldb::addr_t ptr)
Actually deallocate memory in the process.
Definition: Process.h:2023
Status GetMemoryRegionInfo(lldb::addr_t load_addr, MemoryRegionInfo &range_info)
Locate the memory region that contains load_addr.
Definition: Process.cpp:5990
static void SettingsTerminate()
Definition: Process.cpp:4595
lldb::addr_t GetHighmemDataAddressMask()
Definition: Process.cpp:5706
ThreadList m_extended_thread_list
Constituent for extended threads that may be generated, cleared on natural stops.
Definition: Process.h:3047
bool CallVoidArgVoidPtrReturn(const Address *address, lldb::addr_t &returned_func, bool trap_exceptions=false)
Definition: Process.cpp:6164
bool CurrentThreadIsPrivateStateThread()
Definition: Process.cpp:5669
void AddPreResumeAction(PreResumeActionCallback callback, void *baton)
Definition: Process.cpp:5633
size_t GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site)
Definition: Process.cpp:1761
Status Halt(bool clear_thread_plans=false, bool use_run_lock=true)
Halts a running process.
Definition: Process.cpp:3148
const lldb::ABISP & GetABI()
Definition: Process.cpp:1496
Status WillLaunch(Module *module)
Called before launching to a process.
Definition: Process.cpp:2793
lldb::ModuleSP ReadModuleFromMemory(const FileSpec &file_spec, lldb::addr_t header_addr, size_t size_to_read=512)
Definition: Process.cpp:2387
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.
Definition: Process.cpp:2219
virtual size_t GetSTDOUT(char *buf, size_t buf_size, Status &error)
Get any available STDOUT.
Definition: Process.cpp:4349
lldb::ThreadCollectionSP GetHistoryThreads(lldb::addr_t addr)
Definition: Process.cpp:5893
lldb::StateType GetStateChangedEvents(lldb::EventSP &event_sp, const Timeout< std::micro > &timeout, lldb::ListenerSP hijack_listener)
Definition: Process.cpp:961
ThreadedCommunication m_stdio_communication
Definition: Process.h:3078
virtual lldb::addr_t DoAllocateMemory(size_t size, uint32_t permissions, Status &error)
Actually allocate memory in the process.
Definition: Process.h:1755
std::atomic< bool > m_finalizing
This is set at the beginning of Process::Finalize() to stop functions from looking up or creating thi...
Definition: Process.h:3106
std::recursive_mutex m_language_runtimes_mutex
Definition: Process.h:3092
std::string m_stderr_data
Definition: Process.h:3083
Target & GetTarget()
Get the target object pointer for this module.
Definition: Process.h:1276
virtual Status EnableWatchpoint(lldb::WatchpointSP wp_sp, bool notify=true)
Definition: Process.cpp:2423
lldb::OptionValuePropertiesSP m_collection_sp
static llvm::StringRef GetExperimentalSettingsName()
bool SetPropertyAtIndex(uint32_t idx, T t, const ExecutionContext *exe_ctx=nullptr) const
virtual lldb::OptionValuePropertiesSP GetValueProperties() const
const lldb::OptionValueSP & GetValue() const
Definition: Property.h:45
uint32_t GetSize()
Get the number of libdispatch queues that are available.
Definition: QueueList.cpp:21
void Clear()
Clear out the list of queues from the QueueList.
Definition: QueueList.cpp:35
uint64_t GetPC(uint64_t fail_value=LLDB_INVALID_ADDRESS)
size_t GetByteSize() const
Definition: Scalar.cpp:132
bool SignExtend(uint32_t bit_pos)
Definition: Scalar.cpp:746
unsigned long long ULongLong(unsigned long long fail_value=0) const
Definition: Scalar.cpp:335
size_t GetAsMemoryData(void *dst, size_t dst_len, lldb::ByteOrder dst_byte_order, Status &error) const
Definition: Scalar.cpp:774
long long SLongLong(long long fail_value=0) const
Definition: Scalar.cpp:331
This base class provides an interface to stack frames.
Definition: StackFrame.h:42
void CalculateExecutionContext(ExecutionContext &exe_ctx) override
Reconstruct the object's execution context into sc.
bool IsValid() const
Definition: StackID.h:47
An error handling class.
Definition: Status.h:44
void Clear()
Clear the object state.
Definition: Status.cpp:167
bool Fail() const
Test for error condition.
Definition: Status.cpp:181
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition: Status.cpp:130
void SetErrorString(llvm::StringRef err_str)
Set the current error string to err_str.
Definition: Status.cpp:233
bool Success() const
Test for success condition.
Definition: Status.cpp:279
static lldb::ValueObjectSP GetCrashingDereference(lldb::StopInfoSP &stop_info_sp, lldb::addr_t *crashing_address=nullptr)
Definition: StopInfo.cpp:1456
StopPointSite::SiteID Add(const StopPointSiteSP &site_sp)
Add a site to the list.
void ForEach(std::function< void(StopPointSite *)> const &callback)
bool FindInRange(lldb::addr_t lower_bound, lldb::addr_t upper_bound, StopPointSiteList &bp_site_list) const
StopPointSiteSP FindByID(typename StopPointSite::SiteID site_id)
Returns a shared pointer to the site with id site_id.
bool Remove(typename StopPointSite::SiteID site_id)
Removes the site given by site_id from this list.
StopPointSiteSP FindByAddress(lldb::addr_t addr)
Returns a shared pointer to the site at address addr.
bool RemoveByAddress(lldb::addr_t addr)
Removes the site at address addr from this list.
lldb::break_id_t GetID() const
Definition: StoppointSite.h:45
virtual lldb::addr_t GetLoadAddress() const
Definition: StoppointSite.h:27
uint32_t GetByteSize() const
Definition: StoppointSite.h:31
const char * GetData() const
Definition: StreamString.h:43
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition: Stream.h:28
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition: Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition: Stream.cpp:65
bool ForEach(std::function< bool(Object *object)> const &foreach_callback) const
bool GetValueForKeyAsString(llvm::StringRef key, llvm::StringRef &result) const
std::shared_ptr< Object > ObjectSP
Defines a symbol context baton that can be handed other debug core functions.
Definition: SymbolContext.h:34
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
Definition: Symbol.cpp:545
bool IsIndirect() const
Definition: Symbol.cpp:227
ConstString GetName() const
Definition: Symbol.cpp:552
Address GetAddress() const
Definition: Symbol.h:88
A plug-in interface definition class for system runtimes.
Definition: SystemRuntime.h:43
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
Definition: TargetList.cpp:507
lldb::TargetSP GetSelectedTarget()
Definition: TargetList.cpp:544
bool SetPreferDynamicValue(lldb::DynamicValueType d)
Definition: Target.cpp:4271
lldb::DynamicValueType GetPreferDynamicValue() const
Definition: Target.cpp:4264
Module * GetExecutableModulePointer()
Definition: Target.cpp:1436
void UpdateSignalsFromDummy(lldb::UnixSignalsSP signals_sp, lldb::StreamSP warning_stream_sp)
Updates the signals in signals_sp using the stored dummy signals.
Definition: Target.cpp:3630
Debugger & GetDebugger()
Definition: Target.h:1055
void ClearModules(bool delete_locations)
Definition: Target.cpp:1458
Architecture * GetArchitecturePlugin() const
Definition: Target.h:1053
TargetStats & GetStatistics()
Definition: Target.h:1607
bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform=false, bool merge=true)
Set the architecture for this target.
Definition: Target.cpp:1538
llvm::Expected< lldb::TypeSystemSP > GetScratchTypeSystemForLanguage(lldb::LanguageType language, bool create_on_demand=true)
Definition: Target.cpp:2414
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
Definition: Target.cpp:1422
void DidExec()
Called as the last function in Process::DidExec().
Definition: Target.cpp:1465
Status Install(ProcessLaunchInfo *launch_info)
Definition: Target.cpp:3063
lldb::PlatformSP GetPlatform()
Definition: Target.h:1433
const ArchSpec & GetArchitecture() const
Definition: Target.h:1014
void SetExecutableModule(lldb::ModuleSP &module_sp, LoadDependentFiles load_dependent_files=eLoadDependentsDefault)
Set the main executable module.
Definition: Target.cpp:1471
void SetPlatform(const lldb::PlatformSP &platform_sp)
Definition: Target.h:1435
A RAII-friendly terminal state saving/restoring class.
Definition: Terminal.h:87
llvm::Error SetEcho(bool enabled)
Definition: Terminal.cpp:76
llvm::Error SetCanonical(bool enabled)
Definition: Terminal.cpp:92
void AddThread(const lldb::ThreadSP &thread_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()
Definition: ThreadList.cpp:684
bool ShouldStop(Event *event_ptr)
Definition: ThreadList.cpp:226
Vote ShouldReportStop(Event *event_ptr)
Definition: ThreadList.cpp:376
uint32_t GetStopID() const
Definition: ThreadList.cpp:79
uint32_t GetSize(bool can_update=true)
Definition: ThreadList.cpp:83
bool SetSelectedThreadByID(lldb::tid_t tid, bool notify=false)
Definition: ThreadList.cpp:696
lldb::ThreadSP FindThreadByIndexID(uint32_t index_id, bool can_update=true)
Definition: ThreadList.cpp:209
Vote ShouldReportRun(Event *event_ptr)
Definition: ThreadList.cpp:436
void SetStopID(uint32_t stop_id)
Definition: ThreadList.cpp:81
lldb::ThreadSP GetThreadAtIndex(uint32_t idx, bool can_update=true)
Definition: ThreadList.cpp:91
std::recursive_mutex & GetMutex() const override
Definition: ThreadList.cpp:786
lldb::ThreadSP GetExpressionExecutionThread()
Definition: ThreadList.cpp:60
void Update(ThreadList &rhs)
Definition: ThreadList.cpp:737
bool WillResume()
The thread list asks tells all the threads it is about to resume.
Definition: ThreadList.cpp:512
void SetShouldReportStop(Vote vote)
Definition: ThreadList.cpp:425
void ClearThreadCache()
Clear the Thread* cache that each ThreadPlan contains.
void DumpPlans(Stream &strm, lldb::DescriptionLevel desc_level, bool internal, bool ignore_boring, bool skip_unreported)
bool PrunePlansForTID(lldb::tid_t tid)
ThreadPlanStack * Find(lldb::tid_t tid)
void Update(ThreadList &current_threads, bool delete_missing, bool check_for_new=true)
bool DumpPlansForTID(Stream &strm, lldb::tid_t tid, lldb::DescriptionLevel desc_level, bool internal, bool ignore_boring, bool skip_unreported)
void SetValue(const T &value)
const T & GetValueNoLock() const
void SetValueNoLock(const T &value)
std::recursive_mutex & GetMutex()
bool IsThreadPlanDone(ThreadPlan *plan) const
Checks whether the given plan is in the completed plans for this stop.
Definition: Thread.cpp:1140
virtual lldb::StackFrameSP GetStackFrameAtIndex(uint32_t idx)
Definition: Thread.h:405
Status QueueThreadPlan(lldb::ThreadPlanSP &plan_sp, bool abort_other_plans)
Queues a generic thread plan.
Definition: Thread.cpp:1156
bool WasThreadPlanDiscarded(ThreadPlan *plan) const
Checks whether the given plan is in the discarded plans for this stop.
Definition: Thread.cpp:1144
virtual lldb::RegisterContextSP GetRegisterContext()=0
static void SettingsInitialize()
Definition: Thread.cpp:1644
virtual lldb::StopInfoSP GetPrivateStopInfo(bool calculate=true)
Definition: Thread.cpp:379
uint32_t GetIndexID() const
Definition: Thread.cpp:1388
size_t GetStackFrameStatus(Stream &strm, uint32_t first_frame, uint32_t num_frames, bool show_frame_info, uint32_t num_frames_with_source)
Definition: Thread.cpp:1881
lldb::StackFrameSP GetSelectedFrame(SelectMostRelevant select_most_relevant)
Definition: Thread.cpp:265
uint32_t SetSelectedFrame(lldb_private::StackFrame *frame, bool broadcast=false)
Definition: Thread.cpp:273
static void SettingsTerminate()
Definition: Thread.cpp:1646
virtual lldb::StackFrameSP GetFrameWithStackID(const StackID &stack_id)
Definition: Thread.h:431
void DiscardThreadPlansUpToPlan(lldb::ThreadPlanSP &up_to_plan_sp)
Discards the plans queued on the plan stack of the current thread up to and including up_to_plan_sp.
Definition: Thread.cpp:1198
static ThreadProperties & GetGlobalProperties()
Definition: Thread.cpp:61
void SetConnection(std::unique_ptr< Connection > connection) override
Sets the connection that it to be used by this class.
virtual bool StopReadThread(Status *error_ptr=nullptr)
Stops the read thread by cancelling it.
void SynchronizeWithReadThread()
Wait for the read thread to process all outstanding data.
lldb::ConnectionStatus Disconnect(Status *error_ptr=nullptr) override
Disconnect the communications connection if one is currently connected.
virtual bool StartReadThread(Status *error_ptr=nullptr)
Starts a read thread whose sole purpose it to read bytes from the current connection.
void SetReadThreadBytesReceivedCallback(ReadThreadBytesReceived callback, void *callback_baton)
RAII guard that should be acquired when an utility function is called within a given process.
Definition: Process.h:3253
"lldb/Expression/UtilityFunction.h" Encapsulates a bit of source code that provides a function that i...
virtual bool IsDynamic()
Definition: ValueObject.h:633
lldb::LanguageType GetObjectRuntimeLanguage()
Definition: ValueObject.h:373
#define UINT64_MAX
Definition: lldb-defines.h:23
#define LLDB_INVALID_BREAK_ID
Definition: lldb-defines.h:37
#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...
Definition: lldb-defines.h:133
#define LLDB_INVALID_THREAD_ID
Definition: lldb-defines.h:90
#define UNUSED_IF_ASSERT_DISABLED(x)
Definition: lldb-defines.h:140
#define LLDB_INVALID_IMAGE_TOKEN
Definition: lldb-defines.h:85
#define LLDB_INVALID_ADDRESS
Definition: lldb-defines.h:82
#define UINT32_MAX
Definition: lldb-defines.h:19
#define LLDB_INVALID_PROCESS_ID
Definition: lldb-defines.h:89
@ DoNoSelectMostRelevantFrame
@ SelectMostRelevantFrame
A class that represents a running process on the host machine.
Definition: SBAttachInfo.h:14
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition: Log.h:314
bool StateIsStoppedState(lldb::StateType state, bool must_exist)
Check if a state represents a state where the process or thread is stopped.
Definition: State.cpp:89
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.
Definition: State.cpp:68
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.
Definition: Predicate.h:29
const char * StateAsCString(lldb::StateType state)
Converts a StateType to a C string.
Definition: State.cpp:14
std::vector< ProcessInstanceInfo > ProcessInstanceInfoList
Definition: Host.h:32
const char * GetPermissionsAsCString(uint32_t permissions)
Definition: State.cpp:44
static uint32_t bits(const uint32_t val, const uint32_t msbit, const uint32_t lsbit)
Definition: ARMUtils.h:265
Definition: SBAddress.h:15
std::shared_ptr< lldb_private::OptionValueProperties > OptionValuePropertiesSP
Definition: lldb-forward.h:379
std::shared_ptr< lldb_private::ThreadPlan > ThreadPlanSP
Definition: lldb-forward.h:441
std::shared_ptr< lldb_private::ABI > ABISP
Definition: lldb-forward.h:310
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
Definition: lldb-forward.h:412
std::shared_ptr< lldb_private::BreakpointSite > BreakpointSiteSP
Definition: lldb-forward.h:315
std::shared_ptr< lldb_private::BreakpointLocation > BreakpointLocationSP
Definition: lldb-forward.h:316
DescriptionLevel
Description levels for "void GetDescription(Stream *, DescriptionLevel)" calls.
@ eDescriptionLevelBrief
@ eDescriptionLevelVerbose
@ eSaveCoreStackOnly
@ eSaveCoreDirtyOnly
@ eSaveCoreUnspecified
std::shared_ptr< lldb_private::IOHandler > IOHandlerSP
Definition: lldb-forward.h:353
std::shared_ptr< lldb_private::Thread > ThreadSP
Definition: lldb-forward.h:438
void * thread_result_t
Definition: lldb-types.h:62
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
Definition: lldb-forward.h:472
std::shared_ptr< lldb_private::UnixSignals > UnixSignalsSP
Definition: lldb-forward.h:468
std::shared_ptr< lldb_private::Platform > PlatformSP
Definition: lldb-forward.h:380
uint64_t offset_t
Definition: lldb-types.h:83
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.
@ eLanguageTypeUnknown
Unknown or invalid language value.
@ eLanguageTypeC
Non-standardized C, such as K&R.
std::shared_ptr< lldb_private::MemoryHistory > MemoryHistorySP
Definition: lldb-forward.h:362
std::shared_ptr< lldb_private::Stream > StreamSP
Definition: lldb-forward.h:420
ExpressionResults
The results of expression evaluation.
@ eExpressionTimedOut
@ eExpressionCompleted
@ eExpressionHitBreakpoint
@ eExpressionInterrupted
@ eExpressionDiscarded
@ eExpressionParseError
@ eExpressionStoppedForDebug
@ eExpressionResultUnavailable
@ eExpressionThreadVanished
@ eExpressionSetupError
std::shared_ptr< lldb_private::StructuredDataPlugin > StructuredDataPluginSP
Definition: lldb-forward.h:426
int32_t break_id_t
Definition: lldb-types.h:84
std::shared_ptr< lldb_private::Process > ProcessSP
Definition: lldb-forward.h:381
InstrumentationRuntimeType
std::shared_ptr< lldb_private::Disassembler > DisassemblerSP
Definition: lldb-forward.h:333
std::shared_ptr< lldb_private::LanguageRuntime > LanguageRuntimeSP
Definition: lldb-forward.h:358
std::shared_ptr< lldb_private::Event > EventSP
Definition: lldb-forward.h:337
std::unique_ptr< lldb_private::DynamicLoader > DynamicLoaderUP
Definition: lldb-forward.h:336
uint64_t pid_t
Definition: lldb-types.h:81
ByteOrder
Byte ordering definitions.
std::shared_ptr< lldb_private::Watchpoint > WatchpointSP
Definition: lldb-forward.h:477
std::shared_ptr< lldb_private::Listener > ListenerSP
Definition: lldb-forward.h:360
uint64_t user_id_t
Definition: lldb-types.h:80
std::shared_ptr< lldb_private::StopInfo > StopInfoSP
Definition: lldb-forward.h:419
uint64_t addr_t
Definition: lldb-types.h:79
StopReason
Thread stop reasons.
@ eStopReasonInstrumentation
@ eStopReasonPlanComplete
@ eStopReasonTrace
@ eStopReasonBreakpoint
@ eStopReasonExec
Program was re-exec'ed.
@ eStopReasonVForkDone
@ eStopReasonProcessorTrace
@ eStopReasonThreadExiting
@ eStopReasonException
@ eStopReasonInvalid
@ eStopReasonWatchpoint
@ eStopReasonVFork
@ eStopReasonSignal
std::shared_ptr< lldb_private::Target > TargetSP
Definition: lldb-forward.h:436
@ eNoDynamicValues
std::shared_ptr< lldb_private::RegisterContext > RegisterContextSP
Definition: lldb-forward.h:386
std::shared_ptr< lldb_private::InstrumentationRuntime > InstrumentationRuntimeSP
Definition: lldb-forward.h:352
uint64_t tid_t
Definition: lldb-types.h:82
std::shared_ptr< lldb_private::Module > ModuleSP
Definition: lldb-forward.h:365
std::shared_ptr< lldb_private::OptionValue > OptionValueSP
Definition: lldb-forward.h:376
std::shared_ptr< lldb_private::ThreadCollection > ThreadCollectionSP
Definition: lldb-forward.h:440
A SmallBitVector that represents a set of source languages (lldb::LanguageType).
Definition: Type.h:36
A notification structure that can be used by clients to listen for changes in a process's lifetime.
Definition: Process.h:401
void(* process_state_changed)(void *baton, Process *process, lldb::StateType state)
Definition: Process.h:404
void(* initialize)(void *baton, Process *process)
Definition: Process.h:403
BaseType GetRangeBase() const
Definition: RangeMap.h:45
SizeType GetByteSize() const
Definition: RangeMap.h:87
BaseType GetRangeEnd() const
Definition: RangeMap.h:78
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition: UserID.h:47
#define SIGKILL
#define PATH_MAX