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