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