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