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