LLDB mainline
Process.cpp
Go to the documentation of this file.
1//===-- Process.cpp -------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include <atomic>
10#include <memory>
11#include <mutex>
12#include <optional>
13
14#include "llvm/ADT/ScopeExit.h"
15#include "llvm/Support/ScopedPrinter.h"
16#include "llvm/Support/Threading.h"
17
20#include "lldb/Core/Debugger.h"
21#include "lldb/Core/Module.h"
30#include "lldb/Host/Host.h"
31#include "lldb/Host/HostInfo.h"
33#include "lldb/Host/Pipe.h"
34#include "lldb/Host/Terminal.h"
40#include "lldb/Symbol/Symbol.h"
41#include "lldb/Target/ABI.h"
53#include "lldb/Target/Process.h"
58#include "lldb/Target/Target.h"
60#include "lldb/Target/Thread.h"
66#include "lldb/Utility/Event.h"
68#include "lldb/Utility/Log.h"
72#include "lldb/Utility/State.h"
73#include "lldb/Utility/Timer.h"
74
75using namespace lldb;
76using namespace lldb_private;
77using namespace std::chrono;
78
79// Comment out line below to disable memory caching, overriding the process
80// setting target.process.disable-memory-cache
81#define ENABLE_MEMORY_CACHING
82
83#ifdef ENABLE_MEMORY_CACHING
84#define DISABLE_MEM_CACHE_DEFAULT false
85#else
86#define DISABLE_MEM_CACHE_DEFAULT true
87#endif
88
90 : public Cloneable<ProcessOptionValueProperties, OptionValueProperties> {
91public:
92 ProcessOptionValueProperties(llvm::StringRef name) : Cloneable(name) {}
93
94 const Property *
96 const ExecutionContext *exe_ctx) const override {
97 // When getting the value for a key from the process options, we will
98 // always try and grab the setting from the current process if there is
99 // one. Else we just use the one from this instance.
100 if (exe_ctx) {
101 Process *process = exe_ctx->GetProcessPtr();
102 if (process) {
103 ProcessOptionValueProperties *instance_properties =
104 static_cast<ProcessOptionValueProperties *>(
105 process->GetValueProperties().get());
106 if (this != instance_properties)
107 return instance_properties->ProtectedGetPropertyAtIndex(idx);
108 }
109 }
110 return ProtectedGetPropertyAtIndex(idx);
111 }
112};
113
115 {
117 "parent",
118 "Continue tracing the parent process and detach the child.",
119 },
120 {
122 "child",
123 "Trace the child process and detach the parent.",
124 },
125};
126
127#define LLDB_PROPERTIES_process
128#include "TargetProperties.inc"
129
130enum {
131#define LLDB_PROPERTIES_process
132#include "TargetPropertiesEnum.inc"
134};
135
136#define LLDB_PROPERTIES_process_experimental
137#include "TargetProperties.inc"
138
139enum {
140#define LLDB_PROPERTIES_process_experimental
141#include "TargetPropertiesEnum.inc"
142};
143
145 : public Cloneable<ProcessExperimentalOptionValueProperties,
146 OptionValueProperties> {
147public:
149 : Cloneable(Properties::GetExperimentalSettingsName()) {}
150};
151
155 m_collection_sp->Initialize(g_process_experimental_properties);
156}
157
159 : Properties(),
160 m_process(process) // Can be nullptr for global ProcessProperties
161{
162 if (process == nullptr) {
163 // Global process properties, set them up one time
164 m_collection_sp = std::make_shared<ProcessOptionValueProperties>("process");
165 m_collection_sp->Initialize(g_process_properties);
166 m_collection_sp->AppendProperty(
167 "thread", "Settings specific to threads.", true,
169 } else {
172 m_collection_sp->SetValueChangedCallback(
173 ePropertyPythonOSPluginPath,
174 [this] { m_process->LoadOperatingSystemPlugin(true); });
175 }
176
178 std::make_unique<ProcessExperimentalProperties>();
179 m_collection_sp->AppendProperty(
181 "Experimental settings - setting these won't produce "
182 "errors if the setting is not present.",
183 true, m_experimental_properties_up->GetValueProperties());
184}
185
187
189 const uint32_t idx = ePropertyDisableMemCache;
190 return GetPropertyAtIndexAs<bool>(
191 idx, g_process_properties[idx].default_uint_value != 0);
192}
193
195 const uint32_t idx = ePropertyMemCacheLineSize;
196 return GetPropertyAtIndexAs<uint64_t>(
197 idx, g_process_properties[idx].default_uint_value);
198}
199
201 Args args;
202 const uint32_t idx = ePropertyExtraStartCommand;
203 m_collection_sp->GetPropertyAtIndexAsArgs(idx, args);
204 return args;
205}
206
208 const uint32_t idx = ePropertyExtraStartCommand;
209 m_collection_sp->SetPropertyAtIndexFromArgs(idx, args);
210}
211
213 const uint32_t idx = ePropertyPythonOSPluginPath;
214 return GetPropertyAtIndexAs<FileSpec>(idx, {});
215}
216
218 const uint32_t idx = ePropertyVirtualAddressableBits;
219 return GetPropertyAtIndexAs<uint64_t>(
220 idx, g_process_properties[idx].default_uint_value);
221}
222
224 const uint32_t idx = ePropertyVirtualAddressableBits;
225 SetPropertyAtIndex(idx, static_cast<uint64_t>(bits));
226}
227
229 const uint32_t idx = ePropertyHighmemVirtualAddressableBits;
230 return GetPropertyAtIndexAs<uint64_t>(
231 idx, g_process_properties[idx].default_uint_value);
232}
233
235 const uint32_t idx = ePropertyHighmemVirtualAddressableBits;
236 SetPropertyAtIndex(idx, static_cast<uint64_t>(bits));
237}
238
240 const uint32_t idx = ePropertyPythonOSPluginPath;
241 SetPropertyAtIndex(idx, file);
242}
243
245 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
246 return GetPropertyAtIndexAs<bool>(
247 idx, g_process_properties[idx].default_uint_value != 0);
248}
249
251 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
252 SetPropertyAtIndex(idx, ignore);
253}
254
256 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
257 return GetPropertyAtIndexAs<bool>(
258 idx, g_process_properties[idx].default_uint_value != 0);
259}
260
262 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
263 SetPropertyAtIndex(idx, ignore);
264}
265
267 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
268 return GetPropertyAtIndexAs<bool>(
269 idx, g_process_properties[idx].default_uint_value != 0);
270}
271
273 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
274 SetPropertyAtIndex(idx, stop);
275}
276
278 const uint32_t idx = ePropertyDisableLangRuntimeUnwindPlans;
279 return GetPropertyAtIndexAs<bool>(
280 idx, g_process_properties[idx].default_uint_value != 0);
281}
282
284 const uint32_t idx = ePropertyDisableLangRuntimeUnwindPlans;
285 SetPropertyAtIndex(idx, disable);
286 m_process->Flush();
287}
288
290 const uint32_t idx = ePropertyDetachKeepsStopped;
291 return GetPropertyAtIndexAs<bool>(
292 idx, g_process_properties[idx].default_uint_value != 0);
293}
294
296 const uint32_t idx = ePropertyDetachKeepsStopped;
297 SetPropertyAtIndex(idx, stop);
298}
299
301 const uint32_t idx = ePropertyWarningOptimization;
302 return GetPropertyAtIndexAs<bool>(
303 idx, g_process_properties[idx].default_uint_value != 0);
304}
305
307 const uint32_t idx = ePropertyWarningUnsupportedLanguage;
308 return GetPropertyAtIndexAs<bool>(
309 idx, g_process_properties[idx].default_uint_value != 0);
310}
311
313 const uint32_t idx = ePropertyStopOnExec;
314 return GetPropertyAtIndexAs<bool>(
315 idx, g_process_properties[idx].default_uint_value != 0);
316}
317
319 const uint32_t idx = ePropertyUtilityExpressionTimeout;
320 uint64_t value = GetPropertyAtIndexAs<uint64_t>(
321 idx, g_process_properties[idx].default_uint_value);
322 return std::chrono::seconds(value);
323}
324
325std::chrono::seconds ProcessProperties::GetInterruptTimeout() const {
326 const uint32_t idx = ePropertyInterruptTimeout;
327 uint64_t value = GetPropertyAtIndexAs<uint64_t>(
328 idx, g_process_properties[idx].default_uint_value);
329 return std::chrono::seconds(value);
330}
331
333 const uint32_t idx = ePropertySteppingRunsAllThreads;
334 return GetPropertyAtIndexAs<bool>(
335 idx, g_process_properties[idx].default_uint_value != 0);
336}
337
339 const bool fail_value = true;
340 const Property *exp_property =
341 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental);
342 OptionValueProperties *exp_values =
343 exp_property->GetValue()->GetAsProperties();
344 if (!exp_values)
345 return fail_value;
346
347 return exp_values
348 ->GetPropertyAtIndexAs<bool>(ePropertyOSPluginReportsAllThreads)
349 .value_or(fail_value);
350}
351
353 const Property *exp_property =
354 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental);
355 OptionValueProperties *exp_values =
356 exp_property->GetValue()->GetAsProperties();
357 if (exp_values)
358 exp_values->SetPropertyAtIndex(ePropertyOSPluginReportsAllThreads,
359 does_report);
360}
361
363 const uint32_t idx = ePropertyFollowForkMode;
364 return GetPropertyAtIndexAs<FollowForkMode>(
365 idx, static_cast<FollowForkMode>(
366 g_process_properties[idx].default_uint_value));
367}
368
370 llvm::StringRef plugin_name,
371 ListenerSP listener_sp,
372 const FileSpec *crash_file_path,
373 bool can_connect) {
374 static uint32_t g_process_unique_id = 0;
375
376 ProcessSP process_sp;
377 ProcessCreateInstance create_callback = nullptr;
378 if (!plugin_name.empty()) {
379 create_callback =
381 if (create_callback) {
382 process_sp = create_callback(target_sp, listener_sp, crash_file_path,
383 can_connect);
384 if (process_sp) {
385 if (process_sp->CanDebug(target_sp, true)) {
386 process_sp->m_process_unique_id = ++g_process_unique_id;
387 } else
388 process_sp.reset();
389 }
390 }
391 } else {
392 for (uint32_t idx = 0;
393 (create_callback =
395 ++idx) {
396 process_sp = create_callback(target_sp, listener_sp, crash_file_path,
397 can_connect);
398 if (process_sp) {
399 if (process_sp->CanDebug(target_sp, false)) {
400 process_sp->m_process_unique_id = ++g_process_unique_id;
401 break;
402 } else
403 process_sp.reset();
404 }
405 }
406 }
407 return process_sp;
408}
409
411 static ConstString class_name("lldb.process");
412 return class_name;
413}
414
416 : Process(target_sp, listener_sp, UnixSignals::CreateForHost()) {
417 // This constructor just delegates to the full Process constructor,
418 // defaulting to using the Host's UnixSignals.
419}
420
422 const UnixSignalsSP &unix_signals_sp)
423 : ProcessProperties(this),
424 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
425 Process::GetStaticBroadcasterClass().AsCString()),
426 m_target_wp(target_sp), m_public_state(eStateUnloaded),
427 m_private_state(eStateUnloaded),
428 m_private_state_broadcaster(nullptr,
429 "lldb.process.internal_state_broadcaster"),
430 m_private_state_control_broadcaster(
431 nullptr, "lldb.process.internal_state_control_broadcaster"),
432 m_private_state_listener_sp(
433 Listener::MakeListener("lldb.process.internal_state_listener")),
434 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
435 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
436 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
437 m_thread_list(this), m_thread_plans(*this), m_extended_thread_list(this),
438 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
439 m_watchpoint_resource_list(), m_notifications(), m_image_tokens(),
440 m_breakpoint_site_list(), m_dynamic_checkers_up(),
441 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
442 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
443 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
444 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
445 m_memory_cache(*this), m_allocated_memory_cache(*this),
446 m_should_detach(false), m_next_event_action_up(), m_public_run_lock(),
447 m_private_run_lock(), m_currently_handling_do_on_removals(false),
448 m_resume_requested(false), m_finalizing(false), m_destructing(false),
449 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
450 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
451 m_can_interpret_function_calls(false), m_run_thread_plan_lock(),
452 m_can_jit(eCanJITDontKnow) {
454
455 Log *log = GetLog(LLDBLog::Object);
456 LLDB_LOGF(log, "%p Process::Process()", static_cast<void *>(this));
457
459 m_unix_signals_sp = std::make_shared<UnixSignals>();
460
461 SetEventName(eBroadcastBitStateChanged, "state-changed");
463 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
464 SetEventName(eBroadcastBitSTDERR, "stderr-available");
465 SetEventName(eBroadcastBitProfileData, "profile-data-available");
466 SetEventName(eBroadcastBitStructuredData, "structured-data-available");
467
469 eBroadcastInternalStateControlStop, "control-stop");
471 eBroadcastInternalStateControlPause, "control-pause");
473 eBroadcastInternalStateControlResume, "control-resume");
474
475 // The listener passed into process creation is the primary listener:
476 // It always listens for all the event bits for Process:
477 SetPrimaryListener(listener_sp);
478
479 m_private_state_listener_sp->StartListeningForEvents(
482
483 m_private_state_listener_sp->StartListeningForEvents(
487 // We need something valid here, even if just the default UnixSignalsSP.
488 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
489
490 // Allow the platform to override the default cache line size
491 OptionValueSP value_sp =
492 m_collection_sp->GetPropertyAtIndex(ePropertyMemCacheLineSize)
493 ->GetValue();
494 uint64_t platform_cache_line_size =
495 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
496 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
497 value_sp->SetValueAs(platform_cache_line_size);
498
500}
501
503 Log *log = GetLog(LLDBLog::Object);
504 LLDB_LOGF(log, "%p Process::~Process()", static_cast<void *>(this));
506
507 // ThreadList::Clear() will try to acquire this process's mutex, so
508 // explicitly clear the thread list here to ensure that the mutex is not
509 // destroyed before the thread list.
511}
512
514 // NOTE: intentional leak so we don't crash if global destructor chain gets
515 // called as other threads still use the result of this function
516 static ProcessProperties *g_settings_ptr =
517 new ProcessProperties(nullptr);
518 return *g_settings_ptr;
519}
520
521void Process::Finalize(bool destructing) {
522 if (m_finalizing.exchange(true))
523 return;
524 if (destructing)
525 m_destructing.exchange(true);
526
527 // Destroy the process. This will call the virtual function DoDestroy under
528 // the hood, giving our derived class a chance to do the ncessary tear down.
529 DestroyImpl(false);
530
531 // Clear our broadcaster before we proceed with destroying
533
534 // Do any cleanup needed prior to being destructed... Subclasses that
535 // override this method should call this superclass method as well.
536
537 // We need to destroy the loader before the derived Process class gets
538 // destroyed since it is very likely that undoing the loader will require
539 // access to the real process.
540 m_dynamic_checkers_up.reset();
541 m_abi_sp.reset();
542 m_os_up.reset();
543 m_system_runtime_up.reset();
544 m_dyld_up.reset();
545 m_jit_loaders_up.reset();
553 std::vector<Notifications> empty_notifications;
554 m_notifications.swap(empty_notifications);
555 m_image_tokens.clear();
557 m_allocated_memory_cache.Clear(/*deallocate_memory=*/true);
558 {
559 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
560 m_language_runtimes.clear();
561 }
564 // Clear the last natural stop ID since it has a strong reference to this
565 // process
567 // We have to be very careful here as the m_private_state_listener might
568 // contain events that have ProcessSP values in them which can keep this
569 // process around forever. These events need to be cleared out.
571 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
573 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
576}
577
579 m_notifications.push_back(callbacks);
580 if (callbacks.initialize != nullptr)
581 callbacks.initialize(callbacks.baton, this);
582}
583
585 std::vector<Notifications>::iterator pos, end = m_notifications.end();
586 for (pos = m_notifications.begin(); pos != end; ++pos) {
587 if (pos->baton == callbacks.baton &&
588 pos->initialize == callbacks.initialize &&
589 pos->process_state_changed == callbacks.process_state_changed) {
590 m_notifications.erase(pos);
591 return true;
592 }
593 }
594 return false;
595}
596
598 std::vector<Notifications>::iterator notification_pos,
599 notification_end = m_notifications.end();
600 for (notification_pos = m_notifications.begin();
601 notification_pos != notification_end; ++notification_pos) {
602 if (notification_pos->process_state_changed)
603 notification_pos->process_state_changed(notification_pos->baton, this,
604 state);
605 }
606}
607
608// FIXME: We need to do some work on events before the general Listener sees
609// them.
610// For instance if we are continuing from a breakpoint, we need to ensure that
611// we do the little "insert real insn, step & stop" trick. But we can't do
612// that when the event is delivered by the broadcaster - since that is done on
613// the thread that is waiting for new events, so if we needed more than one
614// event for our handling, we would stall. So instead we do it when we fetch
615// the event off of the queue.
616//
617
619 StateType state = eStateInvalid;
620
621 if (GetPrimaryListener()->GetEventForBroadcaster(this, event_sp,
622 std::chrono::seconds(0)) &&
623 event_sp)
624 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
625
626 return state;
627}
628
629void Process::SyncIOHandler(uint32_t iohandler_id,
630 const Timeout<std::micro> &timeout) {
631 // don't sync (potentially context switch) in case where there is no process
632 // IO
634 return;
635
636 auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout);
637
639 if (Result) {
640 LLDB_LOG(
641 log,
642 "waited from m_iohandler_sync to change from {0}. New value is {1}.",
643 iohandler_id, *Result);
644 } else {
645 LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.",
646 iohandler_id);
647 }
648}
649
651 const Timeout<std::micro> &timeout, EventSP *event_sp_ptr, bool wait_always,
652 ListenerSP hijack_listener_sp, Stream *stream, bool use_run_lock,
653 SelectMostRelevant select_most_relevant) {
654 // We can't just wait for a "stopped" event, because the stopped event may
655 // have restarted the target. We have to actually check each event, and in
656 // the case of a stopped event check the restarted flag on the event.
657 if (event_sp_ptr)
658 event_sp_ptr->reset();
659 StateType state = GetState();
660 // If we are exited or detached, we won't ever get back to any other valid
661 // state...
662 if (state == eStateDetached || state == eStateExited)
663 return state;
664
666 LLDB_LOG(log, "timeout = {0}", timeout);
667
668 if (!wait_always && StateIsStoppedState(state, true) &&
670 LLDB_LOGF(log,
671 "Process::%s returning without waiting for events; process "
672 "private and public states are already 'stopped'.",
673 __FUNCTION__);
674 // We need to toggle the run lock as this won't get done in
675 // SetPublicState() if the process is hijacked.
676 if (hijack_listener_sp && use_run_lock)
678 return state;
679 }
680
681 while (state != eStateInvalid) {
682 EventSP event_sp;
683 state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
684 if (event_sp_ptr && event_sp)
685 *event_sp_ptr = event_sp;
686
687 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
689 event_sp, stream, select_most_relevant, pop_process_io_handler);
690
691 switch (state) {
692 case eStateCrashed:
693 case eStateDetached:
694 case eStateExited:
695 case eStateUnloaded:
696 // We need to toggle the run lock as this won't get done in
697 // SetPublicState() if the process is hijacked.
698 if (hijack_listener_sp && use_run_lock)
700 return state;
701 case eStateStopped:
703 continue;
704 else {
705 // We need to toggle the run lock as this won't get done in
706 // SetPublicState() if the process is hijacked.
707 if (hijack_listener_sp && use_run_lock)
709 return state;
710 }
711 default:
712 continue;
713 }
714 }
715 return state;
716}
717
719 const EventSP &event_sp, Stream *stream,
720 SelectMostRelevant select_most_relevant,
721 bool &pop_process_io_handler) {
722 const bool handle_pop = pop_process_io_handler;
723
724 pop_process_io_handler = false;
725 ProcessSP process_sp =
727
728 if (!process_sp)
729 return false;
730
731 StateType event_state =
733 if (event_state == eStateInvalid)
734 return false;
735
736 switch (event_state) {
737 case eStateInvalid:
738 case eStateUnloaded:
739 case eStateAttaching:
740 case eStateLaunching:
741 case eStateStepping:
742 case eStateDetached:
743 if (stream)
744 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
745 StateAsCString(event_state));
746 if (event_state == eStateDetached)
747 pop_process_io_handler = true;
748 break;
749
750 case eStateConnected:
751 case eStateRunning:
752 // Don't be chatty when we run...
753 break;
754
755 case eStateExited:
756 if (stream)
757 process_sp->GetStatus(*stream);
758 pop_process_io_handler = true;
759 break;
760
761 case eStateStopped:
762 case eStateCrashed:
763 case eStateSuspended:
764 // Make sure the program hasn't been auto-restarted:
766 if (stream) {
767 size_t num_reasons =
769 if (num_reasons > 0) {
770 // FIXME: Do we want to report this, or would that just be annoyingly
771 // chatty?
772 if (num_reasons == 1) {
773 const char *reason =
775 event_sp.get(), 0);
776 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
777 process_sp->GetID(),
778 reason ? reason : "<UNKNOWN REASON>");
779 } else {
780 stream->Printf("Process %" PRIu64
781 " stopped and restarted, reasons:\n",
782 process_sp->GetID());
783
784 for (size_t i = 0; i < num_reasons; i++) {
785 const char *reason =
787 event_sp.get(), i);
788 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
789 }
790 }
791 }
792 }
793 } else {
794 StopInfoSP curr_thread_stop_info_sp;
795 // Lock the thread list so it doesn't change on us, this is the scope for
796 // the locker:
797 {
798 ThreadList &thread_list = process_sp->GetThreadList();
799 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
800
801 ThreadSP curr_thread(thread_list.GetSelectedThread());
802 ThreadSP thread;
803 StopReason curr_thread_stop_reason = eStopReasonInvalid;
804 bool prefer_curr_thread = false;
805 if (curr_thread && curr_thread->IsValid()) {
806 curr_thread_stop_reason = curr_thread->GetStopReason();
807 switch (curr_thread_stop_reason) {
808 case eStopReasonNone:
810 // Don't prefer the current thread if it didn't stop for a reason.
811 break;
812 case eStopReasonSignal: {
813 // We need to do the same computation we do for other threads
814 // below in case the current thread happens to be the one that
815 // stopped for the no-stop signal.
816 uint64_t signo = curr_thread->GetStopInfo()->GetValue();
817 if (process_sp->GetUnixSignals()->GetShouldStop(signo))
818 prefer_curr_thread = true;
819 } break;
820 default:
821 prefer_curr_thread = true;
822 break;
823 }
824 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
825 }
826
827 if (!prefer_curr_thread) {
828 // Prefer a thread that has just completed its plan over another
829 // thread as current thread.
830 ThreadSP plan_thread;
831 ThreadSP other_thread;
832
833 const size_t num_threads = thread_list.GetSize();
834 size_t i;
835 for (i = 0; i < num_threads; ++i) {
836 thread = thread_list.GetThreadAtIndex(i);
837 StopReason thread_stop_reason = thread->GetStopReason();
838 switch (thread_stop_reason) {
840 case eStopReasonNone:
841 break;
842
843 case eStopReasonSignal: {
844 // Don't select a signal thread if we weren't going to stop at
845 // that signal. We have to have had another reason for stopping
846 // here, and the user doesn't want to see this thread.
847 uint64_t signo = thread->GetStopInfo()->GetValue();
848 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
849 if (!other_thread)
850 other_thread = thread;
851 }
852 break;
853 }
854 case eStopReasonTrace:
858 case eStopReasonExec:
859 case eStopReasonFork:
860 case eStopReasonVFork:
865 if (!other_thread)
866 other_thread = thread;
867 break;
869 if (!plan_thread)
870 plan_thread = thread;
871 break;
872 }
873 }
874 if (plan_thread)
875 thread_list.SetSelectedThreadByID(plan_thread->GetID());
876 else if (other_thread)
877 thread_list.SetSelectedThreadByID(other_thread->GetID());
878 else {
879 if (curr_thread && curr_thread->IsValid())
880 thread = curr_thread;
881 else
882 thread = thread_list.GetThreadAtIndex(0);
883
884 if (thread)
885 thread_list.SetSelectedThreadByID(thread->GetID());
886 }
887 }
888 }
889 // Drop the ThreadList mutex by here, since GetThreadStatus below might
890 // have to run code, e.g. for Data formatters, and if we hold the
891 // ThreadList mutex, then the process is going to have a hard time
892 // restarting the process.
893 if (stream) {
894 Debugger &debugger = process_sp->GetTarget().GetDebugger();
895 if (debugger.GetTargetList().GetSelectedTarget().get() ==
896 &process_sp->GetTarget()) {
897 ThreadSP thread_sp = process_sp->GetThreadList().GetSelectedThread();
898
899 if (!thread_sp || !thread_sp->IsValid())
900 return false;
901
902 const bool only_threads_with_stop_reason = true;
903 const uint32_t start_frame =
904 thread_sp->GetSelectedFrameIndex(select_most_relevant);
905 const uint32_t num_frames = 1;
906 const uint32_t num_frames_with_source = 1;
907 const bool stop_format = true;
908
909 process_sp->GetStatus(*stream);
910 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
911 start_frame, num_frames,
912 num_frames_with_source,
913 stop_format);
914 if (curr_thread_stop_info_sp) {
915 lldb::addr_t crashing_address;
917 curr_thread_stop_info_sp, &crashing_address);
918 if (valobj_sp) {
922 stream->PutCString("Likely cause: ");
923 valobj_sp->GetExpressionPath(*stream, format);
924 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
925 }
926 }
927 } else {
928 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
929 process_sp->GetTarget().shared_from_this());
930 if (target_idx != UINT32_MAX)
931 stream->Printf("Target %d: (", target_idx);
932 else
933 stream->Printf("Target <unknown index>: (");
934 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
935 stream->Printf(") stopped.\n");
936 }
937 }
938
939 // Pop the process IO handler
940 pop_process_io_handler = true;
941 }
942 break;
943 }
944
945 if (handle_pop && pop_process_io_handler)
946 process_sp->PopProcessIOHandler();
947
948 return true;
949}
950
952 if (listener_sp) {
953 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
955 } else
956 return false;
957}
958
960
962 const Timeout<std::micro> &timeout,
963 ListenerSP hijack_listener_sp) {
965 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
966
967 ListenerSP listener_sp = hijack_listener_sp;
968 if (!listener_sp)
969 listener_sp = GetPrimaryListener();
970
971 StateType state = eStateInvalid;
972 if (listener_sp->GetEventForBroadcasterWithType(
974 timeout)) {
975 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
976 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
977 else
978 LLDB_LOG(log, "got no event or was interrupted.");
979 }
980
981 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
982 return state;
983}
984
987
988 LLDB_LOGF(log, "Process::%s...", __FUNCTION__);
989
990 Event *event_ptr;
991 event_ptr = GetPrimaryListener()->PeekAtNextEventForBroadcasterWithType(
993 if (log) {
994 if (event_ptr) {
995 LLDB_LOGF(log, "Process::%s (event_ptr) => %s", __FUNCTION__,
997 } else {
998 LLDB_LOGF(log, "Process::%s no events found", __FUNCTION__);
999 }
1000 }
1001 return event_ptr;
1002}
1003
1006 const Timeout<std::micro> &timeout) {
1007 Log *log = GetLog(LLDBLog::Process);
1008 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
1009
1010 StateType state = eStateInvalid;
1011 if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1014 timeout))
1015 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1016 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1017
1018 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
1019 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
1020 return state;
1021}
1022
1024 const Timeout<std::micro> &timeout,
1025 bool control_only) {
1026 Log *log = GetLog(LLDBLog::Process);
1027 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
1028
1029 if (control_only)
1030 return m_private_state_listener_sp->GetEventForBroadcaster(
1031 &m_private_state_control_broadcaster, event_sp, timeout);
1032 else
1033 return m_private_state_listener_sp->GetEvent(event_sp, timeout);
1034}
1035
1038}
1039
1041 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1042
1044 return m_exit_status;
1045 return -1;
1046}
1047
1049 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1050
1052 return m_exit_string.c_str();
1053 return nullptr;
1054}
1055
1056bool Process::SetExitStatus(int status, llvm::StringRef exit_string) {
1057 // Use a mutex to protect setting the exit status.
1058 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1059
1061 LLDB_LOG(log, "(plugin = {0} status = {1} ({1:x8}), description=\"{2}\")",
1062 GetPluginName(), status, exit_string);
1063
1064 // We were already in the exited state
1066 LLDB_LOG(
1067 log,
1068 "(plugin = {0}) ignoring exit status because state was already set "
1069 "to eStateExited",
1070 GetPluginName());
1071 return false;
1072 }
1073
1074 m_exit_status = status;
1075 if (!exit_string.empty())
1076 m_exit_string = exit_string.str();
1077 else
1078 m_exit_string.clear();
1079
1080 // Clear the last natural stop ID since it has a strong reference to this
1081 // process
1083
1085
1086 // Allow subclasses to do some cleanup
1087 DidExit();
1088
1089 return true;
1090}
1091
1093 switch (m_private_state.GetValue()) {
1094 case eStateConnected:
1095 case eStateAttaching:
1096 case eStateLaunching:
1097 case eStateStopped:
1098 case eStateRunning:
1099 case eStateStepping:
1100 case eStateCrashed:
1101 case eStateSuspended:
1102 return true;
1103 default:
1104 return false;
1105 }
1106}
1107
1108// This static callback can be used to watch for local child processes on the
1109// current host. The child process exits, the process will be found in the
1110// global target list (we want to be completely sure that the
1111// lldb_private::Process doesn't go away before we can deliver the signal.
1113 lldb::pid_t pid, bool exited,
1114 int signo, // Zero for no signal
1115 int exit_status // Exit value of process if signal is zero
1116 ) {
1117 Log *log = GetLog(LLDBLog::Process);
1118 LLDB_LOGF(log,
1119 "Process::SetProcessExitStatus (pid=%" PRIu64
1120 ", exited=%i, signal=%i, exit_status=%i)\n",
1121 pid, exited, signo, exit_status);
1122
1123 if (exited) {
1125 if (target_sp) {
1126 ProcessSP process_sp(target_sp->GetProcessSP());
1127 if (process_sp) {
1128 llvm::StringRef signal_str =
1129 process_sp->GetUnixSignals()->GetSignalAsStringRef(signo);
1130 process_sp->SetExitStatus(exit_status, signal_str);
1131 }
1132 }
1133 return true;
1134 }
1135 return false;
1136}
1137
1139 ThreadList &new_thread_list) {
1141 return DoUpdateThreadList(old_thread_list, new_thread_list);
1142}
1143
1145 const uint32_t stop_id = GetStopID();
1146 if (m_thread_list.GetSize(false) == 0 ||
1147 stop_id != m_thread_list.GetStopID()) {
1148 bool clear_unused_threads = true;
1149 const StateType state = GetPrivateState();
1150 if (StateIsStoppedState(state, true)) {
1151 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
1152 m_thread_list.SetStopID(stop_id);
1153
1154 // m_thread_list does have its own mutex, but we need to hold onto the
1155 // mutex between the call to UpdateThreadList(...) and the
1156 // os->UpdateThreadList(...) so it doesn't change on us
1157 ThreadList &old_thread_list = m_thread_list;
1158 ThreadList real_thread_list(this);
1159 ThreadList new_thread_list(this);
1160 // Always update the thread list with the protocol specific thread list,
1161 // but only update if "true" is returned
1162 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1163 // Don't call into the OperatingSystem to update the thread list if we
1164 // are shutting down, since that may call back into the SBAPI's,
1165 // requiring the API lock which is already held by whoever is shutting
1166 // us down, causing a deadlock.
1168 if (os && !m_destroy_in_process) {
1169 // Clear any old backing threads where memory threads might have been
1170 // backed by actual threads from the lldb_private::Process subclass
1171 size_t num_old_threads = old_thread_list.GetSize(false);
1172 for (size_t i = 0; i < num_old_threads; ++i)
1173 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1174 // See if the OS plugin reports all threads. If it does, then
1175 // it is safe to clear unseen thread's plans here. Otherwise we
1176 // should preserve them in case they show up again:
1177 clear_unused_threads = GetOSPluginReportsAllThreads();
1178
1179 // Turn off dynamic types to ensure we don't run any expressions.
1180 // Objective-C can run an expression to determine if a SBValue is a
1181 // dynamic type or not and we need to avoid this. OperatingSystem
1182 // plug-ins can't run expressions that require running code...
1183
1184 Target &target = GetTarget();
1185 const lldb::DynamicValueType saved_prefer_dynamic =
1186 target.GetPreferDynamicValue();
1187 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1189
1190 // Now let the OperatingSystem plug-in update the thread list
1191
1192 os->UpdateThreadList(
1193 old_thread_list, // Old list full of threads created by OS plug-in
1194 real_thread_list, // The actual thread list full of threads
1195 // created by each lldb_private::Process
1196 // subclass
1197 new_thread_list); // The new thread list that we will show to the
1198 // user that gets filled in
1199
1200 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1201 target.SetPreferDynamicValue(saved_prefer_dynamic);
1202 } else {
1203 // No OS plug-in, the new thread list is the same as the real thread
1204 // list.
1205 new_thread_list = real_thread_list;
1206 }
1207
1208 m_thread_list_real.Update(real_thread_list);
1209 m_thread_list.Update(new_thread_list);
1210 m_thread_list.SetStopID(stop_id);
1211
1213 // Clear any extended threads that we may have accumulated previously
1216
1219 }
1220 }
1221 // Now update the plan stack map.
1222 // If we do have an OS plugin, any absent real threads in the
1223 // m_thread_list have already been removed from the ThreadPlanStackMap.
1224 // So any remaining threads are OS Plugin threads, and those we want to
1225 // preserve in case they show up again.
1226 m_thread_plans.Update(m_thread_list, clear_unused_threads);
1227 }
1228 }
1229}
1230
1232 return m_thread_plans.Find(tid);
1233}
1234
1236 return m_thread_plans.PrunePlansForTID(tid);
1237}
1238
1240 m_thread_plans.Update(GetThreadList(), true, false);
1241}
1242
1244 lldb::DescriptionLevel desc_level,
1245 bool internal, bool condense_trivial,
1246 bool skip_unreported_plans) {
1248 strm, tid, desc_level, internal, condense_trivial, skip_unreported_plans);
1249}
1251 bool internal, bool condense_trivial,
1252 bool skip_unreported_plans) {
1253 m_thread_plans.DumpPlans(strm, desc_level, internal, condense_trivial,
1254 skip_unreported_plans);
1255}
1256
1258 if (m_system_runtime_up) {
1259 if (m_queue_list.GetSize() == 0 ||
1261 const StateType state = GetPrivateState();
1262 if (StateIsStoppedState(state, true)) {
1263 m_system_runtime_up->PopulateQueueList(m_queue_list);
1265 }
1266 }
1267 }
1268}
1269
1272 if (os)
1273 return os->CreateThread(tid, context);
1274 return ThreadSP();
1275}
1276
1277uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1278 return AssignIndexIDToThread(thread_id);
1279}
1280
1281bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1282 return (m_thread_id_to_index_id_map.find(thread_id) !=
1284}
1285
1286uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1287 uint32_t result = 0;
1288 std::map<uint64_t, uint32_t>::iterator iterator =
1289 m_thread_id_to_index_id_map.find(thread_id);
1290 if (iterator == m_thread_id_to_index_id_map.end()) {
1291 result = ++m_thread_index_id;
1292 m_thread_id_to_index_id_map[thread_id] = result;
1293 } else {
1294 result = iterator->second;
1295 }
1296
1297 return result;
1298}
1299
1302 return m_private_state.GetValue();
1303 else
1304 return m_public_state.GetValue();
1305}
1306
1307void Process::SetPublicState(StateType new_state, bool restarted) {
1308 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1309 if (new_state_is_stopped) {
1310 // This will only set the time if the public stop time has no value, so
1311 // it is ok to call this multiple times. With a public stop we can't look
1312 // at the stop ID because many private stops might have happened, so we
1313 // can't check for a stop ID of zero. This allows the "statistics" command
1314 // to dump the time it takes to reach somewhere in your code, like a
1315 // breakpoint you set.
1317 }
1318
1320 LLDB_LOGF(log, "(plugin = %s, state = %s, restarted = %i)",
1321 GetPluginName().data(), StateAsCString(new_state), restarted);
1322 const StateType old_state = m_public_state.GetValue();
1323 m_public_state.SetValue(new_state);
1324
1325 // On the transition from Run to Stopped, we unlock the writer end of the run
1326 // lock. The lock gets locked in Resume, which is the public API to tell the
1327 // program to run.
1329 if (new_state == eStateDetached) {
1330 LLDB_LOGF(log,
1331 "(plugin = %s, state = %s) -- unlocking run lock for detach",
1332 GetPluginName().data(), StateAsCString(new_state));
1334 } else {
1335 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1336 if ((old_state_is_stopped != new_state_is_stopped)) {
1337 if (new_state_is_stopped && !restarted) {
1338 LLDB_LOGF(log, "(plugin = %s, state = %s) -- unlocking run lock",
1339 GetPluginName().data(), StateAsCString(new_state));
1341 }
1342 }
1343 }
1344 }
1345}
1346
1349 LLDB_LOGF(log, "(plugin = %s) -- locking run lock", GetPluginName().data());
1351 Status error("Resume request failed - process still running.");
1352 LLDB_LOGF(log, "(plugin = %s) -- TrySetRunning failed, not resuming.",
1353 GetPluginName().data());
1354 return error;
1355 }
1357 if (!error.Success()) {
1358 // Undo running state change
1360 }
1361 return error;
1362}
1363
1366 LLDB_LOGF(log, "Process::ResumeSynchronous -- locking run lock");
1368 Status error("Resume request failed - process still running.");
1369 LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");
1370 return error;
1371 }
1372
1373 ListenerSP listener_sp(
1375 HijackProcessEvents(listener_sp);
1376
1378 if (error.Success()) {
1379 StateType state =
1380 WaitForProcessToStop(std::nullopt, nullptr, true, listener_sp, stream,
1381 true /* use_run_lock */, SelectMostRelevantFrame);
1382 const bool must_be_alive =
1383 false; // eStateExited is ok, so this must be false
1384 if (!StateIsStoppedState(state, must_be_alive))
1385 error.SetErrorStringWithFormat(
1386 "process not in stopped state after synchronous resume: %s",
1387 StateAsCString(state));
1388 } else {
1389 // Undo running state change
1391 }
1392
1393 // Undo the hijacking of process events...
1395
1396 return error;
1397}
1398
1401 llvm::StringRef hijacking_name = GetHijackingListenerName();
1402 if (!hijacking_name.starts_with("lldb.internal"))
1403 return true;
1404 }
1405 return false;
1406}
1407
1410 llvm::StringRef hijacking_name = GetHijackingListenerName();
1411 if (hijacking_name == ResumeSynchronousHijackListenerName)
1412 return true;
1413 }
1414 return false;
1415}
1416
1418
1420 // Use m_destructing not m_finalizing here. If we are finalizing a process
1421 // that we haven't started tearing down, we'd like to be able to nicely
1422 // detach if asked, but that requires the event system be live. That will
1423 // not be true for an in-the-middle-of-being-destructed Process, since the
1424 // event system relies on Process::shared_from_this, which may have already
1425 // been destroyed.
1426 if (m_destructing)
1427 return;
1428
1430 bool state_changed = false;
1431
1432 LLDB_LOGF(log, "(plugin = %s, state = %s)", GetPluginName().data(),
1433 StateAsCString(new_state));
1434
1435 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1436 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1437
1438 const StateType old_state = m_private_state.GetValueNoLock();
1439 state_changed = old_state != new_state;
1440
1441 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1442 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1443 if (old_state_is_stopped != new_state_is_stopped) {
1444 if (new_state_is_stopped)
1446 else
1448 }
1449
1450 if (state_changed) {
1452 EventSP event_sp(
1454 new ProcessEventData(shared_from_this(), new_state)));
1455 if (StateIsStoppedState(new_state, false)) {
1456 // Note, this currently assumes that all threads in the list stop when
1457 // the process stops. In the future we will want to support a debugging
1458 // model where some threads continue to run while others are stopped.
1459 // When that happens we will either need a way for the thread list to
1460 // identify which threads are stopping or create a special thread list
1461 // containing only threads which actually stopped.
1462 //
1463 // The process plugin is responsible for managing the actual behavior of
1464 // the threads and should have stopped any threads that are going to stop
1465 // before we get here.
1467
1468 if (m_mod_id.BumpStopID() == 0)
1470
1474 LLDB_LOGF(log, "(plugin = %s, state = %s, stop_id = %u",
1475 GetPluginName().data(), StateAsCString(new_state),
1477 }
1478
1480 } else {
1481 LLDB_LOGF(log, "(plugin = %s, state = %s) state didn't change. Ignoring...",
1482 GetPluginName().data(), StateAsCString(new_state));
1483 }
1484}
1485
1488}
1489
1492}
1493
1495
1497 if (!m_abi_sp)
1498 m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());
1499 return m_abi_sp;
1500}
1501
1502std::vector<LanguageRuntime *> Process::GetLanguageRuntimes() {
1503 std::vector<LanguageRuntime *> language_runtimes;
1504
1505 if (m_finalizing)
1506 return language_runtimes;
1507
1508 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
1509 // Before we pass off a copy of the language runtimes, we must make sure that
1510 // our collection is properly populated. It's possible that some of the
1511 // language runtimes were not loaded yet, either because nobody requested it
1512 // yet or the proper condition for loading wasn't yet met (e.g. libc++.so
1513 // hadn't been loaded).
1514 for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {
1515 if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type))
1516 language_runtimes.emplace_back(runtime);
1517 }
1518
1519 return language_runtimes;
1520}
1521
1523 if (m_finalizing)
1524 return nullptr;
1525
1526 LanguageRuntime *runtime = nullptr;
1527
1528 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
1529 LanguageRuntimeCollection::iterator pos;
1530 pos = m_language_runtimes.find(language);
1531 if (pos == m_language_runtimes.end() || !pos->second) {
1532 lldb::LanguageRuntimeSP runtime_sp(
1533 LanguageRuntime::FindPlugin(this, language));
1534
1535 m_language_runtimes[language] = runtime_sp;
1536 runtime = runtime_sp.get();
1537 } else
1538 runtime = pos->second.get();
1539
1540 if (runtime)
1541 // It's possible that a language runtime can support multiple LanguageTypes,
1542 // for example, CPPLanguageRuntime will support eLanguageTypeC_plus_plus,
1543 // eLanguageTypeC_plus_plus_03, etc. Because of this, we should get the
1544 // primary language type and make sure that our runtime supports it.
1545 assert(runtime->GetLanguageType() == Language::GetPrimaryLanguage(language));
1546
1547 return runtime;
1548}
1549
1551 if (m_finalizing)
1552 return false;
1553
1554 if (in_value.IsDynamic())
1555 return false;
1556 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1557
1558 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1559 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1560 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1561 }
1562
1563 for (LanguageRuntime *runtime : GetLanguageRuntimes()) {
1564 if (runtime->CouldHaveDynamicValue(in_value))
1565 return true;
1566 }
1567
1568 return false;
1569}
1570
1572 m_dynamic_checkers_up.reset(dynamic_checkers);
1573}
1574
1577}
1578
1582}
1583
1585 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1586 // bp_site->SetEnabled(true);
1587 DisableBreakpointSite(bp_site);
1588 });
1589}
1590
1593
1594 if (error.Success())
1596
1597 return error;
1598}
1599
1601 Status error;
1602 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1603 if (bp_site_sp) {
1604 if (bp_site_sp->IsEnabled())
1605 error = DisableBreakpointSite(bp_site_sp.get());
1606 } else {
1607 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1608 break_id);
1609 }
1610
1611 return error;
1612}
1613
1615 Status error;
1616 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1617 if (bp_site_sp) {
1618 if (!bp_site_sp->IsEnabled())
1619 error = EnableBreakpointSite(bp_site_sp.get());
1620 } else {
1621 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1622 break_id);
1623 }
1624 return error;
1625}
1626
1629 bool use_hardware) {
1630 addr_t load_addr = LLDB_INVALID_ADDRESS;
1631
1632 bool show_error = true;
1633 switch (GetState()) {
1634 case eStateInvalid:
1635 case eStateUnloaded:
1636 case eStateConnected:
1637 case eStateAttaching:
1638 case eStateLaunching:
1639 case eStateDetached:
1640 case eStateExited:
1641 show_error = false;
1642 break;
1643
1644 case eStateStopped:
1645 case eStateRunning:
1646 case eStateStepping:
1647 case eStateCrashed:
1648 case eStateSuspended:
1649 show_error = IsAlive();
1650 break;
1651 }
1652
1653 // Reset the IsIndirect flag here, in case the location changes from pointing
1654 // to a indirect symbol to a regular symbol.
1655 constituent->SetIsIndirect(false);
1656
1657 if (constituent->ShouldResolveIndirectFunctions()) {
1658 Symbol *symbol = constituent->GetAddress().CalculateSymbolContextSymbol();
1659 if (symbol && symbol->IsIndirect()) {
1660 Status error;
1661 Address symbol_address = symbol->GetAddress();
1662 load_addr = ResolveIndirectFunction(&symbol_address, error);
1663 if (!error.Success() && show_error) {
1665 "warning: failed to resolve indirect function at 0x%" PRIx64
1666 " for breakpoint %i.%i: %s\n",
1667 symbol->GetLoadAddress(&GetTarget()),
1668 constituent->GetBreakpoint().GetID(), constituent->GetID(),
1669 error.AsCString() ? error.AsCString() : "unknown error");
1670 return LLDB_INVALID_BREAK_ID;
1671 }
1672 Address resolved_address(load_addr);
1673 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1674 constituent->SetIsIndirect(true);
1675 } else
1676 load_addr = constituent->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1677 } else
1678 load_addr = constituent->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1679
1680 if (load_addr != LLDB_INVALID_ADDRESS) {
1681 BreakpointSiteSP bp_site_sp;
1682
1683 // Look up this breakpoint site. If it exists, then add this new
1684 // constituent, otherwise create a new breakpoint site and add it.
1685
1686 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1687
1688 if (bp_site_sp) {
1689 bp_site_sp->AddConstituent(constituent);
1690 constituent->SetBreakpointSite(bp_site_sp);
1691 return bp_site_sp->GetID();
1692 } else {
1693 bp_site_sp.reset(
1694 new BreakpointSite(constituent, load_addr, use_hardware));
1695 if (bp_site_sp) {
1696 Status error = EnableBreakpointSite(bp_site_sp.get());
1697 if (error.Success()) {
1698 constituent->SetBreakpointSite(bp_site_sp);
1699 return m_breakpoint_site_list.Add(bp_site_sp);
1700 } else {
1701 if (show_error || use_hardware) {
1702 // Report error for setting breakpoint...
1704 "warning: failed to set breakpoint site at 0x%" PRIx64
1705 " for breakpoint %i.%i: %s\n",
1706 load_addr, constituent->GetBreakpoint().GetID(),
1707 constituent->GetID(),
1708 error.AsCString() ? error.AsCString() : "unknown error");
1709 }
1710 }
1711 }
1712 }
1713 }
1714 // We failed to enable the breakpoint
1715 return LLDB_INVALID_BREAK_ID;
1716}
1717
1719 lldb::user_id_t constituent_id, lldb::user_id_t constituent_loc_id,
1720 BreakpointSiteSP &bp_site_sp) {
1721 uint32_t num_constituents =
1722 bp_site_sp->RemoveConstituent(constituent_id, constituent_loc_id);
1723 if (num_constituents == 0) {
1724 // Don't try to disable the site if we don't have a live process anymore.
1725 if (IsAlive())
1726 DisableBreakpointSite(bp_site_sp.get());
1727 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1728 }
1729}
1730
1732 uint8_t *buf) const {
1733 size_t bytes_removed = 0;
1734 StopPointSiteList<BreakpointSite> bp_sites_in_range;
1735
1736 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1737 bp_sites_in_range)) {
1738 bp_sites_in_range.ForEach([bp_addr, size,
1739 buf](BreakpointSite *bp_site) -> void {
1740 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1741 addr_t intersect_addr;
1742 size_t intersect_size;
1743 size_t opcode_offset;
1744 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1745 &intersect_size, &opcode_offset)) {
1746 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1747 assert(bp_addr < intersect_addr + intersect_size &&
1748 intersect_addr + intersect_size <= bp_addr + size);
1749 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1750 size_t buf_offset = intersect_addr - bp_addr;
1751 ::memcpy(buf + buf_offset,
1752 bp_site->GetSavedOpcodeBytes() + opcode_offset,
1753 intersect_size);
1754 }
1755 }
1756 });
1757 }
1758 return bytes_removed;
1759}
1760
1762 PlatformSP platform_sp(GetTarget().GetPlatform());
1763 if (platform_sp)
1764 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
1765 return 0;
1766}
1767
1769 Status error;
1770 assert(bp_site != nullptr);
1772 const addr_t bp_addr = bp_site->GetLoadAddress();
1773 LLDB_LOGF(
1774 log, "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
1775 bp_site->GetID(), (uint64_t)bp_addr);
1776 if (bp_site->IsEnabled()) {
1777 LLDB_LOGF(
1778 log,
1779 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1780 " -- already enabled",
1781 bp_site->GetID(), (uint64_t)bp_addr);
1782 return error;
1783 }
1784
1785 if (bp_addr == LLDB_INVALID_ADDRESS) {
1786 error.SetErrorString("BreakpointSite contains an invalid load address.");
1787 return error;
1788 }
1789 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1790 // trap for the breakpoint site
1791 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1792
1793 if (bp_opcode_size == 0) {
1794 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
1795 "returned zero, unable to get breakpoint "
1796 "trap for address 0x%" PRIx64,
1797 bp_addr);
1798 } else {
1799 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1800
1801 if (bp_opcode_bytes == nullptr) {
1802 error.SetErrorString(
1803 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1804 return error;
1805 }
1806
1807 // Save the original opcode by reading it
1808 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
1809 error) == bp_opcode_size) {
1810 // Write a software breakpoint in place of the original opcode
1811 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
1812 bp_opcode_size) {
1813 uint8_t verify_bp_opcode_bytes[64];
1814 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
1815 error) == bp_opcode_size) {
1816 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
1817 bp_opcode_size) == 0) {
1818 bp_site->SetEnabled(true);
1820 LLDB_LOGF(log,
1821 "Process::EnableSoftwareBreakpoint (site_id = %d) "
1822 "addr = 0x%" PRIx64 " -- SUCCESS",
1823 bp_site->GetID(), (uint64_t)bp_addr);
1824 } else
1825 error.SetErrorString(
1826 "failed to verify the breakpoint trap in memory.");
1827 } else
1828 error.SetErrorString(
1829 "Unable to read memory to verify breakpoint trap.");
1830 } else
1831 error.SetErrorString("Unable to write breakpoint trap to memory.");
1832 } else
1833 error.SetErrorString("Unable to read memory at breakpoint address.");
1834 }
1835 if (log && error.Fail())
1836 LLDB_LOGF(
1837 log,
1838 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1839 " -- FAILED: %s",
1840 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1841 return error;
1842}
1843
1845 Status error;
1846 assert(bp_site != nullptr);
1848 addr_t bp_addr = bp_site->GetLoadAddress();
1849 lldb::user_id_t breakID = bp_site->GetID();
1850 LLDB_LOGF(log,
1851 "Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
1852 ") addr = 0x%" PRIx64,
1853 breakID, (uint64_t)bp_addr);
1854
1855 if (bp_site->IsHardware()) {
1856 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1857 } else if (bp_site->IsEnabled()) {
1858 const size_t break_op_size = bp_site->GetByteSize();
1859 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
1860 if (break_op_size > 0) {
1861 // Clear a software breakpoint instruction
1862 uint8_t curr_break_op[8];
1863 assert(break_op_size <= sizeof(curr_break_op));
1864 bool break_op_found = false;
1865
1866 // Read the breakpoint opcode
1867 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
1868 break_op_size) {
1869 bool verify = false;
1870 // Make sure the breakpoint opcode exists at this address
1871 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
1872 break_op_found = true;
1873 // We found a valid breakpoint opcode at this address, now restore
1874 // the saved opcode.
1875 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
1876 break_op_size, error) == break_op_size) {
1877 verify = true;
1878 } else
1879 error.SetErrorString(
1880 "Memory write failed when restoring original opcode.");
1881 } else {
1882 error.SetErrorString(
1883 "Original breakpoint trap is no longer in memory.");
1884 // Set verify to true and so we can check if the original opcode has
1885 // already been restored
1886 verify = true;
1887 }
1888
1889 if (verify) {
1890 uint8_t verify_opcode[8];
1891 assert(break_op_size < sizeof(verify_opcode));
1892 // Verify that our original opcode made it back to the inferior
1893 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
1894 break_op_size) {
1895 // compare the memory we just read with the original opcode
1896 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
1897 break_op_size) == 0) {
1898 // SUCCESS
1899 bp_site->SetEnabled(false);
1900 LLDB_LOGF(log,
1901 "Process::DisableSoftwareBreakpoint (site_id = %d) "
1902 "addr = 0x%" PRIx64 " -- SUCCESS",
1903 bp_site->GetID(), (uint64_t)bp_addr);
1904 return error;
1905 } else {
1906 if (break_op_found)
1907 error.SetErrorString("Failed to restore original opcode.");
1908 }
1909 } else
1910 error.SetErrorString("Failed to read memory to verify that "
1911 "breakpoint trap was restored.");
1912 }
1913 } else
1914 error.SetErrorString(
1915 "Unable to read memory that should contain the breakpoint trap.");
1916 }
1917 } else {
1918 LLDB_LOGF(
1919 log,
1920 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1921 " -- already disabled",
1922 bp_site->GetID(), (uint64_t)bp_addr);
1923 return error;
1924 }
1925
1926 LLDB_LOGF(
1927 log,
1928 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1929 " -- FAILED: %s",
1930 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1931 return error;
1932}
1933
1934// Uncomment to verify memory caching works after making changes to caching
1935// code
1936//#define VERIFY_MEMORY_READS
1937
1938size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
1939 if (ABISP abi_sp = GetABI())
1940 addr = abi_sp->FixAnyAddress(addr);
1941
1942 error.Clear();
1943 if (!GetDisableMemoryCache()) {
1944#if defined(VERIFY_MEMORY_READS)
1945 // Memory caching is enabled, with debug verification
1946
1947 if (buf && size) {
1948 // Uncomment the line below to make sure memory caching is working.
1949 // I ran this through the test suite and got no assertions, so I am
1950 // pretty confident this is working well. If any changes are made to
1951 // memory caching, uncomment the line below and test your changes!
1952
1953 // Verify all memory reads by using the cache first, then redundantly
1954 // reading the same memory from the inferior and comparing to make sure
1955 // everything is exactly the same.
1956 std::string verify_buf(size, '\0');
1957 assert(verify_buf.size() == size);
1958 const size_t cache_bytes_read =
1959 m_memory_cache.Read(this, addr, buf, size, error);
1960 Status verify_error;
1961 const size_t verify_bytes_read =
1962 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
1963 verify_buf.size(), verify_error);
1964 assert(cache_bytes_read == verify_bytes_read);
1965 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1966 assert(verify_error.Success() == error.Success());
1967 return cache_bytes_read;
1968 }
1969 return 0;
1970#else // !defined(VERIFY_MEMORY_READS)
1971 // Memory caching is enabled, without debug verification
1972
1973 return m_memory_cache.Read(addr, buf, size, error);
1974#endif // defined (VERIFY_MEMORY_READS)
1975 } else {
1976 // Memory caching is disabled
1977
1978 return ReadMemoryFromInferior(addr, buf, size, error);
1979 }
1980}
1981
1982size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
1983 Status &error) {
1984 char buf[256];
1985 out_str.clear();
1986 addr_t curr_addr = addr;
1987 while (true) {
1988 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
1989 if (length == 0)
1990 break;
1991 out_str.append(buf, length);
1992 // If we got "length - 1" bytes, we didn't get the whole C string, we need
1993 // to read some more characters
1994 if (length == sizeof(buf) - 1)
1995 curr_addr += length;
1996 else
1997 break;
1998 }
1999 return out_str.size();
2000}
2001
2002// Deprecated in favor of ReadStringFromMemory which has wchar support and
2003// correct code to find null terminators.
2005 size_t dst_max_len,
2006 Status &result_error) {
2007 size_t total_cstr_len = 0;
2008 if (dst && dst_max_len) {
2009 result_error.Clear();
2010 // NULL out everything just to be safe
2011 memset(dst, 0, dst_max_len);
2012 Status error;
2013 addr_t curr_addr = addr;
2014 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2015 size_t bytes_left = dst_max_len - 1;
2016 char *curr_dst = dst;
2017
2018 while (bytes_left > 0) {
2019 addr_t cache_line_bytes_left =
2020 cache_line_size - (curr_addr % cache_line_size);
2021 addr_t bytes_to_read =
2022 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2023 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
2024
2025 if (bytes_read == 0) {
2026 result_error = error;
2027 dst[total_cstr_len] = '\0';
2028 break;
2029 }
2030 const size_t len = strlen(curr_dst);
2031
2032 total_cstr_len += len;
2033
2034 if (len < bytes_to_read)
2035 break;
2036
2037 curr_dst += bytes_read;
2038 curr_addr += bytes_read;
2039 bytes_left -= bytes_read;
2040 }
2041 } else {
2042 if (dst == nullptr)
2043 result_error.SetErrorString("invalid arguments");
2044 else
2045 result_error.Clear();
2046 }
2047 return total_cstr_len;
2048}
2049
2050size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
2051 Status &error) {
2053
2054 if (ABISP abi_sp = GetABI())
2055 addr = abi_sp->FixAnyAddress(addr);
2056
2057 if (buf == nullptr || size == 0)
2058 return 0;
2059
2060 size_t bytes_read = 0;
2061 uint8_t *bytes = (uint8_t *)buf;
2062
2063 while (bytes_read < size) {
2064 const size_t curr_size = size - bytes_read;
2065 const size_t curr_bytes_read =
2066 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2067 bytes_read += curr_bytes_read;
2068 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2069 break;
2070 }
2071
2072 // Replace any software breakpoint opcodes that fall into this range back
2073 // into "buf" before we return
2074 if (bytes_read > 0)
2075 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2076 return bytes_read;
2077}
2078
2080 size_t integer_byte_size,
2081 uint64_t fail_value,
2082 Status &error) {
2083 Scalar scalar;
2084 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2085 error))
2086 return scalar.ULongLong(fail_value);
2087 return fail_value;
2088}
2089
2091 size_t integer_byte_size,
2092 int64_t fail_value,
2093 Status &error) {
2094 Scalar scalar;
2095 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2096 error))
2097 return scalar.SLongLong(fail_value);
2098 return fail_value;
2099}
2100
2102 Scalar scalar;
2103 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2104 error))
2105 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2106 return LLDB_INVALID_ADDRESS;
2107}
2108
2110 Status &error) {
2111 Scalar scalar;
2112 const uint32_t addr_byte_size = GetAddressByteSize();
2113 if (addr_byte_size <= 4)
2114 scalar = (uint32_t)ptr_value;
2115 else
2116 scalar = ptr_value;
2117 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2118 addr_byte_size;
2119}
2120
2121size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
2122 Status &error) {
2123 size_t bytes_written = 0;
2124 const uint8_t *bytes = (const uint8_t *)buf;
2125
2126 while (bytes_written < size) {
2127 const size_t curr_size = size - bytes_written;
2128 const size_t curr_bytes_written = DoWriteMemory(
2129 addr + bytes_written, bytes + bytes_written, curr_size, error);
2130 bytes_written += curr_bytes_written;
2131 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2132 break;
2133 }
2134 return bytes_written;
2135}
2136
2137size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
2138 Status &error) {
2139 if (ABISP abi_sp = GetABI())
2140 addr = abi_sp->FixAnyAddress(addr);
2141
2142#if defined(ENABLE_MEMORY_CACHING)
2143 m_memory_cache.Flush(addr, size);
2144#endif
2145
2146 if (buf == nullptr || size == 0)
2147 return 0;
2148
2150
2151 // We need to write any data that would go where any current software traps
2152 // (enabled software breakpoints) any software traps (breakpoints) that we
2153 // may have placed in our tasks memory.
2154
2155 StopPointSiteList<BreakpointSite> bp_sites_in_range;
2156 if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range))
2157 return WriteMemoryPrivate(addr, buf, size, error);
2158
2159 // No breakpoint sites overlap
2160 if (bp_sites_in_range.IsEmpty())
2161 return WriteMemoryPrivate(addr, buf, size, error);
2162
2163 const uint8_t *ubuf = (const uint8_t *)buf;
2164 uint64_t bytes_written = 0;
2165
2166 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2167 &error](BreakpointSite *bp) -> void {
2168 if (error.Fail())
2169 return;
2170
2172 return;
2173
2174 addr_t intersect_addr;
2175 size_t intersect_size;
2176 size_t opcode_offset;
2177 const bool intersects = bp->IntersectsRange(
2178 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2179 UNUSED_IF_ASSERT_DISABLED(intersects);
2180 assert(intersects);
2181 assert(addr <= intersect_addr && intersect_addr < addr + size);
2182 assert(addr < intersect_addr + intersect_size &&
2183 intersect_addr + intersect_size <= addr + size);
2184 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2185
2186 // Check for bytes before this breakpoint
2187 const addr_t curr_addr = addr + bytes_written;
2188 if (intersect_addr > curr_addr) {
2189 // There are some bytes before this breakpoint that we need to just
2190 // write to memory
2191 size_t curr_size = intersect_addr - curr_addr;
2192 size_t curr_bytes_written =
2193 WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error);
2194 bytes_written += curr_bytes_written;
2195 if (curr_bytes_written != curr_size) {
2196 // We weren't able to write all of the requested bytes, we are
2197 // done looping and will return the number of bytes that we have
2198 // written so far.
2199 if (error.Success())
2200 error.SetErrorToGenericError();
2201 }
2202 }
2203 // Now write any bytes that would cover up any software breakpoints
2204 // directly into the breakpoint opcode buffer
2205 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written,
2206 intersect_size);
2207 bytes_written += intersect_size;
2208 });
2209
2210 // Write any remaining bytes after the last breakpoint if we have any left
2211 if (bytes_written < size)
2212 bytes_written +=
2213 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2214 size - bytes_written, error);
2215
2216 return bytes_written;
2217}
2218
2219size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
2220 size_t byte_size, Status &error) {
2221 if (byte_size == UINT32_MAX)
2222 byte_size = scalar.GetByteSize();
2223 if (byte_size > 0) {
2224 uint8_t buf[32];
2225 const size_t mem_size =
2226 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2227 if (mem_size > 0)
2228 return WriteMemory(addr, buf, mem_size, error);
2229 else
2230 error.SetErrorString("failed to get scalar as memory data");
2231 } else {
2232 error.SetErrorString("invalid scalar value");
2233 }
2234 return 0;
2235}
2236
2237size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2238 bool is_signed, Scalar &scalar,
2239 Status &error) {
2240 uint64_t uval = 0;
2241 if (byte_size == 0) {
2242 error.SetErrorString("byte size is zero");
2243 } else if (byte_size & (byte_size - 1)) {
2244 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2245 byte_size);
2246 } else if (byte_size <= sizeof(uval)) {
2247 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2248 if (bytes_read == byte_size) {
2249 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2251 lldb::offset_t offset = 0;
2252 if (byte_size <= 4)
2253 scalar = data.GetMaxU32(&offset, byte_size);
2254 else
2255 scalar = data.GetMaxU64(&offset, byte_size);
2256 if (is_signed)
2257 scalar.SignExtend(byte_size * 8);
2258 return bytes_read;
2259 }
2260 } else {
2261 error.SetErrorStringWithFormat(
2262 "byte size of %u is too large for integer scalar type", byte_size);
2263 }
2264 return 0;
2265}
2266
2267Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {
2268 Status error;
2269 for (const auto &Entry : entries) {
2270 WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),
2271 error);
2272 if (!error.Success())
2273 break;
2274 }
2275 return error;
2276}
2277
2278#define USE_ALLOCATE_MEMORY_CACHE 1
2279addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
2280 Status &error) {
2281 if (GetPrivateState() != eStateStopped) {
2282 error.SetErrorToGenericError();
2283 return LLDB_INVALID_ADDRESS;
2284 }
2285
2286#if defined(USE_ALLOCATE_MEMORY_CACHE)
2287 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2288#else
2289 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2290 Log *log = GetLog(LLDBLog::Process);
2291 LLDB_LOGF(log,
2292 "Process::AllocateMemory(size=%" PRIu64
2293 ", permissions=%s) => 0x%16.16" PRIx64
2294 " (m_stop_id = %u m_memory_id = %u)",
2295 (uint64_t)size, GetPermissionsAsCString(permissions),
2296 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2298 return allocated_addr;
2299#endif
2300}
2301
2302addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
2303 Status &error) {
2304 addr_t return_addr = AllocateMemory(size, permissions, error);
2305 if (error.Success()) {
2306 std::string buffer(size, 0);
2307 WriteMemory(return_addr, buffer.c_str(), size, error);
2308 }
2309 return return_addr;
2310}
2311
2313 if (m_can_jit == eCanJITDontKnow) {
2314 Log *log = GetLog(LLDBLog::Process);
2315 Status err;
2316
2317 uint64_t allocated_memory = AllocateMemory(
2318 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2319 err);
2320
2321 if (err.Success()) {
2323 LLDB_LOGF(log,
2324 "Process::%s pid %" PRIu64
2325 " allocation test passed, CanJIT () is true",
2326 __FUNCTION__, GetID());
2327 } else {
2329 LLDB_LOGF(log,
2330 "Process::%s pid %" PRIu64
2331 " allocation test failed, CanJIT () is false: %s",
2332 __FUNCTION__, GetID(), err.AsCString());
2333 }
2334
2335 DeallocateMemory(allocated_memory);
2336 }
2337
2338 return m_can_jit == eCanJITYes;
2339}
2340
2341void Process::SetCanJIT(bool can_jit) {
2342 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2343}
2344
2345void Process::SetCanRunCode(bool can_run_code) {
2346 SetCanJIT(can_run_code);
2347 m_can_interpret_function_calls = can_run_code;
2348}
2349
2351 Status error;
2352#if defined(USE_ALLOCATE_MEMORY_CACHE)
2354 error.SetErrorStringWithFormat(
2355 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2356 }
2357#else
2359
2360 Log *log = GetLog(LLDBLog::Process);
2361 LLDB_LOGF(log,
2362 "Process::DeallocateMemory(addr=0x%16.16" PRIx64
2363 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2364 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2366#endif
2367 return error;
2368}
2369
2371 if (std::optional<bool> subclass_override = DoGetWatchpointReportedAfter())
2372 return *subclass_override;
2373
2374 bool reported_after = true;
2375 const ArchSpec &arch = GetTarget().GetArchitecture();
2376 if (!arch.IsValid())
2377 return reported_after;
2378 llvm::Triple triple = arch.GetTriple();
2379
2380 if (triple.isMIPS() || triple.isPPC64() || triple.isRISCV() ||
2381 triple.isAArch64() || triple.isArmMClass() || triple.isARM())
2382 reported_after = false;
2383
2384 return reported_after;
2385}
2386
2388 lldb::addr_t header_addr,
2389 size_t size_to_read) {
2390 Log *log = GetLog(LLDBLog::Host);
2391 if (log) {
2392 LLDB_LOGF(log,
2393 "Process::ReadModuleFromMemory reading %s binary from memory",
2394 file_spec.GetPath().c_str());
2395 }
2396 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2397 if (module_sp) {
2398 Status error;
2399 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2400 shared_from_this(), header_addr, error, size_to_read);
2401 if (objfile)
2402 return module_sp;
2403 }
2404 return ModuleSP();
2405}
2406
2408 uint32_t &permissions) {
2409 MemoryRegionInfo range_info;
2410 permissions = 0;
2411 Status error(GetMemoryRegionInfo(load_addr, range_info));
2412 if (!error.Success())
2413 return false;
2414 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2415 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2417 return false;
2418 }
2419 permissions = range_info.GetLLDBPermissions();
2420 return true;
2421}
2422
2424 Status error;
2425 error.SetErrorString("watchpoints are not supported");
2426 return error;
2427}
2428
2430 Status error;
2431 error.SetErrorString("watchpoints are not supported");
2432 return error;
2433}
2434
2437 const Timeout<std::micro> &timeout) {
2438 StateType state;
2439
2440 while (true) {
2441 event_sp.reset();
2442 state = GetStateChangedEventsPrivate(event_sp, timeout);
2443
2444 if (StateIsStoppedState(state, false))
2445 break;
2446
2447 // If state is invalid, then we timed out
2448 if (state == eStateInvalid)
2449 break;
2450
2451 if (event_sp)
2452 HandlePrivateEvent(event_sp);
2453 }
2454 return state;
2455}
2456
2458 std::lock_guard<std::recursive_mutex> guard(m_thread_mutex);
2459 if (flush)
2461 m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr));
2462 if (flush)
2463 Flush();
2464}
2465
2467 StateType state_after_launch = eStateInvalid;
2468 EventSP first_stop_event_sp;
2469 Status status =
2470 LaunchPrivate(launch_info, state_after_launch, first_stop_event_sp);
2471 if (status.Fail())
2472 return status;
2473
2474 if (state_after_launch != eStateStopped &&
2475 state_after_launch != eStateCrashed)
2476 return Status();
2477
2478 // Note, the stop event was consumed above, but not handled. This
2479 // was done to give DidLaunch a chance to run. The target is either
2480 // stopped or crashed. Directly set the state. This is done to
2481 // prevent a stop message with a bunch of spurious output on thread
2482 // status, as well as not pop a ProcessIOHandler.
2483 SetPublicState(state_after_launch, false);
2484
2487 else
2489
2490 // Target was stopped at entry as was intended. Need to notify the
2491 // listeners about it.
2492 if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2493 HandlePrivateEvent(first_stop_event_sp);
2494
2495 return Status();
2496}
2497
2499 EventSP &event_sp) {
2500 Status error;
2501 m_abi_sp.reset();
2502 m_dyld_up.reset();
2503 m_jit_loaders_up.reset();
2504 m_system_runtime_up.reset();
2505 m_os_up.reset();
2506
2507 {
2508 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
2509 m_process_input_reader.reset();
2510 }
2511
2513
2514 // The "remote executable path" is hooked up to the local Executable
2515 // module. But we should be able to debug a remote process even if the
2516 // executable module only exists on the remote. However, there needs to
2517 // be a way to express this path, without actually having a module.
2518 // The way to do that is to set the ExecutableFile in the LaunchInfo.
2519 // Figure that out here:
2520
2521 FileSpec exe_spec_to_use;
2522 if (!exe_module) {
2523 if (!launch_info.GetExecutableFile() && !launch_info.IsScriptedProcess()) {
2524 error.SetErrorString("executable module does not exist");
2525 return error;
2526 }
2527 exe_spec_to_use = launch_info.GetExecutableFile();
2528 } else
2529 exe_spec_to_use = exe_module->GetFileSpec();
2530
2531 if (exe_module && FileSystem::Instance().Exists(exe_module->GetFileSpec())) {
2532 // Install anything that might need to be installed prior to launching.
2533 // For host systems, this will do nothing, but if we are connected to a
2534 // remote platform it will install any needed binaries
2535 error = GetTarget().Install(&launch_info);
2536 if (error.Fail())
2537 return error;
2538 }
2539
2540 // Listen and queue events that are broadcasted during the process launch.
2541 ListenerSP listener_sp(Listener::MakeListener("LaunchEventHijack"));
2542 HijackProcessEvents(listener_sp);
2543 auto on_exit = llvm::make_scope_exit([this]() { RestoreProcessEvents(); });
2544
2547
2548 error = WillLaunch(exe_module);
2549 if (error.Fail()) {
2550 std::string local_exec_file_path = exe_spec_to_use.GetPath();
2551 return Status("file doesn't exist: '%s'", local_exec_file_path.c_str());
2552 }
2553
2554 const bool restarted = false;
2555 SetPublicState(eStateLaunching, restarted);
2556 m_should_detach = false;
2557
2559 // Now launch using these arguments.
2560 error = DoLaunch(exe_module, launch_info);
2561 } else {
2562 // This shouldn't happen
2563 error.SetErrorString("failed to acquire process run lock");
2564 }
2565
2566 if (error.Fail()) {
2567 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2569 const char *error_string = error.AsCString();
2570 if (error_string == nullptr)
2571 error_string = "launch failed";
2572 SetExitStatus(-1, error_string);
2573 }
2574 return error;
2575 }
2576
2577 // Now wait for the process to launch and return control to us, and then
2578 // call DidLaunch:
2579 state = WaitForProcessStopPrivate(event_sp, seconds(10));
2580
2581 if (state == eStateInvalid || !event_sp) {
2582 // We were able to launch the process, but we failed to catch the
2583 // initial stop.
2584 error.SetErrorString("failed to catch stop after launch");
2585 SetExitStatus(0, error.AsCString());
2586 Destroy(false);
2587 return error;
2588 }
2589
2590 if (state == eStateExited) {
2591 // We exited while trying to launch somehow. Don't call DidLaunch
2592 // as that's not likely to work, and return an invalid pid.
2593 HandlePrivateEvent(event_sp);
2594 return Status();
2595 }
2596
2597 if (state == eStateStopped || state == eStateCrashed) {
2598 DidLaunch();
2599
2600 // Now that we know the process type, update its signal responses from the
2601 // ones stored in the Target:
2602 if (m_unix_signals_sp) {
2605 }
2606
2608 if (dyld)
2609 dyld->DidLaunch();
2610
2612
2613 SystemRuntime *system_runtime = GetSystemRuntime();
2614 if (system_runtime)
2615 system_runtime->DidLaunch();
2616
2617 if (!m_os_up)
2619
2620 // We successfully launched the process and stopped, now it the
2621 // right time to set up signal filters before resuming.
2623 return Status();
2624 }
2625
2626 return Status("Unexpected process state after the launch: %s, expected %s, "
2627 "%s, %s or %s",
2631}
2632
2635 if (error.Success()) {
2636 ListenerSP listener_sp(
2637 Listener::MakeListener("lldb.process.load_core_listener"));
2638 HijackProcessEvents(listener_sp);
2639
2642 else
2644
2646 if (dyld)
2647 dyld->DidAttach();
2648
2650
2651 SystemRuntime *system_runtime = GetSystemRuntime();
2652 if (system_runtime)
2653 system_runtime->DidAttach();
2654
2655 if (!m_os_up)
2657
2658 // We successfully loaded a core file, now pretend we stopped so we can
2659 // show all of the threads in the core file and explore the crashed state.
2661
2662 // Wait for a stopped event since we just posted one above...
2663 lldb::EventSP event_sp;
2664 StateType state =
2665 WaitForProcessToStop(std::nullopt, &event_sp, true, listener_sp,
2666 nullptr, true, SelectMostRelevantFrame);
2667
2668 if (!StateIsStoppedState(state, false)) {
2669 Log *log = GetLog(LLDBLog::Process);
2670 LLDB_LOGF(log, "Process::Halt() failed to stop, state is: %s",
2671 StateAsCString(state));
2672 error.SetErrorString(
2673 "Did not get stopped event after loading the core file.");
2674 }
2676 }
2677 return error;
2678}
2679
2681 if (!m_dyld_up)
2682 m_dyld_up.reset(DynamicLoader::FindPlugin(this, ""));
2683 return m_dyld_up.get();
2684}
2685
2687 m_dyld_up = std::move(dyld_up);
2688}
2689
2691
2692llvm::Expected<bool> Process::SaveCore(llvm::StringRef outfile) {
2693 return false;
2694}
2695
2697 if (!m_jit_loaders_up) {
2698 m_jit_loaders_up = std::make_unique<JITLoaderList>();
2700 }
2701 return *m_jit_loaders_up;
2702}
2703
2707 return m_system_runtime_up.get();
2708}
2709
2711 uint32_t exec_count)
2712 : NextEventAction(process), m_exec_count(exec_count) {
2713 Log *log = GetLog(LLDBLog::Process);
2714 LLDB_LOGF(
2715 log,
2716 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2717 __FUNCTION__, static_cast<void *>(process), exec_count);
2718}
2719
2722 Log *log = GetLog(LLDBLog::Process);
2723
2724 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2725 LLDB_LOGF(log,
2726 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2727 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
2728
2729 switch (state) {
2730 case eStateAttaching:
2731 return eEventActionSuccess;
2732
2733 case eStateRunning:
2734 case eStateConnected:
2735 return eEventActionRetry;
2736
2737 case eStateStopped:
2738 case eStateCrashed:
2739 // During attach, prior to sending the eStateStopped event,
2740 // lldb_private::Process subclasses must set the new process ID.
2742 // We don't want these events to be reported, so go set the
2743 // ShouldReportStop here:
2745
2746 if (m_exec_count > 0) {
2747 --m_exec_count;
2748
2749 LLDB_LOGF(log,
2750 "Process::AttachCompletionHandler::%s state %s: reduced "
2751 "remaining exec count to %" PRIu32 ", requesting resume",
2752 __FUNCTION__, StateAsCString(state), m_exec_count);
2753
2754 RequestResume();
2755 return eEventActionRetry;
2756 } else {
2757 LLDB_LOGF(log,
2758 "Process::AttachCompletionHandler::%s state %s: no more "
2759 "execs expected to start, continuing with attach",
2760 __FUNCTION__, StateAsCString(state));
2761
2763 return eEventActionSuccess;
2764 }
2765 break;
2766
2767 default:
2768 case eStateExited:
2769 case eStateInvalid:
2770 break;
2771 }
2772
2773 m_exit_string.assign("No valid Process");
2774 return eEventActionExit;
2775}
2776
2779 return eEventActionSuccess;
2780}
2781
2783 return m_exit_string.c_str();
2784}
2785
2787 if (m_listener_sp)
2788 return m_listener_sp;
2789 else
2790 return debugger.GetListener();
2791}
2792
2794 return DoWillLaunch(module);
2795}
2796
2798 return DoWillAttachToProcessWithID(pid);
2799}
2800
2802 bool wait_for_launch) {
2803 return DoWillAttachToProcessWithName(process_name, wait_for_launch);
2804}
2805
2807 m_abi_sp.reset();
2808 {
2809 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
2810 m_process_input_reader.reset();
2811 }
2812 m_dyld_up.reset();
2813 m_jit_loaders_up.reset();
2814 m_system_runtime_up.reset();
2815 m_os_up.reset();
2816
2817 lldb::pid_t attach_pid = attach_info.GetProcessID();
2818 Status error;
2819 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
2820 char process_name[PATH_MAX];
2821
2822 if (attach_info.GetExecutableFile().GetPath(process_name,
2823 sizeof(process_name))) {
2824 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2825
2826 if (wait_for_launch) {
2827 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2828 if (error.Success()) {
2830 m_should_detach = true;
2831 const bool restarted = false;
2832 SetPublicState(eStateAttaching, restarted);
2833 // Now attach using these arguments.
2834 error = DoAttachToProcessWithName(process_name, attach_info);
2835 } else {
2836 // This shouldn't happen
2837 error.SetErrorString("failed to acquire process run lock");
2838 }
2839
2840 if (error.Fail()) {
2841 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2843 if (error.AsCString() == nullptr)
2844 error.SetErrorString("attach failed");
2845
2846 SetExitStatus(-1, error.AsCString());
2847 }
2848 } else {
2850 this, attach_info.GetResumeCount()));
2852 }
2853 return error;
2854 }
2855 } else {
2856 ProcessInstanceInfoList process_infos;
2857 PlatformSP platform_sp(GetTarget().GetPlatform());
2858
2859 if (platform_sp) {
2860 ProcessInstanceInfoMatch match_info;
2861 match_info.GetProcessInfo() = attach_info;
2863 platform_sp->FindProcesses(match_info, process_infos);
2864 const uint32_t num_matches = process_infos.size();
2865 if (num_matches == 1) {
2866 attach_pid = process_infos[0].GetProcessID();
2867 // Fall through and attach using the above process ID
2868 } else {
2870 process_name, sizeof(process_name));
2871 if (num_matches > 1) {
2872 StreamString s;
2874 for (size_t i = 0; i < num_matches; i++) {
2875 process_infos[i].DumpAsTableRow(
2876 s, platform_sp->GetUserIDResolver(), true, false);
2877 }
2878 error.SetErrorStringWithFormat(
2879 "more than one process named %s:\n%s", process_name,
2880 s.GetData());
2881 } else
2882 error.SetErrorStringWithFormat(
2883 "could not find a process named %s", process_name);
2884 }
2885 } else {
2886 error.SetErrorString(
2887 "invalid platform, can't find processes by name");
2888 return error;
2889 }
2890 }
2891 } else {
2892 error.SetErrorString("invalid process name");
2893 }
2894 }
2895
2896 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
2897 error = WillAttachToProcessWithID(attach_pid);
2898 if (error.Success()) {
2899
2901 // Now attach using these arguments.
2902 m_should_detach = true;
2903 const bool restarted = false;
2904 SetPublicState(eStateAttaching, restarted);
2905 error = DoAttachToProcessWithID(attach_pid, attach_info);
2906 } else {
2907 // This shouldn't happen
2908 error.SetErrorString("failed to acquire process run lock");
2909 }
2910
2911 if (error.Success()) {
2913 this, attach_info.GetResumeCount()));
2915 } else {
2918
2919 const char *error_string = error.AsCString();
2920 if (error_string == nullptr)
2921 error_string = "attach failed";
2922
2923 SetExitStatus(-1, error_string);
2924 }
2925 }
2926 }
2927 return error;
2928}
2929
2932 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
2933
2934 // Let the process subclass figure out at much as it can about the process
2935 // before we go looking for a dynamic loader plug-in.
2936 ArchSpec process_arch;
2937 DidAttach(process_arch);
2938
2939 if (process_arch.IsValid()) {
2940 LLDB_LOG(log,
2941 "Process::{0} replacing process architecture with DidAttach() "
2942 "architecture: \"{1}\"",
2943 __FUNCTION__, process_arch.GetTriple().getTriple());
2944 GetTarget().SetArchitecture(process_arch);
2945 }
2946
2947 // We just attached. If we have a platform, ask it for the process
2948 // architecture, and if it isn't the same as the one we've already set,
2949 // switch architectures.
2950 PlatformSP platform_sp(GetTarget().GetPlatform());
2951 assert(platform_sp);
2952 ArchSpec process_host_arch = GetSystemArchitecture();
2953 if (platform_sp) {
2954 const ArchSpec &target_arch = GetTarget().GetArchitecture();
2955 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture(
2956 target_arch, process_host_arch,
2957 ArchSpec::CompatibleMatch, nullptr)) {
2958 ArchSpec platform_arch;
2960 target_arch, process_host_arch, &platform_arch);
2961 if (platform_sp) {
2962 GetTarget().SetPlatform(platform_sp);
2963 GetTarget().SetArchitecture(platform_arch);
2964 LLDB_LOG(log,
2965 "switching platform to {0} and architecture to {1} based on "
2966 "info from attach",
2967 platform_sp->GetName(), platform_arch.GetTriple().getTriple());
2968 }
2969 } else if (!process_arch.IsValid()) {
2970 ProcessInstanceInfo process_info;
2971 GetProcessInfo(process_info);
2972 const ArchSpec &process_arch = process_info.GetArchitecture();
2973 const ArchSpec &target_arch = GetTarget().GetArchitecture();
2974 if (process_arch.IsValid() &&
2975 target_arch.IsCompatibleMatch(process_arch) &&
2976 !target_arch.IsExactMatch(process_arch)) {
2977 GetTarget().SetArchitecture(process_arch);
2978 LLDB_LOGF(log,
2979 "Process::%s switching architecture to %s based on info "
2980 "the platform retrieved for pid %" PRIu64,
2981 __FUNCTION__, process_arch.GetTriple().getTriple().c_str(),
2982 GetID());
2983 }
2984 }
2985 }
2986 // Now that we know the process type, update its signal responses from the
2987 // ones stored in the Target:
2988 if (m_unix_signals_sp) {
2991 }
2992
2993 // We have completed the attach, now it is time to find the dynamic loader
2994 // plug-in
2996 if (dyld) {
2997 dyld->DidAttach();
2998 if (log) {
2999 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3000 LLDB_LOG(log,
3001 "after DynamicLoader::DidAttach(), target "
3002 "executable is {0} (using {1} plugin)",
3003 exe_module_sp ? exe_module_sp->GetFileSpec() : FileSpec(),
3004 dyld->GetPluginName());
3005 }
3006 }
3007
3009
3010 SystemRuntime *system_runtime = GetSystemRuntime();
3011 if (system_runtime) {
3012 system_runtime->DidAttach();
3013 if (log) {
3014 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3015 LLDB_LOG(log,
3016 "after SystemRuntime::DidAttach(), target "
3017 "executable is {0} (using {1} plugin)",
3018 exe_module_sp ? exe_module_sp->GetFileSpec() : FileSpec(),
3019 system_runtime->GetPluginName());
3020 }
3021 }
3022
3023 if (!m_os_up) {
3025 if (m_os_up) {
3026 // Somebody might have gotten threads before now, but we need to force the
3027 // update after we've loaded the OperatingSystem plugin or it won't get a
3028 // chance to process the threads.
3031 }
3032 }
3033 // Figure out which one is the executable, and set that in our target:
3034 ModuleSP new_executable_module_sp;
3035 for (ModuleSP module_sp : GetTarget().GetImages().Modules()) {
3036 if (module_sp && module_sp->IsExecutable()) {
3037 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3038 new_executable_module_sp = module_sp;
3039 break;
3040 }
3041 }
3042 if (new_executable_module_sp) {
3043 GetTarget().SetExecutableModule(new_executable_module_sp,
3045 if (log) {
3046 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3047 LLDB_LOGF(
3048 log,
3049 "Process::%s after looping through modules, target executable is %s",
3050 __FUNCTION__,
3051 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3052 : "<none>");
3053 }
3054 }
3055}
3056
3057Status Process::ConnectRemote(llvm::StringRef remote_url) {
3058 m_abi_sp.reset();
3059 {
3060 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
3061 m_process_input_reader.reset();
3062 }
3063
3064 // Find the process and its architecture. Make sure it matches the
3065 // architecture of the current Target, and if not adjust it.
3066
3067 Status error(DoConnectRemote(remote_url));
3068 if (error.Success()) {
3069 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3070 EventSP event_sp;
3071 StateType state = WaitForProcessStopPrivate(event_sp, std::nullopt);
3072
3073 if (state == eStateStopped || state == eStateCrashed) {
3074 // If we attached and actually have a process on the other end, then
3075 // this ended up being the equivalent of an attach.
3077
3078 // This delays passing the stopped event to listeners till
3079 // CompleteAttach gets a chance to complete...
3080 HandlePrivateEvent(event_sp);
3081 }
3082 }
3083
3086 else
3088 }
3089 return error;
3090}
3091
3094 LLDB_LOGF(log,
3095 "Process::PrivateResume() m_stop_id = %u, public state: %s "
3096 "private state: %s",
3099
3100 // If signals handing status changed we might want to update our signal
3101 // filters before resuming.
3103
3105 // Tell the process it is about to resume before the thread list
3106 if (error.Success()) {
3107 // Now let the thread list know we are about to resume so it can let all of
3108 // our threads know that they are about to be resumed. Threads will each be
3109 // called with Thread::WillResume(StateType) where StateType contains the
3110 // state that they are supposed to have when the process is resumed
3111 // (suspended/running/stepping). Threads should also check their resume
3112 // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
3113 // start back up with a signal.
3114 if (m_thread_list.WillResume()) {
3115 // Last thing, do the PreResumeActions.
3116 if (!RunPreResumeActions()) {
3117 error.SetErrorString(
3118 "Process::PrivateResume PreResumeActions failed, not resuming.");
3119 } else {
3121 error = DoResume();
3122 if (error.Success()) {
3123 DidResume();
3125 LLDB_LOGF(log, "Process thinks the process has resumed.");
3126 } else {
3127 LLDB_LOGF(log, "Process::PrivateResume() DoResume failed.");
3128 return error;
3129 }
3130 }
3131 } else {
3132 // Somebody wanted to run without running (e.g. we were faking a step
3133 // from one frame of a set of inlined frames that share the same PC to
3134 // another.) So generate a continue & a stopped event, and let the world
3135 // handle them.
3136 LLDB_LOGF(log,
3137 "Process::PrivateResume() asked to simulate a start & stop.");
3138
3141 }
3142 } else
3143 LLDB_LOGF(log, "Process::PrivateResume() got an error \"%s\".",
3144 error.AsCString("<unknown error>"));
3145 return error;
3146}
3147
3148Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
3150 return Status("Process is not running.");
3151
3152 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
3153 // case it was already set and some thread plan logic calls halt on its own.
3154 m_clear_thread_plans_on_stop |= clear_thread_plans;
3155
3156 ListenerSP halt_listener_sp(
3157 Listener::MakeListener("lldb.process.halt_listener"));
3158 HijackProcessEvents(halt_listener_sp);
3159
3160 EventSP event_sp;
3161
3163
3165 // Don't hijack and eat the eStateExited as the code that was doing the
3166 // attach will be waiting for this event...
3168 Destroy(false);
3169 SetExitStatus(SIGKILL, "Cancelled async attach.");
3170 return Status();
3171 }
3172
3173 // Wait for the process halt timeout seconds for the process to stop.
3174 // If we are going to use the run lock, that means we're stopping out to the
3175 // user, so we should also select the most relevant frame.
3176 SelectMostRelevant select_most_relevant =
3178 StateType state = WaitForProcessToStop(GetInterruptTimeout(), &event_sp, true,
3179 halt_listener_sp, nullptr,
3180 use_run_lock, select_most_relevant);
3182
3183 if (state == eStateInvalid || !event_sp) {
3184 // We timed out and didn't get a stop event...
3185 return Status("Halt timed out. State = %s", StateAsCString(GetState()));
3186 }
3187
3188 BroadcastEvent(event_sp);
3189
3190 return Status();
3191}
3192
3194 Status error;
3195
3196 // Check both the public & private states here. If we're hung evaluating an
3197 // expression, for instance, then the public state will be stopped, but we
3198 // still need to interrupt.
3201 Log *log = GetLog(LLDBLog::Process);
3202 LLDB_LOGF(log, "Process::%s() About to stop.", __FUNCTION__);
3203
3204 ListenerSP listener_sp(
3205 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3206 HijackProcessEvents(listener_sp);
3207
3209
3210 // Consume the interrupt event.
3212 &exit_event_sp, true, listener_sp);
3213
3215
3216 // If the process exited while we were waiting for it to stop, put the
3217 // exited event into the shared pointer passed in and return. Our caller
3218 // doesn't need to do anything else, since they don't have a process
3219 // anymore...
3220
3221 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
3222 LLDB_LOGF(log, "Process::%s() Process exited while waiting to stop.",
3223 __FUNCTION__);
3224 return error;
3225 } else
3226 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3227
3228 if (state != eStateStopped) {
3229 LLDB_LOGF(log, "Process::%s() failed to stop, state is: %s", __FUNCTION__,
3230 StateAsCString(state));
3231 // If we really couldn't stop the process then we should just error out
3232 // here, but if the lower levels just bobbled sending the event and we
3233 // really are stopped, then continue on.
3234 StateType private_state = m_private_state.GetValue();
3235 if (private_state != eStateStopped) {
3236 return Status(
3237 "Attempt to stop the target in order to detach timed out. "
3238 "State = %s",
3240 }
3241 }
3242 }
3243 return error;
3244}
3245
3246Status Process::Detach(bool keep_stopped) {
3247 EventSP exit_event_sp;
3248 Status error;
3249 m_destroy_in_process = true;
3250
3251 error = WillDetach();
3252
3253 if (error.Success()) {
3254 if (DetachRequiresHalt()) {
3255 error = StopForDestroyOrDetach(exit_event_sp);
3256 if (!error.Success()) {
3257 m_destroy_in_process = false;
3258 return error;
3259 } else if (exit_event_sp) {
3260 // We shouldn't need to do anything else here. There's no process left
3261 // to detach from...
3263 m_destroy_in_process = false;
3264 return error;
3265 }
3266 }
3267
3270
3271 error = DoDetach(keep_stopped);
3272 if (error.Success()) {
3273 DidDetach();
3275 } else {
3276 return error;
3277 }
3278 }
3279 m_destroy_in_process = false;
3280
3281 // If we exited when we were waiting for a process to stop, then forward the
3282 // event here so we don't lose the event
3283 if (exit_event_sp) {
3284 // Directly broadcast our exited event because we shut down our private
3285 // state thread above
3286 BroadcastEvent(exit_event_sp);
3287 }
3288
3289 // If we have been interrupted (to kill us) in the middle of running, we may
3290 // not end up propagating the last events through the event system, in which
3291 // case we might strand the write lock. Unlock it here so when we do to tear
3292 // down the process we don't get an error destroying the lock.
3293
3295 return error;
3296}
3297
3298Status Process::Destroy(bool force_kill) {
3299 // If we've already called Process::Finalize then there's nothing useful to
3300 // be done here. Finalize has actually called Destroy already.
3301 if (m_finalizing)
3302 return {};
3303 return DestroyImpl(force_kill);
3304}
3305
3307 // Tell ourselves we are in the process of destroying the process, so that we
3308 // don't do any unnecessary work that might hinder the destruction. Remember
3309 // to set this back to false when we are done. That way if the attempt
3310 // failed and the process stays around for some reason it won't be in a
3311 // confused state.
3312
3313 if (force_kill)
3314 m_should_detach = false;
3315
3316 if (GetShouldDetach()) {
3317 // FIXME: This will have to be a process setting:
3318 bool keep_stopped = false;
3319 Detach(keep_stopped);
3320 }
3321
3322 m_destroy_in_process = true;
3323
3325 if (error.Success()) {
3326 EventSP exit_event_sp;
3327 if (DestroyRequiresHalt()) {
3328 error = StopForDestroyOrDetach(exit_event_sp);
3329 }
3330
3332 // Ditch all thread plans, and remove all our breakpoints: in case we
3333 // have to restart the target to kill it, we don't want it hitting a
3334 // breakpoint... Only do this if we've stopped, however, since if we
3335 // didn't manage to halt it above, then we're not going to have much luck
3336 // doing this now.
3339 }
3340
3341 error = DoDestroy();
3342 if (error.Success()) {
3343 DidDestroy();
3345 }
3348 m_stdin_forward = false;
3349
3350 {
3351 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
3353 m_process_input_reader->SetIsDone(true);
3354 m_process_input_reader->Cancel();
3355 m_process_input_reader.reset();
3356 }
3357 }
3358
3359 // If we exited when we were waiting for a process to stop, then forward
3360 // the event here so we don't lose the event
3361 if (exit_event_sp) {
3362 // Directly broadcast our exited event because we shut down our private
3363 // state thread above
3364 BroadcastEvent(exit_event_sp);
3365 }
3366
3367 // If we have been interrupted (to kill us) in the middle of running, we
3368 // may not end up propagating the last events through the event system, in
3369 // which case we might strand the write lock. Unlock it here so when we do
3370 // to tear down the process we don't get an error destroying the lock.
3372 }
3373
3374 m_destroy_in_process = false;
3375
3376 return error;
3377}
3378
3381 if (error.Success()) {
3382 error = DoSignal(signal);
3383 if (error.Success())
3384 DidSignal();
3385 }
3386 return error;
3387}
3388
3390 assert(signals_sp && "null signals_sp");
3391 m_unix_signals_sp = std::move(signals_sp);
3392}
3393
3395 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3396 return m_unix_signals_sp;
3397}
3398
3401}
3402
3405}
3406
3408 const StateType state =
3410 bool return_value = true;
3412
3413 switch (state) {
3414 case eStateDetached:
3415 case eStateExited:
3416 case eStateUnloaded:
3420 m_stdin_forward = false;
3421
3422 [[fallthrough]];
3423 case eStateConnected:
3424 case eStateAttaching:
3425 case eStateLaunching:
3426 // These events indicate changes in the state of the debugging session,
3427 // always report them.
3428 return_value = true;
3429 break;
3430 case eStateInvalid:
3431 // We stopped for no apparent reason, don't report it.
3432 return_value = false;
3433 break;
3434 case eStateRunning:
3435 case eStateStepping:
3436 // If we've started the target running, we handle the cases where we are
3437 // already running and where there is a transition from stopped to running
3438 // differently. running -> running: Automatically suppress extra running
3439 // events stopped -> running: Report except when there is one or more no
3440 // votes
3441 // and no yes votes.
3444 return_value = true;
3445 else {
3446 switch (m_last_broadcast_state) {
3447 case eStateRunning:
3448 case eStateStepping:
3449 // We always suppress multiple runnings with no PUBLIC stop in between.
3450 return_value = false;
3451 break;
3452 default:
3453 // TODO: make this work correctly. For now always report
3454 // run if we aren't running so we don't miss any running events. If I
3455 // run the lldb/test/thread/a.out file and break at main.cpp:58, run
3456 // and hit the breakpoints on multiple threads, then somehow during the
3457 // stepping over of all breakpoints no run gets reported.
3458
3459 // This is a transition from stop to run.
3460 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3461 case eVoteYes:
3462 case eVoteNoOpinion:
3463 return_value = true;
3464 break;
3465 case eVoteNo:
3466 return_value = false;
3467 break;
3468 }
3469 break;
3470 }
3471 }
3472 break;
3473 case eStateStopped:
3474 case eStateCrashed:
3475 case eStateSuspended:
3476 // We've stopped. First see if we're going to restart the target. If we
3477 // are going to stop, then we always broadcast the event. If we aren't
3478 // going to stop, let the thread plans decide if we're going to report this
3479 // event. If no thread has an opinion, we don't report it.
3480
3484 LLDB_LOGF(log,
3485 "Process::ShouldBroadcastEvent (%p) stopped due to an "
3486 "interrupt, state: %s",
3487 static_cast<void *>(event_ptr), StateAsCString(state));
3488 // Even though we know we are going to stop, we should let the threads
3489 // have a look at the stop, so they can properly set their state.
3490 m_thread_list.ShouldStop(event_ptr);
3491 return_value = true;
3492 } else {
3493 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3494 bool should_resume = false;
3495
3496 // It makes no sense to ask "ShouldStop" if we've already been
3497 // restarted... Asking the thread list is also not likely to go well,
3498 // since we are running again. So in that case just report the event.
3499
3500 if (!was_restarted)
3501 should_resume = !m_thread_list.ShouldStop(event_ptr);
3502
3503 if (was_restarted || should_resume || m_resume_requested) {
3504 Vote report_stop_vote = m_thread_list.ShouldReportStop(event_ptr);
3505 LLDB_LOGF(log,
3506 "Process::ShouldBroadcastEvent: should_resume: %i state: "
3507 "%s was_restarted: %i report_stop_vote: %d.",
3508 should_resume, StateAsCString(state), was_restarted,
3509 report_stop_vote);
3510
3511 switch (report_stop_vote) {
3512 case eVoteYes:
3513 return_value = true;
3514 break;
3515 case eVoteNoOpinion:
3516 case eVoteNo:
3517 return_value = false;
3518 break;
3519 }
3520
3521 if (!was_restarted) {
3522 LLDB_LOGF(log,
3523 "Process::ShouldBroadcastEvent (%p) Restarting process "
3524 "from state: %s",
3525 static_cast<void *>(event_ptr), StateAsCString(state));
3527 PrivateResume();
3528 }
3529 } else {
3530 return_value = true;
3532 }
3533 }
3534 break;
3535 }
3536
3537 // Forcing the next event delivery is a one shot deal. So reset it here.
3539
3540 // We do some coalescing of events (for instance two consecutive running
3541 // events get coalesced.) But we only coalesce against events we actually
3542 // broadcast. So we use m_last_broadcast_state to track that. NB - you
3543 // can't use "m_public_state.GetValue()" for that purpose, as was originally
3544 // done, because the PublicState reflects the last event pulled off the
3545 // queue, and there may be several events stacked up on the queue unserviced.
3546 // So the PublicState may not reflect the last broadcasted event yet.
3547 // m_last_broadcast_state gets updated here.
3548
3549 if (return_value)
3550 m_last_broadcast_state = state;
3551
3552 LLDB_LOGF(log,
3553 "Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3554 "broadcast state: %s - %s",
3555 static_cast<void *>(event_ptr), StateAsCString(state),
3557 return_value ? "YES" : "NO");
3558 return return_value;
3559}
3560
3561bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3562 Log *log = GetLog(LLDBLog::Events);
3563
3564 bool already_running = PrivateStateThreadIsValid();
3565 LLDB_LOGF(log, "Process::%s()%s ", __FUNCTION__,
3566 already_running ? " already running"
3567 : " starting private state thread");
3568
3569 if (!is_secondary_thread && already_running)
3570 return true;
3571
3572 // Create a thread that watches our internal state and controls which events
3573 // make it to clients (into the DCProcess event queue).
3574 char thread_name[1024];
3575 uint32_t max_len = llvm::get_max_thread_name_length();
3576 if (max_len > 0 && max_len <= 30) {
3577 // On platforms with abbreviated thread name lengths, choose thread names
3578 // that fit within the limit.
3579 if (already_running)
3580 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3581 else
3582 snprintf(thread_name, sizeof(thread_name), "intern-state");
3583 } else {
3584 if (already_running)
3585 snprintf(thread_name, sizeof(thread_name),
3586 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3587 GetID());
3588 else
3589 snprintf(thread_name, sizeof(thread_name),
3590 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3591 }
3592
3593 llvm::Expected<HostThread> private_state_thread =
3595 thread_name,
3596 [this, is_secondary_thread] {
3597 return RunPrivateStateThread(is_secondary_thread);
3598 },
3599 8 * 1024 * 1024);
3600 if (!private_state_thread) {
3601 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), private_state_thread.takeError(),
3602 "failed to launch host thread: {0}");
3603 return false;
3604 }
3605
3606 assert(private_state_thread->IsJoinable());
3607 m_private_state_thread = *private_state_thread;
3609 return true;
3610}
3611
3614}
3615
3618}
3619
3623 else {
3624 Log *log = GetLog(LLDBLog::Process);
3625 LLDB_LOGF(
3626 log,
3627 "Went to stop the private state thread, but it was already invalid.");
3628 }
3629}
3630
3632 Log *log = GetLog(LLDBLog::Process);
3633
3634 assert(signal == eBroadcastInternalStateControlStop ||
3637
3638 LLDB_LOGF(log, "Process::%s (signal = %d)", __FUNCTION__, signal);
3639
3640 // Signal the private state thread
3642 // Broadcast the event.
3643 // It is important to do this outside of the if below, because it's
3644 // possible that the thread state is invalid but that the thread is waiting
3645 // on a control event instead of simply being on its way out (this should
3646 // not happen, but it apparently can).
3647 LLDB_LOGF(log, "Sending control event of type: %d.", signal);
3648 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3650 event_receipt_sp);
3651
3652 // Wait for the event receipt or for the private state thread to exit
3653 bool receipt_received = false;
3655 while (!receipt_received) {
3656 // Check for a receipt for n seconds and then check if the private
3657 // state thread is still around.
3658 receipt_received =
3659 event_receipt_sp->WaitForEventReceived(GetUtilityExpressionTimeout());
3660 if (!receipt_received) {
3661 // Check if the private state thread is still around. If it isn't
3662 // then we are done waiting
3664 break; // Private state thread exited or is exiting, we are done
3665 }
3666 }
3667 }
3668
3669 if (signal == eBroadcastInternalStateControlStop) {
3670 thread_result_t result = {};
3673 }
3674 } else {
3675 LLDB_LOGF(
3676 log,
3677 "Private state thread already dead, no need to signal it to stop.");
3678 }
3679}
3680
3684 nullptr);
3685 else
3687}
3688
3690 Log *log = GetLog(LLDBLog::Process);
3691 m_resume_requested = false;
3692
3693 const StateType new_state =
3695
3696 // First check to see if anybody wants a shot at this event:
3699 m_next_event_action_up->PerformAction(event_sp);
3700 LLDB_LOGF(log, "Ran next event action, result was %d.", action_result);
3701
3702 switch (action_result) {
3704 SetNextEventAction(nullptr);
3705 break;
3706
3708 break;
3709
3711 // Handle Exiting Here. If we already got an exited event, we should
3712 // just propagate it. Otherwise, swallow this event, and set our state
3713 // to exit so the next event will kill us.
3714 if (new_state != eStateExited) {
3715 // FIXME: should cons up an exited event, and discard this one.
3716 SetExitStatus(0, m_next_event_action_up->GetExitString());
3717 SetNextEventAction(nullptr);
3718 return;
3719 }
3720 SetNextEventAction(nullptr);
3721 break;
3722 }
3723 }
3724
3725 // See if we should broadcast this state to external clients?
3726 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3727
3728 if (should_broadcast) {
3729 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3730 if (log) {
3731 LLDB_LOGF(log,
3732 "Process::%s (pid = %" PRIu64
3733 ") broadcasting new state %s (old state %s) to %s",
3734 __FUNCTION__, GetID(), StateAsCString(new_state),
3736 is_hijacked ? "hijacked" : "public");
3737 }
3739 if (StateIsRunningState(new_state)) {
3740 // Only push the input handler if we aren't fowarding events, as this
3741 // means the curses GUI is in use... Or don't push it if we are launching
3742 // since it will come up stopped.
3743 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3744 new_state != eStateLaunching && new_state != eStateAttaching) {
3748 LLDB_LOGF(log, "Process::%s updated m_iohandler_sync to %d",
3749 __FUNCTION__, m_iohandler_sync.GetValue());
3750 }
3751 } else if (StateIsStoppedState(new_state, false)) {
3753 // If the lldb_private::Debugger is handling the events, we don't want
3754 // to pop the process IOHandler here, we want to do it when we receive
3755 // the stopped event so we can carefully control when the process
3756 // IOHandler is popped because when we stop we want to display some
3757 // text stating how and why we stopped, then maybe some
3758 // process/thread/frame info, and then we want the "(lldb) " prompt to
3759 // show up. If we pop the process IOHandler here, then we will cause
3760 // the command interpreter to become the top IOHandler after the
3761 // process pops off and it will update its prompt right away... See the
3762 // Debugger.cpp file where it calls the function as
3763 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3764 // Otherwise we end up getting overlapping "(lldb) " prompts and
3765 // garbled output.
3766 //
3767 // If we aren't handling the events in the debugger (which is indicated
3768 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
3769 // we are hijacked, then we always pop the process IO handler manually.
3770 // Hijacking happens when the internal process state thread is running
3771 // thread plans, or when commands want to run in synchronous mode and
3772 // they call "process->WaitForProcessToStop()". An example of something
3773 // that will hijack the events is a simple expression:
3774 //
3775 // (lldb) expr (int)puts("hello")
3776 //
3777 // This will cause the internal process state thread to resume and halt
3778 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3779 // events) and we do need the IO handler to be pushed and popped
3780 // correctly.
3781
3782 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3784 }
3785 }
3786
3787 BroadcastEvent(event_sp);
3788 } else {
3789 if (log) {
3790 LLDB_LOGF(
3791 log,
3792 "Process::%s (pid = %" PRIu64
3793 ") suppressing state %s (old state %s): should_broadcast == false",
3794 __FUNCTION__, GetID(), StateAsCString(new_state),
3796 }
3797 }
3798}
3799
3801 EventSP event_sp;
3803 if (error.Fail())
3804 return error;
3805
3806 // Ask the process subclass to actually halt our process
3807 bool caused_stop;
3808 error = DoHalt(caused_stop);
3809
3810 DidHalt();
3811 return error;
3812}
3813
3815 bool control_only = true;
3816
3817 Log *log = GetLog(LLDBLog::Process);
3818 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3819 __FUNCTION__, static_cast<void *>(this), GetID());
3820
3821 bool exit_now = false;
3822 bool interrupt_requested = false;
3823 while (!exit_now) {
3824 EventSP event_sp;
3825 GetEventsPrivate(event_sp, std::nullopt, control_only);
3826 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
3827 LLDB_LOGF(log,
3828 "Process::%s (arg = %p, pid = %" PRIu64
3829 ") got a control event: %d",
3830 __FUNCTION__, static_cast<void *>(this), GetID(),
3831 event_sp->GetType());
3832
3833 switch (event_sp->GetType()) {
3835 exit_now = true;
3836 break; // doing any internal state management below
3837
3839 control_only = true;
3840 break;
3841
3843 control_only = false;
3844 break;
3845 }
3846
3847 continue;
3848 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
3850 LLDB_LOGF(log,
3851 "Process::%s (arg = %p, pid = %" PRIu64
3852 ") woke up with an interrupt while attaching - "
3853 "forwarding interrupt.",
3854 __FUNCTION__, static_cast<void *>(this), GetID());
3855 // The server may be spinning waiting for a process to appear, in which
3856 // case we should tell it to stop doing that. Normally, we don't NEED
3857 // to do that because we will next close the communication to the stub
3858 // and that will get it to shut down. But there are remote debugging
3859 // cases where relying on that side-effect causes the shutdown to be
3860 // flakey, so we should send a positive signal to interrupt the wait.
3864 LLDB_LOGF(log,
3865 "Process::%s (arg = %p, pid = %" PRIu64
3866 ") woke up with an interrupt - Halting.",
3867 __FUNCTION__, static_cast<void *>(this), GetID());
3869 if (error.Fail() && log)
3870 LLDB_LOGF(log,
3871 "Process::%s (arg = %p, pid = %" PRIu64
3872 ") failed to halt the process: %s",
3873 __FUNCTION__, static_cast<void *>(this), GetID(),
3874 error.AsCString());
3875 // Halt should generate a stopped event. Make a note of the fact that
3876 // we were doing the interrupt, so we can set the interrupted flag
3877 // after we receive the event. We deliberately set this to true even if
3878 // HaltPrivate failed, so that we can interrupt on the next natural
3879 // stop.
3880 interrupt_requested = true;
3881 } else {
3882 // This can happen when someone (e.g. Process::Halt) sees that we are
3883 // running and sends an interrupt request, but the process actually
3884 // stops before we receive it. In that case, we can just ignore the
3885 // request. We use m_last_broadcast_state, because the Stopped event
3886 // may not have been popped of the event queue yet, which is when the
3887 // public state gets updated.
3888 LLDB_LOGF(log,
3889 "Process::%s ignoring interrupt as we have already stopped.",
3890 __FUNCTION__);
3891 }
3892 continue;
3893 }
3894
3895 const StateType internal_state =
3897
3898 if (internal_state != eStateInvalid) {
3900 StateIsStoppedState(internal_state, true)) {
3903 }
3904
3905 if (interrupt_requested) {
3906 if (StateIsStoppedState(internal_state, true)) {
3907 // We requested the interrupt, so mark this as such in the stop event
3908 // so clients can tell an interrupted process from a natural stop
3909 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
3910 interrupt_requested = false;
3911 } else if (log) {
3912 LLDB_LOGF(log,
3913 "Process::%s interrupt_requested, but a non-stopped "
3914 "state '%s' received.",
3915 __FUNCTION__, StateAsCString(internal_state));
3916 }
3917 }
3918
3919 HandlePrivateEvent(event_sp);
3920 }
3921
3922 if (internal_state == eStateInvalid || internal_state == eStateExited ||
3923 internal_state == eStateDetached) {
3924 LLDB_LOGF(log,
3925 "Process::%s (arg = %p, pid = %" PRIu64
3926 ") about to exit with internal state %s...",
3927 __FUNCTION__, static_cast<void *>(this), GetID(),
3928 StateAsCString(internal_state));
3929
3930 break;
3931 }
3932 }
3933
3934 // Verify log is still enabled before attempting to write to it...
3935 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
3936 __FUNCTION__, static_cast<void *>(this), GetID());
3937
3938 // If we are a secondary thread, then the primary thread we are working for
3939 // will have already acquired the public_run_lock, and isn't done with what
3940 // it was doing yet, so don't try to change it on the way out.
3941 if (!is_secondary_thread)
3943 return {};
3944}
3945
3946// Process Event Data
3947
3949
3951 StateType state)
3952 : EventData(), m_process_wp(), m_state(state) {
3953 if (process_sp)
3954 m_process_wp = process_sp;
3955}
3956
3958
3960 return "Process::ProcessEventData";
3961}
3962
3965}
3966
3968 bool &found_valid_stopinfo) {
3969 found_valid_stopinfo = false;
3970
3971 ProcessSP process_sp(m_process_wp.lock());
3972 if (!process_sp)
3973 return false;
3974
3975 ThreadList &curr_thread_list = process_sp->GetThreadList();
3976 uint32_t num_threads = curr_thread_list.GetSize();
3977 uint32_t idx;
3978
3979 // The actions might change one of the thread's stop_info's opinions about
3980 // whether we should stop the process, so we need to query that as we go.
3981
3982 // One other complication here, is that we try to catch any case where the
3983 // target has run (except for expressions) and immediately exit, but if we
3984 // get that wrong (which is possible) then the thread list might have
3985 // changed, and that would cause our iteration here to crash. We could
3986 // make a copy of the thread list, but we'd really like to also know if it
3987 // has changed at all, so we make up a vector of the thread ID's and check
3988 // what we get back against this list & bag out if anything differs.
3989 ThreadList not_suspended_thread_list(process_sp.get());
3990 std::vector<uint32_t> thread_index_array(num_threads);
3991 uint32_t not_suspended_idx = 0;
3992 for (idx = 0; idx < num_threads; ++idx) {
3993 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3994
3995 /*
3996 Filter out all suspended threads, they could not be the reason
3997 of stop and no need to perform any actions on them.
3998 */
3999 if (thread_sp->GetResumeState() != eStateSuspended) {
4000 not_suspended_thread_list.AddThread(thread_sp);
4001 thread_index_array[not_suspended_idx] = thread_sp->GetIndexID();
4002 not_suspended_idx++;
4003 }
4004 }
4005
4006 // Use this to track whether we should continue from here. We will only
4007 // continue the target running if no thread says we should stop. Of course
4008 // if some thread's PerformAction actually sets the target running, then it
4009 // doesn't matter what the other threads say...
4010
4011 bool still_should_stop = false;
4012
4013 // Sometimes - for instance if we have a bug in the stub we are talking to,
4014 // we stop but no thread has a valid stop reason. In that case we should
4015 // just stop, because we have no way of telling what the right thing to do
4016 // is, and it's better to let the user decide than continue behind their
4017 // backs.
4018
4019 for (idx = 0; idx < not_suspended_thread_list.GetSize(); ++idx) {
4020 curr_thread_list = process_sp->GetThreadList();
4021 if (curr_thread_list.GetSize() != num_threads) {
4023 LLDB_LOGF(
4024 log,
4025 "Number of threads changed from %u to %u while processing event.",
4026 num_threads, curr_thread_list.GetSize());
4027 break;
4028 }
4029
4030 lldb::ThreadSP thread_sp = not_suspended_thread_list.GetThreadAtIndex(idx);
4031
4032 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4034 LLDB_LOGF(log,
4035 "The thread at position %u changed from %u to %u while "
4036 "processing event.",
4037 idx, thread_index_array[idx], thread_sp->GetIndexID());
4038 break;
4039 }
4040
4041 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4042 if (stop_info_sp && stop_info_sp->IsValid()) {
4043 found_valid_stopinfo = true;
4044 bool this_thread_wants_to_stop;
4045 if (stop_info_sp->GetOverrideShouldStop()) {
4046 this_thread_wants_to_stop =
4047 stop_info_sp->GetOverriddenShouldStopValue();
4048 } else {
4049 stop_info_sp->PerformAction(event_ptr);
4050 // The stop action might restart the target. If it does, then we
4051 // want to mark that in the event so that whoever is receiving it
4052 // will know to wait for the running event and reflect that state
4053 // appropriately. We also need to stop processing actions, since they
4054 // aren't expecting the target to be running.
4055
4056 // FIXME: we might have run.
4057 if (stop_info_sp->HasTargetRunSinceMe()) {
4058 SetRestarted(true);
4059 break;
4060 }
4061
4062 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
4063 }
4064
4065 if (!still_should_stop)
4066 still_should_stop = this_thread_wants_to_stop;
4067 }
4068 }
4069
4070 return still_should_stop;
4071}
4072
4074 ProcessSP process_sp(m_process_wp.lock());
4075
4076 if (!process_sp)
4077 return;
4078
4079 // This function gets called twice for each event, once when the event gets
4080 // pulled off of the private process event queue, and then any number of
4081 // times, first when it gets pulled off of the public event queue, then other
4082 // times when we're pretending that this is where we stopped at the end of
4083 // expression evaluation. m_update_state is used to distinguish these three
4084 // cases; it is 0 when we're just pulling it off for private handling, and >
4085 // 1 for expression evaluation, and we don't want to do the breakpoint
4086 // command handling then.
4087 if (m_update_state != 1)
4088 return;
4089
4090 process_sp->SetPublicState(
4092
4093 if (m_state == eStateStopped && !m_restarted) {
4094 // Let process subclasses know we are about to do a public stop and do
4095 // anything they might need to in order to speed up register and memory
4096 // accesses.
4097 process_sp->WillPublicStop();
4098 }
4099
4100 // If this is a halt event, even if the halt stopped with some reason other
4101 // than a plain interrupt (e.g. we had already stopped for a breakpoint when
4102 // the halt request came through) don't do the StopInfo actions, as they may
4103 // end up restarting the process.
4104 if (m_interrupted)
4105 return;
4106
4107 // If we're not stopped or have restarted, then skip the StopInfo actions:
4108 if (m_state != eStateStopped || m_restarted) {
4109 return;
4110 }
4111
4112 bool does_anybody_have_an_opinion = false;
4113 bool still_should_stop = ShouldStop(event_ptr, does_anybody_have_an_opinion);
4114
4115 if (GetRestarted()) {
4116 return;
4117 }
4118
4119 if (!still_should_stop && does_anybody_have_an_opinion) {
4120 // We've been asked to continue, so do that here.
4121 SetRestarted(true);
4122 // Use the private resume method here, since we aren't changing the run
4123 // lock state.
4124 process_sp->PrivateResume();
4125 } else {
4126 bool hijacked = process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) &&
4127 !process_sp->StateChangedIsHijackedForSynchronousResume();
4128
4129 if (!hijacked) {
4130 // If we didn't restart, run the Stop Hooks here.
4131 // Don't do that if state changed events aren't hooked up to the
4132 // public (or SyncResume) broadcasters. StopHooks are just for
4133 // real public stops. They might also restart the target,
4134 // so watch for that.
4135 if (process_sp->GetTarget().RunStopHooks())
4136 SetRestarted(true);
4137 }
4138 }
4139}
4140
4142 ProcessSP process_sp(m_process_wp.lock());
4143
4144 if (process_sp)
4145 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4146 static_cast<void *>(process_sp.get()), process_sp->GetID());
4147 else
4148 s->PutCString(" process = NULL, ");
4149
4150 s->Printf("state = %s", StateAsCString(GetState()));
4151}
4152
4155 if (event_ptr) {
4156 const EventData *event_data = event_ptr->GetData();
4157 if (event_data &&
4159 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4160 }
4161 return nullptr;
4162}
4163
4166 ProcessSP process_sp;
4167 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4168 if (data)
4169 process_sp = data->GetProcessSP();
4170 return process_sp;
4171}
4172
4174 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4175 if (data == nullptr)
4176 return eStateInvalid;
4177 else
4178 return data->GetState();
4179}
4180
4182 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4183 if (data == nullptr)
4184 return false;
4185 else
4186 return data->GetRestarted();
4187}
4188
4190 bool new_value) {
4191 ProcessEventData *data =
4192 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4193 if (data != nullptr)
4194 data->SetRestarted(new_value);
4195}
4196
4197size_t
4199 ProcessEventData *data =
4200 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4201 if (data != nullptr)
4202 return data->GetNumRestartedReasons();
4203 else
4204 return 0;
4205}
4206
4207const char *
4209 size_t idx) {
4210 ProcessEventData *data =
4211 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4212 if (data != nullptr)
4213 return data->GetRestartedReasonAtIndex(idx);
4214 else
4215 return nullptr;
4216}
4217
4219 const char *reason) {
4220 ProcessEventData *data =
4221 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4222 if (data != nullptr)
4223 data->AddRestartedReason(reason);
4224}
4225
4227 const Event *event_ptr) {
4228 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4229 if (data == nullptr)
4230 return false;
4231 else
4232 return data->GetInterrupted();
4233}
4234
4236 bool new_value) {
4237 ProcessEventData *data =
4238 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4239 if (data != nullptr)
4240 data->SetInterrupted(new_value);
4241}
4242
4244 ProcessEventData *data =
4245 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4246 if (data) {
4248 return true;
4249 }
4250 return false;
4251}
4252
4254
4256 exe_ctx.SetTargetPtr(&GetTarget());
4257 exe_ctx.SetProcessPtr(this);
4258 exe_ctx.SetThreadPtr(nullptr);
4259 exe_ctx.SetFramePtr(nullptr);
4260}
4261
4262// uint32_t
4263// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4264// std::vector<lldb::pid_t> &pids)
4265//{
4266// return 0;
4267//}
4268//
4269// ArchSpec
4270// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4271//{
4272// return Host::GetArchSpecForExistingProcess (pid);
4273//}
4274//
4275// ArchSpec
4276// Process::GetArchSpecForExistingProcess (const char *process_name)
4277//{
4278// return Host::GetArchSpecForExistingProcess (process_name);
4279//}
4280
4282 auto event_data_sp =
4283 std::make_shared<ProcessEventData>(shared_from_this(), GetState());
4284 return std::make_shared<Event>(event_type, event_data_sp);
4285}
4286
4287void Process::AppendSTDOUT(const char *s, size_t len) {
4288 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4289 m_stdout_data.append(s, len);
4291 BroadcastEventIfUnique(event_sp);
4292}
4293
4294void Process::AppendSTDERR(const char *s, size_t len) {
4295 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4296 m_stderr_data.append(s, len);
4298 BroadcastEventIfUnique(event_sp);
4299}
4300
4301void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4302 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4303 m_profile_data.push_back(one_profile_data);
4305 BroadcastEventIfUnique(event_sp);
4306}
4307
4309 const StructuredDataPluginSP &plugin_sp) {
4310 auto data_sp = std::make_shared<EventDataStructuredData>(
4311 shared_from_this(), object_sp, plugin_sp);
4313}
4314
4316Process::GetStructuredDataPlugin(llvm::StringRef type_name) const {
4317 auto find_it = m_structured_data_plugin_map.find(type_name);
4318 if (find_it != m_structured_data_plugin_map.end())
4319 return find_it->second;
4320 else
4321 return StructuredDataPluginSP();
4322}
4323
4324size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
4325 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4326 if (m_profile_data.empty())
4327 return 0;
4328
4329 std::string &one_profile_data = m_profile_data.front();
4330 size_t bytes_available = one_profile_data.size();
4331 if (bytes_available > 0) {
4332 Log *log = GetLog(LLDBLog::Process);
4333 LLDB_LOGF(log, "Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4334 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4335 if (bytes_available > buf_size) {
4336 memcpy(buf, one_profile_data.c_str(), buf_size);
4337 one_profile_data.erase(0, buf_size);
4338 bytes_available = buf_size;
4339 } else {
4340 memcpy(buf, one_profile_data.c_str(), bytes_available);
4341 m_profile_data.erase(m_profile_data.begin());
4342 }
4343 }
4344 return bytes_available;
4345}
4346
4347// Process STDIO
4348
4349size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
4350 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4351 size_t bytes_available = m_stdout_data.size();
4352 if (bytes_available > 0) {
4353 Log *log = GetLog(LLDBLog::Process);
4354 LLDB_LOGF(log, "Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4355 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4356 if (bytes_available > buf_size) {
4357 memcpy(buf, m_stdout_data.c_str(), buf_size);
4358 m_stdout_data.erase(0, buf_size);
4359 bytes_available = buf_size;
4360 } else {
4361 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4362 m_stdout_data.clear();
4363 }
4364 }
4365 return bytes_available;
4366}
4367
4368size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
4369 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4370 size_t bytes_available = m_stderr_data.size();
4371 if (bytes_available > 0) {
4372 Log *log = GetLog(LLDBLog::Process);
4373 LLDB_LOGF(log, "Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4374 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4375 if (bytes_available > buf_size) {
4376 memcpy(buf, m_stderr_data.c_str(), buf_size);
4377 m_stderr_data.erase(0, buf_size);
4378 bytes_available = buf_size;
4379 } else {
4380 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4381 m_stderr_data.clear();
4382 }
4383 }
4384 return bytes_available;
4385}
4386
4387void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4388 size_t src_len) {
4389 Process *process = (Process *)baton;
4390 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
4391}
4392
4394public:
4395 IOHandlerProcessSTDIO(Process *process, int write_fd)
4396 : IOHandler(process->GetTarget().GetDebugger(),
4397 IOHandler::Type::ProcessIO),
4398 m_process(process),
4399 m_read_file(GetInputFD(), File::eOpenOptionReadOnly, false),
4400 m_write_file(write_fd, File::eOpenOptionWriteOnly, false) {
4401 m_pipe.CreateNew(false);
4402 }
4403
4404 ~IOHandlerProcessSTDIO() override = default;
4405
4406 void SetIsRunning(bool running) {
4407 std::lock_guard<std::mutex> guard(m_mutex);
4408 SetIsDone(!running);
4409 m_is_running = running;
4410 }
4411
4412 // Each IOHandler gets to run until it is done. It should read data from the
4413 // "in" and place output into "out" and "err and return when done.
4414 void Run() override {
4415 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4416 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4417 SetIsDone(true);
4418 return;
4419 }
4420
4421 SetIsDone(false);
4422 const int read_fd = m_read_file.GetDescriptor();
4423 Terminal terminal(read_fd);
4424 TerminalState terminal_state(terminal, false);
4425 // FIXME: error handling?
4426 llvm::consumeError(terminal.SetCanonical(false));
4427 llvm::consumeError(terminal.SetEcho(false));
4428// FD_ZERO, FD_SET are not supported on windows
4429#ifndef _WIN32
4430 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4431 SetIsRunning(true);
4432 while (true) {
4433 {
4434 std::lock_guard<std::mutex> guard(m_mutex);
4435 if (GetIsDone())
4436 break;
4437 }
4438
4439 SelectHelper select_helper;
4440 select_helper.FDSetRead(read_fd);
4441 select_helper.FDSetRead(pipe_read_fd);
4442 Status error = select_helper.Select();
4443
4444 if (error.Fail())
4445 break;
4446
4447 char ch = 0;
4448 size_t n;
4449 if (select_helper.FDIsSetRead(read_fd)) {
4450 n = 1;
4451 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4452 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4453 break;
4454 } else
4455 break;
4456 }
4457
4458 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4459 size_t bytes_read;
4460 // Consume the interrupt byte
4461 Status error = m_pipe.Read(&ch, 1, bytes_read);
4462 if (error.Success()) {
4463 if (ch == 'q')
4464 break;
4465 if (ch == 'i')
4466 if (StateIsRunningState(m_process->GetState()))
4467 m_process->SendAsyncInterrupt();
4468 }
4469 }
4470 }
4471 SetIsRunning(false);
4472#endif
4473 }
4474
4475 void Cancel() override {
4476 std::lock_guard<std::mutex> guard(m_mutex);
4477 SetIsDone(true);
4478 // Only write to our pipe to cancel if we are in
4479 // IOHandlerProcessSTDIO::Run(). We can end up with a python command that
4480 // is being run from the command interpreter:
4481 //
4482 // (lldb) step_process_thousands_of_times
4483 //
4484 // In this case the command interpreter will be in the middle of handling
4485 // the command and if the process pushes and pops the IOHandler thousands
4486 // of times, we can end up writing to m_pipe without ever consuming the
4487 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4488 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4489 if (m_is_running) {
4490 char ch = 'q'; // Send 'q' for quit
4491 size_t bytes_written = 0;
4492 m_pipe.Write(&ch, 1, bytes_written);
4493 }
4494 }
4495
4496 bool Interrupt() override {
4497 // Do only things that are safe to do in an interrupt context (like in a
4498 // SIGINT handler), like write 1 byte to a file descriptor. This will
4499 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4500 // that was written to the pipe and then call
4501 // m_process->SendAsyncInterrupt() from a much safer location in code.
4502 if (m_active) {
4503 char ch = 'i'; // Send 'i' for interrupt
4504 size_t bytes_written = 0;
4505 Status result = m_pipe.Write(&ch, 1, bytes_written);
4506 return result.Success();
4507 } else {
4508 // This IOHandler might be pushed on the stack, but not being run
4509 // currently so do the right thing if we aren't actively watching for
4510 // STDIN by sending the interrupt to the process. Otherwise the write to
4511 // the pipe above would do nothing. This can happen when the command
4512 // interpreter is running and gets a "expression ...". It will be on the
4513 // IOHandler thread and sending the input is complete to the delegate
4514 // which will cause the expression to run, which will push the process IO
4515 // handler, but not run it.
4516
4517 if (StateIsRunningState(m_process->GetState())) {
4518 m_process->SendAsyncInterrupt();
4519 return true;
4520 }
4521 }
4522 return false;
4523 }
4524
4525 void GotEOF() override {}
4526
4527protected:
4529 NativeFile m_read_file; // Read from this file (usually actual STDIN for LLDB
4530 NativeFile m_write_file; // Write to this file (usually the primary pty for
4531 // getting io to debuggee)
4533 std::mutex m_mutex;
4534 bool m_is_running = false;
4535};
4536
4538 // First set up the Read Thread for reading/handling process I/O
4540 std::make_unique<ConnectionFileDescriptor>(fd, true));
4545
4546 // Now read thread is set up, set up input reader.
4547 {
4548 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
4551 std::make_shared<IOHandlerProcessSTDIO>(this, fd);
4552 }
4553 }
4554}
4555
4557 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
4558 IOHandlerSP io_handler_sp(m_process_input_reader);
4559 if (io_handler_sp)
4560 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4561 return false;
4562}
4563
4565 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
4566 IOHandlerSP io_handler_sp(m_process_input_reader);
4567 if (io_handler_sp) {
4568 Log *log = GetLog(LLDBLog::Process);
4569 LLDB_LOGF(log, "Process::%s pushing IO handler", __FUNCTION__);
4570
4571 io_handler_sp->SetIsDone(false);
4572 // If we evaluate an utility function, then we don't cancel the current
4573 // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
4574 // existing IOHandler that potentially provides the user interface (e.g.
4575 // the IOHandler for Editline).
4576 bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();
4577 GetTarget().GetDebugger().RunIOHandlerAsync(io_handler_sp,
4578 cancel_top_handler);
4579 return true;
4580 }
4581 return false;
4582}
4583
4585 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
4586 IOHandlerSP io_handler_sp(m_process_input_reader);
4587 if (io_handler_sp)
4588 return GetTarget().GetDebugger().RemoveIOHandler(io_handler_sp);
4589 return false;
4590}
4591
4592// The process needs to know about installed plug-ins
4594
4596
4597namespace {
4598// RestorePlanState is used to record the "is private", "is controlling" and
4599// "okay
4600// to discard" fields of the plan we are running, and reset it on Clean or on
4601// destruction. It will only reset the state once, so you can call Clean and
4602// then monkey with the state and it won't get reset on you again.
4603
4604class RestorePlanState {
4605public:
4606 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4607 : m_thread_plan_sp(thread_plan_sp) {
4608 if (m_thread_plan_sp) {
4609 m_private = m_thread_plan_sp->GetPrivate();
4610 m_is_controlling = m_thread_plan_sp->IsControllingPlan();
4611 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4612 }
4613 }
4614
4615 ~RestorePlanState() { Clean(); }
4616
4617 void Clean() {
4618 if (!m_already_reset && m_thread_plan_sp) {
4619 m_already_reset = true;
4620 m_thread_plan_sp->SetPrivate(m_private);
4621 m_thread_plan_sp->SetIsControllingPlan(m_is_controlling);
4622 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4623 }
4624 }
4625
4626private:
4627 lldb::ThreadPlanSP m_thread_plan_sp;
4628 bool m_already_reset = false;
4629 bool m_private = false;
4630 bool m_is_controlling = false;
4631 bool m_okay_to_discard = false;
4632};
4633} // anonymous namespace
4634
4635static microseconds
4637 const milliseconds default_one_thread_timeout(250);
4638
4639 // If the overall wait is forever, then we don't need to worry about it.
4640 if (!options.GetTimeout()) {
4641 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4642 : default_one_thread_timeout;
4643 }
4644
4645 // If the one thread timeout is set, use it.
4646 if (options.GetOneThreadTimeout())
4647 return *options.GetOneThreadTimeout();
4648
4649 // Otherwise use half the total timeout, bounded by the
4650 // default_one_thread_timeout.
4651 return std::min<microseconds>(default_one_thread_timeout,
4652 *options.GetTimeout() / 2);
4653}
4654
4657 bool before_first_timeout) {
4658 // If we are going to run all threads the whole time, or if we are only going
4659 // to run one thread, we can just return the overall timeout.
4660 if (!options.GetStopOthers() || !options.GetTryAllThreads())
4661 return options.GetTimeout();
4662
4663 if (before_first_timeout)
4664 return GetOneThreadExpressionTimeout(options);
4665
4666 if (!options.GetTimeout())
4667 return std::nullopt;
4668 else
4669 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
4670}
4671
4672static std::optional<ExpressionResults>
4673HandleStoppedEvent(lldb::tid_t thread_id, const ThreadPlanSP &thread_plan_sp,
4674 RestorePlanState &restorer, const EventSP &event_sp,
4675 EventSP &event_to_broadcast_sp,
4676 const EvaluateExpressionOptions &options,
4677 bool handle_interrupts) {
4679
4680 ThreadSP thread_sp = thread_plan_sp->GetTarget()
4681 .GetProcessSP()
4682 ->GetThreadList()
4683 .FindThreadByID(thread_id);
4684 if (!thread_sp) {
4685 LLDB_LOG(log,
4686 "The thread on which we were running the "
4687 "expression: tid = {0}, exited while "
4688 "the expression was running.",
4689 thread_id);
4691 }
4692
4693 ThreadPlanSP plan = thread_sp->GetCompletedPlan();
4694 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
4695 LLDB_LOG(log, "execution completed successfully");
4696
4697 // Restore the plan state so it will get reported as intended when we are
4698 // done.
4699 restorer.Clean();
4700 return eExpressionCompleted;
4701 }
4702
4703 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4704 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
4705 stop_info_sp->ShouldNotify(event_sp.get())) {
4706 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
4707 if (!options.DoesIgnoreBreakpoints()) {
4708 // Restore the plan state and then force Private to false. We are going
4709 // to stop because of this plan so we need it to become a public plan or
4710 // it won't report correctly when we continue to its termination later
4711 // on.
4712 restorer.Clean();
4713 thread_plan_sp->SetPrivate(false);
4714 event_to_broadcast_sp = event_sp;
4715 }
4717 }
4718
4719 if (!handle_interrupts &&
4721 return std::nullopt;
4722
4723 LLDB_LOG(log, "thread plan did not successfully complete");
4724 if (!options.DoesUnwindOnError())
4725 event_to_broadcast_sp = event_sp;
4727}
4728
4731 lldb::ThreadPlanSP &thread_plan_sp,
4732 const EvaluateExpressionOptions &options,
4733 DiagnosticManager &diagnostic_manager) {
4735
4736 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4737
4738 if (!thread_plan_sp) {
4739 diagnostic_manager.PutString(
4741 "RunThreadPlan called with empty thread plan.");
4742 return eExpressionSetupError;
4743 }
4744
4745 if (!thread_plan_sp->ValidatePlan(nullptr)) {
4746 diagnostic_manager.PutString(
4748 "RunThreadPlan called with an invalid thread plan.");
4749 return eExpressionSetupError;
4750 }
4751
4752 if (exe_ctx.GetProcessPtr() != this) {
4753 diagnostic_manager.PutString(eDiagnosticSeverityError,
4754 "RunThreadPlan called on wrong process.");
4755 return eExpressionSetupError;
4756 }
4757
4758 Thread *thread = exe_ctx.GetThreadPtr();
4759 if (thread == nullptr) {
4760 diagnostic_manager.PutString(eDiagnosticSeverityError,
4761 "RunThreadPlan called with invalid thread.");
4762 return eExpressionSetupError;
4763 }
4764
4765 // Record the thread's id so we can tell when a thread we were using
4766 // to run the expression exits during the expression evaluation.
4767 lldb::tid_t expr_thread_id = thread->GetID();
4768
4769 // We need to change some of the thread plan attributes for the thread plan
4770 // runner. This will restore them when we are done:
4771
4772 RestorePlanState thread_plan_restorer(thread_plan_sp);
4773
4774 // We rely on the thread plan we are running returning "PlanCompleted" if
4775 // when it successfully completes. For that to be true the plan can't be
4776 // private - since private plans suppress themselves in the GetCompletedPlan
4777 // call.
4778
4779 thread_plan_sp->SetPrivate(false);
4780
4781 // The plans run with RunThreadPlan also need to be terminal controlling plans
4782 // or when they are done we will end up asking the plan above us whether we
4783 // should stop, which may give the wrong answer.
4784
4785 thread_plan_sp->SetIsControllingPlan(true);
4786 thread_plan_sp->SetOkayToDiscard(false);
4787
4788 // If we are running some utility expression for LLDB, we now have to mark
4789 // this in the ProcesModID of this process. This RAII takes care of marking
4790 // and reverting the mark it once we are done running the expression.
4791 UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);
4792
4794 diagnostic_manager.PutString(
4796 "RunThreadPlan called while the private state was not stopped.");
4797 return eExpressionSetupError;
4798 }
4799
4800 // Save the thread & frame from the exe_ctx for restoration after we run
4801 const uint32_t thread_idx_id = thread->GetIndexID();
4802 StackFrameSP selected_frame_sp =
4804 if (!selected_frame_sp) {
4805 thread->SetSelectedFrame(nullptr);
4806 selected_frame_sp = thread->GetSelectedFrame(DoNoSelectMostRelevantFrame);
4807 if (!selected_frame_sp) {
4808 diagnostic_manager.Printf(
4810 "RunThreadPlan called without a selected frame on thread %d",
4811 thread_idx_id);
4812 return eExpressionSetupError;
4813 }
4814 }
4815
4816 // Make sure the timeout values make sense. The one thread timeout needs to
4817 // be smaller than the overall timeout.
4818 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4819 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
4820 diagnostic_manager.PutString(eDiagnosticSeverityError,
4821 "RunThreadPlan called with one thread "
4822 "timeout greater than total timeout");
4823 return eExpressionSetupError;
4824 }
4825
4826 StackID ctx_frame_id = selected_frame_sp->GetStackID();
4827
4828 // N.B. Running the target may unset the currently selected thread and frame.
4829 // We don't want to do that either, so we should arrange to reset them as
4830 // well.
4831
4832 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
4833
4834 uint32_t selected_tid;
4835 StackID selected_stack_id;
4836 if (selected_thread_sp) {
4837 selected_tid = selected_thread_sp->GetIndexID();
4838 selected_stack_id =
4839 selected_thread_sp->GetSelectedFrame(DoNoSelectMostRelevantFrame)
4840 ->GetStackID();
4841 } else {
4842 selected_tid = LLDB_INVALID_THREAD_ID;
4843 }
4844
4845 HostThread backup_private_state_thread;
4846 lldb::StateType old_state = eStateInvalid;
4847 lldb::ThreadPlanSP stopper_base_plan_sp;
4848
4851 // Yikes, we are running on the private state thread! So we can't wait for
4852 // public events on this thread, since we are the thread that is generating
4853 // public events. The simplest thing to do is to spin up a temporary thread
4854 // to handle private state thread events while we are fielding public
4855 // events here.
4856 LLDB_LOGF(log, "Running thread plan on private state thread, spinning up "
4857 "another state thread to handle the events.");
4858
4859 backup_private_state_thread = m_private_state_thread;
4860
4861 // One other bit of business: we want to run just this thread plan and
4862 // anything it pushes, and then stop, returning control here. But in the
4863 // normal course of things, the plan above us on the stack would be given a
4864 // shot at the stop event before deciding to stop, and we don't want that.
4865 // So we insert a "stopper" base plan on the stack before the plan we want
4866 // to run. Since base plans always stop and return control to the user,
4867 // that will do just what we want.
4868 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4869 thread->QueueThreadPlan(stopper_base_plan_sp, false);
4870 // Have to make sure our public state is stopped, since otherwise the
4871 // reporting logic below doesn't work correctly.
4872 old_state = m_public_state.GetValue();
4874
4875 // Now spin up the private state thread:
4877 }
4878
4879 thread->QueueThreadPlan(
4880 thread_plan_sp, false); // This used to pass "true" does that make sense?
4881
4882 if (options.GetDebug()) {
4883 // In this case, we aren't actually going to run, we just want to stop
4884 // right away. Flush this thread so we will refetch the stacks and show the
4885 // correct backtrace.
4886 // FIXME: To make this prettier we should invent some stop reason for this,
4887 // but that
4888 // is only cosmetic, and this functionality is only of use to lldb
4889 // developers who can live with not pretty...
4890 thread->Flush();
4892 }
4893
4894 ListenerSP listener_sp(
4895 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4896
4897 lldb::EventSP event_to_broadcast_sp;
4898
4899 {
4900 // This process event hijacker Hijacks the Public events and its destructor
4901 // makes sure that the process events get restored on exit to the function.
4902 //
4903 // If the event needs to propagate beyond the hijacker (e.g., the process
4904 // exits during execution), then the event is put into
4905 // event_to_broadcast_sp for rebroadcasting.
4906
4907 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
4908
4909 if (log) {
4910 StreamString s;
4911 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4912 LLDB_LOGF(log,
4913 "Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
4914 " to run thread plan \"%s\".",
4915 thread_idx_id, expr_thread_id, s.GetData());
4916 }
4917
4918 bool got_event;
4919 lldb::EventSP event_sp;
4921
4922 bool before_first_timeout = true; // This is set to false the first time
4923 // that we have to halt the target.
4924 bool do_resume = true;
4925 bool handle_running_event = true;
4926
4927 // This is just for accounting:
4928 uint32_t num_resumes = 0;
4929
4930 // If we are going to run all threads the whole time, or if we are only
4931 // going to run one thread, then we don't need the first timeout. So we
4932 // pretend we are after the first timeout already.
4933 if (!options.GetStopOthers() || !options.GetTryAllThreads())
4934 before_first_timeout = false;
4935
4936 LLDB_LOGF(log, "Stop others: %u, try all: %u, before_first: %u.\n",
4937 options.GetStopOthers(), options.GetTryAllThreads(),
4938 before_first_timeout);
4939
4940 // This isn't going to work if there are unfetched events on the queue. Are
4941 // there cases where we might want to run the remaining events here, and
4942 // then try to call the function? That's probably being too tricky for our
4943 // own good.
4944
4945 Event *other_events = listener_sp->PeekAtNextEvent();
4946 if (other_events != nullptr) {
4947 diagnostic_manager.PutString(
4949 "RunThreadPlan called with pending events on the queue.");
4950 return eExpressionSetupError;
4951 }
4952
4953 // We also need to make sure that the next event is delivered. We might be
4954 // calling a function as part of a thread plan, in which case the last
4955 // delivered event could be the running event, and we don't want event
4956 // coalescing to cause us to lose OUR running event...
4958
4959// This while loop must exit out the bottom, there's cleanup that we need to do
4960// when we are done. So don't call return anywhere within it.
4961
4962#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
4963 // It's pretty much impossible to write test cases for things like: One
4964 // thread timeout expires, I go to halt, but the process already stopped on
4965 // the function call stop breakpoint. Turning on this define will make us
4966 // not fetch the first event till after the halt. So if you run a quick
4967 // function, it will have completed, and the completion event will be
4968 // waiting, when you interrupt for halt. The expression evaluation should
4969 // still succeed.
4970 bool miss_first_event = true;
4971#endif
4972 while (true) {
4973 // We usually want to resume the process if we get to the top of the
4974 // loop. The only exception is if we get two running events with no
4975 // intervening stop, which can happen, we will just wait for then next
4976 // stop event.
4977 LLDB_LOGF(log,
4978 "Top of while loop: do_resume: %i handle_running_event: %i "
4979 "before_first_timeout: %i.",
4980 do_resume, handle_running_event, before_first_timeout);
4981
4982 if (do_resume || handle_running_event) {
4983 // Do the initial resume and wait for the running event before going
4984 // further.
4985
4986 if (do_resume) {
4987 num_resumes++;
4988 Status resume_error = PrivateResume();
4989 if (!resume_error.Success()) {
4990 diagnostic_manager.Printf(
4991