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