blob: d74aaf1e4e70c59cae16723724a1223a9bbc7167 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chris Lattner30fdc8d2010-06-08 16:52:24 +00006//
7//===----------------------------------------------------------------------===//
8
Greg Clayton5cc45e02016-02-26 19:41:49 +00009#include <atomic>
Jonas Devlieghere796ac802019-02-11 23:13:08 +000010#include <memory>
Greg Clayton04df8ee2016-02-26 19:38:18 +000011#include <mutex>
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +000012
Pavel Labath2ce22162016-12-01 10:57:30 +000013#include "llvm/Support/ScopedPrinter.h"
Zachary Turner777de772017-03-04 16:42:25 +000014#include "llvm/Support/Threading.h"
15
Sean Callanan579e70c2016-03-19 00:03:59 +000016#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000017#include "lldb/Breakpoint/BreakpointLocation.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000018#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000019#include "lldb/Core/Debugger.h"
Greg Clayton1f746072012-08-29 21:13:06 +000020#include "lldb/Core/Module.h"
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000021#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022#include "lldb/Core/PluginManager.h"
Greg Clayton44d93782014-01-27 23:43:24 +000023#include "lldb/Core/StreamFile.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000024#include "lldb/Expression/DiagnosticManager.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000025#include "lldb/Expression/IRDynamicChecks.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000026#include "lldb/Expression/UserExpression.h"
Jim Ingham1ecb34f2018-04-17 20:44:47 +000027#include "lldb/Expression/UtilityFunction.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000028#include "lldb/Host/ConnectionFileDescriptor.h"
Zachary Turner4eff2d32015-10-14 21:37:36 +000029#include "lldb/Host/FileSystem.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000030#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000031#include "lldb/Host/HostInfo.h"
Zachary Turner3eb2b442017-03-22 23:33:16 +000032#include "lldb/Host/OptionParser.h"
Greg Clayton100eb932014-07-02 21:10:39 +000033#include "lldb/Host/Pipe.h"
Greg Clayton44d93782014-01-27 23:43:24 +000034#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000035#include "lldb/Host/ThreadLauncher.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000036#include "lldb/Interpreter/CommandInterpreter.h"
Pavel Labath47cbf4a2018-04-10 09:03:59 +000037#include "lldb/Interpreter/OptionArgParser.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000038#include "lldb/Interpreter/OptionValueProperties.h"
Jason Molenda484900b2015-08-10 07:55:25 +000039#include "lldb/Symbol/Function.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000040#include "lldb/Symbol/Symbol.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000041#include "lldb/Target/ABI.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000042#include "lldb/Target/CPPLanguageRuntime.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000043#include "lldb/Target/DynamicLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000044#include "lldb/Target/InstrumentationRuntime.h"
Andrew MacPherson17220c12014-03-05 10:12:43 +000045#include "lldb/Target/JITLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000046#include "lldb/Target/JITLoaderList.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000047#include "lldb/Target/LanguageRuntime.h"
Kuba Breckaa51ea382014-09-06 01:33:13 +000048#include "lldb/Target/MemoryHistory.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000049#include "lldb/Target/MemoryRegionInfo.h"
Jim Ingham22777012010-09-23 02:01:19 +000050#include "lldb/Target/ObjCLanguageRuntime.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000051#include "lldb/Target/OperatingSystem.h"
Greg Claytone996fd32011-03-08 22:40:15 +000052#include "lldb/Target/Platform.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000053#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000054#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000055#include "lldb/Target/StopInfo.h"
Todd Fiala75930012016-08-19 04:21:48 +000056#include "lldb/Target/StructuredDataPlugin.h"
Jason Molendaeef51062013-11-05 03:57:19 +000057#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000058#include "lldb/Target/Target.h"
59#include "lldb/Target/TargetList.h"
60#include "lldb/Target/Thread.h"
61#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000062#include "lldb/Target/ThreadPlanBase.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000063#include "lldb/Target/UnixSignals.h"
Pavel Labath181b8232018-12-14 15:59:49 +000064#include "lldb/Utility/Event.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000065#include "lldb/Utility/Log.h"
Zachary Turner50232572015-03-18 21:31:45 +000066#include "lldb/Utility/NameMatches.h"
Zachary Turner805e7102019-03-04 21:51:03 +000067#include "lldb/Utility/ProcessInfo.h"
Greg Claytonee1f5782016-08-10 22:43:48 +000068#include "lldb/Utility/SelectHelper.h"
Pavel Labathd821c992018-08-07 11:07:21 +000069#include "lldb/Utility/State.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000070
71using namespace lldb;
72using namespace lldb_private;
Pavel Labathe3e21cf2016-11-30 11:56:32 +000073using namespace std::chrono;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000074
Kate Stoneb9c1b512016-09-06 20:57:50 +000075// Comment out line below to disable memory caching, overriding the process
Pavel Labath43d35412016-12-06 11:24:51 +000076// setting target.process.disable-memory-cache
Greg Clayton67cc0632012-08-22 17:17:09 +000077#define ENABLE_MEMORY_CACHING
78
79#ifdef ENABLE_MEMORY_CACHING
80#define DISABLE_MEM_CACHE_DEFAULT false
81#else
82#define DISABLE_MEM_CACHE_DEFAULT true
83#endif
84
Kate Stoneb9c1b512016-09-06 20:57:50 +000085class ProcessOptionValueProperties : public OptionValueProperties {
Greg Clayton67cc0632012-08-22 17:17:09 +000086public:
Kate Stoneb9c1b512016-09-06 20:57:50 +000087 ProcessOptionValueProperties(const ConstString &name)
88 : OptionValueProperties(name) {}
89
Adrian Prantl05097242018-04-30 16:49:04 +000090 // This constructor is used when creating ProcessOptionValueProperties when
91 // it is part of a new lldb_private::Process instance. It will copy all
92 // current global property values as needed
Kate Stoneb9c1b512016-09-06 20:57:50 +000093 ProcessOptionValueProperties(ProcessProperties *global_properties)
94 : OptionValueProperties(*global_properties->GetValueProperties()) {}
95
96 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
97 bool will_modify,
98 uint32_t idx) const override {
Adrian Prantl05097242018-04-30 16:49:04 +000099 // When getting the value for a key from the process options, we will
100 // always try and grab the setting from the current process if there is
101 // one. Else we just use the one from this instance.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000102 if (exe_ctx) {
103 Process *process = exe_ctx->GetProcessPtr();
104 if (process) {
105 ProcessOptionValueProperties *instance_properties =
106 static_cast<ProcessOptionValueProperties *>(
107 process->GetValueProperties().get());
108 if (this != instance_properties)
109 return instance_properties->ProtectedGetPropertyAtIndex(idx);
110 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000111 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000112 return ProtectedGetPropertyAtIndex(idx);
113 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000114};
115
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000116static constexpr PropertyDefinition g_properties[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000117 {"disable-memory-cache", OptionValue::eTypeBoolean, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000118 DISABLE_MEM_CACHE_DEFAULT, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000119 "Disable reading and caching of memory in fixed-size units."},
120 {"extra-startup-command", OptionValue::eTypeArray, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000121 OptionValue::eTypeString, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000122 "A list containing extra commands understood by the particular process "
123 "plugin used. "
124 "For instance, to turn on debugserver logging set this to "
125 "\"QSetLogging:bitmask=LOG_DEFAULT;\""},
126 {"ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000127 nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000128 "If true, breakpoints will be ignored during expression evaluation."},
129 {"unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000130 nullptr, {}, "If true, errors in expression evaluation will unwind "
131 "the stack back to the state before the call."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000132 {"python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000133 {}, "A path to a python OS plug-in module file that contains a "
134 "OperatingSystemPlugIn class."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000135 {"stop-on-sharedlibrary-events", OptionValue::eTypeBoolean, true, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000136 nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000137 "If true, stop when a shared library is loaded or unloaded."},
138 {"detach-keeps-stopped", OptionValue::eTypeBoolean, true, false, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000139 {}, "If true, detach will attempt to keep the process stopped."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000140 {"memory-cache-line-size", OptionValue::eTypeUInt64, false, 512, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000141 {}, "The memory cache line size"},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000142 {"optimization-warnings", OptionValue::eTypeBoolean, false, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000143 {}, "If true, warn when stopped in code that is optimized where "
144 "stepping and variable availability may not behave as expected."},
Jim Inghamba205c12017-12-05 02:50:45 +0000145 {"stop-on-exec", OptionValue::eTypeBoolean, true, true,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000146 nullptr, {},
Tatyana Krasnukhae40db052018-09-27 07:11:58 +0000147 "If true, stop when a shared library is loaded or unloaded."}};
Greg Clayton67cc0632012-08-22 17:17:09 +0000148
149enum {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000150 ePropertyDisableMemCache,
151 ePropertyExtraStartCommand,
152 ePropertyIgnoreBreakpointsInExpressions,
153 ePropertyUnwindOnErrorInExpressions,
154 ePropertyPythonOSPluginPath,
155 ePropertyStopOnSharedLibraryEvents,
156 ePropertyDetachKeepsStopped,
157 ePropertyMemCacheLineSize,
Jim Inghamba205c12017-12-05 02:50:45 +0000158 ePropertyWarningOptimization,
159 ePropertyStopOnExec
Greg Clayton67cc0632012-08-22 17:17:09 +0000160};
161
Kate Stoneb9c1b512016-09-06 20:57:50 +0000162ProcessProperties::ProcessProperties(lldb_private::Process *process)
163 : Properties(),
164 m_process(process) // Can be nullptr for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000165{
Kate Stoneb9c1b512016-09-06 20:57:50 +0000166 if (process == nullptr) {
167 // Global process properties, set them up one time
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000168 m_collection_sp =
169 std::make_shared<ProcessOptionValueProperties>(ConstString("process"));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000170 m_collection_sp->Initialize(g_properties);
171 m_collection_sp->AppendProperty(
172 ConstString("thread"), ConstString("Settings specific to threads."),
173 true, Thread::GetGlobalProperties()->GetValueProperties());
174 } else {
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000175 m_collection_sp = std::make_shared<ProcessOptionValueProperties>(
176 Process::GetGlobalProperties().get());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000177 m_collection_sp->SetValueChangedCallback(
178 ePropertyPythonOSPluginPath,
179 ProcessProperties::OptionValueChangedCallback, this);
180 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000181}
182
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000183ProcessProperties::~ProcessProperties() = default;
Greg Clayton67cc0632012-08-22 17:17:09 +0000184
Kate Stoneb9c1b512016-09-06 20:57:50 +0000185void ProcessProperties::OptionValueChangedCallback(void *baton,
186 OptionValue *option_value) {
187 ProcessProperties *properties = (ProcessProperties *)baton;
188 if (properties->m_process)
189 properties->m_process->LoadOperatingSystemPlugin(true);
Greg Clayton332e8b12015-01-13 21:13:08 +0000190}
191
Kate Stoneb9c1b512016-09-06 20:57:50 +0000192bool ProcessProperties::GetDisableMemoryCache() const {
193 const uint32_t idx = ePropertyDisableMemCache;
194 return m_collection_sp->GetPropertyAtIndexAsBoolean(
195 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000196}
197
Kate Stoneb9c1b512016-09-06 20:57:50 +0000198uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
199 const uint32_t idx = ePropertyMemCacheLineSize;
200 return m_collection_sp->GetPropertyAtIndexAsUInt64(
201 nullptr, idx, g_properties[idx].default_uint_value);
Jason Molendaf0340c92014-09-03 22:30:54 +0000202}
203
Kate Stoneb9c1b512016-09-06 20:57:50 +0000204Args ProcessProperties::GetExtraStartupCommands() const {
205 Args args;
206 const uint32_t idx = ePropertyExtraStartCommand;
207 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
208 return args;
Greg Clayton67cc0632012-08-22 17:17:09 +0000209}
210
Kate Stoneb9c1b512016-09-06 20:57:50 +0000211void ProcessProperties::SetExtraStartupCommands(const Args &args) {
212 const uint32_t idx = ePropertyExtraStartCommand;
213 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +0000214}
215
Kate Stoneb9c1b512016-09-06 20:57:50 +0000216FileSpec ProcessProperties::GetPythonOSPluginPath() const {
217 const uint32_t idx = ePropertyPythonOSPluginPath;
218 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000219}
220
Kate Stoneb9c1b512016-09-06 20:57:50 +0000221void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {
222 const uint32_t idx = ePropertyPythonOSPluginPath;
223 m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000224}
225
Kate Stoneb9c1b512016-09-06 20:57:50 +0000226bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
227 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
228 return m_collection_sp->GetPropertyAtIndexAsBoolean(
229 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham184e9812013-01-15 02:47:48 +0000230}
231
Kate Stoneb9c1b512016-09-06 20:57:50 +0000232void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {
233 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
234 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Ingham184e9812013-01-15 02:47:48 +0000235}
236
Kate Stoneb9c1b512016-09-06 20:57:50 +0000237bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
238 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
239 return m_collection_sp->GetPropertyAtIndexAsBoolean(
240 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham29950772013-01-26 02:19:28 +0000241}
242
Kate Stoneb9c1b512016-09-06 20:57:50 +0000243void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {
244 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
245 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Inghamacff8952013-05-02 00:27:30 +0000246}
247
Kate Stoneb9c1b512016-09-06 20:57:50 +0000248bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
249 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
250 return m_collection_sp->GetPropertyAtIndexAsBoolean(
251 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jason Molendaef7d6412015-08-06 03:27:10 +0000252}
253
Kate Stoneb9c1b512016-09-06 20:57:50 +0000254void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {
255 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
256 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
257}
258
259bool ProcessProperties::GetDetachKeepsStopped() const {
260 const uint32_t idx = ePropertyDetachKeepsStopped;
261 return m_collection_sp->GetPropertyAtIndexAsBoolean(
262 nullptr, idx, g_properties[idx].default_uint_value != 0);
263}
264
265void ProcessProperties::SetDetachKeepsStopped(bool stop) {
266 const uint32_t idx = ePropertyDetachKeepsStopped;
267 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
268}
269
270bool ProcessProperties::GetWarningsOptimization() const {
271 const uint32_t idx = ePropertyWarningOptimization;
272 return m_collection_sp->GetPropertyAtIndexAsBoolean(
273 nullptr, idx, g_properties[idx].default_uint_value != 0);
274}
275
Jim Inghamba205c12017-12-05 02:50:45 +0000276bool ProcessProperties::GetStopOnExec() const {
277 const uint32_t idx = ePropertyStopOnExec;
278 return m_collection_sp->GetPropertyAtIndexAsBoolean(
279 nullptr, idx, g_properties[idx].default_uint_value != 0);
280}
281
Zachary Turner97206d52017-05-12 04:51:55 +0000282Status ProcessLaunchCommandOptions::SetOptionValue(
Zachary Turnerfe114832016-11-12 16:56:47 +0000283 uint32_t option_idx, llvm::StringRef option_arg,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000284 ExecutionContext *execution_context) {
Zachary Turner97206d52017-05-12 04:51:55 +0000285 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000286 const int short_option = m_getopt_table[option_idx].val;
287
288 switch (short_option) {
289 case 's': // Stop at program entry point
290 launch_info.GetFlags().Set(eLaunchFlagStopAtEntry);
291 break;
292
293 case 'i': // STDIN for read only
294 {
295 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000296 if (action.Open(STDIN_FILENO, FileSpec(option_arg), true, false))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000297 launch_info.AppendFileAction(action);
298 break;
299 }
300
301 case 'o': // Open STDOUT for write only
302 {
303 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000304 if (action.Open(STDOUT_FILENO, FileSpec(option_arg), false, true))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000305 launch_info.AppendFileAction(action);
306 break;
307 }
308
309 case 'e': // STDERR for write only
310 {
311 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000312 if (action.Open(STDERR_FILENO, FileSpec(option_arg), false, true))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000313 launch_info.AppendFileAction(action);
314 break;
315 }
316
317 case 'p': // Process plug-in name
318 launch_info.SetProcessPluginName(option_arg);
319 break;
320
321 case 'n': // Disable STDIO
322 {
323 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000324 const FileSpec dev_null(FileSystem::DEV_NULL);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000325 if (action.Open(STDIN_FILENO, dev_null, true, false))
326 launch_info.AppendFileAction(action);
327 if (action.Open(STDOUT_FILENO, dev_null, false, true))
328 launch_info.AppendFileAction(action);
329 if (action.Open(STDERR_FILENO, dev_null, false, true))
330 launch_info.AppendFileAction(action);
331 break;
332 }
333
334 case 'w':
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000335 launch_info.SetWorkingDirectory(FileSpec(option_arg));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000336 break;
337
338 case 't': // Open process in new terminal window
339 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
340 break;
341
342 case 'a': {
343 TargetSP target_sp =
344 execution_context ? execution_context->GetTargetSP() : TargetSP();
345 PlatformSP platform_sp =
346 target_sp ? target_sp->GetPlatform() : PlatformSP();
Pavel Labath7263f1b2017-10-31 10:56:03 +0000347 launch_info.GetArchitecture() =
348 Platform::GetAugmentedArchSpec(platform_sp.get(), option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000349 } break;
350
351 case 'A': // Disable ASLR.
352 {
353 bool success;
354 const bool disable_aslr_arg =
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000355 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000356 if (success)
357 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
Greg Clayton8b82f082011-04-12 05:54:46 +0000358 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 error.SetErrorStringWithFormat(
360 "Invalid boolean value for disable-aslr option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000361 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362 break;
363 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000364
Kate Stoneb9c1b512016-09-06 20:57:50 +0000365 case 'X': // shell expand args.
366 {
367 bool success;
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000368 const bool expand_args =
369 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000370 if (success)
371 launch_info.SetShellExpandArguments(expand_args);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000372 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000373 error.SetErrorStringWithFormat(
374 "Invalid boolean value for shell-expand-args option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000375 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000376 break;
377 }
378
379 case 'c':
Zachary Turnerfe114832016-11-12 16:56:47 +0000380 if (!option_arg.empty())
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000381 launch_info.SetShell(FileSpec(option_arg));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000382 else
383 launch_info.SetShell(HostInfo::GetDefaultShell());
384 break;
385
386 case 'v':
Pavel Labath62930e52018-01-10 11:57:31 +0000387 launch_info.GetEnvironment().insert(option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000388 break;
389
390 default:
391 error.SetErrorStringWithFormat("unrecognized short option character '%c'",
392 short_option);
393 break;
394 }
395 return error;
Greg Clayton32e0a752011-03-30 18:16:51 +0000396}
397
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000398static constexpr OptionDefinition g_process_launch_options[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000399 {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000400 nullptr, {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000401 "Stop at the entry point of the program when launching a process."},
402 {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000403 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000404 "Set whether to disable address space layout randomization when launching "
405 "a process."},
406 {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000407 nullptr, {}, 0, eArgTypePlugin,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000408 "Name of the process plugin you want to use."},
409 {LLDB_OPT_SET_ALL, false, "working-dir", 'w',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000410 OptionParser::eRequiredArgument, nullptr, {}, 0,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000411 eArgTypeDirectoryName,
412 "Set the current working directory to <path> when running the inferior."},
413 {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000414 nullptr, {}, 0, eArgTypeArchitecture,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000415 "Set the architecture for the process to launch when ambiguous."},
416 {LLDB_OPT_SET_ALL, false, "environment", 'v',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000417 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000418 "Specify an environment variable name/value string (--environment "
419 "NAME=VALUE). Can be specified multiple times for subsequent environment "
420 "entries."},
421 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000422 OptionParser::eOptionalArgument, nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000423 "Run the process in a shell (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000424
Kate Stoneb9c1b512016-09-06 20:57:50 +0000425 {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000426 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000427 "Redirect stdin for the process to <filename>."},
428 {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000429 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000430 "Redirect stdout for the process to <filename>."},
431 {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000432 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000433 "Redirect stderr for the process to <filename>."},
Todd Fiala7df337f2015-10-13 23:41:19 +0000434
Kate Stoneb9c1b512016-09-06 20:57:50 +0000435 {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000436 {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000437 "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000438
Kate Stoneb9c1b512016-09-06 20:57:50 +0000439 {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000440 {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000441 "Do not set up for terminal I/O to go to running process."},
442 {LLDB_OPT_SET_4, false, "shell-expand-args", 'X',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000443 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000444 "Set whether to shell expand arguments to the process when launching."},
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000445};
446
447llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() {
Zachary Turner70602432016-09-22 21:06:13 +0000448 return llvm::makeArrayRef(g_process_launch_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000449}
Greg Clayton32e0a752011-03-30 18:16:51 +0000450
Zachary Turner31659452016-11-17 21:15:14 +0000451ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
452 llvm::StringRef plugin_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000453 ListenerSP listener_sp,
454 const FileSpec *crash_file_path) {
455 static uint32_t g_process_unique_id = 0;
456
457 ProcessSP process_sp;
458 ProcessCreateInstance create_callback = nullptr;
Zachary Turner31659452016-11-17 21:15:14 +0000459 if (!plugin_name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000460 ConstString const_plugin_name(plugin_name);
461 create_callback =
462 PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
463 if (create_callback) {
464 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
465 if (process_sp) {
466 if (process_sp->CanDebug(target_sp, true)) {
467 process_sp->m_process_unique_id = ++g_process_unique_id;
468 } else
469 process_sp.reset();
470 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000471 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000472 } else {
473 for (uint32_t idx = 0;
474 (create_callback =
475 PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
476 ++idx) {
477 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
478 if (process_sp) {
479 if (process_sp->CanDebug(target_sp, false)) {
480 process_sp->m_process_unique_id = ++g_process_unique_id;
481 break;
482 } else
483 process_sp.reset();
484 }
485 }
486 }
487 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000488}
489
Kate Stoneb9c1b512016-09-06 20:57:50 +0000490ConstString &Process::GetStaticBroadcasterClass() {
491 static ConstString class_name("lldb.process");
492 return class_name;
493}
494
495Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
496 : Process(target_sp, listener_sp,
497 UnixSignals::Create(HostInfo::GetArchitecture())) {
498 // This constructor just delegates to the full Process constructor,
499 // defaulting to using the Host's UnixSignals.
500}
501
502Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
503 const UnixSignalsSP &unix_signals_sp)
504 : ProcessProperties(this), UserID(LLDB_INVALID_PROCESS_ID),
505 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
506 Process::GetStaticBroadcasterClass().AsCString()),
Jim Inghamb87b9e62018-06-26 23:38:58 +0000507 m_target_wp(target_sp), m_public_state(eStateUnloaded),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000508 m_private_state(eStateUnloaded),
509 m_private_state_broadcaster(nullptr,
510 "lldb.process.internal_state_broadcaster"),
511 m_private_state_control_broadcaster(
512 nullptr, "lldb.process.internal_state_control_broadcaster"),
513 m_private_state_listener_sp(
514 Listener::MakeListener("lldb.process.internal_state_listener")),
515 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
516 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
517 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
518 m_thread_list(this), m_extended_thread_list(this),
519 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
520 m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000521 m_breakpoint_site_list(), m_dynamic_checkers_up(),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000522 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
523 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
524 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
525 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
526 m_memory_cache(*this), m_allocated_memory_cache(*this),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000527 m_should_detach(false), m_next_event_action_up(), m_public_run_lock(),
Pavel Labath13e37d42017-10-25 21:05:31 +0000528 m_private_run_lock(), m_finalizing(false), m_finalize_called(false),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000529 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
530 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
531 m_can_interpret_function_calls(false), m_warnings_issued(),
532 m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
533 CheckInWithManager();
534
535 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
536 if (log)
537 log->Printf("%p Process::Process()", static_cast<void *>(this));
538
539 if (!m_unix_signals_sp)
540 m_unix_signals_sp = std::make_shared<UnixSignals>();
541
542 SetEventName(eBroadcastBitStateChanged, "state-changed");
543 SetEventName(eBroadcastBitInterrupt, "interrupt");
544 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
545 SetEventName(eBroadcastBitSTDERR, "stderr-available");
546 SetEventName(eBroadcastBitProfileData, "profile-data-available");
547 SetEventName(eBroadcastBitStructuredData, "structured-data-available");
548
549 m_private_state_control_broadcaster.SetEventName(
550 eBroadcastInternalStateControlStop, "control-stop");
551 m_private_state_control_broadcaster.SetEventName(
552 eBroadcastInternalStateControlPause, "control-pause");
553 m_private_state_control_broadcaster.SetEventName(
554 eBroadcastInternalStateControlResume, "control-resume");
555
556 m_listener_sp->StartListeningForEvents(
557 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
558 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
559 eBroadcastBitProfileData | eBroadcastBitStructuredData);
560
561 m_private_state_listener_sp->StartListeningForEvents(
562 &m_private_state_broadcaster,
563 eBroadcastBitStateChanged | eBroadcastBitInterrupt);
564
565 m_private_state_listener_sp->StartListeningForEvents(
566 &m_private_state_control_broadcaster,
567 eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
568 eBroadcastInternalStateControlResume);
569 // We need something valid here, even if just the default UnixSignalsSP.
570 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
571
572 // Allow the platform to override the default cache line size
573 OptionValueSP value_sp =
574 m_collection_sp
575 ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
576 ->GetValue();
577 uint32_t platform_cache_line_size =
578 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
579 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
580 value_sp->SetUInt64Value(platform_cache_line_size);
581}
582
583Process::~Process() {
584 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
585 if (log)
586 log->Printf("%p Process::~Process()", static_cast<void *>(this));
587 StopPrivateStateThread();
588
589 // ThreadList::Clear() will try to acquire this process's mutex, so
Adrian Prantl05097242018-04-30 16:49:04 +0000590 // explicitly clear the thread list here to ensure that the mutex is not
591 // destroyed before the thread list.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000592 m_thread_list.Clear();
593}
594
595const ProcessPropertiesSP &Process::GetGlobalProperties() {
596 // NOTE: intentional leak so we don't crash if global destructor chain gets
597 // called as other threads still use the result of this function
Pavel Labath5f05ea82016-10-19 15:12:45 +0000598 static ProcessPropertiesSP *g_settings_sp_ptr =
599 new ProcessPropertiesSP(new ProcessProperties(nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000600 return *g_settings_sp_ptr;
601}
602
603void Process::Finalize() {
604 m_finalizing = true;
605
606 // Destroy this process if needed
607 switch (GetPrivateState()) {
608 case eStateConnected:
609 case eStateAttaching:
610 case eStateLaunching:
611 case eStateStopped:
612 case eStateRunning:
613 case eStateStepping:
614 case eStateCrashed:
615 case eStateSuspended:
616 Destroy(false);
617 break;
618
619 case eStateInvalid:
620 case eStateUnloaded:
621 case eStateDetached:
622 case eStateExited:
623 break;
624 }
625
626 // Clear our broadcaster before we proceed with destroying
627 Broadcaster::Clear();
628
Adrian Prantl05097242018-04-30 16:49:04 +0000629 // Do any cleanup needed prior to being destructed... Subclasses that
630 // override this method should call this superclass method as well.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000631
632 // We need to destroy the loader before the derived Process class gets
Adrian Prantl05097242018-04-30 16:49:04 +0000633 // destroyed since it is very likely that undoing the loader will require
634 // access to the real process.
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000635 m_dynamic_checkers_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000636 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000637 m_os_up.reset();
638 m_system_runtime_up.reset();
639 m_dyld_up.reset();
640 m_jit_loaders_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000641 m_thread_list_real.Destroy();
642 m_thread_list.Destroy();
643 m_extended_thread_list.Destroy();
644 m_queue_list.Clear();
645 m_queue_list_stop_id = 0;
646 std::vector<Notifications> empty_notifications;
647 m_notifications.swap(empty_notifications);
648 m_image_tokens.clear();
649 m_memory_cache.Clear();
650 m_allocated_memory_cache.Clear();
651 m_language_runtimes.clear();
652 m_instrumentation_runtimes.clear();
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000653 m_next_event_action_up.reset();
Adrian Prantl05097242018-04-30 16:49:04 +0000654 // Clear the last natural stop ID since it has a strong reference to this
655 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +0000656 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
657 //#ifdef LLDB_CONFIGURATION_DEBUG
658 // StreamFile s(stdout, false);
659 // EventSP event_sp;
660 // while (m_private_state_listener_sp->GetNextEvent(event_sp))
661 // {
662 // event_sp->Dump (&s);
663 // s.EOL();
664 // }
665 //#endif
666 // We have to be very careful here as the m_private_state_listener might
667 // contain events that have ProcessSP values in them which can keep this
668 // process around forever. These events need to be cleared out.
669 m_private_state_listener_sp->Clear();
670 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
671 m_public_run_lock.SetStopped();
672 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
673 m_private_run_lock.SetStopped();
Jason Molenda38267272016-12-16 02:48:39 +0000674 m_structured_data_plugin_map.clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000675 m_finalize_called = true;
676}
677
678void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
679 m_notifications.push_back(callbacks);
680 if (callbacks.initialize != nullptr)
681 callbacks.initialize(callbacks.baton, this);
682}
683
684bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
685 std::vector<Notifications>::iterator pos, end = m_notifications.end();
686 for (pos = m_notifications.begin(); pos != end; ++pos) {
687 if (pos->baton == callbacks.baton &&
688 pos->initialize == callbacks.initialize &&
689 pos->process_state_changed == callbacks.process_state_changed) {
690 m_notifications.erase(pos);
691 return true;
692 }
693 }
694 return false;
695}
696
697void Process::SynchronouslyNotifyStateChanged(StateType state) {
698 std::vector<Notifications>::iterator notification_pos,
699 notification_end = m_notifications.end();
700 for (notification_pos = m_notifications.begin();
701 notification_pos != notification_end; ++notification_pos) {
702 if (notification_pos->process_state_changed)
703 notification_pos->process_state_changed(notification_pos->baton, this,
704 state);
705 }
706}
707
708// FIXME: We need to do some work on events before the general Listener sees
709// them.
710// For instance if we are continuing from a breakpoint, we need to ensure that
Adrian Prantl05097242018-04-30 16:49:04 +0000711// we do the little "insert real insn, step & stop" trick. But we can't do
712// that when the event is delivered by the broadcaster - since that is done on
713// the thread that is waiting for new events, so if we needed more than one
714// event for our handling, we would stall. So instead we do it when we fetch
715// the event off of the queue.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000716//
717
Kate Stoneb9c1b512016-09-06 20:57:50 +0000718StateType Process::GetNextEvent(EventSP &event_sp) {
719 StateType state = eStateInvalid;
720
Pavel Labathd35031e12016-11-30 10:41:42 +0000721 if (m_listener_sp->GetEventForBroadcaster(this, event_sp,
722 std::chrono::seconds(0)) &&
723 event_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000724 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
725
726 return state;
727}
728
Pavel Labath3879fe02018-05-09 14:29:30 +0000729void Process::SyncIOHandler(uint32_t iohandler_id,
730 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000731 // don't sync (potentially context switch) in case where there is no process
732 // IO
733 if (!m_process_input_reader)
734 return;
735
Pavel Labath3879fe02018-05-09 14:29:30 +0000736 auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000737
738 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labath3879fe02018-05-09 14:29:30 +0000739 if (Result) {
740 LLDB_LOG(
741 log,
742 "waited from m_iohandler_sync to change from {0}. New value is {1}.",
743 iohandler_id, *Result);
744 } else {
745 LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.",
746 iohandler_id);
747 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000748}
749
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000750StateType Process::WaitForProcessToStop(const Timeout<std::micro> &timeout,
751 EventSP *event_sp_ptr, bool wait_always,
752 ListenerSP hijack_listener_sp,
753 Stream *stream, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000754 // We can't just wait for a "stopped" event, because the stopped event may
Adrian Prantl05097242018-04-30 16:49:04 +0000755 // have restarted the target. We have to actually check each event, and in
756 // the case of a stopped event check the restarted flag on the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000757 if (event_sp_ptr)
758 event_sp_ptr->reset();
759 StateType state = GetState();
Adrian Prantl05097242018-04-30 16:49:04 +0000760 // If we are exited or detached, we won't ever get back to any other valid
761 // state...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000762 if (state == eStateDetached || state == eStateExited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000763 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000764
Kate Stoneb9c1b512016-09-06 20:57:50 +0000765 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +0000766 LLDB_LOG(log, "timeout = {0}", timeout);
Todd Fialaa3b89e22014-08-12 14:33:19 +0000767
Kate Stoneb9c1b512016-09-06 20:57:50 +0000768 if (!wait_always && StateIsStoppedState(state, true) &&
769 StateIsStoppedState(GetPrivateState(), true)) {
Pavel Labath44464872015-05-27 12:40:32 +0000770 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000771 log->Printf("Process::%s returning without waiting for events; process "
772 "private and public states are already 'stopped'.",
773 __FUNCTION__);
774 // We need to toggle the run lock as this won't get done in
775 // SetPublicState() if the process is hijacked.
776 if (hijack_listener_sp && use_run_lock)
777 m_public_run_lock.SetStopped();
778 return state;
779 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000780
Kate Stoneb9c1b512016-09-06 20:57:50 +0000781 while (state != eStateInvalid) {
782 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000783 state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000784 if (event_sp_ptr && event_sp)
785 *event_sp_ptr = event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +0000786
Kate Stoneb9c1b512016-09-06 20:57:50 +0000787 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
788 Process::HandleProcessStateChangedEvent(event_sp, stream,
789 pop_process_io_handler);
Daniel Malea9e9919f2013-10-09 16:56:28 +0000790
Kate Stoneb9c1b512016-09-06 20:57:50 +0000791 switch (state) {
792 case eStateCrashed:
793 case eStateDetached:
794 case eStateExited:
795 case eStateUnloaded:
796 // We need to toggle the run lock as this won't get done in
797 // SetPublicState() if the process is hijacked.
798 if (hijack_listener_sp && use_run_lock)
799 m_public_run_lock.SetStopped();
800 return state;
801 case eStateStopped:
802 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
803 continue;
804 else {
Pavel Labath78521ef2015-03-06 10:52:47 +0000805 // We need to toggle the run lock as this won't get done in
806 // SetPublicState() if the process is hijacked.
Jim Ingham583bbb12016-03-07 21:50:25 +0000807 if (hijack_listener_sp && use_run_lock)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000808 m_public_run_lock.SetStopped();
809 return state;
810 }
811 default:
812 continue;
813 }
814 }
815 return state;
816}
817
818bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
819 Stream *stream,
820 bool &pop_process_io_handler) {
821 const bool handle_pop = pop_process_io_handler;
822
823 pop_process_io_handler = false;
824 ProcessSP process_sp =
825 Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
826
827 if (!process_sp)
828 return false;
829
830 StateType event_state =
831 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
832 if (event_state == eStateInvalid)
833 return false;
834
835 switch (event_state) {
836 case eStateInvalid:
837 case eStateUnloaded:
838 case eStateAttaching:
839 case eStateLaunching:
840 case eStateStepping:
841 case eStateDetached:
842 if (stream)
843 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
844 StateAsCString(event_state));
845 if (event_state == eStateDetached)
846 pop_process_io_handler = true;
847 break;
848
849 case eStateConnected:
850 case eStateRunning:
851 // Don't be chatty when we run...
852 break;
853
854 case eStateExited:
855 if (stream)
856 process_sp->GetStatus(*stream);
857 pop_process_io_handler = true;
858 break;
859
860 case eStateStopped:
861 case eStateCrashed:
862 case eStateSuspended:
863 // Make sure the program hasn't been auto-restarted:
864 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
865 if (stream) {
866 size_t num_reasons =
867 Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
868 if (num_reasons > 0) {
869 // FIXME: Do we want to report this, or would that just be annoyingly
870 // chatty?
871 if (num_reasons == 1) {
872 const char *reason =
873 Process::ProcessEventData::GetRestartedReasonAtIndex(
874 event_sp.get(), 0);
875 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
876 process_sp->GetID(),
877 reason ? reason : "<UNKNOWN REASON>");
878 } else {
879 stream->Printf("Process %" PRIu64
880 " stopped and restarted, reasons:\n",
881 process_sp->GetID());
882
883 for (size_t i = 0; i < num_reasons; i++) {
884 const char *reason =
885 Process::ProcessEventData::GetRestartedReasonAtIndex(
886 event_sp.get(), i);
887 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
888 }
889 }
890 }
891 }
892 } else {
893 StopInfoSP curr_thread_stop_info_sp;
894 // Lock the thread list so it doesn't change on us, this is the scope for
895 // the locker:
896 {
897 ThreadList &thread_list = process_sp->GetThreadList();
898 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
899
900 ThreadSP curr_thread(thread_list.GetSelectedThread());
901 ThreadSP thread;
902 StopReason curr_thread_stop_reason = eStopReasonInvalid;
903 if (curr_thread) {
904 curr_thread_stop_reason = curr_thread->GetStopReason();
905 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
906 }
907 if (!curr_thread || !curr_thread->IsValid() ||
908 curr_thread_stop_reason == eStopReasonInvalid ||
909 curr_thread_stop_reason == eStopReasonNone) {
910 // Prefer a thread that has just completed its plan over another
911 // thread as current thread.
912 ThreadSP plan_thread;
913 ThreadSP other_thread;
914
915 const size_t num_threads = thread_list.GetSize();
916 size_t i;
917 for (i = 0; i < num_threads; ++i) {
918 thread = thread_list.GetThreadAtIndex(i);
919 StopReason thread_stop_reason = thread->GetStopReason();
920 switch (thread_stop_reason) {
921 case eStopReasonInvalid:
922 case eStopReasonNone:
923 break;
924
925 case eStopReasonSignal: {
926 // Don't select a signal thread if we weren't going to stop at
Adrian Prantl05097242018-04-30 16:49:04 +0000927 // that signal. We have to have had another reason for stopping
928 // here, and the user doesn't want to see this thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000929 uint64_t signo = thread->GetStopInfo()->GetValue();
930 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
931 if (!other_thread)
932 other_thread = thread;
933 }
934 break;
935 }
936 case eStopReasonTrace:
937 case eStopReasonBreakpoint:
938 case eStopReasonWatchpoint:
939 case eStopReasonException:
940 case eStopReasonExec:
941 case eStopReasonThreadExiting:
942 case eStopReasonInstrumentation:
943 if (!other_thread)
944 other_thread = thread;
945 break;
946 case eStopReasonPlanComplete:
947 if (!plan_thread)
948 plan_thread = thread;
949 break;
950 }
951 }
952 if (plan_thread)
953 thread_list.SetSelectedThreadByID(plan_thread->GetID());
954 else if (other_thread)
955 thread_list.SetSelectedThreadByID(other_thread->GetID());
956 else {
957 if (curr_thread && curr_thread->IsValid())
958 thread = curr_thread;
959 else
960 thread = thread_list.GetThreadAtIndex(0);
961
962 if (thread)
963 thread_list.SetSelectedThreadByID(thread->GetID());
964 }
965 }
966 }
967 // Drop the ThreadList mutex by here, since GetThreadStatus below might
Adrian Prantl05097242018-04-30 16:49:04 +0000968 // have to run code, e.g. for Data formatters, and if we hold the
969 // ThreadList mutex, then the process is going to have a hard time
970 // restarting the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000971 if (stream) {
972 Debugger &debugger = process_sp->GetTarget().GetDebugger();
973 if (debugger.GetTargetList().GetSelectedTarget().get() ==
974 &process_sp->GetTarget()) {
975 const bool only_threads_with_stop_reason = true;
976 const uint32_t start_frame = 0;
977 const uint32_t num_frames = 1;
978 const uint32_t num_frames_with_source = 1;
Jim Ingham6a9767c2016-11-08 20:36:40 +0000979 const bool stop_format = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000980 process_sp->GetStatus(*stream);
981 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
982 start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +0000983 num_frames_with_source,
984 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000985 if (curr_thread_stop_info_sp) {
986 lldb::addr_t crashing_address;
987 ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
988 curr_thread_stop_info_sp, &crashing_address);
989 if (valobj_sp) {
990 const bool qualify_cxx_base_classes = false;
991
992 const ValueObject::GetExpressionPathFormat format =
993 ValueObject::GetExpressionPathFormat::
994 eGetExpressionPathFormatHonorPointers;
995 stream->PutCString("Likely cause: ");
996 valobj_sp->GetExpressionPath(*stream, qualify_cxx_base_classes,
997 format);
998 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
999 }
1000 }
1001 } else {
1002 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
1003 process_sp->GetTarget().shared_from_this());
1004 if (target_idx != UINT32_MAX)
1005 stream->Printf("Target %d: (", target_idx);
1006 else
1007 stream->Printf("Target <unknown index>: (");
1008 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
1009 stream->Printf(") stopped.\n");
1010 }
1011 }
1012
1013 // Pop the process IO handler
1014 pop_process_io_handler = true;
1015 }
1016 break;
1017 }
1018
1019 if (handle_pop && pop_process_io_handler)
1020 process_sp->PopProcessIOHandler();
1021
1022 return true;
1023}
1024
Kate Stoneb9c1b512016-09-06 20:57:50 +00001025bool Process::HijackProcessEvents(ListenerSP listener_sp) {
1026 if (listener_sp) {
1027 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
1028 eBroadcastBitInterrupt);
1029 } else
1030 return false;
1031}
Greg Claytondc6224e2014-10-21 01:00:42 +00001032
Kate Stoneb9c1b512016-09-06 20:57:50 +00001033void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
Greg Claytondc6224e2014-10-21 01:00:42 +00001034
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001035StateType Process::GetStateChangedEvents(EventSP &event_sp,
1036 const Timeout<std::micro> &timeout,
1037 ListenerSP hijack_listener_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001038 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001039 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Greg Claytondc6224e2014-10-21 01:00:42 +00001040
Kate Stoneb9c1b512016-09-06 20:57:50 +00001041 ListenerSP listener_sp = hijack_listener_sp;
1042 if (!listener_sp)
1043 listener_sp = m_listener_sp;
Greg Claytondc6224e2014-10-21 01:00:42 +00001044
Kate Stoneb9c1b512016-09-06 20:57:50 +00001045 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001046 if (listener_sp->GetEventForBroadcasterWithType(
1047 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001048 timeout)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001049 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1050 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Pavel Labathd02b1c82017-02-10 11:49:33 +00001051 else
1052 LLDB_LOG(log, "got no event or was interrupted.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001053 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001054
Pavel Labathd02b1c82017-02-10 11:49:33 +00001055 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001056 return state;
1057}
Greg Claytondc6224e2014-10-21 01:00:42 +00001058
Kate Stoneb9c1b512016-09-06 20:57:50 +00001059Event *Process::PeekAtStateChangedEvents() {
1060 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001061
Kate Stoneb9c1b512016-09-06 20:57:50 +00001062 if (log)
1063 log->Printf("Process::%s...", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001064
Kate Stoneb9c1b512016-09-06 20:57:50 +00001065 Event *event_ptr;
1066 event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
1067 this, eBroadcastBitStateChanged);
1068 if (log) {
1069 if (event_ptr) {
1070 log->Printf(
1071 "Process::%s (event_ptr) => %s", __FUNCTION__,
1072 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
1073 } else {
1074 log->Printf("Process::%s no events found", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001075 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001076 }
1077 return event_ptr;
1078}
Greg Claytondc6224e2014-10-21 01:00:42 +00001079
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001080StateType
1081Process::GetStateChangedEventsPrivate(EventSP &event_sp,
1082 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001083 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001084 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001085
1086 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001087 if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1088 &m_private_state_broadcaster,
1089 eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001090 timeout))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001091 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1092 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1093
Pavel Labathd02b1c82017-02-10 11:49:33 +00001094 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
1095 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001096 return state;
1097}
1098
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001099bool Process::GetEventsPrivate(EventSP &event_sp,
1100 const Timeout<std::micro> &timeout,
1101 bool control_only) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001102 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001103 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001104
1105 if (control_only)
Pavel Labathd35031e12016-11-30 10:41:42 +00001106 return m_private_state_listener_sp->GetEventForBroadcaster(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001107 &m_private_state_control_broadcaster, event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001108 else
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001109 return m_private_state_listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001110}
1111
1112bool Process::IsRunning() const {
1113 return StateIsRunningState(m_public_state.GetValue());
1114}
1115
1116int Process::GetExitStatus() {
1117 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1118
1119 if (m_public_state.GetValue() == eStateExited)
1120 return m_exit_status;
1121 return -1;
1122}
1123
1124const char *Process::GetExitDescription() {
1125 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1126
1127 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1128 return m_exit_string.c_str();
1129 return nullptr;
1130}
1131
1132bool Process::SetExitStatus(int status, const char *cstr) {
1133 // Use a mutex to protect setting the exit status.
1134 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1135
1136 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1137 LIBLLDB_LOG_PROCESS));
1138 if (log)
1139 log->Printf(
1140 "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1141 status, status, cstr ? "\"" : "", cstr ? cstr : "NULL",
1142 cstr ? "\"" : "");
1143
1144 // We were already in the exited state
1145 if (m_private_state.GetValue() == eStateExited) {
1146 if (log)
1147 log->Printf("Process::SetExitStatus () ignoring exit status because "
1148 "state was already set to eStateExited");
1149 return false;
1150 }
1151
1152 m_exit_status = status;
1153 if (cstr)
1154 m_exit_string = cstr;
1155 else
1156 m_exit_string.clear();
1157
Adrian Prantl05097242018-04-30 16:49:04 +00001158 // Clear the last natural stop ID since it has a strong reference to this
1159 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +00001160 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1161
1162 SetPrivateState(eStateExited);
1163
1164 // Allow subclasses to do some cleanup
1165 DidExit();
1166
1167 return true;
1168}
1169
1170bool Process::IsAlive() {
1171 switch (m_private_state.GetValue()) {
1172 case eStateConnected:
1173 case eStateAttaching:
1174 case eStateLaunching:
1175 case eStateStopped:
1176 case eStateRunning:
1177 case eStateStepping:
1178 case eStateCrashed:
1179 case eStateSuspended:
Greg Claytondc6224e2014-10-21 01:00:42 +00001180 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001181 default:
1182 return false;
1183 }
Jason Molendaa814f702015-11-05 23:03:44 +00001184}
1185
Adrian Prantl05097242018-04-30 16:49:04 +00001186// This static callback can be used to watch for local child processes on the
1187// current host. The child process exits, the process will be found in the
1188// global target list (we want to be completely sure that the
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001189// lldb_private::Process doesn't go away before we can deliver the signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001190bool Process::SetProcessExitStatus(
1191 lldb::pid_t pid, bool exited,
1192 int signo, // Zero for no signal
1193 int exit_status // Exit value of process if signal is zero
1194 ) {
1195 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1196 if (log)
1197 log->Printf("Process::SetProcessExitStatus (pid=%" PRIu64
1198 ", exited=%i, signal=%i, exit_status=%i)\n",
1199 pid, exited, signo, exit_status);
1200
1201 if (exited) {
1202 TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1203 if (target_sp) {
1204 ProcessSP process_sp(target_sp->GetProcessSP());
1205 if (process_sp) {
1206 const char *signal_cstr = nullptr;
1207 if (signo)
1208 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1209
1210 process_sp->SetExitStatus(exit_status, signal_cstr);
1211 }
1212 }
1213 return true;
1214 }
1215 return false;
1216}
1217
1218void Process::UpdateThreadListIfNeeded() {
1219 const uint32_t stop_id = GetStopID();
1220 if (m_thread_list.GetSize(false) == 0 ||
1221 stop_id != m_thread_list.GetStopID()) {
1222 const StateType state = GetPrivateState();
1223 if (StateIsStoppedState(state, true)) {
1224 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
Adrian Prantl05097242018-04-30 16:49:04 +00001225 // m_thread_list does have its own mutex, but we need to hold onto the
1226 // mutex between the call to UpdateThreadList(...) and the
1227 // os->UpdateThreadList(...) so it doesn't change on us
Kate Stoneb9c1b512016-09-06 20:57:50 +00001228 ThreadList &old_thread_list = m_thread_list;
1229 ThreadList real_thread_list(this);
1230 ThreadList new_thread_list(this);
Adrian Prantl05097242018-04-30 16:49:04 +00001231 // Always update the thread list with the protocol specific thread list,
1232 // but only update if "true" is returned
Kate Stoneb9c1b512016-09-06 20:57:50 +00001233 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1234 // Don't call into the OperatingSystem to update the thread list if we
Adrian Prantl05097242018-04-30 16:49:04 +00001235 // are shutting down, since that may call back into the SBAPI's,
1236 // requiring the API lock which is already held by whoever is shutting
1237 // us down, causing a deadlock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001238 OperatingSystem *os = GetOperatingSystem();
1239 if (os && !m_destroy_in_process) {
1240 // Clear any old backing threads where memory threads might have been
1241 // backed by actual threads from the lldb_private::Process subclass
1242 size_t num_old_threads = old_thread_list.GetSize(false);
1243 for (size_t i = 0; i < num_old_threads; ++i)
1244 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1245
1246 // Turn off dynamic types to ensure we don't run any expressions.
Adrian Prantl4e8be2c2018-06-13 16:21:24 +00001247 // Objective-C can run an expression to determine if a SBValue is a
Adrian Prantl05097242018-04-30 16:49:04 +00001248 // dynamic type or not and we need to avoid this. OperatingSystem
1249 // plug-ins can't run expressions that require running code...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001250
1251 Target &target = GetTarget();
1252 const lldb::DynamicValueType saved_prefer_dynamic =
1253 target.GetPreferDynamicValue();
1254 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1255 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1256
1257 // Now let the OperatingSystem plug-in update the thread list
1258
1259 os->UpdateThreadList(
1260 old_thread_list, // Old list full of threads created by OS plug-in
1261 real_thread_list, // The actual thread list full of threads
1262 // created by each lldb_private::Process
1263 // subclass
1264 new_thread_list); // The new thread list that we will show to the
1265 // user that gets filled in
1266
1267 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1268 target.SetPreferDynamicValue(saved_prefer_dynamic);
1269 } else {
1270 // No OS plug-in, the new thread list is the same as the real thread
1271 // list
1272 new_thread_list = real_thread_list;
1273 }
1274
1275 m_thread_list_real.Update(real_thread_list);
1276 m_thread_list.Update(new_thread_list);
1277 m_thread_list.SetStopID(stop_id);
1278
1279 if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
1280 // Clear any extended threads that we may have accumulated previously
1281 m_extended_thread_list.Clear();
1282 m_extended_thread_stop_id = GetLastNaturalStopID();
1283
1284 m_queue_list.Clear();
1285 m_queue_list_stop_id = GetLastNaturalStopID();
1286 }
1287 }
1288 }
1289 }
1290}
1291
1292void Process::UpdateQueueListIfNeeded() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001293 if (m_system_runtime_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001294 if (m_queue_list.GetSize() == 0 ||
1295 m_queue_list_stop_id != GetLastNaturalStopID()) {
1296 const StateType state = GetPrivateState();
1297 if (StateIsStoppedState(state, true)) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001298 m_system_runtime_up->PopulateQueueList(m_queue_list);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001299 m_queue_list_stop_id = GetLastNaturalStopID();
1300 }
1301 }
1302 }
1303}
1304
1305ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
1306 OperatingSystem *os = GetOperatingSystem();
1307 if (os)
1308 return os->CreateThread(tid, context);
1309 return ThreadSP();
1310}
1311
1312uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1313 return AssignIndexIDToThread(thread_id);
1314}
1315
1316bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1317 return (m_thread_id_to_index_id_map.find(thread_id) !=
1318 m_thread_id_to_index_id_map.end());
1319}
1320
1321uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1322 uint32_t result = 0;
1323 std::map<uint64_t, uint32_t>::iterator iterator =
1324 m_thread_id_to_index_id_map.find(thread_id);
1325 if (iterator == m_thread_id_to_index_id_map.end()) {
1326 result = ++m_thread_index_id;
1327 m_thread_id_to_index_id_map[thread_id] = result;
1328 } else {
1329 result = iterator->second;
1330 }
1331
1332 return result;
1333}
1334
1335StateType Process::GetState() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001336 return m_public_state.GetValue();
1337}
1338
Kate Stoneb9c1b512016-09-06 20:57:50 +00001339void Process::SetPublicState(StateType new_state, bool restarted) {
1340 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1341 LIBLLDB_LOG_PROCESS));
1342 if (log)
1343 log->Printf("Process::SetPublicState (state = %s, restarted = %i)",
1344 StateAsCString(new_state), restarted);
1345 const StateType old_state = m_public_state.GetValue();
1346 m_public_state.SetValue(new_state);
1347
Adrian Prantl05097242018-04-30 16:49:04 +00001348 // On the transition from Run to Stopped, we unlock the writer end of the run
1349 // lock. The lock gets locked in Resume, which is the public API to tell the
1350 // program to run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001351 if (!StateChangedIsExternallyHijacked()) {
1352 if (new_state == eStateDetached) {
1353 if (log)
1354 log->Printf(
1355 "Process::SetPublicState (%s) -- unlocking run lock for detach",
1356 StateAsCString(new_state));
1357 m_public_run_lock.SetStopped();
1358 } else {
1359 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1360 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1361 if ((old_state_is_stopped != new_state_is_stopped)) {
1362 if (new_state_is_stopped && !restarted) {
1363 if (log)
1364 log->Printf("Process::SetPublicState (%s) -- unlocking run lock",
1365 StateAsCString(new_state));
1366 m_public_run_lock.SetStopped();
1367 }
1368 }
1369 }
1370 }
1371}
1372
Zachary Turner97206d52017-05-12 04:51:55 +00001373Status Process::Resume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001374 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1375 LIBLLDB_LOG_PROCESS));
1376 if (log)
1377 log->Printf("Process::Resume -- locking run lock");
1378 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001379 Status error("Resume request failed - process still running.");
Greg Claytone4e45922011-11-16 05:37:56 +00001380 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001381 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
Greg Claytondc6224e2014-10-21 01:00:42 +00001382 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001383 }
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001384 Status error = PrivateResume();
1385 if (!error.Success()) {
1386 // Undo running state change
1387 m_public_run_lock.SetStopped();
1388 }
1389 return error;
Greg Claytondc6224e2014-10-21 01:00:42 +00001390}
1391
Jim Ingham3139fc92019-03-01 18:13:38 +00001392static const char *g_resume_sync_name = "lldb.Process.ResumeSynchronous.hijack";
1393
Zachary Turner97206d52017-05-12 04:51:55 +00001394Status Process::ResumeSynchronous(Stream *stream) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001395 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1396 LIBLLDB_LOG_PROCESS));
1397 if (log)
1398 log->Printf("Process::ResumeSynchronous -- locking run lock");
1399 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001400 Status error("Resume request failed - process still running.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001401 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001402 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
1403 return error;
1404 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001405
Kate Stoneb9c1b512016-09-06 20:57:50 +00001406 ListenerSP listener_sp(
Jim Ingham3139fc92019-03-01 18:13:38 +00001407 Listener::MakeListener(g_resume_sync_name));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001408 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001409
Zachary Turner97206d52017-05-12 04:51:55 +00001410 Status error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001411 if (error.Success()) {
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001412 StateType state =
1413 WaitForProcessToStop(llvm::None, NULL, true, listener_sp, stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001414 const bool must_be_alive =
1415 false; // eStateExited is ok, so this must be false
1416 if (!StateIsStoppedState(state, must_be_alive))
1417 error.SetErrorStringWithFormat(
1418 "process not in stopped state after synchronous resume: %s",
1419 StateAsCString(state));
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001420 } else {
1421 // Undo running state change
1422 m_public_run_lock.SetStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001423 }
Ed Mastec29693f2013-07-02 16:35:47 +00001424
Kate Stoneb9c1b512016-09-06 20:57:50 +00001425 // Undo the hijacking of process events...
1426 RestoreProcessEvents();
Andrew Kaylor93132f52013-05-28 23:04:25 +00001427
Kate Stoneb9c1b512016-09-06 20:57:50 +00001428 return error;
1429}
Andrew Kaylor29d65742013-05-10 17:19:04 +00001430
Jim Ingham3139fc92019-03-01 18:13:38 +00001431bool Process::StateChangedIsExternallyHijacked() {
1432 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1433 const char *hijacking_name = GetHijackingListenerName();
1434 if (hijacking_name &&
1435 strcmp(hijacking_name, g_resume_sync_name))
1436 return true;
1437 }
1438 return false;
1439}
1440
1441bool Process::StateChangedIsHijackedForSynchronousResume() {
1442 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1443 const char *hijacking_name = GetHijackingListenerName();
1444 if (hijacking_name &&
1445 strcmp(hijacking_name, g_resume_sync_name) == 0)
1446 return true;
1447 }
1448 return false;
1449}
1450
Kate Stoneb9c1b512016-09-06 20:57:50 +00001451StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
Ilia K38810f42015-05-20 10:15:47 +00001452
Kate Stoneb9c1b512016-09-06 20:57:50 +00001453void Process::SetPrivateState(StateType new_state) {
1454 if (m_finalize_called)
1455 return;
1456
1457 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1458 LIBLLDB_LOG_PROCESS));
1459 bool state_changed = false;
1460
1461 if (log)
1462 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1463
1464 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1465 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1466
1467 const StateType old_state = m_private_state.GetValueNoLock();
1468 state_changed = old_state != new_state;
1469
1470 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1471 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1472 if (old_state_is_stopped != new_state_is_stopped) {
1473 if (new_state_is_stopped)
1474 m_private_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001475 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001476 m_private_run_lock.SetRunning();
1477 }
1478
1479 if (state_changed) {
1480 m_private_state.SetValueNoLock(new_state);
1481 EventSP event_sp(
1482 new Event(eBroadcastBitStateChanged,
1483 new ProcessEventData(shared_from_this(), new_state)));
1484 if (StateIsStoppedState(new_state, false)) {
Adrian Prantl05097242018-04-30 16:49:04 +00001485 // Note, this currently assumes that all threads in the list stop when
1486 // the process stops. In the future we will want to support a debugging
1487 // model where some threads continue to run while others are stopped.
1488 // When that happens we will either need a way for the thread list to
1489 // identify which threads are stopping or create a special thread list
1490 // containing only threads which actually stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001491 //
Adrian Prantl05097242018-04-30 16:49:04 +00001492 // The process plugin is responsible for managing the actual behavior of
1493 // the threads and should have stopped any threads that are going to stop
1494 // before we get here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001495 m_thread_list.DidStop();
1496
1497 m_mod_id.BumpStopID();
1498 if (!m_mod_id.IsLastResumeForUserExpression())
1499 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1500 m_memory_cache.Clear();
1501 if (log)
1502 log->Printf("Process::SetPrivateState (%s) stop_id = %u",
1503 StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001504 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001505
Kate Stoneb9c1b512016-09-06 20:57:50 +00001506 // Use our target to get a shared pointer to ourselves...
1507 if (m_finalize_called && !PrivateStateThreadIsValid())
1508 BroadcastEvent(event_sp);
Jim Ingham22777012010-09-23 02:01:19 +00001509 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001510 m_private_state_broadcaster.BroadcastEvent(event_sp);
1511 } else {
1512 if (log)
1513 log->Printf(
1514 "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1515 StateAsCString(new_state));
1516 }
Jim Ingham22777012010-09-23 02:01:19 +00001517}
1518
Kate Stoneb9c1b512016-09-06 20:57:50 +00001519void Process::SetRunningUserExpression(bool on) {
1520 m_mod_id.SetRunningUserExpression(on);
1521}
1522
Raphael Isemannc01783a2018-08-29 22:50:54 +00001523void Process::SetRunningUtilityFunction(bool on) {
1524 m_mod_id.SetRunningUtilityFunction(on);
1525}
1526
Kate Stoneb9c1b512016-09-06 20:57:50 +00001527addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
1528
1529const lldb::ABISP &Process::GetABI() {
1530 if (!m_abi_sp)
Jason Molenda43294c92017-06-29 02:57:03 +00001531 m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001532 return m_abi_sp;
1533}
1534
1535LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language,
1536 bool retry_if_null) {
1537 if (m_finalizing)
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001538 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001539
1540 LanguageRuntimeCollection::iterator pos;
1541 pos = m_language_runtimes.find(language);
1542 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second)) {
1543 lldb::LanguageRuntimeSP runtime_sp(
1544 LanguageRuntime::FindPlugin(this, language));
1545
1546 m_language_runtimes[language] = runtime_sp;
1547 return runtime_sp.get();
1548 } else
1549 return (*pos).second.get();
Jim Ingham22777012010-09-23 02:01:19 +00001550}
1551
Kate Stoneb9c1b512016-09-06 20:57:50 +00001552CPPLanguageRuntime *Process::GetCPPLanguageRuntime(bool retry_if_null) {
1553 LanguageRuntime *runtime =
1554 GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
1555 if (runtime != nullptr &&
1556 runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1557 return static_cast<CPPLanguageRuntime *>(runtime);
1558 return nullptr;
Jim Ingham22777012010-09-23 02:01:19 +00001559}
1560
Kate Stoneb9c1b512016-09-06 20:57:50 +00001561ObjCLanguageRuntime *Process::GetObjCLanguageRuntime(bool retry_if_null) {
1562 LanguageRuntime *runtime =
1563 GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
1564 if (runtime != nullptr && runtime->GetLanguageType() == eLanguageTypeObjC)
1565 return static_cast<ObjCLanguageRuntime *>(runtime);
1566 return nullptr;
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001567}
1568
Kate Stoneb9c1b512016-09-06 20:57:50 +00001569bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
1570 if (m_finalizing)
1571 return false;
1572
1573 if (in_value.IsDynamic())
1574 return false;
1575 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1576
1577 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1578 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1579 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1580 }
1581
1582 LanguageRuntime *cpp_runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1583 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1584 return true;
1585
1586 LanguageRuntime *objc_runtime = GetLanguageRuntime(eLanguageTypeObjC);
1587 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
Zachary Turner93749ab2015-03-03 21:51:25 +00001588}
1589
Kate Stoneb9c1b512016-09-06 20:57:50 +00001590void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001591 m_dynamic_checkers_up.reset(dynamic_checkers);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001592}
1593
Kate Stoneb9c1b512016-09-06 20:57:50 +00001594BreakpointSiteList &Process::GetBreakpointSiteList() {
1595 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001596}
1597
Kate Stoneb9c1b512016-09-06 20:57:50 +00001598const BreakpointSiteList &Process::GetBreakpointSiteList() const {
1599 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001600}
1601
Kate Stoneb9c1b512016-09-06 20:57:50 +00001602void Process::DisableAllBreakpointSites() {
1603 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1604 // bp_site->SetEnabled(true);
1605 DisableBreakpointSite(bp_site);
1606 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001607}
1608
Zachary Turner97206d52017-05-12 04:51:55 +00001609Status Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
1610 Status error(DisableBreakpointSiteByID(break_id));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001611
Kate Stoneb9c1b512016-09-06 20:57:50 +00001612 if (error.Success())
1613 m_breakpoint_site_list.Remove(break_id);
1614
1615 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001616}
1617
Zachary Turner97206d52017-05-12 04:51:55 +00001618Status Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
1619 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001620 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1621 if (bp_site_sp) {
1622 if (bp_site_sp->IsEnabled())
1623 error = DisableBreakpointSite(bp_site_sp.get());
1624 } else {
1625 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1626 break_id);
1627 }
1628
1629 return error;
1630}
1631
Zachary Turner97206d52017-05-12 04:51:55 +00001632Status Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
1633 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001634 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1635 if (bp_site_sp) {
1636 if (!bp_site_sp->IsEnabled())
1637 error = EnableBreakpointSite(bp_site_sp.get());
1638 } else {
1639 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1640 break_id);
1641 }
1642 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001643}
1644
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001645lldb::break_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001646Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1647 bool use_hardware) {
1648 addr_t load_addr = LLDB_INVALID_ADDRESS;
Jim Ingham1460e4b2014-01-10 23:46:59 +00001649
Kate Stoneb9c1b512016-09-06 20:57:50 +00001650 bool show_error = true;
1651 switch (GetState()) {
1652 case eStateInvalid:
1653 case eStateUnloaded:
1654 case eStateConnected:
1655 case eStateAttaching:
1656 case eStateLaunching:
1657 case eStateDetached:
1658 case eStateExited:
1659 show_error = false;
1660 break;
1661
1662 case eStateStopped:
1663 case eStateRunning:
1664 case eStateStepping:
1665 case eStateCrashed:
1666 case eStateSuspended:
1667 show_error = IsAlive();
1668 break;
1669 }
1670
Adrian Prantl05097242018-04-30 16:49:04 +00001671 // Reset the IsIndirect flag here, in case the location changes from pointing
1672 // to a indirect symbol to a regular symbol.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001673 owner->SetIsIndirect(false);
1674
1675 if (owner->ShouldResolveIndirectFunctions()) {
1676 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1677 if (symbol && symbol->IsIndirect()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001678 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001679 Address symbol_address = symbol->GetAddress();
1680 load_addr = ResolveIndirectFunction(&symbol_address, error);
1681 if (!error.Success() && show_error) {
1682 GetTarget().GetDebugger().GetErrorFile()->Printf(
1683 "warning: failed to resolve indirect function at 0x%" PRIx64
1684 " for breakpoint %i.%i: %s\n",
1685 symbol->GetLoadAddress(&GetTarget()),
1686 owner->GetBreakpoint().GetID(), owner->GetID(),
1687 error.AsCString() ? error.AsCString() : "unknown error");
1688 return LLDB_INVALID_BREAK_ID;
1689 }
1690 Address resolved_address(load_addr);
1691 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1692 owner->SetIsIndirect(true);
1693 } else
1694 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1695 } else
1696 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1697
1698 if (load_addr != LLDB_INVALID_ADDRESS) {
1699 BreakpointSiteSP bp_site_sp;
1700
1701 // Look up this breakpoint site. If it exists, then add this new owner,
Adrian Prantl05097242018-04-30 16:49:04 +00001702 // otherwise create a new breakpoint site and add it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001703
1704 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1705
1706 if (bp_site_sp) {
1707 bp_site_sp->AddOwner(owner);
1708 owner->SetBreakpointSite(bp_site_sp);
1709 return bp_site_sp->GetID();
1710 } else {
1711 bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1712 load_addr, use_hardware));
1713 if (bp_site_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001714 Status error = EnableBreakpointSite(bp_site_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001715 if (error.Success()) {
1716 owner->SetBreakpointSite(bp_site_sp);
1717 return m_breakpoint_site_list.Add(bp_site_sp);
1718 } else {
Jonas Devliegheree103ae92018-11-15 01:18:15 +00001719 if (show_error || use_hardware) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001720 // Report error for setting breakpoint...
1721 GetTarget().GetDebugger().GetErrorFile()->Printf(
1722 "warning: failed to set breakpoint site at 0x%" PRIx64
1723 " for breakpoint %i.%i: %s\n",
1724 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1725 error.AsCString() ? error.AsCString() : "unknown error");
1726 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001727 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001728 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001729 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001730 }
1731 // We failed to enable the breakpoint
1732 return LLDB_INVALID_BREAK_ID;
1733}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001734
Kate Stoneb9c1b512016-09-06 20:57:50 +00001735void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
1736 lldb::user_id_t owner_loc_id,
1737 BreakpointSiteSP &bp_site_sp) {
1738 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1739 if (num_owners == 0) {
1740 // Don't try to disable the site if we don't have a live process anymore.
1741 if (IsAlive())
1742 DisableBreakpointSite(bp_site_sp.get());
1743 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1744 }
1745}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001746
Kate Stoneb9c1b512016-09-06 20:57:50 +00001747size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
1748 uint8_t *buf) const {
1749 size_t bytes_removed = 0;
1750 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001751
Kate Stoneb9c1b512016-09-06 20:57:50 +00001752 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1753 bp_sites_in_range)) {
Zachary Turner3bc714b2017-03-02 00:05:25 +00001754 bp_sites_in_range.ForEach([bp_addr, size,
1755 buf](BreakpointSite *bp_site) -> void {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001756 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1757 addr_t intersect_addr;
1758 size_t intersect_size;
1759 size_t opcode_offset;
1760 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1761 &intersect_size, &opcode_offset)) {
1762 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1763 assert(bp_addr < intersect_addr + intersect_size &&
1764 intersect_addr + intersect_size <= bp_addr + size);
1765 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1766 size_t buf_offset = intersect_addr - bp_addr;
1767 ::memcpy(buf + buf_offset,
1768 bp_site->GetSavedOpcodeBytes() + opcode_offset,
1769 intersect_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001770 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001771 }
1772 });
1773 }
1774 return bytes_removed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001775}
1776
Kate Stoneb9c1b512016-09-06 20:57:50 +00001777size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
1778 PlatformSP platform_sp(GetTarget().GetPlatform());
1779 if (platform_sp)
1780 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
1781 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001782}
1783
Zachary Turner97206d52017-05-12 04:51:55 +00001784Status Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
1785 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001786 assert(bp_site != nullptr);
1787 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1788 const addr_t bp_addr = bp_site->GetLoadAddress();
1789 if (log)
1790 log->Printf(
1791 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
1792 bp_site->GetID(), (uint64_t)bp_addr);
1793 if (bp_site->IsEnabled()) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001794 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001795 log->Printf(
1796 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1797 " -- already enabled",
1798 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001799 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001800 }
1801
1802 if (bp_addr == LLDB_INVALID_ADDRESS) {
1803 error.SetErrorString("BreakpointSite contains an invalid load address.");
1804 return error;
1805 }
1806 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1807 // trap for the breakpoint site
1808 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1809
1810 if (bp_opcode_size == 0) {
1811 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
1812 "returned zero, unable to get breakpoint "
1813 "trap for address 0x%" PRIx64,
1814 bp_addr);
1815 } else {
1816 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1817
1818 if (bp_opcode_bytes == nullptr) {
1819 error.SetErrorString(
1820 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1821 return error;
1822 }
1823
1824 // Save the original opcode by reading it
1825 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
1826 error) == bp_opcode_size) {
1827 // Write a software breakpoint in place of the original opcode
1828 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
1829 bp_opcode_size) {
1830 uint8_t verify_bp_opcode_bytes[64];
1831 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
1832 error) == bp_opcode_size) {
1833 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
1834 bp_opcode_size) == 0) {
1835 bp_site->SetEnabled(true);
1836 bp_site->SetType(BreakpointSite::eSoftware);
1837 if (log)
1838 log->Printf("Process::EnableSoftwareBreakpoint (site_id = %d) "
1839 "addr = 0x%" PRIx64 " -- SUCCESS",
1840 bp_site->GetID(), (uint64_t)bp_addr);
1841 } else
1842 error.SetErrorString(
1843 "failed to verify the breakpoint trap in memory.");
1844 } else
1845 error.SetErrorString(
1846 "Unable to read memory to verify breakpoint trap.");
1847 } else
1848 error.SetErrorString("Unable to write breakpoint trap to memory.");
1849 } else
1850 error.SetErrorString("Unable to read memory at breakpoint address.");
1851 }
1852 if (log && error.Fail())
1853 log->Printf(
1854 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1855 " -- FAILED: %s",
1856 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1857 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001858}
1859
Zachary Turner97206d52017-05-12 04:51:55 +00001860Status Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
1861 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001862 assert(bp_site != nullptr);
1863 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1864 addr_t bp_addr = bp_site->GetLoadAddress();
1865 lldb::user_id_t breakID = bp_site->GetID();
1866 if (log)
1867 log->Printf("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
1868 ") addr = 0x%" PRIx64,
1869 breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001870
Kate Stoneb9c1b512016-09-06 20:57:50 +00001871 if (bp_site->IsHardware()) {
1872 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1873 } else if (bp_site->IsEnabled()) {
1874 const size_t break_op_size = bp_site->GetByteSize();
1875 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
1876 if (break_op_size > 0) {
1877 // Clear a software breakpoint instruction
1878 uint8_t curr_break_op[8];
1879 assert(break_op_size <= sizeof(curr_break_op));
1880 bool break_op_found = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001881
Kate Stoneb9c1b512016-09-06 20:57:50 +00001882 // Read the breakpoint opcode
1883 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
1884 break_op_size) {
1885 bool verify = false;
1886 // Make sure the breakpoint opcode exists at this address
1887 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
1888 break_op_found = true;
1889 // We found a valid breakpoint opcode at this address, now restore
1890 // the saved opcode.
1891 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
1892 break_op_size, error) == break_op_size) {
1893 verify = true;
1894 } else
1895 error.SetErrorString(
1896 "Memory write failed when restoring original opcode.");
1897 } else {
1898 error.SetErrorString(
1899 "Original breakpoint trap is no longer in memory.");
1900 // Set verify to true and so we can check if the original opcode has
1901 // already been restored
1902 verify = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001903 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001904
Kate Stoneb9c1b512016-09-06 20:57:50 +00001905 if (verify) {
1906 uint8_t verify_opcode[8];
1907 assert(break_op_size < sizeof(verify_opcode));
1908 // Verify that our original opcode made it back to the inferior
1909 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
1910 break_op_size) {
1911 // compare the memory we just read with the original opcode
1912 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
1913 break_op_size) == 0) {
1914 // SUCCESS
1915 bp_site->SetEnabled(false);
1916 if (log)
1917 log->Printf("Process::DisableSoftwareBreakpoint (site_id = %d) "
1918 "addr = 0x%" PRIx64 " -- SUCCESS",
1919 bp_site->GetID(), (uint64_t)bp_addr);
1920 return error;
1921 } else {
1922 if (break_op_found)
1923 error.SetErrorString("Failed to restore original opcode.");
1924 }
1925 } else
1926 error.SetErrorString("Failed to read memory to verify that "
1927 "breakpoint trap was restored.");
1928 }
1929 } else
1930 error.SetErrorString(
1931 "Unable to read memory that should contain the breakpoint trap.");
1932 }
1933 } else {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001934 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001935 log->Printf(
1936 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1937 " -- already disabled",
1938 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001939 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001940 }
1941
1942 if (log)
1943 log->Printf(
1944 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1945 " -- FAILED: %s",
1946 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1947 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001948}
1949
Adrian Prantl05097242018-04-30 16:49:04 +00001950// Uncomment to verify memory caching works after making changes to caching
1951// code
Greg Clayton58be07b2011-01-07 06:08:19 +00001952//#define VERIFY_MEMORY_READS
1953
Zachary Turner97206d52017-05-12 04:51:55 +00001954size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001955 error.Clear();
1956 if (!GetDisableMemoryCache()) {
1957#if defined(VERIFY_MEMORY_READS)
1958 // Memory caching is enabled, with debug verification
1959
1960 if (buf && size) {
1961 // Uncomment the line below to make sure memory caching is working.
1962 // I ran this through the test suite and got no assertions, so I am
1963 // pretty confident this is working well. If any changes are made to
1964 // memory caching, uncomment the line below and test your changes!
1965
1966 // Verify all memory reads by using the cache first, then redundantly
1967 // reading the same memory from the inferior and comparing to make sure
1968 // everything is exactly the same.
1969 std::string verify_buf(size, '\0');
1970 assert(verify_buf.size() == size);
1971 const size_t cache_bytes_read =
1972 m_memory_cache.Read(this, addr, buf, size, error);
Zachary Turner97206d52017-05-12 04:51:55 +00001973 Status verify_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001974 const size_t verify_bytes_read =
1975 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
1976 verify_buf.size(), verify_error);
1977 assert(cache_bytes_read == verify_bytes_read);
1978 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1979 assert(verify_error.Success() == error.Success());
1980 return cache_bytes_read;
1981 }
1982 return 0;
1983#else // !defined(VERIFY_MEMORY_READS)
1984 // Memory caching is enabled, without debug verification
1985
1986 return m_memory_cache.Read(addr, buf, size, error);
Sean Callanan64c0cf22012-06-07 22:26:42 +00001987#endif // defined (VERIFY_MEMORY_READS)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001988 } else {
1989 // Memory caching is disabled
1990
1991 return ReadMemoryFromInferior(addr, buf, size, error);
1992 }
Greg Clayton58be07b2011-01-07 06:08:19 +00001993}
Kate Stoneb9c1b512016-09-06 20:57:50 +00001994
1995size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
Zachary Turner97206d52017-05-12 04:51:55 +00001996 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001997 char buf[256];
1998 out_str.clear();
1999 addr_t curr_addr = addr;
2000 while (true) {
2001 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
2002 if (length == 0)
2003 break;
2004 out_str.append(buf, length);
Adrian Prantl05097242018-04-30 16:49:04 +00002005 // If we got "length - 1" bytes, we didn't get the whole C string, we need
2006 // to read some more characters
Kate Stoneb9c1b512016-09-06 20:57:50 +00002007 if (length == sizeof(buf) - 1)
2008 curr_addr += length;
2009 else
2010 break;
2011 }
2012 return out_str.size();
2013}
2014
2015size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
Zachary Turner97206d52017-05-12 04:51:55 +00002016 Status &error, size_t type_width) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002017 size_t total_bytes_read = 0;
2018 if (dst && max_bytes && type_width && max_bytes >= type_width) {
Adrian Prantl05097242018-04-30 16:49:04 +00002019 // Ensure a null terminator independent of the number of bytes that is
2020 // read.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002021 memset(dst, 0, max_bytes);
2022 size_t bytes_left = max_bytes - type_width;
2023
2024 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2025 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2026 "string with more than 4 bytes "
2027 "per character!");
2028
Greg Clayton4c82d422012-05-18 23:20:01 +00002029 addr_t curr_addr = addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002030 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2031 char *curr_dst = dst;
Greg Clayton4c82d422012-05-18 23:20:01 +00002032
Kate Stoneb9c1b512016-09-06 20:57:50 +00002033 error.Clear();
2034 while (bytes_left > 0 && error.Success()) {
2035 addr_t cache_line_bytes_left =
2036 cache_line_size - (curr_addr % cache_line_size);
2037 addr_t bytes_to_read =
2038 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2039 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002040
Kate Stoneb9c1b512016-09-06 20:57:50 +00002041 if (bytes_read == 0)
2042 break;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002043
Kate Stoneb9c1b512016-09-06 20:57:50 +00002044 // Search for a null terminator of correct size and alignment in
2045 // bytes_read
2046 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2047 for (size_t i = aligned_start;
2048 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2049 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2050 error.Clear();
2051 return i;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002052 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002053
2054 total_bytes_read += bytes_read;
2055 curr_dst += bytes_read;
2056 curr_addr += bytes_read;
2057 bytes_left -= bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002058 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002059 } else {
2060 if (max_bytes)
2061 error.SetErrorString("invalid arguments");
2062 }
2063 return total_bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002064}
2065
Kate Stoneb9c1b512016-09-06 20:57:50 +00002066// Deprecated in favor of ReadStringFromMemory which has wchar support and
Adrian Prantl05097242018-04-30 16:49:04 +00002067// correct code to find null terminators.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002068size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
Zachary Turner97206d52017-05-12 04:51:55 +00002069 size_t dst_max_len,
2070 Status &result_error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002071 size_t total_cstr_len = 0;
2072 if (dst && dst_max_len) {
2073 result_error.Clear();
2074 // NULL out everything just to be safe
2075 memset(dst, 0, dst_max_len);
Zachary Turner97206d52017-05-12 04:51:55 +00002076 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002077 addr_t curr_addr = addr;
2078 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2079 size_t bytes_left = dst_max_len - 1;
2080 char *curr_dst = dst;
Greg Clayton8b82f082011-04-12 05:54:46 +00002081
Kate Stoneb9c1b512016-09-06 20:57:50 +00002082 while (bytes_left > 0) {
2083 addr_t cache_line_bytes_left =
2084 cache_line_size - (curr_addr % cache_line_size);
2085 addr_t bytes_to_read =
2086 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2087 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Greg Clayton8b82f082011-04-12 05:54:46 +00002088
Kate Stoneb9c1b512016-09-06 20:57:50 +00002089 if (bytes_read == 0) {
2090 result_error = error;
2091 dst[total_cstr_len] = '\0';
2092 break;
2093 }
2094 const size_t len = strlen(curr_dst);
Greg Clayton8b82f082011-04-12 05:54:46 +00002095
Kate Stoneb9c1b512016-09-06 20:57:50 +00002096 total_cstr_len += len;
2097
2098 if (len < bytes_to_read)
2099 break;
2100
2101 curr_dst += bytes_read;
2102 curr_addr += bytes_read;
2103 bytes_left -= bytes_read;
Greg Clayton8b82f082011-04-12 05:54:46 +00002104 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002105 } else {
2106 if (dst == nullptr)
2107 result_error.SetErrorString("invalid arguments");
Greg Claytone91b7952011-12-15 03:14:23 +00002108 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002109 result_error.Clear();
2110 }
2111 return total_cstr_len;
Greg Clayton8b82f082011-04-12 05:54:46 +00002112}
2113
Kate Stoneb9c1b512016-09-06 20:57:50 +00002114size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002115 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002116 if (buf == nullptr || size == 0)
2117 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002118
Kate Stoneb9c1b512016-09-06 20:57:50 +00002119 size_t bytes_read = 0;
2120 uint8_t *bytes = (uint8_t *)buf;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002121
Kate Stoneb9c1b512016-09-06 20:57:50 +00002122 while (bytes_read < size) {
2123 const size_t curr_size = size - bytes_read;
2124 const size_t curr_bytes_read =
2125 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2126 bytes_read += curr_bytes_read;
2127 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2128 break;
2129 }
2130
2131 // Replace any software breakpoint opcodes that fall into this range back
2132 // into "buf" before we return
2133 if (bytes_read > 0)
2134 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2135 return bytes_read;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002136}
2137
Kate Stoneb9c1b512016-09-06 20:57:50 +00002138uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
2139 size_t integer_byte_size,
2140 uint64_t fail_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002141 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002142 Scalar scalar;
2143 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2144 error))
2145 return scalar.ULongLong(fail_value);
2146 return fail_value;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002147}
2148
Kate Stoneb9c1b512016-09-06 20:57:50 +00002149int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
2150 size_t integer_byte_size,
Zachary Turner97206d52017-05-12 04:51:55 +00002151 int64_t fail_value,
2152 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002153 Scalar scalar;
2154 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2155 error))
2156 return scalar.SLongLong(fail_value);
2157 return fail_value;
Greg Claytonc2267782016-05-23 20:37:24 +00002158}
2159
Zachary Turner97206d52017-05-12 04:51:55 +00002160addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002161 Scalar scalar;
2162 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2163 error))
2164 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2165 return LLDB_INVALID_ADDRESS;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002166}
2167
Kate Stoneb9c1b512016-09-06 20:57:50 +00002168bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002169 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002170 Scalar scalar;
2171 const uint32_t addr_byte_size = GetAddressByteSize();
2172 if (addr_byte_size <= 4)
2173 scalar = (uint32_t)ptr_value;
2174 else
2175 scalar = ptr_value;
2176 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2177 addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002178}
2179
Kate Stoneb9c1b512016-09-06 20:57:50 +00002180size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002181 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002182 size_t bytes_written = 0;
2183 const uint8_t *bytes = (const uint8_t *)buf;
2184
2185 while (bytes_written < size) {
2186 const size_t curr_size = size - bytes_written;
2187 const size_t curr_bytes_written = DoWriteMemory(
2188 addr + bytes_written, bytes + bytes_written, curr_size, error);
2189 bytes_written += curr_bytes_written;
2190 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2191 break;
2192 }
2193 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002194}
2195
Kate Stoneb9c1b512016-09-06 20:57:50 +00002196size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002197 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002198#if defined(ENABLE_MEMORY_CACHING)
2199 m_memory_cache.Flush(addr, size);
Greg Clayton58be07b2011-01-07 06:08:19 +00002200#endif
2201
Kate Stoneb9c1b512016-09-06 20:57:50 +00002202 if (buf == nullptr || size == 0)
2203 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002204
Kate Stoneb9c1b512016-09-06 20:57:50 +00002205 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002206
Kate Stoneb9c1b512016-09-06 20:57:50 +00002207 // We need to write any data that would go where any current software traps
2208 // (enabled software breakpoints) any software traps (breakpoints) that we
2209 // may have placed in our tasks memory.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002210
Kate Stoneb9c1b512016-09-06 20:57:50 +00002211 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002212
Kate Stoneb9c1b512016-09-06 20:57:50 +00002213 if (m_breakpoint_site_list.FindInRange(addr, addr + size,
2214 bp_sites_in_range)) {
2215 // No breakpoint sites overlap
2216 if (bp_sites_in_range.IsEmpty())
2217 return WriteMemoryPrivate(addr, buf, size, error);
2218 else {
2219 const uint8_t *ubuf = (const uint8_t *)buf;
2220 uint64_t bytes_written = 0;
2221
2222 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2223 &error](BreakpointSite *bp) -> void {
2224
2225 if (error.Success()) {
2226 addr_t intersect_addr;
2227 size_t intersect_size;
2228 size_t opcode_offset;
2229 const bool intersects = bp->IntersectsRange(
2230 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2231 UNUSED_IF_ASSERT_DISABLED(intersects);
2232 assert(intersects);
2233 assert(addr <= intersect_addr && intersect_addr < addr + size);
2234 assert(addr < intersect_addr + intersect_size &&
2235 intersect_addr + intersect_size <= addr + size);
2236 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2237
2238 // Check for bytes before this breakpoint
2239 const addr_t curr_addr = addr + bytes_written;
2240 if (intersect_addr > curr_addr) {
Adrian Prantl05097242018-04-30 16:49:04 +00002241 // There are some bytes before this breakpoint that we need to just
2242 // write to memory
Kate Stoneb9c1b512016-09-06 20:57:50 +00002243 size_t curr_size = intersect_addr - curr_addr;
2244 size_t curr_bytes_written = WriteMemoryPrivate(
2245 curr_addr, ubuf + bytes_written, curr_size, error);
2246 bytes_written += curr_bytes_written;
2247 if (curr_bytes_written != curr_size) {
Adrian Prantl05097242018-04-30 16:49:04 +00002248 // We weren't able to write all of the requested bytes, we are
2249 // done looping and will return the number of bytes that we have
2250 // written so far.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002251 if (error.Success())
2252 error.SetErrorToGenericError();
2253 }
2254 }
2255 // Now write any bytes that would cover up any software breakpoints
2256 // directly into the breakpoint opcode buffer
2257 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset,
2258 ubuf + bytes_written, intersect_size);
2259 bytes_written += intersect_size;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002260 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002261 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002262
Kate Stoneb9c1b512016-09-06 20:57:50 +00002263 if (bytes_written < size)
2264 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2265 size - bytes_written, error);
2266 }
2267 } else {
2268 return WriteMemoryPrivate(addr, buf, size, error);
2269 }
2270
2271 // Write any remaining bytes after the last breakpoint if we have any left
2272 return 0; // bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002273}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002274
Kate Stoneb9c1b512016-09-06 20:57:50 +00002275size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002276 size_t byte_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002277 if (byte_size == UINT32_MAX)
2278 byte_size = scalar.GetByteSize();
2279 if (byte_size > 0) {
2280 uint8_t buf[32];
2281 const size_t mem_size =
2282 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2283 if (mem_size > 0)
2284 return WriteMemory(addr, buf, mem_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002285 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002286 error.SetErrorString("failed to get scalar as memory data");
2287 } else {
2288 error.SetErrorString("invalid scalar value");
2289 }
2290 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002291}
2292
Kate Stoneb9c1b512016-09-06 20:57:50 +00002293size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2294 bool is_signed, Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002295 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002296 uint64_t uval = 0;
2297 if (byte_size == 0) {
2298 error.SetErrorString("byte size is zero");
2299 } else if (byte_size & (byte_size - 1)) {
2300 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2301 byte_size);
2302 } else if (byte_size <= sizeof(uval)) {
2303 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2304 if (bytes_read == byte_size) {
2305 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2306 GetAddressByteSize());
2307 lldb::offset_t offset = 0;
2308 if (byte_size <= 4)
2309 scalar = data.GetMaxU32(&offset, byte_size);
2310 else
2311 scalar = data.GetMaxU64(&offset, byte_size);
2312 if (is_signed)
2313 scalar.SignExtend(byte_size * 8);
2314 return bytes_read;
Greg Clayton7060f892013-05-01 23:41:30 +00002315 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002316 } else {
2317 error.SetErrorStringWithFormat(
2318 "byte size of %u is too large for integer scalar type", byte_size);
2319 }
2320 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002321}
2322
Pavel Labath16064d32018-03-20 11:56:24 +00002323Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {
2324 Status error;
2325 for (const auto &Entry : entries) {
2326 WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),
2327 error);
2328 if (!error.Success())
2329 break;
2330 }
2331 return error;
2332}
2333
Greg Claytond495c532011-05-17 03:37:42 +00002334#define USE_ALLOCATE_MEMORY_CACHE 1
Kate Stoneb9c1b512016-09-06 20:57:50 +00002335addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002336 Status &error) {
Vedant Kumarc1cd8262018-05-30 19:39:10 +00002337 if (GetPrivateState() != eStateStopped) {
2338 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002339 return LLDB_INVALID_ADDRESS;
Vedant Kumarc1cd8262018-05-30 19:39:10 +00002340 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002341
2342#if defined(USE_ALLOCATE_MEMORY_CACHE)
2343 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
Greg Claytond495c532011-05-17 03:37:42 +00002344#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002345 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2346 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2347 if (log)
2348 log->Printf("Process::AllocateMemory(size=%" PRIu64
2349 ", permissions=%s) => 0x%16.16" PRIx64
2350 " (m_stop_id = %u m_memory_id = %u)",
2351 (uint64_t)size, GetPermissionsAsCString(permissions),
2352 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2353 m_mod_id.GetMemoryID());
2354 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002355#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002356}
2357
Kate Stoneb9c1b512016-09-06 20:57:50 +00002358addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002359 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002360 addr_t return_addr = AllocateMemory(size, permissions, error);
2361 if (error.Success()) {
2362 std::string buffer(size, 0);
2363 WriteMemory(return_addr, buffer.c_str(), size, error);
2364 }
2365 return return_addr;
2366}
2367
2368bool Process::CanJIT() {
2369 if (m_can_jit == eCanJITDontKnow) {
2370 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +00002371 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002372
2373 uint64_t allocated_memory = AllocateMemory(
2374 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2375 err);
2376
2377 if (err.Success()) {
2378 m_can_jit = eCanJITYes;
2379 if (log)
2380 log->Printf("Process::%s pid %" PRIu64
2381 " allocation test passed, CanJIT () is true",
2382 __FUNCTION__, GetID());
2383 } else {
2384 m_can_jit = eCanJITNo;
2385 if (log)
2386 log->Printf("Process::%s pid %" PRIu64
2387 " allocation test failed, CanJIT () is false: %s",
2388 __FUNCTION__, GetID(), err.AsCString());
Jim Ingham2c381412015-11-04 20:32:27 +00002389 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002390
2391 DeallocateMemory(allocated_memory);
2392 }
2393
2394 return m_can_jit == eCanJITYes;
Jim Ingham2c381412015-11-04 20:32:27 +00002395}
2396
Kate Stoneb9c1b512016-09-06 20:57:50 +00002397void Process::SetCanJIT(bool can_jit) {
2398 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
Sean Callanan90539452011-09-20 23:01:51 +00002399}
2400
Kate Stoneb9c1b512016-09-06 20:57:50 +00002401void Process::SetCanRunCode(bool can_run_code) {
2402 SetCanJIT(can_run_code);
2403 m_can_interpret_function_calls = can_run_code;
Sean Callanan90539452011-09-20 23:01:51 +00002404}
2405
Zachary Turner97206d52017-05-12 04:51:55 +00002406Status Process::DeallocateMemory(addr_t ptr) {
2407 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002408#if defined(USE_ALLOCATE_MEMORY_CACHE)
2409 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2410 error.SetErrorStringWithFormat(
2411 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2412 }
Greg Claytond495c532011-05-17 03:37:42 +00002413#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002414 error = DoDeallocateMemory(ptr);
2415
2416 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2417 if (log)
2418 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64
2419 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2420 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2421 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002422#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00002423 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002424}
2425
Kate Stoneb9c1b512016-09-06 20:57:50 +00002426ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2427 lldb::addr_t header_addr,
2428 size_t size_to_read) {
2429 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2430 if (log) {
2431 log->Printf("Process::ReadModuleFromMemory reading %s binary from memory",
2432 file_spec.GetPath().c_str());
2433 }
2434 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2435 if (module_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00002436 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002437 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2438 shared_from_this(), header_addr, error, size_to_read);
2439 if (objfile)
2440 return module_sp;
2441 }
2442 return ModuleSP();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002443}
2444
Kate Stoneb9c1b512016-09-06 20:57:50 +00002445bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2446 uint32_t &permissions) {
2447 MemoryRegionInfo range_info;
2448 permissions = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002449 Status error(GetMemoryRegionInfo(load_addr, range_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002450 if (!error.Success())
2451 return false;
2452 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2453 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2454 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2455 return false;
2456 }
2457
2458 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2459 permissions |= lldb::ePermissionsReadable;
2460
2461 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2462 permissions |= lldb::ePermissionsWritable;
2463
2464 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2465 permissions |= lldb::ePermissionsExecutable;
2466
2467 return true;
2468}
2469
Zachary Turner97206d52017-05-12 04:51:55 +00002470Status Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2471 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002472 error.SetErrorString("watchpoints are not supported");
2473 return error;
2474}
2475
Zachary Turner97206d52017-05-12 04:51:55 +00002476Status Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2477 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002478 error.SetErrorString("watchpoints are not supported");
2479 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002480}
2481
2482StateType
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002483Process::WaitForProcessStopPrivate(EventSP &event_sp,
2484 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002485 StateType state;
Stella Stamenova36d457c2018-06-01 19:14:53 +00002486
Kate Stoneb9c1b512016-09-06 20:57:50 +00002487 while (true) {
2488 event_sp.reset();
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002489 state = GetStateChangedEventsPrivate(event_sp, timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00002490
Kate Stoneb9c1b512016-09-06 20:57:50 +00002491 if (StateIsStoppedState(state, false))
2492 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002493
Kate Stoneb9c1b512016-09-06 20:57:50 +00002494 // If state is invalid, then we timed out
2495 if (state == eStateInvalid)
2496 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002497
Kate Stoneb9c1b512016-09-06 20:57:50 +00002498 if (event_sp)
2499 HandlePrivateEvent(event_sp);
2500 }
2501 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002502}
2503
Kate Stoneb9c1b512016-09-06 20:57:50 +00002504void Process::LoadOperatingSystemPlugin(bool flush) {
2505 if (flush)
2506 m_thread_list.Clear();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002507 m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002508 if (flush)
2509 Flush();
Greg Clayton332e8b12015-01-13 21:13:08 +00002510}
2511
Zachary Turner97206d52017-05-12 04:51:55 +00002512Status Process::Launch(ProcessLaunchInfo &launch_info) {
2513 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002514 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002515 m_dyld_up.reset();
2516 m_jit_loaders_up.reset();
2517 m_system_runtime_up.reset();
2518 m_os_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002519 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002520
Kate Stoneb9c1b512016-09-06 20:57:50 +00002521 Module *exe_module = GetTarget().GetExecutableModulePointer();
2522 if (exe_module) {
2523 char local_exec_file_path[PATH_MAX];
2524 char platform_exec_file_path[PATH_MAX];
2525 exe_module->GetFileSpec().GetPath(local_exec_file_path,
2526 sizeof(local_exec_file_path));
2527 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2528 sizeof(platform_exec_file_path));
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002529 if (FileSystem::Instance().Exists(exe_module->GetFileSpec())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002530 // Install anything that might need to be installed prior to launching.
2531 // For host systems, this will do nothing, but if we are connected to a
2532 // remote platform it will install any needed binaries
2533 error = GetTarget().Install(&launch_info);
2534 if (error.Fail())
2535 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +00002536
Kate Stoneb9c1b512016-09-06 20:57:50 +00002537 if (PrivateStateThreadIsValid())
2538 PausePrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002539
Kate Stoneb9c1b512016-09-06 20:57:50 +00002540 error = WillLaunch(exe_module);
2541 if (error.Success()) {
2542 const bool restarted = false;
2543 SetPublicState(eStateLaunching, restarted);
2544 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002545
Kate Stoneb9c1b512016-09-06 20:57:50 +00002546 if (m_public_run_lock.TrySetRunning()) {
2547 // Now launch using these arguments.
2548 error = DoLaunch(exe_module, launch_info);
2549 } else {
2550 // This shouldn't happen
2551 error.SetErrorString("failed to acquire process run lock");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002552 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002553
Kate Stoneb9c1b512016-09-06 20:57:50 +00002554 if (error.Fail()) {
2555 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2556 SetID(LLDB_INVALID_PROCESS_ID);
2557 const char *error_string = error.AsCString();
2558 if (error_string == nullptr)
2559 error_string = "launch failed";
2560 SetExitStatus(-1, error_string);
2561 }
2562 } else {
2563 EventSP event_sp;
Stella Stamenova36d457c2018-06-01 19:14:53 +00002564
2565 // Now wait for the process to launch and return control to us, and then call
2566 // DidLaunch:
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002567 StateType state = WaitForProcessStopPrivate(event_sp, seconds(10));
Greg Clayton35824e32015-02-20 20:59:47 +00002568
Kate Stoneb9c1b512016-09-06 20:57:50 +00002569 if (state == eStateInvalid || !event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00002570 // We were able to launch the process, but we failed to catch the
2571 // initial stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002572 error.SetErrorString("failed to catch stop after launch");
2573 SetExitStatus(0, "failed to catch stop after launch");
2574 Destroy(false);
2575 } else if (state == eStateStopped || state == eStateCrashed) {
2576 DidLaunch();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002577
Kate Stoneb9c1b512016-09-06 20:57:50 +00002578 DynamicLoader *dyld = GetDynamicLoader();
2579 if (dyld)
2580 dyld->DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002581
Kate Stoneb9c1b512016-09-06 20:57:50 +00002582 GetJITLoaders().DidLaunch();
Jason Molendaeef51062013-11-05 03:57:19 +00002583
Kate Stoneb9c1b512016-09-06 20:57:50 +00002584 SystemRuntime *system_runtime = GetSystemRuntime();
2585 if (system_runtime)
2586 system_runtime->DidLaunch();
Greg Clayton35824e32015-02-20 20:59:47 +00002587
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002588 if (!m_os_up)
2589 LoadOperatingSystemPlugin(false);
Greg Clayton35824e32015-02-20 20:59:47 +00002590
Adrian Prantl05097242018-04-30 16:49:04 +00002591 // We successfully launched the process and stopped, now it the
2592 // right time to set up signal filters before resuming.
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00002593 UpdateAutomaticSignalFiltering();
2594
Kate Stoneb9c1b512016-09-06 20:57:50 +00002595 // Note, the stop event was consumed above, but not handled. This
Adrian Prantl05097242018-04-30 16:49:04 +00002596 // was done to give DidLaunch a chance to run. The target is either
2597 // stopped or crashed. Directly set the state. This is done to
2598 // prevent a stop message with a bunch of spurious output on thread
2599 // status, as well as not pop a ProcessIOHandler.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002600 SetPublicState(state, false);
Greg Claytonc3776bf2012-02-09 06:16:32 +00002601
Kate Stoneb9c1b512016-09-06 20:57:50 +00002602 if (PrivateStateThreadIsValid())
2603 ResumePrivateStateThread();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002604 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002605 StartPrivateStateThread();
Todd Fiala76e0fc92014-08-27 22:58:26 +00002606
Kate Stoneb9c1b512016-09-06 20:57:50 +00002607 // Target was stopped at entry as was intended. Need to notify the
Adrian Prantl05097242018-04-30 16:49:04 +00002608 // listeners about it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002609 if (state == eStateStopped &&
2610 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2611 HandlePrivateEvent(event_sp);
2612 } else if (state == eStateExited) {
2613 // We exited while trying to launch somehow. Don't call DidLaunch
Adrian Prantl05097242018-04-30 16:49:04 +00002614 // as that's not likely to work, and return an invalid pid.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002615 HandlePrivateEvent(event_sp);
2616 }
2617 }
2618 }
2619 } else {
2620 error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2621 local_exec_file_path);
Jim Inghambb3a2832011-01-29 01:49:25 +00002622 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002623 }
2624 return error;
Jim Inghambb3a2832011-01-29 01:49:25 +00002625}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002626
Zachary Turner97206d52017-05-12 04:51:55 +00002627Status Process::LoadCore() {
2628 Status error = DoLoadCore();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002629 if (error.Success()) {
2630 ListenerSP listener_sp(
2631 Listener::MakeListener("lldb.process.load_core_listener"));
2632 HijackProcessEvents(listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002633
Kate Stoneb9c1b512016-09-06 20:57:50 +00002634 if (PrivateStateThreadIsValid())
2635 ResumePrivateStateThread();
Jim Ingham583bbb12016-03-07 21:50:25 +00002636 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002637 StartPrivateStateThread();
Greg Clayton8012cad2014-11-17 19:39:20 +00002638
Kate Stoneb9c1b512016-09-06 20:57:50 +00002639 DynamicLoader *dyld = GetDynamicLoader();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002640 if (dyld)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002641 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002642
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002643 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002644
Kate Stoneb9c1b512016-09-06 20:57:50 +00002645 SystemRuntime *system_runtime = GetSystemRuntime();
Jason Molendaeef51062013-11-05 03:57:19 +00002646 if (system_runtime)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002647 system_runtime->DidAttach();
Jason Molendaeef51062013-11-05 03:57:19 +00002648
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002649 if (!m_os_up)
Greg Clayton29eeea02017-02-09 18:55:41 +00002650 LoadOperatingSystemPlugin(false);
2651
Kate Stoneb9c1b512016-09-06 20:57:50 +00002652 // We successfully loaded a core file, now pretend we stopped so we can
Adrian Prantl05097242018-04-30 16:49:04 +00002653 // show all of the threads in the core file and explore the crashed state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002654 SetPrivateState(eStateStopped);
Greg Claytona97c4d22014-12-09 23:31:02 +00002655
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002656 // Wait for a stopped event since we just posted one above...
Kate Stoneb9c1b512016-09-06 20:57:50 +00002657 lldb::EventSP event_sp;
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002658 StateType state =
2659 WaitForProcessToStop(seconds(10), &event_sp, true, listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002660
2661 if (!StateIsStoppedState(state, false)) {
2662 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2663 if (log)
2664 log->Printf("Process::Halt() failed to stop, state is: %s",
2665 StateAsCString(state));
2666 error.SetErrorString(
2667 "Did not get stopped event after loading the core file.");
2668 }
2669 RestoreProcessEvents();
2670 }
2671 return error;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002672}
2673
Kate Stoneb9c1b512016-09-06 20:57:50 +00002674DynamicLoader *Process::GetDynamicLoader() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002675 if (!m_dyld_up)
2676 m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr));
2677 return m_dyld_up.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002678}
2679
2680const lldb::DataBufferSP Process::GetAuxvData() { return DataBufferSP(); }
2681
2682JITLoaderList &Process::GetJITLoaders() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002683 if (!m_jit_loaders_up) {
2684 m_jit_loaders_up.reset(new JITLoaderList());
2685 JITLoader::LoadPlugins(this, *m_jit_loaders_up);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002686 }
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002687 return *m_jit_loaders_up;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002688}
2689
2690SystemRuntime *Process::GetSystemRuntime() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002691 if (!m_system_runtime_up)
2692 m_system_runtime_up.reset(SystemRuntime::FindPlugin(this));
2693 return m_system_runtime_up.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002694}
2695
2696Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2697 uint32_t exec_count)
2698 : NextEventAction(process), m_exec_count(exec_count) {
2699 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2700 if (log)
2701 log->Printf(
2702 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2703 __FUNCTION__, static_cast<void *>(process), exec_count);
2704}
2705
2706Process::NextEventAction::EventActionResult
2707Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2708 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2709
2710 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2711 if (log)
2712 log->Printf(
2713 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2714 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
2715
2716 switch (state) {
2717 case eStateAttaching:
2718 return eEventActionSuccess;
2719
2720 case eStateRunning:
2721 case eStateConnected:
2722 return eEventActionRetry;
2723
2724 case eStateStopped:
2725 case eStateCrashed:
2726 // During attach, prior to sending the eStateStopped event,
2727 // lldb_private::Process subclasses must set the new process ID.
2728 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Adrian Prantl05097242018-04-30 16:49:04 +00002729 // We don't want these events to be reported, so go set the
2730 // ShouldReportStop here:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002731 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2732
2733 if (m_exec_count > 0) {
2734 --m_exec_count;
2735
2736 if (log)
2737 log->Printf("Process::AttachCompletionHandler::%s state %s: reduced "
2738 "remaining exec count to %" PRIu32 ", requesting resume",
2739 __FUNCTION__, StateAsCString(state), m_exec_count);
2740
2741 RequestResume();
2742 return eEventActionRetry;
2743 } else {
2744 if (log)
2745 log->Printf("Process::AttachCompletionHandler::%s state %s: no more "
2746 "execs expected to start, continuing with attach",
2747 __FUNCTION__, StateAsCString(state));
2748
2749 m_process->CompleteAttach();
2750 return eEventActionSuccess;
2751 }
2752 break;
2753
2754 default:
2755 case eStateExited:
2756 case eStateInvalid:
2757 break;
2758 }
2759
2760 m_exit_string.assign("No valid Process");
2761 return eEventActionExit;
2762}
2763
2764Process::NextEventAction::EventActionResult
2765Process::AttachCompletionHandler::HandleBeingInterrupted() {
2766 return eEventActionSuccess;
2767}
2768
2769const char *Process::AttachCompletionHandler::GetExitString() {
2770 return m_exit_string.c_str();
2771}
2772
2773ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
2774 if (m_listener_sp)
2775 return m_listener_sp;
2776 else
2777 return debugger.GetListener();
2778}
2779
Zachary Turner97206d52017-05-12 04:51:55 +00002780Status Process::Attach(ProcessAttachInfo &attach_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002781 m_abi_sp.reset();
2782 m_process_input_reader.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002783 m_dyld_up.reset();
2784 m_jit_loaders_up.reset();
2785 m_system_runtime_up.reset();
2786 m_os_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002787
2788 lldb::pid_t attach_pid = attach_info.GetProcessID();
Zachary Turner97206d52017-05-12 04:51:55 +00002789 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002790 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;
Pavel Labathc4a33952017-02-20 11:35:33 +00002833 match_info.SetNameMatchType(NameMatch::Equals);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002834 platform_sp->FindProcesses(match_info, process_infos);
2835 const uint32_t num_matches = process_infos.GetSize();
2836 if (num_matches == 1) {
2837 attach_pid = process_infos.GetProcessIDAtIndex(0);
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;
Pavel Labathaa51e6a2019-03-04 18:48:00 +00002844 ProcessInstanceInfo::DumpTableHeader(s, true, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002845 for (size_t i = 0; i < num_matches; i++) {
2846 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(
Pavel Labathaa51e6a2019-03-04 18:48:00 +00002847 s, platform_sp->GetUserIDResolver(), true, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002848 }
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 {
Greg Clayton71337622011-02-24 22:24:29 +00002887 if (GetID() != LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002888 SetID(LLDB_INVALID_PROCESS_ID);
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00002889
Kate Stoneb9c1b512016-09-06 20:57:50 +00002890 const char *error_string = error.AsCString();
2891 if (error_string == nullptr)
2892 error_string = "attach failed";
Greg Clayton32e0a752011-03-30 18:16:51 +00002893
Kate Stoneb9c1b512016-09-06 20:57:50 +00002894 SetExitStatus(-1, error_string);
2895 }
Greg Claytonb766a732011-02-04 01:58:07 +00002896 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002897 }
2898 return error;
Greg Claytonb766a732011-02-04 01:58:07 +00002899}
2900
Kate Stoneb9c1b512016-09-06 20:57:50 +00002901void Process::CompleteAttach() {
2902 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
2903 LIBLLDB_LOG_TARGET));
2904 if (log)
2905 log->Printf("Process::%s()", __FUNCTION__);
2906
2907 // Let the process subclass figure out at much as it can about the process
2908 // before we go looking for a dynamic loader plug-in.
2909 ArchSpec process_arch;
2910 DidAttach(process_arch);
2911
2912 if (process_arch.IsValid()) {
2913 GetTarget().SetArchitecture(process_arch);
2914 if (log) {
2915 const char *triple_str = process_arch.GetTriple().getTriple().c_str();
2916 log->Printf("Process::%s replacing process architecture with DidAttach() "
2917 "architecture: %s",
2918 __FUNCTION__, triple_str ? triple_str : "<null>");
2919 }
2920 }
2921
2922 // We just attached. If we have a platform, ask it for the process
Adrian Prantl05097242018-04-30 16:49:04 +00002923 // architecture, and if it isn't the same as the one we've already set,
2924 // switch architectures.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002925 PlatformSP platform_sp(GetTarget().GetPlatform());
2926 assert(platform_sp);
2927 if (platform_sp) {
2928 const ArchSpec &target_arch = GetTarget().GetArchitecture();
2929 if (target_arch.IsValid() &&
2930 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
2931 ArchSpec platform_arch;
2932 platform_sp =
2933 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
2934 if (platform_sp) {
2935 GetTarget().SetPlatform(platform_sp);
2936 GetTarget().SetArchitecture(platform_arch);
2937 if (log)
2938 log->Printf("Process::%s switching platform to %s and architecture "
2939 "to %s based on info from attach",
2940 __FUNCTION__, platform_sp->GetName().AsCString(""),
2941 platform_arch.GetTriple().getTriple().c_str());
2942 }
2943 } else if (!process_arch.IsValid()) {
2944 ProcessInstanceInfo process_info;
2945 GetProcessInfo(process_info);
2946 const ArchSpec &process_arch = process_info.GetArchitecture();
2947 if (process_arch.IsValid() &&
2948 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
2949 GetTarget().SetArchitecture(process_arch);
2950 if (log)
2951 log->Printf("Process::%s switching architecture to %s based on info "
2952 "the platform retrieved for pid %" PRIu64,
2953 __FUNCTION__,
2954 process_arch.GetTriple().getTriple().c_str(), GetID());
2955 }
2956 }
2957 }
2958
2959 // We have completed the attach, now it is time to find the dynamic loader
2960 // plug-in
2961 DynamicLoader *dyld = GetDynamicLoader();
2962 if (dyld) {
2963 dyld->DidAttach();
2964 if (log) {
2965 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
2966 log->Printf("Process::%s after DynamicLoader::DidAttach(), target "
2967 "executable is %s (using %s plugin)",
2968 __FUNCTION__,
2969 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
2970 : "<none>",
2971 dyld->GetPluginName().AsCString("<unnamed>"));
2972 }
2973 }
2974
2975 GetJITLoaders().DidAttach();
2976
2977 SystemRuntime *system_runtime = GetSystemRuntime();
2978 if (system_runtime) {
2979 system_runtime->DidAttach();
2980 if (log) {
2981 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
2982 log->Printf("Process::%s after SystemRuntime::DidAttach(), target "
2983 "executable is %s (using %s plugin)",
2984 __FUNCTION__,
2985 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
2986 : "<none>",
2987 system_runtime->GetPluginName().AsCString("<unnamed>"));
2988 }
2989 }
2990
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002991 if (!m_os_up)
Greg Clayton29eeea02017-02-09 18:55:41 +00002992 LoadOperatingSystemPlugin(false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002993 // Figure out which one is the executable, and set that in our target:
2994 const ModuleList &target_modules = GetTarget().GetImages();
2995 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
2996 size_t num_modules = target_modules.GetSize();
2997 ModuleSP new_executable_module_sp;
2998
2999 for (size_t i = 0; i < num_modules; i++) {
3000 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
3001 if (module_sp && module_sp->IsExecutable()) {
3002 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3003 new_executable_module_sp = module_sp;
3004 break;
3005 }
3006 }
3007 if (new_executable_module_sp) {
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00003008 GetTarget().SetExecutableModule(new_executable_module_sp,
3009 eLoadDependentsNo);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003010 if (log) {
3011 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3012 log->Printf(
3013 "Process::%s after looping through modules, target executable is %s",
3014 __FUNCTION__,
3015 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3016 : "<none>");
3017 }
3018 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003019}
3020
Zachary Turner97206d52017-05-12 04:51:55 +00003021Status Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003022 m_abi_sp.reset();
3023 m_process_input_reader.reset();
3024
3025 // Find the process and its architecture. Make sure it matches the
Zachary Turner31659452016-11-17 21:15:14 +00003026 // architecture of the current Target, and if not adjust it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003027
Zachary Turner97206d52017-05-12 04:51:55 +00003028 Status error(DoConnectRemote(strm, remote_url));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003029 if (error.Success()) {
3030 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3031 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003032 StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003033
3034 if (state == eStateStopped || state == eStateCrashed) {
3035 // If we attached and actually have a process on the other end, then
3036 // this ended up being the equivalent of an attach.
3037 CompleteAttach();
3038
3039 // This delays passing the stopped event to listeners till
3040 // CompleteAttach gets a chance to complete...
3041 HandlePrivateEvent(event_sp);
3042 }
3043 }
3044
3045 if (PrivateStateThreadIsValid())
3046 ResumePrivateStateThread();
3047 else
3048 StartPrivateStateThread();
3049 }
3050 return error;
3051}
3052
Zachary Turner97206d52017-05-12 04:51:55 +00003053Status Process::PrivateResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003054 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3055 LIBLLDB_LOG_STEP));
3056 if (log)
3057 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s "
3058 "private state: %s",
3059 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3060 StateAsCString(m_private_state.GetValue()));
3061
Adrian Prantl05097242018-04-30 16:49:04 +00003062 // If signals handing status changed we might want to update our signal
3063 // filters before resuming.
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003064 UpdateAutomaticSignalFiltering();
3065
Zachary Turner97206d52017-05-12 04:51:55 +00003066 Status error(WillResume());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003067 // Tell the process it is about to resume before the thread list
3068 if (error.Success()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003069 // Now let the thread list know we are about to resume so it can let all of
3070 // our threads know that they are about to be resumed. Threads will each be
3071 // called with Thread::WillResume(StateType) where StateType contains the
3072 // state that they are supposed to have when the process is resumed
3073 // (suspended/running/stepping). Threads should also check their resume
3074 // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
3075 // start back up with a signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003076 if (m_thread_list.WillResume()) {
3077 // Last thing, do the PreResumeActions.
3078 if (!RunPreResumeActions()) {
3079 error.SetErrorStringWithFormat(
3080 "Process::PrivateResume PreResumeActions failed, not resuming.");
3081 } else {
3082 m_mod_id.BumpResumeID();
3083 error = DoResume();
3084 if (error.Success()) {
3085 DidResume();
3086 m_thread_list.DidResume();
3087 if (log)
3088 log->Printf("Process thinks the process has resumed.");
Jason Molendaf47c7342018-12-17 23:33:40 +00003089 } else {
3090 if (log)
3091 log->Printf(
3092 "Process::PrivateResume() DoResume failed.");
3093 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003094 }
3095 }
3096 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00003097 // Somebody wanted to run without running (e.g. we were faking a step
3098 // from one frame of a set of inlined frames that share the same PC to
3099 // another.) So generate a continue & a stopped event, and let the world
3100 // handle them.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003101 if (log)
3102 log->Printf(
3103 "Process::PrivateResume() asked to simulate a start & stop.");
3104
3105 SetPrivateState(eStateRunning);
3106 SetPrivateState(eStateStopped);
3107 }
3108 } else if (log)
3109 log->Printf("Process::PrivateResume() got an error \"%s\".",
3110 error.AsCString("<unknown error>"));
3111 return error;
3112}
3113
Zachary Turner97206d52017-05-12 04:51:55 +00003114Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003115 if (!StateIsRunningState(m_public_state.GetValue()))
Zachary Turner97206d52017-05-12 04:51:55 +00003116 return Status("Process is not running.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003117
Adrian Prantl05097242018-04-30 16:49:04 +00003118 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
3119 // case it was already set and some thread plan logic calls halt on its own.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003120 m_clear_thread_plans_on_stop |= clear_thread_plans;
3121
3122 ListenerSP halt_listener_sp(
3123 Listener::MakeListener("lldb.process.halt_listener"));
3124 HijackProcessEvents(halt_listener_sp);
3125
3126 EventSP event_sp;
3127
3128 SendAsyncInterrupt();
3129
3130 if (m_public_state.GetValue() == eStateAttaching) {
Adrian Prantl05097242018-04-30 16:49:04 +00003131 // Don't hijack and eat the eStateExited as the code that was doing the
3132 // attach will be waiting for this event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003133 RestoreProcessEvents();
3134 SetExitStatus(SIGKILL, "Cancelled async attach.");
3135 Destroy(false);
Zachary Turner97206d52017-05-12 04:51:55 +00003136 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003137 }
3138
3139 // Wait for 10 second for the process to stop.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003140 StateType state = WaitForProcessToStop(
3141 seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003142 RestoreProcessEvents();
3143
3144 if (state == eStateInvalid || !event_sp) {
3145 // We timed out and didn't get a stop event...
Zachary Turner97206d52017-05-12 04:51:55 +00003146 return Status("Halt timed out. State = %s", StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003147 }
3148
3149 BroadcastEvent(event_sp);
3150
Zachary Turner97206d52017-05-12 04:51:55 +00003151 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003152}
3153
Zachary Turner97206d52017-05-12 04:51:55 +00003154Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3155 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003156
3157 // Check both the public & private states here. If we're hung evaluating an
Adrian Prantl05097242018-04-30 16:49:04 +00003158 // expression, for instance, then the public state will be stopped, but we
3159 // still need to interrupt.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003160 if (m_public_state.GetValue() == eStateRunning ||
3161 m_private_state.GetValue() == eStateRunning) {
3162 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003163 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003164 log->Printf("Process::%s() About to stop.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003165
Kate Stoneb9c1b512016-09-06 20:57:50 +00003166 ListenerSP listener_sp(
3167 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3168 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003169
Pavel Labath19da1f12015-12-07 12:36:52 +00003170 SendAsyncInterrupt();
3171
Kate Stoneb9c1b512016-09-06 20:57:50 +00003172 // Consume the interrupt event.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003173 StateType state =
3174 WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003175
Pavel Labath19da1f12015-12-07 12:36:52 +00003176 RestoreProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003177
Kate Stoneb9c1b512016-09-06 20:57:50 +00003178 // If the process exited while we were waiting for it to stop, put the
Adrian Prantl05097242018-04-30 16:49:04 +00003179 // exited event into the shared pointer passed in and return. Our caller
3180 // doesn't need to do anything else, since they don't have a process
3181 // anymore...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003182
3183 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
3184 if (log)
3185 log->Printf("Process::%s() Process exited while waiting to stop.",
3186 __FUNCTION__);
3187 return error;
3188 } else
3189 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3190
3191 if (state != eStateStopped) {
3192 if (log)
3193 log->Printf("Process::%s() failed to stop, state is: %s", __FUNCTION__,
3194 StateAsCString(state));
3195 // If we really couldn't stop the process then we should just error out
Adrian Prantl05097242018-04-30 16:49:04 +00003196 // here, but if the lower levels just bobbled sending the event and we
3197 // really are stopped, then continue on.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003198 StateType private_state = m_private_state.GetValue();
3199 if (private_state != eStateStopped) {
Zachary Turner97206d52017-05-12 04:51:55 +00003200 return Status(
3201 "Attempt to stop the target in order to detach timed out. "
3202 "State = %s",
3203 StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003204 }
3205 }
3206 }
3207 return error;
3208}
3209
Zachary Turner97206d52017-05-12 04:51:55 +00003210Status Process::Detach(bool keep_stopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003211 EventSP exit_event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003212 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003213 m_destroy_in_process = true;
3214
3215 error = WillDetach();
3216
3217 if (error.Success()) {
3218 if (DetachRequiresHalt()) {
3219 error = StopForDestroyOrDetach(exit_event_sp);
3220 if (!error.Success()) {
3221 m_destroy_in_process = false;
3222 return error;
3223 } else if (exit_event_sp) {
3224 // We shouldn't need to do anything else here. There's no process left
3225 // to detach from...
3226 StopPrivateStateThread();
3227 m_destroy_in_process = false;
3228 return error;
3229 }
3230 }
3231
3232 m_thread_list.DiscardThreadPlans();
3233 DisableAllBreakpointSites();
3234
3235 error = DoDetach(keep_stopped);
3236 if (error.Success()) {
3237 DidDetach();
3238 StopPrivateStateThread();
3239 } else {
3240 return error;
3241 }
3242 }
3243 m_destroy_in_process = false;
3244
Adrian Prantl05097242018-04-30 16:49:04 +00003245 // If we exited when we were waiting for a process to stop, then forward the
3246 // event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003247 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003248 // Directly broadcast our exited event because we shut down our private
3249 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003250 BroadcastEvent(exit_event_sp);
3251 }
3252
3253 // If we have been interrupted (to kill us) in the middle of running, we may
Adrian Prantl05097242018-04-30 16:49:04 +00003254 // not end up propagating the last events through the event system, in which
3255 // case we might strand the write lock. Unlock it here so when we do to tear
3256 // down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003257
3258 m_public_run_lock.SetStopped();
3259 return error;
3260}
3261
Zachary Turner97206d52017-05-12 04:51:55 +00003262Status Process::Destroy(bool force_kill) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003263
3264 // Tell ourselves we are in the process of destroying the process, so that we
Adrian Prantl05097242018-04-30 16:49:04 +00003265 // don't do any unnecessary work that might hinder the destruction. Remember
3266 // to set this back to false when we are done. That way if the attempt
Kate Stoneb9c1b512016-09-06 20:57:50 +00003267 // failed and the process stays around for some reason it won't be in a
3268 // confused state.
3269
3270 if (force_kill)
3271 m_should_detach = false;
3272
3273 if (GetShouldDetach()) {
3274 // FIXME: This will have to be a process setting:
3275 bool keep_stopped = false;
3276 Detach(keep_stopped);
3277 }
3278
3279 m_destroy_in_process = true;
3280
Zachary Turner97206d52017-05-12 04:51:55 +00003281 Status error(WillDestroy());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003282 if (error.Success()) {
3283 EventSP exit_event_sp;
3284 if (DestroyRequiresHalt()) {
3285 error = StopForDestroyOrDetach(exit_event_sp);
3286 }
3287
3288 if (m_public_state.GetValue() != eStateRunning) {
Adrian Prantl05097242018-04-30 16:49:04 +00003289 // Ditch all thread plans, and remove all our breakpoints: in case we
3290 // have to restart the target to kill it, we don't want it hitting a
3291 // breakpoint... Only do this if we've stopped, however, since if we
3292 // didn't manage to halt it above, then we're not going to have much luck
3293 // doing this now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003294 m_thread_list.DiscardThreadPlans();
3295 DisableAllBreakpointSites();
3296 }
3297
3298 error = DoDestroy();
3299 if (error.Success()) {
3300 DidDestroy();
3301 StopPrivateStateThread();
3302 }
3303 m_stdio_communication.Disconnect();
3304 m_stdio_communication.StopReadThread();
3305 m_stdin_forward = false;
3306
3307 if (m_process_input_reader) {
3308 m_process_input_reader->SetIsDone(true);
3309 m_process_input_reader->Cancel();
3310 m_process_input_reader.reset();
3311 }
3312
Adrian Prantl05097242018-04-30 16:49:04 +00003313 // If we exited when we were waiting for a process to stop, then forward
3314 // the event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003315 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003316 // Directly broadcast our exited event because we shut down our private
3317 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003318 BroadcastEvent(exit_event_sp);
3319 }
3320
Adrian Prantl05097242018-04-30 16:49:04 +00003321 // If we have been interrupted (to kill us) in the middle of running, we
3322 // may not end up propagating the last events through the event system, in
3323 // which case we might strand the write lock. Unlock it here so when we do
3324 // to tear down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003325 m_public_run_lock.SetStopped();
3326 }
3327
3328 m_destroy_in_process = false;
3329
3330 return error;
3331}
3332
Zachary Turner97206d52017-05-12 04:51:55 +00003333Status Process::Signal(int signal) {
3334 Status error(WillSignal());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003335 if (error.Success()) {
3336 error = DoSignal(signal);
3337 if (error.Success())
3338 DidSignal();
3339 }
3340 return error;
3341}
3342
3343void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3344 assert(signals_sp && "null signals_sp");
3345 m_unix_signals_sp = signals_sp;
3346}
3347
3348const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3349 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3350 return m_unix_signals_sp;
3351}
3352
3353lldb::ByteOrder Process::GetByteOrder() const {
3354 return GetTarget().GetArchitecture().GetByteOrder();
3355}
3356
3357uint32_t Process::GetAddressByteSize() const {
3358 return GetTarget().GetArchitecture().GetAddressByteSize();
3359}
3360
3361bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3362 const StateType state =
3363 Process::ProcessEventData::GetStateFromEvent(event_ptr);
3364 bool return_value = true;
3365 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3366 LIBLLDB_LOG_PROCESS));
3367
3368 switch (state) {
3369 case eStateDetached:
3370 case eStateExited:
3371 case eStateUnloaded:
3372 m_stdio_communication.SynchronizeWithReadThread();
3373 m_stdio_communication.Disconnect();
3374 m_stdio_communication.StopReadThread();
3375 m_stdin_forward = false;
3376
3377 LLVM_FALLTHROUGH;
3378 case eStateConnected:
3379 case eStateAttaching:
3380 case eStateLaunching:
3381 // These events indicate changes in the state of the debugging session,
3382 // always report them.
3383 return_value = true;
3384 break;
3385 case eStateInvalid:
3386 // We stopped for no apparent reason, don't report it.
3387 return_value = false;
3388 break;
3389 case eStateRunning:
3390 case eStateStepping:
Adrian Prantl05097242018-04-30 16:49:04 +00003391 // If we've started the target running, we handle the cases where we are
3392 // already running and where there is a transition from stopped to running
3393 // differently. running -> running: Automatically suppress extra running
3394 // events stopped -> running: Report except when there is one or more no
3395 // votes
Kate Stoneb9c1b512016-09-06 20:57:50 +00003396 // and no yes votes.
3397 SynchronouslyNotifyStateChanged(state);
3398 if (m_force_next_event_delivery)
3399 return_value = true;
3400 else {
3401 switch (m_last_broadcast_state) {
3402 case eStateRunning:
3403 case eStateStepping:
3404 // We always suppress multiple runnings with no PUBLIC stop in between.
3405 return_value = false;
3406 break;
3407 default:
3408 // TODO: make this work correctly. For now always report
Adrian Prantl05097242018-04-30 16:49:04 +00003409 // run if we aren't running so we don't miss any running events. If I
3410 // run the lldb/test/thread/a.out file and break at main.cpp:58, run
3411 // and hit the breakpoints on multiple threads, then somehow during the
3412 // stepping over of all breakpoints no run gets reported.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003413
3414 // This is a transition from stop to run.
3415 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3416 case eVoteYes:
3417 case eVoteNoOpinion:
3418 return_value = true;
3419 break;
3420 case eVoteNo:
3421 return_value = false;
3422 break;
3423 }
3424 break;
3425 }
3426 }
3427 break;
3428 case eStateStopped:
3429 case eStateCrashed:
3430 case eStateSuspended:
Adrian Prantl05097242018-04-30 16:49:04 +00003431 // We've stopped. First see if we're going to restart the target. If we
3432 // are going to stop, then we always broadcast the event. If we aren't
3433 // going to stop, let the thread plans decide if we're going to report this
3434 // event. If no thread has an opinion, we don't report it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003435
3436 m_stdio_communication.SynchronizeWithReadThread();
3437 RefreshStateAfterStop();
3438 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
3439 if (log)
3440 log->Printf("Process::ShouldBroadcastEvent (%p) stopped due to an "
3441 "interrupt, state: %s",
3442 static_cast<void *>(event_ptr), StateAsCString(state));
3443 // Even though we know we are going to stop, we should let the threads
Adrian Prantl05097242018-04-30 16:49:04 +00003444 // have a look at the stop, so they can properly set their state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003445 m_thread_list.ShouldStop(event_ptr);
3446 return_value = true;
3447 } else {
3448 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3449 bool should_resume = false;
3450
3451 // It makes no sense to ask "ShouldStop" if we've already been
Adrian Prantl05097242018-04-30 16:49:04 +00003452 // restarted... Asking the thread list is also not likely to go well,
3453 // since we are running again. So in that case just report the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003454
3455 if (!was_restarted)
3456 should_resume = !m_thread_list.ShouldStop(event_ptr);
3457
3458 if (was_restarted || should_resume || m_resume_requested) {
3459 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
3460 if (log)
3461 log->Printf("Process::ShouldBroadcastEvent: should_resume: %i state: "
3462 "%s was_restarted: %i stop_vote: %d.",
3463 should_resume, StateAsCString(state), was_restarted,
3464 stop_vote);
3465
3466 switch (stop_vote) {
3467 case eVoteYes:
3468 return_value = true;
3469 break;
3470 case eVoteNoOpinion:
3471 case eVoteNo:
3472 return_value = false;
3473 break;
3474 }
3475
3476 if (!was_restarted) {
3477 if (log)
3478 log->Printf("Process::ShouldBroadcastEvent (%p) Restarting process "
3479 "from state: %s",
3480 static_cast<void *>(event_ptr), StateAsCString(state));
3481 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3482 PrivateResume();
3483 }
3484 } else {
3485 return_value = true;
3486 SynchronouslyNotifyStateChanged(state);
3487 }
3488 }
3489 break;
3490 }
3491
3492 // Forcing the next event delivery is a one shot deal. So reset it here.
3493 m_force_next_event_delivery = false;
3494
3495 // We do some coalescing of events (for instance two consecutive running
Adrian Prantl05097242018-04-30 16:49:04 +00003496 // events get coalesced.) But we only coalesce against events we actually
3497 // broadcast. So we use m_last_broadcast_state to track that. NB - you
3498 // can't use "m_public_state.GetValue()" for that purpose, as was originally
3499 // done, because the PublicState reflects the last event pulled off the
3500 // queue, and there may be several events stacked up on the queue unserviced.
3501 // So the PublicState may not reflect the last broadcasted event yet.
3502 // m_last_broadcast_state gets updated here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003503
3504 if (return_value)
3505 m_last_broadcast_state = state;
3506
3507 if (log)
3508 log->Printf("Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3509 "broadcast state: %s - %s",
3510 static_cast<void *>(event_ptr), StateAsCString(state),
3511 StateAsCString(m_last_broadcast_state),
3512 return_value ? "YES" : "NO");
3513 return return_value;
3514}
3515
3516bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3517 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3518
3519 bool already_running = PrivateStateThreadIsValid();
3520 if (log)
3521 log->Printf("Process::%s()%s ", __FUNCTION__,
3522 already_running ? " already running"
3523 : " starting private state thread");
3524
3525 if (!is_secondary_thread && already_running)
3526 return true;
3527
Adrian Prantl05097242018-04-30 16:49:04 +00003528 // Create a thread that watches our internal state and controls which events
3529 // make it to clients (into the DCProcess event queue).
Kate Stoneb9c1b512016-09-06 20:57:50 +00003530 char thread_name[1024];
Zachary Turner777de772017-03-04 16:42:25 +00003531 uint32_t max_len = llvm::get_max_thread_name_length();
3532 if (max_len > 0 && max_len <= 30) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003533 // On platforms with abbreviated thread name lengths, choose thread names
3534 // that fit within the limit.
3535 if (already_running)
3536 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3537 else
3538 snprintf(thread_name, sizeof(thread_name), "intern-state");
3539 } else {
3540 if (already_running)
3541 snprintf(thread_name, sizeof(thread_name),
3542 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3543 GetID());
3544 else
3545 snprintf(thread_name, sizeof(thread_name),
3546 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3547 }
3548
3549 // Create the private state thread, and start it running.
3550 PrivateStateThreadArgs *args_ptr =
3551 new PrivateStateThreadArgs(this, is_secondary_thread);
3552 m_private_state_thread =
3553 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
3554 (void *)args_ptr, nullptr, 8 * 1024 * 1024);
3555 if (m_private_state_thread.IsJoinable()) {
3556 ResumePrivateStateThread();
3557 return true;
3558 } else
3559 return false;
3560}
3561
3562void Process::PausePrivateStateThread() {
3563 ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3564}
3565
3566void Process::ResumePrivateStateThread() {
3567 ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3568}
3569
3570void Process::StopPrivateStateThread() {
3571 if (m_private_state_thread.IsJoinable())
3572 ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3573 else {
3574 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3575 if (log)
3576 log->Printf(
3577 "Went to stop the private state thread, but it was already invalid.");
3578 }
3579}
3580
3581void Process::ControlPrivateStateThread(uint32_t signal) {
3582 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3583
3584 assert(signal == eBroadcastInternalStateControlStop ||
3585 signal == eBroadcastInternalStateControlPause ||
3586 signal == eBroadcastInternalStateControlResume);
3587
3588 if (log)
3589 log->Printf("Process::%s (signal = %d)", __FUNCTION__, signal);
3590
3591 // Signal the private state thread
3592 if (m_private_state_thread.IsJoinable()) {
3593 // Broadcast the event.
Adrian Prantl05097242018-04-30 16:49:04 +00003594 // It is important to do this outside of the if below, because it's
3595 // possible that the thread state is invalid but that the thread is waiting
3596 // on a control event instead of simply being on its way out (this should
3597 // not happen, but it apparently can).
Kate Stoneb9c1b512016-09-06 20:57:50 +00003598 if (log)
3599 log->Printf("Sending control event of type: %d.", signal);
3600 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3601 m_private_state_control_broadcaster.BroadcastEvent(signal,
3602 event_receipt_sp);
3603
3604 // Wait for the event receipt or for the private state thread to exit
3605 bool receipt_received = false;
3606 if (PrivateStateThreadIsValid()) {
3607 while (!receipt_received) {
Adrian Prantl05097242018-04-30 16:49:04 +00003608 // Check for a receipt for 2 seconds and then check if the private
3609 // state thread is still around.
Pavel Labath38d67db2018-05-03 15:33:41 +00003610 receipt_received =
3611 event_receipt_sp->WaitForEventReceived(std::chrono::seconds(2));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003612 if (!receipt_received) {
Adrian Prantl05097242018-04-30 16:49:04 +00003613 // Check if the private state thread is still around. If it isn't
3614 // then we are done waiting
Kate Stoneb9c1b512016-09-06 20:57:50 +00003615 if (!PrivateStateThreadIsValid())
3616 break; // Private state thread exited or is exiting, we are done
3617 }
3618 }
3619 }
3620
3621 if (signal == eBroadcastInternalStateControlStop) {
3622 thread_result_t result = NULL;
3623 m_private_state_thread.Join(&result);
3624 m_private_state_thread.Reset();
3625 }
3626 } else {
3627 if (log)
3628 log->Printf(
3629 "Private state thread already dead, no need to signal it to stop.");
3630 }
3631}
3632
3633void Process::SendAsyncInterrupt() {
3634 if (PrivateStateThreadIsValid())
3635 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3636 nullptr);
3637 else
3638 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3639}
3640
3641void Process::HandlePrivateEvent(EventSP &event_sp) {
3642 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3643 m_resume_requested = false;
3644
3645 const StateType new_state =
3646 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3647
3648 // First check to see if anybody wants a shot at this event:
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003649 if (m_next_event_action_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003650 NextEventAction::EventActionResult action_result =
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003651 m_next_event_action_up->PerformAction(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003652 if (log)
3653 log->Printf("Ran next event action, result was %d.", action_result);
3654
3655 switch (action_result) {
3656 case NextEventAction::eEventActionSuccess:
3657 SetNextEventAction(nullptr);
3658 break;
3659
3660 case NextEventAction::eEventActionRetry:
3661 break;
3662
3663 case NextEventAction::eEventActionExit:
Adrian Prantl05097242018-04-30 16:49:04 +00003664 // Handle Exiting Here. If we already got an exited event, we should
3665 // just propagate it. Otherwise, swallow this event, and set our state
3666 // to exit so the next event will kill us.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003667 if (new_state != eStateExited) {
3668 // FIXME: should cons up an exited event, and discard this one.
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003669 SetExitStatus(0, m_next_event_action_up->GetExitString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003670 SetNextEventAction(nullptr);
3671 return;
3672 }
3673 SetNextEventAction(nullptr);
3674 break;
3675 }
3676 }
3677
3678 // See if we should broadcast this state to external clients?
3679 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3680
3681 if (should_broadcast) {
3682 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3683 if (log) {
3684 log->Printf("Process::%s (pid = %" PRIu64
3685 ") broadcasting new state %s (old state %s) to %s",
3686 __FUNCTION__, GetID(), StateAsCString(new_state),
3687 StateAsCString(GetState()),
3688 is_hijacked ? "hijacked" : "public");
3689 }
3690 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3691 if (StateIsRunningState(new_state)) {
Adrian Prantl05097242018-04-30 16:49:04 +00003692 // Only push the input handler if we aren't fowarding events, as this
3693 // means the curses GUI is in use... Or don't push it if we are launching
3694 // since it will come up stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003695 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3696 new_state != eStateLaunching && new_state != eStateAttaching) {
3697 PushProcessIOHandler();
3698 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3699 eBroadcastAlways);
3700 if (log)
3701 log->Printf("Process::%s updated m_iohandler_sync to %d",
3702 __FUNCTION__, m_iohandler_sync.GetValue());
3703 }
3704 } else if (StateIsStoppedState(new_state, false)) {
3705 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
Adrian Prantl05097242018-04-30 16:49:04 +00003706 // If the lldb_private::Debugger is handling the events, we don't want
3707 // to pop the process IOHandler here, we want to do it when we receive
3708 // the stopped event so we can carefully control when the process
3709 // IOHandler is popped because when we stop we want to display some
3710 // text stating how and why we stopped, then maybe some
3711 // process/thread/frame info, and then we want the "(lldb) " prompt to
3712 // show up. If we pop the process IOHandler here, then we will cause
3713 // the command interpreter to become the top IOHandler after the
3714 // process pops off and it will update its prompt right away... See the
3715 // Debugger.cpp file where it calls the function as
Kate Stoneb9c1b512016-09-06 20:57:50 +00003716 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3717 // Otherwise we end up getting overlapping "(lldb) " prompts and
3718 // garbled output.
3719 //
3720 // If we aren't handling the events in the debugger (which is indicated
Adrian Prantl05097242018-04-30 16:49:04 +00003721 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
3722 // we are hijacked, then we always pop the process IO handler manually.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003723 // Hijacking happens when the internal process state thread is running
Adrian Prantl05097242018-04-30 16:49:04 +00003724 // thread plans, or when commands want to run in synchronous mode and
3725 // they call "process->WaitForProcessToStop()". An example of something
Kate Stoneb9c1b512016-09-06 20:57:50 +00003726 // that will hijack the events is a simple expression:
3727 //
3728 // (lldb) expr (int)puts("hello")
3729 //
3730 // This will cause the internal process state thread to resume and halt
3731 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3732 // events) and we do need the IO handler to be pushed and popped
3733 // correctly.
3734
3735 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3736 PopProcessIOHandler();
3737 }
Pavel Labath19da1f12015-12-07 12:36:52 +00003738 }
3739
3740 BroadcastEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003741 } else {
3742 if (log) {
3743 log->Printf(
3744 "Process::%s (pid = %" PRIu64
3745 ") suppressing state %s (old state %s): should_broadcast == false",
3746 __FUNCTION__, GetID(), StateAsCString(new_state),
3747 StateAsCString(GetState()));
3748 }
3749 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003750}
3751
Zachary Turner97206d52017-05-12 04:51:55 +00003752Status Process::HaltPrivate() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003753 EventSP event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003754 Status error(WillHalt());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003755 if (error.Fail())
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003756 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003757
3758 // Ask the process subclass to actually halt our process
3759 bool caused_stop;
3760 error = DoHalt(caused_stop);
3761
3762 DidHalt();
3763 return error;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003764}
3765
Kate Stoneb9c1b512016-09-06 20:57:50 +00003766thread_result_t Process::PrivateStateThread(void *arg) {
3767 std::unique_ptr<PrivateStateThreadArgs> args_up(
3768 static_cast<PrivateStateThreadArgs *>(arg));
3769 thread_result_t result =
3770 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
3771 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003772}
3773
Kate Stoneb9c1b512016-09-06 20:57:50 +00003774thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
3775 bool control_only = true;
Pavel Labath19da1f12015-12-07 12:36:52 +00003776
Kate Stoneb9c1b512016-09-06 20:57:50 +00003777 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3778 if (log)
3779 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3780 __FUNCTION__, static_cast<void *>(this), GetID());
Jason Molendaede31932015-04-17 05:01:58 +00003781
Kate Stoneb9c1b512016-09-06 20:57:50 +00003782 bool exit_now = false;
3783 bool interrupt_requested = false;
3784 while (!exit_now) {
Pavel Labath19da1f12015-12-07 12:36:52 +00003785 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003786 GetEventsPrivate(event_sp, llvm::None, control_only);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003787 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
3788 if (log)
3789 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3790 ") got a control event: %d",
3791 __FUNCTION__, static_cast<void *>(this), GetID(),
3792 event_sp->GetType());
Pavel Labath19da1f12015-12-07 12:36:52 +00003793
Kate Stoneb9c1b512016-09-06 20:57:50 +00003794 switch (event_sp->GetType()) {
3795 case eBroadcastInternalStateControlStop:
3796 exit_now = true;
3797 break; // doing any internal state management below
Pavel Labath19da1f12015-12-07 12:36:52 +00003798
Kate Stoneb9c1b512016-09-06 20:57:50 +00003799 case eBroadcastInternalStateControlPause:
3800 control_only = true;
3801 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003802
Kate Stoneb9c1b512016-09-06 20:57:50 +00003803 case eBroadcastInternalStateControlResume:
3804 control_only = false;
3805 break;
3806 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003807
Kate Stoneb9c1b512016-09-06 20:57:50 +00003808 continue;
3809 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
3810 if (m_public_state.GetValue() == eStateAttaching) {
3811 if (log)
3812 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3813 ") woke up with an interrupt while attaching - "
3814 "forwarding interrupt.",
3815 __FUNCTION__, static_cast<void *>(this), GetID());
3816 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
3817 } else if (StateIsRunningState(m_last_broadcast_state)) {
3818 if (log)
3819 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3820 ") woke up with an interrupt - Halting.",
3821 __FUNCTION__, static_cast<void *>(this), GetID());
Zachary Turner97206d52017-05-12 04:51:55 +00003822 Status error = HaltPrivate();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003823 if (error.Fail() && log)
3824 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3825 ") failed to halt the process: %s",
3826 __FUNCTION__, static_cast<void *>(this), GetID(),
3827 error.AsCString());
Adrian Prantl05097242018-04-30 16:49:04 +00003828 // Halt should generate a stopped event. Make a note of the fact that
3829 // we were doing the interrupt, so we can set the interrupted flag
3830 // after we receive the event. We deliberately set this to true even if
3831 // HaltPrivate failed, so that we can interrupt on the next natural
3832 // stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003833 interrupt_requested = true;
3834 } else {
3835 // This can happen when someone (e.g. Process::Halt) sees that we are
Adrian Prantl05097242018-04-30 16:49:04 +00003836 // running and sends an interrupt request, but the process actually
3837 // stops before we receive it. In that case, we can just ignore the
3838 // request. We use m_last_broadcast_state, because the Stopped event
3839 // may not have been popped of the event queue yet, which is when the
3840 // public state gets updated.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003841 if (log)
3842 log->Printf(
3843 "Process::%s ignoring interrupt as we have already stopped.",
3844 __FUNCTION__);
3845 }
3846 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003847 }
3848
Kate Stoneb9c1b512016-09-06 20:57:50 +00003849 const StateType internal_state =
3850 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003851
Kate Stoneb9c1b512016-09-06 20:57:50 +00003852 if (internal_state != eStateInvalid) {
3853 if (m_clear_thread_plans_on_stop &&
3854 StateIsStoppedState(internal_state, true)) {
3855 m_clear_thread_plans_on_stop = false;
3856 m_thread_list.DiscardThreadPlans();
3857 }
3858
3859 if (interrupt_requested) {
3860 if (StateIsStoppedState(internal_state, true)) {
3861 // We requested the interrupt, so mark this as such in the stop event
Adrian Prantl05097242018-04-30 16:49:04 +00003862 // so clients can tell an interrupted process from a natural stop
Kate Stoneb9c1b512016-09-06 20:57:50 +00003863 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
3864 interrupt_requested = false;
3865 } else if (log) {
3866 log->Printf("Process::%s interrupt_requested, but a non-stopped "
3867 "state '%s' received.",
3868 __FUNCTION__, StateAsCString(internal_state));
3869 }
3870 }
3871
3872 HandlePrivateEvent(event_sp);
3873 }
3874
3875 if (internal_state == eStateInvalid || internal_state == eStateExited ||
3876 internal_state == eStateDetached) {
3877 if (log)
3878 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3879 ") about to exit with internal state %s...",
3880 __FUNCTION__, static_cast<void *>(this), GetID(),
3881 StateAsCString(internal_state));
3882
3883 break;
3884 }
3885 }
3886
3887 // Verify log is still enabled before attempting to write to it...
3888 if (log)
3889 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
3890 __FUNCTION__, static_cast<void *>(this), GetID());
3891
3892 // If we are a secondary thread, then the primary thread we are working for
Adrian Prantl05097242018-04-30 16:49:04 +00003893 // will have already acquired the public_run_lock, and isn't done with what
3894 // it was doing yet, so don't try to change it on the way out.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003895 if (!is_secondary_thread)
3896 m_public_run_lock.SetStopped();
3897 return NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003898}
3899
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003900//------------------------------------------------------------------
3901// Process Event Data
3902//------------------------------------------------------------------
3903
Kate Stoneb9c1b512016-09-06 20:57:50 +00003904Process::ProcessEventData::ProcessEventData()
3905 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
3906 m_update_state(0), m_interrupted(false) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003907
Kate Stoneb9c1b512016-09-06 20:57:50 +00003908Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
3909 StateType state)
3910 : EventData(), m_process_wp(), m_state(state), m_restarted(false),
3911 m_update_state(0), m_interrupted(false) {
3912 if (process_sp)
3913 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003914}
3915
Eugene Zelenko8f30a652015-10-23 18:39:37 +00003916Process::ProcessEventData::~ProcessEventData() = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003917
Kate Stoneb9c1b512016-09-06 20:57:50 +00003918const ConstString &Process::ProcessEventData::GetFlavorString() {
3919 static ConstString g_flavor("Process::ProcessEventData");
3920 return g_flavor;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003921}
3922
Kate Stoneb9c1b512016-09-06 20:57:50 +00003923const ConstString &Process::ProcessEventData::GetFlavor() const {
3924 return ProcessEventData::GetFlavorString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003925}
3926
Kate Stoneb9c1b512016-09-06 20:57:50 +00003927void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
3928 ProcessSP process_sp(m_process_wp.lock());
Greg Clayton2e309072015-07-17 23:42:28 +00003929
Kate Stoneb9c1b512016-09-06 20:57:50 +00003930 if (!process_sp)
3931 return;
Greg Claytonf4b47e12010-08-04 01:40:35 +00003932
Kate Stoneb9c1b512016-09-06 20:57:50 +00003933 // This function gets called twice for each event, once when the event gets
Adrian Prantl05097242018-04-30 16:49:04 +00003934 // pulled off of the private process event queue, and then any number of
3935 // times, first when it gets pulled off of the public event queue, then other
3936 // times when we're pretending that this is where we stopped at the end of
3937 // expression evaluation. m_update_state is used to distinguish these three
3938 // cases; it is 0 when we're just pulling it off for private handling, and >
3939 // 1 for expression evaluation, and we don't want to do the breakpoint
Kate Stoneb9c1b512016-09-06 20:57:50 +00003940 // command handling then.
3941 if (m_update_state != 1)
3942 return;
3943
3944 process_sp->SetPublicState(
3945 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
3946
Jason Molendab3a3cd12016-12-08 06:27:29 +00003947 if (m_state == eStateStopped && !m_restarted) {
Adrian Prantl05097242018-04-30 16:49:04 +00003948 // Let process subclasses know we are about to do a public stop and do
3949 // anything they might need to in order to speed up register and memory
3950 // accesses.
Jason Molendab3a3cd12016-12-08 06:27:29 +00003951 process_sp->WillPublicStop();
3952 }
3953
Kate Stoneb9c1b512016-09-06 20:57:50 +00003954 // If this is a halt event, even if the halt stopped with some reason other
Adrian Prantl05097242018-04-30 16:49:04 +00003955 // than a plain interrupt (e.g. we had already stopped for a breakpoint when
3956 // the halt request came through) don't do the StopInfo actions, as they may
Kate Stoneb9c1b512016-09-06 20:57:50 +00003957 // end up restarting the process.
3958 if (m_interrupted)
3959 return;
3960
3961 // If we're stopped and haven't restarted, then do the StopInfo actions here:
3962 if (m_state == eStateStopped && !m_restarted) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003963 ThreadList &curr_thread_list = process_sp->GetThreadList();
3964 uint32_t num_threads = curr_thread_list.GetSize();
3965 uint32_t idx;
3966
3967 // The actions might change one of the thread's stop_info's opinions about
Adrian Prantl05097242018-04-30 16:49:04 +00003968 // whether we should stop the process, so we need to query that as we go.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003969
3970 // One other complication here, is that we try to catch any case where the
Adrian Prantl05097242018-04-30 16:49:04 +00003971 // target has run (except for expressions) and immediately exit, but if we
3972 // get that wrong (which is possible) then the thread list might have
3973 // changed, and that would cause our iteration here to crash. We could
3974 // make a copy of the thread list, but we'd really like to also know if it
3975 // has changed at all, so we make up a vector of the thread ID's and check
3976 // what we get back against this list & bag out if anything differs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003977 std::vector<uint32_t> thread_index_array(num_threads);
3978 for (idx = 0; idx < num_threads; ++idx)
3979 thread_index_array[idx] =
3980 curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3981
3982 // Use this to track whether we should continue from here. We will only
Adrian Prantl05097242018-04-30 16:49:04 +00003983 // continue the target running if no thread says we should stop. Of course
3984 // if some thread's PerformAction actually sets the target running, then it
3985 // doesn't matter what the other threads say...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003986
3987 bool still_should_stop = false;
3988
3989 // Sometimes - for instance if we have a bug in the stub we are talking to,
Adrian Prantl05097242018-04-30 16:49:04 +00003990 // we stop but no thread has a valid stop reason. In that case we should
3991 // just stop, because we have no way of telling what the right thing to do
3992 // is, and it's better to let the user decide than continue behind their
3993 // backs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003994
3995 bool does_anybody_have_an_opinion = false;
3996
3997 for (idx = 0; idx < num_threads; ++idx) {
3998 curr_thread_list = process_sp->GetThreadList();
3999 if (curr_thread_list.GetSize() != num_threads) {
4000 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4001 LIBLLDB_LOG_PROCESS));
4002 if (log)
4003 log->Printf(
4004 "Number of threads changed from %u to %u while processing event.",
4005 num_threads, curr_thread_list.GetSize());
4006 break;
4007 }
4008
4009 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4010
4011 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4012 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4013 LIBLLDB_LOG_PROCESS));
4014 if (log)
4015 log->Printf("The thread at position %u changed from %u to %u while "
4016 "processing event.",
4017 idx, thread_index_array[idx], thread_sp->GetIndexID());
4018 break;
4019 }
4020
4021 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4022 if (stop_info_sp && stop_info_sp->IsValid()) {
4023 does_anybody_have_an_opinion = true;
4024 bool this_thread_wants_to_stop;
4025 if (stop_info_sp->GetOverrideShouldStop()) {
4026 this_thread_wants_to_stop =
4027 stop_info_sp->GetOverriddenShouldStopValue();
4028 } else {
4029 stop_info_sp->PerformAction(event_ptr);
Adrian Prantl05097242018-04-30 16:49:04 +00004030 // The stop action might restart the target. If it does, then we
4031 // want to mark that in the event so that whoever is receiving it
4032 // will know to wait for the running event and reflect that state
4033 // appropriately. We also need to stop processing actions, since they
4034 // aren't expecting the target to be running.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004035
4036 // FIXME: we might have run.
4037 if (stop_info_sp->HasTargetRunSinceMe()) {
4038 SetRestarted(true);
4039 break;
4040 }
4041
4042 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004043 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004044
4045 if (!still_should_stop)
4046 still_should_stop = this_thread_wants_to_stop;
4047 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004048 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004049
4050 if (!GetRestarted()) {
4051 if (!still_should_stop && does_anybody_have_an_opinion) {
4052 // We've been asked to continue, so do that here.
4053 SetRestarted(true);
Adrian Prantl05097242018-04-30 16:49:04 +00004054 // Use the public resume method here, since this is just extending a
4055 // public resume.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004056 process_sp->PrivateResume();
4057 } else {
Jim Ingham3139fc92019-03-01 18:13:38 +00004058 bool hijacked =
4059 process_sp->IsHijackedForEvent(eBroadcastBitStateChanged)
4060 && !process_sp->StateChangedIsHijackedForSynchronousResume();
4061
4062 if (!hijacked) {
4063 // If we didn't restart, run the Stop Hooks here.
4064 // Don't do that if state changed events aren't hooked up to the
4065 // public (or SyncResume) broadcasters. StopHooks are just for
4066 // real public stops. They might also restart the target,
4067 // so watch for that.
4068 process_sp->GetTarget().RunStopHooks();
4069 if (process_sp->GetPrivateState() == eStateRunning)
4070 SetRestarted(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004071 }
4072 }
4073 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004074}
Zachary Turner805e7102019-03-04 21:51:03 +00004075}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004076
Kate Stoneb9c1b512016-09-06 20:57:50 +00004077void Process::ProcessEventData::Dump(Stream *s) const {
4078 ProcessSP process_sp(m_process_wp.lock());
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004079
Kate Stoneb9c1b512016-09-06 20:57:50 +00004080 if (process_sp)
4081 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4082 static_cast<void *>(process_sp.get()), process_sp->GetID());
4083 else
4084 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004085
Kate Stoneb9c1b512016-09-06 20:57:50 +00004086 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004087}
4088
4089const Process::ProcessEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004090Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4091 if (event_ptr) {
4092 const EventData *event_data = event_ptr->GetData();
4093 if (event_data &&
4094 event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4095 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4096 }
4097 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004098}
4099
4100ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004101Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4102 ProcessSP process_sp;
4103 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4104 if (data)
4105 process_sp = data->GetProcessSP();
4106 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004107}
4108
Kate Stoneb9c1b512016-09-06 20:57:50 +00004109StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4110 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4111 if (data == nullptr)
4112 return eStateInvalid;
4113 else
4114 return data->GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004115}
4116
Kate Stoneb9c1b512016-09-06 20:57:50 +00004117bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4118 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4119 if (data == nullptr)
4120 return false;
4121 else
4122 return data->GetRestarted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004123}
4124
Kate Stoneb9c1b512016-09-06 20:57:50 +00004125void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4126 bool new_value) {
4127 ProcessEventData *data =
4128 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4129 if (data != nullptr)
4130 data->SetRestarted(new_value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004131}
4132
Jim Ingham0161b492013-02-09 01:29:05 +00004133size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00004134Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4135 ProcessEventData *data =
4136 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4137 if (data != nullptr)
4138 return data->GetNumRestartedReasons();
4139 else
4140 return 0;
Jim Ingham0161b492013-02-09 01:29:05 +00004141}
4142
4143const char *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004144Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4145 size_t idx) {
4146 ProcessEventData *data =
4147 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4148 if (data != nullptr)
4149 return data->GetRestartedReasonAtIndex(idx);
4150 else
4151 return nullptr;
Jim Ingham0161b492013-02-09 01:29:05 +00004152}
4153
Kate Stoneb9c1b512016-09-06 20:57:50 +00004154void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4155 const char *reason) {
4156 ProcessEventData *data =
4157 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4158 if (data != nullptr)
4159 data->AddRestartedReason(reason);
Jim Ingham0161b492013-02-09 01:29:05 +00004160}
4161
Kate Stoneb9c1b512016-09-06 20:57:50 +00004162bool Process::ProcessEventData::GetInterruptedFromEvent(
4163 const Event *event_ptr) {
4164 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4165 if (data == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004166 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004167 else
4168 return data->GetInterrupted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004169}
4170
Kate Stoneb9c1b512016-09-06 20:57:50 +00004171void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4172 bool new_value) {
4173 ProcessEventData *data =
4174 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4175 if (data != nullptr)
4176 data->SetInterrupted(new_value);
Greg Claytond9e416c2012-02-18 05:35:26 +00004177}
4178
Kate Stoneb9c1b512016-09-06 20:57:50 +00004179bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4180 ProcessEventData *data =
4181 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4182 if (data) {
4183 data->SetUpdateStateOnRemoval();
4184 return true;
4185 }
4186 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004187}
4188
Jim Inghamb87b9e62018-06-26 23:38:58 +00004189lldb::TargetSP Process::CalculateTarget() { return m_target_wp.lock(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004190
4191void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4192 exe_ctx.SetTargetPtr(&GetTarget());
4193 exe_ctx.SetProcessPtr(this);
4194 exe_ctx.SetThreadPtr(nullptr);
4195 exe_ctx.SetFramePtr(nullptr);
4196}
4197
4198// uint32_t
4199// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4200// std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00004201//{
4202// return 0;
4203//}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004204//
4205// ArchSpec
4206// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
Greg Claytone996fd32011-03-08 22:40:15 +00004207//{
4208// return Host::GetArchSpecForExistingProcess (pid);
4209//}
4210//
Kate Stoneb9c1b512016-09-06 20:57:50 +00004211// ArchSpec
4212// Process::GetArchSpecForExistingProcess (const char *process_name)
Greg Claytone996fd32011-03-08 22:40:15 +00004213//{
4214// return Host::GetArchSpecForExistingProcess (process_name);
4215//}
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004216
Kate Stoneb9c1b512016-09-06 20:57:50 +00004217void Process::AppendSTDOUT(const char *s, size_t len) {
4218 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4219 m_stdout_data.append(s, len);
4220 BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4221 new ProcessEventData(shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004222}
4223
Kate Stoneb9c1b512016-09-06 20:57:50 +00004224void Process::AppendSTDERR(const char *s, size_t len) {
4225 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4226 m_stderr_data.append(s, len);
4227 BroadcastEventIfUnique(eBroadcastBitSTDERR,
4228 new ProcessEventData(shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004229}
4230
Kate Stoneb9c1b512016-09-06 20:57:50 +00004231void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4232 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4233 m_profile_data.push_back(one_profile_data);
4234 BroadcastEventIfUnique(eBroadcastBitProfileData,
4235 new ProcessEventData(shared_from_this(), GetState()));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004236}
4237
Kate Stoneb9c1b512016-09-06 20:57:50 +00004238void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4239 const StructuredDataPluginSP &plugin_sp) {
4240 BroadcastEvent(
4241 eBroadcastBitStructuredData,
4242 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
Todd Fiala75930012016-08-19 04:21:48 +00004243}
4244
4245StructuredDataPluginSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004246Process::GetStructuredDataPlugin(const ConstString &type_name) const {
4247 auto find_it = m_structured_data_plugin_map.find(type_name);
4248 if (find_it != m_structured_data_plugin_map.end())
4249 return find_it->second;
4250 else
4251 return StructuredDataPluginSP();
Todd Fiala75930012016-08-19 04:21:48 +00004252}
4253
Zachary Turner97206d52017-05-12 04:51:55 +00004254size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004255 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4256 if (m_profile_data.empty())
4257 return 0;
4258
4259 std::string &one_profile_data = m_profile_data.front();
4260 size_t bytes_available = one_profile_data.size();
4261 if (bytes_available > 0) {
4262 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4263 if (log)
4264 log->Printf("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4265 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4266 if (bytes_available > buf_size) {
4267 memcpy(buf, one_profile_data.c_str(), buf_size);
4268 one_profile_data.erase(0, buf_size);
4269 bytes_available = buf_size;
4270 } else {
4271 memcpy(buf, one_profile_data.c_str(), bytes_available);
4272 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004273 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004274 }
4275 return bytes_available;
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004276}
4277
Greg Clayton93e86192011-11-13 04:45:22 +00004278//------------------------------------------------------------------
4279// Process STDIO
4280//------------------------------------------------------------------
4281
Zachary Turner97206d52017-05-12 04:51:55 +00004282size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004283 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4284 size_t bytes_available = m_stdout_data.size();
4285 if (bytes_available > 0) {
4286 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4287 if (log)
4288 log->Printf("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4289 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4290 if (bytes_available > buf_size) {
4291 memcpy(buf, m_stdout_data.c_str(), buf_size);
4292 m_stdout_data.erase(0, buf_size);
4293 bytes_available = buf_size;
4294 } else {
4295 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4296 m_stdout_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004297 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004298 }
4299 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004300}
4301
Zachary Turner97206d52017-05-12 04:51:55 +00004302size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004303 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4304 size_t bytes_available = m_stderr_data.size();
4305 if (bytes_available > 0) {
4306 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4307 if (log)
4308 log->Printf("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4309 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4310 if (bytes_available > buf_size) {
4311 memcpy(buf, m_stderr_data.c_str(), buf_size);
4312 m_stderr_data.erase(0, buf_size);
4313 bytes_available = buf_size;
4314 } else {
4315 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4316 m_stderr_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004317 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004318 }
4319 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004320}
4321
Kate Stoneb9c1b512016-09-06 20:57:50 +00004322void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4323 size_t src_len) {
4324 Process *process = (Process *)baton;
4325 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004326}
4327
Kate Stoneb9c1b512016-09-06 20:57:50 +00004328class IOHandlerProcessSTDIO : public IOHandler {
Greg Clayton44d93782014-01-27 23:43:24 +00004329public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004330 IOHandlerProcessSTDIO(Process *process, int write_fd)
4331 : IOHandler(process->GetTarget().GetDebugger(),
4332 IOHandler::Type::ProcessIO),
Sam McCall6f43d9d2016-11-15 10:58:16 +00004333 m_process(process), m_write_file(write_fd, false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004334 m_pipe.CreateNew(false);
4335 m_read_file.SetDescriptor(GetInputFD(), false);
4336 }
4337
4338 ~IOHandlerProcessSTDIO() override = default;
4339
Adrian Prantl05097242018-04-30 16:49:04 +00004340 // Each IOHandler gets to run until it is done. It should read data from the
4341 // "in" and place output into "out" and "err and return when done.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004342 void Run() override {
4343 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4344 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4345 SetIsDone(true);
4346 return;
Greg Clayton44d93782014-01-27 23:43:24 +00004347 }
4348
Kate Stoneb9c1b512016-09-06 20:57:50 +00004349 SetIsDone(false);
4350 const int read_fd = m_read_file.GetDescriptor();
4351 TerminalState terminal_state;
4352 terminal_state.Save(read_fd, false);
4353 Terminal terminal(read_fd);
4354 terminal.SetCanonical(false);
4355 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004356// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004357#ifndef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +00004358 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4359 m_is_running = true;
4360 while (!GetIsDone()) {
4361 SelectHelper select_helper;
4362 select_helper.FDSetRead(read_fd);
4363 select_helper.FDSetRead(pipe_read_fd);
Zachary Turner97206d52017-05-12 04:51:55 +00004364 Status error = select_helper.Select();
Greg Clayton860582f2016-02-26 17:36:44 +00004365
Kate Stoneb9c1b512016-09-06 20:57:50 +00004366 if (error.Fail()) {
Greg Clayton860582f2016-02-26 17:36:44 +00004367 SetIsDone(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004368 } else {
4369 char ch = 0;
4370 size_t n;
4371 if (select_helper.FDIsSetRead(read_fd)) {
4372 n = 1;
4373 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4374 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4375 SetIsDone(true);
4376 } else
4377 SetIsDone(true);
Greg Clayton860582f2016-02-26 17:36:44 +00004378 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004379 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4380 size_t bytes_read;
4381 // Consume the interrupt byte
Zachary Turner97206d52017-05-12 04:51:55 +00004382 Status error = m_pipe.Read(&ch, 1, bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004383 if (error.Success()) {
4384 switch (ch) {
4385 case 'q':
4386 SetIsDone(true);
4387 break;
4388 case 'i':
4389 if (StateIsRunningState(m_process->GetState()))
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004390 m_process->SendAsyncInterrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004391 break;
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004392 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004393 }
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004394 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004395 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004396 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004397 m_is_running = false;
4398#endif
4399 terminal_state.Restore();
4400 }
4401
4402 void Cancel() override {
4403 SetIsDone(true);
4404 // Only write to our pipe to cancel if we are in
Adrian Prantl05097242018-04-30 16:49:04 +00004405 // IOHandlerProcessSTDIO::Run(). We can end up with a python command that
4406 // is being run from the command interpreter:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004407 //
4408 // (lldb) step_process_thousands_of_times
4409 //
4410 // In this case the command interpreter will be in the middle of handling
4411 // the command and if the process pushes and pops the IOHandler thousands
4412 // of times, we can end up writing to m_pipe without ever consuming the
4413 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4414 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4415 if (m_is_running) {
4416 char ch = 'q'; // Send 'q' for quit
4417 size_t bytes_written = 0;
4418 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00004419 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004420 }
4421
4422 bool Interrupt() override {
Adrian Prantl05097242018-04-30 16:49:04 +00004423 // Do only things that are safe to do in an interrupt context (like in a
4424 // SIGINT handler), like write 1 byte to a file descriptor. This will
Kate Stoneb9c1b512016-09-06 20:57:50 +00004425 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4426 // that was written to the pipe and then call
Adrian Prantl05097242018-04-30 16:49:04 +00004427 // m_process->SendAsyncInterrupt() from a much safer location in code.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004428 if (m_active) {
4429 char ch = 'i'; // Send 'i' for interrupt
4430 size_t bytes_written = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00004431 Status result = m_pipe.Write(&ch, 1, bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004432 return result.Success();
4433 } else {
4434 // This IOHandler might be pushed on the stack, but not being run
Adrian Prantl05097242018-04-30 16:49:04 +00004435 // currently so do the right thing if we aren't actively watching for
4436 // STDIN by sending the interrupt to the process. Otherwise the write to
4437 // the pipe above would do nothing. This can happen when the command
4438 // interpreter is running and gets a "expression ...". It will be on the
4439 // IOHandler thread and sending the input is complete to the delegate
4440 // which will cause the expression to run, which will push the process IO
4441 // handler, but not run it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004442
4443 if (StateIsRunningState(m_process->GetState())) {
4444 m_process->SendAsyncInterrupt();
4445 return true;
4446 }
4447 }
4448 return false;
4449 }
4450
4451 void GotEOF() override {}
4452
Greg Clayton44d93782014-01-27 23:43:24 +00004453protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004454 Process *m_process;
4455 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4456 File m_write_file; // Write to this file (usually the master pty for getting
4457 // io to debuggee)
4458 Pipe m_pipe;
Sam McCall6f43d9d2016-11-15 10:58:16 +00004459 std::atomic<bool> m_is_running{false};
Greg Clayton44d93782014-01-27 23:43:24 +00004460};
4461
Kate Stoneb9c1b512016-09-06 20:57:50 +00004462void Process::SetSTDIOFileDescriptor(int fd) {
4463 // First set up the Read Thread for reading/handling process I/O
4464
Jonas Devlieghered5b44032019-02-13 06:25:41 +00004465 std::unique_ptr<ConnectionFileDescriptor> conn_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004466 new ConnectionFileDescriptor(fd, true));
4467
Jonas Devlieghered5b44032019-02-13 06:25:41 +00004468 if (conn_up) {
4469 m_stdio_communication.SetConnection(conn_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004470 if (m_stdio_communication.IsConnected()) {
4471 m_stdio_communication.SetReadThreadBytesReceivedCallback(
4472 STDIOReadThreadBytesReceived, this);
4473 m_stdio_communication.StartReadThread();
4474
4475 // Now read thread is set up, set up input reader.
4476
4477 if (!m_process_input_reader)
Jonas Devlieghere796ac802019-02-11 23:13:08 +00004478 m_process_input_reader =
4479 std::make_shared<IOHandlerProcessSTDIO>(this, fd);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004480 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004481 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004482}
4483
Kate Stoneb9c1b512016-09-06 20:57:50 +00004484bool Process::ProcessIOHandlerIsActive() {
4485 IOHandlerSP io_handler_sp(m_process_input_reader);
4486 if (io_handler_sp)
4487 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4488 return false;
Greg Clayton6fea17e2014-03-03 19:15:20 +00004489}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004490bool Process::PushProcessIOHandler() {
4491 IOHandlerSP io_handler_sp(m_process_input_reader);
4492 if (io_handler_sp) {
4493 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4494 if (log)
4495 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
Pavel Labath44464872015-05-27 12:40:32 +00004496
Kate Stoneb9c1b512016-09-06 20:57:50 +00004497 io_handler_sp->SetIsDone(false);
Raphael Isemannc01783a2018-08-29 22:50:54 +00004498 // If we evaluate an utility function, then we don't cancel the current
4499 // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
4500 // existing IOHandler that potentially provides the user interface (e.g.
4501 // the IOHandler for Editline).
4502 bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();
4503 GetTarget().GetDebugger().PushIOHandler(io_handler_sp, cancel_top_handler);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004504 return true;
4505 }
4506 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004507}
4508
Kate Stoneb9c1b512016-09-06 20:57:50 +00004509bool Process::PopProcessIOHandler() {
4510 IOHandlerSP io_handler_sp(m_process_input_reader);
4511 if (io_handler_sp)
4512 return GetTarget().GetDebugger().PopIOHandler(io_handler_sp);
4513 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004514}
4515
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004516// The process needs to know about installed plug-ins
Kate Stoneb9c1b512016-09-06 20:57:50 +00004517void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004518
Kate Stoneb9c1b512016-09-06 20:57:50 +00004519void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004520
Kate Stoneb9c1b512016-09-06 20:57:50 +00004521namespace {
Adrian Prantl05097242018-04-30 16:49:04 +00004522// RestorePlanState is used to record the "is private", "is master" and "okay
4523// to discard" fields of the plan we are running, and reset it on Clean or on
4524// destruction. It will only reset the state once, so you can call Clean and
4525// then monkey with the state and it won't get reset on you again.
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004526
Kate Stoneb9c1b512016-09-06 20:57:50 +00004527class RestorePlanState {
4528public:
4529 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4530 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4531 if (m_thread_plan_sp) {
4532 m_private = m_thread_plan_sp->GetPrivate();
4533 m_is_master = m_thread_plan_sp->IsMasterPlan();
4534 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4535 }
4536 }
4537
4538 ~RestorePlanState() { Clean(); }
4539
4540 void Clean() {
4541 if (!m_already_reset && m_thread_plan_sp) {
4542 m_already_reset = true;
4543 m_thread_plan_sp->SetPrivate(m_private);
4544 m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4545 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4546 }
4547 }
4548
4549private:
4550 lldb::ThreadPlanSP m_thread_plan_sp;
4551 bool m_already_reset;
4552 bool m_private;
4553 bool m_is_master;
4554 bool m_okay_to_discard;
4555};
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004556} // anonymous namespace
Jim Inghamc60963c2015-10-12 19:11:03 +00004557
Pavel Labath2ce22162016-12-01 10:57:30 +00004558static microseconds
4559GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
4560 const milliseconds default_one_thread_timeout(250);
4561
4562 // If the overall wait is forever, then we don't need to worry about it.
Pavel Labath43d35412016-12-06 11:24:51 +00004563 if (!options.GetTimeout()) {
4564 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4565 : default_one_thread_timeout;
Pavel Labath2ce22162016-12-01 10:57:30 +00004566 }
4567
4568 // If the one thread timeout is set, use it.
Pavel Labath43d35412016-12-06 11:24:51 +00004569 if (options.GetOneThreadTimeout())
4570 return *options.GetOneThreadTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004571
4572 // Otherwise use half the total timeout, bounded by the
4573 // default_one_thread_timeout.
4574 return std::min<microseconds>(default_one_thread_timeout,
Pavel Labath43d35412016-12-06 11:24:51 +00004575 *options.GetTimeout() / 2);
Pavel Labath2ce22162016-12-01 10:57:30 +00004576}
4577
4578static Timeout<std::micro>
4579GetExpressionTimeout(const EvaluateExpressionOptions &options,
4580 bool before_first_timeout) {
Adrian Prantl05097242018-04-30 16:49:04 +00004581 // If we are going to run all threads the whole time, or if we are only going
4582 // to run one thread, we can just return the overall timeout.
Pavel Labath2ce22162016-12-01 10:57:30 +00004583 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Pavel Labath43d35412016-12-06 11:24:51 +00004584 return options.GetTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004585
4586 if (before_first_timeout)
4587 return GetOneThreadExpressionTimeout(options);
4588
Pavel Labath43d35412016-12-06 11:24:51 +00004589 if (!options.GetTimeout())
Pavel Labath2ce22162016-12-01 10:57:30 +00004590 return llvm::None;
4591 else
Pavel Labath43d35412016-12-06 11:24:51 +00004592 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
Pavel Labath2ce22162016-12-01 10:57:30 +00004593}
4594
Pavel Labath45dde232017-05-25 10:50:06 +00004595static llvm::Optional<ExpressionResults>
4596HandleStoppedEvent(Thread &thread, const ThreadPlanSP &thread_plan_sp,
4597 RestorePlanState &restorer, const EventSP &event_sp,
4598 EventSP &event_to_broadcast_sp,
4599 const EvaluateExpressionOptions &options, bool handle_interrupts) {
4600 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS);
4601
4602 ThreadPlanSP plan = thread.GetCompletedPlan();
4603 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
4604 LLDB_LOG(log, "execution completed successfully");
4605
4606 // Restore the plan state so it will get reported as intended when we are
4607 // done.
4608 restorer.Clean();
4609 return eExpressionCompleted;
4610 }
4611
4612 StopInfoSP stop_info_sp = thread.GetStopInfo();
4613 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
4614 stop_info_sp->ShouldNotify(event_sp.get())) {
4615 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
4616 if (!options.DoesIgnoreBreakpoints()) {
4617 // Restore the plan state and then force Private to false. We are going
4618 // to stop because of this plan so we need it to become a public plan or
Adrian Prantl05097242018-04-30 16:49:04 +00004619 // it won't report correctly when we continue to its termination later
4620 // on.
Pavel Labath45dde232017-05-25 10:50:06 +00004621 restorer.Clean();
4622 thread_plan_sp->SetPrivate(false);
4623 event_to_broadcast_sp = event_sp;
4624 }
4625 return eExpressionHitBreakpoint;
4626 }
4627
4628 if (!handle_interrupts &&
4629 Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4630 return llvm::None;
4631
4632 LLDB_LOG(log, "thread plan did not successfully complete");
4633 if (!options.DoesUnwindOnError())
4634 event_to_broadcast_sp = event_sp;
4635 return eExpressionInterrupted;
4636}
4637
Jim Ingham1624a2d2014-05-05 02:26:40 +00004638ExpressionResults
Kate Stoneb9c1b512016-09-06 20:57:50 +00004639Process::RunThreadPlan(ExecutionContext &exe_ctx,
4640 lldb::ThreadPlanSP &thread_plan_sp,
4641 const EvaluateExpressionOptions &options,
4642 DiagnosticManager &diagnostic_manager) {
4643 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004644
Kate Stoneb9c1b512016-09-06 20:57:50 +00004645 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4646
4647 if (!thread_plan_sp) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004648 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004649 eDiagnosticSeverityError,
4650 "RunThreadPlan called with empty thread plan.");
4651 return eExpressionSetupError;
4652 }
4653
4654 if (!thread_plan_sp->ValidatePlan(nullptr)) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004655 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004656 eDiagnosticSeverityError,
4657 "RunThreadPlan called with an invalid thread plan.");
4658 return eExpressionSetupError;
4659 }
4660
4661 if (exe_ctx.GetProcessPtr() != this) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004662 diagnostic_manager.PutString(eDiagnosticSeverityError,
4663 "RunThreadPlan called on wrong process.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004664 return eExpressionSetupError;
4665 }
4666
4667 Thread *thread = exe_ctx.GetThreadPtr();
4668 if (thread == nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004669 diagnostic_manager.PutString(eDiagnosticSeverityError,
4670 "RunThreadPlan called with invalid thread.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004671 return eExpressionSetupError;
4672 }
4673
4674 // We need to change some of the thread plan attributes for the thread plan
Adrian Prantl05097242018-04-30 16:49:04 +00004675 // runner. This will restore them when we are done:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004676
4677 RestorePlanState thread_plan_restorer(thread_plan_sp);
4678
Adrian Prantl05097242018-04-30 16:49:04 +00004679 // We rely on the thread plan we are running returning "PlanCompleted" if
4680 // when it successfully completes. For that to be true the plan can't be
4681 // private - since private plans suppress themselves in the GetCompletedPlan
4682 // call.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004683
4684 thread_plan_sp->SetPrivate(false);
4685
4686 // The plans run with RunThreadPlan also need to be terminal master plans or
Adrian Prantl05097242018-04-30 16:49:04 +00004687 // when they are done we will end up asking the plan above us whether we
4688 // should stop, which may give the wrong answer.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004689
4690 thread_plan_sp->SetIsMasterPlan(true);
4691 thread_plan_sp->SetOkayToDiscard(false);
4692
Raphael Isemannc01783a2018-08-29 22:50:54 +00004693 // If we are running some utility expression for LLDB, we now have to mark
4694 // this in the ProcesModID of this process. This RAII takes care of marking
4695 // and reverting the mark it once we are done running the expression.
4696 UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);
4697
Kate Stoneb9c1b512016-09-06 20:57:50 +00004698 if (m_private_state.GetValue() != eStateStopped) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004699 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004700 eDiagnosticSeverityError,
4701 "RunThreadPlan called while the private state was not stopped.");
4702 return eExpressionSetupError;
4703 }
4704
4705 // Save the thread & frame from the exe_ctx for restoration after we run
4706 const uint32_t thread_idx_id = thread->GetIndexID();
4707 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4708 if (!selected_frame_sp) {
4709 thread->SetSelectedFrame(nullptr);
4710 selected_frame_sp = thread->GetSelectedFrame();
4711 if (!selected_frame_sp) {
4712 diagnostic_manager.Printf(
4713 eDiagnosticSeverityError,
4714 "RunThreadPlan called without a selected frame on thread %d",
4715 thread_idx_id);
4716 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004717 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004718 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004719
Adrian Prantl05097242018-04-30 16:49:04 +00004720 // Make sure the timeout values make sense. The one thread timeout needs to
4721 // be smaller than the overall timeout.
Pavel Labath43d35412016-12-06 11:24:51 +00004722 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4723 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
Pavel Labath2ce22162016-12-01 10:57:30 +00004724 diagnostic_manager.PutString(eDiagnosticSeverityError,
4725 "RunThreadPlan called with one thread "
4726 "timeout greater than total timeout");
4727 return eExpressionSetupError;
4728 }
4729
Kate Stoneb9c1b512016-09-06 20:57:50 +00004730 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004731
Kate Stoneb9c1b512016-09-06 20:57:50 +00004732 // N.B. Running the target may unset the currently selected thread and frame.
Adrian Prantl05097242018-04-30 16:49:04 +00004733 // We don't want to do that either, so we should arrange to reset them as
4734 // well.
Greg Claytonc14ee322011-09-22 04:58:26 +00004735
Kate Stoneb9c1b512016-09-06 20:57:50 +00004736 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004737
Kate Stoneb9c1b512016-09-06 20:57:50 +00004738 uint32_t selected_tid;
4739 StackID selected_stack_id;
4740 if (selected_thread_sp) {
4741 selected_tid = selected_thread_sp->GetIndexID();
4742 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4743 } else {
4744 selected_tid = LLDB_INVALID_THREAD_ID;
4745 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004746
Kate Stoneb9c1b512016-09-06 20:57:50 +00004747 HostThread backup_private_state_thread;
4748 lldb::StateType old_state = eStateInvalid;
4749 lldb::ThreadPlanSP stopper_base_plan_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004750
Kate Stoneb9c1b512016-09-06 20:57:50 +00004751 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4752 LIBLLDB_LOG_PROCESS));
4753 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4754 // Yikes, we are running on the private state thread! So we can't wait for
Adrian Prantl05097242018-04-30 16:49:04 +00004755 // public events on this thread, since we are the thread that is generating
4756 // public events. The simplest thing to do is to spin up a temporary thread
4757 // to handle private state thread events while we are fielding public
4758 // events here.
Todd Fiala76e0fc92014-08-27 22:58:26 +00004759 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004760 log->Printf("Running thread plan on private state thread, spinning up "
4761 "another state thread to handle the events.");
Todd Fiala76e0fc92014-08-27 22:58:26 +00004762
Kate Stoneb9c1b512016-09-06 20:57:50 +00004763 backup_private_state_thread = m_private_state_thread;
Greg Clayton095eeaa2013-11-05 23:28:00 +00004764
Kate Stoneb9c1b512016-09-06 20:57:50 +00004765 // One other bit of business: we want to run just this thread plan and
Adrian Prantl05097242018-04-30 16:49:04 +00004766 // anything it pushes, and then stop, returning control here. But in the
4767 // normal course of things, the plan above us on the stack would be given a
4768 // shot at the stop event before deciding to stop, and we don't want that.
4769 // So we insert a "stopper" base plan on the stack before the plan we want
4770 // to run. Since base plans always stop and return control to the user,
4771 // that will do just what we want.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004772 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4773 thread->QueueThreadPlan(stopper_base_plan_sp, false);
4774 // Have to make sure our public state is stopped, since otherwise the
4775 // reporting logic below doesn't work correctly.
4776 old_state = m_public_state.GetValue();
4777 m_public_state.SetValueNoLock(eStateStopped);
4778
4779 // Now spin up the private state thread:
4780 StartPrivateStateThread(true);
4781 }
4782
4783 thread->QueueThreadPlan(
4784 thread_plan_sp, false); // This used to pass "true" does that make sense?
4785
4786 if (options.GetDebug()) {
Adrian Prantl05097242018-04-30 16:49:04 +00004787 // In this case, we aren't actually going to run, we just want to stop
4788 // right away. Flush this thread so we will refetch the stacks and show the
4789 // correct backtrace.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004790 // FIXME: To make this prettier we should invent some stop reason for this,
4791 // but that
4792 // is only cosmetic, and this functionality is only of use to lldb
Adrian Prantl05097242018-04-30 16:49:04 +00004793 // developers who can live with not pretty...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004794 thread->Flush();
4795 return eExpressionStoppedForDebug;
4796 }
4797
4798 ListenerSP listener_sp(
4799 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4800
4801 lldb::EventSP event_to_broadcast_sp;
4802
4803 {
4804 // This process event hijacker Hijacks the Public events and its destructor
Adrian Prantl05097242018-04-30 16:49:04 +00004805 // makes sure that the process events get restored on exit to the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004806 //
4807 // If the event needs to propagate beyond the hijacker (e.g., the process
Adrian Prantl05097242018-04-30 16:49:04 +00004808 // exits during execution), then the event is put into
4809 // event_to_broadcast_sp for rebroadcasting.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004810
4811 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
4812
4813 if (log) {
4814 StreamString s;
4815 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4816 log->Printf("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
4817 " to run thread plan \"%s\".",
4818 thread->GetIndexID(), thread->GetID(), s.GetData());
Jim Ingham1460e4b2014-01-10 23:46:59 +00004819 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004820
4821 bool got_event;
4822 lldb::EventSP event_sp;
4823 lldb::StateType stop_state = lldb::eStateInvalid;
4824
4825 bool before_first_timeout = true; // This is set to false the first time
4826 // that we have to halt the target.
4827 bool do_resume = true;
4828 bool handle_running_event = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004829
4830 // This is just for accounting:
4831 uint32_t num_resumes = 0;
4832
Kate Stoneb9c1b512016-09-06 20:57:50 +00004833 // If we are going to run all threads the whole time, or if we are only
Pavel Labath2ce22162016-12-01 10:57:30 +00004834 // going to run one thread, then we don't need the first timeout. So we
4835 // pretend we are after the first timeout already.
4836 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Kate Stoneb9c1b512016-09-06 20:57:50 +00004837 before_first_timeout = false;
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00004838
Kate Stoneb9c1b512016-09-06 20:57:50 +00004839 if (log)
Pavel Labath2ce22162016-12-01 10:57:30 +00004840 log->Printf("Stop others: %u, try all: %u, before_first: %u.\n",
4841 options.GetStopOthers(), options.GetTryAllThreads(),
4842 before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004843
Adrian Prantl05097242018-04-30 16:49:04 +00004844 // This isn't going to work if there are unfetched events on the queue. Are
4845 // there cases where we might want to run the remaining events here, and
4846 // then try to call the function? That's probably being too tricky for our
4847 // own good.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004848
4849 Event *other_events = listener_sp->PeekAtNextEvent();
4850 if (other_events != nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004851 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004852 eDiagnosticSeverityError,
4853 "RunThreadPlan called with pending events on the queue.");
4854 return eExpressionSetupError;
Kuba Breckaafdf8422014-10-10 23:43:03 +00004855 }
4856
Kate Stoneb9c1b512016-09-06 20:57:50 +00004857 // We also need to make sure that the next event is delivered. We might be
Adrian Prantl05097242018-04-30 16:49:04 +00004858 // calling a function as part of a thread plan, in which case the last
4859 // delivered event could be the running event, and we don't want event
4860 // coalescing to cause us to lose OUR running event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004861 ForceNextEventDelivery();
Ryan Brown65d4d5c2015-09-16 21:20:44 +00004862
Kate Stoneb9c1b512016-09-06 20:57:50 +00004863// This while loop must exit out the bottom, there's cleanup that we need to do
Adrian Prantl05097242018-04-30 16:49:04 +00004864// when we are done. So don't call return anywhere within it.
Todd Fiala75930012016-08-19 04:21:48 +00004865
Kate Stoneb9c1b512016-09-06 20:57:50 +00004866#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
Adrian Prantl05097242018-04-30 16:49:04 +00004867 // It's pretty much impossible to write test cases for things like: One
4868 // thread timeout expires, I go to halt, but the process already stopped on
4869 // the function call stop breakpoint. Turning on this define will make us
4870 // not fetch the first event till after the halt. So if you run a quick
4871 // function, it will have completed, and the completion event will be
4872 // waiting, when you interrupt for halt. The expression evaluation should
4873 // still succeed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004874 bool miss_first_event = true;
4875#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00004876 while (true) {
Adrian Prantl05097242018-04-30 16:49:04 +00004877 // We usually want to resume the process if we get to the top of the
4878 // loop. The only exception is if we get two running events with no
4879 // intervening stop, which can happen, we will just wait for then next
4880 // stop event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004881 if (log)
4882 log->Printf("Top of while loop: do_resume: %i handle_running_event: %i "
4883 "before_first_timeout: %i.",
4884 do_resume, handle_running_event, before_first_timeout);
Jason Molendaef7d6412015-08-06 03:27:10 +00004885
Kate Stoneb9c1b512016-09-06 20:57:50 +00004886 if (do_resume || handle_running_event) {
4887 // Do the initial resume and wait for the running event before going
4888 // further.
Jason Molendaef7d6412015-08-06 03:27:10 +00004889
Kate Stoneb9c1b512016-09-06 20:57:50 +00004890 if (do_resume) {
4891 num_resumes++;
Zachary Turner97206d52017-05-12 04:51:55 +00004892 Status resume_error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004893 if (!resume_error.Success()) {
4894 diagnostic_manager.Printf(
4895 eDiagnosticSeverityError,
4896 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
4897 resume_error.AsCString());
4898 return_value = eExpressionSetupError;
4899 break;
4900 }
Jason Molendaef7d6412015-08-06 03:27:10 +00004901 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004902
Pavel Labathd35031e12016-11-30 10:41:42 +00004903 got_event =
4904 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004905 if (!got_event) {
4906 if (log)
4907 log->Printf("Process::RunThreadPlan(): didn't get any event after "
4908 "resume %" PRIu32 ", exiting.",
4909 num_resumes);
4910
4911 diagnostic_manager.Printf(eDiagnosticSeverityError,
4912 "didn't get any event after resume %" PRIu32
4913 ", exiting.",
4914 num_resumes);
4915 return_value = eExpressionSetupError;
4916 break;
4917 }
4918
4919 stop_state =
4920 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4921
4922 if (stop_state != eStateRunning) {
4923 bool restarted = false;
4924
4925 if (stop_state == eStateStopped) {
4926 restarted = Process::ProcessEventData::GetRestartedFromEvent(
4927 event_sp.get());
4928 if (log)
4929 log->Printf(
4930 "Process::RunThreadPlan(): didn't get running event after "
4931 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
4932 "handle_running_event: %i).",
4933 num_resumes, StateAsCString(stop_state), restarted, do_resume,
4934 handle_running_event);
4935 }
4936
4937 if (restarted) {
4938 // This is probably an overabundance of caution, I don't think I
Adrian Prantl05097242018-04-30 16:49:04 +00004939 // should ever get a stopped & restarted event here. But if I do,
4940 // the best thing is to Halt and then get out of here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004941 const bool clear_thread_plans = false;
4942 const bool use_run_lock = false;
4943 Halt(clear_thread_plans, use_run_lock);
4944 }
4945
4946 diagnostic_manager.Printf(
4947 eDiagnosticSeverityError,
4948 "didn't get running event after initial resume, got %s instead.",
4949 StateAsCString(stop_state));
4950 return_value = eExpressionSetupError;
4951 break;
4952 }
4953
4954 if (log)
4955 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
Adrian Prantl05097242018-04-30 16:49:04 +00004956 // We need to call the function synchronously, so spin waiting for it
4957 // to return. If we get interrupted while executing, we're going to
4958 // lose our context, and won't be able to gather the result at this
4959 // point. We set the timeout AFTER the resume, since the resume takes
4960 // some time and we don't want to charge that to the timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004961 } else {
4962 if (log)
4963 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
4964 }
4965
Kate Stoneb9c1b512016-09-06 20:57:50 +00004966 do_resume = true;
4967 handle_running_event = true;
4968
4969 // Now wait for the process to stop again:
4970 event_sp.reset();
4971
Pavel Labath2ce22162016-12-01 10:57:30 +00004972 Timeout<std::micro> timeout =
4973 GetExpressionTimeout(options, before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004974 if (log) {
Pavel Labath2ce22162016-12-01 10:57:30 +00004975 if (timeout) {
4976 auto now = system_clock::now();
4977 log->Printf("Process::RunThreadPlan(): about to wait - now is %s - "
4978 "endpoint is %s",
4979 llvm::to_string(now).c_str(),
4980 llvm::to_string(now + *timeout).c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004981 } else {
4982 log->Printf("Process::RunThreadPlan(): about to wait forever.");
Jason Molendaef7d6412015-08-06 03:27:10 +00004983 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004984 }
4985
4986#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
4987 // See comment above...
4988 if (miss_first_event) {
4989 usleep(1000);
4990 miss_first_event = false;
4991 got_event = false;
4992 } else
4993#endif
Pavel Labath2ce22162016-12-01 10:57:30 +00004994 got_event = listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004995
4996 if (got_event) {
4997 if (event_sp) {
4998 bool keep_going = false;
4999 if (event_sp->GetType() == eBroadcastBitInterrupt) {
5000 const bool clear_thread_plans = false;
5001 const bool use_run_lock = false;
5002 Halt(clear_thread_plans, use_run_lock);
5003 return_value = eExpressionInterrupted;
Zachary Turnere2411fa2016-11-12 19:12:56 +00005004 diagnostic_manager.PutString(eDiagnosticSeverityRemark,
5005 "execution halted by user interrupt.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005006 if (log)
5007 log->Printf("Process::RunThreadPlan(): Got interrupted by "
5008 "eBroadcastBitInterrupted, exiting.");
5009 break;
5010 } else {
5011 stop_state =
5012 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5013 if (log)
5014 log->Printf(
5015 "Process::RunThreadPlan(): in while loop, got event: %s.",
5016 StateAsCString(stop_state));
5017
5018 switch (stop_state) {
5019 case lldb::eStateStopped: {
5020 // We stopped, figure out what we are going to do now.
5021 ThreadSP thread_sp =
5022 GetThreadList().FindThreadByIndexID(thread_idx_id);
5023 if (!thread_sp) {
5024 // Ooh, our thread has vanished. Unlikely that this was
5025 // successful execution...
5026 if (log)
5027 log->Printf("Process::RunThreadPlan(): execution completed "
5028 "but our thread (index-id=%u) has vanished.",
5029 thread_idx_id);
5030 return_value = eExpressionInterrupted;
Pavel Labath45dde232017-05-25 10:50:06 +00005031 } else if (Process::ProcessEventData::GetRestartedFromEvent(
5032 event_sp.get())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005033 // If we were restarted, we just need to go back up to fetch
5034 // another event.
Pavel Labath45dde232017-05-25 10:50:06 +00005035 if (log) {
5036 log->Printf("Process::RunThreadPlan(): Got a stop and "
5037 "restart, so we'll continue waiting.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005038 }
Pavel Labath45dde232017-05-25 10:50:06 +00005039 keep_going = true;
5040 do_resume = false;
5041 handle_running_event = true;
5042 } else {
5043 const bool handle_interrupts = true;
5044 return_value = *HandleStoppedEvent(
5045 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5046 event_to_broadcast_sp, options, handle_interrupts);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005047 }
5048 } break;
5049
5050 case lldb::eStateRunning:
5051 // This shouldn't really happen, but sometimes we do get two
Adrian Prantl05097242018-04-30 16:49:04 +00005052 // running events without an intervening stop, and in that case
5053 // we should just go back to waiting for the stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005054 do_resume = false;
5055 keep_going = true;
5056 handle_running_event = false;
5057 break;
5058
5059 default:
5060 if (log)
5061 log->Printf("Process::RunThreadPlan(): execution stopped with "
5062 "unexpected state: %s.",
5063 StateAsCString(stop_state));
5064
5065 if (stop_state == eStateExited)
5066 event_to_broadcast_sp = event_sp;
5067
Zachary Turnere2411fa2016-11-12 19:12:56 +00005068 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005069 eDiagnosticSeverityError,
5070 "execution stopped with unexpected state.");
5071 return_value = eExpressionInterrupted;
5072 break;
5073 }
5074 }
5075
5076 if (keep_going)
5077 continue;
5078 else
5079 break;
5080 } else {
5081 if (log)
5082 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5083 "the event pointer was null. How odd...");
5084 return_value = eExpressionInterrupted;
5085 break;
5086 }
5087 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00005088 // If we didn't get an event that means we've timed out... We will
5089 // interrupt the process here. Depending on what we were asked to do
5090 // we will either exit, or try with all threads running for the same
5091 // timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005092
5093 if (log) {
5094 if (options.GetTryAllThreads()) {
5095 if (before_first_timeout) {
Pavel Labathd02b1c82017-02-10 11:49:33 +00005096 LLDB_LOG(log,
5097 "Running function with one thread timeout timed out.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005098 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005099 LLDB_LOG(log, "Restarting function with all threads enabled and "
5100 "timeout: {0} timed out, abandoning execution.",
5101 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005102 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005103 LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5104 "abandoning execution.",
5105 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005106 }
5107
5108 // It is possible that between the time we issued the Halt, and we get
Adrian Prantl05097242018-04-30 16:49:04 +00005109 // around to calling Halt the target could have stopped. That's fine,
5110 // Halt will figure that out and send the appropriate Stopped event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005111 // BUT it is also possible that we stopped & restarted (e.g. hit a
5112 // signal with "stop" set to false.) In
5113 // that case, we'll get the stopped & restarted event, and we should go
Adrian Prantl05097242018-04-30 16:49:04 +00005114 // back to waiting for the Halt's stopped event. That's what this
5115 // while loop does.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005116
5117 bool back_to_top = true;
5118 uint32_t try_halt_again = 0;
5119 bool do_halt = true;
5120 const uint32_t num_retries = 5;
5121 while (try_halt_again < num_retries) {
Zachary Turner97206d52017-05-12 04:51:55 +00005122 Status halt_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005123 if (do_halt) {
5124 if (log)
5125 log->Printf("Process::RunThreadPlan(): Running Halt.");
5126 const bool clear_thread_plans = false;
5127 const bool use_run_lock = false;
5128 Halt(clear_thread_plans, use_run_lock);
5129 }
5130 if (halt_error.Success()) {
5131 if (log)
5132 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5133
Pavel Labathd35031e12016-11-30 10:41:42 +00005134 got_event =
5135 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005136
5137 if (got_event) {
5138 stop_state =
5139 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5140 if (log) {
5141 log->Printf("Process::RunThreadPlan(): Stopped with event: %s",
5142 StateAsCString(stop_state));
5143 if (stop_state == lldb::eStateStopped &&
5144 Process::ProcessEventData::GetInterruptedFromEvent(
5145 event_sp.get()))
5146 log->PutCString(" Event was the Halt interruption event.");
5147 }
5148
5149 if (stop_state == lldb::eStateStopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005150 if (Process::ProcessEventData::GetRestartedFromEvent(
5151 event_sp.get())) {
5152 if (log)
5153 log->PutCString("Process::RunThreadPlan(): Went to halt "
5154 "but got a restarted event, there must be "
5155 "an un-restarted stopped event so try "
5156 "again... "
5157 "Exiting wait loop.");
5158 try_halt_again++;
5159 do_halt = false;
5160 continue;
5161 }
5162
Pavel Labath45dde232017-05-25 10:50:06 +00005163 // Between the time we initiated the Halt and the time we
Adrian Prantl05097242018-04-30 16:49:04 +00005164 // delivered it, the process could have already finished its
5165 // job. Check that here:
Pavel Labath45dde232017-05-25 10:50:06 +00005166 const bool handle_interrupts = false;
5167 if (auto result = HandleStoppedEvent(
5168 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5169 event_to_broadcast_sp, options, handle_interrupts)) {
5170 return_value = *result;
5171 back_to_top = false;
5172 break;
5173 }
5174
Kate Stoneb9c1b512016-09-06 20:57:50 +00005175 if (!options.GetTryAllThreads()) {
5176 if (log)
5177 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5178 "was false, we stopped so now we're "
5179 "quitting.");
5180 return_value = eExpressionInterrupted;
5181 back_to_top = false;
5182 break;
5183 }
5184
5185 if (before_first_timeout) {
5186 // Set all the other threads to run, and return to the top of
5187 // the loop, which will continue;
5188 before_first_timeout = false;
5189 thread_plan_sp->SetStopOthers(false);
5190 if (log)
5191 log->PutCString(
5192 "Process::RunThreadPlan(): about to resume.");
5193
5194 back_to_top = true;
5195 break;
5196 } else {
5197 // Running all threads failed, so return Interrupted.
5198 if (log)
5199 log->PutCString("Process::RunThreadPlan(): running all "
5200 "threads timed out.");
5201 return_value = eExpressionInterrupted;
5202 back_to_top = false;
5203 break;
5204 }
5205 }
5206 } else {
5207 if (log)
5208 log->PutCString("Process::RunThreadPlan(): halt said it "
5209 "succeeded, but I got no event. "
5210 "I'm getting out of here passing Interrupted.");
5211 return_value = eExpressionInterrupted;
5212 back_to_top = false;
5213 break;
5214 }
5215 } else {
5216 try_halt_again++;
5217 continue;
5218 }
5219 }
5220
5221 if (!back_to_top || try_halt_again > num_retries)
5222 break;
5223 else
5224 continue;
5225 }
5226 } // END WAIT LOOP
5227
Adrian Prantl05097242018-04-30 16:49:04 +00005228 // If we had to start up a temporary private state thread to run this
5229 // thread plan, shut it down now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005230 if (backup_private_state_thread.IsJoinable()) {
5231 StopPrivateStateThread();
Zachary Turner97206d52017-05-12 04:51:55 +00005232 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005233 m_private_state_thread = backup_private_state_thread;
5234 if (stopper_base_plan_sp) {
5235 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5236 }
5237 if (old_state != eStateInvalid)
5238 m_public_state.SetValueNoLock(old_state);
Jason Molendaef7d6412015-08-06 03:27:10 +00005239 }
5240
Kate Stoneb9c1b512016-09-06 20:57:50 +00005241 if (return_value != eExpressionCompleted && log) {
5242 // Print a backtrace into the log so we can figure out where we are:
5243 StreamString s;
5244 s.PutCString("Thread state after unsuccessful completion: \n");
5245 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
Zachary Turnerc1564272016-11-16 21:15:24 +00005246 log->PutString(s.GetString());
Jason Molendaef7d6412015-08-06 03:27:10 +00005247 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005248 // Restore the thread state if we are going to discard the plan execution.
Adrian Prantl05097242018-04-30 16:49:04 +00005249 // There are three cases where this could happen: 1) The execution
5250 // successfully completed 2) We hit a breakpoint, and ignore_breakpoints
5251 // was true 3) We got some other error, and discard_on_error was true
Kate Stoneb9c1b512016-09-06 20:57:50 +00005252 bool should_unwind = (return_value == eExpressionInterrupted &&
5253 options.DoesUnwindOnError()) ||
5254 (return_value == eExpressionHitBreakpoint &&
5255 options.DoesIgnoreBreakpoints());
5256
5257 if (return_value == eExpressionCompleted || should_unwind) {
5258 thread_plan_sp->RestoreThreadState();
5259 }
5260
5261 // Now do some processing on the results of the run:
5262 if (return_value == eExpressionInterrupted ||
5263 return_value == eExpressionHitBreakpoint) {
5264 if (log) {
5265 StreamString s;
5266 if (event_sp)
5267 event_sp->Dump(&s);
5268 else {
5269 log->PutCString("Process::RunThreadPlan(): Stop event that "
5270 "interrupted us is NULL.");
5271 }
5272
5273 StreamString ts;
5274
5275 const char *event_explanation = nullptr;
5276
5277 do {
5278 if (!event_sp) {
5279 event_explanation = "<no event>";
5280 break;
5281 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5282 event_explanation = "<user interrupt>";
5283 break;
5284 } else {
5285 const Process::ProcessEventData *event_data =
5286 Process::ProcessEventData::GetEventDataFromEvent(
5287 event_sp.get());
5288
5289 if (!event_data) {
5290 event_explanation = "<no event data>";
5291 break;
5292 }
5293
5294 Process *process = event_data->GetProcessSP().get();
5295
5296 if (!process) {
5297 event_explanation = "<no process>";
5298 break;
5299 }
5300
5301 ThreadList &thread_list = process->GetThreadList();
5302
5303 uint32_t num_threads = thread_list.GetSize();
5304 uint32_t thread_index;
5305
5306 ts.Printf("<%u threads> ", num_threads);
5307
5308 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5309 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5310
5311 if (!thread) {
5312 ts.Printf("<?> ");
5313 continue;
5314 }
5315
5316 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5317 RegisterContext *register_context =
5318 thread->GetRegisterContext().get();
5319
5320 if (register_context)
5321 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5322 else
5323 ts.Printf("[ip unknown] ");
5324
5325 // Show the private stop info here, the public stop info will be
5326 // from the last natural stop.
5327 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5328 if (stop_info_sp) {
5329 const char *stop_desc = stop_info_sp->GetDescription();
5330 if (stop_desc)
5331 ts.PutCString(stop_desc);
5332 }
5333 ts.Printf(">");
5334 }
5335
5336 event_explanation = ts.GetData();
5337 }
5338 } while (0);
5339
5340 if (event_explanation)
5341 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s",
5342 s.GetData(), event_explanation);
5343 else
5344 log->Printf("Process::RunThreadPlan(): execution interrupted: %s",
5345 s.GetData());
5346 }
5347
5348 if (should_unwind) {
5349 if (log)
5350 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - "
5351 "discarding thread plans up to %p.",
5352 static_cast<void *>(thread_plan_sp.get()));
5353 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5354 } else {
5355 if (log)
5356 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - for "
5357 "plan: %p not discarding.",
5358 static_cast<void *>(thread_plan_sp.get()));
5359 }
5360 } else if (return_value == eExpressionSetupError) {
5361 if (log)
5362 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5363
5364 if (options.DoesUnwindOnError()) {
5365 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5366 }
5367 } else {
5368 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5369 if (log)
5370 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5371 return_value = eExpressionCompleted;
5372 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5373 if (log)
5374 log->PutCString(
5375 "Process::RunThreadPlan(): thread plan was discarded");
5376 return_value = eExpressionDiscarded;
5377 } else {
5378 if (log)
5379 log->PutCString(
5380 "Process::RunThreadPlan(): thread plan stopped in mid course");
5381 if (options.DoesUnwindOnError() && thread_plan_sp) {
5382 if (log)
5383 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5384 "'cause unwind_on_error is set.");
5385 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5386 }
5387 }
5388 }
5389
5390 // Thread we ran the function in may have gone away because we ran the
Adrian Prantl05097242018-04-30 16:49:04 +00005391 // target Check that it's still there, and if it is put it back in the
5392 // context. Also restore the frame in the context if it is still present.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005393 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5394 if (thread) {
5395 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5396 }
5397
5398 // Also restore the current process'es selected frame & thread, since this
Adrian Prantl05097242018-04-30 16:49:04 +00005399 // function calling may be done behind the user's back.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005400
5401 if (selected_tid != LLDB_INVALID_THREAD_ID) {
5402 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5403 selected_stack_id.IsValid()) {
5404 // We were able to restore the selected thread, now restore the frame:
5405 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5406 StackFrameSP old_frame_sp =
5407 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5408 selected_stack_id);
5409 if (old_frame_sp)
5410 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5411 old_frame_sp.get());
5412 }
5413 }
5414 }
5415
5416 // If the process exited during the run of the thread plan, notify everyone.
5417
5418 if (event_to_broadcast_sp) {
5419 if (log)
5420 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5421 BroadcastEvent(event_to_broadcast_sp);
5422 }
5423
5424 return return_value;
Jason Molendaef7d6412015-08-06 03:27:10 +00005425}
5426
Kate Stoneb9c1b512016-09-06 20:57:50 +00005427const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5428 const char *result_name;
5429
5430 switch (result) {
5431 case eExpressionCompleted:
5432 result_name = "eExpressionCompleted";
5433 break;
5434 case eExpressionDiscarded:
5435 result_name = "eExpressionDiscarded";
5436 break;
5437 case eExpressionInterrupted:
5438 result_name = "eExpressionInterrupted";
5439 break;
5440 case eExpressionHitBreakpoint:
5441 result_name = "eExpressionHitBreakpoint";
5442 break;
5443 case eExpressionSetupError:
5444 result_name = "eExpressionSetupError";
5445 break;
5446 case eExpressionParseError:
5447 result_name = "eExpressionParseError";
5448 break;
5449 case eExpressionResultUnavailable:
5450 result_name = "eExpressionResultUnavailable";
5451 break;
5452 case eExpressionTimedOut:
5453 result_name = "eExpressionTimedOut";
5454 break;
5455 case eExpressionStoppedForDebug:
5456 result_name = "eExpressionStoppedForDebug";
5457 break;
5458 }
5459 return result_name;
Jason Molenda484900b2015-08-10 07:55:25 +00005460}
5461
Kate Stoneb9c1b512016-09-06 20:57:50 +00005462void Process::GetStatus(Stream &strm) {
5463 const StateType state = GetState();
5464 if (StateIsStoppedState(state, false)) {
5465 if (state == eStateExited) {
5466 int exit_status = GetExitStatus();
5467 const char *exit_description = GetExitDescription();
5468 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5469 GetID(), exit_status, exit_status,
5470 exit_description ? exit_description : "");
5471 } else {
5472 if (state == eStateConnected)
5473 strm.Printf("Connected to remote target.\n");
5474 else
5475 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5476 }
5477 } else {
5478 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5479 }
Pavel Labatha933d512016-04-05 13:07:16 +00005480}
5481
Kate Stoneb9c1b512016-09-06 20:57:50 +00005482size_t Process::GetThreadStatus(Stream &strm,
5483 bool only_threads_with_stop_reason,
5484 uint32_t start_frame, uint32_t num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005485 uint32_t num_frames_with_source,
5486 bool stop_format) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005487 size_t num_thread_infos_dumped = 0;
Greg Clayton35ca64b2015-04-16 17:13:34 +00005488
Kate Stoneb9c1b512016-09-06 20:57:50 +00005489 // You can't hold the thread list lock while calling Thread::GetStatus. That
Adrian Prantl05097242018-04-30 16:49:04 +00005490 // very well might run code (e.g. if we need it to get return values or
5491 // arguments.) For that to work the process has to be able to acquire it.
5492 // So instead copy the thread ID's, and look them up one by one:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005493
5494 uint32_t num_threads;
5495 std::vector<lldb::tid_t> thread_id_array;
5496 // Scope for thread list locker;
5497 {
5498 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5499 ThreadList &curr_thread_list = GetThreadList();
5500 num_threads = curr_thread_list.GetSize();
5501 uint32_t idx;
5502 thread_id_array.resize(num_threads);
5503 for (idx = 0; idx < num_threads; ++idx)
5504 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5505 }
5506
5507 for (uint32_t i = 0; i < num_threads; i++) {
5508 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5509 if (thread_sp) {
5510 if (only_threads_with_stop_reason) {
5511 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5512 if (!stop_info_sp || !stop_info_sp->IsValid())
5513 continue;
5514 }
5515 thread_sp->GetStatus(strm, start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005516 num_frames_with_source,
5517 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005518 ++num_thread_infos_dumped;
5519 } else {
5520 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5521 if (log)
5522 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64
5523 " vanished while running Thread::GetStatus.");
Kuba Breckaa51ea382014-09-06 01:33:13 +00005524 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005525 }
5526 return num_thread_infos_dumped;
5527}
5528
5529void Process::AddInvalidMemoryRegion(const LoadRange &region) {
5530 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5531}
5532
5533bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
5534 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5535 region.GetByteSize());
5536}
5537
5538void Process::AddPreResumeAction(PreResumeActionCallback callback,
5539 void *baton) {
5540 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5541}
5542
5543bool Process::RunPreResumeActions() {
5544 bool result = true;
5545 while (!m_pre_resume_actions.empty()) {
5546 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5547 m_pre_resume_actions.pop_back();
5548 bool this_result = action.callback(action.baton);
5549 if (result)
5550 result = this_result;
5551 }
5552 return result;
5553}
5554
5555void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5556
Jim Inghamffd91752016-10-20 22:50:00 +00005557void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5558{
5559 PreResumeCallbackAndBaton element(callback, baton);
5560 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5561 if (found_iter != m_pre_resume_actions.end())
5562 {
5563 m_pre_resume_actions.erase(found_iter);
5564 }
5565}
5566
Kate Stoneb9c1b512016-09-06 20:57:50 +00005567ProcessRunLock &Process::GetRunLock() {
5568 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5569 return m_private_run_lock;
5570 else
5571 return m_public_run_lock;
5572}
5573
5574void Process::Flush() {
5575 m_thread_list.Flush();
5576 m_extended_thread_list.Flush();
5577 m_extended_thread_stop_id = 0;
5578 m_queue_list.Clear();
5579 m_queue_list_stop_id = 0;
5580}
5581
5582void Process::DidExec() {
5583 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
5584 if (log)
5585 log->Printf("Process::%s()", __FUNCTION__);
5586
5587 Target &target = GetTarget();
5588 target.CleanupProcess();
5589 target.ClearModules(false);
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005590 m_dynamic_checkers_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005591 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005592 m_system_runtime_up.reset();
5593 m_os_up.reset();
5594 m_dyld_up.reset();
5595 m_jit_loaders_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005596 m_image_tokens.clear();
5597 m_allocated_memory_cache.Clear();
5598 m_language_runtimes.clear();
5599 m_instrumentation_runtimes.clear();
5600 m_thread_list.DiscardThreadPlans();
5601 m_memory_cache.Clear(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005602 DoDidExec();
5603 CompleteAttach();
5604 // Flush the process (threads and all stack frames) after running
Adrian Prantl05097242018-04-30 16:49:04 +00005605 // CompleteAttach() in case the dynamic loader loaded things in new
5606 // locations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005607 Flush();
5608
Adrian Prantl05097242018-04-30 16:49:04 +00005609 // After we figure out what was loaded/unloaded in CompleteAttach, we need to
5610 // let the target know so it can do any cleanup it needs to.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005611 target.DidExec();
5612}
5613
Zachary Turner97206d52017-05-12 04:51:55 +00005614addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005615 if (address == nullptr) {
5616 error.SetErrorString("Invalid address argument");
5617 return LLDB_INVALID_ADDRESS;
5618 }
5619
5620 addr_t function_addr = LLDB_INVALID_ADDRESS;
5621
5622 addr_t addr = address->GetLoadAddress(&GetTarget());
5623 std::map<addr_t, addr_t>::const_iterator iter =
5624 m_resolved_indirect_addresses.find(addr);
5625 if (iter != m_resolved_indirect_addresses.end()) {
5626 function_addr = (*iter).second;
5627 } else {
5628 if (!InferiorCall(this, address, function_addr)) {
5629 Symbol *symbol = address->CalculateSymbolContextSymbol();
5630 error.SetErrorStringWithFormat(
5631 "Unable to call resolver for indirect function %s",
5632 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5633 function_addr = LLDB_INVALID_ADDRESS;
5634 } else {
5635 m_resolved_indirect_addresses.insert(
5636 std::pair<addr_t, addr_t>(addr, function_addr));
5637 }
5638 }
5639 return function_addr;
5640}
5641
5642void Process::ModulesDidLoad(ModuleList &module_list) {
5643 SystemRuntime *sys_runtime = GetSystemRuntime();
5644 if (sys_runtime) {
5645 sys_runtime->ModulesDidLoad(module_list);
5646 }
5647
5648 GetJITLoaders().ModulesDidLoad(module_list);
5649
5650 // Give runtimes a chance to be created.
5651 InstrumentationRuntime::ModulesDidLoad(module_list, this,
5652 m_instrumentation_runtimes);
5653
5654 // Tell runtimes about new modules.
5655 for (auto pos = m_instrumentation_runtimes.begin();
5656 pos != m_instrumentation_runtimes.end(); ++pos) {
5657 InstrumentationRuntimeSP runtime = pos->second;
5658 runtime->ModulesDidLoad(module_list);
5659 }
5660
Adrian Prantl05097242018-04-30 16:49:04 +00005661 // Let any language runtimes we have already created know about the modules
5662 // that loaded.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005663
Adrian Prantl05097242018-04-30 16:49:04 +00005664 // Iterate over a copy of this language runtime list in case the language
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005665 // runtime ModulesDidLoad somehow causes the language runtime to be
Adrian Prantl05097242018-04-30 16:49:04 +00005666 // unloaded.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005667 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5668 for (const auto &pair : language_runtimes) {
Adrian Prantl05097242018-04-30 16:49:04 +00005669 // We must check language_runtime_sp to make sure it is not nullptr as we
5670 // might cache the fact that we didn't have a language runtime for a
5671 // language.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005672 LanguageRuntimeSP language_runtime_sp = pair.second;
5673 if (language_runtime_sp)
5674 language_runtime_sp->ModulesDidLoad(module_list);
5675 }
5676
5677 // If we don't have an operating system plug-in, try to load one since
5678 // loading shared libraries might cause a new one to try and load
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005679 if (!m_os_up)
Kate Stoneb9c1b512016-09-06 20:57:50 +00005680 LoadOperatingSystemPlugin(false);
5681
5682 // Give structured-data plugins a chance to see the modified modules.
5683 for (auto pair : m_structured_data_plugin_map) {
5684 if (pair.second)
5685 pair.second->ModulesDidLoad(*this, module_list);
5686 }
5687}
5688
5689void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
5690 const char *fmt, ...) {
5691 bool print_warning = true;
5692
5693 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
5694 if (!stream_sp)
5695 return;
5696 if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) {
5697 return;
5698 }
5699
5700 if (repeat_key != nullptr) {
5701 WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
5702 if (it == m_warnings_issued.end()) {
5703 m_warnings_issued[warning_type] = WarningsPointerSet();
5704 m_warnings_issued[warning_type].insert(repeat_key);
5705 } else {
5706 if (it->second.find(repeat_key) != it->second.end()) {
5707 print_warning = false;
5708 } else {
5709 it->second.insert(repeat_key);
5710 }
5711 }
5712 }
5713
5714 if (print_warning) {
5715 va_list args;
5716 va_start(args, fmt);
5717 stream_sp->PrintfVarArg(fmt, args);
5718 va_end(args);
5719 }
5720}
5721
5722void Process::PrintWarningOptimization(const SymbolContext &sc) {
5723 if (GetWarningsOptimization() && sc.module_sp &&
5724 !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
5725 sc.function->GetIsOptimized()) {
5726 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
5727 "%s was compiled with optimization - stepping may behave "
5728 "oddly; variables may not be available.\n",
5729 sc.module_sp->GetFileSpec().GetFilename().GetCString());
5730 }
5731}
5732
5733bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
5734 info.Clear();
5735
5736 PlatformSP platform_sp = GetTarget().GetPlatform();
5737 if (!platform_sp)
5738 return false;
5739
5740 return platform_sp->GetProcessInfo(GetID(), info);
5741}
5742
5743ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
5744 ThreadCollectionSP threads;
5745
5746 const MemoryHistorySP &memory_history =
5747 MemoryHistory::FindPlugin(shared_from_this());
5748
5749 if (!memory_history) {
Kuba Breckaa51ea382014-09-06 01:33:13 +00005750 return threads;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005751 }
5752
Jonas Devlieghere796ac802019-02-11 23:13:08 +00005753 threads = std::make_shared<ThreadCollection>(
5754 memory_history->GetHistoryThreads(addr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005755
5756 return threads;
Kuba Breckaa51ea382014-09-06 01:33:13 +00005757}
Kuba Brecka63927542014-10-11 01:59:32 +00005758
5759InstrumentationRuntimeSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00005760Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
5761 InstrumentationRuntimeCollection::iterator pos;
5762 pos = m_instrumentation_runtimes.find(type);
5763 if (pos == m_instrumentation_runtimes.end()) {
5764 return InstrumentationRuntimeSP();
5765 } else
5766 return (*pos).second;
Kuba Brecka63927542014-10-11 01:59:32 +00005767}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005768
Kate Stoneb9c1b512016-09-06 20:57:50 +00005769bool Process::GetModuleSpec(const FileSpec &module_file_spec,
5770 const ArchSpec &arch, ModuleSpec &module_spec) {
5771 module_spec.Clear();
5772 return false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005773}
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005774
Kate Stoneb9c1b512016-09-06 20:57:50 +00005775size_t Process::AddImageToken(lldb::addr_t image_ptr) {
5776 m_image_tokens.push_back(image_ptr);
5777 return m_image_tokens.size() - 1;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005778}
5779
Kate Stoneb9c1b512016-09-06 20:57:50 +00005780lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
5781 if (token < m_image_tokens.size())
5782 return m_image_tokens[token];
5783 return LLDB_INVALID_IMAGE_TOKEN;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005784}
5785
Kate Stoneb9c1b512016-09-06 20:57:50 +00005786void Process::ResetImageToken(size_t token) {
5787 if (token < m_image_tokens.size())
5788 m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
Enrico Granataf3129cb2015-12-03 23:53:45 +00005789}
Jason Molendafd4cea52016-01-08 21:40:11 +00005790
5791Address
Kate Stoneb9c1b512016-09-06 20:57:50 +00005792Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
5793 AddressRange range_bounds) {
5794 Target &target = GetTarget();
5795 DisassemblerSP disassembler_sp;
5796 InstructionList *insn_list = nullptr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005797
Kate Stoneb9c1b512016-09-06 20:57:50 +00005798 Address retval = default_stop_addr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005799
Kate Stoneb9c1b512016-09-06 20:57:50 +00005800 if (!target.GetUseFastStepping())
Jason Molendafd4cea52016-01-08 21:40:11 +00005801 return retval;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005802 if (!default_stop_addr.IsValid())
5803 return retval;
5804
5805 ExecutionContext exe_ctx(this);
5806 const char *plugin_name = nullptr;
5807 const char *flavor = nullptr;
5808 const bool prefer_file_cache = true;
5809 disassembler_sp = Disassembler::DisassembleRange(
5810 target.GetArchitecture(), plugin_name, flavor, exe_ctx, range_bounds,
5811 prefer_file_cache);
5812 if (disassembler_sp)
5813 insn_list = &disassembler_sp->GetInstructionList();
5814
5815 if (insn_list == nullptr) {
5816 return retval;
5817 }
5818
5819 size_t insn_offset =
5820 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
5821 if (insn_offset == UINT32_MAX) {
5822 return retval;
5823 }
5824
5825 uint32_t branch_index =
5826 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target);
5827 if (branch_index == UINT32_MAX) {
5828 return retval;
5829 }
5830
5831 if (branch_index > insn_offset) {
5832 Address next_branch_insn_address =
5833 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
5834 if (next_branch_insn_address.IsValid() &&
5835 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
5836 retval = next_branch_insn_address;
5837 }
5838 }
5839
5840 return retval;
Jason Molendafd4cea52016-01-08 21:40:11 +00005841}
Howard Hellyerad007562016-07-07 08:21:28 +00005842
Zachary Turner97206d52017-05-12 04:51:55 +00005843Status
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005844Process::GetMemoryRegions(lldb_private::MemoryRegionInfos &region_list) {
Howard Hellyerad007562016-07-07 08:21:28 +00005845
Zachary Turner97206d52017-05-12 04:51:55 +00005846 Status error;
Howard Hellyerad007562016-07-07 08:21:28 +00005847
Kate Stoneb9c1b512016-09-06 20:57:50 +00005848 lldb::addr_t range_end = 0;
Howard Hellyerad007562016-07-07 08:21:28 +00005849
Kate Stoneb9c1b512016-09-06 20:57:50 +00005850 region_list.clear();
5851 do {
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005852 lldb_private::MemoryRegionInfo region_info;
5853 error = GetMemoryRegionInfo(range_end, region_info);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005854 // GetMemoryRegionInfo should only return an error if it is unimplemented.
5855 if (error.Fail()) {
5856 region_list.clear();
5857 break;
Todd Fiala75930012016-08-19 04:21:48 +00005858 }
5859
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005860 range_end = region_info.GetRange().GetRangeEnd();
5861 if (region_info.GetMapped() == MemoryRegionInfo::eYes) {
5862 region_list.push_back(std::move(region_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005863 }
5864 } while (range_end != LLDB_INVALID_ADDRESS);
Todd Fiala75930012016-08-19 04:21:48 +00005865
Kate Stoneb9c1b512016-09-06 20:57:50 +00005866 return error;
5867}
5868
Zachary Turner97206d52017-05-12 04:51:55 +00005869Status
5870Process::ConfigureStructuredData(const ConstString &type_name,
5871 const StructuredData::ObjectSP &config_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00005872 // If you get this, the Process-derived class needs to implement a method to
5873 // enable an already-reported asynchronous structured data feature. See
5874 // ProcessGDBRemote for an example implementation over gdb-remote.
Zachary Turner97206d52017-05-12 04:51:55 +00005875 return Status("unimplemented");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005876}
5877
5878void Process::MapSupportedStructuredDataPlugins(
5879 const StructuredData::Array &supported_type_names) {
5880 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5881
5882 // Bail out early if there are no type names to map.
5883 if (supported_type_names.GetSize() == 0) {
Todd Fiala75930012016-08-19 04:21:48 +00005884 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00005885 log->Printf("Process::%s(): no structured data types supported",
5886 __FUNCTION__);
5887 return;
5888 }
Todd Fiala75930012016-08-19 04:21:48 +00005889
Kate Stoneb9c1b512016-09-06 20:57:50 +00005890 // Convert StructuredData type names to ConstString instances.
5891 std::set<ConstString> const_type_names;
5892
5893 if (log)
5894 log->Printf("Process::%s(): the process supports the following async "
5895 "structured data types:",
5896 __FUNCTION__);
5897
5898 supported_type_names.ForEach(
5899 [&const_type_names, &log](StructuredData::Object *object) {
5900 if (!object) {
5901 // Invalid - shouldn't be null objects in the array.
5902 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005903 }
5904
5905 auto type_name = object->GetAsString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005906 if (!type_name) {
5907 // Invalid format - all type names should be strings.
5908 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005909 }
5910
5911 const_type_names.insert(ConstString(type_name->GetValue()));
Zachary Turner28333212017-05-12 05:49:54 +00005912 LLDB_LOG(log, "- {0}", type_name->GetValue());
Todd Fiala75930012016-08-19 04:21:48 +00005913 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005914 });
Todd Fiala75930012016-08-19 04:21:48 +00005915
Adrian Prantl05097242018-04-30 16:49:04 +00005916 // For each StructuredDataPlugin, if the plugin handles any of the types in
5917 // the supported_type_names, map that type name to that plugin. Stop when
5918 // we've consumed all the type names.
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005919 // FIXME: should we return an error if there are type names nobody
Jim Ingham93979f62018-04-27 01:57:40 +00005920 // supports?
5921 for (uint32_t plugin_index = 0; !const_type_names.empty(); plugin_index++) {
5922 auto create_instance =
Kate Stoneb9c1b512016-09-06 20:57:50 +00005923 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
5924 plugin_index);
Jim Ingham93979f62018-04-27 01:57:40 +00005925 if (!create_instance)
5926 break;
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005927
Kate Stoneb9c1b512016-09-06 20:57:50 +00005928 // Create the plugin.
5929 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
5930 if (!plugin_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00005931 // This plugin doesn't think it can work with the process. Move on to the
5932 // next.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005933 continue;
Todd Fiala75930012016-08-19 04:21:48 +00005934 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005935
Adrian Prantl05097242018-04-30 16:49:04 +00005936 // For any of the remaining type names, map any that this plugin supports.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005937 std::vector<ConstString> names_to_remove;
5938 for (auto &type_name : const_type_names) {
5939 if (plugin_sp->SupportsStructuredDataType(type_name)) {
5940 m_structured_data_plugin_map.insert(
5941 std::make_pair(type_name, plugin_sp));
5942 names_to_remove.push_back(type_name);
5943 if (log)
5944 log->Printf("Process::%s(): using plugin %s for type name "
5945 "%s",
5946 __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
5947 type_name.GetCString());
5948 }
5949 }
5950
5951 // Remove the type names that were consumed by this plugin.
5952 for (auto &type_name : names_to_remove)
5953 const_type_names.erase(type_name);
5954 }
Todd Fiala75930012016-08-19 04:21:48 +00005955}
5956
Kate Stoneb9c1b512016-09-06 20:57:50 +00005957bool Process::RouteAsyncStructuredData(
5958 const StructuredData::ObjectSP object_sp) {
5959 // Nothing to do if there's no data.
5960 if (!object_sp)
5961 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005962
Adrian Prantl05097242018-04-30 16:49:04 +00005963 // The contract is this must be a dictionary, so we can look up the routing
5964 // key via the top-level 'type' string value within the dictionary.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005965 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
5966 if (!dictionary)
5967 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005968
Kate Stoneb9c1b512016-09-06 20:57:50 +00005969 // Grab the async structured type name (i.e. the feature/plugin name).
5970 ConstString type_name;
5971 if (!dictionary->GetValueForKeyAsString("type", type_name))
5972 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005973
Kate Stoneb9c1b512016-09-06 20:57:50 +00005974 // Check if there's a plugin registered for this type name.
5975 auto find_it = m_structured_data_plugin_map.find(type_name);
5976 if (find_it == m_structured_data_plugin_map.end()) {
5977 // We don't have a mapping for this structured data type.
5978 return false;
5979 }
Todd Fiala75930012016-08-19 04:21:48 +00005980
Kate Stoneb9c1b512016-09-06 20:57:50 +00005981 // Route the structured data to the plugin.
5982 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
5983 return true;
Howard Hellyerad007562016-07-07 08:21:28 +00005984}
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00005985
Zachary Turner97206d52017-05-12 04:51:55 +00005986Status Process::UpdateAutomaticSignalFiltering() {
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00005987 // Default implementation does nothign.
5988 // No automatic signal filtering to speak of.
Zachary Turner97206d52017-05-12 04:51:55 +00005989 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00005990}
Jim Ingham1ecb34f2018-04-17 20:44:47 +00005991
Frederic Rissd10d3792018-05-11 18:21:11 +00005992UtilityFunction *Process::GetLoadImageUtilityFunction(
5993 Platform *platform,
5994 llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) {
Jim Ingham1ecb34f2018-04-17 20:44:47 +00005995 if (platform != GetTarget().GetPlatform().get())
5996 return nullptr;
Frederic Rissd10d3792018-05-11 18:21:11 +00005997 std::call_once(m_dlopen_utility_func_flag_once,
5998 [&] { m_dlopen_utility_func_up = factory(); });
Jim Ingham1ecb34f2018-04-17 20:44:47 +00005999 return m_dlopen_utility_func_up.get();
6000}