blob: 7c668a216a3a2f72c4b5da2fa7007beb690fe1c0 [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:
Adrian Prantl0e4c4822019-03-06 21:22:25 +000087 ProcessOptionValueProperties(ConstString name)
Kate Stoneb9c1b512016-09-06 20:57:50 +000088 : 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, {},
Adrian Prantl4c03ea12019-04-05 22:43:42 +0000147 "If true, stop when a shared library is loaded or unloaded."},
148 {"utility-expression-timeout", OptionValue::eTypeUInt64, false, 15,
149 nullptr, {},
150 "The time in seconds to wait for LLDB-internal utility expressions."}
151};
Greg Clayton67cc0632012-08-22 17:17:09 +0000152
153enum {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000154 ePropertyDisableMemCache,
155 ePropertyExtraStartCommand,
156 ePropertyIgnoreBreakpointsInExpressions,
157 ePropertyUnwindOnErrorInExpressions,
158 ePropertyPythonOSPluginPath,
159 ePropertyStopOnSharedLibraryEvents,
160 ePropertyDetachKeepsStopped,
161 ePropertyMemCacheLineSize,
Jim Inghamba205c12017-12-05 02:50:45 +0000162 ePropertyWarningOptimization,
Adrian Prantl4c03ea12019-04-05 22:43:42 +0000163 ePropertyStopOnExec,
164 ePropertyUtilityExpressionTimeout,
Greg Clayton67cc0632012-08-22 17:17:09 +0000165};
166
Kate Stoneb9c1b512016-09-06 20:57:50 +0000167ProcessProperties::ProcessProperties(lldb_private::Process *process)
168 : Properties(),
169 m_process(process) // Can be nullptr for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000170{
Kate Stoneb9c1b512016-09-06 20:57:50 +0000171 if (process == nullptr) {
172 // Global process properties, set them up one time
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000173 m_collection_sp =
174 std::make_shared<ProcessOptionValueProperties>(ConstString("process"));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000175 m_collection_sp->Initialize(g_properties);
176 m_collection_sp->AppendProperty(
177 ConstString("thread"), ConstString("Settings specific to threads."),
178 true, Thread::GetGlobalProperties()->GetValueProperties());
179 } else {
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000180 m_collection_sp = std::make_shared<ProcessOptionValueProperties>(
181 Process::GetGlobalProperties().get());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000182 m_collection_sp->SetValueChangedCallback(
183 ePropertyPythonOSPluginPath,
184 ProcessProperties::OptionValueChangedCallback, this);
185 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000186}
187
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000188ProcessProperties::~ProcessProperties() = default;
Greg Clayton67cc0632012-08-22 17:17:09 +0000189
Kate Stoneb9c1b512016-09-06 20:57:50 +0000190void ProcessProperties::OptionValueChangedCallback(void *baton,
191 OptionValue *option_value) {
192 ProcessProperties *properties = (ProcessProperties *)baton;
193 if (properties->m_process)
194 properties->m_process->LoadOperatingSystemPlugin(true);
Greg Clayton332e8b12015-01-13 21:13:08 +0000195}
196
Kate Stoneb9c1b512016-09-06 20:57:50 +0000197bool ProcessProperties::GetDisableMemoryCache() const {
198 const uint32_t idx = ePropertyDisableMemCache;
199 return m_collection_sp->GetPropertyAtIndexAsBoolean(
200 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000201}
202
Kate Stoneb9c1b512016-09-06 20:57:50 +0000203uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
204 const uint32_t idx = ePropertyMemCacheLineSize;
205 return m_collection_sp->GetPropertyAtIndexAsUInt64(
206 nullptr, idx, g_properties[idx].default_uint_value);
Jason Molendaf0340c92014-09-03 22:30:54 +0000207}
208
Kate Stoneb9c1b512016-09-06 20:57:50 +0000209Args ProcessProperties::GetExtraStartupCommands() const {
210 Args args;
211 const uint32_t idx = ePropertyExtraStartCommand;
212 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
213 return args;
Greg Clayton67cc0632012-08-22 17:17:09 +0000214}
215
Kate Stoneb9c1b512016-09-06 20:57:50 +0000216void ProcessProperties::SetExtraStartupCommands(const Args &args) {
217 const uint32_t idx = ePropertyExtraStartCommand;
218 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +0000219}
220
Kate Stoneb9c1b512016-09-06 20:57:50 +0000221FileSpec ProcessProperties::GetPythonOSPluginPath() const {
222 const uint32_t idx = ePropertyPythonOSPluginPath;
223 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000224}
225
Kate Stoneb9c1b512016-09-06 20:57:50 +0000226void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {
227 const uint32_t idx = ePropertyPythonOSPluginPath;
228 m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000229}
230
Kate Stoneb9c1b512016-09-06 20:57:50 +0000231bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
232 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
233 return m_collection_sp->GetPropertyAtIndexAsBoolean(
234 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham184e9812013-01-15 02:47:48 +0000235}
236
Kate Stoneb9c1b512016-09-06 20:57:50 +0000237void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {
238 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
239 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Ingham184e9812013-01-15 02:47:48 +0000240}
241
Kate Stoneb9c1b512016-09-06 20:57:50 +0000242bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
243 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
244 return m_collection_sp->GetPropertyAtIndexAsBoolean(
245 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham29950772013-01-26 02:19:28 +0000246}
247
Kate Stoneb9c1b512016-09-06 20:57:50 +0000248void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {
249 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
250 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Inghamacff8952013-05-02 00:27:30 +0000251}
252
Kate Stoneb9c1b512016-09-06 20:57:50 +0000253bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
254 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
255 return m_collection_sp->GetPropertyAtIndexAsBoolean(
256 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jason Molendaef7d6412015-08-06 03:27:10 +0000257}
258
Kate Stoneb9c1b512016-09-06 20:57:50 +0000259void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {
260 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
261 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
262}
263
264bool ProcessProperties::GetDetachKeepsStopped() const {
265 const uint32_t idx = ePropertyDetachKeepsStopped;
266 return m_collection_sp->GetPropertyAtIndexAsBoolean(
267 nullptr, idx, g_properties[idx].default_uint_value != 0);
268}
269
270void ProcessProperties::SetDetachKeepsStopped(bool stop) {
271 const uint32_t idx = ePropertyDetachKeepsStopped;
272 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
273}
274
275bool ProcessProperties::GetWarningsOptimization() const {
276 const uint32_t idx = ePropertyWarningOptimization;
277 return m_collection_sp->GetPropertyAtIndexAsBoolean(
278 nullptr, idx, g_properties[idx].default_uint_value != 0);
279}
280
Jim Inghamba205c12017-12-05 02:50:45 +0000281bool ProcessProperties::GetStopOnExec() const {
282 const uint32_t idx = ePropertyStopOnExec;
283 return m_collection_sp->GetPropertyAtIndexAsBoolean(
284 nullptr, idx, g_properties[idx].default_uint_value != 0);
285}
286
Adrian Prantl4c03ea12019-04-05 22:43:42 +0000287std::chrono::seconds ProcessProperties::GetUtilityExpressionTimeout() const {
288 const uint32_t idx = ePropertyUtilityExpressionTimeout;
289 uint64_t value = m_collection_sp->GetPropertyAtIndexAsUInt64(
290 nullptr, idx, g_properties[idx].default_uint_value);
291 return std::chrono::seconds(value);
292}
293
Zachary Turner97206d52017-05-12 04:51:55 +0000294Status ProcessLaunchCommandOptions::SetOptionValue(
Zachary Turnerfe114832016-11-12 16:56:47 +0000295 uint32_t option_idx, llvm::StringRef option_arg,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000296 ExecutionContext *execution_context) {
Zachary Turner97206d52017-05-12 04:51:55 +0000297 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000298 const int short_option = m_getopt_table[option_idx].val;
299
300 switch (short_option) {
301 case 's': // Stop at program entry point
302 launch_info.GetFlags().Set(eLaunchFlagStopAtEntry);
303 break;
304
305 case 'i': // STDIN for read only
306 {
307 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000308 if (action.Open(STDIN_FILENO, FileSpec(option_arg), true, false))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000309 launch_info.AppendFileAction(action);
310 break;
311 }
312
313 case 'o': // Open STDOUT for write only
314 {
315 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000316 if (action.Open(STDOUT_FILENO, FileSpec(option_arg), false, true))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000317 launch_info.AppendFileAction(action);
318 break;
319 }
320
321 case 'e': // STDERR for write only
322 {
323 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000324 if (action.Open(STDERR_FILENO, FileSpec(option_arg), false, true))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000325 launch_info.AppendFileAction(action);
326 break;
327 }
328
329 case 'p': // Process plug-in name
330 launch_info.SetProcessPluginName(option_arg);
331 break;
332
333 case 'n': // Disable STDIO
334 {
335 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000336 const FileSpec dev_null(FileSystem::DEV_NULL);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000337 if (action.Open(STDIN_FILENO, dev_null, true, false))
338 launch_info.AppendFileAction(action);
339 if (action.Open(STDOUT_FILENO, dev_null, false, true))
340 launch_info.AppendFileAction(action);
341 if (action.Open(STDERR_FILENO, dev_null, false, true))
342 launch_info.AppendFileAction(action);
343 break;
344 }
345
346 case 'w':
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000347 launch_info.SetWorkingDirectory(FileSpec(option_arg));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000348 break;
349
350 case 't': // Open process in new terminal window
351 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
352 break;
353
354 case 'a': {
355 TargetSP target_sp =
356 execution_context ? execution_context->GetTargetSP() : TargetSP();
357 PlatformSP platform_sp =
358 target_sp ? target_sp->GetPlatform() : PlatformSP();
Pavel Labath7263f1b2017-10-31 10:56:03 +0000359 launch_info.GetArchitecture() =
360 Platform::GetAugmentedArchSpec(platform_sp.get(), option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000361 } break;
362
363 case 'A': // Disable ASLR.
364 {
365 bool success;
366 const bool disable_aslr_arg =
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000367 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000368 if (success)
369 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
Greg Clayton8b82f082011-04-12 05:54:46 +0000370 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000371 error.SetErrorStringWithFormat(
372 "Invalid boolean value for disable-aslr option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000373 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374 break;
375 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000376
Kate Stoneb9c1b512016-09-06 20:57:50 +0000377 case 'X': // shell expand args.
378 {
379 bool success;
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000380 const bool expand_args =
381 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000382 if (success)
383 launch_info.SetShellExpandArguments(expand_args);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000384 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000385 error.SetErrorStringWithFormat(
386 "Invalid boolean value for shell-expand-args option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000387 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000388 break;
389 }
390
391 case 'c':
Zachary Turnerfe114832016-11-12 16:56:47 +0000392 if (!option_arg.empty())
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000393 launch_info.SetShell(FileSpec(option_arg));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000394 else
395 launch_info.SetShell(HostInfo::GetDefaultShell());
396 break;
397
398 case 'v':
Pavel Labath62930e52018-01-10 11:57:31 +0000399 launch_info.GetEnvironment().insert(option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000400 break;
401
402 default:
403 error.SetErrorStringWithFormat("unrecognized short option character '%c'",
404 short_option);
405 break;
406 }
407 return error;
Greg Clayton32e0a752011-03-30 18:16:51 +0000408}
409
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000410static constexpr OptionDefinition g_process_launch_options[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000411 {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000412 nullptr, {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000413 "Stop at the entry point of the program when launching a process."},
414 {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000415 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000416 "Set whether to disable address space layout randomization when launching "
417 "a process."},
418 {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000419 nullptr, {}, 0, eArgTypePlugin,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000420 "Name of the process plugin you want to use."},
421 {LLDB_OPT_SET_ALL, false, "working-dir", 'w',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000422 OptionParser::eRequiredArgument, nullptr, {}, 0,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000423 eArgTypeDirectoryName,
424 "Set the current working directory to <path> when running the inferior."},
425 {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000426 nullptr, {}, 0, eArgTypeArchitecture,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000427 "Set the architecture for the process to launch when ambiguous."},
428 {LLDB_OPT_SET_ALL, false, "environment", 'v',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000429 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000430 "Specify an environment variable name/value string (--environment "
431 "NAME=VALUE). Can be specified multiple times for subsequent environment "
432 "entries."},
433 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000434 OptionParser::eOptionalArgument, nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000435 "Run the process in a shell (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000436
Kate Stoneb9c1b512016-09-06 20:57:50 +0000437 {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000438 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000439 "Redirect stdin for the process to <filename>."},
440 {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000441 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000442 "Redirect stdout for the process to <filename>."},
443 {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000444 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000445 "Redirect stderr for the process to <filename>."},
Todd Fiala7df337f2015-10-13 23:41:19 +0000446
Kate Stoneb9c1b512016-09-06 20:57:50 +0000447 {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000448 {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000449 "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000450
Kate Stoneb9c1b512016-09-06 20:57:50 +0000451 {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000452 {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000453 "Do not set up for terminal I/O to go to running process."},
454 {LLDB_OPT_SET_4, false, "shell-expand-args", 'X',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000455 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000456 "Set whether to shell expand arguments to the process when launching."},
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000457};
458
459llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() {
Zachary Turner70602432016-09-22 21:06:13 +0000460 return llvm::makeArrayRef(g_process_launch_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000461}
Greg Clayton32e0a752011-03-30 18:16:51 +0000462
Zachary Turner31659452016-11-17 21:15:14 +0000463ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
464 llvm::StringRef plugin_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000465 ListenerSP listener_sp,
466 const FileSpec *crash_file_path) {
467 static uint32_t g_process_unique_id = 0;
468
469 ProcessSP process_sp;
470 ProcessCreateInstance create_callback = nullptr;
Zachary Turner31659452016-11-17 21:15:14 +0000471 if (!plugin_name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000472 ConstString const_plugin_name(plugin_name);
473 create_callback =
474 PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
475 if (create_callback) {
476 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
477 if (process_sp) {
478 if (process_sp->CanDebug(target_sp, true)) {
479 process_sp->m_process_unique_id = ++g_process_unique_id;
480 } else
481 process_sp.reset();
482 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000483 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000484 } else {
485 for (uint32_t idx = 0;
486 (create_callback =
487 PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
488 ++idx) {
489 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
490 if (process_sp) {
491 if (process_sp->CanDebug(target_sp, false)) {
492 process_sp->m_process_unique_id = ++g_process_unique_id;
493 break;
494 } else
495 process_sp.reset();
496 }
497 }
498 }
499 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000500}
501
Kate Stoneb9c1b512016-09-06 20:57:50 +0000502ConstString &Process::GetStaticBroadcasterClass() {
503 static ConstString class_name("lldb.process");
504 return class_name;
505}
506
507Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
508 : Process(target_sp, listener_sp,
509 UnixSignals::Create(HostInfo::GetArchitecture())) {
510 // This constructor just delegates to the full Process constructor,
511 // defaulting to using the Host's UnixSignals.
512}
513
514Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
515 const UnixSignalsSP &unix_signals_sp)
516 : ProcessProperties(this), UserID(LLDB_INVALID_PROCESS_ID),
517 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
518 Process::GetStaticBroadcasterClass().AsCString()),
Jim Inghamb87b9e62018-06-26 23:38:58 +0000519 m_target_wp(target_sp), m_public_state(eStateUnloaded),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000520 m_private_state(eStateUnloaded),
521 m_private_state_broadcaster(nullptr,
522 "lldb.process.internal_state_broadcaster"),
523 m_private_state_control_broadcaster(
524 nullptr, "lldb.process.internal_state_control_broadcaster"),
525 m_private_state_listener_sp(
526 Listener::MakeListener("lldb.process.internal_state_listener")),
527 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
528 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
529 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
530 m_thread_list(this), m_extended_thread_list(this),
531 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
532 m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000533 m_breakpoint_site_list(), m_dynamic_checkers_up(),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000534 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
535 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
536 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
537 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
538 m_memory_cache(*this), m_allocated_memory_cache(*this),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000539 m_should_detach(false), m_next_event_action_up(), m_public_run_lock(),
Pavel Labath13e37d42017-10-25 21:05:31 +0000540 m_private_run_lock(), m_finalizing(false), m_finalize_called(false),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000541 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
542 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
543 m_can_interpret_function_calls(false), m_warnings_issued(),
544 m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
545 CheckInWithManager();
546
547 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
548 if (log)
549 log->Printf("%p Process::Process()", static_cast<void *>(this));
550
551 if (!m_unix_signals_sp)
552 m_unix_signals_sp = std::make_shared<UnixSignals>();
553
554 SetEventName(eBroadcastBitStateChanged, "state-changed");
555 SetEventName(eBroadcastBitInterrupt, "interrupt");
556 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
557 SetEventName(eBroadcastBitSTDERR, "stderr-available");
558 SetEventName(eBroadcastBitProfileData, "profile-data-available");
559 SetEventName(eBroadcastBitStructuredData, "structured-data-available");
560
561 m_private_state_control_broadcaster.SetEventName(
562 eBroadcastInternalStateControlStop, "control-stop");
563 m_private_state_control_broadcaster.SetEventName(
564 eBroadcastInternalStateControlPause, "control-pause");
565 m_private_state_control_broadcaster.SetEventName(
566 eBroadcastInternalStateControlResume, "control-resume");
567
568 m_listener_sp->StartListeningForEvents(
569 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
570 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
571 eBroadcastBitProfileData | eBroadcastBitStructuredData);
572
573 m_private_state_listener_sp->StartListeningForEvents(
574 &m_private_state_broadcaster,
575 eBroadcastBitStateChanged | eBroadcastBitInterrupt);
576
577 m_private_state_listener_sp->StartListeningForEvents(
578 &m_private_state_control_broadcaster,
579 eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
580 eBroadcastInternalStateControlResume);
581 // We need something valid here, even if just the default UnixSignalsSP.
582 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
583
584 // Allow the platform to override the default cache line size
585 OptionValueSP value_sp =
586 m_collection_sp
587 ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
588 ->GetValue();
589 uint32_t platform_cache_line_size =
590 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
591 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
592 value_sp->SetUInt64Value(platform_cache_line_size);
593}
594
595Process::~Process() {
596 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
597 if (log)
598 log->Printf("%p Process::~Process()", static_cast<void *>(this));
599 StopPrivateStateThread();
600
601 // ThreadList::Clear() will try to acquire this process's mutex, so
Adrian Prantl05097242018-04-30 16:49:04 +0000602 // explicitly clear the thread list here to ensure that the mutex is not
603 // destroyed before the thread list.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000604 m_thread_list.Clear();
605}
606
607const ProcessPropertiesSP &Process::GetGlobalProperties() {
608 // NOTE: intentional leak so we don't crash if global destructor chain gets
609 // called as other threads still use the result of this function
Pavel Labath5f05ea82016-10-19 15:12:45 +0000610 static ProcessPropertiesSP *g_settings_sp_ptr =
611 new ProcessPropertiesSP(new ProcessProperties(nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000612 return *g_settings_sp_ptr;
613}
614
615void Process::Finalize() {
616 m_finalizing = true;
617
618 // Destroy this process if needed
619 switch (GetPrivateState()) {
620 case eStateConnected:
621 case eStateAttaching:
622 case eStateLaunching:
623 case eStateStopped:
624 case eStateRunning:
625 case eStateStepping:
626 case eStateCrashed:
627 case eStateSuspended:
628 Destroy(false);
629 break;
630
631 case eStateInvalid:
632 case eStateUnloaded:
633 case eStateDetached:
634 case eStateExited:
635 break;
636 }
637
638 // Clear our broadcaster before we proceed with destroying
639 Broadcaster::Clear();
640
Adrian Prantl05097242018-04-30 16:49:04 +0000641 // Do any cleanup needed prior to being destructed... Subclasses that
642 // override this method should call this superclass method as well.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000643
644 // We need to destroy the loader before the derived Process class gets
Adrian Prantl05097242018-04-30 16:49:04 +0000645 // destroyed since it is very likely that undoing the loader will require
646 // access to the real process.
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000647 m_dynamic_checkers_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000648 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000649 m_os_up.reset();
650 m_system_runtime_up.reset();
651 m_dyld_up.reset();
652 m_jit_loaders_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000653 m_thread_list_real.Destroy();
654 m_thread_list.Destroy();
655 m_extended_thread_list.Destroy();
656 m_queue_list.Clear();
657 m_queue_list_stop_id = 0;
658 std::vector<Notifications> empty_notifications;
659 m_notifications.swap(empty_notifications);
660 m_image_tokens.clear();
661 m_memory_cache.Clear();
662 m_allocated_memory_cache.Clear();
Alex Langford74eb76f2019-05-22 23:01:18 +0000663 {
664 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
665 m_language_runtimes.clear();
666 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000667 m_instrumentation_runtimes.clear();
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000668 m_next_event_action_up.reset();
Adrian Prantl05097242018-04-30 16:49:04 +0000669 // Clear the last natural stop ID since it has a strong reference to this
670 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +0000671 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
672 //#ifdef LLDB_CONFIGURATION_DEBUG
673 // StreamFile s(stdout, false);
674 // EventSP event_sp;
675 // while (m_private_state_listener_sp->GetNextEvent(event_sp))
676 // {
677 // event_sp->Dump (&s);
678 // s.EOL();
679 // }
680 //#endif
681 // We have to be very careful here as the m_private_state_listener might
682 // contain events that have ProcessSP values in them which can keep this
683 // process around forever. These events need to be cleared out.
684 m_private_state_listener_sp->Clear();
685 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
686 m_public_run_lock.SetStopped();
687 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
688 m_private_run_lock.SetStopped();
Jason Molenda38267272016-12-16 02:48:39 +0000689 m_structured_data_plugin_map.clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000690 m_finalize_called = true;
691}
692
693void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
694 m_notifications.push_back(callbacks);
695 if (callbacks.initialize != nullptr)
696 callbacks.initialize(callbacks.baton, this);
697}
698
699bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
700 std::vector<Notifications>::iterator pos, end = m_notifications.end();
701 for (pos = m_notifications.begin(); pos != end; ++pos) {
702 if (pos->baton == callbacks.baton &&
703 pos->initialize == callbacks.initialize &&
704 pos->process_state_changed == callbacks.process_state_changed) {
705 m_notifications.erase(pos);
706 return true;
707 }
708 }
709 return false;
710}
711
712void Process::SynchronouslyNotifyStateChanged(StateType state) {
713 std::vector<Notifications>::iterator notification_pos,
714 notification_end = m_notifications.end();
715 for (notification_pos = m_notifications.begin();
716 notification_pos != notification_end; ++notification_pos) {
717 if (notification_pos->process_state_changed)
718 notification_pos->process_state_changed(notification_pos->baton, this,
719 state);
720 }
721}
722
723// FIXME: We need to do some work on events before the general Listener sees
724// them.
725// For instance if we are continuing from a breakpoint, we need to ensure that
Adrian Prantl05097242018-04-30 16:49:04 +0000726// we do the little "insert real insn, step & stop" trick. But we can't do
727// that when the event is delivered by the broadcaster - since that is done on
728// the thread that is waiting for new events, so if we needed more than one
729// event for our handling, we would stall. So instead we do it when we fetch
730// the event off of the queue.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000731//
732
Kate Stoneb9c1b512016-09-06 20:57:50 +0000733StateType Process::GetNextEvent(EventSP &event_sp) {
734 StateType state = eStateInvalid;
735
Pavel Labathd35031e12016-11-30 10:41:42 +0000736 if (m_listener_sp->GetEventForBroadcaster(this, event_sp,
737 std::chrono::seconds(0)) &&
738 event_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000739 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
740
741 return state;
742}
743
Pavel Labath3879fe02018-05-09 14:29:30 +0000744void Process::SyncIOHandler(uint32_t iohandler_id,
745 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000746 // don't sync (potentially context switch) in case where there is no process
747 // IO
748 if (!m_process_input_reader)
749 return;
750
Pavel Labath3879fe02018-05-09 14:29:30 +0000751 auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000752
753 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labath3879fe02018-05-09 14:29:30 +0000754 if (Result) {
755 LLDB_LOG(
756 log,
757 "waited from m_iohandler_sync to change from {0}. New value is {1}.",
758 iohandler_id, *Result);
759 } else {
760 LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.",
761 iohandler_id);
762 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000763}
764
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000765StateType Process::WaitForProcessToStop(const Timeout<std::micro> &timeout,
766 EventSP *event_sp_ptr, bool wait_always,
767 ListenerSP hijack_listener_sp,
768 Stream *stream, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000769 // We can't just wait for a "stopped" event, because the stopped event may
Adrian Prantl05097242018-04-30 16:49:04 +0000770 // have restarted the target. We have to actually check each event, and in
771 // the case of a stopped event check the restarted flag on the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000772 if (event_sp_ptr)
773 event_sp_ptr->reset();
774 StateType state = GetState();
Adrian Prantl05097242018-04-30 16:49:04 +0000775 // If we are exited or detached, we won't ever get back to any other valid
776 // state...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000777 if (state == eStateDetached || state == eStateExited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000778 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000779
Kate Stoneb9c1b512016-09-06 20:57:50 +0000780 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +0000781 LLDB_LOG(log, "timeout = {0}", timeout);
Todd Fialaa3b89e22014-08-12 14:33:19 +0000782
Kate Stoneb9c1b512016-09-06 20:57:50 +0000783 if (!wait_always && StateIsStoppedState(state, true) &&
784 StateIsStoppedState(GetPrivateState(), true)) {
Pavel Labath44464872015-05-27 12:40:32 +0000785 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000786 log->Printf("Process::%s returning without waiting for events; process "
787 "private and public states are already 'stopped'.",
788 __FUNCTION__);
789 // We need to toggle the run lock as this won't get done in
790 // SetPublicState() if the process is hijacked.
791 if (hijack_listener_sp && use_run_lock)
792 m_public_run_lock.SetStopped();
793 return state;
794 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000795
Kate Stoneb9c1b512016-09-06 20:57:50 +0000796 while (state != eStateInvalid) {
797 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000798 state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000799 if (event_sp_ptr && event_sp)
800 *event_sp_ptr = event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +0000801
Kate Stoneb9c1b512016-09-06 20:57:50 +0000802 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
803 Process::HandleProcessStateChangedEvent(event_sp, stream,
804 pop_process_io_handler);
Daniel Malea9e9919f2013-10-09 16:56:28 +0000805
Kate Stoneb9c1b512016-09-06 20:57:50 +0000806 switch (state) {
807 case eStateCrashed:
808 case eStateDetached:
809 case eStateExited:
810 case eStateUnloaded:
811 // We need to toggle the run lock as this won't get done in
812 // SetPublicState() if the process is hijacked.
813 if (hijack_listener_sp && use_run_lock)
814 m_public_run_lock.SetStopped();
815 return state;
816 case eStateStopped:
817 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
818 continue;
819 else {
Pavel Labath78521ef2015-03-06 10:52:47 +0000820 // We need to toggle the run lock as this won't get done in
821 // SetPublicState() if the process is hijacked.
Jim Ingham583bbb12016-03-07 21:50:25 +0000822 if (hijack_listener_sp && use_run_lock)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000823 m_public_run_lock.SetStopped();
824 return state;
825 }
826 default:
827 continue;
828 }
829 }
830 return state;
831}
832
833bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
834 Stream *stream,
835 bool &pop_process_io_handler) {
836 const bool handle_pop = pop_process_io_handler;
837
838 pop_process_io_handler = false;
839 ProcessSP process_sp =
840 Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
841
842 if (!process_sp)
843 return false;
844
845 StateType event_state =
846 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
847 if (event_state == eStateInvalid)
848 return false;
849
850 switch (event_state) {
851 case eStateInvalid:
852 case eStateUnloaded:
853 case eStateAttaching:
854 case eStateLaunching:
855 case eStateStepping:
856 case eStateDetached:
857 if (stream)
858 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
859 StateAsCString(event_state));
860 if (event_state == eStateDetached)
861 pop_process_io_handler = true;
862 break;
863
864 case eStateConnected:
865 case eStateRunning:
866 // Don't be chatty when we run...
867 break;
868
869 case eStateExited:
870 if (stream)
871 process_sp->GetStatus(*stream);
872 pop_process_io_handler = true;
873 break;
874
875 case eStateStopped:
876 case eStateCrashed:
877 case eStateSuspended:
878 // Make sure the program hasn't been auto-restarted:
879 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
880 if (stream) {
881 size_t num_reasons =
882 Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
883 if (num_reasons > 0) {
884 // FIXME: Do we want to report this, or would that just be annoyingly
885 // chatty?
886 if (num_reasons == 1) {
887 const char *reason =
888 Process::ProcessEventData::GetRestartedReasonAtIndex(
889 event_sp.get(), 0);
890 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
891 process_sp->GetID(),
892 reason ? reason : "<UNKNOWN REASON>");
893 } else {
894 stream->Printf("Process %" PRIu64
895 " stopped and restarted, reasons:\n",
896 process_sp->GetID());
897
898 for (size_t i = 0; i < num_reasons; i++) {
899 const char *reason =
900 Process::ProcessEventData::GetRestartedReasonAtIndex(
901 event_sp.get(), i);
902 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
903 }
904 }
905 }
906 }
907 } else {
908 StopInfoSP curr_thread_stop_info_sp;
909 // Lock the thread list so it doesn't change on us, this is the scope for
910 // the locker:
911 {
912 ThreadList &thread_list = process_sp->GetThreadList();
913 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
914
915 ThreadSP curr_thread(thread_list.GetSelectedThread());
916 ThreadSP thread;
917 StopReason curr_thread_stop_reason = eStopReasonInvalid;
918 if (curr_thread) {
919 curr_thread_stop_reason = curr_thread->GetStopReason();
920 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
921 }
922 if (!curr_thread || !curr_thread->IsValid() ||
923 curr_thread_stop_reason == eStopReasonInvalid ||
924 curr_thread_stop_reason == eStopReasonNone) {
925 // Prefer a thread that has just completed its plan over another
926 // thread as current thread.
927 ThreadSP plan_thread;
928 ThreadSP other_thread;
929
930 const size_t num_threads = thread_list.GetSize();
931 size_t i;
932 for (i = 0; i < num_threads; ++i) {
933 thread = thread_list.GetThreadAtIndex(i);
934 StopReason thread_stop_reason = thread->GetStopReason();
935 switch (thread_stop_reason) {
936 case eStopReasonInvalid:
937 case eStopReasonNone:
938 break;
939
940 case eStopReasonSignal: {
941 // Don't select a signal thread if we weren't going to stop at
Adrian Prantl05097242018-04-30 16:49:04 +0000942 // that signal. We have to have had another reason for stopping
943 // here, and the user doesn't want to see this thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000944 uint64_t signo = thread->GetStopInfo()->GetValue();
945 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
946 if (!other_thread)
947 other_thread = thread;
948 }
949 break;
950 }
951 case eStopReasonTrace:
952 case eStopReasonBreakpoint:
953 case eStopReasonWatchpoint:
954 case eStopReasonException:
955 case eStopReasonExec:
956 case eStopReasonThreadExiting:
957 case eStopReasonInstrumentation:
958 if (!other_thread)
959 other_thread = thread;
960 break;
961 case eStopReasonPlanComplete:
962 if (!plan_thread)
963 plan_thread = thread;
964 break;
965 }
966 }
967 if (plan_thread)
968 thread_list.SetSelectedThreadByID(plan_thread->GetID());
969 else if (other_thread)
970 thread_list.SetSelectedThreadByID(other_thread->GetID());
971 else {
972 if (curr_thread && curr_thread->IsValid())
973 thread = curr_thread;
974 else
975 thread = thread_list.GetThreadAtIndex(0);
976
977 if (thread)
978 thread_list.SetSelectedThreadByID(thread->GetID());
979 }
980 }
981 }
982 // Drop the ThreadList mutex by here, since GetThreadStatus below might
Adrian Prantl05097242018-04-30 16:49:04 +0000983 // have to run code, e.g. for Data formatters, and if we hold the
984 // ThreadList mutex, then the process is going to have a hard time
985 // restarting the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000986 if (stream) {
987 Debugger &debugger = process_sp->GetTarget().GetDebugger();
988 if (debugger.GetTargetList().GetSelectedTarget().get() ==
989 &process_sp->GetTarget()) {
990 const bool only_threads_with_stop_reason = true;
991 const uint32_t start_frame = 0;
992 const uint32_t num_frames = 1;
993 const uint32_t num_frames_with_source = 1;
Jim Ingham6a9767c2016-11-08 20:36:40 +0000994 const bool stop_format = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000995 process_sp->GetStatus(*stream);
996 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
997 start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +0000998 num_frames_with_source,
999 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001000 if (curr_thread_stop_info_sp) {
1001 lldb::addr_t crashing_address;
1002 ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
1003 curr_thread_stop_info_sp, &crashing_address);
1004 if (valobj_sp) {
1005 const bool qualify_cxx_base_classes = false;
1006
1007 const ValueObject::GetExpressionPathFormat format =
1008 ValueObject::GetExpressionPathFormat::
1009 eGetExpressionPathFormatHonorPointers;
1010 stream->PutCString("Likely cause: ");
1011 valobj_sp->GetExpressionPath(*stream, qualify_cxx_base_classes,
1012 format);
1013 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
1014 }
1015 }
1016 } else {
1017 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
1018 process_sp->GetTarget().shared_from_this());
1019 if (target_idx != UINT32_MAX)
1020 stream->Printf("Target %d: (", target_idx);
1021 else
1022 stream->Printf("Target <unknown index>: (");
1023 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
1024 stream->Printf(") stopped.\n");
1025 }
1026 }
1027
1028 // Pop the process IO handler
1029 pop_process_io_handler = true;
1030 }
1031 break;
1032 }
1033
1034 if (handle_pop && pop_process_io_handler)
1035 process_sp->PopProcessIOHandler();
1036
1037 return true;
1038}
1039
Kate Stoneb9c1b512016-09-06 20:57:50 +00001040bool Process::HijackProcessEvents(ListenerSP listener_sp) {
1041 if (listener_sp) {
1042 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
1043 eBroadcastBitInterrupt);
1044 } else
1045 return false;
1046}
Greg Claytondc6224e2014-10-21 01:00:42 +00001047
Kate Stoneb9c1b512016-09-06 20:57:50 +00001048void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
Greg Claytondc6224e2014-10-21 01:00:42 +00001049
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001050StateType Process::GetStateChangedEvents(EventSP &event_sp,
1051 const Timeout<std::micro> &timeout,
1052 ListenerSP hijack_listener_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001053 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001054 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Greg Claytondc6224e2014-10-21 01:00:42 +00001055
Kate Stoneb9c1b512016-09-06 20:57:50 +00001056 ListenerSP listener_sp = hijack_listener_sp;
1057 if (!listener_sp)
1058 listener_sp = m_listener_sp;
Greg Claytondc6224e2014-10-21 01:00:42 +00001059
Kate Stoneb9c1b512016-09-06 20:57:50 +00001060 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001061 if (listener_sp->GetEventForBroadcasterWithType(
1062 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001063 timeout)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001064 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1065 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Pavel Labathd02b1c82017-02-10 11:49:33 +00001066 else
1067 LLDB_LOG(log, "got no event or was interrupted.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001068 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001069
Pavel Labathd02b1c82017-02-10 11:49:33 +00001070 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001071 return state;
1072}
Greg Claytondc6224e2014-10-21 01:00:42 +00001073
Kate Stoneb9c1b512016-09-06 20:57:50 +00001074Event *Process::PeekAtStateChangedEvents() {
1075 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001076
Kate Stoneb9c1b512016-09-06 20:57:50 +00001077 if (log)
1078 log->Printf("Process::%s...", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001079
Kate Stoneb9c1b512016-09-06 20:57:50 +00001080 Event *event_ptr;
1081 event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
1082 this, eBroadcastBitStateChanged);
1083 if (log) {
1084 if (event_ptr) {
1085 log->Printf(
1086 "Process::%s (event_ptr) => %s", __FUNCTION__,
1087 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
1088 } else {
1089 log->Printf("Process::%s no events found", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001090 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001091 }
1092 return event_ptr;
1093}
Greg Claytondc6224e2014-10-21 01:00:42 +00001094
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001095StateType
1096Process::GetStateChangedEventsPrivate(EventSP &event_sp,
1097 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001098 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001099 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001100
1101 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001102 if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1103 &m_private_state_broadcaster,
1104 eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001105 timeout))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001106 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1107 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1108
Pavel Labathd02b1c82017-02-10 11:49:33 +00001109 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
1110 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001111 return state;
1112}
1113
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001114bool Process::GetEventsPrivate(EventSP &event_sp,
1115 const Timeout<std::micro> &timeout,
1116 bool control_only) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001117 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001118 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001119
1120 if (control_only)
Pavel Labathd35031e12016-11-30 10:41:42 +00001121 return m_private_state_listener_sp->GetEventForBroadcaster(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001122 &m_private_state_control_broadcaster, event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001123 else
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001124 return m_private_state_listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001125}
1126
1127bool Process::IsRunning() const {
1128 return StateIsRunningState(m_public_state.GetValue());
1129}
1130
1131int Process::GetExitStatus() {
1132 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1133
1134 if (m_public_state.GetValue() == eStateExited)
1135 return m_exit_status;
1136 return -1;
1137}
1138
1139const char *Process::GetExitDescription() {
1140 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1141
1142 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1143 return m_exit_string.c_str();
1144 return nullptr;
1145}
1146
1147bool Process::SetExitStatus(int status, const char *cstr) {
1148 // Use a mutex to protect setting the exit status.
1149 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1150
1151 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1152 LIBLLDB_LOG_PROCESS));
1153 if (log)
1154 log->Printf(
1155 "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1156 status, status, cstr ? "\"" : "", cstr ? cstr : "NULL",
1157 cstr ? "\"" : "");
1158
1159 // We were already in the exited state
1160 if (m_private_state.GetValue() == eStateExited) {
1161 if (log)
1162 log->Printf("Process::SetExitStatus () ignoring exit status because "
1163 "state was already set to eStateExited");
1164 return false;
1165 }
1166
1167 m_exit_status = status;
1168 if (cstr)
1169 m_exit_string = cstr;
1170 else
1171 m_exit_string.clear();
1172
Adrian Prantl05097242018-04-30 16:49:04 +00001173 // Clear the last natural stop ID since it has a strong reference to this
1174 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +00001175 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1176
1177 SetPrivateState(eStateExited);
1178
1179 // Allow subclasses to do some cleanup
1180 DidExit();
1181
1182 return true;
1183}
1184
1185bool Process::IsAlive() {
1186 switch (m_private_state.GetValue()) {
1187 case eStateConnected:
1188 case eStateAttaching:
1189 case eStateLaunching:
1190 case eStateStopped:
1191 case eStateRunning:
1192 case eStateStepping:
1193 case eStateCrashed:
1194 case eStateSuspended:
Greg Claytondc6224e2014-10-21 01:00:42 +00001195 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001196 default:
1197 return false;
1198 }
Jason Molendaa814f702015-11-05 23:03:44 +00001199}
1200
Adrian Prantl05097242018-04-30 16:49:04 +00001201// This static callback can be used to watch for local child processes on the
1202// current host. The child process exits, the process will be found in the
1203// global target list (we want to be completely sure that the
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001204// lldb_private::Process doesn't go away before we can deliver the signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001205bool Process::SetProcessExitStatus(
1206 lldb::pid_t pid, bool exited,
1207 int signo, // Zero for no signal
1208 int exit_status // Exit value of process if signal is zero
1209 ) {
1210 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1211 if (log)
1212 log->Printf("Process::SetProcessExitStatus (pid=%" PRIu64
1213 ", exited=%i, signal=%i, exit_status=%i)\n",
1214 pid, exited, signo, exit_status);
1215
1216 if (exited) {
1217 TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1218 if (target_sp) {
1219 ProcessSP process_sp(target_sp->GetProcessSP());
1220 if (process_sp) {
1221 const char *signal_cstr = nullptr;
1222 if (signo)
1223 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1224
1225 process_sp->SetExitStatus(exit_status, signal_cstr);
1226 }
1227 }
1228 return true;
1229 }
1230 return false;
1231}
1232
1233void Process::UpdateThreadListIfNeeded() {
1234 const uint32_t stop_id = GetStopID();
1235 if (m_thread_list.GetSize(false) == 0 ||
1236 stop_id != m_thread_list.GetStopID()) {
1237 const StateType state = GetPrivateState();
1238 if (StateIsStoppedState(state, true)) {
1239 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
Adrian Prantl05097242018-04-30 16:49:04 +00001240 // m_thread_list does have its own mutex, but we need to hold onto the
1241 // mutex between the call to UpdateThreadList(...) and the
1242 // os->UpdateThreadList(...) so it doesn't change on us
Kate Stoneb9c1b512016-09-06 20:57:50 +00001243 ThreadList &old_thread_list = m_thread_list;
1244 ThreadList real_thread_list(this);
1245 ThreadList new_thread_list(this);
Adrian Prantl05097242018-04-30 16:49:04 +00001246 // Always update the thread list with the protocol specific thread list,
1247 // but only update if "true" is returned
Kate Stoneb9c1b512016-09-06 20:57:50 +00001248 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1249 // Don't call into the OperatingSystem to update the thread list if we
Adrian Prantl05097242018-04-30 16:49:04 +00001250 // are shutting down, since that may call back into the SBAPI's,
1251 // requiring the API lock which is already held by whoever is shutting
1252 // us down, causing a deadlock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001253 OperatingSystem *os = GetOperatingSystem();
1254 if (os && !m_destroy_in_process) {
1255 // Clear any old backing threads where memory threads might have been
1256 // backed by actual threads from the lldb_private::Process subclass
1257 size_t num_old_threads = old_thread_list.GetSize(false);
1258 for (size_t i = 0; i < num_old_threads; ++i)
1259 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1260
1261 // Turn off dynamic types to ensure we don't run any expressions.
Adrian Prantl4e8be2c2018-06-13 16:21:24 +00001262 // Objective-C can run an expression to determine if a SBValue is a
Adrian Prantl05097242018-04-30 16:49:04 +00001263 // dynamic type or not and we need to avoid this. OperatingSystem
1264 // plug-ins can't run expressions that require running code...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001265
1266 Target &target = GetTarget();
1267 const lldb::DynamicValueType saved_prefer_dynamic =
1268 target.GetPreferDynamicValue();
1269 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1270 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1271
1272 // Now let the OperatingSystem plug-in update the thread list
1273
1274 os->UpdateThreadList(
1275 old_thread_list, // Old list full of threads created by OS plug-in
1276 real_thread_list, // The actual thread list full of threads
1277 // created by each lldb_private::Process
1278 // subclass
1279 new_thread_list); // The new thread list that we will show to the
1280 // user that gets filled in
1281
1282 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1283 target.SetPreferDynamicValue(saved_prefer_dynamic);
1284 } else {
1285 // No OS plug-in, the new thread list is the same as the real thread
1286 // list
1287 new_thread_list = real_thread_list;
1288 }
1289
1290 m_thread_list_real.Update(real_thread_list);
1291 m_thread_list.Update(new_thread_list);
1292 m_thread_list.SetStopID(stop_id);
1293
1294 if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
1295 // Clear any extended threads that we may have accumulated previously
1296 m_extended_thread_list.Clear();
1297 m_extended_thread_stop_id = GetLastNaturalStopID();
1298
1299 m_queue_list.Clear();
1300 m_queue_list_stop_id = GetLastNaturalStopID();
1301 }
1302 }
1303 }
1304 }
1305}
1306
1307void Process::UpdateQueueListIfNeeded() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001308 if (m_system_runtime_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001309 if (m_queue_list.GetSize() == 0 ||
1310 m_queue_list_stop_id != GetLastNaturalStopID()) {
1311 const StateType state = GetPrivateState();
1312 if (StateIsStoppedState(state, true)) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001313 m_system_runtime_up->PopulateQueueList(m_queue_list);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001314 m_queue_list_stop_id = GetLastNaturalStopID();
1315 }
1316 }
1317 }
1318}
1319
1320ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
1321 OperatingSystem *os = GetOperatingSystem();
1322 if (os)
1323 return os->CreateThread(tid, context);
1324 return ThreadSP();
1325}
1326
1327uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1328 return AssignIndexIDToThread(thread_id);
1329}
1330
1331bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1332 return (m_thread_id_to_index_id_map.find(thread_id) !=
1333 m_thread_id_to_index_id_map.end());
1334}
1335
1336uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1337 uint32_t result = 0;
1338 std::map<uint64_t, uint32_t>::iterator iterator =
1339 m_thread_id_to_index_id_map.find(thread_id);
1340 if (iterator == m_thread_id_to_index_id_map.end()) {
1341 result = ++m_thread_index_id;
1342 m_thread_id_to_index_id_map[thread_id] = result;
1343 } else {
1344 result = iterator->second;
1345 }
1346
1347 return result;
1348}
1349
1350StateType Process::GetState() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001351 return m_public_state.GetValue();
1352}
1353
Kate Stoneb9c1b512016-09-06 20:57:50 +00001354void Process::SetPublicState(StateType new_state, bool restarted) {
1355 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1356 LIBLLDB_LOG_PROCESS));
1357 if (log)
1358 log->Printf("Process::SetPublicState (state = %s, restarted = %i)",
1359 StateAsCString(new_state), restarted);
1360 const StateType old_state = m_public_state.GetValue();
1361 m_public_state.SetValue(new_state);
1362
Adrian Prantl05097242018-04-30 16:49:04 +00001363 // On the transition from Run to Stopped, we unlock the writer end of the run
1364 // lock. The lock gets locked in Resume, which is the public API to tell the
1365 // program to run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001366 if (!StateChangedIsExternallyHijacked()) {
1367 if (new_state == eStateDetached) {
1368 if (log)
1369 log->Printf(
1370 "Process::SetPublicState (%s) -- unlocking run lock for detach",
1371 StateAsCString(new_state));
1372 m_public_run_lock.SetStopped();
1373 } else {
1374 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1375 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1376 if ((old_state_is_stopped != new_state_is_stopped)) {
1377 if (new_state_is_stopped && !restarted) {
1378 if (log)
1379 log->Printf("Process::SetPublicState (%s) -- unlocking run lock",
1380 StateAsCString(new_state));
1381 m_public_run_lock.SetStopped();
1382 }
1383 }
1384 }
1385 }
1386}
1387
Zachary Turner97206d52017-05-12 04:51:55 +00001388Status Process::Resume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001389 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1390 LIBLLDB_LOG_PROCESS));
1391 if (log)
1392 log->Printf("Process::Resume -- locking run lock");
1393 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001394 Status error("Resume request failed - process still running.");
Greg Claytone4e45922011-11-16 05:37:56 +00001395 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001396 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
Greg Claytondc6224e2014-10-21 01:00:42 +00001397 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001398 }
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001399 Status error = PrivateResume();
1400 if (!error.Success()) {
1401 // Undo running state change
1402 m_public_run_lock.SetStopped();
1403 }
1404 return error;
Greg Claytondc6224e2014-10-21 01:00:42 +00001405}
1406
Jim Ingham3139fc92019-03-01 18:13:38 +00001407static const char *g_resume_sync_name = "lldb.Process.ResumeSynchronous.hijack";
1408
Zachary Turner97206d52017-05-12 04:51:55 +00001409Status Process::ResumeSynchronous(Stream *stream) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001410 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1411 LIBLLDB_LOG_PROCESS));
1412 if (log)
1413 log->Printf("Process::ResumeSynchronous -- locking run lock");
1414 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001415 Status error("Resume request failed - process still running.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001416 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001417 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
1418 return error;
1419 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001420
Kate Stoneb9c1b512016-09-06 20:57:50 +00001421 ListenerSP listener_sp(
Jim Ingham3139fc92019-03-01 18:13:38 +00001422 Listener::MakeListener(g_resume_sync_name));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001423 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001424
Zachary Turner97206d52017-05-12 04:51:55 +00001425 Status error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001426 if (error.Success()) {
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001427 StateType state =
Konrad Kleine248a1302019-05-23 11:14:47 +00001428 WaitForProcessToStop(llvm::None, nullptr, true, listener_sp, stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001429 const bool must_be_alive =
1430 false; // eStateExited is ok, so this must be false
1431 if (!StateIsStoppedState(state, must_be_alive))
1432 error.SetErrorStringWithFormat(
1433 "process not in stopped state after synchronous resume: %s",
1434 StateAsCString(state));
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001435 } else {
1436 // Undo running state change
1437 m_public_run_lock.SetStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001438 }
Ed Mastec29693f2013-07-02 16:35:47 +00001439
Kate Stoneb9c1b512016-09-06 20:57:50 +00001440 // Undo the hijacking of process events...
1441 RestoreProcessEvents();
Andrew Kaylor93132f52013-05-28 23:04:25 +00001442
Kate Stoneb9c1b512016-09-06 20:57:50 +00001443 return error;
1444}
Andrew Kaylor29d65742013-05-10 17:19:04 +00001445
Jim Ingham3139fc92019-03-01 18:13:38 +00001446bool Process::StateChangedIsExternallyHijacked() {
1447 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1448 const char *hijacking_name = GetHijackingListenerName();
1449 if (hijacking_name &&
1450 strcmp(hijacking_name, g_resume_sync_name))
1451 return true;
1452 }
1453 return false;
1454}
1455
1456bool Process::StateChangedIsHijackedForSynchronousResume() {
1457 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1458 const char *hijacking_name = GetHijackingListenerName();
1459 if (hijacking_name &&
1460 strcmp(hijacking_name, g_resume_sync_name) == 0)
1461 return true;
1462 }
1463 return false;
1464}
1465
Kate Stoneb9c1b512016-09-06 20:57:50 +00001466StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
Ilia K38810f42015-05-20 10:15:47 +00001467
Kate Stoneb9c1b512016-09-06 20:57:50 +00001468void Process::SetPrivateState(StateType new_state) {
1469 if (m_finalize_called)
1470 return;
1471
1472 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1473 LIBLLDB_LOG_PROCESS));
1474 bool state_changed = false;
1475
1476 if (log)
1477 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1478
1479 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1480 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1481
1482 const StateType old_state = m_private_state.GetValueNoLock();
1483 state_changed = old_state != new_state;
1484
1485 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1486 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1487 if (old_state_is_stopped != new_state_is_stopped) {
1488 if (new_state_is_stopped)
1489 m_private_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001490 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001491 m_private_run_lock.SetRunning();
1492 }
1493
1494 if (state_changed) {
1495 m_private_state.SetValueNoLock(new_state);
1496 EventSP event_sp(
1497 new Event(eBroadcastBitStateChanged,
1498 new ProcessEventData(shared_from_this(), new_state)));
1499 if (StateIsStoppedState(new_state, false)) {
Adrian Prantl05097242018-04-30 16:49:04 +00001500 // Note, this currently assumes that all threads in the list stop when
1501 // the process stops. In the future we will want to support a debugging
1502 // model where some threads continue to run while others are stopped.
1503 // When that happens we will either need a way for the thread list to
1504 // identify which threads are stopping or create a special thread list
1505 // containing only threads which actually stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001506 //
Adrian Prantl05097242018-04-30 16:49:04 +00001507 // The process plugin is responsible for managing the actual behavior of
1508 // the threads and should have stopped any threads that are going to stop
1509 // before we get here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001510 m_thread_list.DidStop();
1511
1512 m_mod_id.BumpStopID();
1513 if (!m_mod_id.IsLastResumeForUserExpression())
1514 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1515 m_memory_cache.Clear();
1516 if (log)
1517 log->Printf("Process::SetPrivateState (%s) stop_id = %u",
1518 StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001519 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001520
Kate Stoneb9c1b512016-09-06 20:57:50 +00001521 // Use our target to get a shared pointer to ourselves...
1522 if (m_finalize_called && !PrivateStateThreadIsValid())
1523 BroadcastEvent(event_sp);
Jim Ingham22777012010-09-23 02:01:19 +00001524 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001525 m_private_state_broadcaster.BroadcastEvent(event_sp);
1526 } else {
1527 if (log)
1528 log->Printf(
1529 "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1530 StateAsCString(new_state));
1531 }
Jim Ingham22777012010-09-23 02:01:19 +00001532}
1533
Kate Stoneb9c1b512016-09-06 20:57:50 +00001534void Process::SetRunningUserExpression(bool on) {
1535 m_mod_id.SetRunningUserExpression(on);
1536}
1537
Raphael Isemannc01783a2018-08-29 22:50:54 +00001538void Process::SetRunningUtilityFunction(bool on) {
1539 m_mod_id.SetRunningUtilityFunction(on);
1540}
1541
Kate Stoneb9c1b512016-09-06 20:57:50 +00001542addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
1543
1544const lldb::ABISP &Process::GetABI() {
1545 if (!m_abi_sp)
Jason Molenda43294c92017-06-29 02:57:03 +00001546 m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001547 return m_abi_sp;
1548}
1549
1550LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language,
1551 bool retry_if_null) {
1552 if (m_finalizing)
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001553 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001554
Alex Langford74eb76f2019-05-22 23:01:18 +00001555 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001556 LanguageRuntimeCollection::iterator pos;
1557 pos = m_language_runtimes.find(language);
1558 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second)) {
1559 lldb::LanguageRuntimeSP runtime_sp(
1560 LanguageRuntime::FindPlugin(this, language));
1561
1562 m_language_runtimes[language] = runtime_sp;
1563 return runtime_sp.get();
1564 } else
1565 return (*pos).second.get();
Jim Ingham22777012010-09-23 02:01:19 +00001566}
1567
Kate Stoneb9c1b512016-09-06 20:57:50 +00001568CPPLanguageRuntime *Process::GetCPPLanguageRuntime(bool retry_if_null) {
Alex Langford74eb76f2019-05-22 23:01:18 +00001569 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001570 LanguageRuntime *runtime =
1571 GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
1572 if (runtime != nullptr &&
1573 runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1574 return static_cast<CPPLanguageRuntime *>(runtime);
1575 return nullptr;
Jim Ingham22777012010-09-23 02:01:19 +00001576}
1577
Kate Stoneb9c1b512016-09-06 20:57:50 +00001578ObjCLanguageRuntime *Process::GetObjCLanguageRuntime(bool retry_if_null) {
Alex Langford74eb76f2019-05-22 23:01:18 +00001579 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001580 LanguageRuntime *runtime =
1581 GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
1582 if (runtime != nullptr && runtime->GetLanguageType() == eLanguageTypeObjC)
1583 return static_cast<ObjCLanguageRuntime *>(runtime);
1584 return nullptr;
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001585}
1586
Kate Stoneb9c1b512016-09-06 20:57:50 +00001587bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
1588 if (m_finalizing)
1589 return false;
1590
1591 if (in_value.IsDynamic())
1592 return false;
1593 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1594
1595 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1596 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1597 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1598 }
1599
1600 LanguageRuntime *cpp_runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1601 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1602 return true;
1603
1604 LanguageRuntime *objc_runtime = GetLanguageRuntime(eLanguageTypeObjC);
1605 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
Zachary Turner93749ab2015-03-03 21:51:25 +00001606}
1607
Kate Stoneb9c1b512016-09-06 20:57:50 +00001608void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001609 m_dynamic_checkers_up.reset(dynamic_checkers);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001610}
1611
Kate Stoneb9c1b512016-09-06 20:57:50 +00001612BreakpointSiteList &Process::GetBreakpointSiteList() {
1613 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001614}
1615
Kate Stoneb9c1b512016-09-06 20:57:50 +00001616const BreakpointSiteList &Process::GetBreakpointSiteList() const {
1617 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001618}
1619
Kate Stoneb9c1b512016-09-06 20:57:50 +00001620void Process::DisableAllBreakpointSites() {
1621 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1622 // bp_site->SetEnabled(true);
1623 DisableBreakpointSite(bp_site);
1624 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001625}
1626
Zachary Turner97206d52017-05-12 04:51:55 +00001627Status Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
1628 Status error(DisableBreakpointSiteByID(break_id));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001629
Kate Stoneb9c1b512016-09-06 20:57:50 +00001630 if (error.Success())
1631 m_breakpoint_site_list.Remove(break_id);
1632
1633 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001634}
1635
Zachary Turner97206d52017-05-12 04:51:55 +00001636Status Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
1637 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001638 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1639 if (bp_site_sp) {
1640 if (bp_site_sp->IsEnabled())
1641 error = DisableBreakpointSite(bp_site_sp.get());
1642 } else {
1643 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1644 break_id);
1645 }
1646
1647 return error;
1648}
1649
Zachary Turner97206d52017-05-12 04:51:55 +00001650Status Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
1651 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001652 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1653 if (bp_site_sp) {
1654 if (!bp_site_sp->IsEnabled())
1655 error = EnableBreakpointSite(bp_site_sp.get());
1656 } else {
1657 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1658 break_id);
1659 }
1660 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001661}
1662
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001663lldb::break_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001664Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1665 bool use_hardware) {
1666 addr_t load_addr = LLDB_INVALID_ADDRESS;
Jim Ingham1460e4b2014-01-10 23:46:59 +00001667
Kate Stoneb9c1b512016-09-06 20:57:50 +00001668 bool show_error = true;
1669 switch (GetState()) {
1670 case eStateInvalid:
1671 case eStateUnloaded:
1672 case eStateConnected:
1673 case eStateAttaching:
1674 case eStateLaunching:
1675 case eStateDetached:
1676 case eStateExited:
1677 show_error = false;
1678 break;
1679
1680 case eStateStopped:
1681 case eStateRunning:
1682 case eStateStepping:
1683 case eStateCrashed:
1684 case eStateSuspended:
1685 show_error = IsAlive();
1686 break;
1687 }
1688
Adrian Prantl05097242018-04-30 16:49:04 +00001689 // Reset the IsIndirect flag here, in case the location changes from pointing
1690 // to a indirect symbol to a regular symbol.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001691 owner->SetIsIndirect(false);
1692
1693 if (owner->ShouldResolveIndirectFunctions()) {
1694 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1695 if (symbol && symbol->IsIndirect()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001696 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001697 Address symbol_address = symbol->GetAddress();
1698 load_addr = ResolveIndirectFunction(&symbol_address, error);
1699 if (!error.Success() && show_error) {
1700 GetTarget().GetDebugger().GetErrorFile()->Printf(
1701 "warning: failed to resolve indirect function at 0x%" PRIx64
1702 " for breakpoint %i.%i: %s\n",
1703 symbol->GetLoadAddress(&GetTarget()),
1704 owner->GetBreakpoint().GetID(), owner->GetID(),
1705 error.AsCString() ? error.AsCString() : "unknown error");
1706 return LLDB_INVALID_BREAK_ID;
1707 }
1708 Address resolved_address(load_addr);
1709 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1710 owner->SetIsIndirect(true);
1711 } else
1712 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1713 } else
1714 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1715
1716 if (load_addr != LLDB_INVALID_ADDRESS) {
1717 BreakpointSiteSP bp_site_sp;
1718
1719 // Look up this breakpoint site. If it exists, then add this new owner,
Adrian Prantl05097242018-04-30 16:49:04 +00001720 // otherwise create a new breakpoint site and add it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001721
1722 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1723
1724 if (bp_site_sp) {
1725 bp_site_sp->AddOwner(owner);
1726 owner->SetBreakpointSite(bp_site_sp);
1727 return bp_site_sp->GetID();
1728 } else {
1729 bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1730 load_addr, use_hardware));
1731 if (bp_site_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001732 Status error = EnableBreakpointSite(bp_site_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001733 if (error.Success()) {
1734 owner->SetBreakpointSite(bp_site_sp);
1735 return m_breakpoint_site_list.Add(bp_site_sp);
1736 } else {
Jonas Devliegheree103ae92018-11-15 01:18:15 +00001737 if (show_error || use_hardware) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001738 // Report error for setting breakpoint...
1739 GetTarget().GetDebugger().GetErrorFile()->Printf(
1740 "warning: failed to set breakpoint site at 0x%" PRIx64
1741 " for breakpoint %i.%i: %s\n",
1742 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1743 error.AsCString() ? error.AsCString() : "unknown error");
1744 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001745 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001746 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001747 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001748 }
1749 // We failed to enable the breakpoint
1750 return LLDB_INVALID_BREAK_ID;
1751}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001752
Kate Stoneb9c1b512016-09-06 20:57:50 +00001753void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
1754 lldb::user_id_t owner_loc_id,
1755 BreakpointSiteSP &bp_site_sp) {
1756 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1757 if (num_owners == 0) {
1758 // Don't try to disable the site if we don't have a live process anymore.
1759 if (IsAlive())
1760 DisableBreakpointSite(bp_site_sp.get());
1761 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1762 }
1763}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001764
Kate Stoneb9c1b512016-09-06 20:57:50 +00001765size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
1766 uint8_t *buf) const {
1767 size_t bytes_removed = 0;
1768 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001769
Kate Stoneb9c1b512016-09-06 20:57:50 +00001770 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1771 bp_sites_in_range)) {
Zachary Turner3bc714b2017-03-02 00:05:25 +00001772 bp_sites_in_range.ForEach([bp_addr, size,
1773 buf](BreakpointSite *bp_site) -> void {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001774 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1775 addr_t intersect_addr;
1776 size_t intersect_size;
1777 size_t opcode_offset;
1778 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1779 &intersect_size, &opcode_offset)) {
1780 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1781 assert(bp_addr < intersect_addr + intersect_size &&
1782 intersect_addr + intersect_size <= bp_addr + size);
1783 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1784 size_t buf_offset = intersect_addr - bp_addr;
1785 ::memcpy(buf + buf_offset,
1786 bp_site->GetSavedOpcodeBytes() + opcode_offset,
1787 intersect_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001788 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001789 }
1790 });
1791 }
1792 return bytes_removed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001793}
1794
Kate Stoneb9c1b512016-09-06 20:57:50 +00001795size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
1796 PlatformSP platform_sp(GetTarget().GetPlatform());
1797 if (platform_sp)
1798 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
1799 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001800}
1801
Zachary Turner97206d52017-05-12 04:51:55 +00001802Status Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
1803 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001804 assert(bp_site != nullptr);
1805 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1806 const addr_t bp_addr = bp_site->GetLoadAddress();
1807 if (log)
1808 log->Printf(
1809 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
1810 bp_site->GetID(), (uint64_t)bp_addr);
1811 if (bp_site->IsEnabled()) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001812 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001813 log->Printf(
1814 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1815 " -- already enabled",
1816 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001817 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001818 }
1819
1820 if (bp_addr == LLDB_INVALID_ADDRESS) {
1821 error.SetErrorString("BreakpointSite contains an invalid load address.");
1822 return error;
1823 }
1824 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1825 // trap for the breakpoint site
1826 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1827
1828 if (bp_opcode_size == 0) {
1829 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
1830 "returned zero, unable to get breakpoint "
1831 "trap for address 0x%" PRIx64,
1832 bp_addr);
1833 } else {
1834 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1835
1836 if (bp_opcode_bytes == nullptr) {
1837 error.SetErrorString(
1838 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1839 return error;
1840 }
1841
1842 // Save the original opcode by reading it
1843 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
1844 error) == bp_opcode_size) {
1845 // Write a software breakpoint in place of the original opcode
1846 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
1847 bp_opcode_size) {
1848 uint8_t verify_bp_opcode_bytes[64];
1849 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
1850 error) == bp_opcode_size) {
1851 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
1852 bp_opcode_size) == 0) {
1853 bp_site->SetEnabled(true);
1854 bp_site->SetType(BreakpointSite::eSoftware);
1855 if (log)
1856 log->Printf("Process::EnableSoftwareBreakpoint (site_id = %d) "
1857 "addr = 0x%" PRIx64 " -- SUCCESS",
1858 bp_site->GetID(), (uint64_t)bp_addr);
1859 } else
1860 error.SetErrorString(
1861 "failed to verify the breakpoint trap in memory.");
1862 } else
1863 error.SetErrorString(
1864 "Unable to read memory to verify breakpoint trap.");
1865 } else
1866 error.SetErrorString("Unable to write breakpoint trap to memory.");
1867 } else
1868 error.SetErrorString("Unable to read memory at breakpoint address.");
1869 }
1870 if (log && error.Fail())
1871 log->Printf(
1872 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1873 " -- FAILED: %s",
1874 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1875 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001876}
1877
Zachary Turner97206d52017-05-12 04:51:55 +00001878Status Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
1879 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001880 assert(bp_site != nullptr);
1881 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1882 addr_t bp_addr = bp_site->GetLoadAddress();
1883 lldb::user_id_t breakID = bp_site->GetID();
1884 if (log)
1885 log->Printf("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
1886 ") addr = 0x%" PRIx64,
1887 breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001888
Kate Stoneb9c1b512016-09-06 20:57:50 +00001889 if (bp_site->IsHardware()) {
1890 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1891 } else if (bp_site->IsEnabled()) {
1892 const size_t break_op_size = bp_site->GetByteSize();
1893 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
1894 if (break_op_size > 0) {
1895 // Clear a software breakpoint instruction
1896 uint8_t curr_break_op[8];
1897 assert(break_op_size <= sizeof(curr_break_op));
1898 bool break_op_found = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001899
Kate Stoneb9c1b512016-09-06 20:57:50 +00001900 // Read the breakpoint opcode
1901 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
1902 break_op_size) {
1903 bool verify = false;
1904 // Make sure the breakpoint opcode exists at this address
1905 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
1906 break_op_found = true;
1907 // We found a valid breakpoint opcode at this address, now restore
1908 // the saved opcode.
1909 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
1910 break_op_size, error) == break_op_size) {
1911 verify = true;
1912 } else
1913 error.SetErrorString(
1914 "Memory write failed when restoring original opcode.");
1915 } else {
1916 error.SetErrorString(
1917 "Original breakpoint trap is no longer in memory.");
1918 // Set verify to true and so we can check if the original opcode has
1919 // already been restored
1920 verify = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001921 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001922
Kate Stoneb9c1b512016-09-06 20:57:50 +00001923 if (verify) {
1924 uint8_t verify_opcode[8];
1925 assert(break_op_size < sizeof(verify_opcode));
1926 // Verify that our original opcode made it back to the inferior
1927 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
1928 break_op_size) {
1929 // compare the memory we just read with the original opcode
1930 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
1931 break_op_size) == 0) {
1932 // SUCCESS
1933 bp_site->SetEnabled(false);
1934 if (log)
1935 log->Printf("Process::DisableSoftwareBreakpoint (site_id = %d) "
1936 "addr = 0x%" PRIx64 " -- SUCCESS",
1937 bp_site->GetID(), (uint64_t)bp_addr);
1938 return error;
1939 } else {
1940 if (break_op_found)
1941 error.SetErrorString("Failed to restore original opcode.");
1942 }
1943 } else
1944 error.SetErrorString("Failed to read memory to verify that "
1945 "breakpoint trap was restored.");
1946 }
1947 } else
1948 error.SetErrorString(
1949 "Unable to read memory that should contain the breakpoint trap.");
1950 }
1951 } else {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001952 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001953 log->Printf(
1954 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1955 " -- already disabled",
1956 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001957 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001958 }
1959
1960 if (log)
1961 log->Printf(
1962 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1963 " -- FAILED: %s",
1964 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1965 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001966}
1967
Adrian Prantl05097242018-04-30 16:49:04 +00001968// Uncomment to verify memory caching works after making changes to caching
1969// code
Greg Clayton58be07b2011-01-07 06:08:19 +00001970//#define VERIFY_MEMORY_READS
1971
Zachary Turner97206d52017-05-12 04:51:55 +00001972size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001973 error.Clear();
1974 if (!GetDisableMemoryCache()) {
1975#if defined(VERIFY_MEMORY_READS)
1976 // Memory caching is enabled, with debug verification
1977
1978 if (buf && size) {
1979 // Uncomment the line below to make sure memory caching is working.
1980 // I ran this through the test suite and got no assertions, so I am
1981 // pretty confident this is working well. If any changes are made to
1982 // memory caching, uncomment the line below and test your changes!
1983
1984 // Verify all memory reads by using the cache first, then redundantly
1985 // reading the same memory from the inferior and comparing to make sure
1986 // everything is exactly the same.
1987 std::string verify_buf(size, '\0');
1988 assert(verify_buf.size() == size);
1989 const size_t cache_bytes_read =
1990 m_memory_cache.Read(this, addr, buf, size, error);
Zachary Turner97206d52017-05-12 04:51:55 +00001991 Status verify_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001992 const size_t verify_bytes_read =
1993 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
1994 verify_buf.size(), verify_error);
1995 assert(cache_bytes_read == verify_bytes_read);
1996 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1997 assert(verify_error.Success() == error.Success());
1998 return cache_bytes_read;
1999 }
2000 return 0;
2001#else // !defined(VERIFY_MEMORY_READS)
2002 // Memory caching is enabled, without debug verification
2003
2004 return m_memory_cache.Read(addr, buf, size, error);
Sean Callanan64c0cf22012-06-07 22:26:42 +00002005#endif // defined (VERIFY_MEMORY_READS)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002006 } else {
2007 // Memory caching is disabled
2008
2009 return ReadMemoryFromInferior(addr, buf, size, error);
2010 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002011}
Kate Stoneb9c1b512016-09-06 20:57:50 +00002012
2013size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
Zachary Turner97206d52017-05-12 04:51:55 +00002014 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002015 char buf[256];
2016 out_str.clear();
2017 addr_t curr_addr = addr;
2018 while (true) {
2019 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
2020 if (length == 0)
2021 break;
2022 out_str.append(buf, length);
Adrian Prantl05097242018-04-30 16:49:04 +00002023 // If we got "length - 1" bytes, we didn't get the whole C string, we need
2024 // to read some more characters
Kate Stoneb9c1b512016-09-06 20:57:50 +00002025 if (length == sizeof(buf) - 1)
2026 curr_addr += length;
2027 else
2028 break;
2029 }
2030 return out_str.size();
2031}
2032
2033size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
Zachary Turner97206d52017-05-12 04:51:55 +00002034 Status &error, size_t type_width) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002035 size_t total_bytes_read = 0;
2036 if (dst && max_bytes && type_width && max_bytes >= type_width) {
Adrian Prantl05097242018-04-30 16:49:04 +00002037 // Ensure a null terminator independent of the number of bytes that is
2038 // read.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002039 memset(dst, 0, max_bytes);
2040 size_t bytes_left = max_bytes - type_width;
2041
2042 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2043 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2044 "string with more than 4 bytes "
2045 "per character!");
2046
Greg Clayton4c82d422012-05-18 23:20:01 +00002047 addr_t curr_addr = addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002048 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2049 char *curr_dst = dst;
Greg Clayton4c82d422012-05-18 23:20:01 +00002050
Kate Stoneb9c1b512016-09-06 20:57:50 +00002051 error.Clear();
2052 while (bytes_left > 0 && error.Success()) {
2053 addr_t cache_line_bytes_left =
2054 cache_line_size - (curr_addr % cache_line_size);
2055 addr_t bytes_to_read =
2056 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2057 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002058
Kate Stoneb9c1b512016-09-06 20:57:50 +00002059 if (bytes_read == 0)
2060 break;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002061
Kate Stoneb9c1b512016-09-06 20:57:50 +00002062 // Search for a null terminator of correct size and alignment in
2063 // bytes_read
2064 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2065 for (size_t i = aligned_start;
2066 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2067 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2068 error.Clear();
2069 return i;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002070 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002071
2072 total_bytes_read += bytes_read;
2073 curr_dst += bytes_read;
2074 curr_addr += bytes_read;
2075 bytes_left -= bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002076 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002077 } else {
2078 if (max_bytes)
2079 error.SetErrorString("invalid arguments");
2080 }
2081 return total_bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002082}
2083
Kate Stoneb9c1b512016-09-06 20:57:50 +00002084// Deprecated in favor of ReadStringFromMemory which has wchar support and
Adrian Prantl05097242018-04-30 16:49:04 +00002085// correct code to find null terminators.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002086size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
Zachary Turner97206d52017-05-12 04:51:55 +00002087 size_t dst_max_len,
2088 Status &result_error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002089 size_t total_cstr_len = 0;
2090 if (dst && dst_max_len) {
2091 result_error.Clear();
2092 // NULL out everything just to be safe
2093 memset(dst, 0, dst_max_len);
Zachary Turner97206d52017-05-12 04:51:55 +00002094 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002095 addr_t curr_addr = addr;
2096 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2097 size_t bytes_left = dst_max_len - 1;
2098 char *curr_dst = dst;
Greg Clayton8b82f082011-04-12 05:54:46 +00002099
Kate Stoneb9c1b512016-09-06 20:57:50 +00002100 while (bytes_left > 0) {
2101 addr_t cache_line_bytes_left =
2102 cache_line_size - (curr_addr % cache_line_size);
2103 addr_t bytes_to_read =
2104 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2105 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Greg Clayton8b82f082011-04-12 05:54:46 +00002106
Kate Stoneb9c1b512016-09-06 20:57:50 +00002107 if (bytes_read == 0) {
2108 result_error = error;
2109 dst[total_cstr_len] = '\0';
2110 break;
2111 }
2112 const size_t len = strlen(curr_dst);
Greg Clayton8b82f082011-04-12 05:54:46 +00002113
Kate Stoneb9c1b512016-09-06 20:57:50 +00002114 total_cstr_len += len;
2115
2116 if (len < bytes_to_read)
2117 break;
2118
2119 curr_dst += bytes_read;
2120 curr_addr += bytes_read;
2121 bytes_left -= bytes_read;
Greg Clayton8b82f082011-04-12 05:54:46 +00002122 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002123 } else {
2124 if (dst == nullptr)
2125 result_error.SetErrorString("invalid arguments");
Greg Claytone91b7952011-12-15 03:14:23 +00002126 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002127 result_error.Clear();
2128 }
2129 return total_cstr_len;
Greg Clayton8b82f082011-04-12 05:54:46 +00002130}
2131
Kate Stoneb9c1b512016-09-06 20:57:50 +00002132size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002133 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002134 if (buf == nullptr || size == 0)
2135 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002136
Kate Stoneb9c1b512016-09-06 20:57:50 +00002137 size_t bytes_read = 0;
2138 uint8_t *bytes = (uint8_t *)buf;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002139
Kate Stoneb9c1b512016-09-06 20:57:50 +00002140 while (bytes_read < size) {
2141 const size_t curr_size = size - bytes_read;
2142 const size_t curr_bytes_read =
2143 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2144 bytes_read += curr_bytes_read;
2145 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2146 break;
2147 }
2148
2149 // Replace any software breakpoint opcodes that fall into this range back
2150 // into "buf" before we return
2151 if (bytes_read > 0)
2152 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2153 return bytes_read;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002154}
2155
Kate Stoneb9c1b512016-09-06 20:57:50 +00002156uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
2157 size_t integer_byte_size,
2158 uint64_t fail_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002159 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002160 Scalar scalar;
2161 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2162 error))
2163 return scalar.ULongLong(fail_value);
2164 return fail_value;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002165}
2166
Kate Stoneb9c1b512016-09-06 20:57:50 +00002167int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
2168 size_t integer_byte_size,
Zachary Turner97206d52017-05-12 04:51:55 +00002169 int64_t fail_value,
2170 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002171 Scalar scalar;
2172 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2173 error))
2174 return scalar.SLongLong(fail_value);
2175 return fail_value;
Greg Claytonc2267782016-05-23 20:37:24 +00002176}
2177
Zachary Turner97206d52017-05-12 04:51:55 +00002178addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002179 Scalar scalar;
2180 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2181 error))
2182 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2183 return LLDB_INVALID_ADDRESS;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002184}
2185
Kate Stoneb9c1b512016-09-06 20:57:50 +00002186bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002187 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002188 Scalar scalar;
2189 const uint32_t addr_byte_size = GetAddressByteSize();
2190 if (addr_byte_size <= 4)
2191 scalar = (uint32_t)ptr_value;
2192 else
2193 scalar = ptr_value;
2194 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2195 addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002196}
2197
Kate Stoneb9c1b512016-09-06 20:57:50 +00002198size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002199 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002200 size_t bytes_written = 0;
2201 const uint8_t *bytes = (const uint8_t *)buf;
2202
2203 while (bytes_written < size) {
2204 const size_t curr_size = size - bytes_written;
2205 const size_t curr_bytes_written = DoWriteMemory(
2206 addr + bytes_written, bytes + bytes_written, curr_size, error);
2207 bytes_written += curr_bytes_written;
2208 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2209 break;
2210 }
2211 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002212}
2213
Kate Stoneb9c1b512016-09-06 20:57:50 +00002214size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002215 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002216#if defined(ENABLE_MEMORY_CACHING)
2217 m_memory_cache.Flush(addr, size);
Greg Clayton58be07b2011-01-07 06:08:19 +00002218#endif
2219
Kate Stoneb9c1b512016-09-06 20:57:50 +00002220 if (buf == nullptr || size == 0)
2221 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002222
Kate Stoneb9c1b512016-09-06 20:57:50 +00002223 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002224
Kate Stoneb9c1b512016-09-06 20:57:50 +00002225 // We need to write any data that would go where any current software traps
2226 // (enabled software breakpoints) any software traps (breakpoints) that we
2227 // may have placed in our tasks memory.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002228
Kate Stoneb9c1b512016-09-06 20:57:50 +00002229 BreakpointSiteList bp_sites_in_range;
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002230 if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002231 return WriteMemoryPrivate(addr, buf, size, error);
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002232
2233 // No breakpoint sites overlap
2234 if (bp_sites_in_range.IsEmpty())
2235 return WriteMemoryPrivate(addr, buf, size, error);
2236
2237 const uint8_t *ubuf = (const uint8_t *)buf;
2238 uint64_t bytes_written = 0;
2239
2240 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2241 &error](BreakpointSite *bp) -> void {
2242 if (error.Fail())
2243 return;
2244
2245 addr_t intersect_addr;
2246 size_t intersect_size;
2247 size_t opcode_offset;
2248 const bool intersects = bp->IntersectsRange(
2249 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2250 UNUSED_IF_ASSERT_DISABLED(intersects);
2251 assert(intersects);
2252 assert(addr <= intersect_addr && intersect_addr < addr + size);
2253 assert(addr < intersect_addr + intersect_size &&
2254 intersect_addr + intersect_size <= addr + size);
2255 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2256
2257 // Check for bytes before this breakpoint
2258 const addr_t curr_addr = addr + bytes_written;
2259 if (intersect_addr > curr_addr) {
2260 // There are some bytes before this breakpoint that we need to just
2261 // write to memory
2262 size_t curr_size = intersect_addr - curr_addr;
2263 size_t curr_bytes_written =
2264 WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error);
2265 bytes_written += curr_bytes_written;
2266 if (curr_bytes_written != curr_size) {
2267 // We weren't able to write all of the requested bytes, we are
2268 // done looping and will return the number of bytes that we have
2269 // written so far.
2270 if (error.Success())
2271 error.SetErrorToGenericError();
2272 }
2273 }
2274 // Now write any bytes that would cover up any software breakpoints
2275 // directly into the breakpoint opcode buffer
2276 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written,
2277 intersect_size);
2278 bytes_written += intersect_size;
2279 });
Kate Stoneb9c1b512016-09-06 20:57:50 +00002280
2281 // Write any remaining bytes after the last breakpoint if we have any left
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002282 if (bytes_written < size)
2283 bytes_written +=
2284 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2285 size - bytes_written, error);
2286
2287 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002288}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002289
Kate Stoneb9c1b512016-09-06 20:57:50 +00002290size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002291 size_t byte_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002292 if (byte_size == UINT32_MAX)
2293 byte_size = scalar.GetByteSize();
2294 if (byte_size > 0) {
2295 uint8_t buf[32];
2296 const size_t mem_size =
2297 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2298 if (mem_size > 0)
2299 return WriteMemory(addr, buf, mem_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002300 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002301 error.SetErrorString("failed to get scalar as memory data");
2302 } else {
2303 error.SetErrorString("invalid scalar value");
2304 }
2305 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002306}
2307
Kate Stoneb9c1b512016-09-06 20:57:50 +00002308size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2309 bool is_signed, Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002310 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002311 uint64_t uval = 0;
2312 if (byte_size == 0) {
2313 error.SetErrorString("byte size is zero");
2314 } else if (byte_size & (byte_size - 1)) {
2315 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2316 byte_size);
2317 } else if (byte_size <= sizeof(uval)) {
2318 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2319 if (bytes_read == byte_size) {
2320 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2321 GetAddressByteSize());
2322 lldb::offset_t offset = 0;
2323 if (byte_size <= 4)
2324 scalar = data.GetMaxU32(&offset, byte_size);
2325 else
2326 scalar = data.GetMaxU64(&offset, byte_size);
2327 if (is_signed)
2328 scalar.SignExtend(byte_size * 8);
2329 return bytes_read;
Greg Clayton7060f892013-05-01 23:41:30 +00002330 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002331 } else {
2332 error.SetErrorStringWithFormat(
2333 "byte size of %u is too large for integer scalar type", byte_size);
2334 }
2335 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002336}
2337
Pavel Labath16064d32018-03-20 11:56:24 +00002338Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {
2339 Status error;
2340 for (const auto &Entry : entries) {
2341 WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),
2342 error);
2343 if (!error.Success())
2344 break;
2345 }
2346 return error;
2347}
2348
Greg Claytond495c532011-05-17 03:37:42 +00002349#define USE_ALLOCATE_MEMORY_CACHE 1
Kate Stoneb9c1b512016-09-06 20:57:50 +00002350addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002351 Status &error) {
Vedant Kumarc1cd8262018-05-30 19:39:10 +00002352 if (GetPrivateState() != eStateStopped) {
2353 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002354 return LLDB_INVALID_ADDRESS;
Vedant Kumarc1cd8262018-05-30 19:39:10 +00002355 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002356
2357#if defined(USE_ALLOCATE_MEMORY_CACHE)
2358 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
Greg Claytond495c532011-05-17 03:37:42 +00002359#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002360 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2361 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2362 if (log)
2363 log->Printf("Process::AllocateMemory(size=%" PRIu64
2364 ", permissions=%s) => 0x%16.16" PRIx64
2365 " (m_stop_id = %u m_memory_id = %u)",
2366 (uint64_t)size, GetPermissionsAsCString(permissions),
2367 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2368 m_mod_id.GetMemoryID());
2369 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002370#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002371}
2372
Kate Stoneb9c1b512016-09-06 20:57:50 +00002373addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002374 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002375 addr_t return_addr = AllocateMemory(size, permissions, error);
2376 if (error.Success()) {
2377 std::string buffer(size, 0);
2378 WriteMemory(return_addr, buffer.c_str(), size, error);
2379 }
2380 return return_addr;
2381}
2382
2383bool Process::CanJIT() {
2384 if (m_can_jit == eCanJITDontKnow) {
2385 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +00002386 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002387
2388 uint64_t allocated_memory = AllocateMemory(
2389 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2390 err);
2391
2392 if (err.Success()) {
2393 m_can_jit = eCanJITYes;
2394 if (log)
2395 log->Printf("Process::%s pid %" PRIu64
2396 " allocation test passed, CanJIT () is true",
2397 __FUNCTION__, GetID());
2398 } else {
2399 m_can_jit = eCanJITNo;
2400 if (log)
2401 log->Printf("Process::%s pid %" PRIu64
2402 " allocation test failed, CanJIT () is false: %s",
2403 __FUNCTION__, GetID(), err.AsCString());
Jim Ingham2c381412015-11-04 20:32:27 +00002404 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002405
2406 DeallocateMemory(allocated_memory);
2407 }
2408
2409 return m_can_jit == eCanJITYes;
Jim Ingham2c381412015-11-04 20:32:27 +00002410}
2411
Kate Stoneb9c1b512016-09-06 20:57:50 +00002412void Process::SetCanJIT(bool can_jit) {
2413 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
Sean Callanan90539452011-09-20 23:01:51 +00002414}
2415
Kate Stoneb9c1b512016-09-06 20:57:50 +00002416void Process::SetCanRunCode(bool can_run_code) {
2417 SetCanJIT(can_run_code);
2418 m_can_interpret_function_calls = can_run_code;
Sean Callanan90539452011-09-20 23:01:51 +00002419}
2420
Zachary Turner97206d52017-05-12 04:51:55 +00002421Status Process::DeallocateMemory(addr_t ptr) {
2422 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002423#if defined(USE_ALLOCATE_MEMORY_CACHE)
2424 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2425 error.SetErrorStringWithFormat(
2426 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2427 }
Greg Claytond495c532011-05-17 03:37:42 +00002428#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002429 error = DoDeallocateMemory(ptr);
2430
2431 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2432 if (log)
2433 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64
2434 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2435 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2436 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002437#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00002438 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002439}
2440
Kate Stoneb9c1b512016-09-06 20:57:50 +00002441ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2442 lldb::addr_t header_addr,
2443 size_t size_to_read) {
2444 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2445 if (log) {
2446 log->Printf("Process::ReadModuleFromMemory reading %s binary from memory",
2447 file_spec.GetPath().c_str());
2448 }
2449 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2450 if (module_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00002451 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002452 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2453 shared_from_this(), header_addr, error, size_to_read);
2454 if (objfile)
2455 return module_sp;
2456 }
2457 return ModuleSP();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002458}
2459
Kate Stoneb9c1b512016-09-06 20:57:50 +00002460bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2461 uint32_t &permissions) {
2462 MemoryRegionInfo range_info;
2463 permissions = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002464 Status error(GetMemoryRegionInfo(load_addr, range_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002465 if (!error.Success())
2466 return false;
2467 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2468 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2469 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2470 return false;
2471 }
2472
2473 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2474 permissions |= lldb::ePermissionsReadable;
2475
2476 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2477 permissions |= lldb::ePermissionsWritable;
2478
2479 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2480 permissions |= lldb::ePermissionsExecutable;
2481
2482 return true;
2483}
2484
Zachary Turner97206d52017-05-12 04:51:55 +00002485Status Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2486 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002487 error.SetErrorString("watchpoints are not supported");
2488 return error;
2489}
2490
Zachary Turner97206d52017-05-12 04:51:55 +00002491Status Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2492 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002493 error.SetErrorString("watchpoints are not supported");
2494 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002495}
2496
2497StateType
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002498Process::WaitForProcessStopPrivate(EventSP &event_sp,
2499 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002500 StateType state;
Stella Stamenova36d457c2018-06-01 19:14:53 +00002501
Kate Stoneb9c1b512016-09-06 20:57:50 +00002502 while (true) {
2503 event_sp.reset();
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002504 state = GetStateChangedEventsPrivate(event_sp, timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00002505
Kate Stoneb9c1b512016-09-06 20:57:50 +00002506 if (StateIsStoppedState(state, false))
2507 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002508
Kate Stoneb9c1b512016-09-06 20:57:50 +00002509 // If state is invalid, then we timed out
2510 if (state == eStateInvalid)
2511 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002512
Kate Stoneb9c1b512016-09-06 20:57:50 +00002513 if (event_sp)
2514 HandlePrivateEvent(event_sp);
2515 }
2516 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002517}
2518
Kate Stoneb9c1b512016-09-06 20:57:50 +00002519void Process::LoadOperatingSystemPlugin(bool flush) {
2520 if (flush)
2521 m_thread_list.Clear();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002522 m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002523 if (flush)
2524 Flush();
Greg Clayton332e8b12015-01-13 21:13:08 +00002525}
2526
Zachary Turner97206d52017-05-12 04:51:55 +00002527Status Process::Launch(ProcessLaunchInfo &launch_info) {
2528 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002529 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002530 m_dyld_up.reset();
2531 m_jit_loaders_up.reset();
2532 m_system_runtime_up.reset();
2533 m_os_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002534 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002535
Kate Stoneb9c1b512016-09-06 20:57:50 +00002536 Module *exe_module = GetTarget().GetExecutableModulePointer();
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002537 if (!exe_module) {
2538 error.SetErrorString("executable module does not exist");
2539 return error;
2540 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002541
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002542 char local_exec_file_path[PATH_MAX];
2543 char platform_exec_file_path[PATH_MAX];
2544 exe_module->GetFileSpec().GetPath(local_exec_file_path,
2545 sizeof(local_exec_file_path));
2546 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2547 sizeof(platform_exec_file_path));
2548 if (FileSystem::Instance().Exists(exe_module->GetFileSpec())) {
2549 // Install anything that might need to be installed prior to launching.
2550 // For host systems, this will do nothing, but if we are connected to a
2551 // remote platform it will install any needed binaries
2552 error = GetTarget().Install(&launch_info);
2553 if (error.Fail())
2554 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002555
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002556 if (PrivateStateThreadIsValid())
2557 PausePrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002558
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002559 error = WillLaunch(exe_module);
2560 if (error.Success()) {
2561 const bool restarted = false;
2562 SetPublicState(eStateLaunching, restarted);
2563 m_should_detach = false;
2564
2565 if (m_public_run_lock.TrySetRunning()) {
2566 // Now launch using these arguments.
2567 error = DoLaunch(exe_module, launch_info);
2568 } else {
2569 // This shouldn't happen
2570 error.SetErrorString("failed to acquire process run lock");
2571 }
2572
2573 if (error.Fail()) {
2574 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2575 SetID(LLDB_INVALID_PROCESS_ID);
2576 const char *error_string = error.AsCString();
2577 if (error_string == nullptr)
2578 error_string = "launch failed";
2579 SetExitStatus(-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002580 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002581 } else {
2582 EventSP event_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002583
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002584 // Now wait for the process to launch and return control to us, and then
2585 // call DidLaunch:
2586 StateType state = WaitForProcessStopPrivate(event_sp, seconds(10));
Stella Stamenova36d457c2018-06-01 19:14:53 +00002587
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002588 if (state == eStateInvalid || !event_sp) {
2589 // We were able to launch the process, but we failed to catch the
2590 // initial stop.
2591 error.SetErrorString("failed to catch stop after launch");
2592 SetExitStatus(0, "failed to catch stop after launch");
2593 Destroy(false);
2594 } else if (state == eStateStopped || state == eStateCrashed) {
2595 DidLaunch();
Greg Clayton35824e32015-02-20 20:59:47 +00002596
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002597 DynamicLoader *dyld = GetDynamicLoader();
2598 if (dyld)
2599 dyld->DidLaunch();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002600
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002601 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002602
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002603 SystemRuntime *system_runtime = GetSystemRuntime();
2604 if (system_runtime)
2605 system_runtime->DidLaunch();
Jason Molendaeef51062013-11-05 03:57:19 +00002606
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002607 if (!m_os_up)
2608 LoadOperatingSystemPlugin(false);
Greg Clayton35824e32015-02-20 20:59:47 +00002609
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002610 // We successfully launched the process and stopped, now it the
2611 // right time to set up signal filters before resuming.
2612 UpdateAutomaticSignalFiltering();
Greg Clayton35824e32015-02-20 20:59:47 +00002613
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002614 // Note, the stop event was consumed above, but not handled. This
2615 // was done to give DidLaunch a chance to run. The target is either
2616 // stopped or crashed. Directly set the state. This is done to
2617 // prevent a stop message with a bunch of spurious output on thread
2618 // status, as well as not pop a ProcessIOHandler.
2619 SetPublicState(state, false);
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00002620
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002621 if (PrivateStateThreadIsValid())
2622 ResumePrivateStateThread();
2623 else
2624 StartPrivateStateThread();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002625
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002626 // Target was stopped at entry as was intended. Need to notify the
2627 // listeners about it.
2628 if (state == eStateStopped &&
2629 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002630 HandlePrivateEvent(event_sp);
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002631 } else if (state == eStateExited) {
2632 // We exited while trying to launch somehow. Don't call DidLaunch
2633 // as that's not likely to work, and return an invalid pid.
2634 HandlePrivateEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002635 }
2636 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002637 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002638 } else {
2639 error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2640 local_exec_file_path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002641 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002642
Kate Stoneb9c1b512016-09-06 20:57:50 +00002643 return error;
Jim Inghambb3a2832011-01-29 01:49:25 +00002644}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002645
Zachary Turner97206d52017-05-12 04:51:55 +00002646Status Process::LoadCore() {
2647 Status error = DoLoadCore();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002648 if (error.Success()) {
2649 ListenerSP listener_sp(
2650 Listener::MakeListener("lldb.process.load_core_listener"));
2651 HijackProcessEvents(listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002652
Kate Stoneb9c1b512016-09-06 20:57:50 +00002653 if (PrivateStateThreadIsValid())
2654 ResumePrivateStateThread();
Jim Ingham583bbb12016-03-07 21:50:25 +00002655 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002656 StartPrivateStateThread();
Greg Clayton8012cad2014-11-17 19:39:20 +00002657
Kate Stoneb9c1b512016-09-06 20:57:50 +00002658 DynamicLoader *dyld = GetDynamicLoader();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002659 if (dyld)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002660 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002661
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002662 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002663
Kate Stoneb9c1b512016-09-06 20:57:50 +00002664 SystemRuntime *system_runtime = GetSystemRuntime();
Jason Molendaeef51062013-11-05 03:57:19 +00002665 if (system_runtime)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002666 system_runtime->DidAttach();
Jason Molendaeef51062013-11-05 03:57:19 +00002667
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002668 if (!m_os_up)
Greg Clayton29eeea02017-02-09 18:55:41 +00002669 LoadOperatingSystemPlugin(false);
2670
Kate Stoneb9c1b512016-09-06 20:57:50 +00002671 // We successfully loaded a core file, now pretend we stopped so we can
Adrian Prantl05097242018-04-30 16:49:04 +00002672 // show all of the threads in the core file and explore the crashed state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002673 SetPrivateState(eStateStopped);
Greg Claytona97c4d22014-12-09 23:31:02 +00002674
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002675 // Wait for a stopped event since we just posted one above...
Kate Stoneb9c1b512016-09-06 20:57:50 +00002676 lldb::EventSP event_sp;
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002677 StateType state =
2678 WaitForProcessToStop(seconds(10), &event_sp, true, listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002679
2680 if (!StateIsStoppedState(state, false)) {
2681 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2682 if (log)
2683 log->Printf("Process::Halt() failed to stop, state is: %s",
2684 StateAsCString(state));
2685 error.SetErrorString(
2686 "Did not get stopped event after loading the core file.");
2687 }
2688 RestoreProcessEvents();
2689 }
2690 return error;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002691}
2692
Kate Stoneb9c1b512016-09-06 20:57:50 +00002693DynamicLoader *Process::GetDynamicLoader() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002694 if (!m_dyld_up)
2695 m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr));
2696 return m_dyld_up.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002697}
2698
2699const lldb::DataBufferSP Process::GetAuxvData() { return DataBufferSP(); }
2700
2701JITLoaderList &Process::GetJITLoaders() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002702 if (!m_jit_loaders_up) {
2703 m_jit_loaders_up.reset(new JITLoaderList());
2704 JITLoader::LoadPlugins(this, *m_jit_loaders_up);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002705 }
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002706 return *m_jit_loaders_up;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002707}
2708
2709SystemRuntime *Process::GetSystemRuntime() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002710 if (!m_system_runtime_up)
2711 m_system_runtime_up.reset(SystemRuntime::FindPlugin(this));
2712 return m_system_runtime_up.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002713}
2714
2715Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2716 uint32_t exec_count)
2717 : NextEventAction(process), m_exec_count(exec_count) {
2718 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2719 if (log)
2720 log->Printf(
2721 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2722 __FUNCTION__, static_cast<void *>(process), exec_count);
2723}
2724
2725Process::NextEventAction::EventActionResult
2726Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2727 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2728
2729 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2730 if (log)
2731 log->Printf(
2732 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2733 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
2734
2735 switch (state) {
2736 case eStateAttaching:
2737 return eEventActionSuccess;
2738
2739 case eStateRunning:
2740 case eStateConnected:
2741 return eEventActionRetry;
2742
2743 case eStateStopped:
2744 case eStateCrashed:
2745 // During attach, prior to sending the eStateStopped event,
2746 // lldb_private::Process subclasses must set the new process ID.
2747 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Adrian Prantl05097242018-04-30 16:49:04 +00002748 // We don't want these events to be reported, so go set the
2749 // ShouldReportStop here:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002750 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2751
2752 if (m_exec_count > 0) {
2753 --m_exec_count;
2754
2755 if (log)
2756 log->Printf("Process::AttachCompletionHandler::%s state %s: reduced "
2757 "remaining exec count to %" PRIu32 ", requesting resume",
2758 __FUNCTION__, StateAsCString(state), m_exec_count);
2759
2760 RequestResume();
2761 return eEventActionRetry;
2762 } else {
2763 if (log)
2764 log->Printf("Process::AttachCompletionHandler::%s state %s: no more "
2765 "execs expected to start, continuing with attach",
2766 __FUNCTION__, StateAsCString(state));
2767
2768 m_process->CompleteAttach();
2769 return eEventActionSuccess;
2770 }
2771 break;
2772
2773 default:
2774 case eStateExited:
2775 case eStateInvalid:
2776 break;
2777 }
2778
2779 m_exit_string.assign("No valid Process");
2780 return eEventActionExit;
2781}
2782
2783Process::NextEventAction::EventActionResult
2784Process::AttachCompletionHandler::HandleBeingInterrupted() {
2785 return eEventActionSuccess;
2786}
2787
2788const char *Process::AttachCompletionHandler::GetExitString() {
2789 return m_exit_string.c_str();
2790}
2791
2792ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
2793 if (m_listener_sp)
2794 return m_listener_sp;
2795 else
2796 return debugger.GetListener();
2797}
2798
Zachary Turner97206d52017-05-12 04:51:55 +00002799Status Process::Attach(ProcessAttachInfo &attach_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002800 m_abi_sp.reset();
2801 m_process_input_reader.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002802 m_dyld_up.reset();
2803 m_jit_loaders_up.reset();
2804 m_system_runtime_up.reset();
2805 m_os_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002806
2807 lldb::pid_t attach_pid = attach_info.GetProcessID();
Zachary Turner97206d52017-05-12 04:51:55 +00002808 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002809 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
2810 char process_name[PATH_MAX];
2811
2812 if (attach_info.GetExecutableFile().GetPath(process_name,
2813 sizeof(process_name))) {
2814 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2815
2816 if (wait_for_launch) {
2817 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2818 if (error.Success()) {
2819 if (m_public_run_lock.TrySetRunning()) {
2820 m_should_detach = true;
2821 const bool restarted = false;
2822 SetPublicState(eStateAttaching, restarted);
2823 // Now attach using these arguments.
2824 error = DoAttachToProcessWithName(process_name, attach_info);
2825 } else {
2826 // This shouldn't happen
2827 error.SetErrorString("failed to acquire process run lock");
2828 }
2829
2830 if (error.Fail()) {
2831 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2832 SetID(LLDB_INVALID_PROCESS_ID);
2833 if (error.AsCString() == nullptr)
2834 error.SetErrorString("attach failed");
2835
2836 SetExitStatus(-1, error.AsCString());
2837 }
2838 } else {
2839 SetNextEventAction(new Process::AttachCompletionHandler(
2840 this, attach_info.GetResumeCount()));
2841 StartPrivateStateThread();
2842 }
2843 return error;
2844 }
2845 } else {
2846 ProcessInstanceInfoList process_infos;
2847 PlatformSP platform_sp(GetTarget().GetPlatform());
2848
2849 if (platform_sp) {
2850 ProcessInstanceInfoMatch match_info;
2851 match_info.GetProcessInfo() = attach_info;
Pavel Labathc4a33952017-02-20 11:35:33 +00002852 match_info.SetNameMatchType(NameMatch::Equals);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002853 platform_sp->FindProcesses(match_info, process_infos);
2854 const uint32_t num_matches = process_infos.GetSize();
2855 if (num_matches == 1) {
2856 attach_pid = process_infos.GetProcessIDAtIndex(0);
2857 // Fall through and attach using the above process ID
2858 } else {
2859 match_info.GetProcessInfo().GetExecutableFile().GetPath(
2860 process_name, sizeof(process_name));
2861 if (num_matches > 1) {
2862 StreamString s;
Pavel Labathaa51e6a2019-03-04 18:48:00 +00002863 ProcessInstanceInfo::DumpTableHeader(s, true, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002864 for (size_t i = 0; i < num_matches; i++) {
2865 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(
Pavel Labathaa51e6a2019-03-04 18:48:00 +00002866 s, platform_sp->GetUserIDResolver(), true, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002867 }
2868 error.SetErrorStringWithFormat(
2869 "more than one process named %s:\n%s", process_name,
2870 s.GetData());
2871 } else
2872 error.SetErrorStringWithFormat(
2873 "could not find a process named %s", process_name);
2874 }
2875 } else {
2876 error.SetErrorString(
2877 "invalid platform, can't find processes by name");
2878 return error;
2879 }
2880 }
2881 } else {
2882 error.SetErrorString("invalid process name");
2883 }
2884 }
2885
2886 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
2887 error = WillAttachToProcessWithID(attach_pid);
2888 if (error.Success()) {
2889
2890 if (m_public_run_lock.TrySetRunning()) {
2891 // Now attach using these arguments.
2892 m_should_detach = true;
2893 const bool restarted = false;
2894 SetPublicState(eStateAttaching, restarted);
2895 error = DoAttachToProcessWithID(attach_pid, attach_info);
2896 } else {
2897 // This shouldn't happen
2898 error.SetErrorString("failed to acquire process run lock");
2899 }
2900
2901 if (error.Success()) {
2902 SetNextEventAction(new Process::AttachCompletionHandler(
2903 this, attach_info.GetResumeCount()));
2904 StartPrivateStateThread();
2905 } else {
Greg Clayton71337622011-02-24 22:24:29 +00002906 if (GetID() != LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002907 SetID(LLDB_INVALID_PROCESS_ID);
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00002908
Kate Stoneb9c1b512016-09-06 20:57:50 +00002909 const char *error_string = error.AsCString();
2910 if (error_string == nullptr)
2911 error_string = "attach failed";
Greg Clayton32e0a752011-03-30 18:16:51 +00002912
Kate Stoneb9c1b512016-09-06 20:57:50 +00002913 SetExitStatus(-1, error_string);
2914 }
Greg Claytonb766a732011-02-04 01:58:07 +00002915 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002916 }
2917 return error;
Greg Claytonb766a732011-02-04 01:58:07 +00002918}
2919
Kate Stoneb9c1b512016-09-06 20:57:50 +00002920void Process::CompleteAttach() {
2921 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
2922 LIBLLDB_LOG_TARGET));
2923 if (log)
2924 log->Printf("Process::%s()", __FUNCTION__);
2925
2926 // Let the process subclass figure out at much as it can about the process
2927 // before we go looking for a dynamic loader plug-in.
2928 ArchSpec process_arch;
2929 DidAttach(process_arch);
2930
2931 if (process_arch.IsValid()) {
2932 GetTarget().SetArchitecture(process_arch);
2933 if (log) {
2934 const char *triple_str = process_arch.GetTriple().getTriple().c_str();
2935 log->Printf("Process::%s replacing process architecture with DidAttach() "
2936 "architecture: %s",
2937 __FUNCTION__, triple_str ? triple_str : "<null>");
2938 }
2939 }
2940
2941 // We just attached. If we have a platform, ask it for the process
Adrian Prantl05097242018-04-30 16:49:04 +00002942 // architecture, and if it isn't the same as the one we've already set,
2943 // switch architectures.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002944 PlatformSP platform_sp(GetTarget().GetPlatform());
2945 assert(platform_sp);
2946 if (platform_sp) {
2947 const ArchSpec &target_arch = GetTarget().GetArchitecture();
2948 if (target_arch.IsValid() &&
2949 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
2950 ArchSpec platform_arch;
2951 platform_sp =
2952 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
2953 if (platform_sp) {
2954 GetTarget().SetPlatform(platform_sp);
2955 GetTarget().SetArchitecture(platform_arch);
2956 if (log)
2957 log->Printf("Process::%s switching platform to %s and architecture "
2958 "to %s based on info from attach",
2959 __FUNCTION__, platform_sp->GetName().AsCString(""),
2960 platform_arch.GetTriple().getTriple().c_str());
2961 }
2962 } else if (!process_arch.IsValid()) {
2963 ProcessInstanceInfo process_info;
2964 GetProcessInfo(process_info);
2965 const ArchSpec &process_arch = process_info.GetArchitecture();
2966 if (process_arch.IsValid() &&
2967 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
2968 GetTarget().SetArchitecture(process_arch);
2969 if (log)
2970 log->Printf("Process::%s switching architecture to %s based on info "
2971 "the platform retrieved for pid %" PRIu64,
2972 __FUNCTION__,
2973 process_arch.GetTriple().getTriple().c_str(), GetID());
2974 }
2975 }
2976 }
2977
2978 // We have completed the attach, now it is time to find the dynamic loader
2979 // plug-in
2980 DynamicLoader *dyld = GetDynamicLoader();
2981 if (dyld) {
2982 dyld->DidAttach();
2983 if (log) {
2984 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
2985 log->Printf("Process::%s after DynamicLoader::DidAttach(), target "
2986 "executable is %s (using %s plugin)",
2987 __FUNCTION__,
2988 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
2989 : "<none>",
2990 dyld->GetPluginName().AsCString("<unnamed>"));
2991 }
2992 }
2993
2994 GetJITLoaders().DidAttach();
2995
2996 SystemRuntime *system_runtime = GetSystemRuntime();
2997 if (system_runtime) {
2998 system_runtime->DidAttach();
2999 if (log) {
3000 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3001 log->Printf("Process::%s after SystemRuntime::DidAttach(), target "
3002 "executable is %s (using %s plugin)",
3003 __FUNCTION__,
3004 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3005 : "<none>",
3006 system_runtime->GetPluginName().AsCString("<unnamed>"));
3007 }
3008 }
3009
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003010 if (!m_os_up)
Greg Clayton29eeea02017-02-09 18:55:41 +00003011 LoadOperatingSystemPlugin(false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003012 // Figure out which one is the executable, and set that in our target:
3013 const ModuleList &target_modules = GetTarget().GetImages();
3014 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3015 size_t num_modules = target_modules.GetSize();
3016 ModuleSP new_executable_module_sp;
3017
3018 for (size_t i = 0; i < num_modules; i++) {
3019 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
3020 if (module_sp && module_sp->IsExecutable()) {
3021 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3022 new_executable_module_sp = module_sp;
3023 break;
3024 }
3025 }
3026 if (new_executable_module_sp) {
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00003027 GetTarget().SetExecutableModule(new_executable_module_sp,
3028 eLoadDependentsNo);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003029 if (log) {
3030 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3031 log->Printf(
3032 "Process::%s after looping through modules, target executable is %s",
3033 __FUNCTION__,
3034 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3035 : "<none>");
3036 }
3037 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003038}
3039
Zachary Turner97206d52017-05-12 04:51:55 +00003040Status Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003041 m_abi_sp.reset();
3042 m_process_input_reader.reset();
3043
3044 // Find the process and its architecture. Make sure it matches the
Zachary Turner31659452016-11-17 21:15:14 +00003045 // architecture of the current Target, and if not adjust it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003046
Zachary Turner97206d52017-05-12 04:51:55 +00003047 Status error(DoConnectRemote(strm, remote_url));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003048 if (error.Success()) {
3049 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3050 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003051 StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003052
3053 if (state == eStateStopped || state == eStateCrashed) {
3054 // If we attached and actually have a process on the other end, then
3055 // this ended up being the equivalent of an attach.
3056 CompleteAttach();
3057
3058 // This delays passing the stopped event to listeners till
3059 // CompleteAttach gets a chance to complete...
3060 HandlePrivateEvent(event_sp);
3061 }
3062 }
3063
3064 if (PrivateStateThreadIsValid())
3065 ResumePrivateStateThread();
3066 else
3067 StartPrivateStateThread();
3068 }
3069 return error;
3070}
3071
Zachary Turner97206d52017-05-12 04:51:55 +00003072Status Process::PrivateResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003073 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3074 LIBLLDB_LOG_STEP));
3075 if (log)
3076 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s "
3077 "private state: %s",
3078 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3079 StateAsCString(m_private_state.GetValue()));
3080
Adrian Prantl05097242018-04-30 16:49:04 +00003081 // If signals handing status changed we might want to update our signal
3082 // filters before resuming.
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003083 UpdateAutomaticSignalFiltering();
3084
Zachary Turner97206d52017-05-12 04:51:55 +00003085 Status error(WillResume());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003086 // Tell the process it is about to resume before the thread list
3087 if (error.Success()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003088 // Now let the thread list know we are about to resume so it can let all of
3089 // our threads know that they are about to be resumed. Threads will each be
3090 // called with Thread::WillResume(StateType) where StateType contains the
3091 // state that they are supposed to have when the process is resumed
3092 // (suspended/running/stepping). Threads should also check their resume
3093 // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
3094 // start back up with a signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003095 if (m_thread_list.WillResume()) {
3096 // Last thing, do the PreResumeActions.
3097 if (!RunPreResumeActions()) {
3098 error.SetErrorStringWithFormat(
3099 "Process::PrivateResume PreResumeActions failed, not resuming.");
3100 } else {
3101 m_mod_id.BumpResumeID();
3102 error = DoResume();
3103 if (error.Success()) {
3104 DidResume();
3105 m_thread_list.DidResume();
3106 if (log)
3107 log->Printf("Process thinks the process has resumed.");
Jason Molendaf47c7342018-12-17 23:33:40 +00003108 } else {
3109 if (log)
3110 log->Printf(
3111 "Process::PrivateResume() DoResume failed.");
3112 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003113 }
3114 }
3115 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00003116 // Somebody wanted to run without running (e.g. we were faking a step
3117 // from one frame of a set of inlined frames that share the same PC to
3118 // another.) So generate a continue & a stopped event, and let the world
3119 // handle them.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003120 if (log)
3121 log->Printf(
3122 "Process::PrivateResume() asked to simulate a start & stop.");
3123
3124 SetPrivateState(eStateRunning);
3125 SetPrivateState(eStateStopped);
3126 }
3127 } else if (log)
3128 log->Printf("Process::PrivateResume() got an error \"%s\".",
3129 error.AsCString("<unknown error>"));
3130 return error;
3131}
3132
Zachary Turner97206d52017-05-12 04:51:55 +00003133Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003134 if (!StateIsRunningState(m_public_state.GetValue()))
Zachary Turner97206d52017-05-12 04:51:55 +00003135 return Status("Process is not running.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003136
Adrian Prantl05097242018-04-30 16:49:04 +00003137 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
3138 // case it was already set and some thread plan logic calls halt on its own.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003139 m_clear_thread_plans_on_stop |= clear_thread_plans;
3140
3141 ListenerSP halt_listener_sp(
3142 Listener::MakeListener("lldb.process.halt_listener"));
3143 HijackProcessEvents(halt_listener_sp);
3144
3145 EventSP event_sp;
3146
3147 SendAsyncInterrupt();
3148
3149 if (m_public_state.GetValue() == eStateAttaching) {
Adrian Prantl05097242018-04-30 16:49:04 +00003150 // Don't hijack and eat the eStateExited as the code that was doing the
3151 // attach will be waiting for this event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003152 RestoreProcessEvents();
3153 SetExitStatus(SIGKILL, "Cancelled async attach.");
3154 Destroy(false);
Zachary Turner97206d52017-05-12 04:51:55 +00003155 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003156 }
3157
3158 // Wait for 10 second for the process to stop.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003159 StateType state = WaitForProcessToStop(
3160 seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003161 RestoreProcessEvents();
3162
3163 if (state == eStateInvalid || !event_sp) {
3164 // We timed out and didn't get a stop event...
Zachary Turner97206d52017-05-12 04:51:55 +00003165 return Status("Halt timed out. State = %s", StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003166 }
3167
3168 BroadcastEvent(event_sp);
3169
Zachary Turner97206d52017-05-12 04:51:55 +00003170 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003171}
3172
Zachary Turner97206d52017-05-12 04:51:55 +00003173Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3174 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003175
3176 // Check both the public & private states here. If we're hung evaluating an
Adrian Prantl05097242018-04-30 16:49:04 +00003177 // expression, for instance, then the public state will be stopped, but we
3178 // still need to interrupt.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003179 if (m_public_state.GetValue() == eStateRunning ||
3180 m_private_state.GetValue() == eStateRunning) {
3181 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003182 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003183 log->Printf("Process::%s() About to stop.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003184
Kate Stoneb9c1b512016-09-06 20:57:50 +00003185 ListenerSP listener_sp(
3186 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3187 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003188
Pavel Labath19da1f12015-12-07 12:36:52 +00003189 SendAsyncInterrupt();
3190
Kate Stoneb9c1b512016-09-06 20:57:50 +00003191 // Consume the interrupt event.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003192 StateType state =
3193 WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003194
Pavel Labath19da1f12015-12-07 12:36:52 +00003195 RestoreProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003196
Kate Stoneb9c1b512016-09-06 20:57:50 +00003197 // If the process exited while we were waiting for it to stop, put the
Adrian Prantl05097242018-04-30 16:49:04 +00003198 // exited event into the shared pointer passed in and return. Our caller
3199 // doesn't need to do anything else, since they don't have a process
3200 // anymore...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003201
3202 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
3203 if (log)
3204 log->Printf("Process::%s() Process exited while waiting to stop.",
3205 __FUNCTION__);
3206 return error;
3207 } else
3208 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3209
3210 if (state != eStateStopped) {
3211 if (log)
3212 log->Printf("Process::%s() failed to stop, state is: %s", __FUNCTION__,
3213 StateAsCString(state));
3214 // If we really couldn't stop the process then we should just error out
Adrian Prantl05097242018-04-30 16:49:04 +00003215 // here, but if the lower levels just bobbled sending the event and we
3216 // really are stopped, then continue on.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003217 StateType private_state = m_private_state.GetValue();
3218 if (private_state != eStateStopped) {
Zachary Turner97206d52017-05-12 04:51:55 +00003219 return Status(
3220 "Attempt to stop the target in order to detach timed out. "
3221 "State = %s",
3222 StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003223 }
3224 }
3225 }
3226 return error;
3227}
3228
Zachary Turner97206d52017-05-12 04:51:55 +00003229Status Process::Detach(bool keep_stopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003230 EventSP exit_event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003231 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003232 m_destroy_in_process = true;
3233
3234 error = WillDetach();
3235
3236 if (error.Success()) {
3237 if (DetachRequiresHalt()) {
3238 error = StopForDestroyOrDetach(exit_event_sp);
3239 if (!error.Success()) {
3240 m_destroy_in_process = false;
3241 return error;
3242 } else if (exit_event_sp) {
3243 // We shouldn't need to do anything else here. There's no process left
3244 // to detach from...
3245 StopPrivateStateThread();
3246 m_destroy_in_process = false;
3247 return error;
3248 }
3249 }
3250
3251 m_thread_list.DiscardThreadPlans();
3252 DisableAllBreakpointSites();
3253
3254 error = DoDetach(keep_stopped);
3255 if (error.Success()) {
3256 DidDetach();
3257 StopPrivateStateThread();
3258 } else {
3259 return error;
3260 }
3261 }
3262 m_destroy_in_process = false;
3263
Adrian Prantl05097242018-04-30 16:49:04 +00003264 // If we exited when we were waiting for a process to stop, then forward the
3265 // event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003266 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003267 // Directly broadcast our exited event because we shut down our private
3268 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003269 BroadcastEvent(exit_event_sp);
3270 }
3271
3272 // If we have been interrupted (to kill us) in the middle of running, we may
Adrian Prantl05097242018-04-30 16:49:04 +00003273 // not end up propagating the last events through the event system, in which
3274 // case we might strand the write lock. Unlock it here so when we do to tear
3275 // down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003276
3277 m_public_run_lock.SetStopped();
3278 return error;
3279}
3280
Zachary Turner97206d52017-05-12 04:51:55 +00003281Status Process::Destroy(bool force_kill) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003282
3283 // Tell ourselves we are in the process of destroying the process, so that we
Adrian Prantl05097242018-04-30 16:49:04 +00003284 // don't do any unnecessary work that might hinder the destruction. Remember
3285 // to set this back to false when we are done. That way if the attempt
Kate Stoneb9c1b512016-09-06 20:57:50 +00003286 // failed and the process stays around for some reason it won't be in a
3287 // confused state.
3288
3289 if (force_kill)
3290 m_should_detach = false;
3291
3292 if (GetShouldDetach()) {
3293 // FIXME: This will have to be a process setting:
3294 bool keep_stopped = false;
3295 Detach(keep_stopped);
3296 }
3297
3298 m_destroy_in_process = true;
3299
Zachary Turner97206d52017-05-12 04:51:55 +00003300 Status error(WillDestroy());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003301 if (error.Success()) {
3302 EventSP exit_event_sp;
3303 if (DestroyRequiresHalt()) {
3304 error = StopForDestroyOrDetach(exit_event_sp);
3305 }
3306
3307 if (m_public_state.GetValue() != eStateRunning) {
Adrian Prantl05097242018-04-30 16:49:04 +00003308 // Ditch all thread plans, and remove all our breakpoints: in case we
3309 // have to restart the target to kill it, we don't want it hitting a
3310 // breakpoint... Only do this if we've stopped, however, since if we
3311 // didn't manage to halt it above, then we're not going to have much luck
3312 // doing this now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003313 m_thread_list.DiscardThreadPlans();
3314 DisableAllBreakpointSites();
3315 }
3316
3317 error = DoDestroy();
3318 if (error.Success()) {
3319 DidDestroy();
3320 StopPrivateStateThread();
3321 }
3322 m_stdio_communication.Disconnect();
3323 m_stdio_communication.StopReadThread();
3324 m_stdin_forward = false;
3325
3326 if (m_process_input_reader) {
3327 m_process_input_reader->SetIsDone(true);
3328 m_process_input_reader->Cancel();
3329 m_process_input_reader.reset();
3330 }
3331
Adrian Prantl05097242018-04-30 16:49:04 +00003332 // If we exited when we were waiting for a process to stop, then forward
3333 // the event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003334 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003335 // Directly broadcast our exited event because we shut down our private
3336 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003337 BroadcastEvent(exit_event_sp);
3338 }
3339
Adrian Prantl05097242018-04-30 16:49:04 +00003340 // If we have been interrupted (to kill us) in the middle of running, we
3341 // may not end up propagating the last events through the event system, in
3342 // which case we might strand the write lock. Unlock it here so when we do
3343 // to tear down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003344 m_public_run_lock.SetStopped();
3345 }
3346
3347 m_destroy_in_process = false;
3348
3349 return error;
3350}
3351
Zachary Turner97206d52017-05-12 04:51:55 +00003352Status Process::Signal(int signal) {
3353 Status error(WillSignal());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003354 if (error.Success()) {
3355 error = DoSignal(signal);
3356 if (error.Success())
3357 DidSignal();
3358 }
3359 return error;
3360}
3361
3362void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3363 assert(signals_sp && "null signals_sp");
3364 m_unix_signals_sp = signals_sp;
3365}
3366
3367const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3368 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3369 return m_unix_signals_sp;
3370}
3371
3372lldb::ByteOrder Process::GetByteOrder() const {
3373 return GetTarget().GetArchitecture().GetByteOrder();
3374}
3375
3376uint32_t Process::GetAddressByteSize() const {
3377 return GetTarget().GetArchitecture().GetAddressByteSize();
3378}
3379
3380bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3381 const StateType state =
3382 Process::ProcessEventData::GetStateFromEvent(event_ptr);
3383 bool return_value = true;
3384 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3385 LIBLLDB_LOG_PROCESS));
3386
3387 switch (state) {
3388 case eStateDetached:
3389 case eStateExited:
3390 case eStateUnloaded:
3391 m_stdio_communication.SynchronizeWithReadThread();
3392 m_stdio_communication.Disconnect();
3393 m_stdio_communication.StopReadThread();
3394 m_stdin_forward = false;
3395
3396 LLVM_FALLTHROUGH;
3397 case eStateConnected:
3398 case eStateAttaching:
3399 case eStateLaunching:
3400 // These events indicate changes in the state of the debugging session,
3401 // always report them.
3402 return_value = true;
3403 break;
3404 case eStateInvalid:
3405 // We stopped for no apparent reason, don't report it.
3406 return_value = false;
3407 break;
3408 case eStateRunning:
3409 case eStateStepping:
Adrian Prantl05097242018-04-30 16:49:04 +00003410 // If we've started the target running, we handle the cases where we are
3411 // already running and where there is a transition from stopped to running
3412 // differently. running -> running: Automatically suppress extra running
3413 // events stopped -> running: Report except when there is one or more no
3414 // votes
Kate Stoneb9c1b512016-09-06 20:57:50 +00003415 // and no yes votes.
3416 SynchronouslyNotifyStateChanged(state);
3417 if (m_force_next_event_delivery)
3418 return_value = true;
3419 else {
3420 switch (m_last_broadcast_state) {
3421 case eStateRunning:
3422 case eStateStepping:
3423 // We always suppress multiple runnings with no PUBLIC stop in between.
3424 return_value = false;
3425 break;
3426 default:
3427 // TODO: make this work correctly. For now always report
Adrian Prantl05097242018-04-30 16:49:04 +00003428 // run if we aren't running so we don't miss any running events. If I
3429 // run the lldb/test/thread/a.out file and break at main.cpp:58, run
3430 // and hit the breakpoints on multiple threads, then somehow during the
3431 // stepping over of all breakpoints no run gets reported.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003432
3433 // This is a transition from stop to run.
3434 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3435 case eVoteYes:
3436 case eVoteNoOpinion:
3437 return_value = true;
3438 break;
3439 case eVoteNo:
3440 return_value = false;
3441 break;
3442 }
3443 break;
3444 }
3445 }
3446 break;
3447 case eStateStopped:
3448 case eStateCrashed:
3449 case eStateSuspended:
Adrian Prantl05097242018-04-30 16:49:04 +00003450 // We've stopped. First see if we're going to restart the target. If we
3451 // are going to stop, then we always broadcast the event. If we aren't
3452 // going to stop, let the thread plans decide if we're going to report this
3453 // event. If no thread has an opinion, we don't report it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003454
3455 m_stdio_communication.SynchronizeWithReadThread();
3456 RefreshStateAfterStop();
3457 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
3458 if (log)
3459 log->Printf("Process::ShouldBroadcastEvent (%p) stopped due to an "
3460 "interrupt, state: %s",
3461 static_cast<void *>(event_ptr), StateAsCString(state));
3462 // Even though we know we are going to stop, we should let the threads
Adrian Prantl05097242018-04-30 16:49:04 +00003463 // have a look at the stop, so they can properly set their state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003464 m_thread_list.ShouldStop(event_ptr);
3465 return_value = true;
3466 } else {
3467 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3468 bool should_resume = false;
3469
3470 // It makes no sense to ask "ShouldStop" if we've already been
Adrian Prantl05097242018-04-30 16:49:04 +00003471 // restarted... Asking the thread list is also not likely to go well,
3472 // since we are running again. So in that case just report the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003473
3474 if (!was_restarted)
3475 should_resume = !m_thread_list.ShouldStop(event_ptr);
3476
3477 if (was_restarted || should_resume || m_resume_requested) {
3478 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
3479 if (log)
3480 log->Printf("Process::ShouldBroadcastEvent: should_resume: %i state: "
3481 "%s was_restarted: %i stop_vote: %d.",
3482 should_resume, StateAsCString(state), was_restarted,
3483 stop_vote);
3484
3485 switch (stop_vote) {
3486 case eVoteYes:
3487 return_value = true;
3488 break;
3489 case eVoteNoOpinion:
3490 case eVoteNo:
3491 return_value = false;
3492 break;
3493 }
3494
3495 if (!was_restarted) {
3496 if (log)
3497 log->Printf("Process::ShouldBroadcastEvent (%p) Restarting process "
3498 "from state: %s",
3499 static_cast<void *>(event_ptr), StateAsCString(state));
3500 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3501 PrivateResume();
3502 }
3503 } else {
3504 return_value = true;
3505 SynchronouslyNotifyStateChanged(state);
3506 }
3507 }
3508 break;
3509 }
3510
3511 // Forcing the next event delivery is a one shot deal. So reset it here.
3512 m_force_next_event_delivery = false;
3513
3514 // We do some coalescing of events (for instance two consecutive running
Adrian Prantl05097242018-04-30 16:49:04 +00003515 // events get coalesced.) But we only coalesce against events we actually
3516 // broadcast. So we use m_last_broadcast_state to track that. NB - you
3517 // can't use "m_public_state.GetValue()" for that purpose, as was originally
3518 // done, because the PublicState reflects the last event pulled off the
3519 // queue, and there may be several events stacked up on the queue unserviced.
3520 // So the PublicState may not reflect the last broadcasted event yet.
3521 // m_last_broadcast_state gets updated here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003522
3523 if (return_value)
3524 m_last_broadcast_state = state;
3525
3526 if (log)
3527 log->Printf("Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3528 "broadcast state: %s - %s",
3529 static_cast<void *>(event_ptr), StateAsCString(state),
3530 StateAsCString(m_last_broadcast_state),
3531 return_value ? "YES" : "NO");
3532 return return_value;
3533}
3534
3535bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3536 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3537
3538 bool already_running = PrivateStateThreadIsValid();
3539 if (log)
3540 log->Printf("Process::%s()%s ", __FUNCTION__,
3541 already_running ? " already running"
3542 : " starting private state thread");
3543
3544 if (!is_secondary_thread && already_running)
3545 return true;
3546
Adrian Prantl05097242018-04-30 16:49:04 +00003547 // Create a thread that watches our internal state and controls which events
3548 // make it to clients (into the DCProcess event queue).
Kate Stoneb9c1b512016-09-06 20:57:50 +00003549 char thread_name[1024];
Zachary Turner777de772017-03-04 16:42:25 +00003550 uint32_t max_len = llvm::get_max_thread_name_length();
3551 if (max_len > 0 && max_len <= 30) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003552 // On platforms with abbreviated thread name lengths, choose thread names
3553 // that fit within the limit.
3554 if (already_running)
3555 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3556 else
3557 snprintf(thread_name, sizeof(thread_name), "intern-state");
3558 } else {
3559 if (already_running)
3560 snprintf(thread_name, sizeof(thread_name),
3561 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3562 GetID());
3563 else
3564 snprintf(thread_name, sizeof(thread_name),
3565 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3566 }
3567
3568 // Create the private state thread, and start it running.
3569 PrivateStateThreadArgs *args_ptr =
3570 new PrivateStateThreadArgs(this, is_secondary_thread);
3571 m_private_state_thread =
3572 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
3573 (void *)args_ptr, nullptr, 8 * 1024 * 1024);
3574 if (m_private_state_thread.IsJoinable()) {
3575 ResumePrivateStateThread();
3576 return true;
3577 } else
3578 return false;
3579}
3580
3581void Process::PausePrivateStateThread() {
3582 ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3583}
3584
3585void Process::ResumePrivateStateThread() {
3586 ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3587}
3588
3589void Process::StopPrivateStateThread() {
3590 if (m_private_state_thread.IsJoinable())
3591 ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3592 else {
3593 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3594 if (log)
3595 log->Printf(
3596 "Went to stop the private state thread, but it was already invalid.");
3597 }
3598}
3599
3600void Process::ControlPrivateStateThread(uint32_t signal) {
3601 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3602
3603 assert(signal == eBroadcastInternalStateControlStop ||
3604 signal == eBroadcastInternalStateControlPause ||
3605 signal == eBroadcastInternalStateControlResume);
3606
3607 if (log)
3608 log->Printf("Process::%s (signal = %d)", __FUNCTION__, signal);
3609
3610 // Signal the private state thread
3611 if (m_private_state_thread.IsJoinable()) {
3612 // Broadcast the event.
Adrian Prantl05097242018-04-30 16:49:04 +00003613 // It is important to do this outside of the if below, because it's
3614 // possible that the thread state is invalid but that the thread is waiting
3615 // on a control event instead of simply being on its way out (this should
3616 // not happen, but it apparently can).
Kate Stoneb9c1b512016-09-06 20:57:50 +00003617 if (log)
3618 log->Printf("Sending control event of type: %d.", signal);
3619 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3620 m_private_state_control_broadcaster.BroadcastEvent(signal,
3621 event_receipt_sp);
3622
3623 // Wait for the event receipt or for the private state thread to exit
3624 bool receipt_received = false;
3625 if (PrivateStateThreadIsValid()) {
3626 while (!receipt_received) {
Adrian Prantl4c03ea12019-04-05 22:43:42 +00003627 // Check for a receipt for n seconds and then check if the private
Adrian Prantl05097242018-04-30 16:49:04 +00003628 // state thread is still around.
Pavel Labath38d67db2018-05-03 15:33:41 +00003629 receipt_received =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00003630 event_receipt_sp->WaitForEventReceived(GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003631 if (!receipt_received) {
Adrian Prantl05097242018-04-30 16:49:04 +00003632 // Check if the private state thread is still around. If it isn't
3633 // then we are done waiting
Kate Stoneb9c1b512016-09-06 20:57:50 +00003634 if (!PrivateStateThreadIsValid())
3635 break; // Private state thread exited or is exiting, we are done
3636 }
3637 }
3638 }
3639
3640 if (signal == eBroadcastInternalStateControlStop) {
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00003641 thread_result_t result = {};
Kate Stoneb9c1b512016-09-06 20:57:50 +00003642 m_private_state_thread.Join(&result);
3643 m_private_state_thread.Reset();
3644 }
3645 } else {
3646 if (log)
3647 log->Printf(
3648 "Private state thread already dead, no need to signal it to stop.");
3649 }
3650}
3651
3652void Process::SendAsyncInterrupt() {
3653 if (PrivateStateThreadIsValid())
3654 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3655 nullptr);
3656 else
3657 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3658}
3659
3660void Process::HandlePrivateEvent(EventSP &event_sp) {
3661 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3662 m_resume_requested = false;
3663
3664 const StateType new_state =
3665 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3666
3667 // First check to see if anybody wants a shot at this event:
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003668 if (m_next_event_action_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003669 NextEventAction::EventActionResult action_result =
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003670 m_next_event_action_up->PerformAction(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003671 if (log)
3672 log->Printf("Ran next event action, result was %d.", action_result);
3673
3674 switch (action_result) {
3675 case NextEventAction::eEventActionSuccess:
3676 SetNextEventAction(nullptr);
3677 break;
3678
3679 case NextEventAction::eEventActionRetry:
3680 break;
3681
3682 case NextEventAction::eEventActionExit:
Adrian Prantl05097242018-04-30 16:49:04 +00003683 // Handle Exiting Here. If we already got an exited event, we should
3684 // just propagate it. Otherwise, swallow this event, and set our state
3685 // to exit so the next event will kill us.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003686 if (new_state != eStateExited) {
3687 // FIXME: should cons up an exited event, and discard this one.
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003688 SetExitStatus(0, m_next_event_action_up->GetExitString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003689 SetNextEventAction(nullptr);
3690 return;
3691 }
3692 SetNextEventAction(nullptr);
3693 break;
3694 }
3695 }
3696
3697 // See if we should broadcast this state to external clients?
3698 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3699
3700 if (should_broadcast) {
3701 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3702 if (log) {
3703 log->Printf("Process::%s (pid = %" PRIu64
3704 ") broadcasting new state %s (old state %s) to %s",
3705 __FUNCTION__, GetID(), StateAsCString(new_state),
3706 StateAsCString(GetState()),
3707 is_hijacked ? "hijacked" : "public");
3708 }
3709 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3710 if (StateIsRunningState(new_state)) {
Adrian Prantl05097242018-04-30 16:49:04 +00003711 // Only push the input handler if we aren't fowarding events, as this
3712 // means the curses GUI is in use... Or don't push it if we are launching
3713 // since it will come up stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003714 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3715 new_state != eStateLaunching && new_state != eStateAttaching) {
3716 PushProcessIOHandler();
3717 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3718 eBroadcastAlways);
3719 if (log)
3720 log->Printf("Process::%s updated m_iohandler_sync to %d",
3721 __FUNCTION__, m_iohandler_sync.GetValue());
3722 }
3723 } else if (StateIsStoppedState(new_state, false)) {
3724 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
Adrian Prantl05097242018-04-30 16:49:04 +00003725 // If the lldb_private::Debugger is handling the events, we don't want
3726 // to pop the process IOHandler here, we want to do it when we receive
3727 // the stopped event so we can carefully control when the process
3728 // IOHandler is popped because when we stop we want to display some
3729 // text stating how and why we stopped, then maybe some
3730 // process/thread/frame info, and then we want the "(lldb) " prompt to
3731 // show up. If we pop the process IOHandler here, then we will cause
3732 // the command interpreter to become the top IOHandler after the
3733 // process pops off and it will update its prompt right away... See the
3734 // Debugger.cpp file where it calls the function as
Kate Stoneb9c1b512016-09-06 20:57:50 +00003735 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3736 // Otherwise we end up getting overlapping "(lldb) " prompts and
3737 // garbled output.
3738 //
3739 // If we aren't handling the events in the debugger (which is indicated
Adrian Prantl05097242018-04-30 16:49:04 +00003740 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
3741 // we are hijacked, then we always pop the process IO handler manually.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003742 // Hijacking happens when the internal process state thread is running
Adrian Prantl05097242018-04-30 16:49:04 +00003743 // thread plans, or when commands want to run in synchronous mode and
3744 // they call "process->WaitForProcessToStop()". An example of something
Kate Stoneb9c1b512016-09-06 20:57:50 +00003745 // that will hijack the events is a simple expression:
3746 //
3747 // (lldb) expr (int)puts("hello")
3748 //
3749 // This will cause the internal process state thread to resume and halt
3750 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3751 // events) and we do need the IO handler to be pushed and popped
3752 // correctly.
3753
3754 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3755 PopProcessIOHandler();
3756 }
Pavel Labath19da1f12015-12-07 12:36:52 +00003757 }
3758
3759 BroadcastEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003760 } else {
3761 if (log) {
3762 log->Printf(
3763 "Process::%s (pid = %" PRIu64
3764 ") suppressing state %s (old state %s): should_broadcast == false",
3765 __FUNCTION__, GetID(), StateAsCString(new_state),
3766 StateAsCString(GetState()));
3767 }
3768 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003769}
3770
Zachary Turner97206d52017-05-12 04:51:55 +00003771Status Process::HaltPrivate() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003772 EventSP event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003773 Status error(WillHalt());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003774 if (error.Fail())
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003775 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003776
3777 // Ask the process subclass to actually halt our process
3778 bool caused_stop;
3779 error = DoHalt(caused_stop);
3780
3781 DidHalt();
3782 return error;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003783}
3784
Kate Stoneb9c1b512016-09-06 20:57:50 +00003785thread_result_t Process::PrivateStateThread(void *arg) {
3786 std::unique_ptr<PrivateStateThreadArgs> args_up(
3787 static_cast<PrivateStateThreadArgs *>(arg));
3788 thread_result_t result =
3789 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
3790 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003791}
3792
Kate Stoneb9c1b512016-09-06 20:57:50 +00003793thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
3794 bool control_only = true;
Pavel Labath19da1f12015-12-07 12:36:52 +00003795
Kate Stoneb9c1b512016-09-06 20:57:50 +00003796 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3797 if (log)
3798 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3799 __FUNCTION__, static_cast<void *>(this), GetID());
Jason Molendaede31932015-04-17 05:01:58 +00003800
Kate Stoneb9c1b512016-09-06 20:57:50 +00003801 bool exit_now = false;
3802 bool interrupt_requested = false;
3803 while (!exit_now) {
Pavel Labath19da1f12015-12-07 12:36:52 +00003804 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003805 GetEventsPrivate(event_sp, llvm::None, control_only);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003806 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
3807 if (log)
3808 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3809 ") got a control event: %d",
3810 __FUNCTION__, static_cast<void *>(this), GetID(),
3811 event_sp->GetType());
Pavel Labath19da1f12015-12-07 12:36:52 +00003812
Kate Stoneb9c1b512016-09-06 20:57:50 +00003813 switch (event_sp->GetType()) {
3814 case eBroadcastInternalStateControlStop:
3815 exit_now = true;
3816 break; // doing any internal state management below
Pavel Labath19da1f12015-12-07 12:36:52 +00003817
Kate Stoneb9c1b512016-09-06 20:57:50 +00003818 case eBroadcastInternalStateControlPause:
3819 control_only = true;
3820 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003821
Kate Stoneb9c1b512016-09-06 20:57:50 +00003822 case eBroadcastInternalStateControlResume:
3823 control_only = false;
3824 break;
3825 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003826
Kate Stoneb9c1b512016-09-06 20:57:50 +00003827 continue;
3828 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
3829 if (m_public_state.GetValue() == eStateAttaching) {
3830 if (log)
3831 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3832 ") woke up with an interrupt while attaching - "
3833 "forwarding interrupt.",
3834 __FUNCTION__, static_cast<void *>(this), GetID());
3835 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
3836 } else if (StateIsRunningState(m_last_broadcast_state)) {
3837 if (log)
3838 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3839 ") woke up with an interrupt - Halting.",
3840 __FUNCTION__, static_cast<void *>(this), GetID());
Zachary Turner97206d52017-05-12 04:51:55 +00003841 Status error = HaltPrivate();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003842 if (error.Fail() && log)
3843 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3844 ") failed to halt the process: %s",
3845 __FUNCTION__, static_cast<void *>(this), GetID(),
3846 error.AsCString());
Adrian Prantl05097242018-04-30 16:49:04 +00003847 // Halt should generate a stopped event. Make a note of the fact that
3848 // we were doing the interrupt, so we can set the interrupted flag
3849 // after we receive the event. We deliberately set this to true even if
3850 // HaltPrivate failed, so that we can interrupt on the next natural
3851 // stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003852 interrupt_requested = true;
3853 } else {
3854 // This can happen when someone (e.g. Process::Halt) sees that we are
Adrian Prantl05097242018-04-30 16:49:04 +00003855 // running and sends an interrupt request, but the process actually
3856 // stops before we receive it. In that case, we can just ignore the
3857 // request. We use m_last_broadcast_state, because the Stopped event
3858 // may not have been popped of the event queue yet, which is when the
3859 // public state gets updated.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003860 if (log)
3861 log->Printf(
3862 "Process::%s ignoring interrupt as we have already stopped.",
3863 __FUNCTION__);
3864 }
3865 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003866 }
3867
Kate Stoneb9c1b512016-09-06 20:57:50 +00003868 const StateType internal_state =
3869 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003870
Kate Stoneb9c1b512016-09-06 20:57:50 +00003871 if (internal_state != eStateInvalid) {
3872 if (m_clear_thread_plans_on_stop &&
3873 StateIsStoppedState(internal_state, true)) {
3874 m_clear_thread_plans_on_stop = false;
3875 m_thread_list.DiscardThreadPlans();
3876 }
3877
3878 if (interrupt_requested) {
3879 if (StateIsStoppedState(internal_state, true)) {
3880 // We requested the interrupt, so mark this as such in the stop event
Adrian Prantl05097242018-04-30 16:49:04 +00003881 // so clients can tell an interrupted process from a natural stop
Kate Stoneb9c1b512016-09-06 20:57:50 +00003882 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
3883 interrupt_requested = false;
3884 } else if (log) {
3885 log->Printf("Process::%s interrupt_requested, but a non-stopped "
3886 "state '%s' received.",
3887 __FUNCTION__, StateAsCString(internal_state));
3888 }
3889 }
3890
3891 HandlePrivateEvent(event_sp);
3892 }
3893
3894 if (internal_state == eStateInvalid || internal_state == eStateExited ||
3895 internal_state == eStateDetached) {
3896 if (log)
3897 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3898 ") about to exit with internal state %s...",
3899 __FUNCTION__, static_cast<void *>(this), GetID(),
3900 StateAsCString(internal_state));
3901
3902 break;
3903 }
3904 }
3905
3906 // Verify log is still enabled before attempting to write to it...
3907 if (log)
3908 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
3909 __FUNCTION__, static_cast<void *>(this), GetID());
3910
3911 // If we are a secondary thread, then the primary thread we are working for
Adrian Prantl05097242018-04-30 16:49:04 +00003912 // will have already acquired the public_run_lock, and isn't done with what
3913 // it was doing yet, so don't try to change it on the way out.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003914 if (!is_secondary_thread)
3915 m_public_run_lock.SetStopped();
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00003916 return {};
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003917}
3918
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003919// Process Event Data
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003920
Kate Stoneb9c1b512016-09-06 20:57:50 +00003921Process::ProcessEventData::ProcessEventData()
3922 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
3923 m_update_state(0), m_interrupted(false) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003924
Kate Stoneb9c1b512016-09-06 20:57:50 +00003925Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
3926 StateType state)
3927 : EventData(), m_process_wp(), m_state(state), m_restarted(false),
3928 m_update_state(0), m_interrupted(false) {
3929 if (process_sp)
3930 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003931}
3932
Eugene Zelenko8f30a652015-10-23 18:39:37 +00003933Process::ProcessEventData::~ProcessEventData() = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003934
Adrian Prantl0e4c4822019-03-06 21:22:25 +00003935ConstString Process::ProcessEventData::GetFlavorString() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003936 static ConstString g_flavor("Process::ProcessEventData");
3937 return g_flavor;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003938}
3939
Adrian Prantl0e4c4822019-03-06 21:22:25 +00003940ConstString Process::ProcessEventData::GetFlavor() const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003941 return ProcessEventData::GetFlavorString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003942}
3943
Kate Stoneb9c1b512016-09-06 20:57:50 +00003944void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
3945 ProcessSP process_sp(m_process_wp.lock());
Greg Clayton2e309072015-07-17 23:42:28 +00003946
Kate Stoneb9c1b512016-09-06 20:57:50 +00003947 if (!process_sp)
3948 return;
Greg Claytonf4b47e12010-08-04 01:40:35 +00003949
Kate Stoneb9c1b512016-09-06 20:57:50 +00003950 // This function gets called twice for each event, once when the event gets
Adrian Prantl05097242018-04-30 16:49:04 +00003951 // pulled off of the private process event queue, and then any number of
3952 // times, first when it gets pulled off of the public event queue, then other
3953 // times when we're pretending that this is where we stopped at the end of
3954 // expression evaluation. m_update_state is used to distinguish these three
3955 // cases; it is 0 when we're just pulling it off for private handling, and >
3956 // 1 for expression evaluation, and we don't want to do the breakpoint
Kate Stoneb9c1b512016-09-06 20:57:50 +00003957 // command handling then.
3958 if (m_update_state != 1)
3959 return;
3960
3961 process_sp->SetPublicState(
3962 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
3963
Jason Molendab3a3cd12016-12-08 06:27:29 +00003964 if (m_state == eStateStopped && !m_restarted) {
Adrian Prantl05097242018-04-30 16:49:04 +00003965 // Let process subclasses know we are about to do a public stop and do
3966 // anything they might need to in order to speed up register and memory
3967 // accesses.
Jason Molendab3a3cd12016-12-08 06:27:29 +00003968 process_sp->WillPublicStop();
3969 }
3970
Kate Stoneb9c1b512016-09-06 20:57:50 +00003971 // If this is a halt event, even if the halt stopped with some reason other
Adrian Prantl05097242018-04-30 16:49:04 +00003972 // than a plain interrupt (e.g. we had already stopped for a breakpoint when
3973 // the halt request came through) don't do the StopInfo actions, as they may
Kate Stoneb9c1b512016-09-06 20:57:50 +00003974 // end up restarting the process.
3975 if (m_interrupted)
3976 return;
3977
3978 // If we're stopped and haven't restarted, then do the StopInfo actions here:
3979 if (m_state == eStateStopped && !m_restarted) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003980 ThreadList &curr_thread_list = process_sp->GetThreadList();
3981 uint32_t num_threads = curr_thread_list.GetSize();
3982 uint32_t idx;
3983
3984 // The actions might change one of the thread's stop_info's opinions about
Adrian Prantl05097242018-04-30 16:49:04 +00003985 // whether we should stop the process, so we need to query that as we go.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003986
3987 // One other complication here, is that we try to catch any case where the
Adrian Prantl05097242018-04-30 16:49:04 +00003988 // target has run (except for expressions) and immediately exit, but if we
3989 // get that wrong (which is possible) then the thread list might have
3990 // changed, and that would cause our iteration here to crash. We could
3991 // make a copy of the thread list, but we'd really like to also know if it
3992 // has changed at all, so we make up a vector of the thread ID's and check
3993 // what we get back against this list & bag out if anything differs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003994 std::vector<uint32_t> thread_index_array(num_threads);
3995 for (idx = 0; idx < num_threads; ++idx)
3996 thread_index_array[idx] =
3997 curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3998
3999 // Use this to track whether we should continue from here. We will only
Adrian Prantl05097242018-04-30 16:49:04 +00004000 // continue the target running if no thread says we should stop. Of course
4001 // if some thread's PerformAction actually sets the target running, then it
4002 // doesn't matter what the other threads say...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004003
4004 bool still_should_stop = false;
4005
4006 // Sometimes - for instance if we have a bug in the stub we are talking to,
Adrian Prantl05097242018-04-30 16:49:04 +00004007 // we stop but no thread has a valid stop reason. In that case we should
4008 // just stop, because we have no way of telling what the right thing to do
4009 // is, and it's better to let the user decide than continue behind their
4010 // backs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004011
4012 bool does_anybody_have_an_opinion = false;
4013
4014 for (idx = 0; idx < num_threads; ++idx) {
4015 curr_thread_list = process_sp->GetThreadList();
4016 if (curr_thread_list.GetSize() != num_threads) {
4017 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4018 LIBLLDB_LOG_PROCESS));
4019 if (log)
4020 log->Printf(
4021 "Number of threads changed from %u to %u while processing event.",
4022 num_threads, curr_thread_list.GetSize());
4023 break;
4024 }
4025
4026 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4027
4028 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4029 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4030 LIBLLDB_LOG_PROCESS));
4031 if (log)
4032 log->Printf("The thread at position %u changed from %u to %u while "
4033 "processing event.",
4034 idx, thread_index_array[idx], thread_sp->GetIndexID());
4035 break;
4036 }
4037
4038 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4039 if (stop_info_sp && stop_info_sp->IsValid()) {
4040 does_anybody_have_an_opinion = true;
4041 bool this_thread_wants_to_stop;
4042 if (stop_info_sp->GetOverrideShouldStop()) {
4043 this_thread_wants_to_stop =
4044 stop_info_sp->GetOverriddenShouldStopValue();
4045 } else {
4046 stop_info_sp->PerformAction(event_ptr);
Adrian Prantl05097242018-04-30 16:49:04 +00004047 // The stop action might restart the target. If it does, then we
4048 // want to mark that in the event so that whoever is receiving it
4049 // will know to wait for the running event and reflect that state
4050 // appropriately. We also need to stop processing actions, since they
4051 // aren't expecting the target to be running.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004052
4053 // FIXME: we might have run.
4054 if (stop_info_sp->HasTargetRunSinceMe()) {
4055 SetRestarted(true);
4056 break;
4057 }
4058
4059 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004060 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004061
4062 if (!still_should_stop)
4063 still_should_stop = this_thread_wants_to_stop;
4064 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004065 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004066
4067 if (!GetRestarted()) {
4068 if (!still_should_stop && does_anybody_have_an_opinion) {
4069 // We've been asked to continue, so do that here.
4070 SetRestarted(true);
Adrian Prantl05097242018-04-30 16:49:04 +00004071 // Use the public resume method here, since this is just extending a
4072 // public resume.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004073 process_sp->PrivateResume();
4074 } else {
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00004075 bool hijacked =
4076 process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) &&
4077 !process_sp->StateChangedIsHijackedForSynchronousResume();
Jim Ingham3139fc92019-03-01 18:13:38 +00004078
4079 if (!hijacked) {
4080 // If we didn't restart, run the Stop Hooks here.
4081 // Don't do that if state changed events aren't hooked up to the
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00004082 // public (or SyncResume) broadcasters. StopHooks are just for
4083 // real public stops. They might also restart the target,
Jim Ingham3139fc92019-03-01 18:13:38 +00004084 // so watch for that.
4085 process_sp->GetTarget().RunStopHooks();
4086 if (process_sp->GetPrivateState() == eStateRunning)
4087 SetRestarted(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004088 }
4089 }
4090 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004091}
Zachary Turner805e7102019-03-04 21:51:03 +00004092}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004093
Kate Stoneb9c1b512016-09-06 20:57:50 +00004094void Process::ProcessEventData::Dump(Stream *s) const {
4095 ProcessSP process_sp(m_process_wp.lock());
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004096
Kate Stoneb9c1b512016-09-06 20:57:50 +00004097 if (process_sp)
4098 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4099 static_cast<void *>(process_sp.get()), process_sp->GetID());
4100 else
4101 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004102
Kate Stoneb9c1b512016-09-06 20:57:50 +00004103 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004104}
4105
4106const Process::ProcessEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004107Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4108 if (event_ptr) {
4109 const EventData *event_data = event_ptr->GetData();
4110 if (event_data &&
4111 event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4112 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4113 }
4114 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004115}
4116
4117ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004118Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4119 ProcessSP process_sp;
4120 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4121 if (data)
4122 process_sp = data->GetProcessSP();
4123 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004124}
4125
Kate Stoneb9c1b512016-09-06 20:57:50 +00004126StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4127 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4128 if (data == nullptr)
4129 return eStateInvalid;
4130 else
4131 return data->GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004132}
4133
Kate Stoneb9c1b512016-09-06 20:57:50 +00004134bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4135 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4136 if (data == nullptr)
4137 return false;
4138 else
4139 return data->GetRestarted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004140}
4141
Kate Stoneb9c1b512016-09-06 20:57:50 +00004142void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4143 bool new_value) {
4144 ProcessEventData *data =
4145 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4146 if (data != nullptr)
4147 data->SetRestarted(new_value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004148}
4149
Jim Ingham0161b492013-02-09 01:29:05 +00004150size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00004151Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4152 ProcessEventData *data =
4153 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4154 if (data != nullptr)
4155 return data->GetNumRestartedReasons();
4156 else
4157 return 0;
Jim Ingham0161b492013-02-09 01:29:05 +00004158}
4159
4160const char *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004161Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4162 size_t idx) {
4163 ProcessEventData *data =
4164 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4165 if (data != nullptr)
4166 return data->GetRestartedReasonAtIndex(idx);
4167 else
4168 return nullptr;
Jim Ingham0161b492013-02-09 01:29:05 +00004169}
4170
Kate Stoneb9c1b512016-09-06 20:57:50 +00004171void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4172 const char *reason) {
4173 ProcessEventData *data =
4174 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4175 if (data != nullptr)
4176 data->AddRestartedReason(reason);
Jim Ingham0161b492013-02-09 01:29:05 +00004177}
4178
Kate Stoneb9c1b512016-09-06 20:57:50 +00004179bool Process::ProcessEventData::GetInterruptedFromEvent(
4180 const Event *event_ptr) {
4181 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4182 if (data == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004183 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004184 else
4185 return data->GetInterrupted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004186}
4187
Kate Stoneb9c1b512016-09-06 20:57:50 +00004188void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4189 bool new_value) {
4190 ProcessEventData *data =
4191 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4192 if (data != nullptr)
4193 data->SetInterrupted(new_value);
Greg Claytond9e416c2012-02-18 05:35:26 +00004194}
4195
Kate Stoneb9c1b512016-09-06 20:57:50 +00004196bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4197 ProcessEventData *data =
4198 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4199 if (data) {
4200 data->SetUpdateStateOnRemoval();
4201 return true;
4202 }
4203 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004204}
4205
Jim Inghamb87b9e62018-06-26 23:38:58 +00004206lldb::TargetSP Process::CalculateTarget() { return m_target_wp.lock(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004207
4208void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4209 exe_ctx.SetTargetPtr(&GetTarget());
4210 exe_ctx.SetProcessPtr(this);
4211 exe_ctx.SetThreadPtr(nullptr);
4212 exe_ctx.SetFramePtr(nullptr);
4213}
4214
4215// uint32_t
4216// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4217// std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00004218//{
4219// return 0;
4220//}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004221//
4222// ArchSpec
4223// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
Greg Claytone996fd32011-03-08 22:40:15 +00004224//{
4225// return Host::GetArchSpecForExistingProcess (pid);
4226//}
4227//
Kate Stoneb9c1b512016-09-06 20:57:50 +00004228// ArchSpec
4229// Process::GetArchSpecForExistingProcess (const char *process_name)
Greg Claytone996fd32011-03-08 22:40:15 +00004230//{
4231// return Host::GetArchSpecForExistingProcess (process_name);
4232//}
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004233
Kate Stoneb9c1b512016-09-06 20:57:50 +00004234void Process::AppendSTDOUT(const char *s, size_t len) {
4235 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4236 m_stdout_data.append(s, len);
4237 BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4238 new ProcessEventData(shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004239}
4240
Kate Stoneb9c1b512016-09-06 20:57:50 +00004241void Process::AppendSTDERR(const char *s, size_t len) {
4242 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4243 m_stderr_data.append(s, len);
4244 BroadcastEventIfUnique(eBroadcastBitSTDERR,
4245 new ProcessEventData(shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004246}
4247
Kate Stoneb9c1b512016-09-06 20:57:50 +00004248void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4249 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4250 m_profile_data.push_back(one_profile_data);
4251 BroadcastEventIfUnique(eBroadcastBitProfileData,
4252 new ProcessEventData(shared_from_this(), GetState()));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004253}
4254
Kate Stoneb9c1b512016-09-06 20:57:50 +00004255void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4256 const StructuredDataPluginSP &plugin_sp) {
4257 BroadcastEvent(
4258 eBroadcastBitStructuredData,
4259 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
Todd Fiala75930012016-08-19 04:21:48 +00004260}
4261
4262StructuredDataPluginSP
Adrian Prantl0e4c4822019-03-06 21:22:25 +00004263Process::GetStructuredDataPlugin(ConstString type_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004264 auto find_it = m_structured_data_plugin_map.find(type_name);
4265 if (find_it != m_structured_data_plugin_map.end())
4266 return find_it->second;
4267 else
4268 return StructuredDataPluginSP();
Todd Fiala75930012016-08-19 04:21:48 +00004269}
4270
Zachary Turner97206d52017-05-12 04:51:55 +00004271size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004272 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4273 if (m_profile_data.empty())
4274 return 0;
4275
4276 std::string &one_profile_data = m_profile_data.front();
4277 size_t bytes_available = one_profile_data.size();
4278 if (bytes_available > 0) {
4279 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4280 if (log)
4281 log->Printf("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4282 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4283 if (bytes_available > buf_size) {
4284 memcpy(buf, one_profile_data.c_str(), buf_size);
4285 one_profile_data.erase(0, buf_size);
4286 bytes_available = buf_size;
4287 } else {
4288 memcpy(buf, one_profile_data.c_str(), bytes_available);
4289 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004290 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004291 }
4292 return bytes_available;
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004293}
4294
Greg Clayton93e86192011-11-13 04:45:22 +00004295// Process STDIO
Greg Clayton93e86192011-11-13 04:45:22 +00004296
Zachary Turner97206d52017-05-12 04:51:55 +00004297size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004298 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4299 size_t bytes_available = m_stdout_data.size();
4300 if (bytes_available > 0) {
4301 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4302 if (log)
4303 log->Printf("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4304 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4305 if (bytes_available > buf_size) {
4306 memcpy(buf, m_stdout_data.c_str(), buf_size);
4307 m_stdout_data.erase(0, buf_size);
4308 bytes_available = buf_size;
4309 } else {
4310 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4311 m_stdout_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004312 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004313 }
4314 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004315}
4316
Zachary Turner97206d52017-05-12 04:51:55 +00004317size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004318 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4319 size_t bytes_available = m_stderr_data.size();
4320 if (bytes_available > 0) {
4321 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4322 if (log)
4323 log->Printf("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4324 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4325 if (bytes_available > buf_size) {
4326 memcpy(buf, m_stderr_data.c_str(), buf_size);
4327 m_stderr_data.erase(0, buf_size);
4328 bytes_available = buf_size;
4329 } else {
4330 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4331 m_stderr_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004332 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004333 }
4334 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004335}
4336
Kate Stoneb9c1b512016-09-06 20:57:50 +00004337void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4338 size_t src_len) {
4339 Process *process = (Process *)baton;
4340 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004341}
4342
Kate Stoneb9c1b512016-09-06 20:57:50 +00004343class IOHandlerProcessSTDIO : public IOHandler {
Greg Clayton44d93782014-01-27 23:43:24 +00004344public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004345 IOHandlerProcessSTDIO(Process *process, int write_fd)
4346 : IOHandler(process->GetTarget().GetDebugger(),
4347 IOHandler::Type::ProcessIO),
Sam McCall6f43d9d2016-11-15 10:58:16 +00004348 m_process(process), m_write_file(write_fd, false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004349 m_pipe.CreateNew(false);
4350 m_read_file.SetDescriptor(GetInputFD(), false);
4351 }
4352
4353 ~IOHandlerProcessSTDIO() override = default;
4354
Adrian Prantl05097242018-04-30 16:49:04 +00004355 // Each IOHandler gets to run until it is done. It should read data from the
4356 // "in" and place output into "out" and "err and return when done.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004357 void Run() override {
4358 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4359 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4360 SetIsDone(true);
4361 return;
Greg Clayton44d93782014-01-27 23:43:24 +00004362 }
4363
Kate Stoneb9c1b512016-09-06 20:57:50 +00004364 SetIsDone(false);
4365 const int read_fd = m_read_file.GetDescriptor();
4366 TerminalState terminal_state;
4367 terminal_state.Save(read_fd, false);
4368 Terminal terminal(read_fd);
4369 terminal.SetCanonical(false);
4370 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004371// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004372#ifndef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +00004373 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4374 m_is_running = true;
4375 while (!GetIsDone()) {
4376 SelectHelper select_helper;
4377 select_helper.FDSetRead(read_fd);
4378 select_helper.FDSetRead(pipe_read_fd);
Zachary Turner97206d52017-05-12 04:51:55 +00004379 Status error = select_helper.Select();
Greg Clayton860582f2016-02-26 17:36:44 +00004380
Kate Stoneb9c1b512016-09-06 20:57:50 +00004381 if (error.Fail()) {
Greg Clayton860582f2016-02-26 17:36:44 +00004382 SetIsDone(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004383 } else {
4384 char ch = 0;
4385 size_t n;
4386 if (select_helper.FDIsSetRead(read_fd)) {
4387 n = 1;
4388 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4389 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4390 SetIsDone(true);
4391 } else
4392 SetIsDone(true);
Greg Clayton860582f2016-02-26 17:36:44 +00004393 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004394 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4395 size_t bytes_read;
4396 // Consume the interrupt byte
Zachary Turner97206d52017-05-12 04:51:55 +00004397 Status error = m_pipe.Read(&ch, 1, bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004398 if (error.Success()) {
4399 switch (ch) {
4400 case 'q':
4401 SetIsDone(true);
4402 break;
4403 case 'i':
4404 if (StateIsRunningState(m_process->GetState()))
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004405 m_process->SendAsyncInterrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004406 break;
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004407 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004408 }
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004409 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004410 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004411 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004412 m_is_running = false;
4413#endif
4414 terminal_state.Restore();
4415 }
4416
4417 void Cancel() override {
4418 SetIsDone(true);
4419 // Only write to our pipe to cancel if we are in
Adrian Prantl05097242018-04-30 16:49:04 +00004420 // IOHandlerProcessSTDIO::Run(). We can end up with a python command that
4421 // is being run from the command interpreter:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004422 //
4423 // (lldb) step_process_thousands_of_times
4424 //
4425 // In this case the command interpreter will be in the middle of handling
4426 // the command and if the process pushes and pops the IOHandler thousands
4427 // of times, we can end up writing to m_pipe without ever consuming the
4428 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4429 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4430 if (m_is_running) {
4431 char ch = 'q'; // Send 'q' for quit
4432 size_t bytes_written = 0;
4433 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00004434 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004435 }
4436
4437 bool Interrupt() override {
Adrian Prantl05097242018-04-30 16:49:04 +00004438 // Do only things that are safe to do in an interrupt context (like in a
4439 // SIGINT handler), like write 1 byte to a file descriptor. This will
Kate Stoneb9c1b512016-09-06 20:57:50 +00004440 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4441 // that was written to the pipe and then call
Adrian Prantl05097242018-04-30 16:49:04 +00004442 // m_process->SendAsyncInterrupt() from a much safer location in code.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004443 if (m_active) {
4444 char ch = 'i'; // Send 'i' for interrupt
4445 size_t bytes_written = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00004446 Status result = m_pipe.Write(&ch, 1, bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004447 return result.Success();
4448 } else {
4449 // This IOHandler might be pushed on the stack, but not being run
Adrian Prantl05097242018-04-30 16:49:04 +00004450 // currently so do the right thing if we aren't actively watching for
4451 // STDIN by sending the interrupt to the process. Otherwise the write to
4452 // the pipe above would do nothing. This can happen when the command
4453 // interpreter is running and gets a "expression ...". It will be on the
4454 // IOHandler thread and sending the input is complete to the delegate
4455 // which will cause the expression to run, which will push the process IO
4456 // handler, but not run it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004457
4458 if (StateIsRunningState(m_process->GetState())) {
4459 m_process->SendAsyncInterrupt();
4460 return true;
4461 }
4462 }
4463 return false;
4464 }
4465
4466 void GotEOF() override {}
4467
Greg Clayton44d93782014-01-27 23:43:24 +00004468protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004469 Process *m_process;
4470 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4471 File m_write_file; // Write to this file (usually the master pty for getting
4472 // io to debuggee)
4473 Pipe m_pipe;
Sam McCall6f43d9d2016-11-15 10:58:16 +00004474 std::atomic<bool> m_is_running{false};
Greg Clayton44d93782014-01-27 23:43:24 +00004475};
4476
Kate Stoneb9c1b512016-09-06 20:57:50 +00004477void Process::SetSTDIOFileDescriptor(int fd) {
4478 // First set up the Read Thread for reading/handling process I/O
4479
Jonas Devlieghered5b44032019-02-13 06:25:41 +00004480 std::unique_ptr<ConnectionFileDescriptor> conn_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004481 new ConnectionFileDescriptor(fd, true));
4482
Jonas Devlieghered5b44032019-02-13 06:25:41 +00004483 if (conn_up) {
4484 m_stdio_communication.SetConnection(conn_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004485 if (m_stdio_communication.IsConnected()) {
4486 m_stdio_communication.SetReadThreadBytesReceivedCallback(
4487 STDIOReadThreadBytesReceived, this);
4488 m_stdio_communication.StartReadThread();
4489
4490 // Now read thread is set up, set up input reader.
4491
4492 if (!m_process_input_reader)
Jonas Devlieghere796ac802019-02-11 23:13:08 +00004493 m_process_input_reader =
4494 std::make_shared<IOHandlerProcessSTDIO>(this, fd);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004495 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004496 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004497}
4498
Kate Stoneb9c1b512016-09-06 20:57:50 +00004499bool Process::ProcessIOHandlerIsActive() {
4500 IOHandlerSP io_handler_sp(m_process_input_reader);
4501 if (io_handler_sp)
4502 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4503 return false;
Greg Clayton6fea17e2014-03-03 19:15:20 +00004504}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004505bool Process::PushProcessIOHandler() {
4506 IOHandlerSP io_handler_sp(m_process_input_reader);
4507 if (io_handler_sp) {
4508 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4509 if (log)
4510 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
Pavel Labath44464872015-05-27 12:40:32 +00004511
Kate Stoneb9c1b512016-09-06 20:57:50 +00004512 io_handler_sp->SetIsDone(false);
Raphael Isemannc01783a2018-08-29 22:50:54 +00004513 // If we evaluate an utility function, then we don't cancel the current
4514 // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
4515 // existing IOHandler that potentially provides the user interface (e.g.
4516 // the IOHandler for Editline).
4517 bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();
4518 GetTarget().GetDebugger().PushIOHandler(io_handler_sp, cancel_top_handler);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004519 return true;
4520 }
4521 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004522}
4523
Kate Stoneb9c1b512016-09-06 20:57:50 +00004524bool Process::PopProcessIOHandler() {
4525 IOHandlerSP io_handler_sp(m_process_input_reader);
4526 if (io_handler_sp)
4527 return GetTarget().GetDebugger().PopIOHandler(io_handler_sp);
4528 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004529}
4530
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004531// The process needs to know about installed plug-ins
Kate Stoneb9c1b512016-09-06 20:57:50 +00004532void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004533
Kate Stoneb9c1b512016-09-06 20:57:50 +00004534void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004535
Kate Stoneb9c1b512016-09-06 20:57:50 +00004536namespace {
Adrian Prantl05097242018-04-30 16:49:04 +00004537// RestorePlanState is used to record the "is private", "is master" and "okay
4538// to discard" fields of the plan we are running, and reset it on Clean or on
4539// destruction. It will only reset the state once, so you can call Clean and
4540// then monkey with the state and it won't get reset on you again.
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004541
Kate Stoneb9c1b512016-09-06 20:57:50 +00004542class RestorePlanState {
4543public:
4544 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4545 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4546 if (m_thread_plan_sp) {
4547 m_private = m_thread_plan_sp->GetPrivate();
4548 m_is_master = m_thread_plan_sp->IsMasterPlan();
4549 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4550 }
4551 }
4552
4553 ~RestorePlanState() { Clean(); }
4554
4555 void Clean() {
4556 if (!m_already_reset && m_thread_plan_sp) {
4557 m_already_reset = true;
4558 m_thread_plan_sp->SetPrivate(m_private);
4559 m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4560 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4561 }
4562 }
4563
4564private:
4565 lldb::ThreadPlanSP m_thread_plan_sp;
4566 bool m_already_reset;
4567 bool m_private;
4568 bool m_is_master;
4569 bool m_okay_to_discard;
4570};
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004571} // anonymous namespace
Jim Inghamc60963c2015-10-12 19:11:03 +00004572
Pavel Labath2ce22162016-12-01 10:57:30 +00004573static microseconds
4574GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
4575 const milliseconds default_one_thread_timeout(250);
4576
4577 // If the overall wait is forever, then we don't need to worry about it.
Pavel Labath43d35412016-12-06 11:24:51 +00004578 if (!options.GetTimeout()) {
4579 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4580 : default_one_thread_timeout;
Pavel Labath2ce22162016-12-01 10:57:30 +00004581 }
4582
4583 // If the one thread timeout is set, use it.
Pavel Labath43d35412016-12-06 11:24:51 +00004584 if (options.GetOneThreadTimeout())
4585 return *options.GetOneThreadTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004586
4587 // Otherwise use half the total timeout, bounded by the
4588 // default_one_thread_timeout.
4589 return std::min<microseconds>(default_one_thread_timeout,
Pavel Labath43d35412016-12-06 11:24:51 +00004590 *options.GetTimeout() / 2);
Pavel Labath2ce22162016-12-01 10:57:30 +00004591}
4592
4593static Timeout<std::micro>
4594GetExpressionTimeout(const EvaluateExpressionOptions &options,
4595 bool before_first_timeout) {
Adrian Prantl05097242018-04-30 16:49:04 +00004596 // If we are going to run all threads the whole time, or if we are only going
4597 // to run one thread, we can just return the overall timeout.
Pavel Labath2ce22162016-12-01 10:57:30 +00004598 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Pavel Labath43d35412016-12-06 11:24:51 +00004599 return options.GetTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004600
4601 if (before_first_timeout)
4602 return GetOneThreadExpressionTimeout(options);
4603
Pavel Labath43d35412016-12-06 11:24:51 +00004604 if (!options.GetTimeout())
Pavel Labath2ce22162016-12-01 10:57:30 +00004605 return llvm::None;
4606 else
Pavel Labath43d35412016-12-06 11:24:51 +00004607 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
Pavel Labath2ce22162016-12-01 10:57:30 +00004608}
4609
Pavel Labath45dde232017-05-25 10:50:06 +00004610static llvm::Optional<ExpressionResults>
4611HandleStoppedEvent(Thread &thread, const ThreadPlanSP &thread_plan_sp,
4612 RestorePlanState &restorer, const EventSP &event_sp,
4613 EventSP &event_to_broadcast_sp,
4614 const EvaluateExpressionOptions &options, bool handle_interrupts) {
4615 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS);
4616
4617 ThreadPlanSP plan = thread.GetCompletedPlan();
4618 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
4619 LLDB_LOG(log, "execution completed successfully");
4620
4621 // Restore the plan state so it will get reported as intended when we are
4622 // done.
4623 restorer.Clean();
4624 return eExpressionCompleted;
4625 }
4626
4627 StopInfoSP stop_info_sp = thread.GetStopInfo();
4628 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
4629 stop_info_sp->ShouldNotify(event_sp.get())) {
4630 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
4631 if (!options.DoesIgnoreBreakpoints()) {
4632 // Restore the plan state and then force Private to false. We are going
4633 // to stop because of this plan so we need it to become a public plan or
Adrian Prantl05097242018-04-30 16:49:04 +00004634 // it won't report correctly when we continue to its termination later
4635 // on.
Pavel Labath45dde232017-05-25 10:50:06 +00004636 restorer.Clean();
4637 thread_plan_sp->SetPrivate(false);
4638 event_to_broadcast_sp = event_sp;
4639 }
4640 return eExpressionHitBreakpoint;
4641 }
4642
4643 if (!handle_interrupts &&
4644 Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4645 return llvm::None;
4646
4647 LLDB_LOG(log, "thread plan did not successfully complete");
4648 if (!options.DoesUnwindOnError())
4649 event_to_broadcast_sp = event_sp;
4650 return eExpressionInterrupted;
4651}
4652
Jim Ingham1624a2d2014-05-05 02:26:40 +00004653ExpressionResults
Kate Stoneb9c1b512016-09-06 20:57:50 +00004654Process::RunThreadPlan(ExecutionContext &exe_ctx,
4655 lldb::ThreadPlanSP &thread_plan_sp,
4656 const EvaluateExpressionOptions &options,
4657 DiagnosticManager &diagnostic_manager) {
4658 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004659
Kate Stoneb9c1b512016-09-06 20:57:50 +00004660 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4661
4662 if (!thread_plan_sp) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004663 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004664 eDiagnosticSeverityError,
4665 "RunThreadPlan called with empty thread plan.");
4666 return eExpressionSetupError;
4667 }
4668
4669 if (!thread_plan_sp->ValidatePlan(nullptr)) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004670 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004671 eDiagnosticSeverityError,
4672 "RunThreadPlan called with an invalid thread plan.");
4673 return eExpressionSetupError;
4674 }
4675
4676 if (exe_ctx.GetProcessPtr() != this) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004677 diagnostic_manager.PutString(eDiagnosticSeverityError,
4678 "RunThreadPlan called on wrong process.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004679 return eExpressionSetupError;
4680 }
4681
4682 Thread *thread = exe_ctx.GetThreadPtr();
4683 if (thread == nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004684 diagnostic_manager.PutString(eDiagnosticSeverityError,
4685 "RunThreadPlan called with invalid thread.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004686 return eExpressionSetupError;
4687 }
4688
4689 // We need to change some of the thread plan attributes for the thread plan
Adrian Prantl05097242018-04-30 16:49:04 +00004690 // runner. This will restore them when we are done:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004691
4692 RestorePlanState thread_plan_restorer(thread_plan_sp);
4693
Adrian Prantl05097242018-04-30 16:49:04 +00004694 // We rely on the thread plan we are running returning "PlanCompleted" if
4695 // when it successfully completes. For that to be true the plan can't be
4696 // private - since private plans suppress themselves in the GetCompletedPlan
4697 // call.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004698
4699 thread_plan_sp->SetPrivate(false);
4700
4701 // The plans run with RunThreadPlan also need to be terminal master plans or
Adrian Prantl05097242018-04-30 16:49:04 +00004702 // when they are done we will end up asking the plan above us whether we
4703 // should stop, which may give the wrong answer.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004704
4705 thread_plan_sp->SetIsMasterPlan(true);
4706 thread_plan_sp->SetOkayToDiscard(false);
4707
Raphael Isemannc01783a2018-08-29 22:50:54 +00004708 // If we are running some utility expression for LLDB, we now have to mark
4709 // this in the ProcesModID of this process. This RAII takes care of marking
4710 // and reverting the mark it once we are done running the expression.
4711 UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);
4712
Kate Stoneb9c1b512016-09-06 20:57:50 +00004713 if (m_private_state.GetValue() != eStateStopped) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004714 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004715 eDiagnosticSeverityError,
4716 "RunThreadPlan called while the private state was not stopped.");
4717 return eExpressionSetupError;
4718 }
4719
4720 // Save the thread & frame from the exe_ctx for restoration after we run
4721 const uint32_t thread_idx_id = thread->GetIndexID();
4722 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4723 if (!selected_frame_sp) {
4724 thread->SetSelectedFrame(nullptr);
4725 selected_frame_sp = thread->GetSelectedFrame();
4726 if (!selected_frame_sp) {
4727 diagnostic_manager.Printf(
4728 eDiagnosticSeverityError,
4729 "RunThreadPlan called without a selected frame on thread %d",
4730 thread_idx_id);
4731 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004732 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004733 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004734
Adrian Prantl05097242018-04-30 16:49:04 +00004735 // Make sure the timeout values make sense. The one thread timeout needs to
4736 // be smaller than the overall timeout.
Pavel Labath43d35412016-12-06 11:24:51 +00004737 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4738 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
Pavel Labath2ce22162016-12-01 10:57:30 +00004739 diagnostic_manager.PutString(eDiagnosticSeverityError,
4740 "RunThreadPlan called with one thread "
4741 "timeout greater than total timeout");
4742 return eExpressionSetupError;
4743 }
4744
Kate Stoneb9c1b512016-09-06 20:57:50 +00004745 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004746
Kate Stoneb9c1b512016-09-06 20:57:50 +00004747 // N.B. Running the target may unset the currently selected thread and frame.
Adrian Prantl05097242018-04-30 16:49:04 +00004748 // We don't want to do that either, so we should arrange to reset them as
4749 // well.
Greg Claytonc14ee322011-09-22 04:58:26 +00004750
Kate Stoneb9c1b512016-09-06 20:57:50 +00004751 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004752
Kate Stoneb9c1b512016-09-06 20:57:50 +00004753 uint32_t selected_tid;
4754 StackID selected_stack_id;
4755 if (selected_thread_sp) {
4756 selected_tid = selected_thread_sp->GetIndexID();
4757 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4758 } else {
4759 selected_tid = LLDB_INVALID_THREAD_ID;
4760 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004761
Kate Stoneb9c1b512016-09-06 20:57:50 +00004762 HostThread backup_private_state_thread;
4763 lldb::StateType old_state = eStateInvalid;
4764 lldb::ThreadPlanSP stopper_base_plan_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004765
Kate Stoneb9c1b512016-09-06 20:57:50 +00004766 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4767 LIBLLDB_LOG_PROCESS));
4768 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4769 // Yikes, we are running on the private state thread! So we can't wait for
Adrian Prantl05097242018-04-30 16:49:04 +00004770 // public events on this thread, since we are the thread that is generating
4771 // public events. The simplest thing to do is to spin up a temporary thread
4772 // to handle private state thread events while we are fielding public
4773 // events here.
Todd Fiala76e0fc92014-08-27 22:58:26 +00004774 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004775 log->Printf("Running thread plan on private state thread, spinning up "
4776 "another state thread to handle the events.");
Todd Fiala76e0fc92014-08-27 22:58:26 +00004777
Kate Stoneb9c1b512016-09-06 20:57:50 +00004778 backup_private_state_thread = m_private_state_thread;
Greg Clayton095eeaa2013-11-05 23:28:00 +00004779
Kate Stoneb9c1b512016-09-06 20:57:50 +00004780 // One other bit of business: we want to run just this thread plan and
Adrian Prantl05097242018-04-30 16:49:04 +00004781 // anything it pushes, and then stop, returning control here. But in the
4782 // normal course of things, the plan above us on the stack would be given a
4783 // shot at the stop event before deciding to stop, and we don't want that.
4784 // So we insert a "stopper" base plan on the stack before the plan we want
4785 // to run. Since base plans always stop and return control to the user,
4786 // that will do just what we want.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004787 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4788 thread->QueueThreadPlan(stopper_base_plan_sp, false);
4789 // Have to make sure our public state is stopped, since otherwise the
4790 // reporting logic below doesn't work correctly.
4791 old_state = m_public_state.GetValue();
4792 m_public_state.SetValueNoLock(eStateStopped);
4793
4794 // Now spin up the private state thread:
4795 StartPrivateStateThread(true);
4796 }
4797
4798 thread->QueueThreadPlan(
4799 thread_plan_sp, false); // This used to pass "true" does that make sense?
4800
4801 if (options.GetDebug()) {
Adrian Prantl05097242018-04-30 16:49:04 +00004802 // In this case, we aren't actually going to run, we just want to stop
4803 // right away. Flush this thread so we will refetch the stacks and show the
4804 // correct backtrace.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004805 // FIXME: To make this prettier we should invent some stop reason for this,
4806 // but that
4807 // is only cosmetic, and this functionality is only of use to lldb
Adrian Prantl05097242018-04-30 16:49:04 +00004808 // developers who can live with not pretty...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004809 thread->Flush();
4810 return eExpressionStoppedForDebug;
4811 }
4812
4813 ListenerSP listener_sp(
4814 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4815
4816 lldb::EventSP event_to_broadcast_sp;
4817
4818 {
4819 // This process event hijacker Hijacks the Public events and its destructor
Adrian Prantl05097242018-04-30 16:49:04 +00004820 // makes sure that the process events get restored on exit to the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004821 //
4822 // If the event needs to propagate beyond the hijacker (e.g., the process
Adrian Prantl05097242018-04-30 16:49:04 +00004823 // exits during execution), then the event is put into
4824 // event_to_broadcast_sp for rebroadcasting.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004825
4826 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
4827
4828 if (log) {
4829 StreamString s;
4830 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4831 log->Printf("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
4832 " to run thread plan \"%s\".",
4833 thread->GetIndexID(), thread->GetID(), s.GetData());
Jim Ingham1460e4b2014-01-10 23:46:59 +00004834 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004835
4836 bool got_event;
4837 lldb::EventSP event_sp;
4838 lldb::StateType stop_state = lldb::eStateInvalid;
4839
4840 bool before_first_timeout = true; // This is set to false the first time
4841 // that we have to halt the target.
4842 bool do_resume = true;
4843 bool handle_running_event = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004844
4845 // This is just for accounting:
4846 uint32_t num_resumes = 0;
4847
Kate Stoneb9c1b512016-09-06 20:57:50 +00004848 // If we are going to run all threads the whole time, or if we are only
Pavel Labath2ce22162016-12-01 10:57:30 +00004849 // going to run one thread, then we don't need the first timeout. So we
4850 // pretend we are after the first timeout already.
4851 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Kate Stoneb9c1b512016-09-06 20:57:50 +00004852 before_first_timeout = false;
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00004853
Kate Stoneb9c1b512016-09-06 20:57:50 +00004854 if (log)
Pavel Labath2ce22162016-12-01 10:57:30 +00004855 log->Printf("Stop others: %u, try all: %u, before_first: %u.\n",
4856 options.GetStopOthers(), options.GetTryAllThreads(),
4857 before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004858
Adrian Prantl05097242018-04-30 16:49:04 +00004859 // This isn't going to work if there are unfetched events on the queue. Are
4860 // there cases where we might want to run the remaining events here, and
4861 // then try to call the function? That's probably being too tricky for our
4862 // own good.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004863
4864 Event *other_events = listener_sp->PeekAtNextEvent();
4865 if (other_events != nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004866 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004867 eDiagnosticSeverityError,
4868 "RunThreadPlan called with pending events on the queue.");
4869 return eExpressionSetupError;
Kuba Breckaafdf8422014-10-10 23:43:03 +00004870 }
4871
Kate Stoneb9c1b512016-09-06 20:57:50 +00004872 // We also need to make sure that the next event is delivered. We might be
Adrian Prantl05097242018-04-30 16:49:04 +00004873 // calling a function as part of a thread plan, in which case the last
4874 // delivered event could be the running event, and we don't want event
4875 // coalescing to cause us to lose OUR running event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004876 ForceNextEventDelivery();
Ryan Brown65d4d5c2015-09-16 21:20:44 +00004877
Kate Stoneb9c1b512016-09-06 20:57:50 +00004878// This while loop must exit out the bottom, there's cleanup that we need to do
Adrian Prantl05097242018-04-30 16:49:04 +00004879// when we are done. So don't call return anywhere within it.
Todd Fiala75930012016-08-19 04:21:48 +00004880
Kate Stoneb9c1b512016-09-06 20:57:50 +00004881#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
Adrian Prantl05097242018-04-30 16:49:04 +00004882 // It's pretty much impossible to write test cases for things like: One
4883 // thread timeout expires, I go to halt, but the process already stopped on
4884 // the function call stop breakpoint. Turning on this define will make us
4885 // not fetch the first event till after the halt. So if you run a quick
4886 // function, it will have completed, and the completion event will be
4887 // waiting, when you interrupt for halt. The expression evaluation should
4888 // still succeed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004889 bool miss_first_event = true;
4890#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00004891 while (true) {
Adrian Prantl05097242018-04-30 16:49:04 +00004892 // We usually want to resume the process if we get to the top of the
4893 // loop. The only exception is if we get two running events with no
4894 // intervening stop, which can happen, we will just wait for then next
4895 // stop event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004896 if (log)
4897 log->Printf("Top of while loop: do_resume: %i handle_running_event: %i "
4898 "before_first_timeout: %i.",
4899 do_resume, handle_running_event, before_first_timeout);
Jason Molendaef7d6412015-08-06 03:27:10 +00004900
Kate Stoneb9c1b512016-09-06 20:57:50 +00004901 if (do_resume || handle_running_event) {
4902 // Do the initial resume and wait for the running event before going
4903 // further.
Jason Molendaef7d6412015-08-06 03:27:10 +00004904
Kate Stoneb9c1b512016-09-06 20:57:50 +00004905 if (do_resume) {
4906 num_resumes++;
Zachary Turner97206d52017-05-12 04:51:55 +00004907 Status resume_error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004908 if (!resume_error.Success()) {
4909 diagnostic_manager.Printf(
4910 eDiagnosticSeverityError,
4911 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
4912 resume_error.AsCString());
4913 return_value = eExpressionSetupError;
4914 break;
4915 }
Jason Molendaef7d6412015-08-06 03:27:10 +00004916 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004917
Pavel Labathd35031e12016-11-30 10:41:42 +00004918 got_event =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00004919 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004920 if (!got_event) {
4921 if (log)
4922 log->Printf("Process::RunThreadPlan(): didn't get any event after "
4923 "resume %" PRIu32 ", exiting.",
4924 num_resumes);
4925
4926 diagnostic_manager.Printf(eDiagnosticSeverityError,
4927 "didn't get any event after resume %" PRIu32
4928 ", exiting.",
4929 num_resumes);
4930 return_value = eExpressionSetupError;
4931 break;
4932 }
4933
4934 stop_state =
4935 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4936
4937 if (stop_state != eStateRunning) {
4938 bool restarted = false;
4939
4940 if (stop_state == eStateStopped) {
4941 restarted = Process::ProcessEventData::GetRestartedFromEvent(
4942 event_sp.get());
4943 if (log)
4944 log->Printf(
4945 "Process::RunThreadPlan(): didn't get running event after "
4946 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
4947 "handle_running_event: %i).",
4948 num_resumes, StateAsCString(stop_state), restarted, do_resume,
4949 handle_running_event);
4950 }
4951
4952 if (restarted) {
4953 // This is probably an overabundance of caution, I don't think I
Adrian Prantl05097242018-04-30 16:49:04 +00004954 // should ever get a stopped & restarted event here. But if I do,
4955 // the best thing is to Halt and then get out of here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004956 const bool clear_thread_plans = false;
4957 const bool use_run_lock = false;
4958 Halt(clear_thread_plans, use_run_lock);
4959 }
4960
4961 diagnostic_manager.Printf(
4962 eDiagnosticSeverityError,
4963 "didn't get running event after initial resume, got %s instead.",
4964 StateAsCString(stop_state));
4965 return_value = eExpressionSetupError;
4966 break;
4967 }
4968
4969 if (log)
4970 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
Adrian Prantl05097242018-04-30 16:49:04 +00004971 // We need to call the function synchronously, so spin waiting for it
4972 // to return. If we get interrupted while executing, we're going to
4973 // lose our context, and won't be able to gather the result at this
4974 // point. We set the timeout AFTER the resume, since the resume takes
4975 // some time and we don't want to charge that to the timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004976 } else {
4977 if (log)
4978 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
4979 }
4980
Kate Stoneb9c1b512016-09-06 20:57:50 +00004981 do_resume = true;
4982 handle_running_event = true;
4983
4984 // Now wait for the process to stop again:
4985 event_sp.reset();
4986
Pavel Labath2ce22162016-12-01 10:57:30 +00004987 Timeout<std::micro> timeout =
4988 GetExpressionTimeout(options, before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004989 if (log) {
Pavel Labath2ce22162016-12-01 10:57:30 +00004990 if (timeout) {
4991 auto now = system_clock::now();
4992 log->Printf("Process::RunThreadPlan(): about to wait - now is %s - "
4993 "endpoint is %s",
4994 llvm::to_string(now).c_str(),
4995 llvm::to_string(now + *timeout).c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004996 } else {
4997 log->Printf("Process::RunThreadPlan(): about to wait forever.");
Jason Molendaef7d6412015-08-06 03:27:10 +00004998 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004999 }
5000
5001#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5002 // See comment above...
5003 if (miss_first_event) {
5004 usleep(1000);
5005 miss_first_event = false;
5006 got_event = false;
5007 } else
5008#endif
Pavel Labath2ce22162016-12-01 10:57:30 +00005009 got_event = listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005010
5011 if (got_event) {
5012 if (event_sp) {
5013 bool keep_going = false;
5014 if (event_sp->GetType() == eBroadcastBitInterrupt) {
5015 const bool clear_thread_plans = false;
5016 const bool use_run_lock = false;
5017 Halt(clear_thread_plans, use_run_lock);
5018 return_value = eExpressionInterrupted;
Zachary Turnere2411fa2016-11-12 19:12:56 +00005019 diagnostic_manager.PutString(eDiagnosticSeverityRemark,
5020 "execution halted by user interrupt.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005021 if (log)
5022 log->Printf("Process::RunThreadPlan(): Got interrupted by "
5023 "eBroadcastBitInterrupted, exiting.");
5024 break;
5025 } else {
5026 stop_state =
5027 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5028 if (log)
5029 log->Printf(
5030 "Process::RunThreadPlan(): in while loop, got event: %s.",
5031 StateAsCString(stop_state));
5032
5033 switch (stop_state) {
5034 case lldb::eStateStopped: {
5035 // We stopped, figure out what we are going to do now.
5036 ThreadSP thread_sp =
5037 GetThreadList().FindThreadByIndexID(thread_idx_id);
5038 if (!thread_sp) {
5039 // Ooh, our thread has vanished. Unlikely that this was
5040 // successful execution...
5041 if (log)
5042 log->Printf("Process::RunThreadPlan(): execution completed "
5043 "but our thread (index-id=%u) has vanished.",
5044 thread_idx_id);
5045 return_value = eExpressionInterrupted;
Pavel Labath45dde232017-05-25 10:50:06 +00005046 } else if (Process::ProcessEventData::GetRestartedFromEvent(
5047 event_sp.get())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005048 // If we were restarted, we just need to go back up to fetch
5049 // another event.
Pavel Labath45dde232017-05-25 10:50:06 +00005050 if (log) {
5051 log->Printf("Process::RunThreadPlan(): Got a stop and "
5052 "restart, so we'll continue waiting.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005053 }
Pavel Labath45dde232017-05-25 10:50:06 +00005054 keep_going = true;
5055 do_resume = false;
5056 handle_running_event = true;
5057 } else {
5058 const bool handle_interrupts = true;
5059 return_value = *HandleStoppedEvent(
5060 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5061 event_to_broadcast_sp, options, handle_interrupts);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005062 }
5063 } break;
5064
5065 case lldb::eStateRunning:
5066 // This shouldn't really happen, but sometimes we do get two
Adrian Prantl05097242018-04-30 16:49:04 +00005067 // running events without an intervening stop, and in that case
5068 // we should just go back to waiting for the stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005069 do_resume = false;
5070 keep_going = true;
5071 handle_running_event = false;
5072 break;
5073
5074 default:
5075 if (log)
5076 log->Printf("Process::RunThreadPlan(): execution stopped with "
5077 "unexpected state: %s.",
5078 StateAsCString(stop_state));
5079
5080 if (stop_state == eStateExited)
5081 event_to_broadcast_sp = event_sp;
5082
Zachary Turnere2411fa2016-11-12 19:12:56 +00005083 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005084 eDiagnosticSeverityError,
5085 "execution stopped with unexpected state.");
5086 return_value = eExpressionInterrupted;
5087 break;
5088 }
5089 }
5090
5091 if (keep_going)
5092 continue;
5093 else
5094 break;
5095 } else {
5096 if (log)
5097 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5098 "the event pointer was null. How odd...");
5099 return_value = eExpressionInterrupted;
5100 break;
5101 }
5102 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00005103 // If we didn't get an event that means we've timed out... We will
5104 // interrupt the process here. Depending on what we were asked to do
5105 // we will either exit, or try with all threads running for the same
5106 // timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005107
5108 if (log) {
5109 if (options.GetTryAllThreads()) {
5110 if (before_first_timeout) {
Pavel Labathd02b1c82017-02-10 11:49:33 +00005111 LLDB_LOG(log,
5112 "Running function with one thread timeout timed out.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005113 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005114 LLDB_LOG(log, "Restarting function with all threads enabled and "
5115 "timeout: {0} timed out, abandoning execution.",
5116 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005117 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005118 LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5119 "abandoning execution.",
5120 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005121 }
5122
5123 // It is possible that between the time we issued the Halt, and we get
Adrian Prantl05097242018-04-30 16:49:04 +00005124 // around to calling Halt the target could have stopped. That's fine,
5125 // Halt will figure that out and send the appropriate Stopped event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005126 // BUT it is also possible that we stopped & restarted (e.g. hit a
5127 // signal with "stop" set to false.) In
5128 // that case, we'll get the stopped & restarted event, and we should go
Adrian Prantl05097242018-04-30 16:49:04 +00005129 // back to waiting for the Halt's stopped event. That's what this
5130 // while loop does.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005131
5132 bool back_to_top = true;
5133 uint32_t try_halt_again = 0;
5134 bool do_halt = true;
5135 const uint32_t num_retries = 5;
5136 while (try_halt_again < num_retries) {
Zachary Turner97206d52017-05-12 04:51:55 +00005137 Status halt_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005138 if (do_halt) {
5139 if (log)
5140 log->Printf("Process::RunThreadPlan(): Running Halt.");
5141 const bool clear_thread_plans = false;
5142 const bool use_run_lock = false;
5143 Halt(clear_thread_plans, use_run_lock);
5144 }
5145 if (halt_error.Success()) {
5146 if (log)
5147 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5148
Pavel Labathd35031e12016-11-30 10:41:42 +00005149 got_event =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00005150 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005151
5152 if (got_event) {
5153 stop_state =
5154 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5155 if (log) {
5156 log->Printf("Process::RunThreadPlan(): Stopped with event: %s",
5157 StateAsCString(stop_state));
5158 if (stop_state == lldb::eStateStopped &&
5159 Process::ProcessEventData::GetInterruptedFromEvent(
5160 event_sp.get()))
5161 log->PutCString(" Event was the Halt interruption event.");
5162 }
5163
5164 if (stop_state == lldb::eStateStopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005165 if (Process::ProcessEventData::GetRestartedFromEvent(
5166 event_sp.get())) {
5167 if (log)
5168 log->PutCString("Process::RunThreadPlan(): Went to halt "
5169 "but got a restarted event, there must be "
5170 "an un-restarted stopped event so try "
5171 "again... "
5172 "Exiting wait loop.");
5173 try_halt_again++;
5174 do_halt = false;
5175 continue;
5176 }
5177
Pavel Labath45dde232017-05-25 10:50:06 +00005178 // Between the time we initiated the Halt and the time we
Adrian Prantl05097242018-04-30 16:49:04 +00005179 // delivered it, the process could have already finished its
5180 // job. Check that here:
Pavel Labath45dde232017-05-25 10:50:06 +00005181 const bool handle_interrupts = false;
5182 if (auto result = HandleStoppedEvent(
5183 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5184 event_to_broadcast_sp, options, handle_interrupts)) {
5185 return_value = *result;
5186 back_to_top = false;
5187 break;
5188 }
5189
Kate Stoneb9c1b512016-09-06 20:57:50 +00005190 if (!options.GetTryAllThreads()) {
5191 if (log)
5192 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5193 "was false, we stopped so now we're "
5194 "quitting.");
5195 return_value = eExpressionInterrupted;
5196 back_to_top = false;
5197 break;
5198 }
5199
5200 if (before_first_timeout) {
5201 // Set all the other threads to run, and return to the top of
5202 // the loop, which will continue;
5203 before_first_timeout = false;
5204 thread_plan_sp->SetStopOthers(false);
5205 if (log)
5206 log->PutCString(
5207 "Process::RunThreadPlan(): about to resume.");
5208
5209 back_to_top = true;
5210 break;
5211 } else {
5212 // Running all threads failed, so return Interrupted.
5213 if (log)
5214 log->PutCString("Process::RunThreadPlan(): running all "
5215 "threads timed out.");
5216 return_value = eExpressionInterrupted;
5217 back_to_top = false;
5218 break;
5219 }
5220 }
5221 } else {
5222 if (log)
5223 log->PutCString("Process::RunThreadPlan(): halt said it "
5224 "succeeded, but I got no event. "
5225 "I'm getting out of here passing Interrupted.");
5226 return_value = eExpressionInterrupted;
5227 back_to_top = false;
5228 break;
5229 }
5230 } else {
5231 try_halt_again++;
5232 continue;
5233 }
5234 }
5235
5236 if (!back_to_top || try_halt_again > num_retries)
5237 break;
5238 else
5239 continue;
5240 }
5241 } // END WAIT LOOP
5242
Adrian Prantl05097242018-04-30 16:49:04 +00005243 // If we had to start up a temporary private state thread to run this
5244 // thread plan, shut it down now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005245 if (backup_private_state_thread.IsJoinable()) {
5246 StopPrivateStateThread();
Zachary Turner97206d52017-05-12 04:51:55 +00005247 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005248 m_private_state_thread = backup_private_state_thread;
5249 if (stopper_base_plan_sp) {
5250 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5251 }
5252 if (old_state != eStateInvalid)
5253 m_public_state.SetValueNoLock(old_state);
Jason Molendaef7d6412015-08-06 03:27:10 +00005254 }
5255
Kate Stoneb9c1b512016-09-06 20:57:50 +00005256 if (return_value != eExpressionCompleted && log) {
5257 // Print a backtrace into the log so we can figure out where we are:
5258 StreamString s;
5259 s.PutCString("Thread state after unsuccessful completion: \n");
5260 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
Zachary Turnerc1564272016-11-16 21:15:24 +00005261 log->PutString(s.GetString());
Jason Molendaef7d6412015-08-06 03:27:10 +00005262 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005263 // Restore the thread state if we are going to discard the plan execution.
Adrian Prantl05097242018-04-30 16:49:04 +00005264 // There are three cases where this could happen: 1) The execution
5265 // successfully completed 2) We hit a breakpoint, and ignore_breakpoints
5266 // was true 3) We got some other error, and discard_on_error was true
Kate Stoneb9c1b512016-09-06 20:57:50 +00005267 bool should_unwind = (return_value == eExpressionInterrupted &&
5268 options.DoesUnwindOnError()) ||
5269 (return_value == eExpressionHitBreakpoint &&
5270 options.DoesIgnoreBreakpoints());
5271
5272 if (return_value == eExpressionCompleted || should_unwind) {
5273 thread_plan_sp->RestoreThreadState();
5274 }
5275
5276 // Now do some processing on the results of the run:
5277 if (return_value == eExpressionInterrupted ||
5278 return_value == eExpressionHitBreakpoint) {
5279 if (log) {
5280 StreamString s;
5281 if (event_sp)
5282 event_sp->Dump(&s);
5283 else {
5284 log->PutCString("Process::RunThreadPlan(): Stop event that "
5285 "interrupted us is NULL.");
5286 }
5287
5288 StreamString ts;
5289
5290 const char *event_explanation = nullptr;
5291
5292 do {
5293 if (!event_sp) {
5294 event_explanation = "<no event>";
5295 break;
5296 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5297 event_explanation = "<user interrupt>";
5298 break;
5299 } else {
5300 const Process::ProcessEventData *event_data =
5301 Process::ProcessEventData::GetEventDataFromEvent(
5302 event_sp.get());
5303
5304 if (!event_data) {
5305 event_explanation = "<no event data>";
5306 break;
5307 }
5308
5309 Process *process = event_data->GetProcessSP().get();
5310
5311 if (!process) {
5312 event_explanation = "<no process>";
5313 break;
5314 }
5315
5316 ThreadList &thread_list = process->GetThreadList();
5317
5318 uint32_t num_threads = thread_list.GetSize();
5319 uint32_t thread_index;
5320
5321 ts.Printf("<%u threads> ", num_threads);
5322
5323 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5324 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5325
5326 if (!thread) {
5327 ts.Printf("<?> ");
5328 continue;
5329 }
5330
5331 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5332 RegisterContext *register_context =
5333 thread->GetRegisterContext().get();
5334
5335 if (register_context)
5336 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5337 else
5338 ts.Printf("[ip unknown] ");
5339
5340 // Show the private stop info here, the public stop info will be
5341 // from the last natural stop.
5342 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5343 if (stop_info_sp) {
5344 const char *stop_desc = stop_info_sp->GetDescription();
5345 if (stop_desc)
5346 ts.PutCString(stop_desc);
5347 }
5348 ts.Printf(">");
5349 }
5350
5351 event_explanation = ts.GetData();
5352 }
5353 } while (0);
5354
5355 if (event_explanation)
5356 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s",
5357 s.GetData(), event_explanation);
5358 else
5359 log->Printf("Process::RunThreadPlan(): execution interrupted: %s",
5360 s.GetData());
5361 }
5362
5363 if (should_unwind) {
5364 if (log)
5365 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - "
5366 "discarding thread plans up to %p.",
5367 static_cast<void *>(thread_plan_sp.get()));
5368 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5369 } else {
5370 if (log)
5371 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - for "
5372 "plan: %p not discarding.",
5373 static_cast<void *>(thread_plan_sp.get()));
5374 }
5375 } else if (return_value == eExpressionSetupError) {
5376 if (log)
5377 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5378
5379 if (options.DoesUnwindOnError()) {
5380 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5381 }
5382 } else {
5383 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5384 if (log)
5385 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5386 return_value = eExpressionCompleted;
5387 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5388 if (log)
5389 log->PutCString(
5390 "Process::RunThreadPlan(): thread plan was discarded");
5391 return_value = eExpressionDiscarded;
5392 } else {
5393 if (log)
5394 log->PutCString(
5395 "Process::RunThreadPlan(): thread plan stopped in mid course");
5396 if (options.DoesUnwindOnError() && thread_plan_sp) {
5397 if (log)
5398 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5399 "'cause unwind_on_error is set.");
5400 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5401 }
5402 }
5403 }
5404
5405 // Thread we ran the function in may have gone away because we ran the
Adrian Prantl05097242018-04-30 16:49:04 +00005406 // target Check that it's still there, and if it is put it back in the
5407 // context. Also restore the frame in the context if it is still present.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005408 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5409 if (thread) {
5410 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5411 }
5412
5413 // Also restore the current process'es selected frame & thread, since this
Adrian Prantl05097242018-04-30 16:49:04 +00005414 // function calling may be done behind the user's back.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005415
5416 if (selected_tid != LLDB_INVALID_THREAD_ID) {
5417 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5418 selected_stack_id.IsValid()) {
5419 // We were able to restore the selected thread, now restore the frame:
5420 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5421 StackFrameSP old_frame_sp =
5422 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5423 selected_stack_id);
5424 if (old_frame_sp)
5425 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5426 old_frame_sp.get());
5427 }
5428 }
5429 }
5430
5431 // If the process exited during the run of the thread plan, notify everyone.
5432
5433 if (event_to_broadcast_sp) {
5434 if (log)
5435 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5436 BroadcastEvent(event_to_broadcast_sp);
5437 }
5438
5439 return return_value;
Jason Molendaef7d6412015-08-06 03:27:10 +00005440}
5441
Kate Stoneb9c1b512016-09-06 20:57:50 +00005442const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5443 const char *result_name;
5444
5445 switch (result) {
5446 case eExpressionCompleted:
5447 result_name = "eExpressionCompleted";
5448 break;
5449 case eExpressionDiscarded:
5450 result_name = "eExpressionDiscarded";
5451 break;
5452 case eExpressionInterrupted:
5453 result_name = "eExpressionInterrupted";
5454 break;
5455 case eExpressionHitBreakpoint:
5456 result_name = "eExpressionHitBreakpoint";
5457 break;
5458 case eExpressionSetupError:
5459 result_name = "eExpressionSetupError";
5460 break;
5461 case eExpressionParseError:
5462 result_name = "eExpressionParseError";
5463 break;
5464 case eExpressionResultUnavailable:
5465 result_name = "eExpressionResultUnavailable";
5466 break;
5467 case eExpressionTimedOut:
5468 result_name = "eExpressionTimedOut";
5469 break;
5470 case eExpressionStoppedForDebug:
5471 result_name = "eExpressionStoppedForDebug";
5472 break;
5473 }
5474 return result_name;
Jason Molenda484900b2015-08-10 07:55:25 +00005475}
5476
Kate Stoneb9c1b512016-09-06 20:57:50 +00005477void Process::GetStatus(Stream &strm) {
5478 const StateType state = GetState();
5479 if (StateIsStoppedState(state, false)) {
5480 if (state == eStateExited) {
5481 int exit_status = GetExitStatus();
5482 const char *exit_description = GetExitDescription();
5483 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5484 GetID(), exit_status, exit_status,
5485 exit_description ? exit_description : "");
5486 } else {
5487 if (state == eStateConnected)
5488 strm.Printf("Connected to remote target.\n");
5489 else
5490 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5491 }
5492 } else {
5493 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5494 }
Pavel Labatha933d512016-04-05 13:07:16 +00005495}
5496
Kate Stoneb9c1b512016-09-06 20:57:50 +00005497size_t Process::GetThreadStatus(Stream &strm,
5498 bool only_threads_with_stop_reason,
5499 uint32_t start_frame, uint32_t num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005500 uint32_t num_frames_with_source,
5501 bool stop_format) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005502 size_t num_thread_infos_dumped = 0;
Greg Clayton35ca64b2015-04-16 17:13:34 +00005503
Kate Stoneb9c1b512016-09-06 20:57:50 +00005504 // You can't hold the thread list lock while calling Thread::GetStatus. That
Adrian Prantl05097242018-04-30 16:49:04 +00005505 // very well might run code (e.g. if we need it to get return values or
5506 // arguments.) For that to work the process has to be able to acquire it.
5507 // So instead copy the thread ID's, and look them up one by one:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005508
5509 uint32_t num_threads;
5510 std::vector<lldb::tid_t> thread_id_array;
5511 // Scope for thread list locker;
5512 {
5513 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5514 ThreadList &curr_thread_list = GetThreadList();
5515 num_threads = curr_thread_list.GetSize();
5516 uint32_t idx;
5517 thread_id_array.resize(num_threads);
5518 for (idx = 0; idx < num_threads; ++idx)
5519 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5520 }
5521
5522 for (uint32_t i = 0; i < num_threads; i++) {
5523 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5524 if (thread_sp) {
5525 if (only_threads_with_stop_reason) {
5526 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5527 if (!stop_info_sp || !stop_info_sp->IsValid())
5528 continue;
5529 }
5530 thread_sp->GetStatus(strm, start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005531 num_frames_with_source,
5532 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005533 ++num_thread_infos_dumped;
5534 } else {
5535 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5536 if (log)
5537 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64
5538 " vanished while running Thread::GetStatus.");
Kuba Breckaa51ea382014-09-06 01:33:13 +00005539 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005540 }
5541 return num_thread_infos_dumped;
5542}
5543
5544void Process::AddInvalidMemoryRegion(const LoadRange &region) {
5545 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5546}
5547
5548bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
5549 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5550 region.GetByteSize());
5551}
5552
5553void Process::AddPreResumeAction(PreResumeActionCallback callback,
5554 void *baton) {
5555 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5556}
5557
5558bool Process::RunPreResumeActions() {
5559 bool result = true;
5560 while (!m_pre_resume_actions.empty()) {
5561 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5562 m_pre_resume_actions.pop_back();
5563 bool this_result = action.callback(action.baton);
5564 if (result)
5565 result = this_result;
5566 }
5567 return result;
5568}
5569
5570void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5571
Jim Inghamffd91752016-10-20 22:50:00 +00005572void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5573{
5574 PreResumeCallbackAndBaton element(callback, baton);
5575 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5576 if (found_iter != m_pre_resume_actions.end())
5577 {
5578 m_pre_resume_actions.erase(found_iter);
5579 }
5580}
5581
Kate Stoneb9c1b512016-09-06 20:57:50 +00005582ProcessRunLock &Process::GetRunLock() {
5583 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5584 return m_private_run_lock;
5585 else
5586 return m_public_run_lock;
5587}
5588
5589void Process::Flush() {
5590 m_thread_list.Flush();
5591 m_extended_thread_list.Flush();
5592 m_extended_thread_stop_id = 0;
5593 m_queue_list.Clear();
5594 m_queue_list_stop_id = 0;
5595}
5596
5597void Process::DidExec() {
5598 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
5599 if (log)
5600 log->Printf("Process::%s()", __FUNCTION__);
5601
5602 Target &target = GetTarget();
5603 target.CleanupProcess();
5604 target.ClearModules(false);
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005605 m_dynamic_checkers_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005606 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005607 m_system_runtime_up.reset();
5608 m_os_up.reset();
5609 m_dyld_up.reset();
5610 m_jit_loaders_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005611 m_image_tokens.clear();
5612 m_allocated_memory_cache.Clear();
Alex Langford74eb76f2019-05-22 23:01:18 +00005613 {
5614 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
5615 m_language_runtimes.clear();
5616 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005617 m_instrumentation_runtimes.clear();
5618 m_thread_list.DiscardThreadPlans();
5619 m_memory_cache.Clear(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005620 DoDidExec();
5621 CompleteAttach();
5622 // Flush the process (threads and all stack frames) after running
Adrian Prantl05097242018-04-30 16:49:04 +00005623 // CompleteAttach() in case the dynamic loader loaded things in new
5624 // locations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005625 Flush();
5626
Adrian Prantl05097242018-04-30 16:49:04 +00005627 // After we figure out what was loaded/unloaded in CompleteAttach, we need to
5628 // let the target know so it can do any cleanup it needs to.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005629 target.DidExec();
5630}
5631
Zachary Turner97206d52017-05-12 04:51:55 +00005632addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005633 if (address == nullptr) {
5634 error.SetErrorString("Invalid address argument");
5635 return LLDB_INVALID_ADDRESS;
5636 }
5637
5638 addr_t function_addr = LLDB_INVALID_ADDRESS;
5639
5640 addr_t addr = address->GetLoadAddress(&GetTarget());
5641 std::map<addr_t, addr_t>::const_iterator iter =
5642 m_resolved_indirect_addresses.find(addr);
5643 if (iter != m_resolved_indirect_addresses.end()) {
5644 function_addr = (*iter).second;
5645 } else {
5646 if (!InferiorCall(this, address, function_addr)) {
5647 Symbol *symbol = address->CalculateSymbolContextSymbol();
5648 error.SetErrorStringWithFormat(
5649 "Unable to call resolver for indirect function %s",
5650 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5651 function_addr = LLDB_INVALID_ADDRESS;
5652 } else {
5653 m_resolved_indirect_addresses.insert(
5654 std::pair<addr_t, addr_t>(addr, function_addr));
5655 }
5656 }
5657 return function_addr;
5658}
5659
5660void Process::ModulesDidLoad(ModuleList &module_list) {
5661 SystemRuntime *sys_runtime = GetSystemRuntime();
5662 if (sys_runtime) {
5663 sys_runtime->ModulesDidLoad(module_list);
5664 }
5665
5666 GetJITLoaders().ModulesDidLoad(module_list);
5667
5668 // Give runtimes a chance to be created.
5669 InstrumentationRuntime::ModulesDidLoad(module_list, this,
5670 m_instrumentation_runtimes);
5671
5672 // Tell runtimes about new modules.
5673 for (auto pos = m_instrumentation_runtimes.begin();
5674 pos != m_instrumentation_runtimes.end(); ++pos) {
5675 InstrumentationRuntimeSP runtime = pos->second;
5676 runtime->ModulesDidLoad(module_list);
5677 }
5678
Adrian Prantl05097242018-04-30 16:49:04 +00005679 // Let any language runtimes we have already created know about the modules
5680 // that loaded.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005681
Adrian Prantl05097242018-04-30 16:49:04 +00005682 // Iterate over a copy of this language runtime list in case the language
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005683 // runtime ModulesDidLoad somehow causes the language runtime to be
Adrian Prantl05097242018-04-30 16:49:04 +00005684 // unloaded.
Alex Langford74eb76f2019-05-22 23:01:18 +00005685 {
5686 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
5687 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5688 for (const auto &pair : language_runtimes) {
5689 // We must check language_runtime_sp to make sure it is not nullptr as we
5690 // might cache the fact that we didn't have a language runtime for a
5691 // language.
5692 LanguageRuntimeSP language_runtime_sp = pair.second;
5693 if (language_runtime_sp)
5694 language_runtime_sp->ModulesDidLoad(module_list);
5695 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005696 }
5697
5698 // If we don't have an operating system plug-in, try to load one since
5699 // loading shared libraries might cause a new one to try and load
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005700 if (!m_os_up)
Kate Stoneb9c1b512016-09-06 20:57:50 +00005701 LoadOperatingSystemPlugin(false);
5702
5703 // Give structured-data plugins a chance to see the modified modules.
5704 for (auto pair : m_structured_data_plugin_map) {
5705 if (pair.second)
5706 pair.second->ModulesDidLoad(*this, module_list);
5707 }
5708}
5709
5710void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
5711 const char *fmt, ...) {
5712 bool print_warning = true;
5713
5714 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
5715 if (!stream_sp)
5716 return;
5717 if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) {
5718 return;
5719 }
5720
5721 if (repeat_key != nullptr) {
5722 WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
5723 if (it == m_warnings_issued.end()) {
5724 m_warnings_issued[warning_type] = WarningsPointerSet();
5725 m_warnings_issued[warning_type].insert(repeat_key);
5726 } else {
5727 if (it->second.find(repeat_key) != it->second.end()) {
5728 print_warning = false;
5729 } else {
5730 it->second.insert(repeat_key);
5731 }
5732 }
5733 }
5734
5735 if (print_warning) {
5736 va_list args;
5737 va_start(args, fmt);
5738 stream_sp->PrintfVarArg(fmt, args);
5739 va_end(args);
5740 }
5741}
5742
5743void Process::PrintWarningOptimization(const SymbolContext &sc) {
5744 if (GetWarningsOptimization() && sc.module_sp &&
5745 !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
5746 sc.function->GetIsOptimized()) {
5747 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
5748 "%s was compiled with optimization - stepping may behave "
5749 "oddly; variables may not be available.\n",
5750 sc.module_sp->GetFileSpec().GetFilename().GetCString());
5751 }
5752}
5753
5754bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
5755 info.Clear();
5756
5757 PlatformSP platform_sp = GetTarget().GetPlatform();
5758 if (!platform_sp)
5759 return false;
5760
5761 return platform_sp->GetProcessInfo(GetID(), info);
5762}
5763
5764ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
5765 ThreadCollectionSP threads;
5766
5767 const MemoryHistorySP &memory_history =
5768 MemoryHistory::FindPlugin(shared_from_this());
5769
5770 if (!memory_history) {
Kuba Breckaa51ea382014-09-06 01:33:13 +00005771 return threads;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005772 }
5773
Jonas Devlieghere796ac802019-02-11 23:13:08 +00005774 threads = std::make_shared<ThreadCollection>(
5775 memory_history->GetHistoryThreads(addr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005776
5777 return threads;
Kuba Breckaa51ea382014-09-06 01:33:13 +00005778}
Kuba Brecka63927542014-10-11 01:59:32 +00005779
5780InstrumentationRuntimeSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00005781Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
5782 InstrumentationRuntimeCollection::iterator pos;
5783 pos = m_instrumentation_runtimes.find(type);
5784 if (pos == m_instrumentation_runtimes.end()) {
5785 return InstrumentationRuntimeSP();
5786 } else
5787 return (*pos).second;
Kuba Brecka63927542014-10-11 01:59:32 +00005788}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005789
Kate Stoneb9c1b512016-09-06 20:57:50 +00005790bool Process::GetModuleSpec(const FileSpec &module_file_spec,
5791 const ArchSpec &arch, ModuleSpec &module_spec) {
5792 module_spec.Clear();
5793 return false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005794}
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005795
Kate Stoneb9c1b512016-09-06 20:57:50 +00005796size_t Process::AddImageToken(lldb::addr_t image_ptr) {
5797 m_image_tokens.push_back(image_ptr);
5798 return m_image_tokens.size() - 1;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005799}
5800
Kate Stoneb9c1b512016-09-06 20:57:50 +00005801lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
5802 if (token < m_image_tokens.size())
5803 return m_image_tokens[token];
5804 return LLDB_INVALID_IMAGE_TOKEN;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005805}
5806
Kate Stoneb9c1b512016-09-06 20:57:50 +00005807void Process::ResetImageToken(size_t token) {
5808 if (token < m_image_tokens.size())
5809 m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
Enrico Granataf3129cb2015-12-03 23:53:45 +00005810}
Jason Molendafd4cea52016-01-08 21:40:11 +00005811
5812Address
Kate Stoneb9c1b512016-09-06 20:57:50 +00005813Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
5814 AddressRange range_bounds) {
5815 Target &target = GetTarget();
5816 DisassemblerSP disassembler_sp;
5817 InstructionList *insn_list = nullptr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005818
Kate Stoneb9c1b512016-09-06 20:57:50 +00005819 Address retval = default_stop_addr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005820
Kate Stoneb9c1b512016-09-06 20:57:50 +00005821 if (!target.GetUseFastStepping())
Jason Molendafd4cea52016-01-08 21:40:11 +00005822 return retval;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005823 if (!default_stop_addr.IsValid())
5824 return retval;
5825
5826 ExecutionContext exe_ctx(this);
5827 const char *plugin_name = nullptr;
5828 const char *flavor = nullptr;
5829 const bool prefer_file_cache = true;
5830 disassembler_sp = Disassembler::DisassembleRange(
5831 target.GetArchitecture(), plugin_name, flavor, exe_ctx, range_bounds,
5832 prefer_file_cache);
5833 if (disassembler_sp)
5834 insn_list = &disassembler_sp->GetInstructionList();
5835
5836 if (insn_list == nullptr) {
5837 return retval;
5838 }
5839
5840 size_t insn_offset =
5841 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
5842 if (insn_offset == UINT32_MAX) {
5843 return retval;
5844 }
5845
5846 uint32_t branch_index =
Greg Claytondf225762019-05-09 20:39:34 +00005847 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target,
5848 false /* ignore_calls*/);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005849 if (branch_index == UINT32_MAX) {
5850 return retval;
5851 }
5852
5853 if (branch_index > insn_offset) {
5854 Address next_branch_insn_address =
5855 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
5856 if (next_branch_insn_address.IsValid() &&
5857 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
5858 retval = next_branch_insn_address;
5859 }
5860 }
5861
5862 return retval;
Jason Molendafd4cea52016-01-08 21:40:11 +00005863}
Howard Hellyerad007562016-07-07 08:21:28 +00005864
Zachary Turner97206d52017-05-12 04:51:55 +00005865Status
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005866Process::GetMemoryRegions(lldb_private::MemoryRegionInfos &region_list) {
Howard Hellyerad007562016-07-07 08:21:28 +00005867
Zachary Turner97206d52017-05-12 04:51:55 +00005868 Status error;
Howard Hellyerad007562016-07-07 08:21:28 +00005869
Kate Stoneb9c1b512016-09-06 20:57:50 +00005870 lldb::addr_t range_end = 0;
Howard Hellyerad007562016-07-07 08:21:28 +00005871
Kate Stoneb9c1b512016-09-06 20:57:50 +00005872 region_list.clear();
5873 do {
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005874 lldb_private::MemoryRegionInfo region_info;
5875 error = GetMemoryRegionInfo(range_end, region_info);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005876 // GetMemoryRegionInfo should only return an error if it is unimplemented.
5877 if (error.Fail()) {
5878 region_list.clear();
5879 break;
Todd Fiala75930012016-08-19 04:21:48 +00005880 }
5881
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005882 range_end = region_info.GetRange().GetRangeEnd();
5883 if (region_info.GetMapped() == MemoryRegionInfo::eYes) {
5884 region_list.push_back(std::move(region_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005885 }
5886 } while (range_end != LLDB_INVALID_ADDRESS);
Todd Fiala75930012016-08-19 04:21:48 +00005887
Kate Stoneb9c1b512016-09-06 20:57:50 +00005888 return error;
5889}
5890
Zachary Turner97206d52017-05-12 04:51:55 +00005891Status
Adrian Prantl0e4c4822019-03-06 21:22:25 +00005892Process::ConfigureStructuredData(ConstString type_name,
Zachary Turner97206d52017-05-12 04:51:55 +00005893 const StructuredData::ObjectSP &config_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00005894 // If you get this, the Process-derived class needs to implement a method to
5895 // enable an already-reported asynchronous structured data feature. See
5896 // ProcessGDBRemote for an example implementation over gdb-remote.
Zachary Turner97206d52017-05-12 04:51:55 +00005897 return Status("unimplemented");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005898}
5899
5900void Process::MapSupportedStructuredDataPlugins(
5901 const StructuredData::Array &supported_type_names) {
5902 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5903
5904 // Bail out early if there are no type names to map.
5905 if (supported_type_names.GetSize() == 0) {
Todd Fiala75930012016-08-19 04:21:48 +00005906 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00005907 log->Printf("Process::%s(): no structured data types supported",
5908 __FUNCTION__);
5909 return;
5910 }
Todd Fiala75930012016-08-19 04:21:48 +00005911
Kate Stoneb9c1b512016-09-06 20:57:50 +00005912 // Convert StructuredData type names to ConstString instances.
5913 std::set<ConstString> const_type_names;
5914
5915 if (log)
5916 log->Printf("Process::%s(): the process supports the following async "
5917 "structured data types:",
5918 __FUNCTION__);
5919
5920 supported_type_names.ForEach(
5921 [&const_type_names, &log](StructuredData::Object *object) {
5922 if (!object) {
5923 // Invalid - shouldn't be null objects in the array.
5924 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005925 }
5926
5927 auto type_name = object->GetAsString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005928 if (!type_name) {
5929 // Invalid format - all type names should be strings.
5930 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005931 }
5932
5933 const_type_names.insert(ConstString(type_name->GetValue()));
Zachary Turner28333212017-05-12 05:49:54 +00005934 LLDB_LOG(log, "- {0}", type_name->GetValue());
Todd Fiala75930012016-08-19 04:21:48 +00005935 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005936 });
Todd Fiala75930012016-08-19 04:21:48 +00005937
Adrian Prantl05097242018-04-30 16:49:04 +00005938 // For each StructuredDataPlugin, if the plugin handles any of the types in
5939 // the supported_type_names, map that type name to that plugin. Stop when
5940 // we've consumed all the type names.
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005941 // FIXME: should we return an error if there are type names nobody
Jim Ingham93979f62018-04-27 01:57:40 +00005942 // supports?
5943 for (uint32_t plugin_index = 0; !const_type_names.empty(); plugin_index++) {
5944 auto create_instance =
Kate Stoneb9c1b512016-09-06 20:57:50 +00005945 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
5946 plugin_index);
Jim Ingham93979f62018-04-27 01:57:40 +00005947 if (!create_instance)
5948 break;
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005949
Kate Stoneb9c1b512016-09-06 20:57:50 +00005950 // Create the plugin.
5951 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
5952 if (!plugin_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00005953 // This plugin doesn't think it can work with the process. Move on to the
5954 // next.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005955 continue;
Todd Fiala75930012016-08-19 04:21:48 +00005956 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005957
Adrian Prantl05097242018-04-30 16:49:04 +00005958 // For any of the remaining type names, map any that this plugin supports.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005959 std::vector<ConstString> names_to_remove;
5960 for (auto &type_name : const_type_names) {
5961 if (plugin_sp->SupportsStructuredDataType(type_name)) {
5962 m_structured_data_plugin_map.insert(
5963 std::make_pair(type_name, plugin_sp));
5964 names_to_remove.push_back(type_name);
5965 if (log)
5966 log->Printf("Process::%s(): using plugin %s for type name "
5967 "%s",
5968 __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
5969 type_name.GetCString());
5970 }
5971 }
5972
5973 // Remove the type names that were consumed by this plugin.
5974 for (auto &type_name : names_to_remove)
5975 const_type_names.erase(type_name);
5976 }
Todd Fiala75930012016-08-19 04:21:48 +00005977}
5978
Kate Stoneb9c1b512016-09-06 20:57:50 +00005979bool Process::RouteAsyncStructuredData(
5980 const StructuredData::ObjectSP object_sp) {
5981 // Nothing to do if there's no data.
5982 if (!object_sp)
5983 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005984
Adrian Prantl05097242018-04-30 16:49:04 +00005985 // The contract is this must be a dictionary, so we can look up the routing
5986 // key via the top-level 'type' string value within the dictionary.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005987 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
5988 if (!dictionary)
5989 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005990
Kate Stoneb9c1b512016-09-06 20:57:50 +00005991 // Grab the async structured type name (i.e. the feature/plugin name).
5992 ConstString type_name;
5993 if (!dictionary->GetValueForKeyAsString("type", type_name))
5994 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005995
Kate Stoneb9c1b512016-09-06 20:57:50 +00005996 // Check if there's a plugin registered for this type name.
5997 auto find_it = m_structured_data_plugin_map.find(type_name);
5998 if (find_it == m_structured_data_plugin_map.end()) {
5999 // We don't have a mapping for this structured data type.
6000 return false;
6001 }
Todd Fiala75930012016-08-19 04:21:48 +00006002
Kate Stoneb9c1b512016-09-06 20:57:50 +00006003 // Route the structured data to the plugin.
6004 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
6005 return true;
Howard Hellyerad007562016-07-07 08:21:28 +00006006}
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006007
Zachary Turner97206d52017-05-12 04:51:55 +00006008Status Process::UpdateAutomaticSignalFiltering() {
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006009 // Default implementation does nothign.
6010 // No automatic signal filtering to speak of.
Zachary Turner97206d52017-05-12 04:51:55 +00006011 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006012}
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006013
Frederic Rissd10d3792018-05-11 18:21:11 +00006014UtilityFunction *Process::GetLoadImageUtilityFunction(
6015 Platform *platform,
6016 llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) {
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006017 if (platform != GetTarget().GetPlatform().get())
6018 return nullptr;
Frederic Rissd10d3792018-05-11 18:21:11 +00006019 std::call_once(m_dlopen_utility_func_flag_once,
6020 [&] { m_dlopen_utility_func_up = factory(); });
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006021 return m_dlopen_utility_func_up.get();
6022}