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