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_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),
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
522 if (m_finalizing.exchange(true))
523 return;
524
525 // Destroy the process. This will call the virtual function DoDestroy under
526 // the hood, giving our derived class a chance to do the ncessary tear down.
527 DestroyImpl(false);
528
529 // Clear our broadcaster before we proceed with destroying
531
532 // Do any cleanup needed prior to being destructed... Subclasses that
533 // override this method should call this superclass method as well.
534
535 // We need to destroy the loader before the derived Process class gets
536 // destroyed since it is very likely that undoing the loader will require
537 // access to the real process.
538 m_dynamic_checkers_up.reset();
539 m_abi_sp.reset();
540 m_os_up.reset();
541 m_system_runtime_up.reset();
542 m_dyld_up.reset();
543 m_jit_loaders_up.reset();
550 std::vector<Notifications> empty_notifications;
551 m_notifications.swap(empty_notifications);
552 m_image_tokens.clear();
554 m_allocated_memory_cache.Clear(/*deallocate_memory=*/true);
555 {
556 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
557 m_language_runtimes.clear();
558 }
561 // Clear the last natural stop ID since it has a strong reference to this
562 // process
564 // We have to be very careful here as the m_private_state_listener might
565 // contain events that have ProcessSP values in them which can keep this
566 // process around forever. These events need to be cleared out.
568 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
570 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
573}
574
576 m_notifications.push_back(callbacks);
577 if (callbacks.initialize != nullptr)
578 callbacks.initialize(callbacks.baton, this);
579}
580
582 std::vector<Notifications>::iterator pos, end = m_notifications.end();
583 for (pos = m_notifications.begin(); pos != end; ++pos) {
584 if (pos->baton == callbacks.baton &&
585 pos->initialize == callbacks.initialize &&
586 pos->process_state_changed == callbacks.process_state_changed) {
587 m_notifications.erase(pos);
588 return true;
589 }
590 }
591 return false;
592}
593
595 std::vector<Notifications>::iterator notification_pos,
596 notification_end = m_notifications.end();
597 for (notification_pos = m_notifications.begin();
598 notification_pos != notification_end; ++notification_pos) {
599 if (notification_pos->process_state_changed)
600 notification_pos->process_state_changed(notification_pos->baton, this,
601 state);
602 }
603}
604
605// FIXME: We need to do some work on events before the general Listener sees
606// them.
607// For instance if we are continuing from a breakpoint, we need to ensure that
608// we do the little "insert real insn, step & stop" trick. But we can't do
609// that when the event is delivered by the broadcaster - since that is done on
610// the thread that is waiting for new events, so if we needed more than one
611// event for our handling, we would stall. So instead we do it when we fetch
612// the event off of the queue.
613//
614
616 StateType state = eStateInvalid;
617
618 if (GetPrimaryListener()->GetEventForBroadcaster(this, event_sp,
619 std::chrono::seconds(0)) &&
620 event_sp)
621 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
622
623 return state;
624}
625
626void Process::SyncIOHandler(uint32_t iohandler_id,
627 const Timeout<std::micro> &timeout) {
628 // don't sync (potentially context switch) in case where there is no process
629 // IO
631 return;
632
633 auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout);
634
636 if (Result) {
637 LLDB_LOG(
638 log,
639 "waited from m_iohandler_sync to change from {0}. New value is {1}.",
640 iohandler_id, *Result);
641 } else {
642 LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.",
643 iohandler_id);
644 }
645}
646
648 const Timeout<std::micro> &timeout, EventSP *event_sp_ptr, bool wait_always,
649 ListenerSP hijack_listener_sp, Stream *stream, bool use_run_lock,
650 SelectMostRelevant select_most_relevant) {
651 // We can't just wait for a "stopped" event, because the stopped event may
652 // have restarted the target. We have to actually check each event, and in
653 // the case of a stopped event check the restarted flag on the event.
654 if (event_sp_ptr)
655 event_sp_ptr->reset();
656 StateType state = GetState();
657 // If we are exited or detached, we won't ever get back to any other valid
658 // state...
659 if (state == eStateDetached || state == eStateExited)
660 return state;
661
663 LLDB_LOG(log, "timeout = {0}", timeout);
664
665 if (!wait_always && StateIsStoppedState(state, true) &&
667 LLDB_LOGF(log,
668 "Process::%s returning without waiting for events; process "
669 "private and public states are already 'stopped'.",
670 __FUNCTION__);
671 // We need to toggle the run lock as this won't get done in
672 // SetPublicState() if the process is hijacked.
673 if (hijack_listener_sp && use_run_lock)
675 return state;
676 }
677
678 while (state != eStateInvalid) {
679 EventSP event_sp;
680 state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
681 if (event_sp_ptr && event_sp)
682 *event_sp_ptr = event_sp;
683
684 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
686 event_sp, stream, select_most_relevant, pop_process_io_handler);
687
688 switch (state) {
689 case eStateCrashed:
690 case eStateDetached:
691 case eStateExited:
692 case eStateUnloaded:
693 // We need to toggle the run lock as this won't get done in
694 // SetPublicState() if the process is hijacked.
695 if (hijack_listener_sp && use_run_lock)
697 return state;
698 case eStateStopped:
700 continue;
701 else {
702 // We need to toggle the run lock as this won't get done in
703 // SetPublicState() if the process is hijacked.
704 if (hijack_listener_sp && use_run_lock)
706 return state;
707 }
708 default:
709 continue;
710 }
711 }
712 return state;
713}
714
716 const EventSP &event_sp, Stream *stream,
717 SelectMostRelevant select_most_relevant,
718 bool &pop_process_io_handler) {
719 const bool handle_pop = pop_process_io_handler;
720
721 pop_process_io_handler = false;
722 ProcessSP process_sp =
724
725 if (!process_sp)
726 return false;
727
728 StateType event_state =
730 if (event_state == eStateInvalid)
731 return false;
732
733 switch (event_state) {
734 case eStateInvalid:
735 case eStateUnloaded:
736 case eStateAttaching:
737 case eStateLaunching:
738 case eStateStepping:
739 case eStateDetached:
740 if (stream)
741 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
742 StateAsCString(event_state));
743 if (event_state == eStateDetached)
744 pop_process_io_handler = true;
745 break;
746
747 case eStateConnected:
748 case eStateRunning:
749 // Don't be chatty when we run...
750 break;
751
752 case eStateExited:
753 if (stream)
754 process_sp->GetStatus(*stream);
755 pop_process_io_handler = true;
756 break;
757
758 case eStateStopped:
759 case eStateCrashed:
760 case eStateSuspended:
761 // Make sure the program hasn't been auto-restarted:
763 if (stream) {
764 size_t num_reasons =
766 if (num_reasons > 0) {
767 // FIXME: Do we want to report this, or would that just be annoyingly
768 // chatty?
769 if (num_reasons == 1) {
770 const char *reason =
772 event_sp.get(), 0);
773 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
774 process_sp->GetID(),
775 reason ? reason : "<UNKNOWN REASON>");
776 } else {
777 stream->Printf("Process %" PRIu64
778 " stopped and restarted, reasons:\n",
779 process_sp->GetID());
780
781 for (size_t i = 0; i < num_reasons; i++) {
782 const char *reason =
784 event_sp.get(), i);
785 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
786 }
787 }
788 }
789 }
790 } else {
791 StopInfoSP curr_thread_stop_info_sp;
792 // Lock the thread list so it doesn't change on us, this is the scope for
793 // the locker:
794 {
795 ThreadList &thread_list = process_sp->GetThreadList();
796 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
797
798 ThreadSP curr_thread(thread_list.GetSelectedThread());
799 ThreadSP thread;
800 StopReason curr_thread_stop_reason = eStopReasonInvalid;
801 bool prefer_curr_thread = false;
802 if (curr_thread && curr_thread->IsValid()) {
803 curr_thread_stop_reason = curr_thread->GetStopReason();
804 switch (curr_thread_stop_reason) {
805 case eStopReasonNone:
807 // Don't prefer the current thread if it didn't stop for a reason.
808 break;
809 case eStopReasonSignal: {
810 // We need to do the same computation we do for other threads
811 // below in case the current thread happens to be the one that
812 // stopped for the no-stop signal.
813 uint64_t signo = curr_thread->GetStopInfo()->GetValue();
814 if (process_sp->GetUnixSignals()->GetShouldStop(signo))
815 prefer_curr_thread = true;
816 } break;
817 default:
818 prefer_curr_thread = true;
819 break;
820 }
821 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
822 }
823
824 if (!prefer_curr_thread) {
825 // Prefer a thread that has just completed its plan over another
826 // thread as current thread.
827 ThreadSP plan_thread;
828 ThreadSP other_thread;
829
830 const size_t num_threads = thread_list.GetSize();
831 size_t i;
832 for (i = 0; i < num_threads; ++i) {
833 thread = thread_list.GetThreadAtIndex(i);
834 StopReason thread_stop_reason = thread->GetStopReason();
835 switch (thread_stop_reason) {
837 case eStopReasonNone:
838 break;
839
840 case eStopReasonSignal: {
841 // Don't select a signal thread if we weren't going to stop at
842 // that signal. We have to have had another reason for stopping
843 // here, and the user doesn't want to see this thread.
844 uint64_t signo = thread->GetStopInfo()->GetValue();
845 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
846 if (!other_thread)
847 other_thread = thread;
848 }
849 break;
850 }
851 case eStopReasonTrace:
855 case eStopReasonExec:
856 case eStopReasonFork:
857 case eStopReasonVFork:
862 if (!other_thread)
863 other_thread = thread;
864 break;
866 if (!plan_thread)
867 plan_thread = thread;
868 break;
869 }
870 }
871 if (plan_thread)
872 thread_list.SetSelectedThreadByID(plan_thread->GetID());
873 else if (other_thread)
874 thread_list.SetSelectedThreadByID(other_thread->GetID());
875 else {
876 if (curr_thread && curr_thread->IsValid())
877 thread = curr_thread;
878 else
879 thread = thread_list.GetThreadAtIndex(0);
880
881 if (thread)
882 thread_list.SetSelectedThreadByID(thread->GetID());
883 }
884 }
885 }
886 // Drop the ThreadList mutex by here, since GetThreadStatus below might
887 // have to run code, e.g. for Data formatters, and if we hold the
888 // ThreadList mutex, then the process is going to have a hard time
889 // restarting the process.
890 if (stream) {
891 Debugger &debugger = process_sp->GetTarget().GetDebugger();
892 if (debugger.GetTargetList().GetSelectedTarget().get() ==
893 &process_sp->GetTarget()) {
894 ThreadSP thread_sp = process_sp->GetThreadList().GetSelectedThread();
895
896 if (!thread_sp || !thread_sp->IsValid())
897 return false;
898
899 const bool only_threads_with_stop_reason = true;
900 const uint32_t start_frame =
901 thread_sp->GetSelectedFrameIndex(select_most_relevant);
902 const uint32_t num_frames = 1;
903 const uint32_t num_frames_with_source = 1;
904 const bool stop_format = true;
905
906 process_sp->GetStatus(*stream);
907 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
908 start_frame, num_frames,
909 num_frames_with_source,
910 stop_format);
911 if (curr_thread_stop_info_sp) {
912 lldb::addr_t crashing_address;
914 curr_thread_stop_info_sp, &crashing_address);
915 if (valobj_sp) {
919 stream->PutCString("Likely cause: ");
920 valobj_sp->GetExpressionPath(*stream, format);
921 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
922 }
923 }
924 } else {
925 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
926 process_sp->GetTarget().shared_from_this());
927 if (target_idx != UINT32_MAX)
928 stream->Printf("Target %d: (", target_idx);
929 else
930 stream->Printf("Target <unknown index>: (");
931 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
932 stream->Printf(") stopped.\n");
933 }
934 }
935
936 // Pop the process IO handler
937 pop_process_io_handler = true;
938 }
939 break;
940 }
941
942 if (handle_pop && pop_process_io_handler)
943 process_sp->PopProcessIOHandler();
944
945 return true;
946}
947
949 if (listener_sp) {
950 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
952 } else
953 return false;
954}
955
957
959 const Timeout<std::micro> &timeout,
960 ListenerSP hijack_listener_sp) {
962 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
963
964 ListenerSP listener_sp = hijack_listener_sp;
965 if (!listener_sp)
966 listener_sp = GetPrimaryListener();
967
968 StateType state = eStateInvalid;
969 if (listener_sp->GetEventForBroadcasterWithType(
971 timeout)) {
972 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
973 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
974 else
975 LLDB_LOG(log, "got no event or was interrupted.");
976 }
977
978 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
979 return state;
980}
981
984
985 LLDB_LOGF(log, "Process::%s...", __FUNCTION__);
986
987 Event *event_ptr;
988 event_ptr = GetPrimaryListener()->PeekAtNextEventForBroadcasterWithType(
990 if (log) {
991 if (event_ptr) {
992 LLDB_LOGF(log, "Process::%s (event_ptr) => %s", __FUNCTION__,
994 } else {
995 LLDB_LOGF(log, "Process::%s no events found", __FUNCTION__);
996 }
997 }
998 return event_ptr;
999}
1000
1003 const Timeout<std::micro> &timeout) {
1004 Log *log = GetLog(LLDBLog::Process);
1005 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
1006
1007 StateType state = eStateInvalid;
1008 if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1011 timeout))
1012 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1013 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1014
1015 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
1016 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
1017 return state;
1018}
1019
1021 const Timeout<std::micro> &timeout,
1022 bool control_only) {
1023 Log *log = GetLog(LLDBLog::Process);
1024 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
1025
1026 if (control_only)
1027 return m_private_state_listener_sp->GetEventForBroadcaster(
1028 &m_private_state_control_broadcaster, event_sp, timeout);
1029 else
1030 return m_private_state_listener_sp->GetEvent(event_sp, timeout);
1031}
1032
1035}
1036
1038 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1039
1041 return m_exit_status;
1042 return -1;
1043}
1044
1046 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1047
1049 return m_exit_string.c_str();
1050 return nullptr;
1051}
1052
1053bool Process::SetExitStatus(int status, llvm::StringRef exit_string) {
1054 // Use a mutex to protect setting the exit status.
1055 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1056
1058 LLDB_LOG(log, "(plugin = {0} status = {1} ({1:x8}), description=\"{2}\")",
1059 GetPluginName(), status, exit_string);
1060
1061 // We were already in the exited state
1063 LLDB_LOG(
1064 log,
1065 "(plugin = {0}) ignoring exit status because state was already set "
1066 "to eStateExited",
1067 GetPluginName());
1068 return false;
1069 }
1070
1071 m_exit_status = status;
1072 if (!exit_string.empty())
1073 m_exit_string = exit_string.str();
1074 else
1075 m_exit_string.clear();
1076
1077 // Clear the last natural stop ID since it has a strong reference to this
1078 // process
1080
1082
1083 // Allow subclasses to do some cleanup
1084 DidExit();
1085
1086 return true;
1087}
1088
1090 switch (m_private_state.GetValue()) {
1091 case eStateConnected:
1092 case eStateAttaching:
1093 case eStateLaunching:
1094 case eStateStopped:
1095 case eStateRunning:
1096 case eStateStepping:
1097 case eStateCrashed:
1098 case eStateSuspended:
1099 return true;
1100 default:
1101 return false;
1102 }
1103}
1104
1105// This static callback can be used to watch for local child processes on the
1106// current host. The child process exits, the process will be found in the
1107// global target list (we want to be completely sure that the
1108// lldb_private::Process doesn't go away before we can deliver the signal.
1110 lldb::pid_t pid, bool exited,
1111 int signo, // Zero for no signal
1112 int exit_status // Exit value of process if signal is zero
1113 ) {
1114 Log *log = GetLog(LLDBLog::Process);
1115 LLDB_LOGF(log,
1116 "Process::SetProcessExitStatus (pid=%" PRIu64
1117 ", exited=%i, signal=%i, exit_status=%i)\n",
1118 pid, exited, signo, exit_status);
1119
1120 if (exited) {
1122 if (target_sp) {
1123 ProcessSP process_sp(target_sp->GetProcessSP());
1124 if (process_sp) {
1125 llvm::StringRef signal_str =
1126 process_sp->GetUnixSignals()->GetSignalAsStringRef(signo);
1127 process_sp->SetExitStatus(exit_status, signal_str);
1128 }
1129 }
1130 return true;
1131 }
1132 return false;
1133}
1134
1136 ThreadList &new_thread_list) {
1138 return DoUpdateThreadList(old_thread_list, new_thread_list);
1139}
1140
1142 const uint32_t stop_id = GetStopID();
1143 if (m_thread_list.GetSize(false) == 0 ||
1144 stop_id != m_thread_list.GetStopID()) {
1145 bool clear_unused_threads = true;
1146 const StateType state = GetPrivateState();
1147 if (StateIsStoppedState(state, true)) {
1148 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
1149 m_thread_list.SetStopID(stop_id);
1150
1151 // m_thread_list does have its own mutex, but we need to hold onto the
1152 // mutex between the call to UpdateThreadList(...) and the
1153 // os->UpdateThreadList(...) so it doesn't change on us
1154 ThreadList &old_thread_list = m_thread_list;
1155 ThreadList real_thread_list(this);
1156 ThreadList new_thread_list(this);
1157 // Always update the thread list with the protocol specific thread list,
1158 // but only update if "true" is returned
1159 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1160 // Don't call into the OperatingSystem to update the thread list if we
1161 // are shutting down, since that may call back into the SBAPI's,
1162 // requiring the API lock which is already held by whoever is shutting
1163 // us down, causing a deadlock.
1165 if (os && !m_destroy_in_process) {
1166 // Clear any old backing threads where memory threads might have been
1167 // backed by actual threads from the lldb_private::Process subclass
1168 size_t num_old_threads = old_thread_list.GetSize(false);
1169 for (size_t i = 0; i < num_old_threads; ++i)
1170 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1171 // See if the OS plugin reports all threads. If it does, then
1172 // it is safe to clear unseen thread's plans here. Otherwise we
1173 // should preserve them in case they show up again:
1174 clear_unused_threads = GetOSPluginReportsAllThreads();
1175
1176 // Turn off dynamic types to ensure we don't run any expressions.
1177 // Objective-C can run an expression to determine if a SBValue is a
1178 // dynamic type or not and we need to avoid this. OperatingSystem
1179 // plug-ins can't run expressions that require running code...
1180
1181 Target &target = GetTarget();
1182 const lldb::DynamicValueType saved_prefer_dynamic =
1183 target.GetPreferDynamicValue();
1184 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1186
1187 // Now let the OperatingSystem plug-in update the thread list
1188
1189 os->UpdateThreadList(
1190 old_thread_list, // Old list full of threads created by OS plug-in
1191 real_thread_list, // The actual thread list full of threads
1192 // created by each lldb_private::Process
1193 // subclass
1194 new_thread_list); // The new thread list that we will show to the
1195 // user that gets filled in
1196
1197 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1198 target.SetPreferDynamicValue(saved_prefer_dynamic);
1199 } else {
1200 // No OS plug-in, the new thread list is the same as the real thread
1201 // list.
1202 new_thread_list = real_thread_list;
1203 }
1204
1205 m_thread_list_real.Update(real_thread_list);
1206 m_thread_list.Update(new_thread_list);
1207 m_thread_list.SetStopID(stop_id);
1208
1210 // Clear any extended threads that we may have accumulated previously
1213
1216 }
1217 }
1218 // Now update the plan stack map.
1219 // If we do have an OS plugin, any absent real threads in the
1220 // m_thread_list have already been removed from the ThreadPlanStackMap.
1221 // So any remaining threads are OS Plugin threads, and those we want to
1222 // preserve in case they show up again.
1223 m_thread_plans.Update(m_thread_list, clear_unused_threads);
1224 }
1225 }
1226}
1227
1229 return m_thread_plans.Find(tid);
1230}
1231
1233 return m_thread_plans.PrunePlansForTID(tid);
1234}
1235
1237 m_thread_plans.Update(GetThreadList(), true, false);
1238}
1239
1241 lldb::DescriptionLevel desc_level,
1242 bool internal, bool condense_trivial,
1243 bool skip_unreported_plans) {
1245 strm, tid, desc_level, internal, condense_trivial, skip_unreported_plans);
1246}
1248 bool internal, bool condense_trivial,
1249 bool skip_unreported_plans) {
1250 m_thread_plans.DumpPlans(strm, desc_level, internal, condense_trivial,
1251 skip_unreported_plans);
1252}
1253
1255 if (m_system_runtime_up) {
1256 if (m_queue_list.GetSize() == 0 ||
1258 const StateType state = GetPrivateState();
1259 if (StateIsStoppedState(state, true)) {
1260 m_system_runtime_up->PopulateQueueList(m_queue_list);
1262 }
1263 }
1264 }
1265}
1266
1269 if (os)
1270 return os->CreateThread(tid, context);
1271 return ThreadSP();
1272}
1273
1274uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1275 return AssignIndexIDToThread(thread_id);
1276}
1277
1278bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1279 return (m_thread_id_to_index_id_map.find(thread_id) !=
1281}
1282
1283uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1284 uint32_t result = 0;
1285 std::map<uint64_t, uint32_t>::iterator iterator =
1286 m_thread_id_to_index_id_map.find(thread_id);
1287 if (iterator == m_thread_id_to_index_id_map.end()) {
1288 result = ++m_thread_index_id;
1289 m_thread_id_to_index_id_map[thread_id] = result;
1290 } else {
1291 result = iterator->second;
1292 }
1293
1294 return result;
1295}
1296
1299 return m_private_state.GetValue();
1300 else
1301 return m_public_state.GetValue();
1302}
1303
1304void Process::SetPublicState(StateType new_state, bool restarted) {
1305 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1306 if (new_state_is_stopped) {
1307 // This will only set the time if the public stop time has no value, so
1308 // it is ok to call this multiple times. With a public stop we can't look
1309 // at the stop ID because many private stops might have happened, so we
1310 // can't check for a stop ID of zero. This allows the "statistics" command
1311 // to dump the time it takes to reach somewhere in your code, like a
1312 // breakpoint you set.
1314 }
1315
1317 LLDB_LOGF(log, "(plugin = %s, state = %s, restarted = %i)",
1318 GetPluginName().data(), StateAsCString(new_state), restarted);
1319 const StateType old_state = m_public_state.GetValue();
1320 m_public_state.SetValue(new_state);
1321
1322 // On the transition from Run to Stopped, we unlock the writer end of the run
1323 // lock. The lock gets locked in Resume, which is the public API to tell the
1324 // program to run.
1326 if (new_state == eStateDetached) {
1327 LLDB_LOGF(log,
1328 "(plugin = %s, state = %s) -- unlocking run lock for detach",
1329 GetPluginName().data(), StateAsCString(new_state));
1331 } else {
1332 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1333 if ((old_state_is_stopped != new_state_is_stopped)) {
1334 if (new_state_is_stopped && !restarted) {
1335 LLDB_LOGF(log, "(plugin = %s, state = %s) -- unlocking run lock",
1336 GetPluginName().data(), StateAsCString(new_state));
1338 }
1339 }
1340 }
1341 }
1342}
1343
1346 LLDB_LOGF(log, "(plugin = %s) -- locking run lock", GetPluginName().data());
1348 Status error("Resume request failed - process still running.");
1349 LLDB_LOGF(log, "(plugin = %s) -- TrySetRunning failed, not resuming.",
1350 GetPluginName().data());
1351 return error;
1352 }
1354 if (!error.Success()) {
1355 // Undo running state change
1357 }
1358 return error;
1359}
1360
1363 LLDB_LOGF(log, "Process::ResumeSynchronous -- locking run lock");
1365 Status error("Resume request failed - process still running.");
1366 LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");
1367 return error;
1368 }
1369
1370 ListenerSP listener_sp(
1372 HijackProcessEvents(listener_sp);
1373
1375 if (error.Success()) {
1376 StateType state =
1377 WaitForProcessToStop(std::nullopt, nullptr, true, listener_sp, stream,
1378 true /* use_run_lock */, SelectMostRelevantFrame);
1379 const bool must_be_alive =
1380 false; // eStateExited is ok, so this must be false
1381 if (!StateIsStoppedState(state, must_be_alive))
1382 error.SetErrorStringWithFormat(
1383 "process not in stopped state after synchronous resume: %s",
1384 StateAsCString(state));
1385 } else {
1386 // Undo running state change
1388 }
1389
1390 // Undo the hijacking of process events...
1392
1393 return error;
1394}
1395
1398 llvm::StringRef hijacking_name = GetHijackingListenerName();
1399 if (!hijacking_name.starts_with("lldb.internal"))
1400 return true;
1401 }
1402 return false;
1403}
1404
1407 llvm::StringRef hijacking_name = GetHijackingListenerName();
1408 if (hijacking_name == ResumeSynchronousHijackListenerName)
1409 return true;
1410 }
1411 return false;
1412}
1413
1415
1417 if (m_finalizing)
1418 return;
1419
1421 bool state_changed = false;
1422
1423 LLDB_LOGF(log, "(plugin = %s, state = %s)", GetPluginName().data(),
1424 StateAsCString(new_state));
1425
1426 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1427 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1428
1429 const StateType old_state = m_private_state.GetValueNoLock();
1430 state_changed = old_state != new_state;
1431
1432 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1433 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1434 if (old_state_is_stopped != new_state_is_stopped) {
1435 if (new_state_is_stopped)
1437 else
1439 }
1440
1441 if (state_changed) {
1443 EventSP event_sp(
1445 new ProcessEventData(shared_from_this(), new_state)));
1446 if (StateIsStoppedState(new_state, false)) {
1447 // Note, this currently assumes that all threads in the list stop when
1448 // the process stops. In the future we will want to support a debugging
1449 // model where some threads continue to run while others are stopped.
1450 // When that happens we will either need a way for the thread list to
1451 // identify which threads are stopping or create a special thread list
1452 // containing only threads which actually stopped.
1453 //
1454 // The process plugin is responsible for managing the actual behavior of
1455 // the threads and should have stopped any threads that are going to stop
1456 // before we get here.
1458
1459 if (m_mod_id.BumpStopID() == 0)
1461
1465 LLDB_LOGF(log, "(plugin = %s, state = %s, stop_id = %u",
1466 GetPluginName().data(), StateAsCString(new_state),
1468 }
1469
1471 } else {
1472 LLDB_LOGF(log, "(plugin = %s, state = %s) state didn't change. Ignoring...",
1473 GetPluginName().data(), StateAsCString(new_state));
1474 }
1475}
1476
1479}
1480
1483}
1484
1486
1488 if (!m_abi_sp)
1489 m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());
1490 return m_abi_sp;
1491}
1492
1493std::vector<LanguageRuntime *> Process::GetLanguageRuntimes() {
1494 std::vector<LanguageRuntime *> language_runtimes;
1495
1496 if (m_finalizing)
1497 return language_runtimes;
1498
1499 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
1500 // Before we pass off a copy of the language runtimes, we must make sure that
1501 // our collection is properly populated. It's possible that some of the
1502 // language runtimes were not loaded yet, either because nobody requested it
1503 // yet or the proper condition for loading wasn't yet met (e.g. libc++.so
1504 // hadn't been loaded).
1505 for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {
1506 if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type))
1507 language_runtimes.emplace_back(runtime);
1508 }
1509
1510 return language_runtimes;
1511}
1512
1514 if (m_finalizing)
1515 return nullptr;
1516
1517 LanguageRuntime *runtime = nullptr;
1518
1519 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
1520 LanguageRuntimeCollection::iterator pos;
1521 pos = m_language_runtimes.find(language);
1522 if (pos == m_language_runtimes.end() || !pos->second) {
1523 lldb::LanguageRuntimeSP runtime_sp(
1524 LanguageRuntime::FindPlugin(this, language));
1525
1526 m_language_runtimes[language] = runtime_sp;
1527 runtime = runtime_sp.get();
1528 } else
1529 runtime = pos->second.get();
1530
1531 if (runtime)
1532 // It's possible that a language runtime can support multiple LanguageTypes,
1533 // for example, CPPLanguageRuntime will support eLanguageTypeC_plus_plus,
1534 // eLanguageTypeC_plus_plus_03, etc. Because of this, we should get the
1535 // primary language type and make sure that our runtime supports it.
1536 assert(runtime->GetLanguageType() == Language::GetPrimaryLanguage(language));
1537
1538 return runtime;
1539}
1540
1542 if (m_finalizing)
1543 return false;
1544
1545 if (in_value.IsDynamic())
1546 return false;
1547 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1548
1549 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1550 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1551 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1552 }
1553
1554 for (LanguageRuntime *runtime : GetLanguageRuntimes()) {
1555 if (runtime->CouldHaveDynamicValue(in_value))
1556 return true;
1557 }
1558
1559 return false;
1560}
1561
1563 m_dynamic_checkers_up.reset(dynamic_checkers);
1564}
1565
1568}
1569
1572}
1573
1575 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1576 // bp_site->SetEnabled(true);
1577 DisableBreakpointSite(bp_site);
1578 });
1579}
1580
1583
1584 if (error.Success())
1586
1587 return error;
1588}
1589
1591 Status error;
1592 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1593 if (bp_site_sp) {
1594 if (bp_site_sp->IsEnabled())
1595 error = DisableBreakpointSite(bp_site_sp.get());
1596 } else {
1597 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1598 break_id);
1599 }
1600
1601 return error;
1602}
1603
1605 Status error;
1606 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1607 if (bp_site_sp) {
1608 if (!bp_site_sp->IsEnabled())
1609 error = EnableBreakpointSite(bp_site_sp.get());
1610 } else {
1611 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1612 break_id);
1613 }
1614 return error;
1615}
1616
1619 bool use_hardware) {
1620 addr_t load_addr = LLDB_INVALID_ADDRESS;
1621
1622 bool show_error = true;
1623 switch (GetState()) {
1624 case eStateInvalid:
1625 case eStateUnloaded:
1626 case eStateConnected:
1627 case eStateAttaching:
1628 case eStateLaunching:
1629 case eStateDetached:
1630 case eStateExited:
1631 show_error = false;
1632 break;
1633
1634 case eStateStopped:
1635 case eStateRunning:
1636 case eStateStepping:
1637 case eStateCrashed:
1638 case eStateSuspended:
1639 show_error = IsAlive();
1640 break;
1641 }
1642
1643 // Reset the IsIndirect flag here, in case the location changes from pointing
1644 // to a indirect symbol to a regular symbol.
1645 owner->SetIsIndirect(false);
1646
1647 if (owner->ShouldResolveIndirectFunctions()) {
1648 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1649 if (symbol && symbol->IsIndirect()) {
1650 Status error;
1651 Address symbol_address = symbol->GetAddress();
1652 load_addr = ResolveIndirectFunction(&symbol_address, error);
1653 if (!error.Success() && show_error) {
1655 "warning: failed to resolve indirect function at 0x%" PRIx64
1656 " for breakpoint %i.%i: %s\n",
1657 symbol->GetLoadAddress(&GetTarget()),
1658 owner->GetBreakpoint().GetID(), owner->GetID(),
1659 error.AsCString() ? error.AsCString() : "unknown error");
1660 return LLDB_INVALID_BREAK_ID;
1661 }
1662 Address resolved_address(load_addr);
1663 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1664 owner->SetIsIndirect(true);
1665 } else
1666 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1667 } else
1668 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1669
1670 if (load_addr != LLDB_INVALID_ADDRESS) {
1671 BreakpointSiteSP bp_site_sp;
1672
1673 // Look up this breakpoint site. If it exists, then add this new owner,
1674 // otherwise create a new breakpoint site and add it.
1675
1676 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1677
1678 if (bp_site_sp) {
1679 bp_site_sp->AddOwner(owner);
1680 owner->SetBreakpointSite(bp_site_sp);
1681 return bp_site_sp->GetID();
1682 } else {
1683 bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1684 load_addr, use_hardware));
1685 if (bp_site_sp) {
1686 Status error = EnableBreakpointSite(bp_site_sp.get());
1687 if (error.Success()) {
1688 owner->SetBreakpointSite(bp_site_sp);
1689 return m_breakpoint_site_list.Add(bp_site_sp);
1690 } else {
1691 if (show_error || use_hardware) {
1692 // Report error for setting breakpoint...
1694 "warning: failed to set breakpoint site at 0x%" PRIx64
1695 " for breakpoint %i.%i: %s\n",
1696 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1697 error.AsCString() ? error.AsCString() : "unknown error");
1698 }
1699 }
1700 }
1701 }
1702 }
1703 // We failed to enable the breakpoint
1704 return LLDB_INVALID_BREAK_ID;
1705}
1706
1708 lldb::user_id_t owner_loc_id,
1709 BreakpointSiteSP &bp_site_sp) {
1710 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1711 if (num_owners == 0) {
1712 // Don't try to disable the site if we don't have a live process anymore.
1713 if (IsAlive())
1714 DisableBreakpointSite(bp_site_sp.get());
1715 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1716 }
1717}
1718
1720 uint8_t *buf) const {
1721 size_t bytes_removed = 0;
1722 BreakpointSiteList bp_sites_in_range;
1723
1724 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1725 bp_sites_in_range)) {
1726 bp_sites_in_range.ForEach([bp_addr, size,
1727 buf](BreakpointSite *bp_site) -> void {
1728 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1729 addr_t intersect_addr;
1730 size_t intersect_size;
1731 size_t opcode_offset;
1732 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1733 &intersect_size, &opcode_offset)) {
1734 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1735 assert(bp_addr < intersect_addr + intersect_size &&
1736 intersect_addr + intersect_size <= bp_addr + size);
1737 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1738 size_t buf_offset = intersect_addr - bp_addr;
1739 ::memcpy(buf + buf_offset,
1740 bp_site->GetSavedOpcodeBytes() + opcode_offset,
1741 intersect_size);
1742 }
1743 }
1744 });
1745 }
1746 return bytes_removed;
1747}
1748
1750 PlatformSP platform_sp(GetTarget().GetPlatform());
1751 if (platform_sp)
1752 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
1753 return 0;
1754}
1755
1757 Status error;
1758 assert(bp_site != nullptr);
1760 const addr_t bp_addr = bp_site->GetLoadAddress();
1761 LLDB_LOGF(
1762 log, "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
1763 bp_site->GetID(), (uint64_t)bp_addr);
1764 if (bp_site->IsEnabled()) {
1765 LLDB_LOGF(
1766 log,
1767 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1768 " -- already enabled",
1769 bp_site->GetID(), (uint64_t)bp_addr);
1770 return error;
1771 }
1772
1773 if (bp_addr == LLDB_INVALID_ADDRESS) {
1774 error.SetErrorString("BreakpointSite contains an invalid load address.");
1775 return error;
1776 }
1777 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1778 // trap for the breakpoint site
1779 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1780
1781 if (bp_opcode_size == 0) {
1782 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
1783 "returned zero, unable to get breakpoint "
1784 "trap for address 0x%" PRIx64,
1785 bp_addr);
1786 } else {
1787 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1788
1789 if (bp_opcode_bytes == nullptr) {
1790 error.SetErrorString(
1791 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1792 return error;
1793 }
1794
1795 // Save the original opcode by reading it
1796 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
1797 error) == bp_opcode_size) {
1798 // Write a software breakpoint in place of the original opcode
1799 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
1800 bp_opcode_size) {
1801 uint8_t verify_bp_opcode_bytes[64];
1802 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
1803 error) == bp_opcode_size) {
1804 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
1805 bp_opcode_size) == 0) {
1806 bp_site->SetEnabled(true);
1808 LLDB_LOGF(log,
1809 "Process::EnableSoftwareBreakpoint (site_id = %d) "
1810 "addr = 0x%" PRIx64 " -- SUCCESS",
1811 bp_site->GetID(), (uint64_t)bp_addr);
1812 } else
1813 error.SetErrorString(
1814 "failed to verify the breakpoint trap in memory.");
1815 } else
1816 error.SetErrorString(
1817 "Unable to read memory to verify breakpoint trap.");
1818 } else
1819 error.SetErrorString("Unable to write breakpoint trap to memory.");
1820 } else
1821 error.SetErrorString("Unable to read memory at breakpoint address.");
1822 }
1823 if (log && error.Fail())
1824 LLDB_LOGF(
1825 log,
1826 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1827 " -- FAILED: %s",
1828 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1829 return error;
1830}
1831
1833 Status error;
1834 assert(bp_site != nullptr);
1836 addr_t bp_addr = bp_site->GetLoadAddress();
1837 lldb::user_id_t breakID = bp_site->GetID();
1838 LLDB_LOGF(log,
1839 "Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
1840 ") addr = 0x%" PRIx64,
1841 breakID, (uint64_t)bp_addr);
1842
1843 if (bp_site->IsHardware()) {
1844 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1845 } else if (bp_site->IsEnabled()) {
1846 const size_t break_op_size = bp_site->GetByteSize();
1847 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
1848 if (break_op_size > 0) {
1849 // Clear a software breakpoint instruction
1850 uint8_t curr_break_op[8];
1851 assert(break_op_size <= sizeof(curr_break_op));
1852 bool break_op_found = false;
1853
1854 // Read the breakpoint opcode
1855 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
1856 break_op_size) {
1857 bool verify = false;
1858 // Make sure the breakpoint opcode exists at this address
1859 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
1860 break_op_found = true;
1861 // We found a valid breakpoint opcode at this address, now restore
1862 // the saved opcode.
1863 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
1864 break_op_size, error) == break_op_size) {
1865 verify = true;
1866 } else
1867 error.SetErrorString(
1868 "Memory write failed when restoring original opcode.");
1869 } else {
1870 error.SetErrorString(
1871 "Original breakpoint trap is no longer in memory.");
1872 // Set verify to true and so we can check if the original opcode has
1873 // already been restored
1874 verify = true;
1875 }
1876
1877 if (verify) {
1878 uint8_t verify_opcode[8];
1879 assert(break_op_size < sizeof(verify_opcode));
1880 // Verify that our original opcode made it back to the inferior
1881 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
1882 break_op_size) {
1883 // compare the memory we just read with the original opcode
1884 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
1885 break_op_size) == 0) {
1886 // SUCCESS
1887 bp_site->SetEnabled(false);
1888 LLDB_LOGF(log,
1889 "Process::DisableSoftwareBreakpoint (site_id = %d) "
1890 "addr = 0x%" PRIx64 " -- SUCCESS",
1891 bp_site->GetID(), (uint64_t)bp_addr);
1892 return error;
1893 } else {
1894 if (break_op_found)
1895 error.SetErrorString("Failed to restore original opcode.");
1896 }
1897 } else
1898 error.SetErrorString("Failed to read memory to verify that "
1899 "breakpoint trap was restored.");
1900 }
1901 } else
1902 error.SetErrorString(
1903 "Unable to read memory that should contain the breakpoint trap.");
1904 }
1905 } else {
1906 LLDB_LOGF(
1907 log,
1908 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1909 " -- already disabled",
1910 bp_site->GetID(), (uint64_t)bp_addr);
1911 return error;
1912 }
1913
1914 LLDB_LOGF(
1915 log,
1916 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1917 " -- FAILED: %s",
1918 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1919 return error;
1920}
1921
1922// Uncomment to verify memory caching works after making changes to caching
1923// code
1924//#define VERIFY_MEMORY_READS
1925
1926size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
1927 if (ABISP abi_sp = GetABI())
1928 addr = abi_sp->FixAnyAddress(addr);
1929
1930 error.Clear();
1931 if (!GetDisableMemoryCache()) {
1932#if defined(VERIFY_MEMORY_READS)
1933 // Memory caching is enabled, with debug verification
1934
1935 if (buf && size) {
1936 // Uncomment the line below to make sure memory caching is working.
1937 // I ran this through the test suite and got no assertions, so I am
1938 // pretty confident this is working well. If any changes are made to
1939 // memory caching, uncomment the line below and test your changes!
1940
1941 // Verify all memory reads by using the cache first, then redundantly
1942 // reading the same memory from the inferior and comparing to make sure
1943 // everything is exactly the same.
1944 std::string verify_buf(size, '\0');
1945 assert(verify_buf.size() == size);
1946 const size_t cache_bytes_read =
1947 m_memory_cache.Read(this, addr, buf, size, error);
1948 Status verify_error;
1949 const size_t verify_bytes_read =
1950 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
1951 verify_buf.size(), verify_error);
1952 assert(cache_bytes_read == verify_bytes_read);
1953 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1954 assert(verify_error.Success() == error.Success());
1955 return cache_bytes_read;
1956 }
1957 return 0;
1958#else // !defined(VERIFY_MEMORY_READS)
1959 // Memory caching is enabled, without debug verification
1960
1961 return m_memory_cache.Read(addr, buf, size, error);
1962#endif // defined (VERIFY_MEMORY_READS)
1963 } else {
1964 // Memory caching is disabled
1965
1966 return ReadMemoryFromInferior(addr, buf, size, error);
1967 }
1968}
1969
1970size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
1971 Status &error) {
1972 char buf[256];
1973 out_str.clear();
1974 addr_t curr_addr = addr;
1975 while (true) {
1976 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
1977 if (length == 0)
1978 break;
1979 out_str.append(buf, length);
1980 // If we got "length - 1" bytes, we didn't get the whole C string, we need
1981 // to read some more characters
1982 if (length == sizeof(buf) - 1)
1983 curr_addr += length;
1984 else
1985 break;
1986 }
1987 return out_str.size();
1988}
1989
1990// Deprecated in favor of ReadStringFromMemory which has wchar support and
1991// correct code to find null terminators.
1993 size_t dst_max_len,
1994 Status &result_error) {
1995 size_t total_cstr_len = 0;
1996 if (dst && dst_max_len) {
1997 result_error.Clear();
1998 // NULL out everything just to be safe
1999 memset(dst, 0, dst_max_len);
2000 Status error;
2001 addr_t curr_addr = addr;
2002 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2003 size_t bytes_left = dst_max_len - 1;
2004 char *curr_dst = dst;
2005
2006 while (bytes_left > 0) {
2007 addr_t cache_line_bytes_left =
2008 cache_line_size - (curr_addr % cache_line_size);
2009 addr_t bytes_to_read =
2010 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2011 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
2012
2013 if (bytes_read == 0) {
2014 result_error = error;
2015 dst[total_cstr_len] = '\0';
2016 break;
2017 }
2018 const size_t len = strlen(curr_dst);
2019
2020 total_cstr_len += len;
2021
2022 if (len < bytes_to_read)
2023 break;
2024
2025 curr_dst += bytes_read;
2026 curr_addr += bytes_read;
2027 bytes_left -= bytes_read;
2028 }
2029 } else {
2030 if (dst == nullptr)
2031 result_error.SetErrorString("invalid arguments");
2032 else
2033 result_error.Clear();
2034 }
2035 return total_cstr_len;
2036}
2037
2038size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
2039 Status &error) {
2041
2042 if (ABISP abi_sp = GetABI())
2043 addr = abi_sp->FixAnyAddress(addr);
2044
2045 if (buf == nullptr || size == 0)
2046 return 0;
2047
2048 size_t bytes_read = 0;
2049 uint8_t *bytes = (uint8_t *)buf;
2050
2051 while (bytes_read < size) {
2052 const size_t curr_size = size - bytes_read;
2053 const size_t curr_bytes_read =
2054 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2055 bytes_read += curr_bytes_read;
2056 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2057 break;
2058 }
2059
2060 // Replace any software breakpoint opcodes that fall into this range back
2061 // into "buf" before we return
2062 if (bytes_read > 0)
2063 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2064 return bytes_read;
2065}
2066
2068 size_t integer_byte_size,
2069 uint64_t fail_value,
2070 Status &error) {
2071 Scalar scalar;
2072 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2073 error))
2074 return scalar.ULongLong(fail_value);
2075 return fail_value;
2076}
2077
2079 size_t integer_byte_size,
2080 int64_t fail_value,
2081 Status &error) {
2082 Scalar scalar;
2083 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2084 error))
2085 return scalar.SLongLong(fail_value);
2086 return fail_value;
2087}
2088
2090 Scalar scalar;
2091 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2092 error))
2093 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2094 return LLDB_INVALID_ADDRESS;
2095}
2096
2098 Status &error) {
2099 Scalar scalar;
2100 const uint32_t addr_byte_size = GetAddressByteSize();
2101 if (addr_byte_size <= 4)
2102 scalar = (uint32_t)ptr_value;
2103 else
2104 scalar = ptr_value;
2105 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2106 addr_byte_size;
2107}
2108
2109size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
2110 Status &error) {
2111 size_t bytes_written = 0;
2112 const uint8_t *bytes = (const uint8_t *)buf;
2113
2114 while (bytes_written < size) {
2115 const size_t curr_size = size - bytes_written;
2116 const size_t curr_bytes_written = DoWriteMemory(
2117 addr + bytes_written, bytes + bytes_written, curr_size, error);
2118 bytes_written += curr_bytes_written;
2119 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2120 break;
2121 }
2122 return bytes_written;
2123}
2124
2125size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
2126 Status &error) {
2127 if (ABISP abi_sp = GetABI())
2128 addr = abi_sp->FixAnyAddress(addr);
2129
2130#if defined(ENABLE_MEMORY_CACHING)
2131 m_memory_cache.Flush(addr, size);
2132#endif
2133
2134 if (buf == nullptr || size == 0)
2135 return 0;
2136
2138
2139 // We need to write any data that would go where any current software traps
2140 // (enabled software breakpoints) any software traps (breakpoints) that we
2141 // may have placed in our tasks memory.
2142
2143 BreakpointSiteList bp_sites_in_range;
2144 if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range))
2145 return WriteMemoryPrivate(addr, buf, size, error);
2146
2147 // No breakpoint sites overlap
2148 if (bp_sites_in_range.IsEmpty())
2149 return WriteMemoryPrivate(addr, buf, size, error);
2150
2151 const uint8_t *ubuf = (const uint8_t *)buf;
2152 uint64_t bytes_written = 0;
2153
2154 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2155 &error](BreakpointSite *bp) -> void {
2156 if (error.Fail())
2157 return;
2158
2160 return;
2161
2162 addr_t intersect_addr;
2163 size_t intersect_size;
2164 size_t opcode_offset;
2165 const bool intersects = bp->IntersectsRange(
2166 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2167 UNUSED_IF_ASSERT_DISABLED(intersects);
2168 assert(intersects);
2169 assert(addr <= intersect_addr && intersect_addr < addr + size);
2170 assert(addr < intersect_addr + intersect_size &&
2171 intersect_addr + intersect_size <= addr + size);
2172 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2173
2174 // Check for bytes before this breakpoint
2175 const addr_t curr_addr = addr + bytes_written;
2176 if (intersect_addr > curr_addr) {
2177 // There are some bytes before this breakpoint that we need to just
2178 // write to memory
2179 size_t curr_size = intersect_addr - curr_addr;
2180 size_t curr_bytes_written =
2181 WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error);
2182 bytes_written += curr_bytes_written;
2183 if (curr_bytes_written != curr_size) {
2184 // We weren't able to write all of the requested bytes, we are
2185 // done looping and will return the number of bytes that we have
2186 // written so far.
2187 if (error.Success())
2188 error.SetErrorToGenericError();
2189 }
2190 }
2191 // Now write any bytes that would cover up any software breakpoints
2192 // directly into the breakpoint opcode buffer
2193 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written,
2194 intersect_size);
2195 bytes_written += intersect_size;
2196 });
2197
2198 // Write any remaining bytes after the last breakpoint if we have any left
2199 if (bytes_written < size)
2200 bytes_written +=
2201 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2202 size - bytes_written, error);
2203
2204 return bytes_written;
2205}
2206
2207size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
2208 size_t byte_size, Status &error) {
2209 if (byte_size == UINT32_MAX)
2210 byte_size = scalar.GetByteSize();
2211 if (byte_size > 0) {
2212 uint8_t buf[32];
2213 const size_t mem_size =
2214 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2215 if (mem_size > 0)
2216 return WriteMemory(addr, buf, mem_size, error);
2217 else
2218 error.SetErrorString("failed to get scalar as memory data");
2219 } else {
2220 error.SetErrorString("invalid scalar value");
2221 }
2222 return 0;
2223}
2224
2225size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2226 bool is_signed, Scalar &scalar,
2227 Status &error) {
2228 uint64_t uval = 0;
2229 if (byte_size == 0) {
2230 error.SetErrorString("byte size is zero");
2231 } else if (byte_size & (byte_size - 1)) {
2232 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2233 byte_size);
2234 } else if (byte_size <= sizeof(uval)) {
2235 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2236 if (bytes_read == byte_size) {
2237 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2239 lldb::offset_t offset = 0;
2240 if (byte_size <= 4)
2241 scalar = data.GetMaxU32(&offset, byte_size);
2242 else
2243 scalar = data.GetMaxU64(&offset, byte_size);
2244 if (is_signed)
2245 scalar.SignExtend(byte_size * 8);
2246 return bytes_read;
2247 }
2248 } else {
2249 error.SetErrorStringWithFormat(
2250 "byte size of %u is too large for integer scalar type", byte_size);
2251 }
2252 return 0;
2253}
2254
2255Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {
2256 Status error;
2257 for (const auto &Entry : entries) {
2258 WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),
2259 error);
2260 if (!error.Success())
2261 break;
2262 }
2263 return error;
2264}
2265
2266#define USE_ALLOCATE_MEMORY_CACHE 1
2267addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
2268 Status &error) {
2269 if (GetPrivateState() != eStateStopped) {
2270 error.SetErrorToGenericError();
2271 return LLDB_INVALID_ADDRESS;
2272 }
2273
2274#if defined(USE_ALLOCATE_MEMORY_CACHE)
2275 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2276#else
2277 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2278 Log *log = GetLog(LLDBLog::Process);
2279 LLDB_LOGF(log,
2280 "Process::AllocateMemory(size=%" PRIu64
2281 ", permissions=%s) => 0x%16.16" PRIx64
2282 " (m_stop_id = %u m_memory_id = %u)",
2283 (uint64_t)size, GetPermissionsAsCString(permissions),
2284 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2286 return allocated_addr;
2287#endif
2288}
2289
2290addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
2291 Status &error) {
2292 addr_t return_addr = AllocateMemory(size, permissions, error);
2293 if (error.Success()) {
2294 std::string buffer(size, 0);
2295 WriteMemory(return_addr, buffer.c_str(), size, error);
2296 }
2297 return return_addr;
2298}
2299
2301 if (m_can_jit == eCanJITDontKnow) {
2302 Log *log = GetLog(LLDBLog::Process);
2303 Status err;
2304
2305 uint64_t allocated_memory = AllocateMemory(
2306 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2307 err);
2308
2309 if (err.Success()) {
2311 LLDB_LOGF(log,
2312 "Process::%s pid %" PRIu64
2313 " allocation test passed, CanJIT () is true",
2314 __FUNCTION__, GetID());
2315 } else {
2317 LLDB_LOGF(log,
2318 "Process::%s pid %" PRIu64
2319 " allocation test failed, CanJIT () is false: %s",
2320 __FUNCTION__, GetID(), err.AsCString());
2321 }
2322
2323 DeallocateMemory(allocated_memory);
2324 }
2325
2326 return m_can_jit == eCanJITYes;
2327}
2328
2329void Process::SetCanJIT(bool can_jit) {
2330 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2331}
2332
2333void Process::SetCanRunCode(bool can_run_code) {
2334 SetCanJIT(can_run_code);
2335 m_can_interpret_function_calls = can_run_code;
2336}
2337
2339 Status error;
2340#if defined(USE_ALLOCATE_MEMORY_CACHE)
2342 error.SetErrorStringWithFormat(
2343 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2344 }
2345#else
2347
2348 Log *log = GetLog(LLDBLog::Process);
2349 LLDB_LOGF(log,
2350 "Process::DeallocateMemory(addr=0x%16.16" PRIx64
2351 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2352 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2354#endif
2355 return error;
2356}
2357
2359 if (std::optional<bool> subclass_override = DoGetWatchpointReportedAfter())
2360 return *subclass_override;
2361
2362 bool reported_after = true;
2363 const ArchSpec &arch = GetTarget().GetArchitecture();
2364 if (!arch.IsValid())
2365 return reported_after;
2366 llvm::Triple triple = arch.GetTriple();
2367
2368 if (triple.isMIPS() || triple.isPPC64() || triple.isRISCV() ||
2369 triple.isAArch64() || triple.isArmMClass() || triple.isARM())
2370 reported_after = false;
2371
2372 return reported_after;
2373}
2374
2376 lldb::addr_t header_addr,
2377 size_t size_to_read) {
2378 Log *log = GetLog(LLDBLog::Host);
2379 if (log) {
2380 LLDB_LOGF(log,
2381 "Process::ReadModuleFromMemory reading %s binary from memory",
2382 file_spec.GetPath().c_str());
2383 }
2384 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2385 if (module_sp) {
2386 Status error;
2387 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2388 shared_from_this(), header_addr, error, size_to_read);
2389 if (objfile)
2390 return module_sp;
2391 }
2392 return ModuleSP();
2393}
2394
2396 uint32_t &permissions) {
2397 MemoryRegionInfo range_info;
2398 permissions = 0;
2399 Status error(GetMemoryRegionInfo(load_addr, range_info));
2400 if (!error.Success())
2401 return false;
2402 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2403 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2405 return false;
2406 }
2407
2408 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2409 permissions |= lldb::ePermissionsReadable;
2410
2411 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2412 permissions |= lldb::ePermissionsWritable;
2413
2414 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2415 permissions |= lldb::ePermissionsExecutable;
2416
2417 return true;
2418}
2419
2421 Status error;
2422 error.SetErrorString("watchpoints are not supported");
2423 return error;
2424}
2425
2427 Status error;
2428 error.SetErrorString("watchpoints are not supported");
2429 return error;
2430}
2431
2434 const Timeout<std::micro> &timeout) {
2435 StateType state;
2436
2437 while (true) {
2438 event_sp.reset();
2439 state = GetStateChangedEventsPrivate(event_sp, timeout);
2440
2441 if (StateIsStoppedState(state, false))
2442 break;
2443
2444 // If state is invalid, then we timed out
2445 if (state == eStateInvalid)
2446 break;
2447
2448 if (event_sp)
2449 HandlePrivateEvent(event_sp);
2450 }
2451 return state;
2452}
2453
2455 std::lock_guard<std::recursive_mutex> guard(m_thread_mutex);
2456 if (flush)
2458 m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr));
2459 if (flush)
2460 Flush();
2461}
2462
2464 StateType state_after_launch = eStateInvalid;
2465 EventSP first_stop_event_sp;
2466 Status status =
2467 LaunchPrivate(launch_info, state_after_launch, first_stop_event_sp);
2468 if (status.Fail())
2469 return status;
2470
2471 if (state_after_launch != eStateStopped &&
2472 state_after_launch != eStateCrashed)
2473 return Status();
2474
2475 // Note, the stop event was consumed above, but not handled. This
2476 // was done to give DidLaunch a chance to run. The target is either
2477 // stopped or crashed. Directly set the state. This is done to
2478 // prevent a stop message with a bunch of spurious output on thread
2479 // status, as well as not pop a ProcessIOHandler.
2480 SetPublicState(state_after_launch, false);
2481
2484 else
2486
2487 // Target was stopped at entry as was intended. Need to notify the
2488 // listeners about it.
2489 if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2490 HandlePrivateEvent(first_stop_event_sp);
2491
2492 return Status();
2493}
2494
2496 EventSP &event_sp) {
2497 Status error;
2498 m_abi_sp.reset();
2499 m_dyld_up.reset();
2500 m_jit_loaders_up.reset();
2501 m_system_runtime_up.reset();
2502 m_os_up.reset();
2503
2504 {
2505 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
2506 m_process_input_reader.reset();
2507 }
2508
2510
2511 // The "remote executable path" is hooked up to the local Executable
2512 // module. But we should be able to debug a remote process even if the
2513 // executable module only exists on the remote. However, there needs to
2514 // be a way to express this path, without actually having a module.
2515 // The way to do that is to set the ExecutableFile in the LaunchInfo.
2516 // Figure that out here:
2517
2518 FileSpec exe_spec_to_use;
2519 if (!exe_module) {
2520 if (!launch_info.GetExecutableFile() && !launch_info.IsScriptedProcess()) {
2521 error.SetErrorString("executable module does not exist");
2522 return error;
2523 }
2524 exe_spec_to_use = launch_info.GetExecutableFile();
2525 } else
2526 exe_spec_to_use = exe_module->GetFileSpec();
2527
2528 if (exe_module && FileSystem::Instance().Exists(exe_module->GetFileSpec())) {
2529 // Install anything that might need to be installed prior to launching.
2530 // For host systems, this will do nothing, but if we are connected to a
2531 // remote platform it will install any needed binaries
2532 error = GetTarget().Install(&launch_info);
2533 if (error.Fail())
2534 return error;
2535 }
2536
2537 // Listen and queue events that are broadcasted during the process launch.
2538 ListenerSP listener_sp(Listener::MakeListener("LaunchEventHijack"));
2539 HijackProcessEvents(listener_sp);
2540 auto on_exit = llvm::make_scope_exit([this]() { RestoreProcessEvents(); });
2541
2544
2545 error = WillLaunch(exe_module);
2546 if (error.Fail()) {
2547 std::string local_exec_file_path = exe_spec_to_use.GetPath();
2548 return Status("file doesn't exist: '%s'", local_exec_file_path.c_str());
2549 }
2550
2551 const bool restarted = false;
2552 SetPublicState(eStateLaunching, restarted);
2553 m_should_detach = false;
2554
2556 // Now launch using these arguments.
2557 error = DoLaunch(exe_module, launch_info);
2558 } else {
2559 // This shouldn't happen
2560 error.SetErrorString("failed to acquire process run lock");
2561 }
2562
2563 if (error.Fail()) {
2564 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2566 const char *error_string = error.AsCString();
2567 if (error_string == nullptr)
2568 error_string = "launch failed";
2569 SetExitStatus(-1, error_string);
2570 }
2571 return error;
2572 }
2573
2574 // Now wait for the process to launch and return control to us, and then
2575 // call DidLaunch:
2576 state = WaitForProcessStopPrivate(event_sp, seconds(10));
2577
2578 if (state == eStateInvalid || !event_sp) {
2579 // We were able to launch the process, but we failed to catch the
2580 // initial stop.
2581 error.SetErrorString("failed to catch stop after launch");
2582 SetExitStatus(0, error.AsCString());
2583 Destroy(false);
2584 return error;
2585 }
2586
2587 if (state == eStateExited) {
2588 // We exited while trying to launch somehow. Don't call DidLaunch
2589 // as that's not likely to work, and return an invalid pid.
2590 HandlePrivateEvent(event_sp);
2591 return Status();
2592 }
2593
2594 if (state == eStateStopped || state == eStateCrashed) {
2595 DidLaunch();
2596
2597 // Now that we know the process type, update its signal responses from the
2598 // ones stored in the Target:
2599 if (m_unix_signals_sp) {
2602 }
2603
2605 if (dyld)
2606 dyld->DidLaunch();
2607
2609
2610 SystemRuntime *system_runtime = GetSystemRuntime();
2611 if (system_runtime)
2612 system_runtime->DidLaunch();
2613
2614 if (!m_os_up)
2616
2617 // We successfully launched the process and stopped, now it the
2618 // right time to set up signal filters before resuming.
2620 return Status();
2621 }
2622
2623 return Status("Unexpected process state after the launch: %s, expected %s, "
2624 "%s, %s or %s",
2628}
2629
2632 if (error.Success()) {
2633 ListenerSP listener_sp(
2634 Listener::MakeListener("lldb.process.load_core_listener"));
2635 HijackProcessEvents(listener_sp);
2636
2639 else
2641
2643 if (dyld)
2644 dyld->DidAttach();
2645
2647
2648 SystemRuntime *system_runtime = GetSystemRuntime();
2649 if (system_runtime)
2650 system_runtime->DidAttach();
2651
2652 if (!m_os_up)
2654
2655 // We successfully loaded a core file, now pretend we stopped so we can
2656 // show all of the threads in the core file and explore the crashed state.
2658
2659 // Wait for a stopped event since we just posted one above...
2660 lldb::EventSP event_sp;
2661 StateType state =
2662 WaitForProcessToStop(std::nullopt, &event_sp, true, listener_sp,
2663 nullptr, true, SelectMostRelevantFrame);
2664
2665 if (!StateIsStoppedState(state, false)) {
2666 Log *log = GetLog(LLDBLog::Process);
2667 LLDB_LOGF(log, "Process::Halt() failed to stop, state is: %s",
2668 StateAsCString(state));
2669 error.SetErrorString(
2670 "Did not get stopped event after loading the core file.");
2671 }
2673 }
2674 return error;
2675}
2676
2678 if (!m_dyld_up)
2679 m_dyld_up.reset(DynamicLoader::FindPlugin(this, ""));
2680 return m_dyld_up.get();
2681}
2682
2684 m_dyld_up = std::move(dyld_up);
2685}
2686
2688
2689llvm::Expected<bool> Process::SaveCore(llvm::StringRef outfile) {
2690 return false;
2691}
2692
2694 if (!m_jit_loaders_up) {
2695 m_jit_loaders_up = std::make_unique<JITLoaderList>();
2697 }
2698 return *m_jit_loaders_up;
2699}
2700
2704 return m_system_runtime_up.get();
2705}
2706
2708 uint32_t exec_count)
2709 : NextEventAction(process), m_exec_count(exec_count) {
2710 Log *log = GetLog(LLDBLog::Process);
2711 LLDB_LOGF(
2712 log,
2713 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2714 __FUNCTION__, static_cast<void *>(process), exec_count);
2715}
2716
2719 Log *log = GetLog(LLDBLog::Process);
2720
2721 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2722 LLDB_LOGF(log,
2723 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2724 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
2725
2726 switch (state) {
2727 case eStateAttaching:
2728 return eEventActionSuccess;
2729
2730 case eStateRunning:
2731 case eStateConnected:
2732 return eEventActionRetry;
2733
2734 case eStateStopped:
2735 case eStateCrashed:
2736 // During attach, prior to sending the eStateStopped event,
2737 // lldb_private::Process subclasses must set the new process ID.
2739 // We don't want these events to be reported, so go set the
2740 // ShouldReportStop here:
2742
2743 if (m_exec_count > 0) {
2744 --m_exec_count;
2745
2746 LLDB_LOGF(log,
2747 "Process::AttachCompletionHandler::%s state %s: reduced "
2748 "remaining exec count to %" PRIu32 ", requesting resume",
2749 __FUNCTION__, StateAsCString(state), m_exec_count);
2750
2751 RequestResume();
2752 return eEventActionRetry;
2753 } else {
2754 LLDB_LOGF(log,
2755 "Process::AttachCompletionHandler::%s state %s: no more "
2756 "execs expected to start, continuing with attach",
2757 __FUNCTION__, StateAsCString(state));
2758
2760 return eEventActionSuccess;
2761 }
2762 break;
2763
2764 default:
2765 case eStateExited:
2766 case eStateInvalid:
2767 break;
2768 }
2769
2770 m_exit_string.assign("No valid Process");
2771 return eEventActionExit;
2772}
2773
2776 return eEventActionSuccess;
2777}
2778
2780 return m_exit_string.c_str();
2781}
2782
2784 if (m_listener_sp)
2785 return m_listener_sp;
2786 else
2787 return debugger.GetListener();
2788}
2789
2791 return DoWillLaunch(module);
2792}
2793
2795 return DoWillAttachToProcessWithID(pid);
2796}
2797
2799 bool wait_for_launch) {
2800 return DoWillAttachToProcessWithName(process_name, wait_for_launch);
2801}
2802
2804 m_abi_sp.reset();
2805 {
2806 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
2807 m_process_input_reader.reset();
2808 }
2809 m_dyld_up.reset();
2810 m_jit_loaders_up.reset();
2811 m_system_runtime_up.reset();
2812 m_os_up.reset();
2813
2814 lldb::pid_t attach_pid = attach_info.GetProcessID();
2815 Status error;
2816 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
2817 char process_name[PATH_MAX];
2818
2819 if (attach_info.GetExecutableFile().GetPath(process_name,
2820 sizeof(process_name))) {
2821 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2822
2823 if (wait_for_launch) {
2824 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2825 if (error.Success()) {
2827 m_should_detach = true;
2828 const bool restarted = false;
2829 SetPublicState(eStateAttaching, restarted);
2830 // Now attach using these arguments.
2831 error = DoAttachToProcessWithName(process_name, attach_info);
2832 } else {
2833 // This shouldn't happen
2834 error.SetErrorString("failed to acquire process run lock");
2835 }
2836
2837 if (error.Fail()) {
2838 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2840 if (error.AsCString() == nullptr)
2841 error.SetErrorString("attach failed");
2842
2843 SetExitStatus(-1, error.AsCString());
2844 }
2845 } else {
2847 this, attach_info.GetResumeCount()));
2849 }
2850 return error;
2851 }
2852 } else {
2853 ProcessInstanceInfoList process_infos;
2854 PlatformSP platform_sp(GetTarget().GetPlatform());
2855
2856 if (platform_sp) {
2857 ProcessInstanceInfoMatch match_info;
2858 match_info.GetProcessInfo() = attach_info;
2860 platform_sp->FindProcesses(match_info, process_infos);
2861 const uint32_t num_matches = process_infos.size();
2862 if (num_matches == 1) {
2863 attach_pid = process_infos[0].GetProcessID();
2864 // Fall through and attach using the above process ID
2865 } else {
2867 process_name, sizeof(process_name));
2868 if (num_matches > 1) {
2869 StreamString s;
2871 for (size_t i = 0; i < num_matches; i++) {
2872 process_infos[i].DumpAsTableRow(
2873 s, platform_sp->GetUserIDResolver(), true, false);
2874 }
2875 error.SetErrorStringWithFormat(
2876 "more than one process named %s:\n%s", process_name,
2877 s.GetData());
2878 } else
2879 error.SetErrorStringWithFormat(
2880 "could not find a process named %s", process_name);
2881 }
2882 } else {
2883 error.SetErrorString(
2884 "invalid platform, can't find processes by name");
2885 return error;
2886 }
2887 }
2888 } else {
2889 error.SetErrorString("invalid process name");
2890 }
2891 }
2892
2893 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
2894 error = WillAttachToProcessWithID(attach_pid);
2895 if (error.Success()) {
2896
2898 // Now attach using these arguments.
2899 m_should_detach = true;
2900 const bool restarted = false;
2901 SetPublicState(eStateAttaching, restarted);
2902 error = DoAttachToProcessWithID(attach_pid, attach_info);
2903 } else {
2904 // This shouldn't happen
2905 error.SetErrorString("failed to acquire process run lock");
2906 }
2907
2908 if (error.Success()) {
2910 this, attach_info.GetResumeCount()));
2912 } else {
2915
2916 const char *error_string = error.AsCString();
2917 if (error_string == nullptr)
2918 error_string = "attach failed";
2919
2920 SetExitStatus(-1, error_string);
2921 }
2922 }
2923 }
2924 return error;
2925}
2926
2929 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
2930
2931 // Let the process subclass figure out at much as it can about the process
2932 // before we go looking for a dynamic loader plug-in.
2933 ArchSpec process_arch;
2934 DidAttach(process_arch);
2935
2936 if (process_arch.IsValid()) {
2937 GetTarget().SetArchitecture(process_arch);
2938 if (log) {
2939 const char *triple_str = process_arch.GetTriple().getTriple().c_str();
2940 LLDB_LOGF(log,
2941 "Process::%s replacing process architecture with DidAttach() "
2942 "architecture: %s",
2943 __FUNCTION__, triple_str ? triple_str : "<null>");
2944 }
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 SetExitStatus(SIGKILL, "Cancelled async attach.");
3169 Destroy(false);
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());
3857 LLDB_LOGF(log,
3858 "Process::%s (arg = %p, pid = %" PRIu64
3859 ") woke up with an interrupt - Halting.",
3860 __FUNCTION__, static_cast<void *>(this), GetID());
3862 if (error.Fail() && log)
3863 LLDB_LOGF(log,
3864 "Process::%s (arg = %p, pid = %" PRIu64
3865 ") failed to halt the process: %s",
3866 __FUNCTION__, static_cast<void *>(this), GetID(),
3867 error.AsCString());
3868 // Halt should generate a stopped event. Make a note of the fact that
3869 // we were doing the interrupt, so we can set the interrupted flag
3870 // after we receive the event. We deliberately set this to true even if
3871 // HaltPrivate failed, so that we can interrupt on the next natural
3872 // stop.
3873 interrupt_requested = true;
3874 } else {
3875 // This can happen when someone (e.g. Process::Halt) sees that we are
3876 // running and sends an interrupt request, but the process actually
3877 // stops before we receive it. In that case, we can just ignore the
3878 // request. We use m_last_broadcast_state, because the Stopped event
3879 // may not have been popped of the event queue yet, which is when the
3880 // public state gets updated.
3881 LLDB_LOGF(log,
3882 "Process::%s ignoring interrupt as we have already stopped.",
3883 __FUNCTION__);
3884 }
3885 continue;
3886 }
3887
3888 const StateType internal_state =
3890
3891 if (internal_state != eStateInvalid) {
3893 StateIsStoppedState(internal_state, true)) {
3896 }
3897
3898 if (interrupt_requested) {
3899 if (StateIsStoppedState(internal_state, true)) {
3900 // We requested the interrupt, so mark this as such in the stop event
3901 // so clients can tell an interrupted process from a natural stop
3902 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
3903 interrupt_requested = false;
3904 } else if (log) {
3905 LLDB_LOGF(log,
3906 "Process::%s interrupt_requested, but a non-stopped "
3907 "state '%s' received.",
3908 __FUNCTION__, StateAsCString(internal_state));
3909 }
3910 }
3911
3912 HandlePrivateEvent(event_sp);
3913 }
3914
3915 if (internal_state == eStateInvalid || internal_state == eStateExited ||
3916 internal_state == eStateDetached) {
3917 LLDB_LOGF(log,
3918 "Process::%s (arg = %p, pid = %" PRIu64
3919 ") about to exit with internal state %s...",
3920 __FUNCTION__, static_cast<void *>(this), GetID(),
3921 StateAsCString(internal_state));
3922
3923 break;
3924 }
3925 }
3926
3927 // Verify log is still enabled before attempting to write to it...
3928 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
3929 __FUNCTION__, static_cast<void *>(this), GetID());
3930
3931 // If we are a secondary thread, then the primary thread we are working for
3932 // will have already acquired the public_run_lock, and isn't done with what
3933 // it was doing yet, so don't try to change it on the way out.
3934 if (!is_secondary_thread)
3936 return {};
3937}
3938
3939// Process Event Data
3940
3942
3944 StateType state)
3945 : EventData(), m_process_wp(), m_state(state) {
3946 if (process_sp)
3947 m_process_wp = process_sp;
3948}
3949
3951
3953 return "Process::ProcessEventData";
3954}
3955
3958}
3959
3961 bool &found_valid_stopinfo) {
3962 found_valid_stopinfo = false;
3963
3964 ProcessSP process_sp(m_process_wp.lock());
3965 if (!process_sp)
3966 return false;
3967
3968 ThreadList &curr_thread_list = process_sp->GetThreadList();
3969 uint32_t num_threads = curr_thread_list.GetSize();
3970 uint32_t idx;
3971
3972 // The actions might change one of the thread's stop_info's opinions about
3973 // whether we should stop the process, so we need to query that as we go.
3974
3975 // One other complication here, is that we try to catch any case where the
3976 // target has run (except for expressions) and immediately exit, but if we
3977 // get that wrong (which is possible) then the thread list might have
3978 // changed, and that would cause our iteration here to crash. We could
3979 // make a copy of the thread list, but we'd really like to also know if it
3980 // has changed at all, so we make up a vector of the thread ID's and check
3981 // what we get back against this list & bag out if anything differs.
3982 ThreadList not_suspended_thread_list(process_sp.get());
3983 std::vector<uint32_t> thread_index_array(num_threads);
3984 uint32_t not_suspended_idx = 0;
3985 for (idx = 0; idx < num_threads; ++idx) {
3986 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3987
3988 /*
3989 Filter out all suspended threads, they could not be the reason
3990 of stop and no need to perform any actions on them.
3991 */
3992 if (thread_sp->GetResumeState() != eStateSuspended) {
3993 not_suspended_thread_list.AddThread(thread_sp);
3994 thread_index_array[not_suspended_idx] = thread_sp->GetIndexID();
3995 not_suspended_idx++;
3996 }
3997 }
3998
3999 // Use this to track whether we should continue from here. We will only
4000 // continue the target running if no thread says we should stop. Of course
4001 // if some thread's PerformAction actually sets the target running, then it
4002 // doesn't matter what the other threads say...
4003
4004 bool still_should_stop = false;
4005
4006 // Sometimes - for instance if we have a bug in the stub we are talking to,
4007 // we stop but no thread has a valid stop reason. In that case we should
4008 // just stop, because we have no way of telling what the right thing to do
4009 // is, and it's better to let the user decide than continue behind their
4010 // backs.
4011
4012 for (idx = 0; idx < not_suspended_thread_list.GetSize(); ++idx) {
4013 curr_thread_list = process_sp->GetThreadList();
4014 if (curr_thread_list.GetSize() != num_threads) {
4016 LLDB_LOGF(
4017 log,
4018 "Number of threads changed from %u to %u while processing event.",
4019 num_threads, curr_thread_list.GetSize());
4020 break;
4021 }
4022
4023 lldb::ThreadSP thread_sp = not_suspended_thread_list.GetThreadAtIndex(idx);
4024
4025 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4027 LLDB_LOGF(log,
4028 "The thread at position %u changed from %u to %u while "
4029 "processing event.",
4030 idx, thread_index_array[idx], thread_sp->GetIndexID());
4031 break;
4032 }
4033
4034 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4035 if (stop_info_sp && stop_info_sp->IsValid()) {
4036 found_valid_stopinfo = true;
4037 bool this_thread_wants_to_stop;
4038 if (stop_info_sp->GetOverrideShouldStop()) {
4039 this_thread_wants_to_stop =
4040 stop_info_sp->GetOverriddenShouldStopValue();
4041 } else {
4042 stop_info_sp->PerformAction(event_ptr);
4043 // The stop action might restart the target. If it does, then we
4044 // want to mark that in the event so that whoever is receiving it
4045 // will know to wait for the running event and reflect that state
4046 // appropriately. We also need to stop processing actions, since they
4047 // aren't expecting the target to be running.
4048
4049 // FIXME: we might have run.
4050 if (stop_info_sp->HasTargetRunSinceMe()) {
4051 SetRestarted(true);
4052 break;
4053 }
4054
4055 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
4056 }
4057
4058 if (!still_should_stop)
4059 still_should_stop = this_thread_wants_to_stop;
4060 }
4061 }
4062
4063 return still_should_stop;
4064}
4065
4067 ProcessSP process_sp(m_process_wp.lock());
4068
4069 if (!process_sp)
4070 return;
4071
4072 // This function gets called twice for each event, once when the event gets
4073 // pulled off of the private process event queue, and then any number of
4074 // times, first when it gets pulled off of the public event queue, then other
4075 // times when we're pretending that this is where we stopped at the end of
4076 // expression evaluation. m_update_state is used to distinguish these three
4077 // cases; it is 0 when we're just pulling it off for private handling, and >
4078 // 1 for expression evaluation, and we don't want to do the breakpoint
4079 // command handling then.
4080 if (m_update_state != 1)
4081 return;
4082
4083 process_sp->SetPublicState(
4085
4086 if (m_state == eStateStopped && !m_restarted) {
4087 // Let process subclasses know we are about to do a public stop and do
4088 // anything they might need to in order to speed up register and memory
4089 // accesses.
4090 process_sp->WillPublicStop();
4091 }
4092
4093 // If this is a halt event, even if the halt stopped with some reason other
4094 // than a plain interrupt (e.g. we had already stopped for a breakpoint when
4095 // the halt request came through) don't do the StopInfo actions, as they may
4096 // end up restarting the process.
4097 if (m_interrupted)
4098 return;
4099
4100 // If we're not stopped or have restarted, then skip the StopInfo actions:
4101 if (m_state != eStateStopped || m_restarted) {
4102 return;
4103 }
4104
4105 bool does_anybody_have_an_opinion = false;
4106 bool still_should_stop = ShouldStop(event_ptr, does_anybody_have_an_opinion);
4107
4108 if (GetRestarted()) {
4109 return;
4110 }
4111
4112 if (!still_should_stop && does_anybody_have_an_opinion) {
4113 // We've been asked to continue, so do that here.
4114 SetRestarted(true);
4115 // Use the private resume method here, since we aren't changing the run
4116 // lock state.
4117 process_sp->PrivateResume();
4118 } else {
4119 bool hijacked = process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) &&
4120 !process_sp->StateChangedIsHijackedForSynchronousResume();
4121
4122 if (!hijacked) {
4123 // If we didn't restart, run the Stop Hooks here.
4124 // Don't do that if state changed events aren't hooked up to the
4125 // public (or SyncResume) broadcasters. StopHooks are just for
4126 // real public stops. They might also restart the target,
4127 // so watch for that.
4128 if (process_sp->GetTarget().RunStopHooks())
4129 SetRestarted(true);
4130 }
4131 }
4132}
4133
4135 ProcessSP process_sp(m_process_wp.lock());
4136
4137 if (process_sp)
4138 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4139 static_cast<void *>(process_sp.get()), process_sp->GetID());
4140 else
4141 s->PutCString(" process = NULL, ");
4142
4143 s->Printf("state = %s", StateAsCString(GetState()));
4144}
4145
4148 if (event_ptr) {
4149 const EventData *event_data = event_ptr->GetData();
4150 if (event_data &&
4152 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4153 }
4154 return nullptr;
4155}
4156
4159 ProcessSP process_sp;
4160 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4161 if (data)
4162 process_sp = data->GetProcessSP();
4163 return process_sp;
4164}
4165
4167 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4168 if (data == nullptr)
4169 return eStateInvalid;
4170 else
4171 return data->GetState();
4172}
4173
4175 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4176 if (data == nullptr)
4177 return false;
4178 else
4179 return data->GetRestarted();
4180}
4181
4183 bool new_value) {
4184 ProcessEventData *data =
4185 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4186 if (data != nullptr)
4187 data->SetRestarted(new_value);
4188}
4189
4190size_t
4192 ProcessEventData *data =
4193 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4194 if (data != nullptr)
4195 return data->GetNumRestartedReasons();
4196 else
4197 return 0;
4198}
4199
4200const char *
4202 size_t idx) {
4203 ProcessEventData *data =
4204 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4205 if (data != nullptr)
4206 return data->GetRestartedReasonAtIndex(idx);
4207 else
4208 return nullptr;
4209}
4210
4212 const char *reason) {
4213 ProcessEventData *data =
4214 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4215 if (data != nullptr)
4216 data->AddRestartedReason(reason);
4217}
4218
4220 const Event *event_ptr) {
4221 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4222 if (data == nullptr)
4223 return false;
4224 else
4225 return data->GetInterrupted();
4226}
4227
4229 bool new_value) {
4230 ProcessEventData *data =
4231 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4232 if (data != nullptr)
4233 data->SetInterrupted(new_value);
4234}
4235
4237 ProcessEventData *data =
4238 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4239 if (data) {
4241 return true;
4242 }
4243 return false;
4244}
4245
4247
4249 exe_ctx.SetTargetPtr(&GetTarget());
4250 exe_ctx.SetProcessPtr(this);
4251 exe_ctx.SetThreadPtr(nullptr);
4252 exe_ctx.SetFramePtr(nullptr);
4253}
4254
4255// uint32_t
4256// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4257// std::vector<lldb::pid_t> &pids)
4258//{
4259// return 0;
4260//}
4261//
4262// ArchSpec
4263// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4264//{
4265// return Host::GetArchSpecForExistingProcess (pid);
4266//}
4267//
4268// ArchSpec
4269// Process::GetArchSpecForExistingProcess (const char *process_name)
4270//{
4271// return Host::GetArchSpecForExistingProcess (process_name);
4272//}
4273
4274void Process::AppendSTDOUT(const char *s, size_t len) {
4275 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4276 m_stdout_data.append(s, len);
4278 new ProcessEventData(shared_from_this(), GetState()));
4279}
4280
4281void Process::AppendSTDERR(const char *s, size_t len) {
4282 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4283 m_stderr_data.append(s, len);
4285 new ProcessEventData(shared_from_this(), GetState()));
4286}
4287
4288void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4289 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4290 m_profile_data.push_back(one_profile_data);
4292 new ProcessEventData(shared_from_this(), GetState()));
4293}
4294
4296 const StructuredDataPluginSP &plugin_sp) {
4299 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
4300}
4301
4303Process::GetStructuredDataPlugin(llvm::StringRef type_name) const {
4304 auto find_it = m_structured_data_plugin_map.find(type_name);
4305 if (find_it != m_structured_data_plugin_map.end())
4306 return find_it->second;
4307 else
4308 return StructuredDataPluginSP();
4309}
4310
4311size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
4312 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4313 if (m_profile_data.empty())
4314 return 0;
4315
4316 std::string &one_profile_data = m_profile_data.front();
4317 size_t bytes_available = one_profile_data.size();
4318 if (bytes_available > 0) {
4319 Log *log = GetLog(LLDBLog::Process);
4320 LLDB_LOGF(log, "Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4321 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4322 if (bytes_available > buf_size) {
4323 memcpy(buf, one_profile_data.c_str(), buf_size);
4324 one_profile_data.erase(0, buf_size);
4325 bytes_available = buf_size;
4326 } else {
4327 memcpy(buf, one_profile_data.c_str(), bytes_available);
4328 m_profile_data.erase(m_profile_data.begin());
4329 }
4330 }
4331 return bytes_available;
4332}
4333
4334// Process STDIO
4335
4336size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
4337 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4338 size_t bytes_available = m_stdout_data.size();
4339 if (bytes_available > 0) {
4340 Log *log = GetLog(LLDBLog::Process);
4341 LLDB_LOGF(log, "Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4342 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4343 if (bytes_available > buf_size) {
4344 memcpy(buf, m_stdout_data.c_str(), buf_size);
4345 m_stdout_data.erase(0, buf_size);
4346 bytes_available = buf_size;
4347 } else {
4348 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4349 m_stdout_data.clear();
4350 }
4351 }
4352 return bytes_available;
4353}
4354
4355size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
4356 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4357 size_t bytes_available = m_stderr_data.size();
4358 if (bytes_available > 0) {
4359 Log *log = GetLog(LLDBLog::Process);
4360 LLDB_LOGF(log, "Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4361 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4362 if (bytes_available > buf_size) {
4363 memcpy(buf, m_stderr_data.c_str(), buf_size);
4364 m_stderr_data.erase(0, buf_size);
4365 bytes_available = buf_size;
4366 } else {
4367 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4368 m_stderr_data.clear();
4369 }
4370 }
4371 return bytes_available;
4372}
4373
4374void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4375 size_t src_len) {
4376 Process *process = (Process *)baton;
4377 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
4378}
4379
4381public:
4382 IOHandlerProcessSTDIO(Process *process, int write_fd)
4383 : IOHandler(process->GetTarget().GetDebugger(),
4384 IOHandler::Type::ProcessIO),
4385 m_process(process),
4386 m_read_file(GetInputFD(), File::eOpenOptionReadOnly, false),
4387 m_write_file(write_fd, File::eOpenOptionWriteOnly, false) {
4388 m_pipe.CreateNew(false);
4389 }
4390
4391 ~IOHandlerProcessSTDIO() override = default;
4392
4393 void SetIsRunning(bool running) {
4394 std::lock_guard<std::mutex> guard(m_mutex);
4395 SetIsDone(!running);
4396 m_is_running = running;
4397 }
4398
4399 // Each IOHandler gets to run until it is done. It should read data from the
4400 // "in" and place output into "out" and "err and return when done.
4401 void Run() override {
4402 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4403 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4404 SetIsDone(true);
4405 return;
4406 }
4407
4408 SetIsDone(false);
4409 const int read_fd = m_read_file.GetDescriptor();
4410 Terminal terminal(read_fd);
4411 TerminalState terminal_state(terminal, false);
4412 // FIXME: error handling?
4413 llvm::consumeError(terminal.SetCanonical(false));
4414 llvm::consumeError(terminal.SetEcho(false));
4415// FD_ZERO, FD_SET are not supported on windows
4416#ifndef _WIN32
4417 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4418 SetIsRunning(true);
4419 while (true) {
4420 {
4421 std::lock_guard<std::mutex> guard(m_mutex);
4422 if (GetIsDone())
4423 break;
4424 }
4425
4426 SelectHelper select_helper;
4427 select_helper.FDSetRead(read_fd);
4428 select_helper.FDSetRead(pipe_read_fd);
4429 Status error = select_helper.Select();
4430
4431 if (error.Fail())
4432 break;
4433
4434 char ch = 0;
4435 size_t n;
4436 if (select_helper.FDIsSetRead(read_fd)) {
4437 n = 1;
4438 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4439 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4440 break;
4441 } else
4442 break;
4443 }
4444
4445 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4446 size_t bytes_read;
4447 // Consume the interrupt byte
4448 Status error = m_pipe.Read(&ch, 1, bytes_read);
4449 if (error.Success()) {
4450 if (ch == 'q')
4451 break;
4452 if (ch == 'i')
4453 if (StateIsRunningState(m_process->GetState()))
4454 m_process->SendAsyncInterrupt();
4455 }
4456 }
4457 }
4458 SetIsRunning(false);
4459#endif
4460 }
4461
4462 void Cancel() override {
4463 std::lock_guard<std::mutex> guard(m_mutex);
4464 SetIsDone(true);
4465 // Only write to our pipe to cancel if we are in
4466 // IOHandlerProcessSTDIO::Run(). We can end up with a python command that
4467 // is being run from the command interpreter:
4468 //
4469 // (lldb) step_process_thousands_of_times
4470 //
4471 // In this case the command interpreter will be in the middle of handling
4472 // the command and if the process pushes and pops the IOHandler thousands
4473 // of times, we can end up writing to m_pipe without ever consuming the
4474 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4475 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4476 if (m_is_running) {
4477 char ch = 'q'; // Send 'q' for quit
4478 size_t bytes_written = 0;
4479 m_pipe.Write(&ch, 1, bytes_written);
4480 }
4481 }
4482
4483 bool Interrupt() override {
4484 // Do only things that are safe to do in an interrupt context (like in a
4485 // SIGINT handler), like write 1 byte to a file descriptor. This will
4486 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4487 // that was written to the pipe and then call
4488 // m_process->SendAsyncInterrupt() from a much safer location in code.
4489 if (m_active) {
4490 char ch = 'i'; // Send 'i' for interrupt
4491 size_t bytes_written = 0;
4492 Status result = m_pipe.Write(&ch, 1, bytes_written);
4493 return result.Success();
4494 } else {
4495 // This IOHandler might be pushed on the stack, but not being run
4496 // currently so do the right thing if we aren't actively watching for
4497 // STDIN by sending the interrupt to the process. Otherwise the write to
4498 // the pipe above would do nothing. This can happen when the command
4499 // interpreter is running and gets a "expression ...". It will be on the
4500 // IOHandler thread and sending the input is complete to the delegate
4501 // which will cause the expression to run, which will push the process IO
4502 // handler, but not run it.
4503
4504 if (StateIsRunningState(m_process->GetState())) {
4505 m_process->SendAsyncInterrupt();
4506 return true;
4507 }
4508 }
4509 return false;
4510 }
4511
4512 void GotEOF() override {}
4513
4514protected:
4516 NativeFile m_read_file; // Read from this file (usually actual STDIN for LLDB
4517 NativeFile m_write_file; // Write to this file (usually the primary pty for
4518 // getting io to debuggee)
4520 std::mutex m_mutex;
4521 bool m_is_running = false;
4522};
4523
4525 // First set up the Read Thread for reading/handling process I/O
4527 std::make_unique<ConnectionFileDescriptor>(fd, true));
4532
4533 // Now read thread is set up, set up input reader.
4534 {
4535 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
4538 std::make_shared<IOHandlerProcessSTDIO>(this, fd);
4539 }
4540 }
4541}
4542
4544 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
4545 IOHandlerSP io_handler_sp(m_process_input_reader);
4546 if (io_handler_sp)
4547 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4548 return false;
4549}
4550
4552 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
4553 IOHandlerSP io_handler_sp(m_process_input_reader);
4554 if (io_handler_sp) {
4555 Log *log = GetLog(LLDBLog::Process);
4556 LLDB_LOGF(log, "Process::%s pushing IO handler", __FUNCTION__);
4557
4558 io_handler_sp->SetIsDone(false);
4559 // If we evaluate an utility function, then we don't cancel the current
4560 // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
4561 // existing IOHandler that potentially provides the user interface (e.g.
4562 // the IOHandler for Editline).
4563 bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();
4564 GetTarget().GetDebugger().RunIOHandlerAsync(io_handler_sp,
4565 cancel_top_handler);
4566 return true;
4567 }
4568 return false;
4569}
4570
4572 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
4573 IOHandlerSP io_handler_sp(m_process_input_reader);
4574 if (io_handler_sp)
4575 return GetTarget().GetDebugger().RemoveIOHandler(io_handler_sp);
4576 return false;
4577}
4578
4579// The process needs to know about installed plug-ins
4581
4583
4584namespace {
4585// RestorePlanState is used to record the "is private", "is controlling" and
4586// "okay
4587// to discard" fields of the plan we are running, and reset it on Clean or on
4588// destruction. It will only reset the state once, so you can call Clean and
4589// then monkey with the state and it won't get reset on you again.
4590
4591class RestorePlanState {
4592public:
4593 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4594 : m_thread_plan_sp(thread_plan_sp) {
4595 if (m_thread_plan_sp) {
4596 m_private = m_thread_plan_sp->GetPrivate();
4597 m_is_controlling = m_thread_plan_sp->IsControllingPlan();
4598 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4599 }
4600 }
4601
4602 ~RestorePlanState() { Clean(); }
4603
4604 void Clean() {
4605 if (!m_already_reset && m_thread_plan_sp) {
4606 m_already_reset = true;
4607 m_thread_plan_sp->SetPrivate(m_private);
4608 m_thread_plan_sp->SetIsControllingPlan(m_is_controlling);
4609 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4610 }
4611 }
4612
4613private:
4614 lldb::ThreadPlanSP m_thread_plan_sp;
4615 bool m_already_reset = false;
4616 bool m_private = false;
4617 bool m_is_controlling = false;
4618 bool m_okay_to_discard = false;
4619};
4620} // anonymous namespace
4621
4622static microseconds
4624 const milliseconds default_one_thread_timeout(250);
4625
4626 // If the overall wait is forever, then we don't need to worry about it.
4627 if (!options.GetTimeout()) {
4628 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4629 : default_one_thread_timeout;
4630 }
4631
4632 // If the one thread timeout is set, use it.
4633 if (options.GetOneThreadTimeout())
4634 return *options.GetOneThreadTimeout();
4635
4636 // Otherwise use half the total timeout, bounded by the
4637 // default_one_thread_timeout.
4638 return std::min<microseconds>(default_one_thread_timeout,
4639 *options.GetTimeout() / 2);
4640}
4641
4644 bool before_first_timeout) {
4645 // If we are going to run all threads the whole time, or if we are only going
4646 // to run one thread, we can just return the overall timeout.
4647 if (!options.GetStopOthers() || !options.GetTryAllThreads())
4648 return options.GetTimeout();
4649
4650 if (before_first_timeout)
4651 return GetOneThreadExpressionTimeout(options);
4652
4653 if (!options.GetTimeout())
4654 return std::nullopt;
4655 else
4656 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
4657}
4658
4659static std::optional<ExpressionResults>
4660HandleStoppedEvent(lldb::tid_t thread_id, const ThreadPlanSP &thread_plan_sp,
4661 RestorePlanState &restorer, const EventSP &event_sp,
4662 EventSP &event_to_broadcast_sp,
4663 const EvaluateExpressionOptions &options,
4664 bool handle_interrupts) {
4666
4667 ThreadSP thread_sp = thread_plan_sp->GetTarget()
4668 .GetProcessSP()
4669 ->GetThreadList()
4670 .FindThreadByID(thread_id);
4671 if (!thread_sp) {
4672 LLDB_LOG(log,
4673 "The thread on which we were running the "
4674 "expression: tid = {0}, exited while "
4675 "the expression was running.",
4676 thread_id);
4678 }
4679
4680 ThreadPlanSP plan = thread_sp->GetCompletedPlan();
4681 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
4682 LLDB_LOG(log, "execution completed successfully");
4683
4684 // Restore the plan state so it will get reported as intended when we are
4685 // done.
4686 restorer.Clean();
4687 return eExpressionCompleted;
4688 }
4689
4690 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4691 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
4692 stop_info_sp->ShouldNotify(event_sp.get())) {
4693 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
4694 if (!options.DoesIgnoreBreakpoints()) {
4695 // Restore the plan state and then force Private to false. We are going
4696 // to stop because of this plan so we need it to become a public plan or
4697 // it won't report correctly when we continue to its termination later
4698 // on.
4699 restorer.Clean();
4700 thread_plan_sp->SetPrivate(false);
4701 event_to_broadcast_sp = event_sp;
4702 }
4704 }
4705
4706 if (!handle_interrupts &&
4708 return std::nullopt;
4709
4710 LLDB_LOG(log, "thread plan did not successfully complete");
4711 if (!options.DoesUnwindOnError())
4712 event_to_broadcast_sp = event_sp;
4714}
4715
4718 lldb::ThreadPlanSP &thread_plan_sp,
4719 const EvaluateExpressionOptions &options,
4720 DiagnosticManager &diagnostic_manager) {
4722
4723 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4724
4725 if (!thread_plan_sp) {
4726 diagnostic_manager.PutString(
4728 "RunThreadPlan called with empty thread plan.");
4729 return eExpressionSetupError;
4730 }
4731
4732 if (!thread_plan_sp->ValidatePlan(nullptr)) {
4733 diagnostic_manager.PutString(
4735 "RunThreadPlan called with an invalid thread plan.");
4736 return eExpressionSetupError;
4737 }
4738
4739 if (exe_ctx.GetProcessPtr() != this) {
4740 diagnostic_manager.PutString(eDiagnosticSeverityError,
4741 "RunThreadPlan called on wrong process.");
4742 return eExpressionSetupError;
4743 }
4744
4745 Thread *thread = exe_ctx.GetThreadPtr();
4746 if (thread == nullptr) {
4747 diagnostic_manager.PutString(eDiagnosticSeverityError,
4748 "RunThreadPlan called with invalid thread.");
4749 return eExpressionSetupError;
4750 }
4751
4752 // Record the thread's id so we can tell when a thread we were using
4753 // to run the expression exits during the expression evaluation.
4754 lldb::tid_t expr_thread_id = thread->GetID();
4755
4756 // We need to change some of the thread plan attributes for the thread plan
4757 // runner. This will restore them when we are done:
4758
4759 RestorePlanState thread_plan_restorer(thread_plan_sp);
4760
4761 // We rely on the thread plan we are running returning "PlanCompleted" if
4762 // when it successfully completes. For that to be true the plan can't be
4763 // private - since private plans suppress themselves in the GetCompletedPlan
4764 // call.
4765
4766 thread_plan_sp->SetPrivate(false);
4767
4768 // The plans run with RunThreadPlan also need to be terminal controlling plans
4769 // or when they are done we will end up asking the plan above us whether we
4770 // should stop, which may give the wrong answer.
4771
4772 thread_plan_sp->SetIsControllingPlan(true);
4773 thread_plan_sp->SetOkayToDiscard(false);
4774
4775 // If we are running some utility expression for LLDB, we now have to mark
4776 // this in the ProcesModID of this process. This RAII takes care of marking
4777 // and reverting the mark it once we are done running the expression.
4778 UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);
4779
4781 diagnostic_manager.PutString(
4783 "RunThreadPlan called while the private state was not stopped.");
4784 return eExpressionSetupError;
4785 }
4786
4787 // Save the thread & frame from the exe_ctx for restoration after we run
4788 const uint32_t thread_idx_id = thread->GetIndexID();
4789 StackFrameSP selected_frame_sp =
4791 if (!selected_frame_sp) {
4792 thread->SetSelectedFrame(nullptr);
4793 selected_frame_sp = thread->GetSelectedFrame(DoNoSelectMostRelevantFrame);
4794 if (!selected_frame_sp) {
4795 diagnostic_manager.Printf(
4797 "RunThreadPlan called without a selected frame on thread %d",
4798 thread_idx_id);
4799 return eExpressionSetupError;
4800 }
4801 }
4802
4803 // Make sure the timeout values make sense. The one thread timeout needs to
4804 // be smaller than the overall timeout.
4805 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4806 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
4807 diagnostic_manager.PutString(eDiagnosticSeverityError,
4808 "RunThreadPlan called with one thread "
4809 "timeout greater than total timeout");
4810 return eExpressionSetupError;
4811 }
4812
4813 StackID ctx_frame_id = selected_frame_sp->GetStackID();
4814
4815 // N.B. Running the target may unset the currently selected thread and frame.
4816 // We don't want to do that either, so we should arrange to reset them as
4817 // well.
4818
4819 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
4820
4821 uint32_t selected_tid;
4822 StackID selected_stack_id;
4823 if (selected_thread_sp) {
4824 selected_tid = selected_thread_sp->GetIndexID();
4825 selected_stack_id =
4826 selected_thread_sp->GetSelectedFrame(DoNoSelectMostRelevantFrame)
4827 ->GetStackID();
4828 } else {
4829 selected_tid = LLDB_INVALID_THREAD_ID;
4830 }
4831
4832 HostThread backup_private_state_thread;
4833 lldb::StateType old_state = eStateInvalid;
4834 lldb::ThreadPlanSP stopper_base_plan_sp;
4835
4838 // Yikes, we are running on the private state thread! So we can't wait for
4839 // public events on this thread, since we are the thread that is generating
4840 // public events. The simplest thing to do is to spin up a temporary thread
4841 // to handle private state thread events while we are fielding public
4842 // events here.
4843 LLDB_LOGF(log, "Running thread plan on private state thread, spinning up "
4844 "another state thread to handle the events.");
4845
4846 backup_private_state_thread = m_private_state_thread;
4847
4848 // One other bit of business: we want to run just this thread plan and
4849 // anything it pushes, and then stop, returning control here. But in the
4850 // normal course of things, the plan above us on the stack would be given a
4851 // shot at the stop event before deciding to stop, and we don't want that.
4852 // So we insert a "stopper" base plan on the stack before the plan we want
4853 // to run. Since base plans always stop and return control to the user,
4854 // that will do just what we want.
4855 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4856 thread->QueueThreadPlan(stopper_base_plan_sp, false);
4857 // Have to make sure our public state is stopped, since otherwise the
4858 // reporting logic below doesn't work correctly.
4859 old_state = m_public_state.GetValue();
4861
4862 // Now spin up the private state thread:
4864 }
4865
4866 thread->QueueThreadPlan(
4867 thread_plan_sp, false); // This used to pass "true" does that make sense?
4868
4869 if (options.GetDebug()) {
4870 // In this case, we aren't actually going to run, we just want to stop
4871 // right away. Flush this thread so we will refetch the stacks and show the
4872 // correct backtrace.
4873 // FIXME: To make this prettier we should invent some stop reason for this,
4874 // but that
4875 // is only cosmetic, and this functionality is only of use to lldb
4876 // developers who can live with not pretty...
4877 thread->Flush();
4879 }
4880
4881 ListenerSP listener_sp(
4882 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4883
4884 lldb::EventSP event_to_broadcast_sp;
4885
4886 {
4887 // This process event hijacker Hijacks the Public events and its destructor
4888 // makes sure that the process events get restored on exit to the function.
4889 //
4890 // If the event needs to propagate beyond the hijacker (e.g., the process
4891 // exits during execution), then the event is put into
4892 // event_to_broadcast_sp for rebroadcasting.
4893
4894 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
4895
4896 if (log) {
4897 StreamString s;
4898 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4899 LLDB_LOGF(log,
4900 "Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
4901 " to run thread plan \"%s\".",
4902 thread_idx_id, expr_thread_id, s.GetData());
4903 }
4904
4905 bool got_event;
4906 lldb::EventSP event_sp;
4908
4909 bool before_first_timeout = true; // This is set to false the first time
4910 // that we have to halt the target.
4911 bool do_resume = true;
4912 bool handle_running_event = true;
4913
4914 // This is just for accounting:
4915 uint32_t num_resumes = 0;
4916
4917 // If we are going to run all threads the whole time, or if we are only
4918 // going to run one thread, then we don't need the first timeout. So we
4919 // pretend we are after the first timeout already.
4920 if (!options.GetStopOthers() || !options.GetTryAllThreads())
4921 before_first_timeout = false;
4922
4923 LLDB_LOGF(log, "Stop others: %u, try all: %u, before_first: %u.\n",
4924 options.GetStopOthers(), options.GetTryAllThreads(),
4925 before_first_timeout);
4926
4927 // This isn't going to work if there are unfetched events on the queue. Are
4928 // there cases where we might want to run the remaining events here, and
4929 // then try to call the function? That's probably being too tricky for our
4930 // own good.
4931
4932 Event *other_events = listener_sp->PeekAtNextEvent();
4933 if (other_events != nullptr) {
4934 diagnostic_manager.PutString(
4936 "RunThreadPlan called with pending events on the queue.");
4937 return eExpressionSetupError;
4938 }
4939
4940 // We also need to make sure that the next event is delivered. We might be
4941 // calling a function as part of a thread plan, in which case the last
4942 // delivered event could be the running event, and we don't want event
4943 // coalescing to cause us to lose OUR running event...
4945
4946// This while loop must exit out the bottom, there's cleanup that we need to do
4947// when we are done. So don't call return anywhere within it.
4948
4949#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
4950 // It's pretty much impossible to write test cases for things like: One
4951 // thread timeout expires, I go to halt, but the process already stopped on
4952 // the function call stop breakpoint. Turning on this define will make us
4953 // not fetch the first event till after the halt. So if you run a quick
4954 // function, it will have completed, and the completion event will be
4955 // waiting, when you interrupt for halt. The expression evaluation should
4956 // still succeed.
4957 bool miss_first_event = true;
4958#endif
4959 while (true) {
4960 // We usually want to resume the process if we get to the top of the
4961 // loop. The only exception is if we get two running events with no
4962 // intervening stop, which can happen, we will just wait for then next
4963 // stop event.
4964 LLDB_LOGF(log,
4965 "Top of while loop: do_resume: %i handle_running_event: %i "
4966 "before_first_timeout: %i.",
4967 do_resume, handle_running_event, before_first_timeout);
4968
4969 if (do_resume || handle_running_event) {
4970 // Do the initial resume and wait for the running event before going
4971 // further.
4972
4973 if (do_resume) {
4974 num_resumes++;
4975 Status resume_error = PrivateResume();
4976 if (!resume_error.Success()) {
4977 diagnostic_manager.Printf(
4979 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
4980 resume_error.AsCString());
4981 return_value = eExpressionSetupError;
4982 break;
4983 }
4984 }
4985
4986 got_event =
4987 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
4988 if (!got_event) {
4989 LLDB_LOGF(log,
4990 "Process::RunThreadPlan(): didn't get any event after "
4