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

source code of lldb/source/Target/Process.cpp