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